@assemblyvoting/js-client
    Preparing search index...

    Class AVClient

    Assembly Voting Client API

    The API is responsible for handling all the cryptographic operations and all network communication with:

    • the Digital Ballot Box
    • the Voter Authorization Coordinator service
    • the OTP provider(s)

    Two authorization modes are supported, depending on the election configuration:

    • proof-of-identity: the voter receives a one-time password by email (OTP flow).
    • proof-of-election-codes: the voter derives a cryptographic proof from printed election codes.
    Method Description
    initialize Initializes the library by fetching election configuration
    requestAccessCode Requests a one-time password sent to the voter's email
    validateAccessCode Validates the OTP code and obtains the identity token
    registerVoter Registers the voter on the bulletin board
    constructBallot Encrypts the ballot selections and submits cryptograms
    spoilBallot Optional. Initiates ballot encryption testing (challenge flow).
    castBallot Finalizes the voting process
    Method Description
    initialize Initializes the library by fetching election configuration
    generateProofOfElectionCodes Derives a cryptographic proof from the voter's election codes
    createVoterRegistration Registers the voter on the bulletin board
    constructBallot Encrypts the ballot selections and submits cryptograms
    spoilBallot Optional. Initiates ballot encryption testing (challenge flow).
    castBallot Finalizes the voting process
    [[include:readme_example.test.ts]]
    

    Implements

    Index

    Constructors

    • Creates a new AVClient instance pointed at a specific Digital Ballot Box.

      Parameters

      • bulletinBoardURL: string

        Base URL of the Digital Ballot Box for this election.

      • OptionaldbbPublicKey: string

        Optional DBB public key to pin at construction time. If omitted, the key is read from the genesis config once initialize is called.

      Returns AVClient

    Methods

    • Loads the election configuration and generates a fresh EC key pair for the voter.

      If latestConfig is provided it is validated and used directly; otherwise the config is fetched from the DBB (GET /configuration/latest_config). After loading the config, AVCrypto is initialised with the elliptic curve from genesisConfig.eaCurveName and a fresh EC key pair is generated. Must be the first method called on a new AVClient.

      Parameters

      • OptionallatestConfig: LatestConfig

        Optional election configuration to inject. If provided it is validated before use; if omitted the config is fetched from the DBB.

      • OptionalkeyPair: KeyPair

        Optional key pair to inject instead of generating a fresh one. For testing only.

      Returns Promise<void>

      Returns undefined on success or throws an error.

      InvalidConfigError if the injected latestConfig fails validation.

      An error if the DBB is unreachable and no config was injected (raw Axios error — not wrapped in NetworkError).

    • Starts the OTP (one-time password) authorization flow by requesting an access code sent to the voter's email address.

      Calls the Voter Authorizer coordinator to create a session and trigger an OTP email. Stores the returned sessionId as authorizationSessionId and the email address internally.

      Only used when authorizationMode === 'proof-of-identity'. For the election-codes flow, use generateProofOfElectionCodes instead.

      Should be followed by validateAccessCode.

      Parameters

      • opaqueVoterId: string

        Voter ID that preserves voter anonymity.

      • email: string

        The voter's email address where the OTP will be sent.

      • OptionalballotReference: string

        Optional ballot reference identifying which ballot the voter intends to vote on.

      Returns Promise<void>

      Returns undefined on success or throws an error.

      VoterRecordNotFoundError if no voter record matches the given ID.

      EmailDoesNotMatchVoterRecordError if the email address does not match the voter's record.

      BallotReferenceNotOnVoterRecord if the provided ballotReference is not on the voter's record.

      NetworkError if any request failed to get a response.

    • Should be called after requestAccessCode.

      Validates the one-time password (OTP) the voter received by email. On success, stores the identity confirmation token internally so that registerVoter can authorize the voter with the DBB.

      Should be followed by registerVoter.

      Parameters

      • code: string

        The one-time password string received by the voter via email.

      Returns Promise<void>

      Returns undefined if authorization succeeded or throws an error.

      InvalidStateError if called before requestAccessCode.

      AccessCodeExpired if the OTP code has expired.

      AccessCodeInvalid if the OTP code is invalid.

      NetworkError if any request failed to get a response.

    • Derives a cryptographic proof from the voter's printed election codes.

      Required when the election uses authorizationMode === 'proof-of-election-codes' as an alternative to the OTP email flow. The derived proof is stored internally and consumed by createVoterRegistration.

      Must be called after initialize and before createVoterRegistration.

      Parameters

      • electionCodes: string[]

        Array of election code strings provided to the voter (e.g. on a printed card).

      Returns void

    • Directly sets the identity confirmation token without going through the standard OTP flow.

      Use this when the consuming application obtains an identity token through an external authentication mechanism and needs to inject it before calling registerVoter. This is an alternative to calling requestAccessCodevalidateAccessCode.

      Parameters

      • token: string

        The identity confirmation token string obtained from the external identity provider.

      Returns void

    • Sets the registration channel before calling createVoterRegistration.

      When the election configuration includes segmentsConfig.content.channels, the consuming application should call this method with a channel private key (typically stored in localStorage by a channel-provisioning flow) before registering the voter. Internally, the key is used to sign a JWT ({ sub: "channel" }) that is sent alongside the voter registration request, allowing the DBB to associate the vote with a specific channel.

      Passing undefined clears any previously set channel, which means no channel JWT is included in the registration request.

      Must be called after initialize and before createVoterRegistration.

      Parameters

      • channelPrivateKey: string | undefined

        Hex-encoded P-256 private key for the channel, or undefined to clear.

      Returns Promise<void>

    • Retrieves voter information from the Voter Authorizer coordinator.

      Requires that the voter has already been identified — either via the OTP flow (validateAccessCode) or via election codes (generateProofOfElectionCodes).

      The returned AxiosResponse.data contains voter metadata as returned by the Voter Authorizer. Commonly accessed fields include:

      • ballotReference — identifies which ballot config applies to this voter.
      • demo — whether this voter is a demo voter (used to filter voting rounds).

      Typical usage: call this method after identification and use data.ballotReference to look up the voter's ballot config from getLatestConfig().items.ballotConfigs, then determine which voting rounds are active and applicable before calling createVoterRegistration.

      Returns Promise<AxiosResponse<any, any, {}>>

      The raw AxiosResponse from the Voter Authorizer. Relevant shape:

      { data: { ballotReference: string, demo: boolean, ...voterMetadata } }
      

      InvalidStateError if neither an identity token nor an election code proof is available.

      NetworkError if any request failed to get a response.

    • Registers the voter on the Digital Ballot Box, branching on the election's authorizationMode.

      • proof-of-identity: uses the identity confirmation token obtained via validateAccessCode (or setIdentityToken) to request a JWT from the Voter Authorizer, then posts a voter session to the DBB.
      • proof-of-election-codes: uses the proof generated by generateProofOfElectionCodes to request a JWT from the Voter Authorizer, then posts a voter session to the DBB.

      Note: if an identity confirmation token is present (set via setIdentityToken), the identity path is used regardless of authorizationMode. This allows SSO-integrated consumers to inject a token even in elections configured as proof-of-election-codes.

      The DBB response is validated against the DBB public key. On success, the voter session is stored internally and used in all subsequent calls.

      Prefer registerVoter for the standard single-round case. Use this method when you need to specify a non-default votingRoundReference.

      Parameters

      • votingRoundReference: string = "voting-round-1"

        Identifies which voting round to register for. Defaults to "voting-round-1".

      Returns Promise<void>

      Returns undefined on success or throws an error.

      InvalidStateError if the required token or proof is missing.

      InvalidTokenError if the JWT from the Voter Authorizer cannot be decoded.

      InvalidConfigError if the election has an unknown authorizationMode.

      BulletinBoardError if the DBB rejects the registration.

      NetworkError if any request failed to get a response.

    • Registers the voter on the Digital Ballot Box for voting round 1.

      Convenience wrapper around createVoterRegistration using the default votingRoundReference = "voting-round-1". This is the method defined in the IAVClient interface and is sufficient for most single-round elections.

      Must be preceded by voter identification:

      Returns Promise<void>

      Returns undefined on success or throws an error.

      InvalidStateError if the required token or proof is missing.

      InvalidTokenError if the JWT from the Voter Authorizer cannot be decoded.

      BulletinBoardError if the DBB rejects the registration.

      NetworkError if any request failed to get a response.

    • Expires all active voter sessions for the given voting round on the Digital Ballot Box.

      Only supported when authorizationMode === 'proof-of-election-codes'. Uses the stored election code proof (set by generateProofOfElectionCodes) to obtain an expiration JWT from the Voter Authorizer (action "expire"), then posts to POST /voting/expirations on the DBB.

      Primarily used by IVR telephony consumers to end a voting session programmatically.

      Parameters

      • votingRoundReference: string

        Identifies which voting round's sessions to expire.

      Returns Promise<AxiosResponse<any, any, {}>>

      The raw AxiosResponse from the DBB expiration endpoint.

      InvalidStateError if called when authorizationMode === 'proof-of-identity' (not supported).

      InvalidTokenError if the expiration JWT from the Voter Authorizer cannot be decoded.

      InvalidConfigError if the election has an unknown authorizationMode.

      NetworkError if any request failed to get a response.

    • Extends the active voter session on the Digital Ballot Box.

      Signs a SessionExtensionItem containing { extendedBy } with the voter's private key and posts it to POST /voting/extensions. Requires that voter registration has completed (so that voterSession is set). No-ops silently if the voter session has an empty address.

      Used by consuming applications to refresh the session timeout when the voter is still active (e.g. after a "Extend session" prompt in the UI, or while the voter is on the phone in an IVR flow). The number of seconds to extend by is typically read from electionStatus.sessionCountdown.extendSeconds.

      Parameters

      • extendedBy: number

        Number of seconds to extend the session by.

      Returns Promise<void>

      Returns undefined on success or throws an error.

      TypeError if called before voter registration (this.voterSession is undefined — the guard on line 628 dereferences it directly).

      NetworkError if any request failed to get a response.

    • Encrypts the voter's ballot selections and submits them to the Digital Ballot Box.

      Must be called after registerVoter (or createVoterRegistration).

      Internally performs the following steps:

      1. Validates ballotSelection against the voter's contest configs and marking rules.
      2. Encodes selections to byte arrays.
      3. Encrypts each contest pile with the threshold key and voter randomizers; generates a Pedersen commitment of the voter randomizers.
      4. POST /voting/commitments — submits the voter commitment to the DBB. Receives the board commitment (server's Pedersen commitment) and server envelopes.
      5. Finalises cryptograms by combining voter and server envelopes.
      6. POST /voting/votes — submits ballot cryptograms and ZK proofs to the DBB.
      7. Derives a 7-character Base58 tracking code from the verification start item.

      Should be followed by either spoilBallot or castBallot.

      Example:

      const client = new AVClient(url);
      const trackingCode = await client.constructBallot(ballotSelection);

      Example of handling errors:

      try {
      await client.constructBallot(ballotSelection);
      } catch(error) {
      if(error instanceof AvClientError) {
      switch(error.name) {
      case 'InvalidStateError':
      console.log("State is not valid for this call");
      break;
      case 'NetworkError':
      console.log("It's a network error");
      break;
      default:
      console.log('Something else was wrong');
      }
      }
      }

      Parameters

      • ballotSelection: BallotSelection

        BallotSelection containing the voter's selections for each contest.

      Returns Promise<string>

      The 7-character Base58 ballot tracking code (e.g. 'A3K9mNP').

      InvalidStateError if called before registerVoter.

      CorruptCvrError if the ballot selection is structurally invalid.

      NetworkError if any request failed to get a response.

    • Finalises the voting process by casting the previously constructed ballot.

      Must be called after constructBallot. Signs a CastRequestItem with the voter's private key and posts it to POST /voting/cast on the DBB. The DBB response payload and receipt are validated against the DBB public key.

      If sendTrackingCodeByEmail is enabled in the election configuration, an attempt is made to send the receipt to the voter by email via the Voter Authorizer. Email delivery failures are logged but not propagated as errors.

      Parameters

      • locale: string = "en"

        BCP 47 locale tag for the receipt email (e.g. "en", "es", "fr"). Defaults to "en".

      Returns Promise<BallotBoxReceipt>

      The BallotBoxReceipt confirming the ballot was recorded. Shape:

      {
      previousBoardHash: string,
      boardHash: string,
      registeredAt: string, // ISO 8601
      serverSignature: string, // EC signature from the DBB
      voteSubmissionId: number
      }

      InvalidStateError if called before constructBallot.

      NetworkError if any request failed to get a response.

    • Initiates the ballot challenge (spoil) flow to test the ballot encryption.

      Must be called after constructBallot, as an alternative to castBallot. Signs a SpoilRequestItem and posts it to POST /voting/spoil. Retrieves the server commitment opening and validates it against the previously stored board commitment and server envelopes.

      The returned address is passed to AVVerifier.submitVerifierKey on the second (verifier) device to link the two devices.

      Should be followed by waitForVerifierRegistration.

      Returns Promise<string>

      The spoilRequest.address string — the DBB chain address of the spoil request item.

      InvalidStateError if called before constructBallot.

      An error if the server commitment opening is invalid.

      NetworkError if any request failed to get a response.

    • Sends the voter's commitment opening (ballot randomizers) to the verifier device via the DBB.

      Must be called after constructBallot (which generates the commitment opening) and after waitForVerifierRegistration (which provides the verifier's public key). Encrypts the voter's CommitmentOpening (ballot randomizers and commitment randomness) under the verifier's public key and fires a POST /verification/commitment_openings request to the DBB.

      Note: The HTTP request is fire-and-forget — it is not awaited. The method returns immediately regardless of network success.

      Returns Promise<void>

      Returns undefined immediately (HTTP request is not awaited).

      InvalidStateError if called before voter registration (this.voterSession not set).

      TypeError if called before waitForVerifierRegistrationthis.verifierItem and this.voterCommitmentOpening are not explicitly guarded and will be undefined.

    • Returns the full election configuration loaded during initialize.

      Returns LatestConfig

      The LatestConfig object containing genesis config, election config, contest configs, ballot configs, voting round configs, and threshold key.

      InvalidStateError if called before initialize.

    • Returns the voter session item received from the DBB after registration.

      The voter session item contains the voter's identifier, public key, weight, voter group, and voting round reference as stored on the DBB chain.

      Returns VoterSessionItem

      The VoterSessionItem from the DBB.

      InvalidStateError if called before registerVoter.

    • Returns the Voter Authorizer session ID for the current authorization session.

      Set during requestAccessCode (OTP flow) or during createVoterRegistration (election codes flow).

      Common uses by consumers:

      • Signing the UUID with generateSignature to authenticate requests to external services (e.g. a conference/candidate-info API).
      • Passing to the Voter Authorizer to send the vote receipt by email.

      Returns string

      The authorization session ID string.

    • Returns the ballot configuration for the voter's voter group.

      The ballot config defines which contests appear on the voter's ballot (i.e. the set of contest references for this voter group). Use getVoterContestConfigs to get the full contest configs filtered to the active voting round.

      Returns BallotConfig

      The BallotConfig for the voter's group.

      InvalidStateError if called before registerVoter.

    • Returns the contest configurations accessible to this voter in the current voting round.

      Computes the intersection of contests on the voter's ballot (from their voter group) and contests active in the current voting round. Each ContestConfig includes the contest title, marking rules (min/max selections, weights), available options, and encoding parameters.

      Returns ContestConfig[]

      Array of ContestConfig objects for the contests this voter can vote on.

      InvalidStateError if called before registerVoter.

    • Returns the DBB public key used to verify DBB-signed payloads and receipts.

      Returns the key pinned at construction time (if provided), otherwise falls back to the key from the genesis config loaded during initialize.

      Returns string

      The hex-encoded DBB public key string.

      InvalidStateError if no DBB public key is available (neither pinned nor loaded).

    • Signs an arbitrary string payload with the voter's EC private key.

      Useful when the consuming application needs to produce a signature on behalf of the voter (e.g. for authenticating requests to external services). Requires initialize to have been called so the key pair is available.

      Parameters

      • payload: string

        The string to sign.

      Returns string

      The EC signature as a hex string.

    • Polls the Digital Ballot Box until the verifier device registers its public key.

      Must be called after spoilBallot. Queries GET /verification/verifiers/{address} every 1000ms for up to 600 attempts (10 minutes). Resolves once a VerifierItem is detected on the DBB chain for this spoil request, stores the verifier item internally (used by challengeBallot), and returns the 7-character Base58 pairing code derived from the verifier item's short address.

      Both the voter's app and the verifier device should display the pairing code so the voter can confirm they are connected to the correct second device.

      Should be followed by challengeBallot.

      Returns Promise<string>

      The 7-character Base58 pairing code derived from the verifier item's DBB address.

      InvalidStateError if called before voter registration or before spoilBallot.

      TimeoutError if the verifier does not register within 600 poll attempts.

    • Retrieves the current status and audit log for a ballot identified by its tracking code.

      Decodes the Base58 tracking code to its hex short address and queries GET /ballot_status on the DBB. This method does not require an active voter session and can be called unauthenticated — useful for voters checking their ballot after the fact or for external verification tools.

      Parameters

      • trackingCode: string

        The 7-character Base58 tracking code returned by constructBallot.

      Returns Promise<BallotStatus>

      A BallotStatus object:

      {
      status: string, // e.g. "cast", "spoiled", "pending"
      activities: Activity[] // audit log entries for this ballot
      }

      An error if the DBB request fails (raw Axios error — not wrapped in NetworkError).

    • Disables the voter in the Voter Authorizer so they can no longer sign in or vote.

      Signs the current authorizationSessionId with the voter's private key and calls the VA disable endpoint. Used in two contexts:

      • Decline to vote: when the voter explicitly chooses not to vote via a UI action.
      • IVR management: to programmatically end a voter's eligibility after a phone vote or an administrative decision.

      Requires that voter registration has been completed (registerVoter or createVoterRegistration) so that both authorizationSessionId and voterSession.content.votingRoundReference are available.

      Returns Promise<AxiosResponse<any, any, {}>>

      The raw AxiosResponse from the Voter Authorizer disable endpoint.

      NetworkError if any request failed to get a response.

    • Retrieves the voting round items for the voter's current voting round from the Voter Authorizer.

      Signs the authorizationSessionId with the voter's private key to authenticate the request. The returned AxiosResponse.data.items is an array of voting round items (e.g. information pages to display before the ballot). Consumers should handle the case where data.items is missing or not an array, as the shape depends on the Voter Authorizer configuration.

      Requires that voter registration has been completed so that authorizationSessionId and the voter session's votingRoundReference are available.

      Returns Promise<AxiosResponse<any, any, {}>>

      The raw AxiosResponse from the Voter Authorizer. Relevant shape:

      { data: { items: RawVotingRoundItem[] } }
      

      InvalidStateError if called before registerVoter.

      NetworkError if any request failed to get a response.