# Wallet Sign-in (https://dev.cosmospay.lat/docs/api/wallet-auth/)

> The Cosmos Pay Wallet’s own sign-in: Authentik (OpenID Connect), Google, GitHub or an emailed code. It proves who a person is and never touches a key; the seed backup it stores is sealed on the device under a password this service never sees.

Base URL: `https://api.cosmospay.lat/cosmos-api`

## Which sign-in doors this deployment has

`GET /v1/wallet/auth/providers`

Render buttons from this rather than from a compiled-in list. A deployment with no Google credentials should not show a Google button that dies at the consent screen.

Requires the `payments:read` scope. The shared public key may call it.

**Responses**

- `200` (`WalletAuthProvidersEntity`): OK
  - `providers` (string[], required): Which providers this deployment has credentials for. Render buttons from this rather than from a compiled-in list, so a deployment that configured neither does not show two buttons that die at the consent screen.
  - `sources` (WalletAuthSourceEntity[], required): Authentik’s own sources (Google, GitHub…), each to show as a button of its own that starts the Authentik sign-in at that source. With these, a wallet need not show a generic Authentik button. Empty without Authentik, or when the operator listed none (WALLET_AUTH_OIDC_SOURCES).
  - `email` (boolean, required): Whether the email-code door works here. False when no console is configured to deliver the mail.
  - `mfaSettingsUrl` (string, required): The page of the person’s Cosmos Pay (Authentik) account where they add or remove a second factor (a security key or passkey, an authenticator app, recovery codes), to open in a browser. It goes through the Authentik login first when there is no session. A second factor is optional (the sign-in only offers one), so offer this as a setting. Null when this deployment has no Authentik.
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `500`: InternalError (see Shared responses)

## Open a provider sign-in

`POST /v1/wallet/auth/oauth/authorize`

Returns the URL to open in a browser. Keep the PKCE verifier on the device: the `state` travels through the browser and buys only polling, while the verifier is what redeems the handshake.

Requires the `payments:write` scope. The shared public key may call it.

**Request body** (`application/json`, required): `StartWalletOauthDto`

- `provider` (string, required): The identity provider to sign in with. One of: `authentik`, `google`, `github`.
- `codeChallenge` (string, required): base64url(SHA-256(verifier)), RFC 7636 S256. Keep the verifier on the device: it is what makes a `state` seen in a browser worthless to anyone else, and it is the only thing that can redeem this handshake.
- `codeChallengeMethod` (string, required): RFC 7636 S256, the only method accepted. Declared rather than ignored: the wallet sends it, and an undeclared field is a 400 under `forbidNonWhitelisted`. Pinned rather than defaulted, because `plain` is the one value that would make the verifier no secret at all. One of: `S256`.
- `returnTo` (string, optional): A native wallet’s own URL: a custom scheme, a universal/app link, or `http://127.0.0.1:<port>/…` from a desktop app. When set, the callback answers `302` to it with `?state=…` (plus `&error=<reason>` on failure) instead of rendering a page, which is what closes the platform’s auth session. Must be listed in the deployment’s `WALLET_AUTH_RETURN_URLS` (a loopback entry matches any port). Only the `state` travels: the handshake is still redeemed with the verifier.
- `source` (string, optional): Start at one of Authentik’s sources (Google, GitHub…) instead of its login page: an `id` from `sources` on GET /v1/wallet/auth/providers, with `provider: authentik`. The browser goes straight to that provider and comes back through Authentik, so the handshake and its ID token are the same as any Authentik sign-in. Send it only to a deployment that listed it: an older one refuses the unknown field.

**Responses**

- `200` (`WalletOauthStartedEntity`): OK
  - `state` (string, required): The handshake handle. Public by construction: it travels in a URL bar. Knowing it buys polling, never redemption.
  - `authorizationUrl` (string, required): Open this in a browser.
  - `expiresAt` (string (date-time), required): When the handshake expires (ISO 8601).
- `400` (`ApiErrorBodyEntity`): `wallet_provider_unavailable`: That provider is unknown, or not configured on this deployment `wallet_return_url_not_allowed`: The return URL is not one this deployment redirects to
  - `statusCode` (number, required): Always the HTTP status of the response itself.
  - `code` (string, required): Stable machine-readable code. Branch on this, never on the message: messages are human-facing and may be reworded; codes are never renamed once published. Each response documents the subset it can return. One of: `insufficient_scope`, `no_authenticated_consumer`, `gateway_required`, `admin_console_only`, `not_found`, `validation_failed`, `payload_too_large`, `idempotency_conflict`, `operation_in_flight`, `invalid_state_transition`, `slippage_exceeded`, `insufficient_balance`, `no_path_found`, `trustline_missing`, `invalid_amount`, `invalid_memo`, `transaction_rejected`, `transaction_already_settled`, `recipient_not_registered`, `payment_transfer_mismatch`, `fee_transfer_mismatch`, `merchant_fee_transfer_mismatch`, `payer_mismatch`, `transaction_not_found`, `expired`, `network_unsupported`, `asset_unsupported`, `merchant_fee_unsupported`, `provider_error`, `provider_unavailable`, `quote_not_found`, `quote_expired`, `kyc_state_invalid`, `kyc_review_required`, `account_disabled`, `payload_expired`, `rate_limited`, `customer_wallet_taken`, `alias_taken`, `alias_name_invalid`, `alias_challenge_invalid`, `alias_signature_invalid`, `alias_recovery_invalid`, `alias_address_conflict`, `wallet_handshake_invalid`, `wallet_verifier_invalid`, `wallet_login_code_invalid`, `wallet_login_code_cooldown`, `wallet_session_invalid`, `wallet_signature_invalid`, `wallet_backup_invalid`, `wallet_backup_limit`, `wallet_account_mismatch`, `wallet_provider_unavailable`, `wallet_return_url_not_allowed`, `wallet_recovery_setup_refused`, `easy_recovery_not_found`, `easy_recovery_already_offered`, `easy_recovery_not_offered`, `easy_recovery_code_invalid`, `easy_recovery_burned`, `plugin_not_installed`, `plugin_consent_mismatch`, `plugin_rejected`, `plugin_quota_exceeded`, `plugin_failed`, `protected_payment_buyer_mismatch`, `protected_payment_signature_invalid`, `misconfigured`, `internal_error`.
  - `error` (string, required): The HTTP reason phrase for `statusCode`.
  - `message` (string | string[], required): Human-readable detail. An array when class-validator rejected the body.
  - `details` (object, optional): Machine-readable facts about this failure, present only on the codes whose example shows it: `easy_recovery_code_invalid` carries `{ "attemptsLeft": 4 }`. Absent everywhere else.
  - `path` (string, required): The path of the request that failed.
  - `timestamp` (string, required): When the envelope was produced, ISO 8601.
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503` (`ApiErrorBodyEntity`): `wallet_provider_unavailable`: That provider is unknown, or not configured on this deployment

## Where the provider returns the browser after consent

`GET /v1/wallet/auth/oauth/callback/{provider}`

Not called by your code: the person’s browser lands here. Public by necessity: a navigation carries no API key and no gateway consumer. It renders a page (or, when the handshake was opened with a `returnTo`, redirects to it with the `state`) and nothing else; the identity is collected by the device that holds the PKCE verifier. Register `{WALLET_AUTH_PUBLIC_BASE_URL}/v1/wallet/auth/oauth/callback/{provider}` with each provider.

No authentication.

**Path parameters**

- `provider` (string, required):  One of: `authentik`, `google`, `github`.

**Query parameters**

- `error` (object, optional): Sent by the provider when the person declined or the authorization failed. Any value ends a pending handshake `denied`, and no code is exchanged.
- `state` (object, optional): The handshake's `state`, as `POST /v1/wallet/auth/oauth/authorize` answered it. Missing, unknown, for another provider, no longer pending or past its expiry: the callback reports `expired` and changes nothing.
- `code` (object, optional): The authorization code the provider issued, which this service exchanges with the provider for the person's identity. Missing, a pending handshake ends `denied`.

**Responses**

- `200`: A "you can go back to your wallet" page. It never contains the identity or a token.
- `302`: The handshake was opened with a `returnTo`: the browser is sent there with `?state=…`, plus `&error=<reason>` when the sign-in did not succeed. The same reason tokens the poll reports; never the identity.
- `400`: ValidationFailed (see Shared responses)
- `404`: NotFound (see Shared responses)
- `500`: InternalError (see Shared responses)

## Poll a sign-in

`GET /v1/wallet/auth/oauth/session/{state}`

Answers on the `state` alone, and never returns the identity at any status. Poll until it leaves `pending`, then redeem with the verifier.

Requires the `payments:read` scope. The shared public key may call it.

**Path parameters**

- `state` (string, required)

**Responses**

- `200` (`WalletAuthStatusEntity`): OK
  - `status` (string, required): Poll until this leaves `pending`. `authorized` means the person came back and the identity is waiting for the PKCE verifier. The identity itself is never in this response, at any status. One of: `pending`, `authorized`, `redeemed`, `failed`, `expired`.
  - `error` (string, optional): Present only on `failed`. A token to map to a sentence, never prose, which cannot be translated on the device. One of: `denied`, `email_unverified`, `profile_invalid`, `failed`.
  - `bound` (boolean, optional): Present (true) only on `authorized`, after an Authentik emailed sign-in whose callback sent the wallet’s return URL a device binding: claim with it (`binding`), or the claim sends the inbox a code. The value itself is never in this response.
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `404`: NotFound (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)

## Redeem a handshake with the PKCE verifier

`POST /v1/wallet/auth/oauth/claim`

A NEW email ends here, with a session token. An email that ALREADY has an account gets `verify_email` instead and a code in its inbox: a provider proves who consented, not who opened the sign-in, and an existing account is where the backup worth stealing is. An Authentik email the provider has not confirmed also gets `verify_email`, account or not, under the same per-address cooldown as `email/start`. The exception is a sign-in through Authentik’s emailed link (the `email` source), whose ID token carries `cosmos_inbox_proven: true`: that login already proved the inbox, so an existing account ends here too, with its backups and the `idToken`.

Requires the `payments:write` scope. The shared public key may call it.

**Request body** (`application/json`, required): `ClaimWalletOauthDto`

- `state` (string, required): The handshake handle, from /oauth/authorize.
- `codeVerifier` (string, required): The PKCE verifier this device kept. Never sent anywhere else, and never stored by this service.
- `purpose` (string, optional): `recovery` when the proven identity is going to be presented to the SEP-30 recovery servers. It always routes through an emailed code, even for an email with no account, and only then does the answer carry the provider's `idToken`: a provider proves who consented, not who opened the sign-in, and a recovery identity is worth a wallet. The one exception is an existing account signed in through Authentik’s emailed link (`cosmos_inbox_proven: true` in its ID token), which already proved the inbox. One of: `sign-in`, `recovery`.
- `binding` (string, optional): The device binding: the one-time value the callback put in the fragment of its redirect to the wallet’s return URL, after an Authentik emailed sign-in (the poll says `bound`). Only with it does that sign-in skip the code for an existing account. Send it only when the poll said `bound`: an older server refuses the unknown field.

**Responses**

- `200` (`WalletAuthReadyEntity | WalletAuthVerifyEmailEntity`): OK
- `400` (`ApiErrorBodyEntity`): `wallet_verifier_invalid`: The PKCE verifier does not match the handshake `wallet_login_code_cooldown`: Another code was sent to this mailbox moments ago
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)

## Send a sign-in code to a mailbox

`POST /v1/wallet/auth/email/start`

Emails a six-digit code to `email`, valid 15 minutes (`expiresInSeconds`), and answers a `claimToken` naming that code; send both to `POST /v1/wallet/auth/email/verify`. One mailbox gets at most one code a minute and 10 in 24 hours, whoever asks: more is `400 wallet_login_code_cooldown`. Only SHA-256 hashes of the code and the claim token are stored.

Requires the `payments:write` scope. The shared public key may call it.

**Request body** (`application/json`, required): `StartWalletEmailDto`

- `email` (string, required): The email address to send the six-digit code to.

**Responses**

- `200` (`WalletEmailStartedEntity`): OK
  - `claimToken` (string, required): Identifies WHICH code is being answered, so a second request for the same mailbox cannot be answered with the first code. Only its SHA-256 is stored here.
  - `expiresInSeconds` (number, required): Lifetime of the emailed code, in seconds.
- `400` (`ApiErrorBodyEntity`): `wallet_login_code_cooldown`: Another code was sent to this mailbox moments ago
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)

## Answer a sign-in code

`POST /v1/wallet/auth/email/verify`

Wrong codes are counted on the row, not by the client. Five burns it, and a burned code is replaced by asking for another.

Requires the `payments:write` scope. The shared public key may call it.

**Request body** (`application/json`, required): `VerifyWalletEmailDto`

- `claimToken` (string, required): The claim token returned by /auth/email/start.
- `code` (string, required): The six digits emailed.

**Responses**

- `200` (`WalletAuthReadyEntity | WalletCodeInvalidEntity`): OK
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)

## Attach the proven identity to the account this device signs for

`POST /v1/wallet/auth/finish`

Send the session token as `X-Wallet-Session: {sessionToken}`. The gateway strips `Authorization`. The signature covers exactly:

```
Cosmos Pay Wallet sign-in
email: {lowercased email}
account: {address}
at: {signedAt}
```

signed over those raw UTF-8 bytes with the account key, base64. The first line is one no Stellar transaction envelope can begin with, which is what makes signing it safe.

On Solana and Monad (`chain`), a `chain: {chain}` line follows the first one. Solana signs the bytes with ed25519 (`signMessage`; base64 or base58); Monad with EIP-191 `personal_sign` (0x-hex).

Requires the `payments:write` scope. The shared public key may call it.

**Headers**

- `X-Wallet-Session` (string, required): {sessionToken}, from the sign-in that just finished. `Authorization: Bearer {sessionToken}` is read too, but only on a direct call: APISIX strips it.

**Request body** (`application/json`, required): `FinishWalletSignInDto`

- `chain` (string, optional): Chain the account is on. Omit for Stellar. Solana signs the challenge with ed25519 over its UTF-8 bytes; Monad with EIP-191 `personal_sign`. One of: `stellar`, `solana`, `monad`.
- `address` (string, optional): The account on `chain`: Stellar G…, Solana base58, Monad 0x…. Send this or `stellarAddress`, not both.
- `stellarAddress` (string, optional): The Stellar account (the field’s original name, still accepted for Stellar). New clients send `address`.
- `signedAt` (string, required): When the challenge was signed: an ISO 8601 instant in UTC (`Z`), at most millisecond precision; it must be close to the server's clock.
- `signature` (string, required): Signature over the sign-in challenge: base64 ed25519 on Stellar, base64 or base58 ed25519 on Solana, 0x-hex EIP-191 on Monad. The exact bytes are documented on the operation; a client that rebuilds them from prose is one field-order change away from producing signatures nothing accepts.
- `backup` (string, optional): The device's sealed seed box, to keep for the next device: one per (chain, address), up to 20 per account. Opaque here: it is sealed under a key derived from a password this service never sees.
- `replaceBackup` (boolean, optional): Accepted for older wallets and ignored. Backups are kept per wallet: a box for another address is added beside the ones the account keeps, and a box for the same wallet replaces its own. Nothing is ever discarded to make room.
- `network` (string, optional): The ledger the account's signers are read from (a recovered account's key signs for it on the ledger it was re-keyed on). Omit for the default. One of: `public`, `testnet`.

**Responses**

- `200` (`WalletSignInFinishedEntity`): OK
  - `status` (string, required): Always `ready`. One of: `ready`.
  - `account` (string, required): Whether this call created the account or attached the identity to one that already existed. A different vocabulary from `ready.account`, deliberately: they answer two different questions. One of: `created`, `linked`.
  - `organizationId` (string, required): Id of the account's organization, carried by its API keys.
  - `keys` (WalletProvisionedKeysEntity, required): The account's gateway API keys.
- `400` (`ApiErrorBodyEntity`): `wallet_signature_invalid`: The signature does not verify, or its timestamp is out of window `wallet_backup_invalid`: Not a backup box this service will keep `wallet_backup_limit`: The account already keeps as many wallet backups as it may
- `401` (`ApiErrorBodyEntity`): `wallet_session_invalid`: The sign-in token is missing, expired, or was not minted here
- `403`: Forbidden (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## Replace the sealed box stored for an account

`PUT /v1/wallet/backup`

What `changePassword` on the device sends. No session: the signature is the credential, and it covers the SHA-256 of the box, so one signature stores exactly one box and cannot be replayed to store another. The bytes are:

```
Cosmos Pay Wallet backup
account: {address}
box: {sha256 hex of box}
at: {signedAt}
```

On Solana and Monad a `chain: {chain}` line follows the first one, and the bytes are signed as for sign-in.

Requires the `payments:write` scope. The shared public key may call it.

**Request body** (`application/json`, required): `ReplaceWalletBackupDto`

- `chain` (string, optional): Chain the account is on. Omit for Stellar. Solana signs the challenge with ed25519 over its UTF-8 bytes; Monad with EIP-191 `personal_sign`. One of: `stellar`, `solana`, `monad`.
- `address` (string, optional): The account on `chain`: Stellar G…, Solana base58, Monad 0x…. Send this or `stellarAddress`, not both.
- `stellarAddress` (string, optional): The Stellar account (the field’s original name, still accepted for Stellar). New clients send `address`.
- `box` (string, required): The re-sealed box. Opaque to this service.
- `signedAt` (string, required): When the challenge was signed: an ISO 8601 instant in UTC (`Z`), at most millisecond precision; it must be close to the server's clock.
- `signature` (string, required): Signature over the backup challenge (encoded as for sign-in), which covers the box's SHA-256, so one signature stores exactly one box.
- `network` (string, optional): The ledger the account's signers are read from (a recovered account's key signs for it on the ledger it was re-keyed on). Omit for the default. One of: `public`, `testnet`.

**Responses**

- `200` (`WalletBackupUpdatedEntity`): OK
  - `status` (string, required): Always `ok`. One of: `ok`.
  - `chain` (string, required): The chain of the account whose box was replaced. One of: `stellar`, `solana`, `monad`.
  - `address` (string, required): The account whose box was replaced, on `chain` (Stellar G…, Solana base58, Monad 0x…).
  - `stellarAddress` (string, required): Same as `address` (the field’s original name, kept for older wallets).
  - `updatedAt` (string (date-time), required): When the box was replaced (ISO 8601).
- `400` (`ApiErrorBodyEntity`): `wallet_signature_invalid`: The signature does not verify, or its timestamp is out of window `wallet_backup_invalid`: Not a backup box this service will keep
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `404` (`ApiErrorBodyEntity`): `wallet_account_mismatch`: No backup is stored for the account that signed
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## Sponsor the reserve of an account's two recovery signers

`POST /v1/wallet/recovery/setup`

Send the session token as `X-Wallet-Session: {sessionToken}`. The gateway strips `Authorization`. The signature covers exactly:

```
Cosmos Pay Wallet recovery setup
account: {stellarAddress}
signers: {signerA},{signerB}
at: {signedAt}
```

The envelope comes back signed by the sponsor only. Once per account: refused when the account already has a signer besides its master key.

Requires the `payments:write` scope. The shared public key may call it.

**Headers**

- `X-Wallet-Session` (string, required): {sessionToken}. `Authorization: Bearer {sessionToken}` is read too, but only on a direct call: APISIX strips it.

**Request body** (`application/json`, required): `SponsorRecoverySetupDto`

- `stellarAddress` (string, required): The Stellar account (G...) to set the recovery signers on.
- `signers` (string[], required): The two recovery servers' signers for this account, in role order.
- `signedAt` (string, required): When the challenge was signed: an ISO 8601 instant in UTC (`Z`), at most millisecond precision; it must be close to the server's clock.
- `signature` (string, required): base64 ed25519 signature over the recovery-setup challenge.
- `network` (string, optional): The ledger the account's signers are read from (a recovered account's key signs for it on the ledger it was re-keyed on). Omit for the default. One of: `public`, `testnet`.

**Responses**

- `200` (`WalletRecoverySetupEntity`): OK
  - `transaction` (string, required): base64 XDR, signed by the sponsor and NOT by the account: the wallet adds its signature only after its own guard has decoded every operation.
  - `sponsor` (string, required): The account paying the two signer reserves.
  - `network_passphrase` (string, required): Passphrase of the Stellar network the transaction is for.
- `400` (`ApiErrorBodyEntity`): `wallet_signature_invalid`: The signature does not verify, or its timestamp is out of window
- `401` (`ApiErrorBodyEntity`): `wallet_session_invalid`: The sign-in token is missing, expired, or was not minted here
- `403`: Forbidden (see Shared responses)
- `409` (`ApiErrorBodyEntity`): `wallet_recovery_setup_refused`: The account cannot be sponsored: missing, or already has signers
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## Shared responses

- **Unauthorized** (`ApiErrorBodyEntity`): `no_authenticated_consumer`: The gateway forwarded no API key identity
- **Forbidden** (`ApiErrorBodyEntity`): `insufficient_scope`: the API key does not hold the scope this route requires. The shared public API key also gets this on every route that is not marked `x-cosmos-public-key`, with a message saying so; more scopes will not help, the key is the wrong one. `gateway_required`: the request did not arrive through APISIX.
- **InternalError** (`ApiErrorBodyEntity`): Unexpected server error. The detail is logged server-side and never returned: there is nothing in the body to branch on beyond the code.
- **RateLimited** (`ApiErrorBodyEntity`): The budget in `x-cosmos-rate-limit` is spent for this caller. Honour `Retry-After`. The `ratelimit-*` triple rides along on successful responses too, so a client can pace itself instead of being refused. If the counter store itself is unreachable the guard fails closed and answers `503 provider_unavailable`.
- **ValidationFailed** (`ApiErrorBodyEntity`): The body, query or path failed validation. `message` is an array of the individual failures. Routes that reject a *valid* request for a reason of their own (an amount, a memo, a state) document the code for it on their own 400.
- **NotFound** (`ApiErrorBodyEntity`): No such resource, or it exists and belongs to another consumer. The two are deliberately the same answer: "exists but not yours" is an ownership oracle.
- **UpstreamUnavailable** (`ApiErrorBodyEntity`): `provider_unavailable`: the provider in `x-cosmos-upstream` is down or unreachable; the message names it. Retry. `misconfigured`: this deployment is missing configuration the route needs (a provider instance, a fee wallet, the plan header the gateway must forward). Retrying will not help; it is an operator problem.
