From 8b7afb0f347e90f45f7f1d4f940d0f6801591806 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 24 Oct 2026 21:31:47 -0500 Subject: [PATCH 1/8] chore(auth): vendor platform-auth app-connect module Copy platform-auth's App Connect v2 module (src/app-connect at a627708, feat/app-connect-module) into forge-web/lib/vendor/platform-auth with platform-auth's tools/vendor.mjs; VENDORED.json records the commit and a hash per file. The module's only externals are @noble/hashes and @noble/secp256k1, which Forge already depends on, and it is clean under Forge's noUncheckedIndexedAccess. Its tests run in pnpm test. - copy-lint skips lib/vendor: those strings are upstream developer errors, and editing them would only add drift. - eslint limits imports of the vendored test-helpers (fixed-seed vector requests) to tests and lib/auth/wallet-sim.ts. - pnpm vendor:status reports drift against a platform-auth checkout (PLATFORM_AUTH_DIR, default ../../platform-auth). Co-Authored-By: Claude Opus 5.5 --- forge-web/.eslintrc.json | 14 + .../lib/vendor/platform-auth/VENDORED.json | 41 ++ .../platform-auth/app-connect/crypto.test.ts | 95 ++++ .../platform-auth/app-connect/crypto.ts | 164 ++++++ .../platform-auth/app-connect/errors.test.ts | 75 +++ .../platform-auth/app-connect/errors.ts | 57 ++ .../vendor/platform-auth/app-connect/group.ts | 55 ++ .../vendor/platform-auth/app-connect/index.ts | 11 + .../platform-auth/app-connect/poller.test.ts | 88 ++++ .../platform-auth/app-connect/poller.ts | 110 ++++ .../app-connect/primitives.test.ts | 58 ++ .../platform-auth/app-connect/primitives.ts | 118 +++++ .../platform-auth/app-connect/request.test.ts | 197 +++++++ .../platform-auth/app-connect/request.ts | 495 ++++++++++++++++++ .../platform-auth/app-connect/session.test.ts | 257 +++++++++ .../platform-auth/app-connect/session.ts | 320 +++++++++++ .../platform-auth/app-connect/test-helpers.ts | 125 +++++ .../vendor/platform-auth/app-connect/types.ts | 90 ++++ .../platform-auth/app-connect/vectors.json | 46 ++ .../platform-auth/app-connect/vectors.test.ts | 56 ++ .../platform-auth/app-connect/verify.test.ts | 267 ++++++++++ .../platform-auth/app-connect/verify.ts | 329 ++++++++++++ forge-web/package.json | 3 +- forge-web/scripts/copy-lint.mjs | 16 +- forge-web/scripts/copy-lint.test.ts | 10 + 25 files changed, 3092 insertions(+), 5 deletions(-) create mode 100644 forge-web/lib/vendor/platform-auth/VENDORED.json create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/crypto.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/crypto.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/errors.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/errors.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/group.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/index.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/poller.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/poller.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/primitives.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/primitives.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/request.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/request.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/session.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/session.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/test-helpers.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/types.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/vectors.json create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/vectors.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/verify.test.ts create mode 100644 forge-web/lib/vendor/platform-auth/app-connect/verify.ts diff --git a/forge-web/.eslintrc.json b/forge-web/.eslintrc.json index 1aae13a48..77f04664b 100644 --- a/forge-web/.eslintrc.json +++ b/forge-web/.eslintrc.json @@ -63,6 +63,20 @@ ] }] } + }, + { + "files": ["**/*.ts", "**/*.tsx"], + "excludedFiles": ["**/*.test.ts", "**/*.test.tsx", "lib/auth/wallet-sim.ts"], + "rules": { + "@typescript-eslint/no-restricted-imports": ["error", { + "patterns": [ + { + "group": ["**/vendor/platform-auth/app-connect/test-helpers", "**/vendor/platform-auth/app-connect/test-helpers.*", "./test-helpers", "./test-helpers.*"], + "message": "The vendored App Connect test-helpers build vector requests from fixed seeds: tests and lib/auth/wallet-sim.ts only." + } + ] + }] + } } ], "ignorePatterns": [ diff --git a/forge-web/lib/vendor/platform-auth/VENDORED.json b/forge-web/lib/vendor/platform-auth/VENDORED.json new file mode 100644 index 000000000..5d1f79989 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/VENDORED.json @@ -0,0 +1,41 @@ +{ + "modules": { + "app-connect": { + "commit": "a627708db82112d20f76d81a99c8b94559933686", + "dirty": false, + "externals": [ + "@noble/hashes", + "@noble/secp256k1" + ], + "files": { + "crypto.test.ts": "sha256-d1db62d5588808fbe3d95479ee94a542383430f5896bb8db849d977fe3cea84a", + "crypto.ts": "sha256-784e0783422169408509127259fab81d05998ace48794dcc5f96febe69df17a3", + "errors.test.ts": "sha256-6c276d5d02f8a2e0c83c818591bf92c3f90aa144f8f38f0c9dcb459678440a92", + "errors.ts": "sha256-eac0717f11776499f2587ccd7fa18caf32815bf2adb70509dddfa95c9cf2a892", + "group.ts": "sha256-5e81144f70e143d295cba89fe5858cf0e9c8f7093fda4f6996a8942feab37fd9", + "index.ts": "sha256-d828cc4a68526d7ac82a39c9263fa7ae10ab6c237fe74621bdd31b12d4c7b611", + "poller.test.ts": "sha256-c930fe802ba78b6e118a470fadc3c7c5b7889889c30eb250fc7a8a078fc1ca25", + "poller.ts": "sha256-8e2f989e309ab4dbd75a5932a1bc0c7b5589fbeee8085a96c2734059a77b93d3", + "primitives.test.ts": "sha256-4df9f7c1fa30a175754b4cda1dcfbd6e2cc24b943c3fb9efdbbb84a01b2383d8", + "primitives.ts": "sha256-0ee5552233134bd198ee0c7f4333ec642ede80815b28f2e9031601399e19161d", + "request.test.ts": "sha256-26d581128c7c8812d97b7a8f83dbd7c6f3fcaa165cf5fd327d4691771792ef1c", + "request.ts": "sha256-4d2be8fc81782d8eb76a998e2c53a81c5b375f3cac178f3da2679bc13481e56e", + "session.test.ts": "sha256-9820c0fdcbc808fbfb51c3a95d19589ea79a2c0d1cfcffcae46e01618125f728", + "session.ts": "sha256-7c7437fbbbc121ddad3ba8a5291c303b784abc2df14bbc32ee0806cfd2952418", + "test-helpers.ts": "sha256-b6386cbd941dbcd235e225e2f9285f3af67bd784ffb9e56b95385b392ff087e2", + "types.ts": "sha256-f15dd07645db675d2a00c253c5b85e2f367c75f6a35e3486817918315f10084a", + "vectors.json": "sha256-014ba6465a8fb27d65c04c05b8131fad3c9902a008510696a85759b0eaa87515", + "vectors.test.ts": "sha256-bc543817d848c7090ec68ed0eca513bc42b4d4f0c178153658ada6cbc86c1ca4", + "verify.test.ts": "sha256-d36c16fcb15a40384327799e39974bd2a9b92f10e4b39eef6dd19428784cd203", + "verify.ts": "sha256-5272d8263e7efe719fab01e114785a867580e0d6785e66fdd92baa0bc10e5f72" + }, + "ref": "feat/app-connect-module" + } + }, + "note": "Owned by this repo, free to diverge. Run platform-auth tools/vendor.mjs status .", + "schema": 1, + "upstream": { + "package": "@pastapastapasta/platform-auth", + "repo": "https://github.com/PastaPastaPasta/platform-auth" + } +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/crypto.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/crypto.test.ts new file mode 100644 index 000000000..718694d47 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/crypto.test.ts @@ -0,0 +1,95 @@ +import * as secp256k1 from '@noble/secp256k1' +import { describe, expect, it } from 'vitest' +import { AppConnectPayloadError, appConnectSlotCount, openAppConnectPayload, sealAppConnectPayload } from './crypto' +import { seed, vectorKeys, yapprVectorRequest } from './test-helpers' + +const appEphemeralPubKey = yapprVectorRequest().appEphemeralPubKey +const slots = [vectorKeys.groupKey, vectorKeys.profileKey] + +async function sealed(ownerId = vectorKeys.ownerId) { + return sealAppConnectPayload({ appEphemeralPubKey, ownerId, slots }) +} + +async function openError(input: Parameters[0]): Promise { + try { + await openAppConnectPayload(input) + } catch (error) { + if (error instanceof AppConnectPayloadError) return error.code + throw error + } + throw new Error('expected the payload to be refused') +} + +describe('App Connect payload crypto', () => { + it('opens what it seals, in slot order', async () => { + const response = await sealed() + expect(response.encryptedPayload.length).toBe(28 + 64) + const opened = await openAppConnectPayload({ + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + ownerId: vectorKeys.ownerId, + ...response, + }) + expect(opened).toEqual(slots) + }) + + it('refuses a response published under another identity (AAD binds $ownerId)', async () => { + const response = await sealed() + expect(await openError({ + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + ownerId: seed('someone else'), + ...response, + })).toBe('decrypt') + }) + + it('refuses a response to another request', async () => { + const response = await sealed() + expect(await openError({ + appEphemeralPrivateKey: seed('another request'), + ownerId: vectorKeys.ownerId, + ...response, + })).toBe('decrypt') + }) + + it('refuses a tampered tag or ciphertext', async () => { + const response = await sealed() + for (const index of [12, response.encryptedPayload.length - 1]) { + const encryptedPayload = response.encryptedPayload.slice() + encryptedPayload[index]! ^= 1 + expect(await openError({ + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + ownerId: vectorKeys.ownerId, + walletEphemeralPubKey: response.walletEphemeralPubKey, + encryptedPayload, + })).toBe('decrypt') + } + }) + + it('refuses a wallet key that is not a point', async () => { + const response = await sealed() + expect(await openError({ + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + ownerId: vectorKeys.ownerId, + walletEphemeralPubKey: Uint8Array.of(2, ...Array(32).fill(0xff)), + encryptedPayload: response.encryptedPayload, + })).toBe('decrypt') + }) + + it('checks framing before decrypting', async () => { + for (const length of [0, 28, 59, 61, 28 + 32 * 18]) { + expect(appConnectSlotCount(length), `length ${length}`).toBeNull() + expect(await openError({ + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + ownerId: vectorKeys.ownerId, + walletEphemeralPubKey: secp256k1.getPublicKey(vectorKeys.walletEphemeralPrivateKey, true), + encryptedPayload: new Uint8Array(length), + })).toBe('framing') + } + expect(appConnectSlotCount(60)).toBe(1) + expect(appConnectSlotCount(28 + 32 * 17)).toBe(17) + }) + + it('refuses to seal malformed slots', async () => { + await expect(sealAppConnectPayload({ appEphemeralPubKey, ownerId: vectorKeys.ownerId, slots: [] })).rejects.toThrow() + await expect(sealAppConnectPayload({ appEphemeralPubKey, ownerId: vectorKeys.ownerId, slots: [new Uint8Array(31)] })).rejects.toThrow() + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/crypto.ts b/forge-web/lib/vendor/platform-auth/app-connect/crypto.ts new file mode 100644 index 000000000..8496a6783 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/crypto.ts @@ -0,0 +1,164 @@ +import * as secp256k1 from '@noble/secp256k1' +import { concatBytes } from '@noble/hashes/utils.js' +import { clearSensitiveBytes, deriveSharedSecret, getPublicKey, hash160 } from './primitives' + +/** + * App Connect v2 response encryption: + * + * key = HKDF-SHA256(ECDH-x(appEph, walletEph), salt "dash:key-exchange:v1", info "app-connect:v2") + * aad = "dash:app-connect:v2" ‖ hash160(appEphPub) ‖ $ownerId + * body = nonce(12) ‖ AES-256-GCM(key, nonce, aad, slot₀ ‖ … ‖ slotₙ₋₁) ‖ tag(16) + * + * Each slot is a 32-byte private key. The AAD ties the ciphertext to the + * request and to the identity that publishes it, so a response copied under + * another identity fails to open. + */ + +export const APP_CONNECT_HKDF_INFO = 'app-connect:v2' +export const APP_CONNECT_AAD_PREFIX = 'dash:app-connect:v2' +export const APP_CONNECT_NONCE_BYTES = 12 +export const APP_CONNECT_ENVELOPE_BYTES = APP_CONNECT_NONCE_BYTES + 16 +export const APP_CONNECT_SLOT_BYTES = 32 +/** The `loginKeyResponse` schema's limit (572-byte payload). */ +export const APP_CONNECT_MAX_SLOTS = 17 + +const encoder = new TextEncoder() + +export class AppConnectPayloadError extends Error { + readonly code: 'framing' | 'decrypt' + + constructor(code: 'framing' | 'decrypt', message: string) { + super(message) + this.name = 'AppConnectPayloadError' + this.code = code + } +} + +export function appConnectAad(appEphemeralPubKey: Uint8Array, ownerId: Uint8Array): Uint8Array { + if (appEphemeralPubKey.length !== 33) throw new Error('app ephemeral public key must be 33 bytes') + if (ownerId.length !== 32) throw new Error('owner id must be 32 bytes') + return concatBytes(encoder.encode(APP_CONNECT_AAD_PREFIX), hash160(appEphemeralPubKey), ownerId) +} + +/** Number of key slots a payload of this length holds, or null when the framing is wrong. */ +export function appConnectSlotCount(payloadLength: number): number | null { + const body = payloadLength - APP_CONNECT_ENVELOPE_BYTES + if (body <= 0 || body % APP_CONNECT_SLOT_BYTES !== 0) return null + const slots = body / APP_CONNECT_SLOT_BYTES + return slots <= APP_CONNECT_MAX_SLOTS ? slots : null +} + +function appConnectSessionKey(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array { + return deriveSharedSecret(privateKey, publicKey, encoder.encode(APP_CONNECT_HKDF_INFO)) +} + +async function importAesKey(rawKey: Uint8Array, usage: 'encrypt' | 'decrypt'): Promise { + const copy = toArrayBuffer(rawKey) + try { + return await crypto.subtle.importKey('raw', copy, { name: 'AES-GCM' }, false, [usage]) + } finally { + new Uint8Array(copy).fill(0) + } +} + +function toArrayBuffer(bytes: Uint8Array): ArrayBuffer { + return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer +} + +export interface SealAppConnectPayloadInput { + appEphemeralPubKey: Uint8Array + ownerId: Uint8Array + slots: Uint8Array[] + /** Fresh per response; fixed only for test vectors. */ + walletEphemeralPrivateKey?: Uint8Array + /** Random by default; fixed only for test vectors. */ + nonce?: Uint8Array +} + +/** Wallet side: encrypts the granted keys to the app's request. */ +export async function sealAppConnectPayload( + input: SealAppConnectPayloadInput, +): Promise<{ walletEphemeralPubKey: Uint8Array; encryptedPayload: Uint8Array }> { + const { appEphemeralPubKey, ownerId, slots } = input + if (slots.length < 1 || slots.length > APP_CONNECT_MAX_SLOTS) { + throw new Error(`expected 1 to ${APP_CONNECT_MAX_SLOTS} slots, got ${slots.length}`) + } + if (slots.some((slot) => slot.length !== APP_CONNECT_SLOT_BYTES)) { + throw new Error(`every slot must be ${APP_CONNECT_SLOT_BYTES} bytes`) + } + const nonce = input.nonce ?? crypto.getRandomValues(new Uint8Array(APP_CONNECT_NONCE_BYTES)) + if (nonce.length !== APP_CONNECT_NONCE_BYTES) throw new Error(`nonce must be ${APP_CONNECT_NONCE_BYTES} bytes`) + + const walletEphemeralPrivateKey = input.walletEphemeralPrivateKey ?? secp256k1.utils.randomSecretKey() + const walletEphemeralPubKey = getPublicKey(walletEphemeralPrivateKey) + const sessionKey = appConnectSessionKey(walletEphemeralPrivateKey, appEphemeralPubKey) + // Built in its own ArrayBuffer and passed as is, so no copy of the keys escapes the wipe below. + const plaintextBuffer = new ArrayBuffer(slots.length * APP_CONNECT_SLOT_BYTES) + const plaintext = new Uint8Array(plaintextBuffer) + slots.forEach((slot, index) => plaintext.set(slot, index * APP_CONNECT_SLOT_BYTES)) + + try { + const key = await importAesKey(sessionKey, 'encrypt') + const sealed = new Uint8Array(await crypto.subtle.encrypt( + { name: 'AES-GCM', iv: toArrayBuffer(nonce), additionalData: toArrayBuffer(appConnectAad(appEphemeralPubKey, ownerId)) }, + key, + plaintextBuffer, + )) + return { walletEphemeralPubKey, encryptedPayload: concatBytes(nonce, sealed) } + } finally { + clearSensitiveBytes(sessionKey) + clearSensitiveBytes(plaintext) + if (!input.walletEphemeralPrivateKey) clearSensitiveBytes(walletEphemeralPrivateKey) + } +} + +export interface OpenAppConnectPayloadInput { + appEphemeralPrivateKey: Uint8Array + ownerId: Uint8Array + walletEphemeralPubKey: Uint8Array + encryptedPayload: Uint8Array +} + +/** + * App side: checks the framing and the tag, and returns the slots in payload + * order. The caller owns (and should clear) the returned keys. Throws + * {@link AppConnectPayloadError}. + */ +export async function openAppConnectPayload(input: OpenAppConnectPayloadInput): Promise { + const { encryptedPayload } = input + const slotCount = appConnectSlotCount(encryptedPayload.length) + if (slotCount === null) { + throw new AppConnectPayloadError('framing', `payload of ${encryptedPayload.length} bytes is not 28 + 32n with 1 <= n <= ${APP_CONNECT_MAX_SLOTS}`) + } + + const appEphemeralPubKey = getPublicKey(input.appEphemeralPrivateKey) + let sessionKey: Uint8Array + try { + sessionKey = appConnectSessionKey(input.appEphemeralPrivateKey, input.walletEphemeralPubKey) + } catch { + throw new AppConnectPayloadError('decrypt', 'wallet ephemeral public key is not a valid point') + } + + let plaintext: Uint8Array + try { + const key = await importAesKey(sessionKey, 'decrypt') + plaintext = new Uint8Array(await crypto.subtle.decrypt( + { + name: 'AES-GCM', + iv: toArrayBuffer(encryptedPayload.subarray(0, APP_CONNECT_NONCE_BYTES)), + additionalData: toArrayBuffer(appConnectAad(appEphemeralPubKey, input.ownerId)), + }, + key, + toArrayBuffer(encryptedPayload.subarray(APP_CONNECT_NONCE_BYTES)), + )) + } catch { + throw new AppConnectPayloadError('decrypt', 'payload does not decrypt for this request and owner') + } finally { + clearSensitiveBytes(sessionKey) + } + + const slots = Array.from({ length: slotCount }, (_, index) => + plaintext.slice(index * APP_CONNECT_SLOT_BYTES, (index + 1) * APP_CONNECT_SLOT_BYTES)) + clearSensitiveBytes(plaintext) + return slots +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/errors.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/errors.test.ts new file mode 100644 index 000000000..e022d76f6 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/errors.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' +import { classifyAppConnectError } from './errors' +import { checkAppConnectGroupTrust, type PinnedGroupTrust } from './group' +import type { AppConnectGroupInfo } from './types' + +describe('classifyAppConnectError', () => { + it('maps the key-ring consensus codes to actions', () => { + const table = [20013, 20014, 20015, 20016, 40218, 20006, 40208, 20003, 20004, 20007].map((code) => { + const c = classifyAppConnectError(code) + return [code, c?.failure, c?.action, c?.paid] + }) + expect(table).toEqual([ + [20013, 'bound-key-non-batch', 'handoff', false], + [20014, 'out-of-bounds', 'invalidate', true], + [20015, 'allowance-spent', 'renew', false], + [20016, 'expired', 'renew', false], + [40218, 'insufficient-allowance', 'renew', false], + [20006, 'key-disabled', 'logout', false], + [40208, 'key-disabled', 'logout', true], + [20003, 'key-missing', 'logout', false], + [20004, 'security-level', 'handoff', true], + [20007, 'security-level', 'handoff', false], + ]) + }) + + it('returns null for anything else', () => { + expect(classifyAppConnectError(null)).toBeNull() + expect(classifyAppConnectError(undefined)).toBeNull() + expect(classifyAppConnectError(40105)).toBeNull() + }) +}) + +describe('checkAppConnectGroupTrust', () => { + const pinned: PinnedGroupTrust = { + groupId: 'Group', + ownerId: 'Owner', + members: [ + { kind: 'contract', contractId: 'Anchor' }, + { kind: 'contract', contractId: 'Social' }, + { kind: 'documentType', contractId: 'Blog', documentTypeName: 'post' }, + ], + } + const onChain = (info: Partial): AppConnectGroupInfo => ({ + ownerId: 'Owner', + adminIds: [], + members: [...pinned.members].reverse(), + ...info, + }) + const check = (info: AppConnectGroupInfo | null, trust = pinned) => checkAppConnectGroupTrust({ groupInfo: async () => info }, trust) + + it('accepts the pinned group in any member order', async () => { + expect(await check(onChain({}))).toEqual({ ok: true }) + }) + + it('blocks a missing group, a different owner or admins', async () => { + expect(await check(null)).toEqual({ ok: false, reason: 'group-not-found' }) + expect(await check(onChain({ ownerId: 'Mallory' }))).toEqual({ ok: false, reason: 'owner-mismatch' }) + expect(await check(onChain({ adminIds: ['Mallory'] }))).toEqual({ ok: false, reason: 'admins-mismatch' }) + expect(await check(onChain({ adminIds: ['Ops'] }), { ...pinned, adminIds: ['Ops'] })).toEqual({ ok: true }) + }) + + it('blocks a missing pinned member and an unexpected member', async () => { + expect(await check(onChain({ members: pinned.members.slice(1) }))).toEqual({ + ok: false, + reason: 'missing-members', + members: [{ kind: 'contract', contractId: 'Anchor' }], + }) + const extra = { kind: 'token' as const, contractId: 'Social', position: 0 } + expect(await check(onChain({ members: [...pinned.members, extra] }))).toEqual({ + ok: false, + reason: 'unexpected-members', + members: [extra], + }) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/errors.ts b/forge-web/lib/vendor/platform-auth/app-connect/errors.ts new file mode 100644 index 000000000..8bdd632fc --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/errors.ts @@ -0,0 +1,57 @@ +/** + * Consensus errors an App Connect key ring can meet, mapped to what the app + * should do. Callers extract the numeric code from the SDK error (the app has + * `consensusCodeOf`) and pass it here. + */ + +export type AppConnectSigningFailure = + /** 20013: a bound key signed a non-batch transition. A routing bug; hand off to the wallet. */ + | 'bound-key-non-batch' + /** 20014: a batch member outside the key's bounds. Paid; the selector should make it impossible. */ + | 'out-of-bounds' + /** 20015: the key's budget is spent. */ + | 'allowance-spent' + /** 20016: the key has expired. */ + | 'expired' + /** 40218: this write needs more than the key has left. */ + | 'insufficient-allowance' + /** 20006 / 40208: the key was disabled (revoked in the wallet). */ + | 'key-disabled' + /** 20003: the key is no longer on the identity. */ + | 'key-missing' + /** 20004 / 20007: the key's security level does not meet the transition's (20004 is paid inside a batch). */ + | 'security-level' + +/** + * `renew`: keep the session (reads continue) and ask for a new grant. + * `logout`: the grant is gone; wipe the session. + * `handoff`: send this one write to the wallet. + * `invalidate`: drop cached budgets and bounds, report loudly, show a generic error. + */ +export type AppConnectFailureAction = 'renew' | 'logout' | 'handoff' | 'invalidate' + +export interface AppConnectErrorClassification { + failure: AppConnectSigningFailure + action: AppConnectFailureAction + /** Whether the refusal still cost fees (and so budget). */ + paid: boolean +} + +const CLASSIFICATIONS: Record = { + 20003: { failure: 'key-missing', action: 'logout', paid: false }, + 20004: { failure: 'security-level', action: 'handoff', paid: true }, + 20006: { failure: 'key-disabled', action: 'logout', paid: false }, + 20007: { failure: 'security-level', action: 'handoff', paid: false }, + 20013: { failure: 'bound-key-non-batch', action: 'handoff', paid: false }, + 20014: { failure: 'out-of-bounds', action: 'invalidate', paid: true }, + 20015: { failure: 'allowance-spent', action: 'renew', paid: false }, + 20016: { failure: 'expired', action: 'renew', paid: false }, + 40208: { failure: 'key-disabled', action: 'logout', paid: true }, + 40218: { failure: 'insufficient-allowance', action: 'renew', paid: false }, +} + +/** The App Connect reading of a consensus code, or null when it is not a key-ring error. */ +export function classifyAppConnectError(code: number | null | undefined): AppConnectErrorClassification | null { + if (code === null || code === undefined) return null + return CLASSIFICATIONS[code] ?? null +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/group.ts b/forge-web/lib/vendor/platform-auth/app-connect/group.ts new file mode 100644 index 000000000..cf226b8c0 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/group.ts @@ -0,0 +1,55 @@ +import type { AppConnectGroupMember, AppConnectIdentityPort, PinnedGroup } from './types' + +/** + * A group-bound key may sign for every member the group ever gains, and the + * selector routes writes by the members pinned in config. So before offering + * App Connect login the app proves the group on chain is exactly what it + * pinned: the expected owner, the expected admins (none, for Yappr), every + * pinned member present and no member it did not expect. + */ + +export interface PinnedGroupTrust extends PinnedGroup { + ownerId: string + /** Defaults to none. */ + adminIds?: string[] +} + +export type AppConnectGroupTrust = + | { ok: true } + | { ok: false; reason: 'group-not-found' | 'owner-mismatch' | 'admins-mismatch' } + | { ok: false; reason: 'missing-members' | 'unexpected-members'; members: AppConnectGroupMember[] } + +function memberKey(member: AppConnectGroupMember): string { + switch (member.kind) { + case 'contract': + return `contract:${member.contractId}` + case 'documentType': + return `documentType:${member.contractId}:${member.documentTypeName}` + case 'token': + return `token:${member.contractId}:${member.position}` + } +} + +export async function checkAppConnectGroupTrust( + port: Pick, + pinned: PinnedGroupTrust, +): Promise { + const info = await port.groupInfo(pinned.groupId) + if (!info) return { ok: false, reason: 'group-not-found' } + if (info.ownerId !== pinned.ownerId) return { ok: false, reason: 'owner-mismatch' } + + const pinnedAdmins = new Set(pinned.adminIds ?? []) + if (info.adminIds.length !== pinnedAdmins.size || info.adminIds.some((id) => !pinnedAdmins.has(id))) { + return { ok: false, reason: 'admins-mismatch' } + } + + const onChain = new Set(info.members.map(memberKey)) + const missing = pinned.members.filter((member) => !onChain.has(memberKey(member))) + if (missing.length > 0) return { ok: false, reason: 'missing-members', members: missing } + + const expected = new Set(pinned.members.map(memberKey)) + const unexpected = info.members.filter((member) => !expected.has(memberKey(member))) + if (unexpected.length > 0) return { ok: false, reason: 'unexpected-members', members: unexpected } + + return { ok: true } +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/index.ts b/forge-web/lib/vendor/platform-auth/app-connect/index.ts new file mode 100644 index 000000000..027e33262 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/index.ts @@ -0,0 +1,11 @@ +export * from './crypto' +export * from './errors' +export * from './group' +export * from './poller' +export * from './request' +export * from './session' +export * from './types' +export * from './verify' + +// primitives.ts is internal (its helper names would clash with key-exchange in the root export *). +export type { AppConnectNetworkName } from './primitives' diff --git a/forge-web/lib/vendor/platform-auth/app-connect/poller.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/poller.test.ts new file mode 100644 index 000000000..2e76604f4 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/poller.test.ts @@ -0,0 +1,88 @@ +import { encodeBase58 } from './primitives' +import { describe, expect, it, vi } from 'vitest' +import { + appConnectCandidateKey, + appConnectPollDelayMs, + listAppConnectCandidates, + type AppConnectCandidate, + type AppConnectResponsePort, +} from './poller' + +/** Ids with distinct leading bytes, so byte order is obvious; one has a leading zero byte (shorter base58). */ +const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((n) => encodeBase58(Uint8Array.from({ length: 32 }, (_, i) => (i === 0 ? n * 16 : 7)))) + +function candidate(ownerId: string): AppConnectCandidate { + return { ownerId, walletEphemeralPubKey: new Uint8Array(33).fill(2), encryptedPayload: new Uint8Array(60) } +} + +/** A port over `owners` that honours the cursor, the hint and the limit like Platform does. */ +function port(owners: string[]): AppConnectResponsePort & { calls: unknown[][] } { + const calls: unknown[][] = [] + return { + calls, + async listCandidates(_hash, hint, startAfter, limit) { + calls.push([hint, startAfter, limit]) + const after = startAfter === undefined ? 0 : owners.indexOf(startAfter) + 1 + return owners.slice(after).filter((o) => hint === undefined || o === hint).slice(0, limit).map(candidate) + }, + } +} + +describe('listAppConnectCandidates', () => { + it('pages with the last owner as cursor until a short page', async () => { + const p = port(ids.slice(0, 7)) + const { candidates, truncated } = await listAppConnectCandidates(p, new Uint8Array(20), { pageSize: 3 }) + expect(candidates.map((c) => c.ownerId)).toEqual(ids.slice(0, 7)) + expect(truncated).toBe(false) + expect(p.calls).toEqual([[undefined, undefined, 3], [undefined, ids[2]!, 3], [undefined, ids[5]!, 3]]) + }) + + it('stops at maxCandidates and reports truncation', async () => { + const { candidates, truncated } = await listAppConnectCandidates(port(ids), new Uint8Array(20), { pageSize: 5, maxCandidates: 8 }) + expect(candidates).toHaveLength(8) + expect(truncated).toBe(true) + }) + + it('passes the hint and drops anything else a port returns', async () => { + const sloppy: AppConnectResponsePort = { listCandidates: async () => [candidate(ids[1]!), candidate(ids[2]!)] } + const { candidates } = await listAppConnectCandidates(sloppy, new Uint8Array(20), { hint: ids[2]! }) + expect(candidates.map((c) => c.ownerId)).toEqual([ids[2]!]) + const p = port(ids) + await listAppConnectCandidates(p, new Uint8Array(20), { hint: ids[4]! }) + expect(p.calls[0]![0]).toBe(ids[4]!) + }) + + it('stops when a port ignores the cursor instead of looping', async () => { + const listCandidates = vi.fn(async () => [candidate(ids[0]!), candidate(ids[1]!)]) + const { candidates } = await listAppConnectCandidates({ listCandidates }, new Uint8Array(20), { pageSize: 2 }) + expect(candidates.map((c) => c.ownerId)).toEqual([ids[0]!, ids[1]!]) + expect(listCandidates).toHaveBeenCalledTimes(2) + }) + + it('orders the cursor by bytes, not by base58 text', async () => { + // ids[0]! has a leading zero byte, so its base58 form is shorter and sorts oddly as text. + expect(ids[0]!.length).toBeLessThan(ids[1]!.length) + const { candidates } = await listAppConnectCandidates(port(ids.slice(0, 4)), new Uint8Array(20), { pageSize: 1 }) + expect(candidates.map((c) => c.ownerId)).toEqual(ids.slice(0, 4)) + }) +}) + +describe('appConnectPollDelayMs', () => { + it('polls every 2 s for a minute, then every 4 s, and stops at 10 minutes', () => { + expect(appConnectPollDelayMs(0)).toBe(2000) + expect(appConnectPollDelayMs(59_999)).toBe(2000) + expect(appConnectPollDelayMs(60_000)).toBe(4000) + expect(appConnectPollDelayMs(10 * 60_000 - 1)).toBe(4000) + expect(appConnectPollDelayMs(10 * 60_000)).toBeNull() + }) +}) + +describe('appConnectCandidateKey', () => { + it('changes when a response is republished with different contents', () => { + const a = candidate(ids[1]!) + const b = { ...a, encryptedPayload: Uint8Array.from(a.encryptedPayload, (_, i) => (i === 0 ? 1 : 0)) } + expect(appConnectCandidateKey(a)).toBe(appConnectCandidateKey(candidate(ids[1]!))) + expect(appConnectCandidateKey(a)).not.toBe(appConnectCandidateKey(b)) + expect(appConnectCandidateKey(a).startsWith(`${ids[1]!}:`)).toBe(true) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/poller.ts b/forge-web/lib/vendor/platform-auth/app-connect/poller.ts new file mode 100644 index 000000000..3236522c5 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/poller.ts @@ -0,0 +1,110 @@ +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex, concatBytes } from '@noble/hashes/utils.js' +import { decodeBase58 } from './primitives' +import { APP_CONNECT_MAX_REQUEST_AGE_MS } from './request' + +/** + * Candidate discovery for App Connect. Responses live in the App Connect system + * contract (`H8F9…`, `loginKeyResponse`), keyed by `appEphemeralPubKeyHash` + * then `$ownerId`. Anyone can answer a request, so the app pages through every + * candidate and verifies each one; nothing here decides who logged in. + */ + +/** One `loginKeyResponse` entry. */ +export interface AppConnectCandidate { + ownerId: string + walletEphemeralPubKey: Uint8Array + encryptedPayload: Uint8Array +} + +export interface AppConnectResponsePort { + /** + * Up to `limit` responses with `appEphemeralPubKeyHash == requestHash`, + * ordered by `$ownerId` ascending, after `startAfter` when given, and only + * `$ownerId == hint` when a hint is given. + */ + listCandidates( + requestHash: Uint8Array, + hint: string | undefined, + startAfter: string | undefined, + limit: number, + ): Promise +} + +export const APP_CONNECT_PAGE_SIZE = 10 +/** Past this many candidates the app stops and asks the user to start again. */ +export const APP_CONNECT_MAX_CANDIDATES = 20 +export const APP_CONNECT_FAST_POLL_MS = 2_000 +export const APP_CONNECT_SLOW_POLL_MS = 4_000 +export const APP_CONNECT_FAST_POLL_WINDOW_MS = 60_000 + +export interface ListAppConnectCandidatesOptions { + hint?: string + pageSize?: number + maxCandidates?: number +} + +/** + * Pages through every candidate for a request. `truncated` means more than + * `maxCandidates` exist (spam): the caller should abandon the request. + */ +export async function listAppConnectCandidates( + port: AppConnectResponsePort, + requestHash: Uint8Array, + options: ListAppConnectCandidatesOptions = {}, +): Promise<{ candidates: AppConnectCandidate[]; truncated: boolean }> { + const { hint, pageSize = APP_CONNECT_PAGE_SIZE, maxCandidates = APP_CONNECT_MAX_CANDIDATES } = options + const candidates: AppConnectCandidate[] = [] + let startAfter: string | undefined + + for (;;) { + const page = await port.listCandidates(requestHash, hint, startAfter, pageSize) + for (const candidate of page) { + // Defend against a port that ignores the cursor or the hint: anything not + // strictly after the cursor would loop, anything else is not ours to see. + if (startAfter !== undefined && !idAfter(candidate.ownerId, startAfter)) return { candidates, truncated: false } + startAfter = candidate.ownerId + if (hint !== undefined && candidate.ownerId !== hint) continue + if (candidates.length === maxCandidates) return { candidates, truncated: true } + candidates.push(candidate) + } + if (page.length < pageSize) return { candidates, truncated: false } + } +} + +/** Whether base58 id `a` sorts strictly after `b` in byte order, as Platform orders `$ownerId`. */ +function idAfter(a: string, b: string): boolean { + let left: Uint8Array + let right: Uint8Array + try { + left = decodeBase58(a) + right = decodeBase58(b) + } catch { + return false + } + for (let i = 0; i < Math.min(left.length, right.length); i++) { + const l = left[i] ?? 0 + const r = right[i] ?? 0 + if (l !== r) return l > r + } + return left.length > right.length +} + +/** + * Delay before the next poll: every 2 s for the first minute, then every 4 s, + * and null once the request has expired (10 minutes). Polls on focus or on the + * wallet's callback happen immediately, outside this cadence. + */ +export function appConnectPollDelayMs(elapsedMs: number): number | null { + if (elapsedMs >= APP_CONNECT_MAX_REQUEST_AGE_MS) return null + return elapsedMs < APP_CONNECT_FAST_POLL_WINDOW_MS ? APP_CONNECT_FAST_POLL_MS : APP_CONNECT_SLOW_POLL_MS +} + +/** + * Identifies a candidate's exact contents, so a poll loop verifies each + * response once and notices when an identity republishes a different one. + */ +export function appConnectCandidateKey(candidate: AppConnectCandidate): string { + const contents = concatBytes(candidate.walletEphemeralPubKey, candidate.encryptedPayload) + return `${candidate.ownerId}:${bytesToHex(sha256(contents))}` +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/primitives.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/primitives.test.ts new file mode 100644 index 000000000..bcc51d492 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/primitives.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { decodeBase58, decodeIdentityId, deriveSharedSecret, encodeBase58, getPublicKey, hash160 } from './primitives' +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' + +const text = (value: string) => new TextEncoder().encode(value) + +describe('base58', () => { + const cases: Array<[string, string]> = [ + ['', ''], + ['00', '1'], + ['0000', '11'], + ['61', '2g'], + ['00000001', '1112'], + [bytesToHex(text('Hello World!')), '2NEpo7TZRRrLZSi2U'], + ['00eb15231dfceb60925886b67d065299925915aeb172c06647', '1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L'], + ] + + it('matches known Bitcoin-alphabet vectors both ways', () => { + for (const [hex, base58] of cases) { + expect(encodeBase58(hexToBytes(hex))).toBe(base58) + expect(bytesToHex(decodeBase58(base58))).toBe(hex) + } + }) + + it('round-trips identity ids with and without a leading zero byte', () => { + for (const first of [0, 1, 0x80, 0xff]) { + const bytes = Uint8Array.from({ length: 32 }, (_, i) => (i === 0 ? first : (i * 37) & 0xff)) + expect(decodeBase58(encodeBase58(bytes))).toEqual(bytes) + } + }) + + it('rejects characters outside the alphabet', () => { + for (const bad of ['0', 'O', 'I', 'l', 'ab c', '+/']) expect(() => decodeBase58(bad)).toThrow() + }) +}) + +describe('decodeIdentityId', () => { + it('requires exactly 32 bytes', () => { + const id = 'Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7' + expect(decodeIdentityId(id)).toHaveLength(32) + expect(() => decodeIdentityId(encodeBase58(new Uint8Array(31).fill(1)))).toThrow(/expected 32, got 31/) + }) +}) + +describe('hash160 and ECDH', () => { + it('hash160 of the empty input is the well-known RIPEMD160(SHA256(""))', () => { + expect(bytesToHex(hash160(new Uint8Array(0)))).toBe('b472a266d0bd89c13706a4132ccfb16f7c3b9fcb') + }) + + it('derives the same secret from either side and separates by info', () => { + const a = Uint8Array.from({ length: 32 }, (_, i) => i + 1) + const b = Uint8Array.from({ length: 32 }, (_, i) => 100 + i) + const ab = deriveSharedSecret(a, getPublicKey(b), text('app-connect:v2')) + const ba = deriveSharedSecret(b, getPublicKey(a), text('app-connect:v2')) + expect(ab).toEqual(ba) + expect(ab).not.toEqual(deriveSharedSecret(a, getPublicKey(b))) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/primitives.ts b/forge-web/lib/vendor/platform-auth/app-connect/primitives.ts new file mode 100644 index 000000000..f764ae174 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/primitives.ts @@ -0,0 +1,118 @@ +import * as secp256k1 from '@noble/secp256k1' +import { hkdf } from '@noble/hashes/hkdf.js' +import { ripemd160 } from '@noble/hashes/legacy.js' +import { sha256 } from '@noble/hashes/sha2.js' + +/** + * The small set of primitives the App Connect module needs, kept here so the + * module depends only on `@noble/hashes` and `@noble/secp256k1` and can be + * vendored on its own. These are internal: `index.ts` re-exports only the + * `AppConnectNetworkName` type, because names like `hash160` would clash with + * the key-exchange module in the package root. + */ + +/** The one-letter network id carried in the `n=` parameter of an App Connect URI. */ +export const APP_CONNECT_NETWORK_IDS = { + mainnet: 'm', + testnet: 't', + devnet: 'd', +} as const + +export type AppConnectNetworkName = keyof typeof APP_CONNECT_NETWORK_IDS + +const encoder = new TextEncoder() +const NO_HKDF_INFO = new Uint8Array(0) + +export function hash160(data: Uint8Array): Uint8Array { + return ripemd160(sha256(data)) +} + +/** + * ECDH x-coordinate then HKDF-SHA256 (salt `dash:key-exchange:v1`). ECDH is + * symmetric, so the wallet calls this with its private key and the app's + * public key. The legacy key exchange uses an empty `info`; App Connect v2 + * passes `app-connect:v2`. Intermediate buffers are zeroed before returning. + */ +export function deriveSharedSecret( + privateKey: Uint8Array, + publicKey: Uint8Array, + info: Uint8Array = NO_HKDF_INFO, +): Uint8Array { + const sharedPoint = secp256k1.getSharedSecret(privateKey, publicKey) + const sharedX = sharedPoint.slice(1, 33) + try { + return hkdf(sha256, sharedX, encoder.encode('dash:key-exchange:v1'), info, 32) + } finally { + sharedX.fill(0) + sharedPoint.fill(0) + } +} + +export function getPublicKey(privateKey: Uint8Array): Uint8Array { + return secp256k1.getPublicKey(privateKey, true) +} + +export function clearSensitiveBytes(bytes: Uint8Array): void { + bytes.fill(0) +} + +const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +const BASE58_INDEX: Record = Object.fromEntries( + Array.from(BASE58_ALPHABET, (char, index) => [char, index]), +) + +/** Base58 (Bitcoin alphabet) encoding; each leading zero byte becomes a leading `1`. */ +export function encodeBase58(bytes: Uint8Array): string { + let zeros = 0 + while (zeros < bytes.length && bytes[zeros] === 0) zeros++ + // Little-endian base-58 digits of the remaining big-endian number. + const digits: number[] = [] + for (let i = zeros; i < bytes.length; i++) { + let carry = bytes[i] ?? 0 + for (let j = 0; j < digits.length; j++) { + carry += (digits[j] ?? 0) << 8 + digits[j] = carry % 58 + carry = Math.floor(carry / 58) + } + while (carry > 0) { + digits.push(carry % 58) + carry = Math.floor(carry / 58) + } + } + let out = '1'.repeat(zeros) + for (let i = digits.length - 1; i >= 0; i--) out += BASE58_ALPHABET.charAt(digits[i] ?? 0) + return out +} + +/** Inverse of {@link encodeBase58}; throws on any character outside the alphabet. */ +export function decodeBase58(text: string): Uint8Array { + let zeros = 0 + while (zeros < text.length && text.charAt(zeros) === '1') zeros++ + // Little-endian bytes of the remaining base-58 number. + const bytes: number[] = [] + for (let i = zeros; i < text.length; i++) { + const value = BASE58_INDEX[text.charAt(i)] + if (value === undefined) throw new Error('Non-base58 character') + let carry = value + for (let j = 0; j < bytes.length; j++) { + carry += (bytes[j] ?? 0) * 58 + bytes[j] = carry & 0xff + carry >>= 8 + } + while (carry > 0) { + bytes.push(carry & 0xff) + carry >>= 8 + } + } + const out = new Uint8Array(zeros + bytes.length) + for (let i = 0; i < bytes.length; i++) out[out.length - 1 - i] = bytes[i] ?? 0 + return out +} + +export function decodeIdentityId(identityIdBase58: string): Uint8Array { + const decoded = decodeBase58(identityIdBase58) + if (decoded.length !== 32) { + throw new Error(`Invalid identity ID length: expected 32, got ${decoded.length}`) + } + return decoded +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/request.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/request.test.ts new file mode 100644 index 000000000..bd6b690ab --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/request.test.ts @@ -0,0 +1,197 @@ +import { encodeBase58 } from './primitives' +import { describe, expect, it } from 'vitest' +import { + AppConnectRequestError, + buildAppConnectUri, + checkAppConnectRequestAge, + decodeAppConnectRequest, + encodeAppConnectRequest, + parseAppConnectUri, + type AppConnectRequest, +} from './request' +import { KeySecurityLevel } from './types' +import { VECTOR_CREATED_AT, renewVectorRequest, yapprVectorRequest } from './test-helpers' + +function refusal(fn: () => unknown): AppConnectRequestError { + try { + fn() + } catch (error) { + if (error instanceof AppConnectRequestError) return error + throw error + } + throw new Error('expected an AppConnectRequestError') +} + +// Layout of the Yappr vector request: a 72-byte header (version, key, app id, +// label "Yappr"), the group AUTH_BINDING TLV at 72 (52 bytes), the DashPay +// profile AUTH_BINDING at 124 (60 bytes), CONNECTION_ID at 184, ENC_BINDING +// at 202 (184 without a connection id) and CREATED_AT last. +const GROUP_KIND_AT = 74 +const PROFILE_LEVEL_AT = 127 +const CONNECTION_ID_AT = 184 + +function withTlv(bytes: Uint8Array, type: number, value: number[]): Uint8Array { + return Uint8Array.from([...bytes, type, value.length, ...value]) +} + +describe('App Connect request v2 codec', () => { + it('round-trips the Yappr request and the renew request', () => { + for (const request of [yapprVectorRequest(), renewVectorRequest()]) { + expect(decodeAppConnectRequest(encodeAppConnectRequest(request))).toEqual(request) + } + }) + + it('round-trips through the URI with network and callback', () => { + const request = yapprVectorRequest() + const uri = buildAppConnectUri(request, 'mainnet', 'https://yap.pr/connect?r=ab') + expect(uri.startsWith('dash-key:')).toBe(true) + expect(uri).toContain('?n=m&v=2&cb=https%3A%2F%2Fyap.pr%2Fconnect%3Fr%3Dab') + const parsed = parseAppConnectUri(uri) + expect(parsed.request).toEqual(request) + expect(parsed.network).toBe('mainnet') + expect(parsed.callbackUrl).toBe('https://yap.pr/connect?r=ab') + }) + + it('ignores unknown optional (odd) TLVs', () => { + const request = yapprVectorRequest() + const bytes = withTlv(encodeAppConnectRequest(request), 0x07, [0xaa, 0xbb]) + expect(decodeAppConnectRequest(withTlv(bytes, 0x09, []))).toEqual(request) + }) + + it('accepts repeats of an unknown optional TLV', () => { + const request = yapprVectorRequest() + const bytes = withTlv(withTlv(encodeAppConnectRequest(request), 0x07, [1]), 0x07, [2]) + expect(decodeAppConnectRequest(bytes)).toEqual(request) + }) + + it('refuses unknown mandatory (even) TLVs as unsupported', () => { + const bytes = withTlv(encodeAppConnectRequest(yapprVectorRequest()), 0x08, [0x01]) + expect(refusal(() => decodeAppConnectRequest(bytes)).code).toBe('unsupported') + }) + + it('refuses an unknown binding kind as unsupported', () => { + const tampered = encodeAppConnectRequest(yapprVectorRequest()) + tampered[GROUP_KIND_AT] = 7 + expect(refusal(() => decodeAppConnectRequest(tampered)).code).toBe('unsupported') + }) + + it('refuses every truncation', () => { + const bytes = encodeAppConnectRequest(yapprVectorRequest()) + for (let length = 0; length < bytes.length; length++) { + expect(() => decodeAppConnectRequest(bytes.subarray(0, length)), `length ${length}`).toThrow(AppConnectRequestError) + } + }) + + it('refuses a v1 body and a v1 URI as unsupported', () => { + const bytes = encodeAppConnectRequest(yapprVectorRequest()) + bytes[0] = 1 + expect(refusal(() => decodeAppConnectRequest(bytes)).code).toBe('unsupported') + const uri = buildAppConnectUri(yapprVectorRequest(), 'testnet').replace('&v=2', '&v=1') + expect(refusal(() => parseAppConnectUri(uri)).code).toBe('unsupported') + }) + + it('refuses TLVs out of order and repeated singletons', () => { + const base = encodeAppConnectRequest(yapprVectorRequest()) + // A second CREATED_AT after the first. + expect(refusal(() => decodeAppConnectRequest(withTlv(base, 0x06, [0, 0, 1, 0x99, 0, 0, 0, 0]))).code).toBe('invalid') + // An IDENTITY_HINT after CREATED_AT. + expect(refusal(() => decodeAppConnectRequest(withTlv(base, 0x01, Array(32).fill(1)))).code).toBe('invalid') + }) + + it('refuses known TLVs with the wrong length', () => { + const bytes = encodeAppConnectRequest({ ...yapprVectorRequest(), connectionId: undefined }) + const at = CONNECTION_ID_AT + const spliced = Uint8Array.from([...bytes.subarray(0, at), 0x03, 15, ...Array(15).fill(0), ...bytes.subarray(at)]) + expect(refusal(() => decodeAppConnectRequest(spliced)).code).toBe('invalid') + }) + + it('only knows MODE = renew (absent means login)', () => { + const renew = encodeAppConnectRequest(renewVectorRequest()) + // MODE sits just before the 10-byte CREATED_AT. + const modeAt = renew.length - 10 - 3 + expect([...renew.subarray(modeAt, modeAt + 3)]).toEqual([0x05, 1, 1]) + const zero = renew.slice() + zero[modeAt + 2] = 0 + expect(refusal(() => decodeAppConnectRequest(zero)).code).toBe('invalid') + }) + + it('keeps a leading BOM instead of stripping it', () => { + const request = yapprVectorRequest() + const labelled = { ...request, label: '\ufeffYappr' } + expect(decodeAppConnectRequest(encodeAppConnectRequest(labelled)).label).toBe('\ufeffYappr') + + // A DashPay binding whose name is EF BB BF "profile" must not decode as "profile". + const bytes = encodeAppConnectRequest(request) + const nameAt = PROFILE_LEVEL_AT + 1 + 32 + 16 + expect(bytes[nameAt]).toBe(7) + const spliced = Uint8Array.from([ + ...bytes.subarray(0, PROFILE_LEVEL_AT - 3), + 0x02, 61, ...bytes.subarray(PROFILE_LEVEL_AT - 1, nameAt), 10, 0xef, 0xbb, 0xbf, + ...bytes.subarray(nameAt + 1), + ]) + expect(refusal(() => decodeAppConnectRequest(spliced)).message).toMatch(/document type name/) + }) + + it('requires CREATED_AT', () => { + const bytes = encodeAppConnectRequest(yapprVectorRequest()) + expect(refusal(() => decodeAppConnectRequest(bytes.subarray(0, bytes.length - 10))).code).toBe('invalid') + }) + + it('enforces binding rules on encode and decode', () => { + const request = yapprVectorRequest() + const group = request.authBindings[0]! + const profile = request.authBindings[1]! + const cases: Array<[string, AppConnectRequest]> = [ + ['CRITICAL on a documentType binding', { ...request, authBindings: [group, { ...profile, securityLevel: KeySecurityLevel.CRITICAL }] }], + ['MASTER on a group binding', { ...request, authBindings: [{ ...group, securityLevel: KeySecurityLevel.MASTER }] }], + ['MEDIUM on a group binding', { ...request, authBindings: [{ ...group, securityLevel: KeySecurityLevel.MEDIUM }] }], + ['a group binding without a budget', { ...request, authBindings: [{ ...group, totalBudget: undefined }] }], + ['a documentType binding without a name', { ...request, authBindings: [{ ...profile, documentTypeName: undefined }] }], + ['a bad document type name', { ...request, authBindings: [{ ...profile, documentTypeName: 'pro file' }] }], + ['a name on a group binding', { ...request, authBindings: [{ ...group, documentTypeName: 'post' }] }], + ['no auth bindings', { ...request, authBindings: [] }], + ['five auth bindings', { ...request, authBindings: [group, profile, { ...profile, documentTypeName: 'a' }, { ...profile, documentTypeName: 'b' }, { ...profile, documentTypeName: 'c' }] }], + ['duplicate auth bindings', { ...request, authBindings: [group, group] }], + ['an encryption binding with the AUTHENTICATION purpose', { ...request, encBindings: [{ contractId: request.appId, purpose: 0 }] }], + ['a short identity hint', { ...request, identityHint: new Uint8Array(31) }], + ['a long label', { ...request, label: 'x'.repeat(65) }], + ['a label with a bidi override', { ...request, label: 'Yappr\u202e' }], + ['a label with a control character', { ...request, label: 'Yap\npr' }], + ['an inherited property as the binding kind', { ...request, authBindings: [{ ...group, kind: 'toString' as 'contractGroup' }] }], + ['an invalid ephemeral key', { ...request, appEphemeralPubKey: Uint8Array.of(2, ...Array(32).fill(0xff)) }], + ] + for (const [name, bad] of cases) { + expect(() => encodeAppConnectRequest(bad), name).toThrow(AppConnectRequestError) + } + + // The decoder applies the same rules to bytes a lax encoder produced. + const tampered = encodeAppConnectRequest(request) + expect(tampered[PROFILE_LEVEL_AT]).toBe(KeySecurityLevel.HIGH) + tampered[PROFILE_LEVEL_AT] = KeySecurityLevel.CRITICAL + expect(refusal(() => decodeAppConnectRequest(tampered)).message).toMatch(/security level 1/) + }) + + it('checks the URI query', () => { + const uri = buildAppConnectUri(yapprVectorRequest(), 'devnet') + expect(parseAppConnectUri(uri).network).toBe('devnet') + expect(refusal(() => parseAppConnectUri(uri.replace('n=d', 'n=x'))).code).toBe('invalid') + expect(refusal(() => parseAppConnectUri(`${uri}&v=2`)).code).toBe('invalid') + expect(refusal(() => parseAppConnectUri(`${uri}&cb=${encodeURIComponent('http://yap.pr/connect')}`)).code).toBe('invalid') + expect(refusal(() => parseAppConnectUri(`${uri}&cb=${encodeURIComponent('https://u:p@yap.pr/')}`)).code).toBe('invalid') + expect(() => buildAppConnectUri(yapprVectorRequest(), 'devnet', 'javascript:alert(1)')).toThrow(AppConnectRequestError) + expect(refusal(() => parseAppConnectUri(uri.replace('dash-key:', 'dash-key:0OIl'))).code).toBe('invalid') + }) + + it('applies the wallet freshness window', () => { + expect(checkAppConnectRequestAge(VECTOR_CREATED_AT, VECTOR_CREATED_AT + 10 * 60_000)).toBeNull() + expect(checkAppConnectRequestAge(VECTOR_CREATED_AT, VECTOR_CREATED_AT + 10 * 60_000 + 1)).toBe('stale') + expect(checkAppConnectRequestAge(VECTOR_CREATED_AT, VECTOR_CREATED_AT - 2 * 60_000)).toBeNull() + expect(checkAppConnectRequestAge(VECTOR_CREATED_AT, VECTOR_CREATED_AT - 2 * 60_000 - 1)).toBe('future') + }) + + it('carries ids as raw bytes', () => { + const request = yapprVectorRequest() + const decoded = decodeAppConnectRequest(encodeAppConnectRequest(request)) + expect(encodeBase58(decoded.authBindings[1]!.id)).toBe('Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7') + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/request.ts b/forge-web/lib/vendor/platform-auth/app-connect/request.ts new file mode 100644 index 000000000..3a848b96c --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/request.ts @@ -0,0 +1,495 @@ +import * as secp256k1 from '@noble/secp256k1' +import { APP_CONNECT_NETWORK_IDS, decodeBase58, encodeBase58, hash160, type AppConnectNetworkName } from './primitives' +import { KeyPurpose, KeySecurityLevel, type AppConnectKeyBounds } from './types' + +/** + * App Connect request v2 (docs/APP_CONNECT_PROFILE.md): + * + * body = 0x02 ‖ appEphPub(33) ‖ appId(32) ‖ labelLen(1) ‖ label ‖ TLV* + * TLV = type(1) ‖ len(1) ‖ value + * uri = dash-key:?n=&v=2[&cb=] + * + * Even TLV types must be understood (a decoder refuses unknown ones); odd + * types are optional and unknown ones are skipped. TLVs appear in ascending + * type order and only AUTH_BINDING and ENC_BINDING repeat, so every request + * has exactly one encoding. + */ + +export const APP_CONNECT_REQUEST_VERSION = 2 +export const APP_CONNECT_MAX_LABEL_BYTES = 64 +export const APP_CONNECT_MAX_AUTH_BINDINGS = 4 +export const APP_CONNECT_MAX_ENC_BINDINGS = 2 +export const APP_CONNECT_MAX_CALLBACK_LENGTH = 512 +/** A wallet refuses a request created longer ago than this... */ +export const APP_CONNECT_MAX_REQUEST_AGE_MS = 10 * 60_000 +/** ...or further in the future than this (clock skew). */ +export const APP_CONNECT_MAX_REQUEST_SKEW_MS = 2 * 60_000 + +export const AppConnectTlv = { + IDENTITY_HINT: 0x01, + AUTH_BINDING: 0x02, + CONNECTION_ID: 0x03, + ENC_BINDING: 0x04, + MODE: 0x05, + CREATED_AT: 0x06, +} as const + +/** Wire tags of AUTH_BINDING kinds; equal to Platform's `ContractBounds` bincode tags. */ +const BINDING_KIND_TAGS = { singleContract: 0, documentType: 1, contractGroup: 2 } as const + +export type AppConnectBindingKind = keyof typeof BINDING_KIND_TAGS +/** Absent means login; MODE carries only renew. */ +export type AppConnectMode = 'renew' + +export interface AppConnectAuthBinding { + kind: AppConnectBindingKind + /** Contract id, or the group id for `contractGroup`. */ + id: Uint8Array + /** Required for `documentType`, absent otherwise. */ + documentTypeName?: string + /** CRITICAL only on `contractGroup`; HIGH everywhere. */ + securityLevel: number + /** Proposed lifetime budget in credits; mandatory on `contractGroup`. Zero on the wire means none. */ + totalBudget?: bigint + /** Proposed expiry, block time in ms. Zero on the wire means none. */ + expiresAt?: number +} + +export interface AppConnectEncBinding { + contractId: Uint8Array + /** ENCRYPTION or DECRYPTION. */ + purpose: number +} + +export interface AppConnectRequest { + appEphemeralPubKey: Uint8Array + appId: Uint8Array + label: string + /** 1–4; the first is the primary binding a wallet may not decline on its own. */ + authBindings: AppConnectAuthBinding[] + encBindings: AppConnectEncBinding[] + /** ms since epoch. */ + createdAt: number + identityHint?: Uint8Array + connectionId?: Uint8Array + mode?: AppConnectMode +} + +export interface ParsedAppConnectUri { + request: AppConnectRequest + requestBytes: Uint8Array + network: AppConnectNetworkName + callbackUrl?: string +} + +/** + * `unsupported`: a version or mandatory field this decoder does not know (a + * newer app); `invalid`: anything else that breaks the format. + */ +export type AppConnectRequestErrorCode = 'unsupported' | 'invalid' + +export class AppConnectRequestError extends Error { + readonly code: AppConnectRequestErrorCode + + constructor(code: AppConnectRequestErrorCode, message: string) { + super(message) + this.name = 'AppConnectRequestError' + this.code = code + } +} + +const encoder = new TextEncoder() +// ignoreBOM keeps a leading U+FEFF instead of silently dropping it. +const strictDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) +const DOCUMENT_TYPE_NAME = /^[A-Za-z0-9_-]{1,64}$/ +// C0 and C1 controls, and the bidi marks, embeddings, overrides and isolates a label could use to disguise itself. +// eslint-disable-next-line no-control-regex -- matching control characters is the point (EvoVote lint) +const LABEL_FORBIDDEN = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/ +const AUTH_BINDING_FIXED_BYTES = 1 + 1 + 32 + 8 + 8 +const ENC_BINDING_BYTES = 33 +const FIXED_VALUE_BYTES: Partial> = { + [AppConnectTlv.IDENTITY_HINT]: 32, + [AppConnectTlv.CONNECTION_ID]: 16, + [AppConnectTlv.ENC_BINDING]: ENC_BINDING_BYTES, + [AppConnectTlv.MODE]: 1, + [AppConnectTlv.CREATED_AT]: 8, +} +const MAX_U64 = (1n << 64n) - 1n +const KNOWN_TLV_TYPES: ReadonlySet = new Set(Object.values(AppConnectTlv)) + +function invalid(message: string): never { + throw new AppConnectRequestError('invalid', message) +} + +/** `hash160(appEphPub)`: the `appEphemeralPubKeyHash` responses are stored under. */ +export function appConnectRequestHash(request: Pick): Uint8Array { + return hash160(request.appEphemeralPubKey) +} + +/** The key bounds an auth binding asks for, with base58 ids. */ +export function authBindingBounds(binding: AppConnectAuthBinding): AppConnectKeyBounds { + const id = encodeBase58(binding.id) + switch (binding.kind) { + case 'singleContract': + return { kind: 'singleContract', contractId: id } + case 'documentType': + return { kind: 'documentType', contractId: id, documentTypeName: binding.documentTypeName ?? '' } + case 'contractGroup': + return { kind: 'contractGroup', groupId: id } + } +} + +/** The key bounds an encryption binding asks for: `singleContract` on its contract. */ +export function encBindingBounds(binding: AppConnectEncBinding): AppConnectKeyBounds { + return { kind: 'singleContract', contractId: encodeBase58(binding.contractId) } +} + +/** + * Checks the protocol rules every request obeys, whoever built it. The encoder + * runs it before writing and the decoder after reading, so neither side can + * produce or accept a request the other would refuse. + */ +export function validateAppConnectRequest(request: AppConnectRequest): void { + checkPublicKey(request.appEphemeralPubKey) + checkLength(request.appId, 32, 'app id') + if (encoder.encode(request.label).length > APP_CONNECT_MAX_LABEL_BYTES) { + invalid(`label is longer than ${APP_CONNECT_MAX_LABEL_BYTES} bytes`) + } + if (LABEL_FORBIDDEN.test(request.label)) invalid('label contains control or bidirectional formatting characters') + + const { authBindings, encBindings } = request + if (authBindings.length < 1 || authBindings.length > APP_CONNECT_MAX_AUTH_BINDINGS) { + invalid(`expected 1 to ${APP_CONNECT_MAX_AUTH_BINDINGS} auth bindings, got ${authBindings.length}`) + } + const seenBounds = new Set() + for (const binding of authBindings) { + checkAuthBinding(binding) + const key = `${binding.kind}:${encodeBase58(binding.id)}:${binding.documentTypeName ?? ''}` + if (seenBounds.has(key)) invalid('duplicate auth binding') + seenBounds.add(key) + } + + if (encBindings.length > APP_CONNECT_MAX_ENC_BINDINGS) { + invalid(`expected at most ${APP_CONNECT_MAX_ENC_BINDINGS} encryption bindings, got ${encBindings.length}`) + } + const seenEnc = new Set() + for (const binding of encBindings) { + checkLength(binding.contractId, 32, 'encryption binding contract id') + if (binding.purpose !== KeyPurpose.ENCRYPTION && binding.purpose !== KeyPurpose.DECRYPTION) { + invalid(`encryption binding purpose ${binding.purpose} is not ENCRYPTION or DECRYPTION`) + } + const key = `${encodeBase58(binding.contractId)}:${binding.purpose}` + if (seenEnc.has(key)) invalid('duplicate encryption binding') + seenEnc.add(key) + } + + if (!Number.isSafeInteger(request.createdAt) || request.createdAt <= 0) { + invalid('created-at must be a positive millisecond timestamp') + } + if (request.identityHint !== undefined) checkLength(request.identityHint, 32, 'identity hint') + if (request.connectionId !== undefined) checkLength(request.connectionId, 16, 'connection id') + if (request.mode !== undefined && request.mode !== 'renew') { + invalid(`unknown mode ${String(request.mode)}`) + } +} + +function checkAuthBinding(binding: AppConnectAuthBinding): void { + // hasOwn, not `in`: 'toString' is `in` every object. + if (!Object.hasOwn(BINDING_KIND_TAGS, binding.kind)) invalid(`unknown binding kind ${String(binding.kind)}`) + checkLength(binding.id, 32, 'binding id') + + if (binding.kind === 'documentType') { + if (binding.documentTypeName === undefined || !DOCUMENT_TYPE_NAME.test(binding.documentTypeName)) { + invalid('a documentType binding needs a document type name of 1-64 [A-Za-z0-9_-]') + } + } else if (binding.documentTypeName !== undefined) { + invalid(`a ${binding.kind} binding carries no document type name`) + } + + const level = binding.securityLevel + const levelAllowed = binding.kind === 'contractGroup' + ? level === KeySecurityLevel.CRITICAL || level === KeySecurityLevel.HIGH + : level === KeySecurityLevel.HIGH + if (!levelAllowed) { + invalid(`security level ${binding.securityLevel} is not allowed on a ${binding.kind} binding`) + } + + if (binding.totalBudget !== undefined && (binding.totalBudget <= 0n || binding.totalBudget > MAX_U64)) { + invalid('total budget must be between 1 and 2^64-1 credits') + } + if (binding.kind === 'contractGroup' && binding.totalBudget === undefined) { + invalid('a contractGroup binding must carry a budget') + } + if (binding.expiresAt !== undefined && (!Number.isSafeInteger(binding.expiresAt) || binding.expiresAt <= 0)) { + invalid('expires-at must be a positive millisecond timestamp') + } +} + +function checkLength(bytes: Uint8Array, expected: number, what: string): void { + if (!(bytes instanceof Uint8Array) || bytes.length !== expected) { + invalid(`${what} must be ${expected} bytes`) + } +} + +function checkPublicKey(publicKey: Uint8Array): void { + checkLength(publicKey, 33, 'app ephemeral public key') + try { + secp256k1.Point.fromBytes(publicKey) + } catch { + invalid('app ephemeral public key is not a compressed secp256k1 point') + } +} + +export function encodeAppConnectRequest(request: AppConnectRequest): Uint8Array { + validateAppConnectRequest(request) + + const out: number[] = [APP_CONNECT_REQUEST_VERSION, ...request.appEphemeralPubKey, ...request.appId] + const label = encoder.encode(request.label) + out.push(label.length, ...label) + + const tlv = (type: number, value: Uint8Array) => { + out.push(type, value.length, ...value) + } + if (request.identityHint) tlv(AppConnectTlv.IDENTITY_HINT, request.identityHint) + for (const binding of request.authBindings) tlv(AppConnectTlv.AUTH_BINDING, encodeAuthBinding(binding)) + if (request.connectionId) tlv(AppConnectTlv.CONNECTION_ID, request.connectionId) + for (const binding of request.encBindings) { + tlv(AppConnectTlv.ENC_BINDING, Uint8Array.of(...binding.contractId, binding.purpose)) + } + if (request.mode === 'renew') tlv(AppConnectTlv.MODE, Uint8Array.of(1)) + tlv(AppConnectTlv.CREATED_AT, u64(BigInt(request.createdAt))) + + return Uint8Array.from(out) +} + +function encodeAuthBinding(binding: AppConnectAuthBinding): Uint8Array { + const name = binding.documentTypeName === undefined ? [] : [...encoder.encode(binding.documentTypeName)] + return Uint8Array.from([ + BINDING_KIND_TAGS[binding.kind], + binding.securityLevel, + ...binding.id, + ...u64(binding.totalBudget ?? 0n), + ...u64(BigInt(binding.expiresAt ?? 0)), + ...(name.length > 0 ? [name.length, ...name] : []), + ]) +} + +function u64(value: bigint): Uint8Array { + const bytes = new Uint8Array(8) + new DataView(bytes.buffer).setBigUint64(0, value) + return bytes +} + +function readU64(bytes: Uint8Array, offset: number): bigint { + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(offset) +} + +function readMs(bytes: Uint8Array, offset: number, what: string): number | undefined { + const value = readU64(bytes, offset) + if (value === 0n) return undefined + if (value > BigInt(Number.MAX_SAFE_INTEGER)) invalid(`${what} is out of range`) + return Number(value) +} + +export function decodeAppConnectRequest(bytes: Uint8Array): AppConnectRequest { + if (bytes.length < 1) invalid('empty request') + if (bytes[0] !== APP_CONNECT_REQUEST_VERSION) { + throw new AppConnectRequestError('unsupported', `unsupported request version ${bytes[0]}`) + } + if (bytes.length < 1 + 33 + 32 + 1) invalid('request is truncated') + + let offset = 1 + const appEphemeralPubKey = bytes.slice(offset, offset + 33) + offset += 33 + const appId = bytes.slice(offset, offset + 32) + offset += 32 + const labelLength = bytes[offset++] ?? invalid('request is truncated') + if (labelLength > APP_CONNECT_MAX_LABEL_BYTES) invalid('label is too long') + if (offset + labelLength > bytes.length) invalid('request is truncated') + let label: string + try { + label = strictDecoder.decode(bytes.subarray(offset, offset + labelLength)) + } catch { + invalid('label is not valid UTF-8') + } + offset += labelLength + + const request: AppConnectRequest = { + appEphemeralPubKey, + appId, + label, + authBindings: [], + encBindings: [], + createdAt: 0, + } + let previousType = 0 + let sawCreatedAt = false + + while (offset < bytes.length) { + if (offset + 2 > bytes.length) invalid('TLV header is truncated') + const type = bytes[offset] + const length = bytes[offset + 1] + if (type === undefined || length === undefined) invalid('TLV header is truncated') + offset += 2 + if (offset + length > bytes.length) invalid(`TLV 0x${hex2(type)} is truncated`) + const value = bytes.subarray(offset, offset + length) + offset += length + + // The repeatable known types, and any unknown optional type (a future one may repeat). + const repeatable = type === AppConnectTlv.AUTH_BINDING || type === AppConnectTlv.ENC_BINDING + || (type % 2 === 1 && !KNOWN_TLV_TYPES.has(type)) + if (type < previousType || (type === previousType && !repeatable)) { + invalid(`TLV 0x${hex2(type)} is out of order or repeated`) + } + previousType = type + + const fixed = FIXED_VALUE_BYTES[type] + if (fixed !== undefined && length !== fixed) invalid(`TLV 0x${hex2(type)} must be ${fixed} bytes`) + + switch (type) { + case AppConnectTlv.IDENTITY_HINT: + request.identityHint = value.slice() + break + case AppConnectTlv.AUTH_BINDING: + if (request.authBindings.length === APP_CONNECT_MAX_AUTH_BINDINGS) invalid('too many auth bindings') + request.authBindings.push(decodeAuthBinding(value)) + break + case AppConnectTlv.CONNECTION_ID: + request.connectionId = value.slice() + break + case AppConnectTlv.ENC_BINDING: + if (request.encBindings.length === APP_CONNECT_MAX_ENC_BINDINGS) invalid('too many encryption bindings') + request.encBindings.push({ contractId: value.slice(0, 32), purpose: value[32] ?? invalid('encryption binding is truncated') }) + break + case AppConnectTlv.MODE: + if (value[0] !== 1) invalid(`unknown mode ${value[0]}`) + request.mode = 'renew' + break + case AppConnectTlv.CREATED_AT: + request.createdAt = readMs(value, 0, 'created-at') ?? invalid('created-at is zero') + sawCreatedAt = true + break + default: + if (type % 2 === 0) { + throw new AppConnectRequestError('unsupported', `unknown mandatory TLV 0x${hex2(type)}`) + } + } + } + + if (!sawCreatedAt) invalid('request has no created-at') + validateAppConnectRequest(request) + return request +} + +function decodeAuthBinding(value: Uint8Array): AppConnectAuthBinding { + if (value.length < AUTH_BINDING_FIXED_BYTES) invalid('auth binding is truncated') + const tag = value[0] + const securityLevel = value[1] + if (tag === undefined || securityLevel === undefined) invalid('auth binding is truncated') + const kind = (Object.keys(BINDING_KIND_TAGS) as AppConnectBindingKind[]).find((k) => BINDING_KIND_TAGS[k] === tag) + if (kind === undefined) { + throw new AppConnectRequestError('unsupported', `unknown auth binding kind ${tag}`) + } + + const binding: AppConnectAuthBinding = { + kind, + securityLevel, + id: value.slice(2, 34), + } + const budget = readU64(value, 34) + if (budget > 0n) binding.totalBudget = budget + const expiresAt = readMs(value, 42, 'expires-at') + if (expiresAt !== undefined) binding.expiresAt = expiresAt + + const rest = value.subarray(AUTH_BINDING_FIXED_BYTES) + if (kind === 'documentType') { + const nameLength = rest[0] + if (nameLength === undefined || nameLength + 1 !== rest.length) invalid('document type name length does not match') + try { + binding.documentTypeName = strictDecoder.decode(rest.subarray(1)) + } catch { + invalid('document type name is not valid UTF-8') + } + } else if (rest.length !== 0) { + invalid(`a ${kind} binding carries trailing bytes`) + } + return binding +} + +function hex2(byte: number): string { + return byte.toString(16).padStart(2, '0') +} + +/** `cb` must be an absolute https URL without credentials. */ +function checkCallbackUrl(callbackUrl: string): void { + if (callbackUrl.length > APP_CONNECT_MAX_CALLBACK_LENGTH) invalid('callback URL is too long') + let url: URL + try { + url = new URL(callbackUrl) + } catch { + invalid('callback URL is not a URL') + } + if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') { + invalid('callback URL must be https without credentials') + } +} + +export function buildAppConnectUri( + request: AppConnectRequest, + network: AppConnectNetworkName, + callbackUrl?: string, +): string { + const body = encodeBase58(encodeAppConnectRequest(request)) + let uri = `dash-key:${body}?n=${APP_CONNECT_NETWORK_IDS[network]}&v=${APP_CONNECT_REQUEST_VERSION}` + if (callbackUrl !== undefined) { + checkCallbackUrl(callbackUrl) + uri += `&cb=${encodeURIComponent(callbackUrl)}` + } + return uri +} + +/** + * Parses a `dash-key:` v2 URI. Throws {@link AppConnectRequestError}; a v1 URI + * is `unsupported` here (it belongs to the legacy key exchange). + */ +export function parseAppConnectUri(uri: string): ParsedAppConnectUri { + if (!uri.startsWith('dash-key:')) invalid('not a dash-key URI') + const rest = uri.slice('dash-key:'.length) + const queryStart = rest.indexOf('?') + if (queryStart === -1) invalid('URI has no query') + + const params = new URLSearchParams(rest.slice(queryStart + 1)) + for (const name of ['n', 'v', 'cb']) { + if (params.getAll(name).length > 1) invalid(`query parameter ${name} is repeated`) + } + const version = params.get('v') + if (version !== String(APP_CONNECT_REQUEST_VERSION)) { + throw new AppConnectRequestError('unsupported', `unsupported URI version ${version ?? '(none)'}`) + } + const networkId = params.get('n') + const network = (Object.keys(APP_CONNECT_NETWORK_IDS) as AppConnectNetworkName[]) + .find((name) => APP_CONNECT_NETWORK_IDS[name] === networkId) + if (network === undefined) invalid(`unknown network ${networkId ?? '(none)'}`) + + let requestBytes: Uint8Array + try { + requestBytes = decodeBase58(rest.slice(0, queryStart)) + } catch { + invalid('request is not base58') + } + + const callbackUrl = params.get('cb') ?? undefined + if (callbackUrl !== undefined) checkCallbackUrl(callbackUrl) + + return { request: decodeAppConnectRequest(requestBytes), requestBytes, network, callbackUrl } +} + +/** + * The wallet's freshness rule: `stale` when created more than 10 minutes + * before `now`, `future` when more than 2 minutes after it. + */ +export function checkAppConnectRequestAge(createdAt: number, now: number): 'stale' | 'future' | null { + if (now - createdAt > APP_CONNECT_MAX_REQUEST_AGE_MS) return 'stale' + if (createdAt - now > APP_CONNECT_MAX_REQUEST_SKEW_MS) return 'future' + return null +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/session.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/session.test.ts new file mode 100644 index 000000000..49ffd3194 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/session.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it } from 'vitest' +import { + buildAppConnectSession, + selectSigningKey, + type AppConnectSessionKey, + type DocumentSigningMember, + type SigningMember, + type SigningRequest, +} from './session' +import { KeyPurpose, KeySecurityLevel, KeyType, type PinnedGroup } from './types' +import type { AppConnectGrant } from './verify' + +const GROUP = 'GroupId1111111111111111111111111111111111111' +const SOCIAL = 'Social11111111111111111111111111111111111111' +const DM = 'Dm1111111111111111111111111111111111111111111' +const BLOG = 'Blog111111111111111111111111111111111111111' +const SHOP = 'Shop111111111111111111111111111111111111111' +const DASHPAY = 'Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7' +const KEY_EXCHANGE = 'KeyExchange111111111111111111111111111111111' +const NOW = 1_800_000_000_000 + +const groups: PinnedGroup[] = [{ + groupId: GROUP, + members: [ + { kind: 'contract', contractId: SOCIAL }, + { kind: 'contract', contractId: DM }, + { kind: 'documentType', contractId: BLOG, documentTypeName: 'post' }, + { kind: 'token', contractId: SHOP, position: 0 }, + ], +}] + +function key(keyId: number, overrides: Partial): AppConnectSessionKey { + return { keyId, securityLevel: KeySecurityLevel.HIGH, keyRef: `ref-${keyId}`, ...overrides } +} + +const groupKey = key(5, { + bounds: { kind: 'contractGroup', groupId: GROUP }, + securityLevel: KeySecurityLevel.CRITICAL, + totalBudget: 50_000_000_000n, + remainingBudget: 40_000_000_000n, + expiresAt: NOW + 30 * 86_400_000, +}) +const profileKey = key(6, { + bounds: { kind: 'documentType', contractId: DASHPAY, documentTypeName: 'profile' }, + totalBudget: 1_000_000_000n, + remainingBudget: 900_000_000n, + expiresAt: NOW + 30 * 86_400_000, +}) +const ring = [groupKey, profileKey] + +const doc = (contractId: string, documentType: string, extra: Partial = {}): DocumentSigningMember => + ({ contractId, documentType, securityLevel: KeySecurityLevel.HIGH, ...extra }) +const token = (contractId: string, tokenPosition: number): SigningMember => ({ contractId, tokenPosition }) +const batch = (...members: SigningMember[]): SigningRequest => ({ transition: 'batch', members }) +const costing = (cost: bigint) => batch(doc(SOCIAL, 'post', { estimatedCost: cost })) + +function chosen(keys: AppConnectSessionKey[], request: SigningRequest, now = NOW): number | string { + const result = selectSigningKey(keys, request, { now, groups }) + return result.ok ? result.key.keyId : result.reason +} + +describe('selectSigningKey', () => { + it('signs Yappr writes with the group key and DashPay profile writes with the profile key', () => { + expect(chosen(ring, batch(doc(SOCIAL, 'post')))).toBe(5) + expect(chosen(ring, batch(doc(DM, 'message'), doc(SOCIAL, 'like')))).toBe(5) + expect(chosen(ring, batch(doc(DASHPAY, 'profile')))).toBe(6) + }) + + it('never routes a write no key covers (no paid 20014)', () => { + expect(chosen(ring, batch(doc(DASHPAY, 'contactRequest')))).toBe('no-covering-key') + expect(chosen(ring, batch(doc(KEY_EXCHANGE, 'loginKey')))).toBe('no-covering-key') + expect(chosen(ring, batch(doc(BLOG, 'comment')))).toBe('no-covering-key') + expect(chosen(ring, batch(doc(BLOG, 'post')))).toBe(5) + }) + + it('only trusts pinned membership for a group key', () => { + const otherGroup = key(9, { bounds: { kind: 'contractGroup', groupId: 'Other1111111111111111111111111111111111111' } }) + expect(chosen([otherGroup], batch(doc(SOCIAL, 'post')))).toBe('no-covering-key') + }) + + it('never uses a bound key for a non-batch transition', () => { + expect(chosen(ring, { transition: 'non-batch', requiredSecurityLevel: KeySecurityLevel.HIGH })).toBe('non-batch') + const rawKey = key(1, { securityLevel: KeySecurityLevel.CRITICAL }) + expect(chosen([...ring, rawKey], { transition: 'non-batch', requiredSecurityLevel: KeySecurityLevel.CRITICAL })).toBe(1) + }) + + it('requires CRITICAL for token operations', () => { + expect(chosen(ring, batch(token(SOCIAL, 0)))).toBe(5) + expect(chosen(ring, batch(token(DM, 0), doc(DM, 'message')))).toBe(5) + const highGroup = { ...groupKey, securityLevel: KeySecurityLevel.HIGH } + expect(chosen([highGroup], batch(token(SOCIAL, 0)))).toBe('no-covering-key') + expect(chosen([highGroup], batch(doc(SOCIAL, 'post')))).toBe(5) + }) + + it('never covers tokens with a document-type key, or a token outside the group', () => { + const socialPostKey = key(7, { bounds: { kind: 'documentType', contractId: SOCIAL, documentTypeName: 'post' }, securityLevel: KeySecurityLevel.CRITICAL }) + expect(chosen([socialPostKey], batch(token(SOCIAL, 0)))).toBe('no-covering-key') + expect(chosen(ring, batch(token(BLOG, 0)))).toBe('no-covering-key') + expect(chosen(ring, batch(token(SHOP, 0)))).toBe(5) + expect(chosen(ring, batch(token(SHOP, 1)))).toBe('no-covering-key') + expect(chosen(ring, batch(doc(SHOP, 'order')))).toBe('no-covering-key') + }) + + it('checks the types a create consumes against the key too', () => { + const postKey = key(10, { bounds: { kind: 'documentType', contractId: SOCIAL, documentTypeName: 'post' } }) + const consuming = doc(SOCIAL, 'post') + expect(chosen([postKey], batch(consuming))).toBe(10) + expect(chosen([postKey], batch({ ...consuming, consumedDocumentTypes: ['draft'] }))).toBe('no-covering-key') + expect(chosen([postKey, groupKey], batch({ ...consuming, consumedDocumentTypes: ['draft'] }))).toBe(5) + expect(chosen(ring, batch({ ...doc(BLOG, 'post'), consumedDocumentTypes: ['draft'] }))).toBe('no-covering-key') + }) + + it('honours a document type that requires CRITICAL', () => { + const request = batch(doc(DASHPAY, 'profile', { securityLevel: KeySecurityLevel.CRITICAL })) + expect(chosen(ring, request)).toBe('no-covering-key') + }) + + it('drops expiring, spent, under-budget and disabled keys', () => { + const post = batch(doc(SOCIAL, 'post')) + expect(chosen([{ ...groupKey, expiresAt: NOW + 4 * 60_000 }], post)).toBe('no-covering-key') + expect(chosen([{ ...groupKey, remainingBudget: 0n }], post)).toBe('no-covering-key') + expect(chosen([{ ...groupKey, remainingBudget: 0n }], costing(0n))).toBe('no-covering-key') + expect(chosen([{ ...groupKey, remainingBudget: 100n }], costing(101n))).toBe('no-covering-key') + expect(chosen([{ ...groupKey, remainingBudget: 101n }], costing(101n))).toBe(5) + expect(chosen([{ ...groupKey, disabled: true }], post)).toBe('no-covering-key') + // A budgeted key with no known remaining budget is skipped, and an equivalent known one used instead. + const unknownBudget = { ...groupKey, keyId: 12, remainingBudget: undefined } + expect(chosen([unknownBudget], costing(101n))).toBe('no-covering-key') + expect(chosen([unknownBudget, groupKey], post)).toBe(5) + // A key with no budget at all is unlimited. + expect(chosen([{ ...groupKey, totalBudget: undefined, remainingBudget: undefined }], costing(10n ** 12n))).toBe(5) + }) + + it('prefers the narrowest key, then the least privileged', () => { + const socialKey = key(8, { bounds: { kind: 'singleContract', contractId: SOCIAL } }) + const postKey = key(10, { bounds: { kind: 'documentType', contractId: SOCIAL, documentTypeName: 'post' } }) + const unbound = key(1, {}) + expect(chosen([unbound, groupKey, socialKey, postKey], batch(doc(SOCIAL, 'post')))).toBe(10) + expect(chosen([unbound, groupKey, socialKey], batch(doc(SOCIAL, 'post')))).toBe(8) + expect(chosen([unbound, groupKey], batch(doc(SOCIAL, 'post')))).toBe(5) + const highGroup = { ...groupKey, keyId: 11, securityLevel: KeySecurityLevel.HIGH } + expect(chosen([groupKey, highGroup], batch(doc(SOCIAL, 'post')))).toBe(11) + expect(chosen([groupKey, highGroup], batch(token(SOCIAL, 0)))).toBe(5) + }) + + it('splits a mixed batch by key, and refuses one that cannot be covered', () => { + const result = selectSigningKey(ring, batch(doc(DASHPAY, 'profile'), doc(SOCIAL, 'yapprProfile'), doc(SOCIAL, 'post')), { now: NOW, groups }) + expect(result.ok).toBe(false) + if (result.ok || result.reason !== 'needs-split') throw new Error('expected a split plan') + expect(result.plan.map((step) => [step.key.keyId, step.members.length])).toEqual([[6, 1], [5, 2]]) + expect(chosen(ring, batch(doc(DASHPAY, 'profile'), doc(KEY_EXCHANGE, 'loginKey')))).toBe('no-covering-key') + }) + + it('checks each split step against its own level and cost, not the whole batch', () => { + // A CRITICAL-only Yappr type plus the HIGH DashPay profile: CRITICAL group key, HIGH profile key. + const mixedLevels = selectSigningKey(ring, batch( + doc(SOCIAL, 'moderatorNote', { securityLevel: KeySecurityLevel.CRITICAL }), + doc(DASHPAY, 'profile'), + ), { now: NOW, groups }) + expect(mixedLevels.ok === false && mixedLevels.reason === 'needs-split' && mixedLevels.plan.map((s) => s.key.keyId)).toEqual([5, 6]) + + // Each key can afford its own step but neither could afford the whole batch. + const tight = [{ ...groupKey, remainingBudget: 100n }, { ...profileKey, remainingBudget: 50n }] + const affordable = selectSigningKey(tight, batch( + doc(SOCIAL, 'post', { estimatedCost: 60n }), + doc(DASHPAY, 'profile', { estimatedCost: 50n }), + ), { now: NOW, groups }) + expect(affordable.ok === false && affordable.reason === 'needs-split' && affordable.plan.map((s) => s.key.keyId)).toEqual([5, 6]) + + // Members regrouped onto one key must fit its budget together. + expect(chosen(tight, batch( + doc(SOCIAL, 'post', { estimatedCost: 60n }), + doc(DASHPAY, 'profile', { estimatedCost: 50n }), + doc(SOCIAL, 'like', { estimatedCost: 60n }), + ))).toBe('no-covering-key') + }) + + it('spills split members onto another covering key once the preferred one is fully allocated', () => { + // Overlapping scopes: a narrower contract key and the group key both cover SOCIAL, 100 each. + const socialKey = key(8, { bounds: { kind: 'singleContract', contractId: SOCIAL }, totalBudget: 100n, remainingBudget: 100n }) + const keys = [socialKey, { ...groupKey, remainingBudget: 100n }] + const result = selectSigningKey(keys, batch( + doc(SOCIAL, 'post', { estimatedCost: 60n }), + doc(SOCIAL, 'like', { estimatedCost: 60n }), + ), { now: NOW, groups }) + expect(result.ok === false && result.reason === 'needs-split' + && result.plan.map((s) => [s.key.keyId, s.members.map((m) => ('documentType' in m ? m.documentType : ''))])) + .toEqual([[8, ['post']], [5, ['like']]]) + }) + + it('refuses an empty batch', () => { + expect(chosen(ring, batch())).toBe('empty') + }) +}) + +describe('buildAppConnectSession', () => { + it('keeps key metadata, stores private keys by reference and wipes them from the grant', () => { + const grant: AppConnectGrant = { + identityId: 'Owner', + authKeys: [{ + role: 'contractGroup', + bindingIndex: 0, + privateKey: new Uint8Array(32).fill(1), + remainingBudget: 10n, + key: { + id: 5, + type: KeyType.ECDSA_HASH160, + purpose: KeyPurpose.AUTHENTICATION, + securityLevel: KeySecurityLevel.CRITICAL, + data: new Uint8Array(20), + bounds: { kind: 'contractGroup', groupId: GROUP }, + totalBudget: 20n, + expiresAt: NOW, + }, + }], + encryptionKeys: [{ + role: 'encryption', + bindingIndex: 0, + privateKey: new Uint8Array(32).fill(2), + key: { + id: 7, + type: KeyType.ECDSA_SECP256K1, + purpose: KeyPurpose.ENCRYPTION, + securityLevel: KeySecurityLevel.MEDIUM, + data: new Uint8Array(33), + bounds: { kind: 'singleContract', contractId: 'Anchor' }, + }, + }], + } + const stored: Array<[number, number]> = [] + const session = buildAppConnectSession(grant, { + network: 'devnet', + appId: 'Anchor', + groupId: GROUP, + connectionId: '00'.repeat(16), + grantedAt: NOW, + keyRef: (privateKey, keyId) => { + stored.push([keyId, privateKey[0]!]) + return `k${keyId}` + }, + }) + expect(stored).toEqual([[5, 1], [7, 2]]) + expect(session.authKeys).toEqual([{ + keyId: 5, + bounds: { kind: 'contractGroup', groupId: GROUP }, + securityLevel: KeySecurityLevel.CRITICAL, + totalBudget: 20n, + remainingBudget: 10n, + expiresAt: NOW, + keyRef: 'k5', + }]) + expect(session.encKeys).toEqual([{ keyId: 7, contractId: 'Anchor', purpose: KeyPurpose.ENCRYPTION, keyRef: 'k7' }]) + expect(JSON.stringify(session, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))).not.toContain('privateKey') + expect(grant.authKeys[0]!.privateKey.every((byte) => byte === 0)).toBe(true) + expect(grant.encryptionKeys[0]!.privateKey.every((byte) => byte === 0)).toBe(true) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/session.ts b/forge-web/lib/vendor/platform-auth/app-connect/session.ts new file mode 100644 index 000000000..64a2b7403 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/session.ts @@ -0,0 +1,320 @@ +import { clearSensitiveBytes, type AppConnectNetworkName } from './primitives' +import type { AppConnectGrant } from './verify' +import { KeySecurityLevel, type AppConnectGroupMember, type AppConnectKeyBounds, type PinnedGroup } from './types' + +/** + * An App Connect session is a key ring, not one key: a group key, a DashPay + * profile key and an encryption key, each with its own bounds and limits. + * `selectSigningKey` picks the key for a write before it is built, so a write + * no key covers never reaches the network (where a bound key outside its + * bounds is a paid failure, 20014). + */ + +export const APP_CONNECT_SESSION_VERSION = 1 +/** Keys expiring within this window are not used for new writes. */ +export const APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS = 5 * 60_000 + +export interface AppConnectSessionKey { + keyId: number + /** Absent only for a raw-key session's unbound key. */ + bounds?: AppConnectKeyBounds + securityLevel: number + totalBudget?: bigint + /** Last known remaining budget; refreshed after writes and on 40218. A budgeted key without one is not used. */ + remainingBudget?: bigint + expiresAt?: number + disabled?: boolean + /** Opaque handle into the platform's key store; the private key never sits in the session. */ + keyRef: string +} + +export interface AppConnectSession { + v: typeof APP_CONNECT_SESSION_VERSION + network: AppConnectNetworkName + identityId: string + appId: string + groupId: string + /** Hex, 16 bytes, per device and network; survives logout so re-logins supersede. */ + connectionId: string + grantedAt: number + authKeys: AppConnectSessionKey[] + /** ENCRYPTION and DECRYPTION keys, one per granted encryption binding. */ + encKeys: AppConnectSessionEncKey[] +} + +export interface AppConnectSessionEncKey { + keyId: number + contractId: string + /** ENCRYPTION or DECRYPTION. */ + purpose: number + keyRef: string +} + +export interface BuildAppConnectSessionInput { + network: AppConnectNetworkName + appId: string + groupId: string + connectionId: string + grantedAt: number + /** Stores a granted private key and returns its handle. */ + keyRef: (privateKey: Uint8Array, keyId: number) => string +} + +/** + * Turns a verified grant into a session: every private key goes to `keyRef` + * and is then wiped from the grant, so the grant is spent afterwards. + */ +export function buildAppConnectSession(grant: AppConnectGrant, input: BuildAppConnectSessionInput): AppConnectSession { + try { + const authKeys = grant.authKeys.map((granted): AppConnectSessionKey => ({ + keyId: granted.key.id, + bounds: granted.key.bounds, + securityLevel: granted.key.securityLevel, + totalBudget: granted.key.totalBudget, + remainingBudget: granted.remainingBudget, + expiresAt: granted.key.expiresAt, + keyRef: input.keyRef(granted.privateKey, granted.key.id), + })) + const encKeys = grant.encryptionKeys.map((granted): AppConnectSessionEncKey => { + // The verifier only accepts encryption keys bound to a single contract. + const bounds = granted.key.bounds + if (bounds?.kind !== 'singleContract') throw new Error('encryption key is not bound to a contract') + return { + keyId: granted.key.id, + contractId: bounds.contractId, + purpose: granted.key.purpose, + keyRef: input.keyRef(granted.privateKey, granted.key.id), + } + }) + return { + v: APP_CONNECT_SESSION_VERSION, + network: input.network, + identityId: grant.identityId, + appId: input.appId, + groupId: input.groupId, + connectionId: input.connectionId, + grantedAt: input.grantedAt, + authKeys, + encKeys, + } + } finally { + for (const granted of [...grant.authKeys, ...grant.encryptionKeys]) clearSensitiveBytes(granted.privateKey) + } +} + +/** + * One member of a batch: a document operation or a token operation. Each + * carries its own requirements, so a batch that has to be split is checked + * step by step rather than against the whole batch's. + */ +export type SigningMember = DocumentSigningMember | TokenSigningMember + +export interface DocumentSigningMember { + contractId: string + documentType: string + /** + * The type's `securityLevelRequirement` (HIGH unless the type says + * otherwise). Required, because guessing low costs a paid 20004. + */ + securityLevel: number + /** Types this create consumes (`consume`); the key's bounds must cover them too. */ + consumedDocumentTypes?: string[] + /** Expected credit cost of this member. */ + estimatedCost?: bigint +} + +/** Platform requires CRITICAL for any batch with a token transition. */ +export interface TokenSigningMember { + contractId: string + tokenPosition: number + estimatedCost?: bigint +} + +export type SigningRequest = + | { transition: 'batch'; members: SigningMember[] } + /** Bound keys sign batches only (20013 otherwise). */ + | { transition: 'non-batch'; requiredSecurityLevel: number; estimatedCost?: bigint } + +export interface SelectSigningKeyContext { + now: number + /** Only pins that passed `checkAppConnectGroupTrust`: the selector trusts them as the group's members. */ + groups: PinnedGroup[] + expiryMarginMs?: number +} + +export interface SigningPlanStep { + key: AppConnectSessionKey + members: SigningMember[] +} + +export type SigningKeySelection = + | { ok: true; key: AppConnectSessionKey } + /** + * `non-batch`: only an unbound key could sign it; hand off to the wallet. + * `needs-split`: no one key covers every member, but `plan` signs them in + * separate batches. Not atomic, and members are regrouped by key, so the + * order across steps can differ from the request's; the caller decides + * whether that is fine. + * `no-covering-key`: nothing usable covers some member; renew or hand off. + */ + | { ok: false; reason: 'empty' | 'non-batch' | 'no-covering-key' } + | { ok: false; reason: 'needs-split'; plan: SigningPlanStep[] } + +function isToken(member: SigningMember): member is TokenSigningMember { + return 'tokenPosition' in member +} + +/** What signing a set of members needs: the strictest level and the summed cost. */ +interface Requirement { + level: number + cost: bigint +} + +function requirementOf(members: SigningMember[]): Requirement { + return { + level: Math.min(...members.map((m) => (isToken(m) ? KeySecurityLevel.CRITICAL : m.securityLevel))), + cost: members.reduce((sum, m) => sum + (m.estimatedCost ?? 0n), 0n), + } +} + +/** Whether `bounds` (or no bounds: an unbound key) admits `member`, including every type it consumes. */ +function covers(bounds: AppConnectKeyBounds | undefined, member: SigningMember, groups: PinnedGroup[]): boolean { + if (isToken(member) || !member.consumedDocumentTypes?.length) return coversOne(bounds, member, groups) + return [member.documentType, ...member.consumedDocumentTypes] + .every((documentType) => coversOne(bounds, { contractId: member.contractId, documentType }, groups)) +} + +function coversOne( + bounds: AppConnectKeyBounds | undefined, + member: Pick | TokenSigningMember, + groups: PinnedGroup[], +): boolean { + if (!bounds) return true + switch (bounds.kind) { + case 'singleContract': + return member.contractId === bounds.contractId + case 'documentType': + // Token operations are contract-wide and never covered by a document-type bound. + return !('tokenPosition' in member) && member.contractId === bounds.contractId && member.documentType === bounds.documentTypeName + case 'contractGroup': { + const group = groups.find((g) => g.groupId === bounds.groupId) + return group !== undefined && group.members.some((m) => groupMemberCovers(m, member)) + } + } +} + +function groupMemberCovers( + groupMember: AppConnectGroupMember, + member: Pick | TokenSigningMember, +): boolean { + if (groupMember.contractId !== member.contractId) return false + const token = 'tokenPosition' in member + switch (groupMember.kind) { + case 'contract': + return true + case 'documentType': + return !token && member.documentType === groupMember.documentTypeName + case 'token': + return token && member.tokenPosition === groupMember.position + } +} + +/** Narrowest first: a documentType key before a contract key before a group key before an unbound key. */ +function scopeRank(key: AppConnectSessionKey): number { + switch (key.bounds?.kind) { + case 'documentType': + return 0 + case 'singleContract': + return 1 + case 'contractGroup': + return 2 + default: + return 3 + } +} + +function usable(key: AppConnectSessionKey, requirement: Requirement, ctx: SelectSigningKeyContext): boolean { + if (key.disabled) return false + if (key.securityLevel === KeySecurityLevel.MASTER) return false + const margin = ctx.expiryMarginMs ?? APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS + if (key.expiresAt !== undefined && key.expiresAt - ctx.now <= margin) return false + // A budgeted key whose remaining budget is unknown is not unlimited: skip it until refreshed. + if (key.totalBudget !== undefined && key.remainingBudget === undefined) return false + if (key.remainingBudget !== undefined + && (key.remainingBudget <= 0n || key.remainingBudget < requirement.cost)) return false + // Lower is more privileged, so the key's level must be numerically at most the requirement. + return key.securityLevel <= requirement.level +} + +/** Narrowest scope, then least privilege, then the most budget left, then the newest key. */ +function compareKeys(a: AppConnectSessionKey, b: AppConnectSessionKey): number { + return scopeRank(a) - scopeRank(b) + || b.securityLevel - a.securityLevel + || compareBudget(b.remainingBudget, a.remainingBudget) + || b.keyId - a.keyId +} + +function compareBudget(a: bigint | undefined, b: bigint | undefined): number { + // No budget means unlimited. + if (a === b) return 0 + if (a === undefined) return 1 + if (b === undefined) return -1 + return a > b ? 1 : -1 +} + +/** `allocated`: cost already assigned to each key by earlier steps of a split plan. */ +function bestKey( + keys: AppConnectSessionKey[], + members: SigningMember[], + requirement: Requirement, + ctx: SelectSigningKeyContext, + allocated: ReadonlyMap = new Map(), +): AppConnectSessionKey | undefined { + return keys + .filter((key) => usable(key, { ...requirement, cost: requirement.cost + (allocated.get(key.keyId) ?? 0n) }, ctx) + && members.every((member) => covers(key.bounds, member, ctx.groups))) + .sort(compareKeys)[0] +} + +/** + * Picks the key that signs `request`, or says why none can. Pure: budgets and + * expiries come from the session, membership from the pinned groups. + */ +export function selectSigningKey( + keys: AppConnectSessionKey[], + request: SigningRequest, + ctx: SelectSigningKeyContext, +): SigningKeySelection { + if (request.transition === 'non-batch') { + // Only an unbound authentication key (a raw-key session) can sign these. + // Session keys carry no purpose, so TRANSFER-purpose transitions are out of scope. + const unbound = keys.filter((key) => !key.bounds) + const requirement = { level: request.requiredSecurityLevel, cost: request.estimatedCost ?? 0n } + const key = bestKey(unbound, [], requirement, ctx) + return key ? { ok: true, key } : { ok: false, reason: 'non-batch' } + } + const { members } = request + if (members.length === 0) return { ok: false, reason: 'empty' } + + const key = bestKey(keys, members, requirementOf(members), ctx) + if (key) return { ok: true, key } + + // Mixed batch (for example a DashPay profile plus a Yappr profile): give + // each member, in order, the most preferred key that covers it at its own + // level and can still afford it on top of what earlier members took from + // that key; group the members by key in first-use order. This is greedy, so + // an exotic allocation can be missed; that ends in `no-covering-key` (a + // wallet handoff), never in an unaffordable plan. + const plan: SigningPlanStep[] = [] + const allocated = new Map() + for (const member of members) { + const requirement = requirementOf([member]) + const memberKey = bestKey(keys, [member], requirement, ctx, allocated) + if (!memberKey) return { ok: false, reason: 'no-covering-key' } + allocated.set(memberKey.keyId, (allocated.get(memberKey.keyId) ?? 0n) + requirement.cost) + const step = plan.find((s) => s.key.keyId === memberKey.keyId) + if (step) step.members.push(member) + else plan.push({ key: memberKey, members: [member] }) + } + return { ok: false, reason: 'needs-split', plan } +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/test-helpers.ts b/forge-web/lib/vendor/platform-auth/app-connect/test-helpers.ts new file mode 100644 index 000000000..a4f3e00cb --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/test-helpers.ts @@ -0,0 +1,125 @@ +import * as secp256k1 from '@noble/secp256k1' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex } from '@noble/hashes/utils.js' +import { decodeBase58, deriveSharedSecret, encodeBase58, hash160 } from './primitives' +import { APP_CONNECT_HKDF_INFO, appConnectAad, sealAppConnectPayload } from './crypto' +import { appConnectRequestHash, buildAppConnectUri, encodeAppConnectRequest, type AppConnectRequest } from './request' +import { KeyPurpose, KeySecurityLevel } from './types' + +/** Deterministic 32 bytes for fixtures: sha256("dash app-connect v2 vector/" + label). */ +export function seed(label: string): Uint8Array { + return sha256(new TextEncoder().encode(`dash app-connect v2 vector/${label}`)) +} + +export const DASHPAY_CONTRACT_ID = 'Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7' +export const VECTOR_CREATED_AT = 1791676800000 // 2026-10-11T00:00:00Z +export const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000 + +export const vectorKeys = { + appEphemeralPrivateKey: seed('app ephemeral'), + walletEphemeralPrivateKey: seed('wallet ephemeral'), + appId: seed('app id'), + groupId: seed('group id'), + ownerId: seed('owner'), + connectionId: seed('connection id').slice(0, 16), + nonce: seed('nonce').slice(0, 12), + groupKey: seed('slot group key'), + profileKey: seed('slot dashpay profile key'), + encryptionKey: seed('slot encryption key'), +} + +/** Yappr's request: group key CRITICAL 0.5 DASH / 90 d, DashPay profile HIGH 1e9 / 90 d, encryption on the anchor. */ +export function yapprVectorRequest(): AppConnectRequest { + const expiresAt = VECTOR_CREATED_AT + NINETY_DAYS_MS + return { + appEphemeralPubKey: secp256k1.getPublicKey(vectorKeys.appEphemeralPrivateKey, true), + appId: vectorKeys.appId, + label: 'Yappr', + authBindings: [ + { + kind: 'contractGroup', + id: vectorKeys.groupId, + securityLevel: KeySecurityLevel.CRITICAL, + totalBudget: 50_000_000_000n, + expiresAt, + }, + { + kind: 'documentType', + id: decodeBase58(DASHPAY_CONTRACT_ID), + documentTypeName: 'profile', + securityLevel: KeySecurityLevel.HIGH, + totalBudget: 1_000_000_000n, + expiresAt, + }, + ], + encBindings: [{ contractId: vectorKeys.appId, purpose: KeyPurpose.ENCRYPTION }], + createdAt: VECTOR_CREATED_AT, + connectionId: vectorKeys.connectionId, + } +} + +/** A renewal for a known identity: adds IDENTITY_HINT and MODE = renew, group binding only. */ +export function renewVectorRequest(): AppConnectRequest { + const base = yapprVectorRequest() + return { + ...base, + authBindings: [base.authBindings[0]!], + encBindings: [], + identityHint: vectorKeys.ownerId, + mode: 'renew', + } +} + +export async function buildAppConnectVectors() { + const request = yapprVectorRequest() + const requestHash = appConnectRequestHash(request) + const callbackUrl = `https://yap.pr/connect?r=${bytesToHex(requestHash)}` + const slots = [vectorKeys.groupKey, vectorKeys.profileKey, vectorKeys.encryptionKey] + const sealed = await sealAppConnectPayload({ + appEphemeralPubKey: request.appEphemeralPubKey, + ownerId: vectorKeys.ownerId, + slots, + walletEphemeralPrivateKey: vectorKeys.walletEphemeralPrivateKey, + nonce: vectorKeys.nonce, + }) + const renew = renewVectorRequest() + + return { + inputs: { + appEphemeralPrivateKey: bytesToHex(vectorKeys.appEphemeralPrivateKey), + appId: encodeBase58(vectorKeys.appId), + groupId: encodeBase58(vectorKeys.groupId), + dashpayContractId: DASHPAY_CONTRACT_ID, + ownerId: encodeBase58(vectorKeys.ownerId), + connectionId: bytesToHex(vectorKeys.connectionId), + createdAt: VECTOR_CREATED_AT, + expiresAt: VECTOR_CREATED_AT + NINETY_DAYS_MS, + walletEphemeralPrivateKey: bytesToHex(vectorKeys.walletEphemeralPrivateKey), + nonce: bytesToHex(vectorKeys.nonce), + slotPrivateKeys: slots.map(bytesToHex), + }, + request: { + appEphemeralPubKey: bytesToHex(request.appEphemeralPubKey), + bytes: bytesToHex(encodeAppConnectRequest(request)), + uri: buildAppConnectUri(request, 'devnet', callbackUrl), + appEphemeralPubKeyHash: bytesToHex(requestHash), + }, + response: { + walletEphemeralPubKey: bytesToHex(sealed.walletEphemeralPubKey), + sessionKey: bytesToHex(deriveSharedSecret( + vectorKeys.walletEphemeralPrivateKey, + request.appEphemeralPubKey, + new TextEncoder().encode(APP_CONNECT_HKDF_INFO), + )), + aad: bytesToHex(appConnectAad(request.appEphemeralPubKey, vectorKeys.ownerId)), + plaintext: slots.map(bytesToHex).join(''), + encryptedPayload: bytesToHex(sealed.encryptedPayload), + slotPublicKeys: slots.map((slot) => bytesToHex(secp256k1.getPublicKey(slot, true))), + slotPublicKeyHashes: slots.map((slot) => bytesToHex(hash160(secp256k1.getPublicKey(slot, true)))), + }, + renewRequest: { + bytes: bytesToHex(encodeAppConnectRequest(renew)), + uri: buildAppConnectUri(renew, 'testnet'), + }, + } +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/types.ts b/forge-web/lib/vendor/platform-auth/app-connect/types.ts new file mode 100644 index 000000000..04e78ca91 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/types.ts @@ -0,0 +1,90 @@ +/** + * Platform identity-key vocabulary shared by the App Connect modules. Numbers + * match Platform's encodings (`Purpose`, `SecurityLevel`, `KeyType`), so keys + * read through the SDK can be passed through without translation. + */ + +export const KeyPurpose = { + AUTHENTICATION: 0, + ENCRYPTION: 1, + DECRYPTION: 2, + TRANSFER: 3, +} as const + +export const KeySecurityLevel = { + MASTER: 0, + CRITICAL: 1, + HIGH: 2, + MEDIUM: 3, +} as const + +export const KeyType = { + ECDSA_SECP256K1: 0, + ECDSA_HASH160: 2, +} as const + +/** `contractBounds` of an identity key; ids are base58. */ +export type AppConnectKeyBounds = + | { kind: 'singleContract'; contractId: string } + | { kind: 'documentType'; contractId: string; documentTypeName: string } + | { kind: 'contractGroup'; groupId: string } + +/** An identity public key as the verifier needs it (V0 or V1). */ +export interface AppConnectIdentityKey { + id: number + type: number + purpose: number + securityLevel: number + /** 33-byte compressed point (ECDSA_SECP256K1) or 20-byte hash160 (ECDSA_HASH160). */ + data: Uint8Array + disabledAt?: number + bounds?: AppConnectKeyBounds + /** V1 limit: lifetime credit budget. */ + totalBudget?: bigint + /** V1 limit: block time (ms) from which the key can no longer sign. */ + expiresAt?: number +} + +/** One member of a contract group; ids are base58. */ +export type AppConnectGroupMember = + | { kind: 'contract'; contractId: string } + | { kind: 'documentType'; contractId: string; documentTypeName: string } + | { kind: 'token'; contractId: string; position: number } + +/** A group whose members are pinned in the app's config (and checked against chain before use). */ +export interface PinnedGroup { + groupId: string + members: AppConnectGroupMember[] +} + +export interface AppConnectGroupInfo { + ownerId: string + adminIds: string[] + members: AppConnectGroupMember[] +} + +/** + * Reads the app needs to verify a grant. Every read should be proved, and + * `getIdentityFresh` must bypass any identity cache: a key added moments ago is + * exactly what is being checked. + */ +export interface AppConnectIdentityPort { + getIdentityFresh(identityId: string): Promise<{ id: string; publicKeys: AppConnectIdentityKey[] } | null> + /** Remaining credits per key id; a key without a budget is absent or undefined. */ + remainingBudgets(identityId: string, keyIds: number[]): Promise> + /** The keys Platform currently resolves for `contractId` and `purpose` (`identities.contractKeys`). */ + contractKeys(identityId: string, contractId: string, purpose: number): Promise + /** The whole group (the port pages the members), or null when it does not exist. */ + groupInfo(groupId: string): Promise +} + +export function boundsEqual(a: AppConnectKeyBounds, b: AppConnectKeyBounds): boolean { + switch (a.kind) { + case 'singleContract': + return b.kind === 'singleContract' && a.contractId === b.contractId + case 'documentType': + return b.kind === 'documentType' && a.contractId === b.contractId && a.documentTypeName === b.documentTypeName + case 'contractGroup': + return b.kind === 'contractGroup' && a.groupId === b.groupId + } +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/vectors.json b/forge-web/lib/vendor/platform-auth/app-connect/vectors.json new file mode 100644 index 000000000..aaaa950d6 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/vectors.json @@ -0,0 +1,46 @@ +{ + "inputs": { + "appEphemeralPrivateKey": "83adc3b5a48a1f3938969be4e3d674210d09aec8a2c2cb2b43b22972afca8682", + "appId": "Hj6B9qRVHcVB97LZGEQvKm7zFsCP85cuSkEAssc1XWL7", + "groupId": "CsPWxFwNvLPjACBCQBSXJLHAimU44DDFimzA2Jbxm9GK", + "dashpayContractId": "Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7", + "ownerId": "AsDve9GcVemmG7hRFkVMpX2UVQupcoFo7EAg33m8PcTA", + "connectionId": "a69b1b4f666681453dec3734667a5ab2", + "createdAt": 1791676800000, + "expiresAt": 1799452800000, + "walletEphemeralPrivateKey": "d1772740bcf476137df337bbe42122e82da08e11b632d6c3ff0d7281576e4127", + "nonce": "22bb26ec9e0d316c4fb36be2", + "slotPrivateKeys": [ + "7df2f40f15e6079e514d7e5cb9cb1861b89986906ed820e158c3144272df9586", + "3a992d9275d082af7540d1333a134ff0572c2bb79567437daa88dee55af1571f", + "b37bb0ae8d6bbf01b38e843470570d5158d1939762a88673dd6cdf71bc144753" + ] + }, + "request": { + "appEphemeralPubKey": "03e83cb927e85f96ae50a95ca3be21cc7a3755139a941b15d99b01af4fecf0d270", + "bytes": "0203e83cb927e85f96ae50a95ca3be21cc7a3755139a941b15d99b01af4fecf0d270f8833c7a2d58ab816c24ae915fe2aa94676588b467ba1e9f2b24c1a3df7fdb7805596170707202320201b0590e59269c6885acf71d27ddfce85187e2cc9736c42e958127cd35be6d38e80000000ba43b7400000001a2f7beb400023a0102a2a1b4ac6fef22ea2a1a68e8123644b357875f6b412c18109281c146e7b271bc000000003b9aca00000001a2f7beb4000770726f66696c650310a69b1b4f666681453dec3734667a5ab20421f8833c7a2d58ab816c24ae915fe2aa94676588b467ba1e9f2b24c1a3df7fdb78010608000001a128425c00", + "uri": "dash-key:2fAANHHASdojyjV9Sqa2wf2nwZE8kLLqmeHpZWa8sBfaGsddVqyMG2ZVte7xJkTKsXvmFYbXzXbNnMo7bJQBxNcf79N8YWi7pLKyb39Rqv6b1KUmxw9UeJGYz2CV9hFGNUQtcyMYVq2Fg6vAxtxpYays61H8gLMcWqaG8TfgGA3H7setGAYiBsM5YmdZgeuCdGAHSwfNfav5cfFjXNDkPWv37UNSgFxj6o58jfXc3kCLKqLJtc5ZPjm1thEGYxK8HVYBi8fRQeEVy76n27DXGrVTyHz94CfJRuMnH76xGYbMgeuvurxjJMLrQgWUu53cjocYyzzNWdJrgs2D5?n=d&v=2&cb=https%3A%2F%2Fyap.pr%2Fconnect%3Fr%3Dd77dc0da9df83a47755a15c42c5d9db9d7a7fd62", + "appEphemeralPubKeyHash": "d77dc0da9df83a47755a15c42c5d9db9d7a7fd62" + }, + "response": { + "walletEphemeralPubKey": "02ee49ae562aa74ea28f95094da6800db9244b1addc1499439ffc7382cd7862d5a", + "sessionKey": "b9837f16975f02d7c06df91441bbf3dad51ca7d65016178f34084247dd1b703f", + "aad": "646173683a6170702d636f6e6e6563743a7632d77dc0da9df83a47755a15c42c5d9db9d7a7fd629296d642338cb3bfceeb554285462719e15f004d0579ce53ea77fb6d86cd9ab9", + "plaintext": "7df2f40f15e6079e514d7e5cb9cb1861b89986906ed820e158c3144272df95863a992d9275d082af7540d1333a134ff0572c2bb79567437daa88dee55af1571fb37bb0ae8d6bbf01b38e843470570d5158d1939762a88673dd6cdf71bc144753", + "encryptedPayload": "22bb26ec9e0d316c4fb36be20e3f2a358cce3609d09094351ce5e78f08e5253b0f9258616374753411c97faecb1fbde336c01d7f08380095a0a7ffe3fe207f80e92a7adb7bd8731dffe3b96a6b2c363aa1302c4e82d60f75419aa1f6f3ac5522453f2b761495fb3b7816ea8bfe66a210e14fdad8b7f7c15ffb3ef39b", + "slotPublicKeys": [ + "03ad37affe6d1018d4c4f24429a749e64be98650a76935f0094d2b74577b3e64be", + "029029b4134dc7b49071545ddd3b5743a41ea831c647defe988fa2663c57b6ef9e", + "022dfa00c086d19058f0b80d7d6eb4caa4a65e8f3f50dbabcf675dbc165096b7f5" + ], + "slotPublicKeyHashes": [ + "6a584cee34f9db5658af56dbb4ae4afd9da41f0e", + "ccb3641d29579908ef4bb127a9490431de470c7a", + "c53b46c1ccc8e7e58920e6e010be233fa3166ae0" + ] + }, + "renewRequest": { + "bytes": "0203e83cb927e85f96ae50a95ca3be21cc7a3755139a941b15d99b01af4fecf0d270f8833c7a2d58ab816c24ae915fe2aa94676588b467ba1e9f2b24c1a3df7fdb7805596170707201209296d642338cb3bfceeb554285462719e15f004d0579ce53ea77fb6d86cd9ab902320201b0590e59269c6885acf71d27ddfce85187e2cc9736c42e958127cd35be6d38e80000000ba43b7400000001a2f7beb4000310a69b1b4f666681453dec3734667a5ab20501010608000001a128425c00", + "uri": "dash-key:iJ1PNsQ8ThpuRCEMwQJG9ffSCyMb7vfLJDiYFhU3epnaeTDAZxAdVv9NyHP4CeToE4XT1UYUtTeBzHZ6pFcCRtRnDkeVA32woHqKBGsGrJWYcmVFeTKM5Sip7jKiWC2emRfmekq3qpcrXBmUZon1Ro4vTxztmGCbEdwyMf6DKHbJ9JLuBF3G17bXdjrg32xMMftA36fKEtNr9J2auvn8XBi322CmWUWUgKmwxpAvtwnnvZYTG81eQ73YPiCRX6Soh?n=t&v=2" + } +} diff --git a/forge-web/lib/vendor/platform-auth/app-connect/vectors.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/vectors.test.ts new file mode 100644 index 000000000..be53851a3 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/vectors.test.ts @@ -0,0 +1,56 @@ +import { createDecipheriv } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' +import { hexToBytes } from '@noble/hashes/utils.js' +import { describe, expect, it } from 'vitest' +import { openAppConnectPayload } from './crypto' +import { parseAppConnectUri } from './request' +import { buildAppConnectVectors, renewVectorRequest, vectorKeys, yapprVectorRequest } from './test-helpers' + +/** + * The published interop vectors. `vectors.json` is what the code produces; + * docs/APP_CONNECT_PROFILE.md embeds the same JSON for wallet teams, so both + * are checked here. Vendored copies of this module do not carry the doc, so + * that case is skipped when the file is absent. + */ +const DOC_URL = new URL('../../docs/APP_CONNECT_PROFILE.md', import.meta.url) +const fixture = JSON.parse(readFileSync(new URL('./vectors.json', import.meta.url), 'utf8')) + +describe('App Connect v2 test vectors', () => { + it('reproduces vectors.json exactly', async () => { + expect(await buildAppConnectVectors()).toEqual(fixture) + }) + + it.skipIf(!existsSync(DOC_URL))('matches the vectors published in docs/APP_CONNECT_PROFILE.md', () => { + const doc = readFileSync(DOC_URL, 'utf8') + const block = doc.match(/\s*```json\n([\s\S]*?)\n```/) + expect(block, 'the profile must embed the vectors after ').not.toBeNull() + expect(JSON.parse(block![1]!)).toEqual(fixture) + }) + + it('parses the published URIs back to the vector requests', () => { + const parsed = parseAppConnectUri(fixture.request.uri) + expect(parsed.request).toEqual(yapprVectorRequest()) + expect(parsed.network).toBe('devnet') + expect(parsed.callbackUrl).toBe(`https://yap.pr/connect?r=${fixture.request.appEphemeralPubKeyHash}`) + expect(parseAppConnectUri(fixture.renewRequest.uri).request).toEqual(renewVectorRequest()) + }) + + it('decrypts with an independent AES-256-GCM (node:crypto)', () => { + const payload = hexToBytes(fixture.response.encryptedPayload) + const decipher = createDecipheriv('aes-256-gcm', hexToBytes(fixture.response.sessionKey), payload.subarray(0, 12)) + decipher.setAAD(hexToBytes(fixture.response.aad)) + decipher.setAuthTag(payload.subarray(payload.length - 16)) + const plaintext = Buffer.concat([decipher.update(payload.subarray(12, payload.length - 16)), decipher.final()]) + expect(plaintext.toString('hex')).toBe(fixture.response.plaintext) + }) + + it('opens on the app side', async () => { + const slots = await openAppConnectPayload({ + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + ownerId: vectorKeys.ownerId, + walletEphemeralPubKey: hexToBytes(fixture.response.walletEphemeralPubKey), + encryptedPayload: hexToBytes(fixture.response.encryptedPayload), + }) + expect(slots).toEqual(fixture.inputs.slotPrivateKeys.map(hexToBytes)) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/verify.test.ts b/forge-web/lib/vendor/platform-auth/app-connect/verify.test.ts new file mode 100644 index 000000000..0f897e9b7 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/verify.test.ts @@ -0,0 +1,267 @@ +import * as secp256k1 from '@noble/secp256k1' +import { describe, expect, it } from 'vitest' +import { encodeBase58, hash160 } from './primitives' +import { sealAppConnectPayload } from './crypto' +import type { AppConnectRequest } from './request' +import { DASHPAY_CONTRACT_ID, NINETY_DAYS_MS, VECTOR_CREATED_AT, seed, vectorKeys, yapprVectorRequest } from './test-helpers' +import { KeyPurpose, KeySecurityLevel, KeyType, type AppConnectIdentityKey, type AppConnectIdentityPort } from './types' +import { verifyAppConnectCandidate, verifyAppConnectKeys, type AppConnectVerification } from './verify' + +const OWNER = encodeBase58(vectorKeys.ownerId) +const STRANGER_BYTES = seed('stranger') +const STRANGER = encodeBase58(STRANGER_BYTES) +const APP_ID = encodeBase58(vectorKeys.appId) +const GROUP_ID = encodeBase58(vectorKeys.groupId) +const EXPIRES_AT = VECTOR_CREATED_AT + NINETY_DAYS_MS +const NOW = VECTOR_CREATED_AT + 60_000 + +function pub(privateKey: Uint8Array): Uint8Array { + return secp256k1.getPublicKey(privateKey, true) +} + +function groupKey(overrides: Partial = {}): AppConnectIdentityKey { + return { + id: 5, + type: KeyType.ECDSA_HASH160, + purpose: KeyPurpose.AUTHENTICATION, + securityLevel: KeySecurityLevel.CRITICAL, + data: hash160(pub(vectorKeys.groupKey)), + bounds: { kind: 'contractGroup', groupId: GROUP_ID }, + totalBudget: 50_000_000_000n, + expiresAt: EXPIRES_AT, + ...overrides, + } +} + +function profileKey(overrides: Partial = {}): AppConnectIdentityKey { + return { + id: 6, + type: KeyType.ECDSA_SECP256K1, + purpose: KeyPurpose.AUTHENTICATION, + securityLevel: KeySecurityLevel.HIGH, + data: pub(vectorKeys.profileKey), + bounds: { kind: 'documentType', contractId: DASHPAY_CONTRACT_ID, documentTypeName: 'profile' }, + totalBudget: 1_000_000_000n, + expiresAt: EXPIRES_AT, + ...overrides, + } +} + +function encryptionKey(overrides: Partial = {}): AppConnectIdentityKey { + return { + id: 7, + type: KeyType.ECDSA_SECP256K1, + purpose: KeyPurpose.ENCRYPTION, + securityLevel: KeySecurityLevel.MEDIUM, + data: pub(vectorKeys.encryptionKey), + bounds: { kind: 'singleContract', contractId: APP_ID }, + ...overrides, + } +} + +const masterKey: AppConnectIdentityKey = { + id: 0, + type: KeyType.ECDSA_SECP256K1, + purpose: KeyPurpose.AUTHENTICATION, + securityLevel: KeySecurityLevel.MASTER, + data: pub(seed('master')), +} + +interface Scenario { + request?: AppConnectRequest + slots?: Uint8Array[] + /** Identity whose id the AAD carries. */ + sealedFor?: Uint8Array + /** Identity the response is published under. */ + publishedAs?: string + keys?: AppConnectIdentityKey[] + identities?: Record + budgets?: Record + currentEncryptionKeys?: AppConnectIdentityKey[] + now?: number +} + +async function verify(scenario: Scenario = {}): Promise { + const request = scenario.request ?? yapprVectorRequest() + const keys = scenario.keys ?? [masterKey, groupKey(), profileKey(), encryptionKey()] + const identities = scenario.identities ?? { [OWNER]: keys } + const budgets = scenario.budgets ?? { 5: 49_000_000_000n, 6: 900_000_000n } + const port: AppConnectIdentityPort = { + getIdentityFresh: async (id) => (identities[id] ? { id, publicKeys: identities[id] } : null), + remainingBudgets: async (_id, keyIds) => new Map(keyIds.map((keyId) => [keyId, budgets[keyId]])), + contractKeys: async (id, contractId, purpose) => + id === OWNER && contractId === APP_ID && purpose === KeyPurpose.ENCRYPTION + ? scenario.currentEncryptionKeys ?? [encryptionKey()] + : [], + groupInfo: async () => null, + } + const response = await sealAppConnectPayload({ + appEphemeralPubKey: request.appEphemeralPubKey, + ownerId: scenario.sealedFor ?? vectorKeys.ownerId, + slots: scenario.slots ?? [vectorKeys.groupKey, vectorKeys.profileKey, vectorKeys.encryptionKey], + }) + return verifyAppConnectCandidate({ + request, + appEphemeralPrivateKey: vectorKeys.appEphemeralPrivateKey, + candidate: { ownerId: scenario.publishedAs ?? OWNER, ...response }, + identity: port, + now: scenario.now ?? NOW, + }) +} + +function rejection(result: AppConnectVerification) { + if (result.ok) throw new Error('expected a rejection') + return { reason: result.reason, retryable: result.retryable, slot: result.slot } +} + +describe('verifyAppConnectCandidate', () => { + it('accepts the full Yappr grant and classifies each key', async () => { + const result = await verify() + if (!result.ok) throw new Error(`rejected: ${result.reason}`) + const { grant } = result + expect(grant.identityId).toBe(OWNER) + expect(grant.authKeys.map((k) => [k.role, k.key.id, k.remainingBudget])).toEqual([ + ['contractGroup', 5, 49_000_000_000n], + ['documentType', 6, 900_000_000n], + ]) + expect(grant.encryptionKeys.map((k) => [k.role, k.key.id])).toEqual([['encryption', 7]]) + expect(grant.authKeys[0]!.privateKey).toEqual(vectorKeys.groupKey) + }) + + it('accepts a partial grant that keeps the primary binding, in any slot order', async () => { + const result = await verify({ slots: [vectorKeys.encryptionKey, vectorKeys.groupKey] }) + expect(result.ok && result.grant.authKeys.map((k) => k.role)).toEqual(['contractGroup']) + }) + + it('accepts a HIGH group key when CRITICAL was asked (the claim is just unavailable)', async () => { + const result = await verify({ keys: [groupKey({ securityLevel: KeySecurityLevel.HIGH }), profileKey(), encryptionKey()] }) + expect(result.ok).toBe(true) + }) + + it('matches both ECDSA_HASH160 and ECDSA_SECP256K1 key data', async () => { + const swapped = [ + groupKey({ type: KeyType.ECDSA_SECP256K1, data: pub(vectorKeys.groupKey) }), + profileKey({ type: KeyType.ECDSA_HASH160, data: hash160(pub(vectorKeys.profileKey)) }), + encryptionKey(), + ] + expect((await verify({ keys: swapped })).ok).toBe(true) + }) + + it.each([0, 1, 19, 21, 33, 65])('refuses HASH160 grant key data of %i bytes', async (length) => { + const data = new Uint8Array(length) + data.set(groupKey().data.subarray(0, length)) + const result = await verify({ keys: [groupKey({ data }), profileKey(), encryptionKey()] }) + expect(rejection(result)).toEqual({ reason: 'key-not-found', retryable: true, slot: 0 }) + }) + + it('honours the identity hint', async () => { + const hinted = { ...yapprVectorRequest(), identityHint: vectorKeys.ownerId } + expect((await verify({ request: hinted })).ok).toBe(true) + const other = { ...yapprVectorRequest(), identityHint: STRANGER_BYTES } + expect(rejection(await verify({ request: other })).reason).toBe('hint-mismatch') + }) + + const cases: Array<[string, Scenario, string, boolean?]> = [ + ['a response copied under another identity', { publishedAs: STRANGER, identities: { [STRANGER]: [groupKey()] } }, 'decrypt'], + ['keys that live on another identity (wrong owner)', { + sealedFor: STRANGER_BYTES, + publishedAs: STRANGER, + identities: { [OWNER]: [groupKey(), profileKey(), encryptionKey()], [STRANGER]: [masterKey] }, + }, 'key-not-found', true], + ['an identity that cannot be read yet', { identities: {} }, 'identity-not-found', true], + ['an unregistered key', { keys: [masterKey, profileKey(), encryptionKey()] }, 'key-not-found', true], + ['a disabled key', { keys: [groupKey({ disabledAt: NOW - 1 }), profileKey(), encryptionKey()] }, 'key-disabled'], + ['an unbound auth key', { keys: [groupKey({ bounds: undefined }), profileKey(), encryptionKey()] }, 'key-unbound'], + ['a MASTER key', { keys: [groupKey({ securityLevel: KeySecurityLevel.MASTER }), profileKey(), encryptionKey()] }, 'key-master'], + ['a CRITICAL key on the DashPay binding', { keys: [groupKey(), profileKey({ securityLevel: KeySecurityLevel.CRITICAL }), encryptionKey()] }, 'key-level'], + ['a MEDIUM group key', { keys: [groupKey({ securityLevel: KeySecurityLevel.MEDIUM }), profileKey(), encryptionKey()] }, 'key-level'], + ['a key bound to another group', { keys: [groupKey({ bounds: { kind: 'contractGroup', groupId: STRANGER } }), profileKey(), encryptionKey()] }, 'key-unmatched'], + ['a key bound to another DashPay type', { + keys: [groupKey(), profileKey({ bounds: { kind: 'documentType', contractId: DASHPAY_CONTRACT_ID, documentTypeName: 'contactRequest' } }), encryptionKey()], + }, 'key-unmatched'], + ['a key bound to a foreign contract', { keys: [groupKey({ bounds: { kind: 'singleContract', contractId: STRANGER } }), profileKey(), encryptionKey()] }, 'key-unmatched'], + ['a TRANSFER key', { keys: [groupKey({ purpose: KeyPurpose.TRANSFER }), profileKey(), encryptionKey()] }, 'key-purpose'], + ['a key that expires within the margin', { keys: [groupKey({ expiresAt: NOW + 30 * 60_000 }), profileKey(), encryptionKey()] }, 'key-expired'], + ['an expired key', { keys: [groupKey({ expiresAt: NOW - 1 }), profileKey(), encryptionKey()] }, 'key-expired'], + ['a group key without a budget', { keys: [groupKey({ totalBudget: undefined }), profileKey(), encryptionKey()] }, 'key-limits'], + ['a key that dropped the requested budget', { keys: [groupKey(), profileKey({ totalBudget: undefined }), encryptionKey()] }, 'key-limits'], + ['a key that dropped the requested expiry', { keys: [groupKey({ expiresAt: undefined }), profileKey(), encryptionKey()] }, 'key-limits'], + ['a spent budget', { budgets: { 5: 0n, 6: 1n } }, 'budget-exhausted'], + ['a budget Platform does not report (yet)', { budgets: { 6: 1n } }, 'budget-unknown', true], + ['an encryption key that is not current', { currentEncryptionKeys: [encryptionKey({ id: 9, data: pub(seed('newer')) })] }, 'encryption-key-not-current', true], + ['an encryption key at HIGH', { keys: [groupKey(), profileKey(), encryptionKey({ securityLevel: KeySecurityLevel.HIGH })] }, 'key-level'], + ['a hash-only encryption key', { + keys: [groupKey(), profileKey(), encryptionKey({ type: KeyType.ECDSA_HASH160, data: hash160(pub(vectorKeys.encryptionKey)) })], + }, 'key-type'], + ['an unbound encryption key', { keys: [groupKey(), profileKey(), encryptionKey({ bounds: undefined })] }, 'key-unbound'], + ['an encryption key bound elsewhere', { keys: [groupKey(), profileKey(), encryptionKey({ bounds: { kind: 'singleContract', contractId: STRANGER } })] }, 'key-unmatched'], + ['a grant without the primary binding', { slots: [vectorKeys.profileKey, vectorKeys.encryptionKey] }, 'primary-missing'], + ['the same key twice', { slots: [vectorKeys.groupKey, vectorKeys.groupKey] }, 'duplicate-binding'], + ['two keys for one binding', { + slots: [vectorKeys.groupKey, seed('second group key')], + keys: [groupKey(), groupKey({ id: 8, data: hash160(pub(seed('second group key'))) })], + }, 'duplicate-binding'], + ['more slots than bindings', { slots: [vectorKeys.groupKey, vectorKeys.profileKey, vectorKeys.encryptionKey, seed('extra')] }, 'framing'], + ['a slot that is not a private key', { slots: [vectorKeys.groupKey, new Uint8Array(32)] }, 'invalid-key'], + ] + + for (const [name, scenario, reason, retryable = false] of cases) { + it(`rejects ${name}`, async () => { + const result = rejection(await verify(scenario)) + expect(result.reason).toBe(reason) + expect(result.retryable).toBe(retryable) + }) + } + + it('reports which slot failed', async () => { + const result = rejection(await verify({ keys: [groupKey(), profileKey({ disabledAt: 1 }), encryptionKey()] })) + expect(result.slot).toBe(1) + }) + + it('rejects a CRITICAL group key when only HIGH was asked', async () => { + const request = yapprVectorRequest() + request.authBindings[0] = { ...request.authBindings[0]!, securityLevel: KeySecurityLevel.HIGH } + expect(rejection(await verify({ request })).reason).toBe('key-level') + }) +}) + +describe('verifyAppConnectKeys (keys kept from an earlier grant)', () => { + const port = (keys: AppConnectIdentityKey[], budgets: Record = { 5: 49_000_000_000n, 6: 900_000_000n }): AppConnectIdentityPort => ({ + getIdentityFresh: async (id) => (id === OWNER ? { id, publicKeys: keys } : null), + remainingBudgets: async (_id, keyIds) => new Map(keyIds.map((keyId) => [keyId, budgets[keyId]])), + contractKeys: async (id, contractId, purpose) => (id === OWNER && contractId === APP_ID && purpose === KeyPurpose.ENCRYPTION ? [encryptionKey()] : []), + groupInfo: async () => null, + }) + const kept = () => [vectorKeys.groupKey.slice(), vectorKeys.profileKey.slice(), vectorKeys.encryptionKey.slice()] + + it('rebuilds the grant from chain', async () => { + const result = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: OWNER, identity: port([masterKey, groupKey(), profileKey(), encryptionKey()]), now: NOW, privateKeys: kept() }) + if (!result.ok) throw new Error(`rejected: ${result.reason}`) + expect(result.grant.authKeys.map((k) => k.key.id)).toEqual([5, 6]) + expect(result.grant.encryptionKeys.map((k) => k.key.id)).toEqual([7]) + }) + + it('says an expired or spent grant is expired or spent, and wipes the keys', async () => { + const keys = kept() + const expired = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: OWNER, identity: port([groupKey({ expiresAt: NOW - 1 }), profileKey(), encryptionKey()]), now: NOW, privateKeys: keys }) + expect(rejection(expired).reason).toBe('key-expired') + expect(keys.every((key) => key.every((byte) => byte === 0))).toBe(true) + const spent = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: OWNER, identity: port([groupKey(), profileKey(), encryptionKey()], { 5: 0n, 6: 1n }), now: NOW, privateKeys: kept() }) + expect(rejection(spent).reason).toBe('budget-exhausted') + }) + + it('takes the caller\'s expiry margin: a key 30 minutes from expiry is fine at the signing margin, not the default hour', async () => { + const keys = [groupKey({ expiresAt: NOW + 30 * 60_000 }), profileKey(), encryptionKey()] + const atDefault = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: OWNER, identity: port(keys), now: NOW, privateKeys: kept() }) + expect(rejection(atDefault).reason).toBe('key-expired') + const atSigning = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: OWNER, identity: port(keys), now: NOW, expiryMarginMs: 5 * 60_000, privateKeys: kept() }) + expect(atSigning.ok).toBe(true) + }) + + it('refuses keys the wallet has since revoked, or that belong to another identity', async () => { + const revoked = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: OWNER, identity: port([groupKey({ disabledAt: NOW - 1 }), profileKey(), encryptionKey()]), now: NOW, privateKeys: kept() }) + expect(rejection(revoked).reason).toBe('key-disabled') + const stranger = await verifyAppConnectKeys({ request: yapprVectorRequest(), ownerId: STRANGER, identity: port([groupKey()]), now: NOW, privateKeys: kept() }) + expect(rejection(stranger).reason).toBe('identity-not-found') + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/app-connect/verify.ts b/forge-web/lib/vendor/platform-auth/app-connect/verify.ts new file mode 100644 index 000000000..ad3309a72 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/app-connect/verify.ts @@ -0,0 +1,329 @@ +import { clearSensitiveBytes, decodeIdentityId, encodeBase58, getPublicKey, hash160 } from './primitives' +import { AppConnectPayloadError, openAppConnectPayload } from './crypto' +import type { AppConnectCandidate } from './poller' +import { authBindingBounds, encBindingBounds, type AppConnectAuthBinding, type AppConnectRequest } from './request' +import { + KeyPurpose, + KeySecurityLevel, + KeyType, + boundsEqual, + type AppConnectIdentityKey, + type AppConnectIdentityPort, +} from './types' + +/** A granted key must stay valid this long past `now` to be accepted. */ +export const APP_CONNECT_EXPIRY_MARGIN_MS = 60 * 60_000 + +export type AppConnectRejectReason = + /** The request named an identity and the candidate is someone else. */ + | 'hint-mismatch' + | 'framing' + /** Wrong request, wrong owner (a copied response) or tampered ciphertext. */ + | 'decrypt' + | 'invalid-key' + | 'identity-not-found' + /** A slot's key is not on the candidate identity (yet). */ + | 'key-not-found' + | 'key-disabled' + | 'key-master' + | 'key-purpose' + | 'key-type' + | 'key-unbound' + /** Bound to something the request did not ask for (foreign contract, wrong group or document type). */ + | 'key-unmatched' + | 'key-level' + /** Missing the budget or expiry the request asked for, or the group key's mandatory budget. */ + | 'key-limits' + | 'key-expired' + | 'budget-exhausted' + /** Platform returned no remaining budget for a budgeted key (a lagging read). */ + | 'budget-unknown' + | 'encryption-key-not-current' + | 'duplicate-binding' + | 'primary-missing' + +export type AppConnectKeyRole = 'singleContract' | 'documentType' | 'contractGroup' | 'encryption' | 'decryption' + +export interface AppConnectGrantedKey { + role: AppConnectKeyRole + /** Position of the matching binding in `authBindings` or `encBindings`. */ + bindingIndex: number + privateKey: Uint8Array + key: AppConnectIdentityKey + remainingBudget?: bigint +} + +export interface AppConnectGrant { + identityId: string + authKeys: AppConnectGrantedKey[] + encryptionKeys: AppConnectGrantedKey[] +} + +export type AppConnectVerification = + | { ok: true; grant: AppConnectGrant } + /** `retryable`: the identity read may lag the wallet's update; check again shortly. */ + | { ok: false; reason: AppConnectRejectReason; retryable: boolean; slot?: number } + +export interface VerifyAppConnectCandidateInput { + request: AppConnectRequest + appEphemeralPrivateKey: Uint8Array + candidate: AppConnectCandidate + identity: AppConnectIdentityPort + /** Latest block time (ms), or the wall clock when that is unavailable. */ + now: number + expiryMarginMs?: number +} + +class Rejection { + constructor(readonly reason: AppConnectRejectReason, readonly slot?: number) {} +} + +const RETRYABLE: ReadonlySet = new Set([ + 'identity-not-found', + 'key-not-found', + 'budget-unknown', + 'encryption-key-not-current', +]) + +interface SlotMatch { + slot: number + privateKey: Uint8Array + key: AppConnectIdentityKey + role: AppConnectKeyRole + bindingIndex: number +} + +/** + * Verifies one `loginKeyResponse` candidate against the request it answers. + * Accepts only if every slot is a live key on the candidate's `$ownerId` that + * matches one requested binding exactly (bounds, purpose, level, limits), the + * primary binding is granted, no key is about to expire or out of budget, and + * each encryption key is the one Platform currently resolves for its contract. + * Anything else rejects the whole candidate; there is no partial accept of a + * response that contains a key the app did not ask for. + * + * `ok: true` means a valid grant from `grant.identityId`, not that this is the + * user: anyone can answer a request with their own identity. Without an + * identity hint the app must still ask "Continue as @name?". + */ +export async function verifyAppConnectCandidate(input: VerifyAppConnectCandidateInput): Promise { + const { request, candidate } = input + if (request.identityHint && candidate.ownerId !== encodeBase58(request.identityHint)) { + return reject(new Rejection('hint-mismatch')) + } + + let ownerIdBytes: Uint8Array + try { + ownerIdBytes = decodeIdentityId(candidate.ownerId) + } catch { + return reject(new Rejection('identity-not-found')) + } + + let slots: Uint8Array[] + try { + slots = await openAppConnectPayload({ + appEphemeralPrivateKey: input.appEphemeralPrivateKey, + ownerId: ownerIdBytes, + walletEphemeralPubKey: candidate.walletEphemeralPubKey, + encryptedPayload: candidate.encryptedPayload, + }) + } catch (error) { + return reject(new Rejection(error instanceof AppConnectPayloadError ? error.code : 'decrypt')) + } + + return verifyKeys({ request, ownerId: candidate.ownerId, identity: input.identity, now: input.now, expiryMarginMs: input.expiryMarginMs }, slots) +} + +/** What a grant is checked against, whether its keys came from a wallet's answer or were kept from one. */ +interface VerifyContext { + request: Pick + ownerId: string + identity: AppConnectIdentityPort + now: number + expiryMarginMs?: number +} + +export interface VerifyAppConnectKeysInput extends VerifyContext { + /** The private keys of one earlier grant, in any order; wiped when they are refused. */ + privateKeys: Uint8Array[] +} + +/** + * Verifies private keys an app kept from an earlier grant (Yappr's passkey + * vault) exactly as {@link verifyAppConnectCandidate} verifies a wallet's + * answer, against the request the app makes today: every key must still be + * a live key of `ownerId` that matches one binding (bounds, purpose, level, + * limits), the primary binding must be there, and nothing may be expired, + * spent or superseded. A refusal says why, so an expired or spent grant can + * lead to a renewal in the wallet rather than a dead session. + */ +export function verifyAppConnectKeys(input: VerifyAppConnectKeysInput): Promise { + return verifyKeys(input, input.privateKeys) +} + +async function verifyKeys(context: VerifyContext, slots: Uint8Array[]): Promise { + try { + if (slots.length > context.request.authBindings.length + context.request.encBindings.length) { + throw new Rejection('framing') + } + const grant = await verifySlots(context, slots) + return { ok: true, grant } + } catch (error) { + slots.forEach(clearSensitiveBytes) + if (error instanceof Rejection) return reject(error) + throw error + } +} + +function reject(rejection: Rejection): AppConnectVerification { + return { ok: false, reason: rejection.reason, retryable: RETRYABLE.has(rejection.reason), slot: rejection.slot } +} + +async function verifySlots(input: VerifyContext, slots: Uint8Array[]): Promise { + const { request, ownerId, identity, now } = input + const margin = input.expiryMarginMs ?? APP_CONNECT_EXPIRY_MARGIN_MS + + const record = await identity.getIdentityFresh(ownerId) + if (!record || record.id !== ownerId) throw new Rejection('identity-not-found') + + const matches: SlotMatch[] = [] + for (const [slot, privateKey] of slots.entries()) { + const key = findKeyForSlot(record.publicKeys, privateKey, slot) + const match = matchBinding(request, key, slot) + checkKeyLimits(key, match, request, now, margin, slot) + if (matches.some((m) => m.key.id === key.id || (m.role === match.role && m.bindingIndex === match.bindingIndex))) { + throw new Rejection('duplicate-binding', slot) + } + matches.push({ slot, privateKey, key, ...match }) + } + + if (!matches.some((m) => isAuthRole(m.role) && m.bindingIndex === 0)) { + throw new Rejection('primary-missing') + } + + for (const match of matches.filter((m) => !isAuthRole(m.role))) { + const binding = request.encBindings[match.bindingIndex] + if (!binding) throw new Rejection('key-unmatched', match.slot) + const current = await identity.contractKeys(ownerId, encodeBase58(binding.contractId), binding.purpose) + if (!current.some((key) => key.id === match.key.id && bytesEqual(key.data, match.key.data))) { + throw new Rejection('encryption-key-not-current', match.slot) + } + } + + const budgeted = matches.filter((m) => m.key.totalBudget !== undefined) + const remaining = budgeted.length > 0 + ? await identity.remainingBudgets(ownerId, budgeted.map((m) => m.key.id)) + : new Map() + for (const match of budgeted) { + const left = remaining.get(match.key.id) + if (left === undefined) throw new Rejection('budget-unknown', match.slot) + if (left <= 0n) throw new Rejection('budget-exhausted', match.slot) + } + + const granted = matches.map((m): AppConnectGrantedKey => ({ + role: m.role, + bindingIndex: m.bindingIndex, + privateKey: m.privateKey, + key: m.key, + remainingBudget: remaining.get(m.key.id), + })) + return { + identityId: ownerId, + authKeys: granted.filter((g) => isAuthRole(g.role)), + encryptionKeys: granted.filter((g) => !isAuthRole(g.role)), + } +} + +function isAuthRole(role: AppConnectKeyRole): boolean { + return role !== 'encryption' && role !== 'decryption' +} + +function findKeyForSlot(keys: AppConnectIdentityKey[], privateKey: Uint8Array, slot: number): AppConnectIdentityKey { + let publicKey: Uint8Array + try { + publicKey = getPublicKey(privateKey) + } catch { + throw new Rejection('invalid-key', slot) + } + const publicKeyHash = hash160(publicKey) + const found = keys.filter((key) => + (key.type === KeyType.ECDSA_SECP256K1 && bytesEqual(key.data, publicKey)) + || (key.type === KeyType.ECDSA_HASH160 && bytesEqual(key.data, publicKeyHash))) + if (found.length === 0) throw new Rejection('key-not-found', slot) + if (found.length > 1) throw new Rejection('duplicate-binding', slot) + const only = found[0] + if (!only) throw new Rejection('key-not-found', slot) + return only +} + +function matchBinding( + request: Pick, + key: AppConnectIdentityKey, + slot: number, +): { role: AppConnectKeyRole; bindingIndex: number } { + if (key.disabledAt !== undefined) throw new Rejection('key-disabled', slot) + if (key.securityLevel === KeySecurityLevel.MASTER) throw new Rejection('key-master', slot) + + const isAuth = key.purpose === KeyPurpose.AUTHENTICATION + if (!isAuth && key.purpose !== KeyPurpose.ENCRYPTION && key.purpose !== KeyPurpose.DECRYPTION) { + throw new Rejection('key-purpose', slot) + } + if (!key.bounds) throw new Rejection('key-unbound', slot) + const bounds = key.bounds + + if (isAuth) { + const bindingIndex = request.authBindings.findIndex((binding) => boundsEqual(authBindingBounds(binding), bounds)) + if (bindingIndex === -1) throw new Rejection('key-unmatched', slot) + const binding = request.authBindings[bindingIndex] + if (!binding) throw new Rejection('key-unmatched', slot) + if (!authLevelAllowed(binding, key.securityLevel)) throw new Rejection('key-level', slot) + if (key.type !== KeyType.ECDSA_SECP256K1 && key.type !== KeyType.ECDSA_HASH160) { + throw new Rejection('key-type', slot) + } + return { role: binding.kind, bindingIndex } + } + + const bindingIndex = request.encBindings.findIndex((binding) => + binding.purpose === key.purpose && boundsEqual(encBindingBounds(binding), bounds)) + if (bindingIndex === -1) throw new Rejection('key-unmatched', slot) + if (key.securityLevel !== KeySecurityLevel.MEDIUM) throw new Rejection('key-level', slot) + // Peers need the full point for ECDH, so a hash-only key is useless here. + if (key.type !== KeyType.ECDSA_SECP256K1) throw new Rejection('key-type', slot) + return { role: key.purpose === KeyPurpose.ENCRYPTION ? 'encryption' : 'decryption', bindingIndex } +} + +/** + * A group key may be CRITICAL or HIGH and never more privileged than asked; + * everything else is exactly HIGH. (Lower numbers are more privileged.) + */ +function authLevelAllowed(binding: AppConnectAuthBinding, level: number): boolean { + if (binding.kind === 'contractGroup') { + return (level === KeySecurityLevel.CRITICAL || level === KeySecurityLevel.HIGH) && level >= binding.securityLevel + } + return level === KeySecurityLevel.HIGH +} + +function checkKeyLimits( + key: AppConnectIdentityKey, + match: { role: AppConnectKeyRole; bindingIndex: number }, + request: Pick, + now: number, + margin: number, + slot: number, +): void { + if (isAuthRole(match.role)) { + const binding = request.authBindings[match.bindingIndex] + if (!binding) throw new Rejection('key-unmatched', slot) + // The wallet may change the values (clamps, presets) but never drop a limit. + const budgetRequired = binding.kind === 'contractGroup' || binding.totalBudget !== undefined + if (budgetRequired && (key.totalBudget === undefined || key.totalBudget <= 0n)) { + throw new Rejection('key-limits', slot) + } + if (binding.expiresAt !== undefined && key.expiresAt === undefined) throw new Rejection('key-limits', slot) + } + if (key.expiresAt !== undefined && key.expiresAt - now <= margin) throw new Rejection('key-expired', slot) +} + +function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { + return a.length === b.length && a.every((byte, index) => byte === b[index]) +} diff --git a/forge-web/package.json b/forge-web/package.json index e6de3ac6f..1ef20d814 100644 --- a/forge-web/package.json +++ b/forge-web/package.json @@ -21,7 +21,8 @@ "lint:copy": "node scripts/copy-lint.mjs", "typecheck": "tsc --noEmit", "test": "vitest run", - "test:e2e": "playwright test" + "test:e2e": "playwright test", + "vendor:status": "node ${PLATFORM_AUTH_DIR:-../../platform-auth}/tools/vendor.mjs status lib/vendor/platform-auth" }, "dependencies": { "@dashevo/evo-sdk": "5.0.0-rc.4", diff --git a/forge-web/scripts/copy-lint.mjs b/forge-web/scripts/copy-lint.mjs index f29516ce8..6a3c31b6e 100644 --- a/forge-web/scripts/copy-lint.mjs +++ b/forge-web/scripts/copy-lint.mjs @@ -13,7 +13,7 @@ // whole file with `// copy-lint-ignore-file: ` as its first line. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' -import { dirname, join, relative } from 'node:path' +import { dirname, join, relative, sep } from 'node:path' import { fileURLToPath } from 'node:url' import ts from 'typescript' @@ -53,11 +53,19 @@ export const RULES = [ { id: 'lazy-plural', pattern: /\w\(s\)/, why: 'use plural() instead of "(s)"' }, ] -function walk(dir, files) { +/** + * Directories, relative to the web root, that hold code copied in from another repo + * (lib/vendor, synced by platform-auth's tools/vendor.mjs). Their strings are that + * project's developer errors, not Forge copy, and editing them would only add drift. + */ +export const SKIP_DIRS = ['lib/vendor'] + +function walk(dir, files, root) { for (const name of readdirSync(dir)) { const path = join(dir, name) if (statSync(path).isDirectory()) { - if (!/^(node_modules|__tests__|e2e|e2e-drill)$/.test(name)) walk(path, files) + const skip = /^(node_modules|__tests__|e2e|e2e-drill)$/.test(name) || SKIP_DIRS.includes(relative(root, path).split(sep).join('/')) + if (!skip) walk(path, files, root) } else if (/\.tsx?$/.test(name) && !/\.(test|spec)\.tsx?$|fixtures?\.tsx?$|\.d\.ts$/.test(name)) { files.push(path) } @@ -199,7 +207,7 @@ export function extractFile(path, root = WEB_ROOT) { export function extractAll(root = WEB_ROOT, dirs = SOURCE_DIRS) { const files = [] - for (const d of dirs) if (existsSync(join(root, d))) walk(join(root, d), files) + for (const d of dirs) if (existsSync(join(root, d))) walk(join(root, d), files, root) return files.sort().flatMap((f) => extractFile(f, root)) } diff --git a/forge-web/scripts/copy-lint.test.ts b/forge-web/scripts/copy-lint.test.ts index cc9da6f50..748e2c212 100644 --- a/forge-web/scripts/copy-lint.test.ts +++ b/forge-web/scripts/copy-lint.test.ts @@ -81,6 +81,16 @@ describe('copy lint extraction', () => { const found = lint(dir) as Array expect(found.map((f) => `${f.file}:${f.id}`)).toEqual(['app/page.tsx:code-identifier']) }) + + it('skips vendored code', () => { + mkdirSync(join(dir, 'lib', 'vendor', 'mod'), { recursive: true }) + writeFileSync(join(dir, 'lib', 'vendor', 'mod', 'x.ts'), `throw new Error('the packManifest is missing here')\n`) + mkdirSync(join(dir, 'lib', 'auth'), { recursive: true }) + writeFileSync(join(dir, 'lib', 'auth', 'vendor.ts'), `throw new Error('the starBeat is missing here')\n`) + const found = lint(dir) as Array + expect(found.map((f) => f.file)).not.toContain(join('lib', 'vendor', 'mod', 'x.ts')) + expect(found.map((f) => f.file)).toContain(join('lib', 'auth', 'vendor.ts')) + }) }) describe('the shipped web copy', () => { From 1101632186226c02d7cd45ed008e914f1890f152 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 24 Oct 2026 22:14:45 -0500 Subject: [PATCH 2/8] feat(auth): App Connect v2 request, poll and verification Add Forge's App Connect v2 sign-in core beside the v1 flow, which is unchanged (a v1 wallet refuses a v=2 request, so they never share a QR). - app-connect-port: the vendored verifier's and poller's ports over the SDK (proved identity reads, remaining budgets, contract keys, answers in the App Connect contract sorted by owner bytes) and the chain clock. A key whose type, data or bounds cannot be read is dropped, never treated as unbound. - app-connect-v2: one request for a HIGH key bound to the dash-forge group with Forge's default limits from chain time (app forge-core, label "Dash Forge", connection id, CREATED_AT from this device's clock, no encryption binding, no MODE; a renewal adds IDENTITY_HINT). The QR carries no callback, the deep link may. awaitV2Grant pages every answer, verifies each against chain time, refuses when two identities answered (counting every answer that opens), settles like v1, then checks the key again with findWalletKey and wipes the granted and ephemeral keys. - connection-id: the per-network connection id (kept across logout and forget) and the renewal-in-flight mark, both in localStorage. - wallet-sim: answerV2, a v2 wallet on the vendored parser and sealing. Co-Authored-By: Claude Opus 5.5 --- forge-web/lib/auth/app-connect-port.test.ts | 141 +++++++ forge-web/lib/auth/app-connect-port.ts | 195 ++++++++++ forge-web/lib/auth/app-connect-v2.test.ts | 395 +++++++++++++++++++ forge-web/lib/auth/app-connect-v2.ts | 399 ++++++++++++++++++++ forge-web/lib/auth/connection-id.test.ts | 61 +++ forge-web/lib/auth/connection-id.ts | 103 +++++ forge-web/lib/auth/wallet-protocol.test.ts | 9 + forge-web/lib/auth/wallet-sim.ts | 24 ++ forge-web/lib/sdk/facade.ts | 8 + 9 files changed, 1335 insertions(+) create mode 100644 forge-web/lib/auth/app-connect-port.test.ts create mode 100644 forge-web/lib/auth/app-connect-port.ts create mode 100644 forge-web/lib/auth/app-connect-v2.test.ts create mode 100644 forge-web/lib/auth/app-connect-v2.ts create mode 100644 forge-web/lib/auth/connection-id.test.ts create mode 100644 forge-web/lib/auth/connection-id.ts diff --git a/forge-web/lib/auth/app-connect-port.test.ts b/forge-web/lib/auth/app-connect-port.test.ts new file mode 100644 index 000000000..c1e4e7ca7 --- /dev/null +++ b/forge-web/lib/auth/app-connect-port.test.ts @@ -0,0 +1,141 @@ +/** + * The App Connect ports over fake wasm objects: how a key is read (and when it is dropped rather + * than misread), answers sorted by owner whatever order the SDK hands them back in, and the + * chain clock. + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' +import { describe, expect, it } from 'vitest' + +import type { WasmKey } from '../sdk/facade' +import { APP_CONNECT_CONTRACT_ID } from './app-connect' +import { appConnectPort, candidateOf, compareIds, toAppConnectKey, toAppConnectKeys } from './app-connect-port' +import { base58Encode } from './base58' + +const GROUP = '6dV3kMBWHGR7pLKrHToMBQgbTpjqeE2VAyCEWmLbrkWC' +const CONTRACT = 'A2KL77ngVM1ft1t1em2XKt1rWCBZANdAJMyfWrDGCcd1' + +function wasmKey(over: Partial & { bounds?: unknown } = {}): WasmKey { + const { bounds, ...rest } = over + return { + keyId: 3, + keyTypeNumber: 0, + data: '02' + 'ab'.repeat(32), + purposeNumber: 0, + securityLevelNumber: 2, + ...(bounds !== undefined ? { contractBounds: { toJSON: () => bounds as { $type: string; id: string } } } : {}), + validatePrivateKey: () => false, + ...rest, + } +} + +describe('reading keys for the verifier', () => { + it('maps a group-bound V1 key with its limits', () => { + const k = toAppConnectKey(wasmKey({ bounds: { $type: 'contractGroup', id: GROUP }, totalBudget: 5n, expiresAt: 1_800_000_000_000n, disabledAt: 1_700_000_000_000n })) + expect(k).toEqual({ + id: 3, + type: 0, + purpose: 0, + securityLevel: 2, + data: new Uint8Array([2, ...new Array(32).fill(0xab)]), + bounds: { kind: 'contractGroup', groupId: GROUP }, + totalBudget: 5n, + expiresAt: 1_800_000_000_000, + disabledAt: 1_700_000_000_000, + }) + }) + + it('maps every bounds kind, and an unbound key as unbound', () => { + expect(toAppConnectKey(wasmKey({ bounds: { $type: 'singleContract', id: CONTRACT } }))?.bounds).toEqual({ kind: 'singleContract', contractId: CONTRACT }) + expect(toAppConnectKey(wasmKey({ bounds: { $type: 'documentType', id: CONTRACT, documentTypeName: 'profile' } }))?.bounds).toEqual({ + kind: 'documentType', + contractId: CONTRACT, + documentTypeName: 'profile', + }) + const unbound = toAppConnectKey(wasmKey()) + expect(unbound).not.toBeNull() + expect(unbound?.bounds).toBeUndefined() + }) + + it('drops a key it cannot read faithfully: an unreadable bound never looks unbound', () => { + const unreadable = [ + wasmKey({ bounds: { $type: 'someFutureKind', id: GROUP } }), + wasmKey({ bounds: { $type: 'documentType', id: CONTRACT } }), + wasmKey({ bounds: { $type: 'contractGroup' } }), + wasmKey({ keyTypeNumber: undefined }), + wasmKey({ data: 'not hex' }), + wasmKey({ data: undefined }), + { ...wasmKey(), contractBounds: { toJSON: () => { throw new Error('freed') } } }, + ] + for (const k of unreadable) expect(toAppConnectKey(k)).toBeNull() + expect(toAppConnectKeys([...unreadable, wasmKey({ keyId: 9 })]).map((k) => k.id)).toEqual([9]) + }) +}) + +describe('reading answers', () => { + const ids = [new Uint8Array(32).fill(9), new Uint8Array(32).fill(1), new Uint8Array(32).fill(200)].map(base58Encode) + + it('orders owners by bytes, as Platform does (not as strings)', () => { + // As strings '2…' < 'E…' < 'm…'; as bytes 0x01 < 0x09 < 0xc8. + const sorted = [...ids].sort(compareIds) + expect(sorted).toEqual([ids[1], ids[0], ids[2]]) + }) + + it('pages the App Connect contract by request and owner, sorted by owner whatever the SDK order', async () => { + const queries: unknown[] = [] + const sdk = { + documents: { + async query(q: unknown) { + queries.push(q) + return new Map(ids.map((id, i) => [String(i), { toJSON: () => ({ $ownerId: id, walletEphemeralPubKey: btoa('\x02'.repeat(33)), encryptedPayload: btoa('x'.repeat(60)) }) }])) + }, + }, + } as unknown as EvoSDK + const port = appConnectPort(sdk) + const hash = new Uint8Array(20).fill(5) + const got = await port.listCandidates(hash, undefined, ids[1], 10) + expect(got.map((c) => c.ownerId)).toEqual([ids[1], ids[0], ids[2]]) + expect(got[0]!.encryptedPayload.length).toBe(60) + expect(queries[0]).toMatchObject({ + dataContractId: APP_CONNECT_CONTRACT_ID, + documentTypeName: 'loginKeyResponse', + where: [ + ['appEphemeralPubKeyHash', '==', btoa(String.fromCharCode(...hash))], + ['$ownerId', '>', ids[1]], + ], + limit: 10, + }) + await port.listCandidates(hash, ids[2], undefined, 10) + expect((queries[1] as { where: unknown[] }).where[1]).toEqual(['$ownerId', '==', ids[2]]) + }) + + it('keeps an answer whose bytes do not read (the verifier refuses it), and fails a row without an owner', () => { + const c = candidateOf({ $ownerId: ids[0], walletEphemeralPubKey: 42, encryptedPayload: '%%%' }) + expect(c.walletEphemeralPubKey.length).toBe(0) + expect(c.encryptedPayload.length).toBe(0) + expect(() => candidateOf({ walletEphemeralPubKey: '', encryptedPayload: '' })).toThrow(/no readable owner/) + expect(() => candidateOf({ $ownerId: 'X', walletEphemeralPubKey: '', encryptedPayload: '' })).toThrow(/no readable owner/) + }) +}) + +describe('the other reads', () => { + it('reads remaining budgets, contract keys and the chain clock', async () => { + const sdk = { + identities: { + fetch: async () => ({ publicKeys: [wasmKey({ keyId: 4 }), wasmKey({ keyId: 5, keyTypeNumber: undefined })] }), + keysRemainingBudgets: async () => new Map([[4, 7n], [5, null]]), + contractKeys: async () => [ + { identityId: { toBase58: () => 'someone else' }, keys: [wasmKey({ keyId: 1 })] }, + { identityId: { toBase58: () => 'me' }, keys: [wasmKey({ keyId: 2 })] }, + ], + }, + protocol: { versionUpgradeStateWithProof: async () => ({ metadata: { protocolVersion: 14, timeMs: 1_800_000_000_000n } }) }, + } as unknown as EvoSDK + const port = appConnectPort(sdk) + expect((await port.getIdentityFresh('me'))?.publicKeys.map((k) => k.id)).toEqual([4]) + expect(await port.remainingBudgets('me', [4, 5])).toEqual(new Map([[4, 7n], [5, undefined]])) + expect((await port.contractKeys('me', CONTRACT, 1)).map((k) => k.id)).toEqual([2]) + expect(await port.groupInfo(GROUP)).toBeNull() + expect(await port.chainClock()).toEqual({ protocolVersion: 14, timeMs: 1_800_000_000_000 }) + }) +}) diff --git a/forge-web/lib/auth/app-connect-port.ts b/forge-web/lib/auth/app-connect-port.ts new file mode 100644 index 000000000..eac0459b6 --- /dev/null +++ b/forge-web/lib/auth/app-connect-port.ts @@ -0,0 +1,195 @@ +/** + * App Connect v2's chain reads (the vendored verifier's and poller's ports, + * `lib/vendor/platform-auth/app-connect`) over Forge's SDK connection, plus the chain clock the + * request and the verifier use (`docs/design/wallet-login.md`, App Connect v2). + * + * Every read is a proved SDK read, and identity reads go to the network directly (the SDK keeps + * no identity cache): a key a wallet added moments ago is exactly what the verifier checks. + * Forge binds no contract group by request member list (its group trust is `./group-trust`), so + * `groupInfo` has nothing to read; the verifier never calls it. + */ + +import { hexToBytes } from '@noble/hashes/utils.js' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { authSdk, type WasmKey } from '../sdk/facade' +import { base64ToBytes, bytesToBase64 } from '../sdk/query' +import type { + AppConnectCandidate, + AppConnectIdentityKey, + AppConnectIdentityPort, + AppConnectKeyBounds, + AppConnectResponsePort, +} from '../vendor/platform-auth/app-connect' +import { APP_CONNECT_CONTRACT_ID } from './app-connect' +import { base58Decode, decodeIdentifier } from './base58' + +/** The latest block's time and protocol version, from a proved response's metadata. */ +export interface ChainClock { + readonly protocolVersion: number + readonly timeMs: number +} + +export interface AppConnectPort extends AppConnectIdentityPort, AppConnectResponsePort { + chainClock(): Promise +} + +/** Bytes from a key's data as the SDK hands it back: hex (the wasm getter) or bytes. */ +function keyData(value: unknown): Uint8Array | null { + if (value instanceof Uint8Array) return value + return typeof value === 'string' && /^(?:[0-9a-f]{2})+$/i.test(value) ? hexToBytes(value) : null +} + +/** A key's bounds; undefined when it has none, null when they cannot be read. */ +function keyBounds(k: Pick): AppConnectKeyBounds | undefined | null { + if (!k.contractBounds) return undefined + let json: { $type?: unknown; id?: unknown; documentTypeName?: unknown } + try { + json = k.contractBounds.toJSON() + } catch { + return null + } + if (typeof json.id !== 'string') return null + switch (json.$type) { + case 'singleContract': + return { kind: 'singleContract', contractId: json.id } + case 'documentType': + return typeof json.documentTypeName === 'string' ? { kind: 'documentType', contractId: json.id, documentTypeName: json.documentTypeName } : null + case 'contractGroup': + return { kind: 'contractGroup', groupId: json.id } + default: + return null + } +} + +/** + * A wasm key in the verifier's shape (ported from EvoVote `keyMapping.ts`), or null when it + * cannot be read faithfully (no key type, undecodable data, unknown bounds). The caller drops a + * null key: an unreadable bound must never look unbound, so such a key can neither verify nor + * be matched. + */ +export function toAppConnectKey(k: WasmKey): AppConnectIdentityKey | null { + const data = keyData(k.data) + const bounds = keyBounds(k) + if (k.keyTypeNumber === undefined || data === null || bounds === null) return null + return { + id: k.keyId, + type: k.keyTypeNumber, + purpose: k.purposeNumber, + securityLevel: k.securityLevelNumber, + data, + ...(k.disabledAt !== undefined ? { disabledAt: Number(k.disabledAt) } : {}), + ...(bounds !== undefined ? { bounds } : {}), + ...(k.totalBudget !== undefined ? { totalBudget: k.totalBudget } : {}), + ...(k.expiresAt !== undefined ? { expiresAt: Number(k.expiresAt) } : {}), + } +} + +/** Every key mapped, the unreadable ones dropped. */ +export function toAppConnectKeys(keys: readonly WasmKey[]): AppConnectIdentityKey[] { + return keys.flatMap((k) => { + const mapped = toAppConnectKey(k) + return mapped ? [mapped] : [] + }) +} + +/** Byte order of two base58 ids, as Platform orders `$ownerId`. */ +export function compareIds(a: string, b: string): number { + const left = base58Decode(a) + const right = base58Decode(b) + for (let i = 0; i < Math.min(left.length, right.length); i++) { + const d = (left[i] ?? 0) - (right[i] ?? 0) + if (d !== 0) return d + } + return left.length - right.length +} + +interface ResponseJson { + $ownerId?: unknown + walletEphemeralPubKey?: unknown + encryptedPayload?: unknown +} + +function bytesOr(value: unknown): Uint8Array { + if (typeof value !== 'string') return new Uint8Array(0) + try { + return base64ToBytes(value) + } catch { + return new Uint8Array(0) + } +} + +/** + * A `loginKeyResponse` row as a candidate. A row whose bytes do not read is still returned, with + * empty bytes (the verifier refuses it as `framing`): dropping it would shorten the page, and + * the poller takes a short page for the last one. A row without a readable owner (only a node + * that lies can return one) is a read Forge cannot use: it throws, so the round counts as + * incomplete rather than as one more identity answering. + */ +export function candidateOf(json: ResponseJson): AppConnectCandidate { + if (typeof json.$ownerId !== 'string' || !isIdentifier(json.$ownerId)) throw new Error('an App Connect answer has no readable owner') + return { ownerId: json.$ownerId, walletEphemeralPubKey: bytesOr(json.walletEphemeralPubKey), encryptedPayload: bytesOr(json.encryptedPayload) } +} + +function isIdentifier(id: string): boolean { + try { + decodeIdentifier(id) + return true + } catch { + return false + } +} + +/** The App Connect ports over `sdk`. */ +export function appConnectPort(sdk: EvoSDK): AppConnectPort { + const api = authSdk(sdk) + return { + async getIdentityFresh(identityId) { + const identity = await api.identities.fetch(identityId) + // A proved fetch by id: the identity returned is the one asked for. + return identity ? { id: identityId, publicKeys: toAppConnectKeys(identity.publicKeys) } : null + }, + + async remainingBudgets(identityId, keyIds) { + const budgets = await api.identities.keysRemainingBudgets(identityId, keyIds) + const out = new Map() + for (const [keyId, remaining] of budgets) out.set(Number(keyId), remaining ?? undefined) + return out + }, + + async contractKeys(identityId, contractId, purpose) { + const entries = await api.identities.contractKeys({ identityIds: [identityId], contractId, purposes: [purpose] }) + const entry = entries.find((e) => e.identityId.toBase58() === identityId) + return entry ? toAppConnectKeys(entry.keys) : [] + }, + + async groupInfo() { + return null + }, + + async listCandidates(requestHash, hint, startAfter, limit) { + const where: unknown[][] = [['appEphemeralPubKeyHash', '==', bytesToBase64(requestHash)]] + if (hint !== undefined) where.push(['$ownerId', '==', hint]) + else if (startAfter !== undefined) where.push(['$ownerId', '>', startAfter]) + const rows = await api.documents.query({ + dataContractId: APP_CONNECT_CONTRACT_ID, + documentTypeName: 'loginKeyResponse', + where, + // The (appEphemeralPubKeyHash, $ownerId) index, as the v1 poll reads it (`./app-connect`). + orderBy: [ + ['appEphemeralPubKeyHash', 'asc'], + ['$ownerId', 'asc'], + ], + limit, + }) + const candidates = [...rows.values()].filter(Boolean).map((r) => candidateOf((r as { toJSON(): ResponseJson }).toJSON())) + // The poller relies on owner order; Platform returns it, but a Map's order is the SDK's. + return candidates.sort((a, b) => compareIds(a.ownerId, b.ownerId)) + }, + + async chainClock() { + const { metadata } = await api.protocol.versionUpgradeStateWithProof() + return { protocolVersion: metadata.protocolVersion, timeMs: Number(metadata.timeMs) } + }, + } +} diff --git a/forge-web/lib/auth/app-connect-v2.test.ts b/forge-web/lib/auth/app-connect-v2.test.ts new file mode 100644 index 000000000..09bbb8d14 --- /dev/null +++ b/forge-web/lib/auth/app-connect-v2.test.ts @@ -0,0 +1,395 @@ +/** + * App Connect v2 sign-in, offline: Forge's request against the vendored parser (bytes, callback, + * renewal), and the poll against a simulated v2 wallet (`./wallet-sim` `answerV2`) on a fake + * chain: the verifier's accepts and refusals, two answerers, and a key a node shows late. + */ + +import * as secp from '@noble/secp256k1' +import { ripemd160 } from '@noble/hashes/legacy.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex } from '@noble/hashes/utils.js' +import type { EvoSDK } from '@dashevo/evo-sdk' +import { describe, expect, it } from 'vitest' + +import type { ForgeIds } from '../deployments' +import { CREDITS_PER_DASH } from '../sdk/cost' +import { bytesToBase64 } from '../sdk/query' +import { AppConnectTlv, KeySecurityLevel, parseAppConnectUri } from '../vendor/platform-auth/app-connect' +import { AmbiguousWalletLogin, APP_CONNECT_CONTRACT_ID, RequestExpired } from './app-connect' +import { + APP_CONNECT_LABEL, + PollTrigger, + TooManyAnswers, + WalletGrantRefused, + awaitV2Grant, + forgeV2Request, + newV2LoginRequest, + type V2LoginRequest, +} from './app-connect-v2' +import { compareIds } from './app-connect-port' +import { base58Decode, base58Encode } from './base58' +import { isUnlimited } from './key-registration' +import { answerV2 } from './wallet-sim' +import { decodeWif } from './wif' + +const FORGE: ForgeIds = { + core: 'A2KL77ngVM1ft1t1em2XKt1rWCBZANdAJMyfWrDGCcd1', + collab: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + community: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + group: '6dV3kMBWHGR7pLKrHToMBQgbTpjqeE2VAyCEWmLbrkWC', +} +const OTHER_GROUP = 'Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7' +const ALICE = 'HwhCv9N5BHsbGNLzDR4tnZnqJ6VxtwJSLsM4aUWn2Tnr' +const MALLORY = 'CJao2MVHL4x3f2Ko2xTUibnZ8G1t9exTPtvJnCbHAgDH' +const CONNECTION = new Uint8Array(16).fill(7) +const DAY = 24 * 60 * 60 * 1000 + +/** The TLVs after the fixed header (version, key, app id, label), as [type, value]. */ +function tlvs(body: Uint8Array): [number, Uint8Array][] { + let at = 1 + 33 + 32 + at += 1 + (body[at] as number) + const out: [number, Uint8Array][] = [] + while (at < body.length) { + const type = body[at] as number + const len = body[at + 1] as number + out.push([type, body.slice(at + 2, at + 2 + len)]) + at += 2 + len + } + return out +} + +describe('the request Forge makes', () => { + const chainNow = Date.UTC(2026, 9, 24) + + it('asks for one group-bound HIGH key with Forge’s default limits: 157 bytes', () => { + const req = newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow, now: chainNow + 5000 }) + const { request, requestBytes, network, callbackUrl } = parseAppConnectUri(req.qrUri) + expect(network).toBe('devnet') + expect(callbackUrl).toBeUndefined() + expect(requestBytes.length).toBe(157) + expect(request.label).toBe(APP_CONNECT_LABEL) + expect(bytesToHex(request.appId)).toBe(bytesToHex(base58Decode(FORGE.core))) + expect(request.encBindings).toEqual([]) + expect(request.authBindings).toHaveLength(1) + const binding = request.authBindings[0]! + expect(binding.kind).toBe('contractGroup') + expect(bytesToHex(binding.id)).toBe(bytesToHex(base58Decode(FORGE.group))) + expect(binding.securityLevel).toBe(KeySecurityLevel.HIGH) + expect(binding.totalBudget).toBe(BigInt(0.05 * CREDITS_PER_DASH)) + // Expiry from chain time; CREATED_AT from this device's clock. + expect(binding.expiresAt).toBe(chainNow + 90 * DAY) + expect(request.createdAt).toBe(chainNow + 5000) + expect(bytesToHex(request.connectionId!)).toBe(bytesToHex(CONNECTION)) + const types = tlvs(requestBytes).map(([t, v]) => [t, v.length + 2]) + expect(types).toEqual([ + [AppConnectTlv.AUTH_BINDING, 52], + [AppConnectTlv.CONNECTION_ID, 18], + [AppConnectTlv.CREATED_AT, 10], + ]) + // Answers are stored under hash160 of the request's ephemeral key. + expect(bytesToHex(req.requestHash)).toBe(bytesToHex(ripemd160(sha256(request.appEphemeralPubKey)))) + expect(req.expiresAt - req.createdAt).toBe(10 * 60 * 1000) + }) + + it('puts the callback on the deep link only', () => { + let seen: Uint8Array | null = null + const req = newV2LoginRequest('devnet', FORGE, { + connectionId: CONNECTION, + chainNow, + callbackUrl: (hash) => { + seen = hash + return `https://forge.dashhq.org/connect/?r=${bytesToHex(hash)}` + }, + }) + expect(bytesToHex(seen!)).toBe(bytesToHex(req.requestHash)) + expect(req.qrUri).not.toContain('cb=') + const link = parseAppConnectUri(req.linkUri) + expect(link.callbackUrl).toBe(`https://forge.dashhq.org/connect/?r=${bytesToHex(req.requestHash)}`) + // One request: the same bytes behind both. + expect(bytesToHex(link.requestBytes)).toBe(bytesToHex(parseAppConnectUri(req.qrUri).requestBytes)) + const none = newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow, callbackUrl: () => null }) + expect(none.linkUri).toBe(none.qrUri) + }) + + it('renews with the identity as hint and the same connection id, and no MODE', () => { + const login = forgeV2Request(FORGE, { appEphemeralPubKey: secp.getPublicKey(secp.utils.randomSecretKey(), true), connectionId: CONNECTION, chainNow, now: chainNow }) + const req = newV2LoginRequest('testnet', FORGE, { connectionId: CONNECTION, chainNow, identityHint: ALICE }) + const { request, requestBytes } = parseAppConnectUri(req.qrUri) + expect(req.identityHint).toBe(ALICE) + expect(bytesToHex(request.identityHint!)).toBe(bytesToHex(base58Decode(ALICE))) + expect(bytesToHex(request.connectionId!)).toBe(bytesToHex(login.connectionId!)) + expect(request.mode).toBeUndefined() + expect(tlvs(requestBytes).map(([t]) => t)).toEqual([AppConnectTlv.IDENTITY_HINT, AppConnectTlv.AUTH_BINDING, AppConnectTlv.CONNECTION_ID, AppConnectTlv.CREATED_AT]) + expect(requestBytes.length).toBe(157 + 34) + }) +}) + +// --------------------------------------------------------------------------- +// The poll against a simulated v2 wallet +// --------------------------------------------------------------------------- + +interface ChainKey { + keyId: number + priv: Uint8Array + bounds: { $type: string; id: string } | null + securityLevelNumber?: number + totalBudget?: bigint + expiresAt?: bigint + disabledAt?: bigint +} + +/** A fake SDK: identities with keys (as wasm reads them), and App Connect answers. */ +function fakeChain() { + const identities = new Map() + const docs: Record[] = [] + let queries = 0 + const sdk = { + identities: { + async fetch(id: string) { + const keys = identities.get(id) + if (!keys) return undefined + return { + balance: 10n ** 11n, + revision: 1n, + publicKeys: keys.map((k) => ({ + keyId: k.keyId, + keyTypeNumber: 0, + data: bytesToHex(secp.getPublicKey(k.priv, true)), + purposeNumber: 0, + securityLevelNumber: k.securityLevelNumber ?? 2, + disabledAt: k.disabledAt, + totalBudget: k.totalBudget, + expiresAt: k.expiresAt, + contractBounds: k.bounds ? { toJSON: () => k.bounds } : undefined, + validatePrivateKey: (bytes: Uint8Array) => bytesToHex(bytes) === bytesToHex(k.priv), + })), + } + }, + async keysRemainingBudgets(id: string, ids: number[]) { + const keys = identities.get(id) ?? [] + return new Map(ids.map((i) => [i, keys.find((k) => k.keyId === i)?.totalBudget ?? null])) + }, + }, + documents: { + async query(q: { dataContractId: string; where: [string, string, string][]; limit?: number }) { + queries++ + const hash = q.where.find((w) => w[0] === 'appEphemeralPubKeyHash')?.[2] + const owner = q.where.find((w) => w[0] === '$ownerId' && w[1] === '==')?.[2] + const after = q.where.find((w) => w[0] === '$ownerId' && w[1] === '>')?.[2] + const rows = docs + .filter((d) => q.dataContractId === APP_CONNECT_CONTRACT_ID && d['appEphemeralPubKeyHash'] === hash) + .filter((d) => owner === undefined || d['$ownerId'] === owner) + .filter((d) => after === undefined || compareIds(String(d['$ownerId']), after) > 0) + .sort((a, b) => compareIds(String(a['$ownerId']), String(b['$ownerId']))) + .slice(0, q.limit ?? 100) + // Reversed: the port must not rely on the SDK's map order. + return new Map(rows.reverse().map((r, i) => [String(i), { toJSON: () => r }])) + }, + }, + } + /** + * A v2 wallet approving `uri` for `identityId`: registers a fresh key (unless `register` is + * false) with the limits asked for, overridden by `register`, and publishes its answer. + */ + async function approve(uri: string, identityId: string, register: Partial | false = {}) { + const { request } = parseAppConnectUri(uri) + const binding = request.authBindings[0]! + const priv = secp.utils.randomSecretKey() + const keys = identities.get(identityId) ?? [{ keyId: 0, priv: new Uint8Array(32).fill(0x77), bounds: null, securityLevelNumber: 0 }] + identities.set(identityId, keys) + const chainKey: ChainKey = { + keyId: keys.length, + priv, + bounds: { $type: 'contractGroup', id: FORGE.group }, + totalBudget: binding.totalBudget, + expiresAt: BigInt(binding.expiresAt!), + ...(register || {}), + } + if (register !== false) keys.push(chainKey) + const answer = await answerV2(uri, { ownerId: identityId, slots: [priv] }) + docs.push({ + $ownerId: identityId, + appEphemeralPubKeyHash: bytesToBase64(answer.requestHash), + walletEphemeralPubKey: bytesToBase64(answer.walletEphemeralPubKey), + encryptedPayload: bytesToBase64(answer.encryptedPayload), + }) + return { priv, register: () => keys.push(chainKey) } + } + return { sdk: sdk as unknown as EvoSDK, identities, docs, approve, queries: () => queries } +} + +const fast = { network: 'devnet' as const, forge: FORGE, intervalMs: 1, settleMs: 0 } +const request = (identityHint?: string): V2LoginRequest => + newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow: Date.now(), ...(identityHint ? { identityHint } : {}) }) + +describe('v2 poll against a simulated wallet', () => { + it('accepts a group-bound HIGH key with a budget and an expiry, as Forge’s own wallet key', async () => { + const chain = fakeChain() + const req = request() + const { priv } = await chain.approve(req.qrUri, ALICE) + const grant = await awaitV2Grant(chain.sdk, req, fast) + expect(grant.identityId).toBe(ALICE) + expect(grant.key.keyId).toBe(1) + expect(grant.key.scope).toEqual({ core: true, collab: true, community: true, meta: true, unbounded: false }) + expect(isUnlimited(grant.key)).toBe(false) + expect(grant.key.limits?.total).toBe(BigInt(0.05 * CREDITS_PER_DASH)) + expect(bytesToHex(decodeWif(grant.key.wif).privateKey)).toBe(bytesToHex(priv)) + // The request is spent. + expect(req.appEphemeralPriv.every((b) => b === 0)).toBe(true) + }) + + it('takes a budget the wallet raised (its presets start at 0.1 DASH)', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE, { totalBudget: BigInt(0.1 * CREDITS_PER_DASH) }) + const grant = await awaitV2Grant(chain.sdk, req, fast) + expect(grant.key.limits?.total).toBe(BigInt(0.1 * CREDITS_PER_DASH)) + }) + + it.each([ + ['a key without a budget', { totalBudget: undefined }, 'key-limits'], + ['a CRITICAL key', { securityLevelNumber: 1 }, 'key-level'], + ['a key bound to another group', { bounds: { $type: 'contractGroup', id: OTHER_GROUP } }, 'key-unmatched'], + ['a key expiring within the hour', { expiresAt: BigInt(Date.now() + 30 * 60 * 1000) }, 'key-expired'], + ['a disabled key', { disabledAt: 1n }, 'key-disabled'], + ] as const)('refuses %s', async (_what, register, reason) => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE, register) + const outcome = awaitV2Grant(chain.sdk, req, fast) + await expect(outcome).rejects.toBeInstanceOf(WalletGrantRefused) + await expect(outcome).rejects.toMatchObject({ reason }) + }) + + it('refuses when two identities answer (someone else saw the QR)', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE) + await chain.approve(req.qrUri, MALLORY) + await expect(awaitV2Grant(chain.sdk, req, fast)).rejects.toBeInstanceOf(AmbiguousWalletLogin) + }) + + it('waits out the settle window: a second answer inside it is refused', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE) + let late: Promise | null = null + const outcome = awaitV2Grant(chain.sdk, req, { + ...fast, + settleMs: 5_000, + onStatus: (s) => { + // ALICE's answer is verified; MALLORY answers while Forge waits for competitors. + if (s === 'answered' && late === null) late = chain.approve(req.qrUri, MALLORY) + }, + }) + await expect(outcome).rejects.toBeInstanceOf(AmbiguousWalletLogin) + expect(late).not.toBeNull() + }) + + it('checks expiry against chain time, not this device’s clock', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE) + const expiresAt = Number(chain.identities.get(ALICE)![1]!.expiresAt) + // The chain is 30 minutes from the key's expiry while this device's clock is 90 days before it. + const late = { ...req, chainTimeAtCreation: expiresAt - 30 * 60 * 1000 } + await expect(awaitV2Grant(chain.sdk, late, fast)).rejects.toMatchObject({ reason: 'key-expired' }) + }) + + it('counts an answer whose key no node shows yet: a quick stranger does not win', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE, false) + await chain.approve(req.qrUri, MALLORY) + await expect(awaitV2Grant(chain.sdk, req, fast)).rejects.toBeInstanceOf(AmbiguousWalletLogin) + }) + + it('checks again when the key is not shown yet (key-not-found), and accepts it once it is', async () => { + const chain = fakeChain() + const req = request() + const { register } = await chain.approve(req.qrUri, ALICE, false) + const statuses: string[] = [] + const grant = awaitV2Grant(chain.sdk, req, { + ...fast, + onStatus: (s) => { + statuses.push(s) + // A few polls later the node shows the key. + if (statuses.length === 3) register() + }, + }) + expect((await grant).identityId).toBe(ALICE) + expect(statuses.slice(0, 3)).toEqual(['waiting', 'waiting', 'waiting']) + }) + + it('ignores answers not encrypted to this request', async () => { + const chain = fakeChain() + const req = request() + const other = request() + await chain.approve(other.qrUri, MALLORY) + // MALLORY's answer to another request, relabelled as an answer to this one. + chain.docs[0]!['appEphemeralPubKeyHash'] = bytesToBase64(req.requestHash) + await chain.approve(req.qrUri, ALICE) + expect((await awaitV2Grant(chain.sdk, req, fast)).identityId).toBe(ALICE) + }) + + it('a renewal reads only the named identity, and its refusal is final at once', async () => { + const chain = fakeChain() + const req = request(ALICE) + await chain.approve(req.qrUri, MALLORY) + await chain.approve(req.qrUri, ALICE) + expect((await awaitV2Grant(chain.sdk, req, { ...fast, settleMs: 60_000 })).identityId).toBe(ALICE) + + const chain2 = fakeChain() + const req2 = request(ALICE) + await chain2.approve(req2.qrUri, ALICE, { securityLevelNumber: 1 }) + await expect(awaitV2Grant(chain2.sdk, req2, fast)).rejects.toMatchObject({ reason: 'key-level' }) + }) + + it('stops when more answers arrive than it reads (junk)', async () => { + const chain = fakeChain() + const req = request() + for (let i = 0; i < 21; i++) { + const id = base58Encode(new Uint8Array(32).fill(i + 1)) + chain.docs.push({ $ownerId: id, appEphemeralPubKeyHash: bytesToBase64(req.requestHash), walletEphemeralPubKey: bytesToBase64(new Uint8Array(33)), encryptedPayload: bytesToBase64(new Uint8Array(60)) }) + } + await expect(awaitV2Grant(chain.sdk, req, fast)).rejects.toBeInstanceOf(TooManyAnswers) + }) + + it('does not settle on a round that could not read the answers', async () => { + const chain = fakeChain() + const req = { ...request(), expiresAt: Date.now() + 60 } + await chain.approve(req.qrUri, ALICE) + ;(chain.sdk as unknown as { documents: { query: () => Promise } }).documents.query = () => Promise.reject(new Error('node refused')) + const statuses: string[] = [] + await expect(awaitV2Grant(chain.sdk, req, { ...fast, onStatus: (s) => statuses.push(s) })).rejects.toBeInstanceOf(RequestExpired) + expect(statuses).toContain('incomplete-read') + }) + + it('polls at once when triggered, and expires', async () => { + const chain = fakeChain() + const trigger = new PollTrigger() + const req = request() + const before = chain.queries() + const outcome = awaitV2Grant(chain.sdk, req, { network: 'devnet', forge: FORGE, trigger, settleMs: 0 }) + await new Promise((r) => setTimeout(r, 20)) + trigger.fire() + await new Promise((r) => setTimeout(r, 20)) + // Two polls in well under the 2 s cadence: the second was the trigger's. + expect(chain.queries() - before).toBe(2) + await chain.approve(req.qrUri, ALICE) + trigger.fire() + expect((await outcome).identityId).toBe(ALICE) + + const stale = newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow: Date.now(), now: Date.now() - 10 * 60 * 1000 - 1 }) + await expect(awaitV2Grant(chain.sdk, stale, fast)).rejects.toBeInstanceOf(RequestExpired) + expect(stale.appEphemeralPriv.every((b) => b === 0)).toBe(true) + }) + + it('stops on abort', async () => { + const chain = fakeChain() + const ac = new AbortController() + const outcome = awaitV2Grant(chain.sdk, request(), { network: 'devnet', forge: FORGE, signal: ac.signal }) + ac.abort() + await expect(outcome).rejects.toMatchObject({ name: 'AbortError' }) + }) +}) diff --git a/forge-web/lib/auth/app-connect-v2.ts b/forge-web/lib/auth/app-connect-v2.ts new file mode 100644 index 000000000..57ac79ce8 --- /dev/null +++ b/forge-web/lib/auth/app-connect-v2.ts @@ -0,0 +1,399 @@ +/** + * "Use my Dash wallet" with App Connect v2 (`APP_CONNECT_PROFILE.md`; docs/design/wallet-login.md, + * "Upgrade path"), beside the v1 flow in {@link ./app-connect}, which stays as it is: a wallet that + * speaks only v1 refuses a `v=2` request, so the two never share a QR code. + * + * One request asks for ONE key: AUTHENTICATION / HIGH, bound to the dash-forge contract group, with + * Forge's default budget and expiry ({@link defaultLimits}, from chain time). It covers every Forge + * contract, so no further grants are asked for. The request's app is forge-core (its owner is the + * group's owner, as the profile's owner rule needs); no encryption key is asked for, since no Forge + * contract allows a wallet-issued one (members-only content is set up in Settings). + * + * A wallet that approves registers the key (disabling the key of its previous grant for this + * browser's connection id, `./connection-id`) and publishes a `loginKeyResponse` in the App + * Connect contract under its identity. The poll pages through every answer, opens each with the + * request's ephemeral key and checks it with the vendored verifier (live key on the answering + * identity, exactly the bounds, level and limits asked for, not about to expire or spent), then + * once more with Forge's own rules ({@link findWalletKey}), which yields the {@link WalletKey} the + * controller stores (`adoptWalletKeys`, origin `app-connect`) like any wallet key. + * + * Who answered is not proven (anyone who saw the QR can answer from their own identity): two + * answers are refused, and without an identity hint the UI asks "Continue as …?". A renewal names + * the identity (`IDENTITY_HINT`) and carries the same connection id, and no `MODE`: wallets do not + * know `MODE` = renew yet, and its type is even, so a wallet that does not know it refuses the + * whole request. + * + * Clocks: `CREATED_AT` is this device's clock (the wallet compares it with its own); the proposed + * expiry and the verifier's "now" are chain time (the latest block's), falling back to this + * device's clock when it cannot be read. + */ + +import * as secp from '@noble/secp256k1' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { NETWORKS, type Network } from '../constants' +import { withTimeout } from '../timeout' +import type { ForgeIds } from '../deployments' +import { + APP_CONNECT_MAX_REQUEST_AGE_MS, + KeySecurityLevel, + appConnectCandidateKey, + appConnectPollDelayMs, + appConnectRequestHash, + buildAppConnectUri, + listAppConnectCandidates, + verifyAppConnectCandidate, + type AppConnectGrant, + type AppConnectRejectReason, + type AppConnectRequest, +} from '../vendor/platform-auth/app-connect' +import { AmbiguousWalletLogin, RequestExpired, type PollStatus } from './app-connect' +import { appConnectPort } from './app-connect-port' +import { decodeIdentifier } from './base58' +import { PLATFORM_READ_MS } from './connect' +import { findWalletKey, isUnlimited, RevokedWalletKey, UnusableWalletKey, type WalletKey } from './key-registration' +import { defaultLimits } from './limited-key' +import { encodeWif } from './wif' + +/** The name a wallet shows for Forge. */ +export const APP_CONNECT_LABEL = 'Dash Forge' + +/** + * Whether a renewal carries `MODE` = renew. Off: no wallet supports it yet, and a wallet that + * does not know the (even, so mandatory) type refuses the request. A renewal is a new grant for + * the same identity and connection id instead, which disables the old key. + */ +export const RENEW_MODE = false + +/** The App Connect contract and v2 requests exist from protocol 14. */ +export const APP_CONNECT_MIN_PROTOCOL = 14 + +/** The request Forge makes: one group-bound HIGH key with Forge's default limits. */ +export function forgeV2Request( + forge: ForgeIds, + p: { + readonly appEphemeralPubKey: Uint8Array + readonly connectionId: Uint8Array + /** Chain time (ms): the proposed expiry counts from it. */ + readonly chainNow: number + /** This device's clock (ms): `CREATED_AT`. */ + readonly now: number + /** The identity a renewal is for. */ + readonly identityHint?: string + }, +): AppConnectRequest { + const limits = defaultLimits(p.chainNow) + return { + appEphemeralPubKey: p.appEphemeralPubKey, + appId: decodeIdentifier(forge.core), + label: APP_CONNECT_LABEL, + authBindings: [ + { + kind: 'contractGroup', + id: decodeIdentifier(forge.group), + securityLevel: KeySecurityLevel.HIGH, + totalBudget: limits.budgetCredits, + expiresAt: limits.expiresAt, + }, + ], + encBindings: [], + createdAt: p.now, + connectionId: p.connectionId, + ...(p.identityHint !== undefined ? { identityHint: decodeIdentifier(p.identityHint) } : {}), + ...(RENEW_MODE && p.identityHint !== undefined ? { mode: 'renew' as const } : {}), + } +} + +export interface V2LoginRequest { + readonly request: AppConnectRequest + /** For the QR code: no callback (a shorter code, and the phone has no Forge tab to return to). */ + readonly qrUri: string + /** For a wallet on this device: the same request, with the callback when one was given. */ + readonly linkUri: string + /** `hash160(appEphemeralPub)`: what the answers are stored under (the callback's `r`). */ + readonly requestHash: Uint8Array + /** `CREATED_AT`, this device's clock (ms). */ + readonly createdAt: number + /** When the poll stops: the protocol's 10 minutes after `createdAt`. */ + readonly expiresAt: number + /** Chain time at `createdAt`: the verifier's clock is this plus the time elapsed here. */ + readonly chainTimeAtCreation: number + /** The identity a renewal is for (`IDENTITY_HINT`); null for a sign-in. */ + readonly identityHint: string | null + /** Held only in memory; zeroed by {@link disposeV2Request}. */ + readonly appEphemeralPriv: Uint8Array +} + +/** + * A fresh v2 request. `callbackUrl` builds the deep link's `cb` from the request hash (null: + * none); only {@link V2LoginRequest.linkUri} carries it. + */ +export function newV2LoginRequest( + network: Network, + forge: ForgeIds, + p: { + readonly connectionId: Uint8Array + readonly chainNow: number + readonly identityHint?: string + readonly now?: number + readonly callbackUrl?: (requestHash: Uint8Array) => string | null + }, +): V2LoginRequest { + const now = p.now ?? Date.now() + const priv = secp.utils.randomSecretKey() + const request = forgeV2Request(forge, { + appEphemeralPubKey: secp.getPublicKey(priv, true), + connectionId: p.connectionId, + chainNow: p.chainNow, + now, + ...(p.identityHint !== undefined ? { identityHint: p.identityHint } : {}), + }) + const requestHash = appConnectRequestHash(request) + const callback = p.callbackUrl?.(requestHash) + const qrUri = buildAppConnectUri(request, network) + return { + request, + qrUri, + linkUri: callback ? buildAppConnectUri(request, network, callback) : qrUri, + requestHash, + createdAt: now, + expiresAt: now + APP_CONNECT_MAX_REQUEST_AGE_MS, + chainTimeAtCreation: p.chainNow, + identityHint: p.identityHint ?? null, + appEphemeralPriv: priv, + } +} + +export function disposeV2Request(req: V2LoginRequest): void { + req.appEphemeralPriv.fill(0) +} + +/** Chain time (ms) and protocol version; this device's clock and null when the read fails. */ +export async function readChainClock(sdk: EvoSDK): Promise<{ readonly timeMs: number; readonly protocolVersion: number | null }> { + try { + const clock = await withTimeout(appConnectPort(sdk).chainClock(), PLATFORM_READ_MS, 'Reading the time on Platform') + if (Number.isSafeInteger(clock.timeMs) && clock.timeMs > 0) return clock + } catch { + /* fall back below */ + } + return { timeMs: Date.now(), protocolVersion: null } +} + +/** + * Whether a v2 request can be offered here: Forge is deployed on the network (its contract group + * exists) and the chain runs protocol 14 or later. The caller also runs the group check + * (`AuthController.checkGroup`) before showing a code. + */ +export async function appConnectV2Available(sdk: EvoSDK, network: Network): Promise { + if (NETWORKS[network].v2 === null) return false + const { protocolVersion } = await readChainClock(sdk) + return protocolVersion !== null && protocolVersion >= APP_CONNECT_MIN_PROTOCOL +} + +/** Why Forge refused a wallet's v2 answer, in a user's words. */ +const REFUSED: Partial> = { + 'key-disabled': 'The key your wallet sent is already disabled.', + 'key-expired': 'The key your wallet sent expires within the hour.', + 'budget-exhausted': 'The key your wallet sent has no budget left.', + 'key-limits': 'The key your wallet sent has no spending limit or no expiry.', + 'key-level': 'The key your wallet sent can do more than Forge asked for.', + 'key-master': 'Your wallet sent its master key.', + 'key-unmatched': 'The key your wallet sent is for something other than Dash Forge.', + 'key-unbound': 'The key your wallet sent is not limited to Dash Forge.', +} + +/** A wallet's v2 answer that Forge will not use (the verifier's `reason`). */ +export class WalletGrantRefused extends UnusableWalletKey { + constructor(readonly reason: AppConnectRejectReason) { + super(`${REFUSED[reason] ?? "Your wallet's answer doesn't match what Forge asked for."} Forge didn't use it. Start again; if it happens again, sign in another way.`) + this.name = 'WalletGrantRefused' + } +} + +/** More answers reached the request than Forge reads (junk): it cannot tell which is the user's. */ +export class TooManyAnswers extends Error { + constructor() { + super("So many answers reached this sign-in request that Forge can't check them all. Start again and keep the QR code private.") + this.name = 'TooManyAnswers' + } +} + +/** + * Cuts the poll's wait short: the UI fires it when the tab regains focus or the wallet's callback + * page says it answered. A fire while nothing waits makes the next wait return at once. + */ +export class PollTrigger { + private wake: (() => void) | null = null + private pending = false + + fire(): void { + if (this.wake) this.wake() + else this.pending = true + } + + /** Wait `ms`, or until fired; rejects with AbortError on `signal`. */ + wait(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new DOMException('cancelled', 'AbortError')) + return + } + if (this.pending) { + this.pending = false + resolve() + return + } + const end = (): void => { + clearTimeout(t) + signal?.removeEventListener('abort', onAbort) + this.wake = null + } + const onAbort = (): void => { + end() + reject(new DOMException('cancelled', 'AbortError')) + } + const t = setTimeout(() => { + end() + resolve() + }, ms) + this.wake = () => { + end() + resolve() + } + signal?.addEventListener('abort', onAbort, { once: true }) + }) + } +} + +/** A verified v2 grant: the answering identity and its key, checked by Forge's own rules. */ +export interface V2Grant { + readonly identityId: string + readonly key: WalletKey +} + +/** Rejections that mean "not an answer to this request" (another request's, or tampered). */ +const NOT_AN_ANSWER: ReadonlySet = new Set(['decrypt', 'framing', 'hint-mismatch']) + +/** + * The verifier's grant as a {@link V2Grant}: its key as a WIF, read back and checked with + * {@link findWalletKey} (group-bound, AUTHENTICATION / HIGH, live, with its budget and expiry). + * Null when the node read does not show the key yet. The grant's private keys are zeroed. + */ +async function grantOf(sdk: EvoSDK, grant: AppConnectGrant, p: { readonly network: Network; readonly forge: ForgeIds }): Promise { + try { + const [main, ...others] = grant.authKeys + if (!main || others.length > 0 || grant.encryptionKeys.length > 0 || main.role !== 'contractGroup') throw new WalletGrantRefused('framing') + let key: WalletKey | null + try { + key = await findWalletKey(sdk, { identityId: grant.identityId, wif: encodeWif(main.privateKey, p.network), forge: p.forge, network: p.network }) + } catch (e) { + // Disabled since the verifier read it: v1's wording (a key derived the same every time) is wrong here. + throw e instanceof RevokedWalletKey ? new WalletGrantRefused('key-disabled') : e + } + if (key === null) return null + if (key.keyId !== main.key.id || isUnlimited(key) || key.scope.unbounded) throw new WalletGrantRefused('key-limits') + return { identityId: grant.identityId, key } + } finally { + for (const g of [...grant.authKeys, ...grant.encryptionKeys]) g.privateKey.fill(0) + } +} + +/** + * Poll the App Connect contract until an identity's answer to `req` is verified, then keep + * polling for `settleMs` for a competing answer before returning it; only rounds that read every + * answer count towards that window. Refuses ({@link AmbiguousWalletLogin}) when two identities + * answered: every answer that opens with this request's key counts, accepted or not, so an + * attacker's quick answer cannot win over the user's slow one. More answers than the poller reads + * is {@link TooManyAnswers}. + * + * A renewal (`req.identityHint`) reads only that identity's answer, so nothing can compete with + * it: no settle window, and its refusal is final at once. An answer whose key a node does not + * show yet (or whose budget it has not seen) is checked again on the next poll. + * + * Polls on the protocol's cadence ({@link appConnectPollDelayMs}: every 2 s for a minute, then + * every 4 s), at once when `trigger` fires. Rejects with {@link RequestExpired} after 10 minutes, + * AbortError on `signal`, {@link WalletGrantRefused} (or another {@link UnusableWalletKey}) for + * the sole answer Forge will not use. The request is spent either way ({@link disposeV2Request}). + */ +export async function awaitV2Grant( + sdk: EvoSDK, + req: V2LoginRequest, + p: { + readonly network: Network + readonly forge: ForgeIds + readonly signal?: AbortSignal + readonly trigger?: PollTrigger + readonly intervalMs?: number + readonly settleMs?: number + readonly now?: () => number + readonly onStatus?: (status: PollStatus) => void + }, +): Promise { + const now = p.now ?? Date.now + const hint = req.identityHint ?? undefined + const settleMs = hint !== undefined ? 0 : (p.settleMs ?? 3000) + const trigger = p.trigger ?? new PollTrigger() + const port = appConnectPort(sdk) + /** Per answering identity: its grant, null (check again), or why Forge will not use it. */ + const answered = new Map() + /** Every identity whose answer opened with this request's key. */ + const responders = new Set() + /** Answers already found not to be answers to this request, by exact contents. */ + const notAnswers = new Set() + let cleanSince = 0 + let firstAt = 0 + try { + for (;;) { + if (p.signal?.aborted) throw new DOMException('cancelled', 'AbortError') + // A failed read is never "no answers": the round does not count towards the settle window. + const page = await listAppConnectCandidates(port, req.requestHash, hint !== undefined ? { hint } : {}).catch(() => null) + if (page?.truncated) throw new TooManyAnswers() + const complete = page !== null + for (const c of page?.candidates ?? []) { + const prior = answered.get(c.ownerId) + if (prior !== undefined && prior !== null) continue + const contents = appConnectCandidateKey(c) + if (notAnswers.has(contents)) continue + let answer: V2Grant | UnusableWalletKey | null = null + try { + const chainNow = req.chainTimeAtCreation + (now() - req.createdAt) + const verdict = await verifyAppConnectCandidate({ request: req.request, appEphemeralPrivateKey: req.appEphemeralPriv, candidate: c, identity: port, now: chainNow }) + if (!verdict.ok && NOT_AN_ANSWER.has(verdict.reason)) { + notAnswers.add(contents) + continue + } + // It opened: this identity saw the QR and answered, whatever its key turns out to be. + responders.add(c.ownerId) + if (verdict.ok) answer = await grantOf(sdk, verdict.grant, { network: p.network, forge: p.forge }) + else if (!verdict.retryable) answer = new WalletGrantRefused(verdict.reason) + } catch (e) { + // Only reads fail past the decryption: this identity answered; check it again next poll. + responders.add(c.ownerId) + if (e instanceof UnusableWalletKey) answer = e + } + // The one identity a renewal listens to: its refusal is final. + if (answer instanceof UnusableWalletKey && hint !== undefined) throw answer + answered.set(c.ownerId, answer) + if (answer !== null && firstAt === 0) firstAt = now() + } + if (responders.size > 1) throw new AmbiguousWalletLogin([...responders]) + const t = now() + if (complete) { + if (cleanSince === 0) cleanSince = t + } else { + cleanSince = 0 + } + p.onStatus?.(!complete ? 'incomplete-read' : firstAt !== 0 ? 'answered' : 'waiting') + const only = [...answered.values()].find((a) => a !== null) + if (only && cleanSince !== 0 && t - Math.max(firstAt, cleanSince) >= settleMs) { + if (only instanceof UnusableWalletKey) throw only + return only + } + const delay = p.intervalMs ?? appConnectPollDelayMs(t - req.createdAt) + if (t >= req.expiresAt || delay === null) throw new RequestExpired() + await trigger.wait(delay, p.signal) + } + } finally { + disposeV2Request(req) + } +} diff --git a/forge-web/lib/auth/connection-id.test.ts b/forge-web/lib/auth/connection-id.test.ts new file mode 100644 index 000000000..83a418814 --- /dev/null +++ b/forge-web/lib/auth/connection-id.test.ts @@ -0,0 +1,61 @@ +// @vitest-environment jsdom +/** + * The App Connect state kept in localStorage: one connection id per network that outlives a + * sign-out, and a renewal marker that names one key and lapses. + */ + +import { bytesToHex } from '@noble/hashes/utils.js' +import { beforeEach, describe, expect, it } from 'vitest' + +import { clearWalletRenewal, connectionId, markWalletRenewal, walletRenewalInFlight } from './connection-id' + +const ID = 'HwhCv9N5BHsbGNLzDR4tnZnqJ6VxtwJSLsM4aUWn2Tnr' + +beforeEach(() => localStorage.clear()) + +describe('connection id', () => { + it('is 16 random bytes per network, made once and kept', () => { + const a = connectionId('devnet-sakura') + expect(a.length).toBe(16) + expect(bytesToHex(connectionId('devnet-sakura'))).toBe(bytesToHex(a)) + expect(bytesToHex(connectionId('testnet'))).not.toBe(bytesToHex(a)) + expect(localStorage.getItem('forge:app-connect:connection-id:devnet-sakura')).toBe(bytesToHex(a)) + }) + + it('replaces a malformed stored value', () => { + localStorage.setItem('forge:app-connect:connection-id:testnet', 'nope') + const id = connectionId('testnet') + expect(localStorage.getItem('forge:app-connect:connection-id:testnet')).toBe(bytesToHex(id)) + }) +}) + +describe('renewal marker', () => { + it('names one key of one identity and lapses', () => { + markWalletRenewal('testnet', ID, 7, 2_000) + expect(walletRenewalInFlight('testnet', ID, 7, 1_000)).toBe(true) + expect(walletRenewalInFlight('testnet', ID, 8, 1_000)).toBe(false) + expect(walletRenewalInFlight('devnet-sakura', ID, 7, 1_000)).toBe(false) + expect(walletRenewalInFlight('testnet', ID, 7, 2_000)).toBe(false) + clearWalletRenewal('testnet', ID) + expect(walletRenewalInFlight('testnet', ID, 7, 1_000)).toBe(false) + }) + + it('does not honour a mark that ends further out than a renewal can take (a clock set back)', () => { + markWalletRenewal('testnet', ID, 7, 1_000 + 21 * 60 * 1000) + expect(walletRenewalInFlight('testnet', ID, 7, 1_000)).toBe(false) + expect(walletRenewalInFlight('testnet', ID, 7, 1_000 + 2 * 60 * 1000)).toBe(true) + }) + + it('clears only the mark of the key named', () => { + markWalletRenewal('testnet', ID, 7, 2_000) + clearWalletRenewal('testnet', ID, 8) + expect(walletRenewalInFlight('testnet', ID, 7, 1_000)).toBe(true) + clearWalletRenewal('testnet', ID, 7) + expect(walletRenewalInFlight('testnet', ID, 7, 1_000)).toBe(false) + }) + + it('reads a garbled marker as none', () => { + localStorage.setItem(`forge:app-connect:renewing:testnet:${ID}`, '{') + expect(walletRenewalInFlight('testnet', ID, 7, 0)).toBe(false) + }) +}) diff --git a/forge-web/lib/auth/connection-id.ts b/forge-web/lib/auth/connection-id.ts new file mode 100644 index 000000000..404a13650 --- /dev/null +++ b/forge-web/lib/auth/connection-id.ts @@ -0,0 +1,103 @@ +/** + * The App Connect v2 state this browser keeps in localStorage (`APP_CONNECT_PROFILE.md`). None of + * it is secret. + * + * - The **connection id** (`CONNECTION_ID`): 16 random bytes per network, carried by every v2 + * request. A wallet that approves disables the keys of its previous grant for the same + * (identity, app, connection id) in the same identity update, so signing in again or renewing + * from this browser never leaves this browser's old key live. It survives logout and forget, as + * the profile requires: a fresh id would leave the old grant's key live in the wallet. + * - The **renewal marker**: set while a wallet renewal of this browser's key is shown and being + * answered. The wallet disables the old key in the update that adds the new one, a moment + * before this tab stores the new one; meanwhile other tabs see their key disabled. The marker + * tells them it was replaced, not revoked, so they drop it quietly instead of locking every tab + * (`AuthController.superseded`). It names the key being replaced and lapses with the request. + */ + +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' + +const CONNECTION_KEY = 'forge:app-connect:connection-id:' +const RENEWAL_KEY = 'forge:app-connect:renewing:' +/** + * The furthest ahead a renewal mark may end: a request lives 10 minutes, and storing its answer a + * little longer. A mark that ends later (a clock set back since) is not honoured, so it can never + * keep a revoked key's tabs from locking for long. + */ +export const MAX_RENEWAL_MARK_MS = 20 * 60 * 1000 + +function storage(): Storage | null { + if (typeof window === 'undefined') return null + try { + return window.localStorage + } catch { + return null + } +} + +/** + * This browser's connection id for `networkKey` (`NETWORKS[n].key`: `testnet`, `devnet-sakura`), + * made on first use. With storage disabled every request gets a fresh one (a renewal then leaves + * the old key live until it expires; the master-key revoke still disables it). + */ +export function connectionId(networkKey: string): Uint8Array { + const s = storage() + try { + const kept = s?.getItem(CONNECTION_KEY + networkKey) + if (kept && /^[0-9a-f]{32}$/.test(kept)) return hexToBytes(kept) + } catch { + /* unreadable: make a new one */ + } + const fresh = crypto.getRandomValues(new Uint8Array(16)) + try { + s?.setItem(CONNECTION_KEY + networkKey, bytesToHex(fresh)) + } catch { + /* storage full or disabled: this request only */ + } + return fresh +} + +interface RenewalMarker { + readonly keyId: number + readonly until: number +} + +function renewalKey(networkKey: string, identityId: string): string { + return `${RENEWAL_KEY}${networkKey}:${identityId}` +} + +/** Mark a wallet renewal of `keyId` on `identityId` as in flight until `until` (ms). */ +export function markWalletRenewal(networkKey: string, identityId: string, keyId: number, until: number): void { + try { + storage()?.setItem(renewalKey(networkKey, identityId), JSON.stringify({ keyId, until } satisfies RenewalMarker)) + } catch { + /* storage disabled: another tab may lock while the renewal finishes, as before */ + } +} + +/** + * The renewal of `identityId`'s key ended (stored, cancelled or expired). With `keyId`, only a + * mark for that key goes: another tab's renewal of another key keeps its own. + */ +export function clearWalletRenewal(networkKey: string, identityId: string, keyId?: number | null): void { + try { + if (keyId != null && readMarker(networkKey, identityId)?.keyId !== keyId) return + storage()?.removeItem(renewalKey(networkKey, identityId)) + } catch { + /* storage disabled */ + } +} + +function readMarker(networkKey: string, identityId: string): Partial | null { + try { + const raw = storage()?.getItem(renewalKey(networkKey, identityId)) + return raw ? (JSON.parse(raw) as Partial) : null + } catch { + return null + } +} + +/** Whether a wallet renewal of exactly `keyId` on `identityId` is in flight at `now`. */ +export function walletRenewalInFlight(networkKey: string, identityId: string, keyId: number, now = Date.now()): boolean { + const marker = readMarker(networkKey, identityId) + return marker?.keyId === keyId && typeof marker.until === 'number' && marker.until > now && marker.until <= now + MAX_RENEWAL_MARK_MS +} diff --git a/forge-web/lib/auth/wallet-protocol.test.ts b/forge-web/lib/auth/wallet-protocol.test.ts index 810b6f8b9..2cc148390 100644 --- a/forge-web/lib/auth/wallet-protocol.test.ts +++ b/forge-web/lib/auth/wallet-protocol.test.ts @@ -24,6 +24,8 @@ import { wipeAnswer, type ResponseSource, } from './app-connect' +import { newV2LoginRequest } from './app-connect-v2' +import { parseAppConnectUri } from '../vendor/platform-auth/app-connect' import { buildKeyRegistration, isUnlimited, keyScope, loginKeys, nextGrant, scopeCovers, RevokedWalletKey } from './key-registration' import { heldToDisable } from './limited-key' import { authKeyFromLogin, encodeKeyRequest, encryptionKeyFromLogin, openEnvelope, protocolUri } from './wallet-protocol' @@ -87,6 +89,13 @@ describe('dash-key request: byte-compatible with the shipped wallets', () => { expect(() => parseKeyRequest(`dash-key://${base58Encode(good)}?n=d&v=1`)).toThrow(/\/\//) }) + it('cannot share a QR code with App Connect v2: a v1 wallet refuses a v2 request, and the v2 parser a v1 one', () => { + const v2 = newV2LoginRequest('devnet', FORGE, { connectionId: new Uint8Array(16), chainNow: Date.now() }) + expect(() => parseKeyRequest(v2.qrUri)).toThrow(/unsupported version: 2/) + expect(() => parseKeyRequest(v2.linkUri)).toThrow(DashConnectUriException) + expect(() => parseAppConnectUri(newLoginRequest('devnet', FORGE.core).uri)).toThrow(expect.objectContaining({ code: 'unsupported' })) + }) + it('carries no pairing code: the key-exchange protocol and the wallets have none', () => { expect(Object.keys(newLoginRequest('devnet', FORGE.core))).not.toContain('pairingCode') }) diff --git a/forge-web/lib/auth/wallet-sim.ts b/forge-web/lib/auth/wallet-sim.ts index ea471b6a9..6d9f0fe7b 100644 --- a/forge-web/lib/auth/wallet-sim.ts +++ b/forge-web/lib/auth/wallet-sim.ts @@ -4,12 +4,16 @@ * iOS `DashConnectUri.swift` length ceiling), derives the login key the way they do * (`LoginKeyDerivation`), and seals a response (`KeyExchangeCrypto.encryptLoginKey`). A test * that passes here passes the wallets' own parsers byte for byte. + * + * {@link answerV2} is an App Connect v2 wallet (`APP_CONNECT_PROFILE.md`), on the vendored + * module's parser and sealing: the reference the profile's vectors check. */ import * as secp from '@noble/secp256k1' import { hkdf } from '@noble/hashes/hkdf.js' import { sha256 } from '@noble/hashes/sha2.js' +import { appConnectRequestHash, parseAppConnectUri, sealAppConnectPayload, type ParsedAppConnectUri } from '../vendor/platform-auth/app-connect' import { base58Decode } from './base58' import { envelopeKey } from './wallet-protocol' @@ -109,3 +113,23 @@ export async function sealLoginKeys(loginKeys: readonly Uint8Array[], walletPriv const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: new Uint8Array(nonce) }, k, plain)) return new Uint8Array([...nonce, ...ct]) } + +/** What an App Connect v2 wallet publishes for a request: the `loginKeyResponse` fields. */ +export interface V2Answer { + readonly parsed: ParsedAppConnectUri + /** `appEphemeralPubKeyHash`. */ + readonly requestHash: Uint8Array + readonly walletEphemeralPubKey: Uint8Array + readonly encryptedPayload: Uint8Array +} + +/** + * An App Connect v2 wallet's answer to `uri`: the request parsed as the profile specifies (a v1 + * URI is refused as unsupported), and `slots` (the private keys it registered, one per granted + * binding) sealed to it under `ownerId`. Registering those keys is the caller's part. + */ +export async function answerV2(uri: string, p: { readonly ownerId: string; readonly slots: readonly Uint8Array[] }): Promise { + const parsed = parseAppConnectUri(uri) + const sealed = await sealAppConnectPayload({ appEphemeralPubKey: parsed.request.appEphemeralPubKey, ownerId: base58Decode(p.ownerId), slots: [...p.slots] }) + return { parsed, requestHash: appConnectRequestHash(parsed.request), ...sealed } +} diff --git a/forge-web/lib/sdk/facade.ts b/forge-web/lib/sdk/facade.ts index 88b4f34ab..5478723c2 100644 --- a/forge-web/lib/sdk/facade.ts +++ b/forge-web/lib/sdk/facade.ts @@ -15,6 +15,10 @@ export interface WasmKey { readonly totalBudget?: bigint readonly expiresAt?: bigint readonly contractBounds?: { toJSON(): { $type: string; id: string } } + /** `KeyType` (0 ECDSA_SECP256K1, 2 ECDSA_HASH160, …); read by the App Connect verifier only. */ + readonly keyTypeNumber?: number + /** The key data, hex (the wasm getter); read by the App Connect verifier only. */ + readonly data?: string validatePrivateKey(bytes: Uint8Array, network: string): boolean } @@ -43,7 +47,11 @@ export interface AuthSdk { * object `fetch` returned (the wasm Identity, narrowed here to {@link WasmIdentity}). */ updateKeyLimits(options: Omit & { identity: WasmIdentity }): Promise + /** The keys Platform resolves for `contractId` and `purposes` (`getIdentitiesContractKeys`). */ + contractKeys(query: { identityIds: string[]; contractId: string; purposes?: number[] }): Promise<{ readonly identityId: { toBase58(): string }; readonly keys: WasmKey[] }[]> } + /** The proved response's metadata: the latest block's time and protocol version. */ + protocol: { versionUpgradeStateWithProof(): Promise<{ readonly metadata: { readonly protocolVersion: number; readonly timeMs: bigint } }> } documents: { query(q: unknown): Promise> } contracts: { fetch(id: string): Promise } system: { From 16535954dcd0d3d4c8dad1548af0998aee1922fe Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 24 Oct 2026 22:14:45 -0500 Subject: [PATCH 3/8] feat(auth): App Connect v2 sessions in the controller and vault - vault: a stored key's origin is 'dg' or 'app-connect' (VaultInfo fromAppConnect, storedOrigin); a master-key renewal clears it. - controller: AuthSession.origin (from the stored record, validated in a kept hint); adoptWalletKeys({ origin: 'app-connect' }) stores it, drops held keys the chain shows disabled, refuses to overwrite a key another tab stored meanwhile, and ends the renewal mark. An App Connect key starts no write within APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS of expiry. walletRenewalRequest/endWalletRenewal renew in the wallet with the same connection id; while the mark names a key, a tab that finds it disabled neither locks nor drops its unlock. walletSignInBlocker says when a locked vault must be unlocked before a v2 sign-in; recheckSession re-verifies the keys. - write-errors: for App Connect sessions, a disabled or removed key reads as revoked by the wallet and a write outside the key's bounds asks for a recheck (classifyAppConnectError). - funds: renewFix and fundsNotice(state, origin) route renewal of an App Connect key to the wallet, at the same thresholds. Co-Authored-By: Claude Opus 5.5 --- .../lib/auth/app-connect-session.test.ts | 324 ++++++++++++++++++ forge-web/lib/auth/controller.ts | 188 +++++++++- forge-web/lib/auth/vault.ts | 33 +- forge-web/lib/view/funds.test.ts | 11 +- forge-web/lib/view/funds.ts | 26 +- forge-web/lib/view/write-errors.test.ts | 48 +++ forge-web/lib/view/write-errors.ts | 37 +- 7 files changed, 645 insertions(+), 22 deletions(-) create mode 100644 forge-web/lib/auth/app-connect-session.test.ts diff --git a/forge-web/lib/auth/app-connect-session.test.ts b/forge-web/lib/auth/app-connect-session.test.ts new file mode 100644 index 000000000..de607a988 --- /dev/null +++ b/forge-web/lib/auth/app-connect-session.test.ts @@ -0,0 +1,324 @@ +/** + * A session on a key a wallet granted through App Connect v2: one group-bound key covering every + * Forge contract, kept across reloads, with its origin stored beside it; no new write in its last + * five minutes; renewed in the wallet without locking anything while the wallet swaps the key; + * and a master-key renewal that makes it an ordinary Forge key again. The chain is a fake; the + * vault is the real one (in-memory IndexedDB, a fake window's localStorage). The vault's unlock is + * one per page, so these tests are one tab: what another tab does in the same moment is the same + * code path (`superseded`, `supersede`) reached from its own refresh or kept-session event. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { NETWORKS } from '../constants' +import { forgeContractIds } from '../deployments' +import { idbGet, resetMemoryStores } from '../idb' +import { KeyUnusableError } from '../sdk/write' +import { AuthController } from './controller' +import { walletRenewalInFlight } from './connection-id' +import type { WalletKey } from './key-registration' +import { LOCKED_AT_KEY } from './session-resume' +import { hasExtraKeys, listVaults, lockVault, readStorageBlob, releaseUnlocked, writeStorageBlob } from './vault' +import { encodeWif } from './wif' + +vi.mock('../sdk/write', async (orig) => { + const real = await orig() + return { + ...real, + findSigningKey: async (identity: { publicKeys: FakeKey[] }, wif: string) => { + const k = identity.publicKeys.find((x) => x.wif === wif && x.disabledAt === undefined) + return k ? { publicKey: {}, keyId: k.keyId, securityLevel: 2 } : null + }, + } +}) +vi.mock('../constants', async (orig) => { + const real = await orig() + const { DEPLOYMENTS, forgeV2Ids } = await import('../deployments') + const devnet = { ...real.NETWORKS.devnet, key: 'devnet-moutai', v2: forgeV2Ids(DEPLOYMENTS['devnet-moutai']) } + return { ...real, NETWORKS: { ...real.NETWORKS, devnet } } +}) +// The group check before a renewal's code (its reads are `group-trust.test.ts`'s). +vi.mock('./group-trust', async (orig) => ({ ...(await orig()), assertGroupHolds: async () => ({ unknown: [], unchecked: [], notice: null }) })) +vi.mock('../view/retry', () => ({ retryWhileMissing: async (read: () => Promise) => read() })) +vi.mock('./wif', async (orig) => { + const real = await orig() + return { ...real, controlsKey: (k: FakeKey, wif: string) => k.wif === wif } +}) +vi.mock('./identity-file', async (orig) => { + const real = await orig() + return { ...real, masterMaterialFromFile: () => ({ identityId: '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD', networkKey: 'devnet-moutai', masterWif: 'MASTER', mnemonic: null }) } +}) +// The master-key renewal: recorded, not sent; it registers key 20. +const registered = vi.hoisted(() => [] as unknown[]) +vi.mock('./limited-key', async (orig) => { + const real = await orig() + return { + ...real, + registerLimitedKey: async (_sdk: unknown, params: { persist?: (k: { keyId: number; wif: string }) => Promise }) => { + registered.push(params) + const key = { keyId: 20, wif: encodeWif(new Uint8Array(32).fill(20), 'devnet') } + await params.persist?.(key) + return { ...key, limits: { remaining: 5n, total: 5n, expiresAt: Date.now() + 1e9 } } + }, + } +}) + +interface FakeKey { + keyId: number + wif: string + purposeNumber: number + securityLevelNumber: number + disabledAt?: bigint + expiresAt?: bigint + totalBudget?: bigint + contractBounds?: { toJSON(): { $type: string; id: string } } +} + +const NET = 'devnet' as const +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const FORGE = NETWORKS[NET].v2! +const NETWORK_KEY = NETWORKS[NET].key +const wifOf = (n: number): string => encodeWif(new Uint8Array(32).fill(n), NET) +/** A passkey protection (no Argon2: fast). The fake `navigator.credentials` returns this PRF. */ +const PRF = new Uint8Array(32).fill(9) +const PASSKEY = { passkey: { credentialId: new Uint8Array([1]), prfSalt: new Uint8Array(32), output: PRF } } +const WAIT = { timeout: 15_000, interval: 20 } +const MIN = 60 * 1000 + +function fakeWindow(): { localStorage: Storage } { + const data = new Map() + const localStorage = { + get length() { + return data.size + }, + key: (i: number) => [...data.keys()][i] ?? null, + getItem: (k: string) => data.get(k) ?? null, + setItem: (k: string, v: string) => void data.set(k, String(v)), + removeItem: (k: string) => void data.delete(k), + clear: () => data.clear(), + } as Storage + const win: Record = { + localStorage, + location: { hostname: 'forge.dashhq.org', pathname: '/' }, + addEventListener: () => undefined, + isSecureContext: true, + PublicKeyCredential: function PublicKeyCredential() {}, + } + win.top = win + win.self = win + return win as unknown as { localStorage: Storage } +} + +function fakeNavigator(): unknown { + return { + credentials: { + get: async () => ({ + rawId: new Uint8Array([1]).buffer, + getClientExtensionResults: () => ({ prf: { results: { first: PRF.slice().buffer, second: PRF.slice().buffer } } }), + }), + }, + } +} + +/** A group-bound HIGH key with a budget and `expiresAt`: what a v2 wallet registers. */ +function groupKey(keyId: number, expiresAt = Date.now() + 90 * 24 * 60 * MIN): FakeKey { + return { + keyId, + wif: wifOf(keyId), + purposeNumber: 0, + securityLevelNumber: 2, + totalBudget: 5_000_000_000n, + expiresAt: BigInt(expiresAt), + contractBounds: { toJSON: () => ({ $type: 'contractGroup', id: FORGE.group }) }, + } +} + +/** The verified grant `awaitV2Grant` hands back for `k`. */ +function grantOf(k: FakeKey): WalletKey { + return { + keyId: k.keyId, + wif: k.wif, + scope: { core: true, collab: true, community: true, meta: true, unbounded: false }, + limits: { remaining: k.totalBudget!, total: k.totalBudget!, expiresAt: Number(k.expiresAt) }, + } +} + +describe('an App Connect v2 session', () => { + let keys: FakeKey[] + const sdk = { + identities: { + fetch: async () => ({ balance: 10n ** 11n, publicKeys: keys, getPublicKeyById: () => ({}) }), + keysRemainingBudgets: async (_id: string, ids: number[]) => new Map(ids.map((i) => [i, keys.find((k) => k.keyId === i)?.totalBudget ?? null])), + nonce: async () => 1n, + }, + } as unknown as EvoSDK + const controllers: (() => void)[] = [] + const make = (): AuthController => { + const c = new AuthController(async () => sdk, NET) + controllers.push(c.attach()) + return c + } + const signIn = async (k: FakeKey, c = make()): Promise => { + await c.adoptWalletKeys(ID, [grantOf(k)], PASSKEY, { origin: 'app-connect' }) + return c + } + const locked = (): boolean => window.localStorage.getItem(LOCKED_AT_KEY) !== null + + beforeEach(() => { + resetMemoryStores() + vi.stubGlobal('window', fakeWindow()) + vi.stubGlobal('navigator', fakeNavigator()) + releaseUnlocked() + registered.length = 0 + keys = [{ keyId: 0, wif: wifOf(1), purposeNumber: 0, securityLevelNumber: 0 }, groupKey(5)] + }) + afterEach(() => { + for (const off of controllers.splice(0)) off() + vi.unstubAllGlobals() + }) + + it('covers every Forge contract with one limited key, signs each, and is kept for reloads', async () => { + const c = await signIn(keys[1]!) + const s = c.getState().session! + expect(s.origin).toBe('app-connect') + expect(s.grants).toEqual({ core: true, collab: true, community: true, meta: true }) + expect(s.unlimited).toBe(false) + expect(s.unbounded).toBe(false) + for (const contract of forgeContractIds(FORGE)) expect(c.writeAuth!.getSigningKeyWif(contract)).toBe(wifOf(5)) + // "Stay signed in for public repos" keeps it: a budgeted, expiring, group-bound key. + await vi.waitFor(async () => expect(await idbGet('vault', `session:${NET}`)).toBeDefined(), WAIT) + }, 30_000) + + it('starts no write in the key’s last five minutes (renew it in the wallet), but signs before them', async () => { + keys[1] = groupKey(5, Date.now() + 4 * MIN) + const c = await signIn(keys[1]) + expect(() => c.writeAuth!.getSigningKeyWif(FORGE.core)).toThrow(KeyUnusableError) + expect(() => c.writeAuth!.getSigningKeyWif(FORGE.core)).toThrow(expect.objectContaining({ reason: 'expired' })) + + keys[1] = groupKey(5, Date.now() + 6 * MIN) + const fresh = await signIn(keys[1]) + expect(fresh.writeAuth!.getSigningKeyWif(FORGE.core)).toBe(wifOf(5)) + }, 30_000) + + it('the margin is App Connect’s: the same key from a v1 wallet still signs', async () => { + keys[1] = groupKey(5, Date.now() + 4 * MIN) + const c = make() + await c.adoptWalletKeys(ID, [grantOf(keys[1])], PASSKEY) + expect(c.getState().session?.origin).toBeUndefined() + expect(c.writeAuth!.getSigningKeyWif(FORGE.core)).toBe(wifOf(5)) + }, 30_000) + + it('keeps its origin across a lock and unlock, and across a reload of a kept session', async () => { + const c = await signIn(keys[1]!) + await vi.waitFor(async () => expect(await idbGet('vault', `session:${NET}`)).toBeDefined(), WAIT) + expect((await listVaults(NET)).find((v) => v.identityId === ID)).toMatchObject({ fromAppConnect: true }) + // A reload picks up the kept session: its origin is there before and after the chain check. + releaseUnlocked() + const next = make() + expect(await next.resume()).toBe(true) + expect(next.getState().session?.origin).toBe('app-connect') + await vi.waitFor(() => expect(next.getState().session?.balanceReadAt).toBeTypeOf('number'), WAIT) + expect(next.getState().session?.origin).toBe('app-connect') + // An interactive unlock reads it from the stored record. + c.logout() + const unlocked = await make().unlock(ID, 'passkey') + expect(unlocked.origin).toBe('app-connect') + }, 60_000) + + it('a master-key renewal makes it an ordinary Forge key (origin cleared)', async () => { + const c = await signIn(keys[1]!) + keys.push({ ...groupKey(20), wif: wifOf(20) }) + const renewed = await c.importIdentity({ fileText: '{}' }, PASSKEY, undefined, { renew: true }) + expect(registered).toHaveLength(1) + expect(renewed.keyId).toBe(20) + expect(renewed.origin).toBeUndefined() + const stored = (await listVaults(NET)).find((v) => v.identityId === ID) + expect(stored?.keyId).toBe(20) + expect(stored?.fromAppConnect).toBeUndefined() + }, 30_000) + + it('renews in the wallet: the replaced key locks nothing, and the renewal carries everything over', async () => { + const c = await signIn(keys[1]!) + await writeStorageBlob(NET, ID, { bucket: 'kept' }) + const req = await c.walletRenewalRequest() + expect(req).toMatchObject({ identityHint: ID, replacesKeyId: 5 }) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(true) + // The wallet's update: key 5 disabled, key 6 added. A refresh now finds its key disabled: no + // lock, and the renewing tab keeps its unlock (it stores the new key with it). + keys[1]!.disabledAt = 1n + keys.push(groupKey(6)) + await c.refreshBalance() + expect(locked()).toBe(false) + expect(c.getState().session?.keyId).toBe(5) + const renewed = await signIn(keys[2]!, c) + expect(renewed.getState().session).toMatchObject({ keyId: 6, origin: 'app-connect' }) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(false) + expect(locked()).toBe(false) + // Storage settings carried over; the disabled key is not held on (nothing left to disable). + expect(await readStorageBlob(NET, ID)).toEqual({ bucket: 'kept' }) + expect(await hasExtraKeys(NET, ID)).toBe(false) + }, 60_000) + + it('keeps a replaced key the wallet left live, so a later revoke disables it', async () => { + const c = await signIn(keys[1]!) + keys.push(groupKey(6)) + await signIn(keys[2]!, c) + expect(await hasExtraKeys(NET, ID)).toBe(true) + }, 30_000) + + it('a v2 sign-in over a locked vault is blocked only where unlocking would be needed', async () => { + const c = await signIn(keys[1]!) + c.logout() + // A group-bound Forge key alone: a master-key update disables it by id, locked or not. + expect(await c.walletSignInBlocker()).toBeNull() + // A shipped wallet's unlimited key: unlock first, while it still opens. + keys[1] = { ...keys[1]!, totalBudget: undefined, expiresAt: undefined, contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.core }) } } + expect(await c.walletSignInBlocker()).toMatch(/Unlock first/) + }, 30_000) + + it('ends a renewal it gave up without touching another key’s mark', async () => { + const c = await signIn(keys[1]!) + const req = await c.walletRenewalRequest() + c.endWalletRenewal({ ...req, replacesKeyId: 99 }) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(true) + c.endWalletRenewal(req) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(false) + }, 30_000) + + it('without a renewal in flight, a disabled key still signs out every tab', async () => { + const c = await signIn(keys[1]!) + const req = await c.walletRenewalRequest() + c.endWalletRenewal(req) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(false) + keys[1]!.disabledAt = 1n + await c.refreshBalance() + expect(locked()).toBe(true) + expect(c.getState().notice).toMatch(/Signed out/) + }, 30_000) + + it('renews in the wallet only a key a wallet granted, with the whole vault open', async () => { + const v1 = make() + await v1.adoptWalletKeys(ID, [grantOf(keys[1]!)], PASSKEY) + await expect(v1.walletRenewalRequest()).rejects.toThrow(/identity file or recovery phrase/) + lockVault() + // A reload's signing-only tab must unlock first: storing the new key needs the whole vault. + const c = await signIn(keys[1]!) + await vi.waitFor(async () => expect(await idbGet('vault', `session:${NET}`)).toBeDefined(), WAIT) + releaseUnlocked() + const resumed = make() + await resumed.resume() + await expect(resumed.walletRenewalRequest()).rejects.toThrow(/Unlock this tab first/) + expect(c).toBeDefined() + }, 60_000) + + it('checks the session again on request (a write outside the key’s bounds)', async () => { + const c = await signIn(keys[1]!) + keys[1]!.totalBudget = 4_000_000_000n + const s = await c.recheckSession() + expect(s?.keyLimits?.remaining).toBe(4_000_000_000n) + keys[1]!.disabledAt = 1n + await expect(c.recheckSession()).rejects.toThrow() + expect(locked()).toBe(true) + }, 30_000) +}) diff --git a/forge-web/lib/auth/controller.ts b/forge-web/lib/auth/controller.ts index e41c5761c..2ae8b2e79 100644 --- a/forge-web/lib/auth/controller.ts +++ b/forge-web/lib/auth/controller.ts @@ -16,6 +16,11 @@ * {@link MissingGrantError} (the UI then asks the wallet for that contract) rather than sign a * write consensus would refuse and charge for. * + * A wallet that speaks App Connect v2 (`./app-connect-v2`) grants one key bound to the Forge + * contract group, with a budget and an expiry: stored like any wallet key, with origin + * `app-connect`, so it is renewed in that wallet (the same connection id disables the old key) + * and is not used for a new write in the last minutes before it expires. + * * The controller's observable state never carries key material. `writeAuth.getSigningKeyWif()` * reads the unlocked key at signing time and throws once the vault is locked. * @@ -31,7 +36,10 @@ import { errorMessage, shortId } from '../utils' import { stepClock, timed } from '../step-timing' import { DEPLOYMENTS, FORGE_CONTRACT_KINDS, contractKind, groupTrust, type ForgeIds, type GroupTrust } from '../deployments' import { assertGroupHolds, type GroupCheck } from './group-trust' -import { SECURITY_LEVEL, WriteAuthError, assertWritesAllowed, balanceBeforeWrite, findSigningKey, measureActual, readIdentityBalance, serialized, type SpendEvent, type WriteAuth } from '../sdk/write' +import { KeyUnusableError, SECURITY_LEVEL, WriteAuthError, assertWritesAllowed, balanceBeforeWrite, findSigningKey, measureActual, readIdentityBalance, serialized, type SpendEvent, type WriteAuth } from '../sdk/write' +import { APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS } from '../vendor/platform-auth/app-connect' +import { newV2LoginRequest, readChainClock, type V2LoginRequest } from './app-connect-v2' +import { clearWalletRenewal, connectionId, markWalletRenewal, walletRenewalInFlight } from './connection-id' import { KEY_ADD_FLOOR_CREDITS, KEY_DISABLE_CREDITS, KEY_LIMITS_UPDATE_CREDITS, KEY_REGISTER_CREDITS, KEY_RENEW_CREDITS, NAME_REGISTER_CREDITS, NAME_REGISTER_FLOOR_CREDITS } from '../sdk/cost' import { authSdk, type WasmIdentity, type WasmKey } from '../sdk/facade' import type { HeldBrowserKey } from './create-identity' @@ -96,6 +104,8 @@ import { watchOtherTabs, clearSignedWrites, storeInVault, + storedOrigin, + isKeyOrigin, VaultChangedError, stageInVault, hasStaged, @@ -111,6 +121,7 @@ import { unlockWithPassphrase, unlockedSecret, type ExtraKey, + type KeyOrigin, type Protection, type StoreOutcome, type VaultInfo, @@ -122,6 +133,18 @@ function watched(k: WasmKey): WatchedKey { return { keyId: k.keyId, purpose: k.purposeNumber, level: k.securityLevelNumber, disabled: k.disabledAt !== undefined } } +/** + * How long a wallet renewal's mark outlives its request: the answer arrives at the latest when the + * request expires, and checking and storing the new key take a little longer. + */ +const WALLET_RENEWAL_GRACE_MS = 5 * 60 * 1000 + +/** A wallet renewal's request: a v2 request naming the identity, and the key it replaces. */ +export interface WalletRenewalRequest extends V2LoginRequest { + readonly identityHint: string + readonly replacesKeyId: number +} + /** The notice when a renewal could not carry the encryption key over. */ const ENCRYPTION_KEY_DROPPED = 'Your encryption key for members-only and private content was encrypted with the previous key, which was locked when you renewed it, so it was not carried over. Add it again in Settings → Members-only and private content.' @@ -143,6 +166,12 @@ export interface AuthSession { readonly keyId?: number /** `vault`: a stored limited key; `session`: a tab-only key (advanced raw key). */ readonly storage: 'vault' | 'session' + /** + * Where the stored key came from when this browser did not register it: `app-connect` (a + * wallet's App Connect grant: renew it in the wallet, {@link AuthController.walletRenewalRequest}) + * or `dg`. Absent for a key registered here with the master key. + */ + readonly origin?: KeyOrigin /** Which Forge contracts this session's keys can sign on. */ readonly grants?: { readonly core: boolean; readonly collab: boolean; readonly community: boolean; readonly meta: boolean } /** @@ -292,6 +321,7 @@ function parseHint(v: unknown, secret: VaultSecret, network: Network): { session const s = h?.session if (typeof s !== 'object' || s === null || s.identityId !== secret.identityId || s.network !== network || s.storage !== 'vault' || s.keyId !== secret.keyId) return null if (typeof s.balance !== 'string' || !/^\d+$/.test(s.balance)) return null + if (s.origin !== undefined && !isKeyOrigin(s.origin)) return null const main = h?.scopes?.main ?? null const extra = h?.scopes?.extra if ((main !== null && !isScope(main)) || !Array.isArray(extra)) return null @@ -348,18 +378,34 @@ export class AuthController { } } - /** This tab's key was replaced by another tab's renewal: drop it here and pick up the new one. */ + /** + * This tab's key was replaced by another tab's renewal: drop it here and pick up the new one. + * While a wallet renewal of it is still in flight the new key is not stored yet, so nothing + * changes: the renewing tab (perhaps this one) still needs its unlock to store the new key and + * carry the storage settings and encryption key over, and its keep then announces the new key + * to every other tab ({@link attach}). Until then a write fails on the disabled key as usual. + */ private async supersede(): Promise { + const session = this.state.session + if (session?.keyId !== undefined && walletRenewalInFlight(this.networkKey, session.identityId, session.keyId)) return this.abandonSignIn() await this.resume() } + /** The deployment key of this controller's network (`testnet`, `devnet-sakura`). */ + private get networkKey(): string { + return NETWORKS[this.network].key + } + /** * Whether this tab's key for `identityId` is no longer the one this browser stores (another - * tab renewed it): then its failure on chain is expected, and no reason to lock other tabs. + * tab renewed it), or is being replaced by a wallet renewal (`./connection-id`: the wallet + * disables it in the update that adds the new key, a moment before the renewing tab stores + * that one): then its failure on chain is expected, and no reason to lock other tabs. */ private async superseded(identityId: string, keyId: number | undefined): Promise { if (keyId === undefined) return false + if (walletRenewalInFlight(this.networkKey, identityId, keyId)) return true const stored = await storedKeyId(this.network, identityId).catch(() => null) return stored !== null && stored !== keyId } @@ -512,6 +558,12 @@ export class AuthController { throw new WriteAuthError(`this browser's key signs only Dash Forge writes${contractId ? ` (not ${contractId})` : ''}`) } if (this.scopes.main && scopeCovers(this.scopes.main, forge, contractId)) { + // A wallet's App Connect key starts no write in its last minutes: one signed now could + // reach a block after it expired (APP_CONNECT_PROFILE.md). Renew it in the wallet. + const expiresAt = current.keyLimits?.expiresAt + if (current.origin === 'app-connect' && expiresAt != null && expiresAt - Date.now() <= APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS) { + throw new KeyUnusableError('expired') + } noteSessionUse(network) return secret.wif } @@ -596,11 +648,13 @@ export class AuthController { const match = await findSigningKey(identity, secret.wif, this.network, SECURITY_LEVEL.HIGH) if (!match) throw keyFailure(identity, secret.keyId) const keyLimits = knownLimits ?? (await readKeyLimits(sdk, secret.identityId, match.keyId).catch(() => null)) - let extra: Pick = {} + let extra: Pick = {} if (storage === 'vault') { const forge = NETWORKS[this.network].v2 if (!forge) throw new KeyNotUsableError(new NotDeployedError(NETWORKS[this.network]).message) extra = await this.verifyScopes(identity, secret, match.keyId, forge) + const origin = await storedOrigin(this.network, secret.identityId, secret.keyId).catch(() => null) + if (origin !== null) extra = { ...extra, origin } } // Held to be disabled later: listed while still live on the identity. const heldOnly = (secret.extra ?? []) @@ -1092,13 +1146,17 @@ export class AuthController { /** * Adopt the keys a wallet granted (verified on chain by the caller): the first is the vault's - * main key, each further one is kept as the grant for the contract it covers. + * main key, each further one is kept as the grant for the contract it covers. An App Connect v2 + * grant (`origin: 'app-connect'`, `./app-connect-v2` `awaitV2Grant`) is one group-bound key; + * its origin is stored with it, and a wallet renewal of this browser's key ends once it is stored. */ async adoptWalletKeys( identityId: string, keys: readonly WalletKey[], protection: Protection, options: { + /** Where the keys came from: `app-connect` for an App Connect v2 grant. */ + readonly origin?: 'app-connect' /** Give up this device's unfinished renewal (the user chose the wallet). */ readonly discardPendingRenewal?: boolean /** The renewal's own passphrase or passkey, when the protection chosen here is not it. */ @@ -1125,7 +1183,7 @@ export class AuthController { // that stores it. As this identity's one writer: no other tab's stage is dropped instead. return serialized(identityId, async () => { try { - return await this.storeWalletKeys(identityId, main, rest, forge, protection, withCopies) + return await this.storeWalletKeys(identityId, main, rest, forge, protection, withCopies, previous?.keyId ?? null) } finally { forgetPasskeyOutputs() } @@ -1140,7 +1198,10 @@ export class AuthController { forge: ForgeIds, protection: Protection, options: Parameters[3] = {}, + /** The key id of the record found for this identity before the answer (null: none). */ + previousKeyId: number | null = null, ): Promise { + const appConnect = options.origin === 'app-connect' const pending = await stagedInfo(this.network, identityId) let given: ExtraKey | null = null if (pending !== null) { @@ -1155,12 +1216,33 @@ export class AuthController { // beside the new ones (a returning login keeps its forge-collab grant; a key the new // grant supersedes is still held, so a later revoke can disable it). Stale ones fall // out at the next unlock. + // + // An App Connect grant disables the key of the wallet's previous grant for this browser (the + // same connection id): a held key the chain shows disabled is dropped, since there is nothing + // left to disable, and keeping it would make every later sign-in over a locked vault ask to + // unlock a key that no longer opens anything. const fresh = new Set([main.keyId, ...rest.map((k) => k.keyId)]) + const disabled = appConnect ? await this.disabledKeyIds(identityId) : new Set() const held: ExtraKey[] = this.heldKeys(identityId).map((h) => ('contractId' in h ? h : { contractId: forge.core, keyId: h.keyId, wif: h.wif })) - const kept = [...held, ...(given ? [given] : [])].filter((h, i, all) => !fresh.has(h.keyId) && all.findIndex((x) => x.keyId === h.keyId) === i) + const kept = [...held, ...(given ? [given] : [])].filter((h, i, all) => !fresh.has(h.keyId) && !disabled.has(h.keyId) && all.findIndex((x) => x.keyId === h.keyId) === i) const extra = [...rest.map((k) => toExtraKey(k, forge)), ...kept] const secret: VaultSecret = { identityId, keyId: main.keyId, wif: main.wif, ...(extra.length ? { extra } : {}) } - const stored = await storeInVault(this.network, secret, protection, pending !== null ? { dropStagedKeyId: pending.keyId } : {}) + let stored: StoreOutcome + try { + stored = await storeInVault(this.network, secret, protection, { + ...(pending !== null ? { dropStagedKeyId: pending.keyId } : {}), + ...(options.origin !== undefined ? { origin: options.origin } : {}), + // A wallet approval can take minutes: a key another tab stored meanwhile (a master-key + // renewal) is not overwritten unseen. + ...(appConnect ? { expectHeldKeyId: previousKeyId } : {}), + }) + } catch (e) { + if (!(e instanceof VaultChangedError)) throw e + throw new WriteAuthError(`Another tab changed the key stored for ${shortId(identityId)} meanwhile, so the key your wallet just granted was not stored. Disable it in your wallet's connections, then sign in again.`) + } + // The new key is this browser's now: another tab that finds the old one disabled has been + // superseded by the stored key id alone. + if (appConnect) clearWalletRenewal(this.networkKey, identityId, previousKeyId) const encryption = await this.keepWalletEncryptionKey(identityId, forge, options) // Keys the vault could not carry over (by id, from its stored entries) are not reported only // when the wallet's own keys put every one of them back. @@ -1171,13 +1253,24 @@ export class AuthController { 'Your storage settings could not be carried over to the new key. Add your storage again in Settings → Storage.', encryption.notice, ) + // A shipped wallet registers an encryption key right after each auth key; a v2 grant does not. + const walletKeys = appConnect ? [] : [main.keyId, ...rest.map((k) => k.keyId)] try { - return await this.open(secret, 'vault', main.limits ?? undefined, true, [main.keyId, ...rest.map((k) => k.keyId)]) + return await this.open(secret, 'vault', main.limits ?? undefined, true, walletKeys) } catch (e) { throw new Error(`Key saved on this device, but signing in did not finish (${errorMessage(e)}). Unlock to continue.`) } } + /** + * The ids of `identityId`'s keys the chain shows disabled (positive evidence only: a read that + * fails, or a key not shown, disables nothing here). + */ + private async disabledKeyIds(identityId: string): Promise> { + const identity = await authSdk(await this.getSdk()).identities.fetch(identityId).catch(() => undefined) + return new Set((identity?.publicKeys ?? []).filter((k) => k.disabledAt !== undefined).map((k) => k.keyId)) + } + /** * Add the encryption keys a wallet answer stands for to the vault's keys, each that is a usable * ENCRYPTION key of the identity (DESIGN D27, {@link adoptWalletEncryptionKey}). Signing in @@ -1201,6 +1294,80 @@ export class AuthController { } } + /** + * Start renewing this session's key in the wallet that granted it (origin `app-connect`): an App + * Connect v2 request naming this identity (`IDENTITY_HINT`) with this browser's connection id, + * so the wallet disables the current key in the update that adds the new one. Until the new key + * is stored ({@link adoptWalletKeys} with origin `app-connect`) or {@link endWalletRenewal}, the + * current key is marked as being replaced: another tab that finds it disabled drops it quietly + * instead of locking every tab. Choose the protection (passphrase or passkey) before showing the + * code, so that window stays short; the mark lapses on its own a while after the request does. + * Needs the whole vault open in this tab, as storing the new key does. + */ + async walletRenewalRequest(options: { readonly callbackUrl?: (requestHash: Uint8Array) => string | null } = {}): Promise { + const session = this.state.session + if (!session || session.storage !== 'vault' || session.origin !== 'app-connect' || session.keyId === undefined) { + throw new Error('Only a key your wallet granted can be renewed in your wallet. Renew it with your identity file or recovery phrase instead.') + } + const { identityId, keyId } = session + this.requireFullUnlock(identityId) + const forge = NETWORKS[this.network].v2 + if (!forge) throw new NotDeployedError(NETWORKS[this.network]) + // The new key is bound to the group as the first one was: check it still holds (throws). + await this.checkGroup() + const { timeMs } = await readChainClock(await this.getSdk()) + const req = newV2LoginRequest(this.network, forge, { + connectionId: connectionId(this.networkKey), + chainNow: timeMs, + identityHint: identityId, + ...(options.callbackUrl ? { callbackUrl: options.callbackUrl } : {}), + }) + markWalletRenewal(this.networkKey, identityId, keyId, req.expiresAt + WALLET_RENEWAL_GRACE_MS) + return { ...req, identityHint: identityId, replacesKeyId: keyId } + } + + /** + * A wallet renewal ended without a new key (cancelled, expired, refused): drop its mark, unless + * it is another renewal's (another tab's, of another key). + */ + endWalletRenewal(req: Pick): void { + if (req.identityHint !== null) clearWalletRenewal(this.networkKey, req.identityHint, req.replacesKeyId) + } + + /** + * Why a v2 wallet sign-in cannot start now, or null. Any approval disables the key of the + * wallet's previous grant for this browser (its connection id) before Forge sees the answer, and + * nobody knows beforehand which identity will answer: a locked vault holding keys a master-key + * update could not otherwise disable (wallet keys) must be unlocked first, while it still opens. + */ + async walletSignInBlocker(): Promise { + const sdk = await this.getSdk() + for (const v of await listVaults(this.network)) { + if (v.staged === true) continue + try { + await this.assertUnlockedIfWalletKeys(sdk, v.identityId, v.keyId) + } catch (e) { + if (e instanceof VaultLockedError) return e.message + throw e + } + } + return null + } + + /** + * Check the session's keys on chain again (App Connect's `invalidate`: a write was refused as + * outside its key's bounds, 20014): the scopes, limits and balance are read afresh, and a key + * found disabled or expired ends the session as on unlock. A read that fails rejects and keeps + * the session as it was. + */ + async recheckSession(): Promise { + const session = this.state.session + if (!session || session.storage !== 'vault') return session + const secret = unlockedSecret(this.network, session.identityId) + if (!secret) return null + return this.open(secret, 'vault', undefined, false) + } + /** * Add a wallet grant for another Forge contract to the signed-in identity (a shipped wallet * grants one contract per approval). The key must belong to the session's identity. @@ -1808,6 +1975,9 @@ export class AuthController { async forget(identityId: string): Promise { if (this.state.session?.identityId === identityId) this.logout() forgetKeySnapshot(this.network, identityId) + // The connection id stays (APP_CONNECT_PROFILE.md): a fresh one would leave the wallet's key + // for this browser live. A renewal mark has nothing left to protect. + clearWalletRenewal(this.networkKey, identityId) await forgetVault(this.network, identityId) forgetLastIdentity(this.network, identityId) clearDrafts(identityId) diff --git a/forge-web/lib/auth/vault.ts b/forge-web/lib/auth/vault.ts index 031e17b88..7fde6e102 100644 --- a/forge-web/lib/auth/vault.ts +++ b/forge-web/lib/auth/vault.ts @@ -150,8 +150,21 @@ interface VaultRecord { * when there was none (a first import). Finishing it replaces only that record. */ readonly replaces?: number | null - /** The key came from `dg auth keys add --for-browser` (`./key-handoff`): renew it the same way. */ - readonly origin?: 'dg' + /** Where the key came from, when it was not registered here: renew it the same way. */ + readonly origin?: KeyOrigin +} + +/** + * Where a stored key came from, when this browser did not register it with the master key: + * `dg` (`dg auth keys add --for-browser`, `./key-handoff`) or `app-connect` (a wallet's App + * Connect v2 grant, `./app-connect-v2`). A key this browser registers itself has none; storing + * one (a renewal with the identity file or recovery phrase) clears it. + */ +export type KeyOrigin = 'dg' | 'app-connect' + +/** Whether a stored value is a {@link KeyOrigin} (records and kept hints are read back unchecked). */ +export function isKeyOrigin(v: unknown): v is KeyOrigin { + return v === 'dg' || v === 'app-connect' } /** What the UI may know about a stored vault (no secrets). */ @@ -169,6 +182,8 @@ export interface VaultInfo { readonly encryptionKey?: true /** The key came from `dg` (a key handoff): Renew offers `dg` first, not the recovery phrase. */ readonly fromDg?: true + /** The key came from a wallet's App Connect grant: Renew offers the wallet first. */ + readonly fromAppConnect?: true } const enc = new TextEncoder() @@ -924,8 +939,8 @@ export async function storeInVault( * gave up, its key carried in `secret.extra`): it is never gone before its key is stored. */ readonly dropStagedKeyId?: number - /** Where the key came from ({@link VaultRecord.origin}). */ - readonly origin?: 'dg' + /** Where the key came from ({@link KeyOrigin}); none clears an earlier record's. */ + readonly origin?: KeyOrigin /** * The key id of the record the caller found for this identity (null: none), checked in the * write's own transaction: a key another tab stored meanwhile aborts it ({@link VaultChangedError}). @@ -1086,6 +1101,7 @@ export async function listVaults(network: Network): Promise { methods: r.slots.map((s) => s.kind), ...(withEnc.has(encryptionBlobKey(network, r.identityId)) ? { encryptionKey: true as const } : {}), ...(r.origin === 'dg' ? { fromDg: true as const } : {}), + ...(r.origin === 'app-connect' ? { fromAppConnect: true as const } : {}), })) // An identity with only a staged key (a first import whose tab closed after registering, // D-016) must still be offered for unlock, or the key it paid for is unreachable. @@ -1382,6 +1398,15 @@ export async function storedKeyId(network: Network, identityId: string): Promise return (await idbGet('vault', key(network, identityId)))?.keyId ?? null } +/** + * Where the stored (main) record of (network, identity) came from ({@link KeyOrigin}), when that + * record holds `keyId`; null otherwise (none recorded, another key stored, or no record). + */ +export async function storedOrigin(network: Network, identityId: string, keyId: number): Promise { + const r = await idbGet('vault', key(network, identityId)) + return r?.keyId === keyId && isKeyOrigin(r.origin) ? r.origin : null +} + /** The kept session was used (a signature, the user active): its idle limit counts from now. */ export function noteSessionUse(network: Network): void { if (unlocked !== null) void touchResume(network).catch(() => undefined) diff --git a/forge-web/lib/view/funds.test.ts b/forge-web/lib/view/funds.test.ts index ee76b5a30..dc0ad9db5 100644 --- a/forge-web/lib/view/funds.test.ts +++ b/forge-web/lib/view/funds.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { affordability, fundsNotice, fundsState, issueCoverage, LOW_BALANCE_CREDITS, nextFundsChange } from './funds' +import { affordability, fundsNotice, fundsState, issueCoverage, LOW_BALANCE_CREDITS, nextFundsChange, renewFix } from './funds' import { previewCreate } from '../sdk/cost' import { balanceSettled, estimateMissed, reconcile, summarize, type SpendRow } from '../spend' @@ -66,6 +66,15 @@ describe('fundsNotice (the low-balance banner, ux-dx-spec §4)', () => { expect(fundsNotice(fundsState(10n ** 11n, key(4_000_000_000n, -1), NOW))).toMatchObject({ key: 'empty:key-expiry', fix: 'renew-key' }) expect(fundsNotice(fundsState(10n ** 11n, key(0n, 90 * DAY), NOW))?.key).toBe('empty:key-budget') }) + it('sends a key a wallet granted through App Connect to the wallet to renew, at the same thresholds', () => { + expect(fundsNotice(fundsState(10n ** 11n, key(900_000_000n, 90 * DAY), NOW), 'app-connect')).toMatchObject({ key: 'low:key-budget', fix: 'renew-in-wallet' }) + expect(fundsNotice(fundsState(10n ** 11n, key(4_000_000_000n, 3 * DAY), NOW), 'app-connect')).toMatchObject({ key: 'low:key-expiry', fix: 'renew-in-wallet' }) + expect(fundsNotice(fundsState(10n ** 11n, key(4_000_000_000n, 8 * DAY), NOW), 'app-connect')).toBeNull() + expect(fundsNotice(fundsState(BigInt(LOW_BALANCE_CREDITS - 1), null, NOW), 'app-connect')).toMatchObject({ fix: 'top-up' }) + expect(fundsNotice(fundsState(10n ** 11n, key(4_000_000_000n, 3 * DAY), NOW), 'dg')).toMatchObject({ fix: 'renew-key' }) + expect(renewFix('app-connect')).toBe('renew-in-wallet') + expect(renewFix(null)).toBe('renew-key') + }) }) describe('affordability compares what Platform needs available, not the estimate (D-012)', () => { diff --git a/forge-web/lib/view/funds.ts b/forge-web/lib/view/funds.ts index 4de0f8fe0..d40be8ce9 100644 --- a/forge-web/lib/view/funds.ts +++ b/forge-web/lib/view/funds.ts @@ -89,15 +89,29 @@ export function issueCoverage(spendable: bigint | null, issueCredits: number, da return `${cost.before}${dash(cost.credits)} DASH${cost.after}` } -/** The one fix a low or empty state needs (`ux-dx-spec.md` §4: top up / renew key). */ -export type FundsFix = 'top-up' | 'renew-key' +/** + * The one fix a low or empty state needs (`ux-dx-spec.md` §4: top up / renew key). + * `renew-in-wallet`: the key came from a wallet's App Connect grant (session origin + * `app-connect`), so it is renewed in that wallet (`AuthController.walletRenewalRequest`); the + * identity file or recovery phrase still works as the other way. + */ +export type FundsFix = 'top-up' | 'renew-key' | 'renew-in-wallet' + +/** How "Renew" goes for a session: in the wallet for a key it granted through App Connect. */ +export function renewFix(origin: string | null | undefined): 'renew-key' | 'renew-in-wallet' { + return origin === 'app-connect' ? 'renew-in-wallet' : 'renew-key' +} /** * What the low-balance banner says for a funds state, or null when there is nothing to say * (comfortable). `key` names the state, so dismissing "low balance" does not also hide a later - * "key expired" (one dismissal per state per session). + * "key expired" (one dismissal per state per session). `origin`: the session's key origin, which + * picks the renewal ({@link renewFix}); the thresholds are the same for every key. */ -export function fundsNotice(state: FundsState): { readonly key: string; readonly message: string; readonly threshold?: { before: string; dash: number; after: string }; readonly fix: FundsFix } | null { +export function fundsNotice( + state: FundsState, + origin?: string | null, +): { readonly key: string; readonly message: string; readonly threshold?: { before: string; dash: number; after: string }; readonly fix: FundsFix } | null { if (state.level === 'comfortable') return null const reason = state.reason ?? 'balance' const empty = state.level === 'empty' @@ -116,7 +130,7 @@ export function fundsNotice(state: FundsState): { readonly key: string; readonly if (reason === 'key-budget') { return { key, - fix: 'renew-key', + fix: renewFix(origin), message: empty ? "This browser's key has spent its budget: writes are off until you renew it. Reading still works." : "This browser's key has less than 20 % of its budget left. Renew it (or top up its budget in Settings).", @@ -124,7 +138,7 @@ export function fundsNotice(state: FundsState): { readonly key: string; readonly } return { key, - fix: 'renew-key', + fix: renewFix(origin), message: empty ? "This browser's key has expired: writes are off until you renew it. Reading still works." : "This browser's key expires within 7 days. Renew it to keep writing.", diff --git a/forge-web/lib/view/write-errors.test.ts b/forge-web/lib/view/write-errors.test.ts index 66229c121..7c49f86b4 100644 --- a/forge-web/lib/view/write-errors.test.ts +++ b/forge-web/lib/view/write-errors.test.ts @@ -257,6 +257,54 @@ describe('an unusable key opens renew, not a raw error (D-042)', () => { }) }) +describe('a session on a wallet’s App Connect key reads key refusals as App Connect does', () => { + const ac = { appConnect: true } + const refusal = (code: number, figures = {}) => new ConsensusRefusal(code, `refused ${code}`, figures, false) + + it('renew (20015, 20016, 40218): the same key sheet, which offers the wallet first', () => { + expect(writeFailure(refusal(20015), ac)).toEqual(writeFailure(refusal(20015))) + expect(writeFailure(refusal(20015), ac).sheet).toEqual({ blocker: 'key-budget' }) + expect(writeFailure(refusal(20016), ac).sheet).toEqual({ blocker: 'key-expiry' }) + const short = writeFailure(refusal(40218, { remaining: 1_000n, required: 5_000n }), ac) + expect(short.sheet).toEqual({ blocker: 'key-budget', shortfall: 4_000n }) + expect(short.recheck).toBeUndefined() + }) + + it('logout (20003, 20006, 40208): the wallet revoked this browser, and the renew sheet opens', () => { + for (const [code, blocker] of [[20003, 'key-missing'], [20006, 'key-disabled'], [40208, 'key-disabled']] as const) { + const f = writeFailure(refusal(code), ac) + expect(f.message).toMatch(/^Your wallet revoked this browser's access\. You weren't charged\./) + expect(f.sheet).toEqual({ blocker }) + } + // The same refusal outside App Connect keeps today's words. + expect(writeFailure(refusal(20006)).message).toMatch(/key was disabled/) + expect(writeFailure(refusal(20003)).sheet).toBeNull() + }) + + it('a key found disabled before signing says the same; one not shown (a node behind a renewal) does not', () => { + expect(writeFailure(new KeyUnusableError('disabled'), ac)).toEqual({ message: expect.stringMatching(/^Your wallet revoked/), sheet: { blocker: 'key-disabled' } }) + expect(writeFailure(new KeyUnusableError('missing'), ac)).toEqual(writeFailure(new KeyUnusableError('missing'))) + // Within the last minutes (the controller's margin) it is a renewal, not a revocation. + expect(writeFailure(new KeyUnusableError('expired'), ac)).toEqual(writeFailure(new KeyUnusableError('expired'))) + }) + + it('handoff (20004, 20007, 20013): cannot happen to a Forge write; reads as any refusal', () => { + for (const code of [20004, 20007, 20013]) { + const f = writeFailure(refusal(code), ac) + expect(f).toEqual(writeFailure(refusal(code))) + expect(f.message).toMatch(new RegExp(`Error code ${code}`)) + expect(f.sheet).toBeNull() + } + }) + + it('invalidate (20014): the usual sentence, and the session is checked again', () => { + const f = writeFailure(refusal(20014), ac) + expect(f.message).toBe(writeFailure(refusal(20014)).message) + expect(f.recheck).toBe(true) + expect(writeFailure(refusal(20014)).recheck).toBeUndefined() + }) +}) + describe('an immutable-property refusal (40128) names the frozen field', () => { // Drive's text, rs-dpp 5.0.0-beta.1 `document_immutable_property_changed_error.rs:27`. const immutable = (property: string, type: string) => diff --git a/forge-web/lib/view/write-errors.ts b/forge-web/lib/view/write-errors.ts index 70829e5ce..2c669ffd9 100644 --- a/forge-web/lib/view/write-errors.ts +++ b/forge-web/lib/view/write-errors.ts @@ -10,9 +10,17 @@ * Every message has the style guide's three beats (§C rule 8): what happened, whether you were * charged, what to do next. Platform's error code appears only where no sentence explains the * refusal, as the last words, so a bug report can quote it. + * + * A session whose key a wallet granted through App Connect (origin `app-connect`) reads a key + * refusal as App Connect does (`classifyAppConnectError`): a spent or expired key (`renew`) opens + * the same sheet, which offers the wallet first; a disabled or missing key (`logout`) says the + * wallet revoked this browser's access, and the session locks as for any disabled key; a write + * outside the key's bounds (`invalidate`) asks for the session's keys to be checked again + * (`recheck`); a level refusal (`handoff`) cannot happen to a Forge write and reads as any refusal. */ import { isUnreachableError } from '../sdk/unreachable' +import { classifyAppConnectError } from '../vendor/platform-auth/app-connect' import { BUDGET_EXCEEDED_CODE, CONTEST_FULL_CODE, @@ -51,6 +59,22 @@ export interface WriteFailure { readonly message: string /** The sheet that fixes it (renew or top up), or null when there is none to offer. */ readonly sheet: TopUpReason | null + /** + * The session's keys must be checked on chain again before the next write (App Connect's + * `invalidate`): `AuthController.recheckSession`. + */ + readonly recheck?: true +} + +/** The session a write failed in, where it changes the fix or the words. */ +export interface WriteContext { + /** The session signs with a key a wallet granted through App Connect (origin `app-connect`). */ + readonly appConnect?: boolean +} + +/** A wallet that granted the key through App Connect took it back (disabled, or removed). */ +function walletRevoked(charged: string): string { + return `Your wallet revoked this browser's access. ${charged} Sign in with your wallet again to keep writing.` } const KEY_BLOCKER: Readonly> = { @@ -182,14 +206,23 @@ const NO_ANSWER = /failed to fetch|fetch failed|networkerror|network error|load /** A write that could not reach Platform ({@link NO_ANSWER}). */ export const UNREACHABLE_WRITE = "Couldn't reach Dash Platform, so this change may not have been sent. Check your connection, then try again." -export function writeFailure(e: unknown): WriteFailure { +export function writeFailure(e: unknown, context: WriteContext = {}): WriteFailure { const out = (message: string, sheet: TopUpReason | null = null): WriteFailure => ({ message, sheet }) // Plain sentences of their own: may still land, was superseded, or another write holds the lock. if (e instanceof UnconfirmedWriteError || e instanceof SupersededWriteError || e instanceof WriterBusyError) return out(e.message) if (e instanceof KeyUnusableError) { - return out(e.message, { blocker: KEY_BLOCKER[e.reason] }) + const sheet = { blocker: KEY_BLOCKER[e.reason] } + // Found before signing (nothing was sent). Only a key shown disabled was revoked: one not + // shown at all may be a node that has not seen a renewal's new key yet. + if (context.appConnect && e.reason === 'disabled') return out(walletRevoked(chargedSentence(false)), sheet) + return out(e.message, sheet) } if (e instanceof ConsensusRefusal) { + const appConnect = context.appConnect ? classifyAppConnectError(e.code) : null + if (appConnect?.action === 'logout') { + return out(walletRevoked(chargedSentence(e.feeCharged)), { blocker: appConnect.failure === 'key-missing' ? 'key-missing' : 'key-disabled' }) + } + if (appConnect?.action === 'invalidate') return { ...out(refusalSentence(e)), recheck: true } const { remaining, balance, required } = e.figures if (e.isKeyLimit) { if (EXPIRY_CODES.has(e.code)) return out("This browser's key has expired. You weren't charged. Renew the key to continue.", { blocker: 'key-expiry' }) From 451e2f892bba66e5d940ba4efc9ab275b1aebe13 Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 24 Oct 2026 23:07:55 -0500 Subject: [PATCH 4/8] feat(web): App Connect v2 wallet sign-in and renewal UI The wallet tile now shows an App Connect v2 request first where the chain supports it: one approval for a key that works on every Forge contract, with a budget and an expiry, so no guided grants follow. A link switches to the older code (v1, unchanged) for wallets without v2, and back. - wallet-connect-flow: v2 login with the group and locked-key checks before the code, confirm step with the granted limits and group notice, poll on focus and visibility and on the return page's nudge, and mode="renew": protection is chosen before the code shows, the new key is stored even if the sheet is closing (held for a decision or unlock when it cannot be stored yet), and the renewal mark ends on every way out but a stored key. - /connect/ (static) and lib/auth/connect-callback: the phone link's `cb` (https, canonical origin, never on IPFS builds), `r`/`ac` parsing, and the BroadcastChannel nudge and ack between the return page and the tab that shows the code. A wallet-reported decline reaches that tab. - Wallet-granted keys are renewed in the wallet from the low-funds banner, the top-up sheet and Settings, with the identity file as the other way; the write guard passes the session origin to writeFailure and re-checks the session on a write refused as outside the key's bounds. - The wallet tile comes first where v2 is on offer; WalletSupportNote and the sheet copy follow. `connect` is a reserved short-URL segment. Co-Authored-By: Claude Sonnet 5.5 --- forge-web/app/connect/page.tsx | 18 + .../components/auth/connect-return.test.tsx | 95 ++++ forge-web/components/auth/connect-return.tsx | 100 ++++ .../auth/wallet-connect-flow.test.tsx | 454 +++++++++++++++- .../components/auth/wallet-connect-flow.tsx | 510 +++++++++++++++--- forge-web/components/keys-panel.tsx | 24 +- forge-web/components/login-modal.test.tsx | 54 +- forge-web/components/login-modal.tsx | 101 ++-- .../components/low-funds-banner.test.tsx | 82 +++ forge-web/components/low-funds-banner.tsx | 16 +- forge-web/components/repo/bulk-actions.tsx | 4 +- forge-web/components/top-up-sheet.test.tsx | 43 ++ forge-web/components/top-up-sheet.tsx | 32 +- forge-web/contexts/auth-context.tsx | 12 + forge-web/hooks/use-ui-store.ts | 7 +- forge-web/hooks/use-write-guard.test.tsx | 41 +- forge-web/hooks/use-write-guard.ts | 12 +- forge-web/lib/auth/connect-callback.test.ts | 160 ++++++ forge-web/lib/auth/connect-callback.ts | 126 +++++ forge-web/lib/page-title.ts | 1 + forge-web/lib/short-url.ts | 2 + 21 files changed, 1760 insertions(+), 134 deletions(-) create mode 100644 forge-web/app/connect/page.tsx create mode 100644 forge-web/components/auth/connect-return.test.tsx create mode 100644 forge-web/components/auth/connect-return.tsx create mode 100644 forge-web/components/low-funds-banner.test.tsx create mode 100644 forge-web/lib/auth/connect-callback.test.ts create mode 100644 forge-web/lib/auth/connect-callback.ts diff --git a/forge-web/app/connect/page.tsx b/forge-web/app/connect/page.tsx new file mode 100644 index 000000000..07a7f1973 --- /dev/null +++ b/forge-web/app/connect/page.tsx @@ -0,0 +1,18 @@ +'use client' + +/** + * `/connect` — where a wallet returns after an App Connect v2 approval (`cb` in the request). + * Static: it only passes the wallet's nudge to the tab that showed the code + * (`components/auth/connect-return.tsx`, `lib/auth/connect-callback.ts`). + */ + +import { AppShell } from '@/components/app-shell' +import { ConnectReturn } from '@/components/auth/connect-return' + +export default function ConnectPage(): JSX.Element { + return ( + + + + ) +} diff --git a/forge-web/components/auth/connect-return.test.tsx b/forge-web/components/auth/connect-return.test.tsx new file mode 100644 index 000000000..da8db2e8f --- /dev/null +++ b/forge-web/components/auth/connect-return.test.tsx @@ -0,0 +1,95 @@ +// @vitest-environment jsdom +/** + * The page a wallet returns to after an App Connect v2 approval: it nudges the tab that showed the + * code, and when none answers says what the wallet reported and points back to that tab. It never + * continues a sign-in itself. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { CALLBACK_CHANNEL, ACK_WAIT_MS } from '@/lib/auth/connect-callback' + +const replace = vi.hoisted(() => vi.fn()) +// The router object is stable across renders, as Next's is (the page's effect depends on it). +const router = vi.hoisted(() => ({ replace })) +vi.mock('next/navigation', () => ({ useRouter: () => router })) + +const { ConnectReturn } = await import('./connect-return') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const HASH = 'ab'.repeat(20) +let host: HTMLDivElement +let root: Root + +function visit(search: string): void { + window.history.replaceState(null, '', `/connect/${search}`) + act(() => root.render()) +} +const text = (): string => host.textContent ?? '' + +beforeEach(() => { + replace.mockClear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() + vi.useRealTimers() + window.history.replaceState(null, '', '/') +}) + +describe('the wallet return page', () => { + it('goes home when the link is not a well-formed callback', () => { + visit('?r=nope&ac=ok') + expect(replace).toHaveBeenCalledWith('/') + }) + + it('says what a declined or failed approval was, without waiting for a tab', () => { + visit(`?r=${HASH}&ac=declined`) + expect(text()).toContain('Sign-in declined') + // A fresh page load for the next one. + act(() => root.unmount()) + root = createRoot(host) + visit(`?r=${HASH}&ac=failed`) + expect(text()).toContain("Your wallet couldn't finish") + }) + + it('tells the tab with the code about a decline too, so it can stop waiting', async () => { + const waiting = new BroadcastChannel(CALLBACK_CHANNEL) + const seen: unknown[] = [] + waiting.onmessage = (e: MessageEvent) => seen.push(e.data) + visit(`?r=${HASH}&ac=declined`) + await act(async () => new Promise((r) => setTimeout(r, 60))) + expect(seen).toEqual([{ type: 'forge-app-connect-callback', requestHash: HASH, status: 'declined' }]) + expect(text()).toContain('Sign-in declined') + waiting.close() + }) + + it('tells the tab with the code, and steps aside when it answers', async () => { + const waiting = new BroadcastChannel(CALLBACK_CHANNEL) + const seen: unknown[] = [] + waiting.onmessage = (e: MessageEvent) => { + seen.push(e.data) + waiting.postMessage({ type: 'forge-app-connect-ack', requestHash: HASH }) + } + visit(`?r=${HASH}&ac=ok`) + await act(async () => new Promise((r) => setTimeout(r, 60))) + expect(seen).toEqual([{ type: 'forge-app-connect-callback', requestHash: HASH, status: 'ok' }]) + expect(text()).toContain("You're signing in on your other Forge tab") + waiting.close() + }) + + it('points back to the Forge tab where the user started when none answers', () => { + vi.useFakeTimers() + visit(`?r=${HASH}&ac=ok`) + expect(text()).toContain('Finishing sign-in') + act(() => void vi.advanceTimersByTime(ACK_WAIT_MS + 10)) + expect(text()).toContain('Go back to Forge') + expect(text()).toContain('Forge tab where you started') + expect(host.querySelector('a')!.getAttribute('href')).toBe('/') + }) +}) diff --git a/forge-web/components/auth/connect-return.tsx b/forge-web/components/auth/connect-return.tsx new file mode 100644 index 000000000..aded28af1 --- /dev/null +++ b/forge-web/components/auth/connect-return.tsx @@ -0,0 +1,100 @@ +'use client' + +/** + * Where a wallet returns after an App Connect v2 approval (`cb` in the request; `/connect/`). + * + * It is a nudge and nothing more: it tells the tab that showed the code to check now, and if that + * tab answers, this one can be closed. If no tab answers (the code was shown in another browser + * or a tab that was closed), it says what the wallet reported and points back to where the user + * started. It stores nothing and signs nothing: the request's key exists in the first tab's + * memory only, so a sign-in cannot continue here. + */ + +import { useEffect, useState } from 'react' +import Link from 'next/link' +import { useRouter } from 'next/navigation' +import { Button } from '@/components/ui/button' +import { Spinner } from '@/components/ui/states' +import { + ACK_WAIT_MS, + CALLBACK_CHANNEL, + CALLBACK_STATUS_COPY, + isConnectCallbackAck, + parseConnectCallback, + type ConnectCallbackMessage, +} from '@/lib/auth/connect-callback' + +type View = + | { readonly kind: 'waiting' } + | { readonly kind: 'other-tab' } + | { readonly kind: 'status'; readonly title: string; readonly body: string } + +export function ConnectReturn(): JSX.Element { + const router = useRouter() + const [view, setView] = useState({ kind: 'waiting' }) + + useEffect(() => { + const callback = parseConnectCallback(window.location.search) + // Not one of ours: nothing to do here. + if (callback === null) { + router.replace('/') + return + } + // The wallet reported a failure: said at once. The tab that showed the code is told too, so it + // can stop waiting for an answer that will not come. + const failure = callback.status !== null ? CALLBACK_STATUS_COPY[callback.status] : undefined + const fallback: View = { + kind: 'status', + title: 'Go back to Forge', + body: 'Return to the Forge tab where you started. It checks your wallet on its own, and signs you in when the approval is there.', + } + if (failure) setView({ kind: 'status', ...failure }) + let channel: BroadcastChannel | null = null + try { + channel = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel(CALLBACK_CHANNEL) + } catch { + channel = null + } + if (channel === null) { + if (!failure) setView(fallback) + return + } + const open = channel + let answered = false + open.onmessage = (event: MessageEvent) => { + if (!isConnectCallbackAck(event.data, callback.requestHash)) return + answered = true + if (!failure) setView({ kind: 'other-tab' }) + } + const message: ConnectCallbackMessage = { type: 'forge-app-connect-callback', requestHash: callback.requestHash, status: callback.status } + open.postMessage(message) + const timer = setTimeout(() => { + if (!answered && !failure) setView(fallback) + }, ACK_WAIT_MS) + return () => { + clearTimeout(timer) + open.close() + } + }, [router]) + + return ( +
+ {view.kind === 'waiting' ? : null} + {view.kind === 'other-tab' ? ( + <> +

You're signing in on your other Forge tab

+

You can close this one.

+ + ) : null} + {view.kind === 'status' ? ( + <> +

{view.title}

+

{view.body}

+ + + + + ) : null} +
+ ) +} diff --git a/forge-web/components/auth/wallet-connect-flow.test.tsx b/forge-web/components/auth/wallet-connect-flow.test.tsx index 12d3b216d..c755552cc 100644 --- a/forge-web/components/auth/wallet-connect-flow.test.tsx +++ b/forge-web/components/auth/wallet-connect-flow.test.tsx @@ -3,6 +3,11 @@ * Wallet sign-in over an unfinished renewal whose key is locked: the renewal's passphrase input is * uncontrolled, so the typed passphrase never lands in the DOM's `value` attribute. The wallet's * encryption key goes to the sign-in with every attempt, and is wiped once it is done (D27). + * + * App Connect v2: shown first where the chain supports it (with the group check and the locked-key + * check before the code), a link to the older code and back, the poll cut short on focus and on the + * return page's message, the confirm step, and a renewal in the wallet that granted the key + * (protection first, the old key's renewal mark ended on every way out but a stored key). */ import { act } from 'react' @@ -10,11 +15,32 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { PendingRenewalChoiceError, PendingRenewalLockedError } from '@/lib/auth/controller' -const { ID, FORGE, answered } = vi.hoisted(() => ({ +const { ID, FORGE, answered, v2, auth } = vi.hoisted(() => ({ ID: '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD', FORGE: { core: 'CoreContract111', collab: 'CollabContract111', community: 'CommunityContract111', group: 'Group111' }, /** The encryption keys of the last answer the fake wallet gave. */ answered: { keys: [] as Uint8Array[] }, + /** The App Connect v2 side of the fake chain and wallet. */ + v2: { + available: false, + /** What the fake wallet answers: resolve it from a test, or reject it. */ + pending: null as { resolve: (g: unknown) => void; reject: (e: Error) => void } | null, + trigger: null as { fire: () => void } | null, + awaited: 0, + calls: [] as string[], + /** The older (v1) request stays unanswered, so its request step stays on screen. */ + holdV1: false, + /** The older flow's response-source lookup never returns (it is still being built). */ + holdSources: false, + /** The renewal request's private key, to see it spent. */ + renewalPriv: null as Uint8Array | null, + }, + /** The signed-in session and controller the flow reads. */ + auth: { + identity: null as string | null, + unlockScope: null as 'full' | 'signing' | null, + controller: {} as Record, + }, })) const FAKE_VAULT_PASSPHRASE = 'fake-vault-passphrase-000' const FAKE_RENEWAL_PASSPHRASE = 'fake-renewal-passphrase-789' @@ -31,13 +57,35 @@ vi.mock('@/lib/auth/connect', async (importOriginal) => ({ })) vi.mock('@/lib/auth/app-connect', async (importOriginal) => ({ ...(await importOriginal()), - responseSources: async () => [{}], - newLoginRequest: () => ({ uri: 'dash-key:fake', expiresAt: Date.now() + 60_000 }), + responseSources: async () => (v2.holdSources ? new Promise(() => undefined) : [{}]), + newLoginRequest: () => { + v2.calls.push('v1-request') + return { uri: 'dash-key:fake', expiresAt: Date.now() + 60_000 } + }, awaitWalletAnswer: async () => { + if (v2.holdV1) return new Promise(() => undefined) answered.keys = [new Uint8Array(32).fill(0x42)] return { kind: 'keys', identityId: ID, keys: [{ scope: {}, limits: {} }], encryptionKeys: answered.keys } }, })) +vi.mock('@/lib/auth/app-connect-v2', async (importOriginal) => ({ + ...(await importOriginal()), + appConnectV2Available: async () => v2.available, + readChainClock: async () => ({ timeMs: 1_800_000_000_000, protocolVersion: 14 }), + newV2LoginRequest: () => { + v2.calls.push('request') + return fakeV2Request(null) + }, + awaitV2Grant: (_sdk: unknown, _req: unknown, p: { trigger: { fire: () => void }; signal: AbortSignal }) => { + v2.awaited++ + v2.trigger = p.trigger + return new Promise((resolve, reject) => { + v2.pending = { resolve, reject } + // The real poll ends with an AbortError when the sheet closes or restarts. + p.signal.addEventListener('abort', () => reject(new DOMException('cancelled', 'AbortError')), { once: true }) + }) + }, +})) vi.mock('@/lib/auth/key-registration', async (importOriginal) => ({ ...(await importOriginal()), isUnlimited: () => false, @@ -45,11 +93,34 @@ vi.mock('@/lib/auth/key-registration', async (importOriginal) => ({ vi.mock('@/lib/auth/responder-profile', () => ({ responderProfile: async () => ({ identityId: ID, name: null, namedAt: null, warnings: [] }), })) -vi.mock('@/components/ui/qr', () => ({ Qr: () => null })) +vi.mock('@/components/ui/qr', () => ({ Qr: ({ value }: { value: string }) =>
{value}
})) vi.mock('@/contexts/auth-context', () => ({ - useAuth: () => ({ adoptWalletKeys, addWalletGrant: vi.fn(), identity: null, isLoading: false, vaults: [], unlockScope: null }), + useAuth: () => ({ + adoptWalletKeys, + addWalletGrant: vi.fn(), + identity: auth.identity, + isLoading: false, + vaults: [], + unlockScope: auth.unlockScope, + controller: auth.controller, + }), })) +/** A v2 request as the (mocked) builder returns it; `hint`: the identity a renewal names. */ +function fakeV2Request(hint: string | null): { appEphemeralPriv: Uint8Array } & Record { + return { + request: { authBindings: [{ totalBudget: 5_000_000_000n, expiresAt: 1_807_776_000_000 }] }, + qrUri: 'dash-key:v2qr?v=2', + linkUri: 'dash-key:v2link?v=2&cb=x', + requestHash: new Uint8Array(20).fill(0xab), + createdAt: Date.now(), + expiresAt: Date.now() + 600_000, + chainTimeAtCreation: 1_800_000_000_000, + identityHint: hint, + appEphemeralPriv: new Uint8Array(32).fill(7), + } +} + const { WalletConnectFlow } = await import('./wallet-connect-flow') ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true @@ -68,8 +139,39 @@ async function flush(): Promise { for (let i = 0; i < 5; i++) await act(async () => Promise.resolve()) } +const checkGroup = vi.fn() +const walletSignInBlocker = vi.fn() +const walletRenewalRequest = vi.fn() +const endWalletRenewal = vi.fn() + beforeEach(() => { adoptWalletKeys.mockReset() + v2.available = false + v2.pending = null + v2.trigger = null + v2.awaited = 0 + v2.calls = [] + v2.holdV1 = false + v2.holdSources = false + v2.renewalPriv = null + auth.identity = null + auth.unlockScope = null + checkGroup.mockReset().mockImplementation(async () => { + v2.calls.push('group') + return { unknown: [], unchecked: [], notice: null } + }) + walletSignInBlocker.mockReset().mockImplementation(async () => { + v2.calls.push('blocker') + return null + }) + walletRenewalRequest.mockReset().mockImplementation(async () => { + v2.calls.push('renewal-request') + const req = { ...fakeV2Request(ID), replacesKeyId: 7 } + v2.renewalPriv = req.appEphemeralPriv + return req + }) + endWalletRenewal.mockReset() + auth.controller = { checkGroup, walletSignInBlocker, walletRenewalRequest, endWalletRenewal } host = document.createElement('div') document.body.appendChild(host) root = createRoot(host) @@ -123,3 +225,345 @@ describe('WalletConnectFlow: a locked unfinished renewal', () => { expect(answered.keys[0]!.every((b) => b === 0)).toBe(true) }) }) + +/** What the verified v2 grant is: the identity and its group-bound key (budget 0.05 DASH). */ +const V2_GRANT = { + identityId: ID, + key: { keyId: 9, wif: 'wif', scope: { unbounded: false }, limits: { remaining: 5_000_000_000n, total: 5_000_000_000n, expiresAt: 1_807_776_000_000 } }, +} +const q = (testId: string): HTMLElement | null => host.querySelector(`[data-testid="${testId}"]`) + +describe('WalletConnectFlow: App Connect v2 sign-in', () => { + it('shows the v2 request first, after the group and locked-key checks, with one-approval terms', async () => { + v2.available = true + act(() => root.render()) + await flush() + expect(v2.calls).toEqual(['group', 'blocker', 'request']) + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + expect(q('approval-terms')!.textContent).toMatch(/One approval covers all of Forge, spending up to 0\.05\d* DASH/) + expect(q('approval-terms')!.textContent).toMatch(/until /) + expect(q('wallet-support')!.textContent).toMatch(/App Connect v2/) + expect(q('older-code')!.textContent).toBe('Using a Dash Wallet build without App Connect v2? Show the older code') + expect(v2.awaited).toBe(1) + }) + + it('goes straight to the older code where v2 is not available', async () => { + v2.holdV1 = true + act(() => root.render()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:fake') + expect(q('older-code')).toBeNull() + expect(q('newer-code')).toBeNull() + expect(v2.calls).toEqual(['v1-request']) + }) + + it('falls back to the older code when the group check refuses', async () => { + v2.available = true + v2.holdV1 = true + checkGroup.mockRejectedValueOnce(new Error('refusing to bind a key to this group')) + act(() => root.render()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:fake') + expect(v2.awaited).toBe(0) + }) + + it('switches to the older code and back', async () => { + v2.available = true + v2.holdV1 = true + act(() => root.render()) + await flush() + await act(async () => q('older-code')!.click()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:fake') + expect(q('wallet-support')!.textContent).not.toMatch(/App Connect v2/) + expect(q('older-code')).toBeNull() + await act(async () => q('newer-code')!.click()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + }) + + it('asks to unlock first when a locked vault holds a wallet key', async () => { + v2.available = true + walletSignInBlocker.mockResolvedValueOnce('Unlock the key stored for 9r27eD…9dUD first.') + const onUnlock = vi.fn() + act(() => root.render()) + await flush() + expect(q('wallet-blocked')!.textContent).toContain('Unlock the key stored') + expect(q('qr-value')).toBeNull() + expect(v2.calls).not.toContain('request') + await act(async () => byText('Unlock').click()) + expect(onUnlock).toHaveBeenCalled() + }) + + it('confirms who answered, shows the granted limits and the group notice, then stores it as App Connect\'s', async () => { + v2.available = true + checkGroup.mockResolvedValueOnce({ unknown: ['x'], unchecked: [], notice: 'The group also holds 1 contract this build does not know.' }) + const onDone = vi.fn() + adoptWalletKeys.mockResolvedValue(undefined) + act(() => root.render()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(q('wallet-confirm')).not.toBeNull() + expect(q('granted-identity')!.textContent).toBe(ID) + expect(q('unlimited-key-warning')).toBeNull() + expect(q('approval-terms')!.textContent).toMatch(/spending capped at 0\.05\d* DASH/) + expect(q('group-notice')!.textContent).toContain('does not know') + act(() => host.querySelector('input[type="checkbox"]')!.click()) + act(() => type(host.querySelector('#vault-passphrase')!, FAKE_VAULT_PASSPHRASE)) + act(() => type(host.querySelector('#vault-passphrase-2')!, FAKE_VAULT_PASSPHRASE)) + await act(async () => byText('Finish signing in').click()) + expect(adoptWalletKeys).toHaveBeenCalledWith(ID, [V2_GRANT.key], expect.objectContaining({ passphrase: FAKE_VAULT_PASSPHRASE }), { + discardPendingRenewal: false, + origin: 'app-connect', + }) + expect(onDone).toHaveBeenCalled() + }) + + it('polls at once when the tab regains focus or becomes visible', async () => { + v2.available = true + act(() => root.render()) + await flush() + const fire = vi.spyOn(v2.trigger!, 'fire') + act(() => void window.dispatchEvent(new Event('focus'))) + expect(fire).toHaveBeenCalledTimes(1) + act(() => void document.dispatchEvent(new Event('visibilitychange'))) + expect(fire).toHaveBeenCalledTimes(2) + }) + + it("polls at once when the return page reports this request, and ignores another's", async () => { + v2.available = true + act(() => root.render()) + await flush() + const fire = vi.spyOn(v2.trigger!, 'fire') + const page = new BroadcastChannel('forge-app-connect') + const acks: unknown[] = [] + page.onmessage = (e: MessageEvent) => acks.push(e.data) + page.postMessage({ type: 'forge-app-connect-callback', requestHash: 'cd'.repeat(20), status: 'ok' }) + page.postMessage({ type: 'forge-app-connect-callback', requestHash: 'ab'.repeat(20), status: 'ok' }) + await new Promise((r) => setTimeout(r, 40)) + expect(fire).toHaveBeenCalledTimes(1) + expect(acks).toEqual([{ type: 'forge-app-connect-ack', requestHash: 'ab'.repeat(20) }]) + page.close() + }) + + it('names a refusal and offers another try', async () => { + v2.available = true + act(() => root.render()) + await flush() + await act(async () => v2.pending!.reject(new Error('Two identities answered.'))) + await flush() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('Two identities answered.') + expect(byText('Try again')).toBeDefined() + }) +}) + +describe('WalletConnectFlow: App Connect v2, the edges', () => { + it('takes the old request off screen at once when the code is switched', async () => { + v2.available = true + act(() => root.render()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + // The older flow is still being built (its sources are not back): the spent v2 code must not stay up. + v2.holdSources = true + await act(async () => q('older-code')!.click()) + await flush() + expect(q('qr-value')).toBeNull() + expect(q('older-code')).toBeNull() + expect(host.textContent).toContain('Finding the wallet login contract') + }) + + it('shows a failed group read with Try again, not a silent switch to the older code', async () => { + v2.available = true + checkGroup.mockRejectedValueOnce(new Error('Reading the contract group timed out')) + act(() => root.render()) + await flush() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('timed out') + expect(byText('Try again')).toBeDefined() + expect(v2.calls).not.toContain('v1-request') + expect(v2.awaited).toBe(0) + }) + + it('says what the wallet reported when it returns with a decline', async () => { + v2.available = true + act(() => root.render()) + await flush() + const page = new BroadcastChannel('forge-app-connect') + page.postMessage({ type: 'forge-app-connect-callback', requestHash: 'ab'.repeat(20), status: 'declined' }) + await act(async () => new Promise((r) => setTimeout(r, 40))) + expect(q('wallet-reported')!.textContent).toContain('Sign-in declined') + page.close() + }) +}) + +describe('WalletConnectFlow: renew in the wallet that granted the key', () => { + const fillProtection = (): void => { + act(() => type(host.querySelector('#vault-passphrase')!, FAKE_VAULT_PASSPHRASE)) + act(() => type(host.querySelector('#vault-passphrase-2')!, FAKE_VAULT_PASSPHRASE)) + } + + it('chooses the protection before any request exists', async () => { + auth.identity = ID + act(() => root.render()) + await flush() + expect(q('wallet-renew-prepare')).not.toBeNull() + expect(q('qr-value')).toBeNull() + expect(walletRenewalRequest).not.toHaveBeenCalled() + expect(byText('Continue to your wallet').disabled).toBe(true) + fillProtection() + expect(byText('Continue to your wallet').disabled).toBe(false) + expect(walletRenewalRequest).not.toHaveBeenCalled() + }) + + it('shows the code, stores the new key as App Connect\'s and keeps the renewal mark until then', async () => { + auth.identity = ID + adoptWalletKeys.mockResolvedValue(undefined) + const onDone = vi.fn() + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + expect(walletRenewalRequest).toHaveBeenCalledTimes(1) + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + expect(q('approval-terms')!.textContent).toMatch(/Approve the renewal in the wallet/) + expect(q('older-code')).toBeNull() + expect(endWalletRenewal).not.toHaveBeenCalled() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(adoptWalletKeys).toHaveBeenCalledWith(ID, [V2_GRANT.key], expect.objectContaining({ passphrase: FAKE_VAULT_PASSPHRASE }), { + discardPendingRenewal: false, + origin: 'app-connect', + }) + expect(onDone).toHaveBeenCalled() + // Stored: the controller already cleared the mark. + expect(endWalletRenewal).not.toHaveBeenCalled() + }) + + it('ends the renewal when the sheet closes before the wallet answers', async () => { + auth.identity = ID + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => { + root.render(<>) + }) + // The poll ends with an abort; the renewal's mark goes with it. + await act(async () => v2.pending!.reject(new DOMException('cancelled', 'AbortError'))) + await flush() + expect(endWalletRenewal).toHaveBeenCalledWith(expect.objectContaining({ identityHint: ID, replacesKeyId: 7 })) + expect(adoptWalletKeys).not.toHaveBeenCalled() + }) + + it('ends the renewal when the wallet refuses, and names why', async () => { + auth.identity = ID + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.reject(new Error("The key your wallet sent has no spending limit or no expiry. Forge didn't use it."))) + await flush() + expect(endWalletRenewal).toHaveBeenCalledTimes(1) + expect(host.querySelector('[role="alert"]')!.textContent).toContain('no spending limit') + }) + + it('keeps a granted key that failed to store on screen, with the reason', async () => { + auth.identity = ID + adoptWalletKeys.mockRejectedValue(new Error('Another tab changed the key stored meanwhile.')) + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(q('wallet-renew-store')).not.toBeNull() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('Another tab changed') + expect(byText('Store the new key')).toBeDefined() + // Not given up until the sheet closes. + expect(endWalletRenewal).not.toHaveBeenCalled() + }) + + it('closing the sheet before the wallet request exists spends it and ends the renewal', async () => { + auth.identity = ID + let release: () => void = () => undefined + const gate = new Promise((resolve) => { + release = resolve + }) + walletRenewalRequest.mockImplementation(async () => { + await gate + const req = { ...fakeV2Request(ID), replacesKeyId: 7 } + v2.renewalPriv = req.appEphemeralPriv + return req + }) + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => { + root.render(<>) + }) + await act(async () => release()) + await flush() + expect(v2.awaited).toBe(0) + expect(endWalletRenewal).toHaveBeenCalledWith(expect.objectContaining({ identityHint: ID, replacesKeyId: 7 })) + expect(v2.renewalPriv!.every((b) => b === 0)).toBe(true) + }) + + it('a granted key that cannot be stored yet is held for a decision, then stored', async () => { + auth.identity = ID + adoptWalletKeys.mockRejectedValueOnce(new PendingRenewalChoiceError(7)).mockResolvedValueOnce(undefined) + const onDone = vi.fn() + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + // The wallet has disabled the old key: the new one is kept on screen, not dropped. + expect(q('wallet-renew-store')).not.toBeNull() + expect(q('pending-renewal-choice')).not.toBeNull() + expect(onDone).not.toHaveBeenCalled() + expect(endWalletRenewal).not.toHaveBeenCalled() + await act(async () => byText('Continue with the wallet').click()) + await flush() + expect(adoptWalletKeys).toHaveBeenLastCalledWith(ID, [V2_GRANT.key], expect.anything(), { discardPendingRenewal: true, origin: 'app-connect' }) + expect(onDone).toHaveBeenCalled() + expect(endWalletRenewal).not.toHaveBeenCalled() + }) + + it('closing the sheet with the new key unstored ends the renewal', async () => { + auth.identity = ID + adoptWalletKeys.mockRejectedValue(new Error('The vault is locked.')) + const onUnlock = vi.fn() + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(q('wallet-renew-store')).not.toBeNull() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('vault is locked') + await act(async () => byText('Unlock').click()) + expect(onUnlock).toHaveBeenCalled() + expect(endWalletRenewal).not.toHaveBeenCalled() + act(() => root.unmount()) + expect(endWalletRenewal).toHaveBeenCalledTimes(1) + root = createRoot(host) + }) + + it('asks a signing-only tab to unlock first', async () => { + auth.identity = ID + auth.unlockScope = 'signing' + act(() => root.render()) + await flush() + expect(q('renew-unlock')).not.toBeNull() + expect(walletRenewalRequest).not.toHaveBeenCalled() + }) +}) diff --git a/forge-web/components/auth/wallet-connect-flow.tsx b/forge-web/components/auth/wallet-connect-flow.tsx index bf57987dc..cd82e9151 100644 --- a/forge-web/components/auth/wallet-connect-flow.tsx +++ b/forge-web/components/auth/wallet-connect-flow.tsx @@ -19,6 +19,19 @@ * * Dash Wallet answers on testnet only (`walletSignInSupported`); elsewhere the sheet says so. * + * App Connect v2 (`lib/auth/app-connect-v2.ts`) comes first where the network and the chain allow + * it: ONE request, one approval, one key bound to the whole Forge contract group with a budget + * and an expiry, so no guided grants follow. A link switches to the v1 flow above for wallets + * that do not speak v2 (the two never share a QR: a v1-only wallet refuses `v=2`). The phone's + * deep link carries a callback to `/connect/`; the poll also runs when the tab regains focus and + * when that page reports the wallet came back (`lib/auth/connect-callback.ts`). Without an + * identity hint the confirm step stays ("A wallet answered for this identity"). + * + * `mode="renew"` renews the signed-in session's key in the wallet that granted it (origin + * `app-connect`): the protection for the new key is chosen BEFORE the code shows (the wallet + * disables the old key when it approves), the request names the identity, and the new key is + * stored without a confirm step. + * * `mode="grant"` asks the signed-in identity's wallet for a key on another contract (a shipped * wallet grants one contract per approval) and adds it to the session: no confirmation step, * since only answers from the signed-in identity are read. @@ -31,9 +44,10 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { AlertTriangle, RefreshCw, Smartphone } from 'lucide-react' +import { FiatNote } from '@/components/ui/fiat-note' import { useAuth } from '@/contexts/auth-context' import { useUiStore } from '@/hooks/use-ui-store' -import { PendingRenewalChoiceError, PendingRenewalLockedError, UnlockNeededError } from '@/lib/auth/controller' +import { PendingRenewalChoiceError, PendingRenewalLockedError, UnlockNeededError, type WalletRenewalRequest } from '@/lib/auth/controller' import { Button } from '@/components/ui/button' import { UnlockMore } from '@/components/auth/unlock-more' import { Field, Input } from '@/components/ui/input' @@ -42,6 +56,7 @@ import { ErrorBox, useProtection } from '@/components/auth/protection-fields' import { Waiting } from '@/components/auth/step-status' import { ScanOnlyHere } from '@/components/auth/scan-warning' import { ACTIVE_NETWORK } from '@/lib/constants' +import { creditsToDash } from '@/lib/sdk/cost' import { REQUEST_TTL_MS, RequestExpired, @@ -54,12 +69,26 @@ import { type PollStatus, type WalletAnswer, } from '@/lib/auth/app-connect' +import { + PollTrigger, + appConnectV2Available, + awaitV2Grant, + disposeV2Request, + newV2LoginRequest, + readChainClock, + type V2Grant, + type V2LoginRequest, +} from '@/lib/auth/app-connect-v2' +import { connectionId } from '@/lib/auth/connection-id' +import { CALLBACK_STATUS_COPY, connectCallbackUrl, listenForCallback } from '@/lib/auth/connect-callback' +import { defaultLimits } from '@/lib/auth/limited-key' import { GRANT_COPY, isUnlimited, keyRegistrationUri, scopeCovers, type WalletKey } from '@/lib/auth/key-registration' -import { contractKind } from '@/lib/deployments' +import { contractKind, type ForgeIds } from '@/lib/deployments' import { responderProfile, type ResponderProfile } from '@/lib/auth/responder-profile' import { isAbort } from '@/lib/sdk/facade' import { PHASE_TEXT, connectPlatform, withPlatformRead } from '@/lib/auth/connect' -import { formatDate } from '@/lib/view/format' +import { creditsAsDash, formatDate } from '@/lib/view/format' +import type { KeyLimits } from '@/lib/view/funds' import { cn, errorMessage } from '@/lib/utils' /** The wallet link where a wallet can answer (the main action), and where none can (secondary). */ @@ -67,12 +96,82 @@ const DEEP_LINK_PRIMARY = 'bg-forge-700 text-white hover:bg-forge-800' const DEEP_LINK_SECONDARY = 'border border-anvil-300 text-anvil-800 hover:bg-anvil-100 dark:border-anvil-700 dark:text-anvil-100 dark:hover:bg-anvil-800' +/** A small underlined text button under the code (the older/newer code links). */ +const TEXT_BUTTON = 'hit-area block text-[12px] text-anvil-500 underline hover:text-anvil-800 dark:text-anvil-400 dark:hover:text-anvil-100' + +type Sdk = Awaited> + +/** What a v2 request asks the wallet for: the budget (credits) and the proposed expiry (ms). */ +interface V2Terms { + readonly budget: bigint | null + readonly expiresAt: number | null +} + type Step = - | { readonly kind: 'request'; readonly uri: string; readonly expiresAt: number } + /** `linkUri`: the phone's deep link (v2: it carries the callback); `v2`: the App Connect v2 request. */ + | { readonly kind: 'request'; readonly uri: string; readonly linkUri?: string; readonly expiresAt: number; readonly v2?: V2Terms } | { readonly kind: 'register'; readonly uri: string; readonly expiresAt: number } - | { readonly kind: 'confirm'; readonly profile: ResponderProfile; readonly unlimited: boolean; readonly unbounded: boolean } + | { + readonly kind: 'confirm' + readonly profile: ResponderProfile + readonly unlimited: boolean + readonly unbounded: boolean + /** A v2 grant's limits (as the chain records them), and the group check's notice. */ + readonly v2?: { readonly limits: KeyLimits | null; readonly notice: string | null } + } + /** A locked vault holds a wallet key that a new approval would disable: unlock it first. */ + | { readonly kind: 'blocked'; readonly message: string } + /** + * A renewal's new key is granted (the wallet has already disabled the old one) and is being + * stored. When storing needs a decision or an unlock (an unfinished renewal on this device, a + * locked vault), the grant is held here to try again; closing the sheet drops it. + */ + | { readonly kind: 'renew-store' } | { readonly kind: 'expired' } +/** The request's primary binding as {@link V2Terms}. */ +function termsOf(req: V2LoginRequest): V2Terms { + const binding = req.request.authBindings[0] + return { budget: binding?.totalBudget ?? null, expiresAt: binding?.expiresAt ?? null } +} + +/** + * Poll for the wallet's v2 answer, and poll at once when the tab regains focus or becomes visible + * (the user comes back from the wallet) or the `/connect/` page reports the wallet returned + * (`onReturn` gets the status it carries). The request is spent however this ends. + */ +export function awaitGrantWithWake( + sdk: Parameters[0], + req: V2LoginRequest, + p: Omit[2], 'trigger'> & { readonly onReturn?: (status: string | null) => void }, +): Promise { + const { onReturn, ...rest } = p + const trigger = new PollTrigger() + const wake = (): void => trigger.fire() + const onVisible = (): void => { + if (document.visibilityState === 'visible') trigger.fire() + } + let stopCallback = (): void => undefined + const stop = (): void => { + window.removeEventListener('focus', wake) + document.removeEventListener('visibilitychange', onVisible) + stopCallback() + } + try { + window.addEventListener('focus', wake) + document.addEventListener('visibilitychange', onVisible) + stopCallback = listenForCallback(req.requestHash, (status) => { + onReturn?.(status) + wake() + }) + } catch (e) { + stop() + disposeV2Request(req) + return Promise.reject(e) + } + return awaitV2Grant(sdk, req, { ...rest, trigger }).finally(stop) +} + /** * A phone or tablet browser: the wallet is on this device, so a link beats a QR. Dash Wallet * exists for Android and iOS only, so a desktop browser gets the QR alone. @@ -83,8 +182,19 @@ function onMobile(): boolean { return uaData?.mobile ?? /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent) } -export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDone: () => void; mode?: 'login' | 'grant'; contractId?: string }): JSX.Element { - const { adoptWalletKeys, addWalletGrant, identity, isLoading, vaults, unlockScope } = useAuth() +export function WalletConnectFlow({ + onDone, + mode = 'login', + contractId, + onUnlock, +}: { + onDone: () => void + mode?: 'login' | 'grant' | 'renew' + contractId?: string + /** Open the sheet's Unlock view (a v2 sign-in that must wait for a locked wallet key to be opened). */ + onUnlock?: () => void +}): JSX.Element { + const { adoptWalletKeys, addWalletGrant, identity, isLoading, vaults, unlockScope, controller } = useAuth() // Read when the request starts (a scope change must not restart a running request). const scopeRef = useRef(unlockScope) scopeRef.current = unlockScope @@ -117,32 +227,59 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo const [preparing, setPreparing] = useState(PHASE_TEXT.connecting) const [attempt, setAttempt] = useState(0) const [confirmed, setConfirmed] = useState(false) - const grant = useRef<{ identityId: string; keys: readonly WalletKey[]; answer: WalletAnswer } | null>(null) + /** The answer held for the confirm step: a v1 answer (its key bytes are wiped) or a v2 grant (`answer: null`). */ + const grant = useRef<{ identityId: string; keys: readonly WalletKey[]; answer: WalletAnswer | null } | null>(null) /** Wipe the held answer's private key bytes and drop the grant. */ const dropGrant = useCallback(() => { - if (grant.current) wipeAnswer(grant.current.answer) + if (grant.current?.answer) wipeAnswer(grant.current.answer) grant.current = null }, []) const mobile = onMobile() const unlimited = step?.kind === 'confirm' && step.unlimited const { fields, protection, problem } = useProtection({ preferPasskey: unlimited }) + /** + * The wallet-login version the user asked for with "Show the older code" (v1), and whether a v2 + * request was on offer here at all (then the v1 code links back to it). + */ + const [olderCode, setOlderCode] = useState(false) + const [v2Offered, setV2Offered] = useState(false) + /** + * Renewal: the protection for the new key is chosen first (the wallet disables the old key when + * it approves), then the code shows. `renewGo` flips on that choice; the protection is kept for + * a retry. The renewal is of the signed-in session; its tab must be fully unlocked. + */ + const [renewGo, setRenewGo] = useState(false) + const renewProtection = useRef | null>(null) + const needsUnlock = mode === 'renew' && unlockScope === 'signing' + /** A wallet renewal whose new key is not stored yet: its mark ends if the sheet closes first. */ + const renewalReq = useRef(null) + /** What the wallet's return page reported (`ac`), when it was a failure. */ + const [reported, setReported] = useState(null) // Read at request time, not effect deps: a change must not restart a request mid-flow (the // identity changes from null to the new one inside the login itself). - const latest = useRef({ addWalletGrant, onDone, stored: vaults.map((v) => v.identityId) }) - latest.current = { addWalletGrant, onDone, stored: vaults.map((v) => v.identityId) } + const latest = useRef({ addWalletGrant, adoptWalletKeys, onDone, controller, stored: vaults.map((v) => v.identityId) }) + latest.current = { addWalletGrant, adoptWalletKeys, onDone, controller, stored: vaults.map((v) => v.identityId) } // A grant is for the signed-in identity: a different one (or signing out) starts over. const grantFor = mode === 'grant' ? identity : null // The sign-in sheet: unlocking there finishes an unfinished renewal with its passphrase. const openLogin = useUiStore((s) => s.openLogin) + // The sheet closes with a renewal's new key unstored (the old one is already disabled): no key + // is being replaced after all, so other tabs stop expecting one. + useEffect( + () => () => { + if (renewalReq.current) latest.current.controller.endWalletRenewal(renewalReq.current) + }, + [], + ) + // A reloaded tab holds the signing key only: storing the wallet's keys over the stored key + // (carrying its grants and settings across) needs the vault open. Unlock, then carry on. + const [unlockFirst, setUnlockFirst] = useState<(() => void) | null>(null) /** * Store the wallet's keys. `discard`: give up an unfinished renewal on this device first, * keeping its key (opened with `renewalUnlock` when given) for the next revoke to disable; * `drop`: give it up without its key. */ - // A reloaded tab holds the signing key only: storing the wallet's keys over the stored key - // (carrying its grants and settings across) needs the vault open. Unlock, then carry on. - const [unlockFirst, setUnlockFirst] = useState<(() => void) | null>(null) const finish = async (discard: boolean, renewalUnlock?: { passphrase: string } | 'passkey', drop = false): Promise => { const g = grant.current if (!protection || !g) return @@ -152,10 +289,12 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo discardPendingRenewal: discard, ...(renewalUnlock ? { renewalUnlock } : {}), ...(drop ? { dropUnopened: true } : {}), - encryptionKeys: g.answer.encryptionKeys, - justRegistered: g.answer.kind === 'register', + // A v1 answer brings the wallet's encryption key; a v2 grant has none and is stored as App Connect's. + ...(g.answer ? { encryptionKeys: g.answer.encryptionKeys, justRegistered: g.answer.kind === 'register' } : { origin: 'app-connect' as const }), }) dropGrant() + // Stored: the controller already ended a wallet renewal's mark. + renewalReq.current = null setPendingRenewal(null) setRenewalLocked(null) if (renewalPassphraseRef.current) renewalPassphraseRef.current.value = '' @@ -172,20 +311,43 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo } } + // The effect below stores a renewal's grant through the latest render's `finish`. + const finishRef = useRef(finish) + finishRef.current = finish + useEffect(() => { - const controller = new AbortController() - const signal = controller.signal + const abort = new AbortController() + const signal = abort.signal setError(null) setConfirmed(false) setStatus('waiting') + setReported(null) void (async () => { try { if (!forge) throw new Error('Dash Forge is not deployed here') if (mode === 'grant' && !grantFor) throw new Error('Sign in (or unlock) first: the approval is added to the signed-in identity.') // A grant is sealed with the vault: a reloaded (signing-only) tab unlocks first (below). if (mode === 'grant' && scopeRef.current === 'signing') return + // A renewal waits for its protection (chosen before the code shows) and for a full unlock. + if (mode === 'renew' && (!renewGo || scopeRef.current === 'signing')) return const sdk = await connectPlatform(ACTIVE_NETWORK.network, (p) => !signal.aborted && setPreparing(PHASE_TEXT[p])) if (signal.aborted) return + if (mode === 'renew') { + await runRenewal(sdk, forge, signal) + return + } + // App Connect v2 first where the network and the chain allow it, unless the user asked + // for the older code (a wallet without v2 refuses a v2 request). + if (mode === 'login') { + setPreparing('Checking what your wallet can answer') + const v2 = await v2Offer(sdk) + if (signal.aborted) return + setV2Offered(v2.available) + if (v2.available && !olderCode) { + await runV2Login(sdk, forge, signal, v2.notice) + return + } + } setPreparing('Finding the wallet login contract') const sources = await withPlatformRead(responseSources(sdk, ACTIVE_NETWORK.key), 'Finding the wallet login contract') if (signal.aborted) return @@ -239,19 +401,211 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo else setError(errorMessage(e)) } })() + + /** Whether a v2 request can be offered here, and the group check's notice for the confirm step. */ + async function v2Offer(sdk: Sdk): Promise<{ available: boolean; notice: string | null }> { + if (!(await appConnectV2Available(sdk, ACTIVE_NETWORK.network))) return { available: false, notice: null } + try { + // Forge's own group check, before any code shows. + const check = await latest.current.controller.checkGroup() + return { available: true, notice: check.notice } + } catch (e) { + // Only Forge's refusal of the group means "no v2 here"; a failed read is shown, with Try again. + if (errorMessage(e).startsWith('refusing to bind')) return { available: false, notice: null } + throw e + } + } + + /** What both v2 paths pass the poll: status updates only while this request is current. */ + const pollOptions = (forge: ForgeIds): Parameters[2] => ({ + network: ACTIVE_NETWORK.network, + forge, + signal, + onStatus: (s) => { + if (!signal.aborted) setStatus(s) + }, + onReturn: (status) => { + if (!signal.aborted) setReported(status) + }, + }) + + /** v2 sign-in: one request, then the confirm step (nobody is named, so anyone could answer). */ + async function runV2Login(sdk: Sdk, forge: ForgeIds, aborted: AbortSignal, notice: string | null): Promise { + // Any approval disables the key of this browser's previous grant: a locked vault that holds + // one is opened first, while it still can be. + const blocker = await latest.current.controller.walletSignInBlocker() + if (aborted.aborted) return + if (blocker !== null) { + setStep({ kind: 'blocked', message: blocker }) + return + } + const { timeMs } = await readChainClock(sdk) + if (aborted.aborted) return + const req = newV2LoginRequest(ACTIVE_NETWORK.network, forge, { + connectionId: connectionId(ACTIVE_NETWORK.key), + chainNow: timeMs, + callbackUrl: connectCallbackUrl, + }) + setStep({ kind: 'request', uri: req.qrUri, linkUri: req.linkUri, expiresAt: req.expiresAt, v2: termsOf(req) }) + const granted = await awaitGrantWithWake(sdk, req, pollOptions(forge)) + if (aborted.aborted) return + grant.current = { identityId: granted.identityId, keys: [granted.key], answer: null } + const profile = await responderProfile(sdk, granted.identityId, ACTIVE_NETWORK.network, latest.current.stored) + if (aborted.aborted) return + setStep({ kind: 'confirm', profile, unlimited: false, unbounded: false, v2: { limits: granted.key.limits, notice } }) + } + + /** Renewal: the wallet that granted this browser's key grants a new one (no confirm: the identity is known). */ + async function runRenewal(sdk: Sdk, forge: ForgeIds, aborted: AbortSignal): Promise { + if (!renewProtection.current) throw new Error('Choose how to protect the new key first.') + const auth = latest.current.controller + const req = await auth.walletRenewalRequest({ callbackUrl: connectCallbackUrl }) + let granted: V2Grant + try { + if (aborted.aborted) { + disposeV2Request(req) + auth.endWalletRenewal(req) + return + } + setStep({ kind: 'request', uri: req.qrUri, linkUri: req.linkUri, expiresAt: req.expiresAt, v2: termsOf(req) }) + granted = await awaitGrantWithWake(sdk, req, pollOptions(forge)) + } catch (e) { + // Cancelled, expired or refused: the old key is not being replaced after all. + auth.endWalletRenewal(req) + throw e + } + // The wallet has answered, so it has disabled the old key: store the new one now, even if + // the sheet is closing. When that needs a decision or an unlock, the grant is held for it. + renewalReq.current = req + grant.current = { identityId: granted.identityId, keys: [granted.key], answer: null } + setStep({ kind: 'renew-store' }) + await finishRef.current(false) + } return () => { - controller.abort() + abort.abort() dropGrant() } // `attempt` restarts the whole request (a new ephemeral key and QR). - }, [attempt, forge, target, mode, grantFor, dropGrant, grantWhat]) + }, [attempt, forge, target, mode, grantFor, dropGrant, grantWhat, olderCode, renewGo, needsUnlock]) const restart = useCallback(() => setAttempt((a) => a + 1), []) + /** Switch between the v2 and the older code: the old request goes off screen at once (its key is spent). */ + const switchCode = (older: boolean): void => { + setStep(null) + setOlderCode(older) + } // A reloaded tab holds the signing key only; an approval is stored with the rest of the vault. if (mode === 'grant' && unlockScope === 'signing') { return } + if (needsUnlock) return + // A renewal asks how to protect the new key before its code shows: the wallet disables the old + // key as it approves, so the new one must be storable the moment the answer arrives. + if (mode === 'renew' && !renewGo) { + const defaults = defaultLimits() + return ( +
+

+ Your wallet gave this browser its key. A new request goes to the same wallet: when you approve, it adds a new key and disables the + current one. +

+

+ +

+ {fields} + + {problem ?

{problem}

: null} +
+ ) + } + if (step?.kind === 'blocked') { + return ( +
+

{step.message}

+
+ {onUnlock ? ( + + ) : null} + +
+
+ ) + } + /** An unfinished renewal on this device that storing the wallet's keys ran into: the choice, and its unlock. */ + const pendingRenewalUi = + pendingRenewal !== null ? ( +
+

{pendingRenewal}

+
+ + +
+ {renewalLocked !== null ? ( +
+

{renewalLocked.message}

+ {renewalLocked.methods.includes('passphrase') ? ( + + setHasRenewalPassphrase(e.target.value !== '')} /> + + ) : null} +
+ {renewalLocked.methods.includes('passphrase') ? ( + + ) : null} + {renewalLocked.methods.includes('passkey') ? ( + + ) : null} + +
+
+ ) : null} +
+ ) : null + if (step?.kind === 'renew-store') { + return ( +
+

Your wallet gave this browser a new key and disabled the old one. Forge has not stored the new key yet.

+ {pendingRenewalUi} + {unlockFirst ? : null} + +
+ + {onUnlock ? ( + + ) : null} +
+
+ ) + } if (step?.kind === 'confirm') { const { profile } = step return ( @@ -280,6 +634,20 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo ))} {step.unlimited ? : null} + {step.v2 ? ( + <> + {step.v2.limits?.total != null ? ( +

+ +

+ ) : null} + {step.v2.notice ? ( +

+ {step.v2.notice} +

+ ) : null} + + ) : null}

Anyone who saw your QR code could have answered first with their own identity; this wallet protocol cannot tell. Only you can, by comparing the username and id above with what your wallet showed. @@ -298,44 +666,7 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo > Finish signing in - {pendingRenewal !== null ? ( -

-

{pendingRenewal}

-
- - -
- {renewalLocked !== null ? ( -
-

{renewalLocked.message}

- {renewalLocked.methods.includes('passphrase') ? ( - - setHasRenewalPassphrase(e.target.value !== '')} /> - - ) : null} -
- {renewalLocked.methods.includes('passphrase') ? ( - - ) : null} - {renewalLocked.methods.includes('passkey') ? ( - - ) : null} - -
-
- ) : null} -
- ) : null} + {pendingRenewalUi} {problem ?

{problem}

: null} {unlockFirst ? : null} @@ -359,8 +690,14 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo const qrLabel = isRegister ? 'Wallet key registration request' : 'Wallet login request' // Where no released wallet can answer (a devnet, mainnet), that comes first and the wallet // link is secondary: a big primary button that cannot work is a dead end (QW2-029). - const supported = walletSignInSupported(ACTIVE_NETWORK.network) - const supportNote = mode === 'login' && step?.kind === 'request' ? : null + const v2 = step?.kind === 'request' ? step.v2 : undefined + const reportedCopy = step?.kind === 'request' && reported !== null ? CALLBACK_STATUS_COPY[reported] : undefined + // The phone's deep link may carry the callback the QR leaves out. + const linkUri = step?.kind === 'request' && step.linkUri ? step.linkUri : uri + // A v2 request is the one on offer where it shows, so its link leads even where no released + // wallet answers yet; a v1 request keeps the dead-end rule above. + const supported = walletSignInSupported(ACTIVE_NETWORK.network) || v2 !== undefined + const supportNote = mode === 'login' && step?.kind === 'request' ? : null // Said where the QR is on screen: a phone's QR sits in a collapsed disclosure. const qrPrivate = step?.kind === 'request' ?

Keep this QR code private: anyone who scans it can answer it.

: null return ( @@ -369,6 +706,12 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo {mode === 'grant' && !isRegister ? (

Approve {grantWhat.toLowerCase()} for this identity in your wallet.

) : null} + {v2 ? ( +

+ {mode === 'renew' ? 'Approve the renewal in the wallet that gave this browser its key. ' : 'Approve in your wallet. '} + +

+ ) : null} {isRegister ? (

One more step, first time only. Your wallet approved, and now it has to add Forge's key to your identity.{' '} @@ -380,7 +723,7 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo mobile ? ( <> : null} {supported ? supportNote : null} + {reportedCopy ? ( +

+ {reportedCopy.title}. {reportedCopy.body} +

+ ) : null} + {mode === 'login' && v2 ? ( + + ) : null} + {mode === 'login' && step?.kind === 'request' && !v2 && v2Offered ? ( + + ) : null} {error ? ( ) : null} {/* A pasted key is not Forge's to renew: that is a first import. */} - + ) : null} + {pasted ? ( + + + ) : null} {view === 'grant' ? ( <> {/* Keyed by contract: the next step starts a new request, never the last one's QR. */} @@ -231,6 +232,27 @@ export function LoginModal(): JSX.Element { ) } +/** + * The sheet's title. A write asked for the sheet: say which (L-62). Creating an identity is + * sign-up, and says so on every step (QW4-022), as GitHub's "Create your account" does. + */ +function titleFor(view: View | null, grantTitle: string, action: string | undefined): string { + switch (view) { + case 'grant': + return grantTitle + case 'renew': + return "Renew this browser's key" + case 'wallet-renew': + return "Renew this browser's key in your wallet" + case 'create': + return 'Create your identity' + case 'dg': + return 'Sign in with dg' + default: + return action ? `Sign in to ${action}` : 'Sign in to Dash Forge' + } +} + /** Skip this approval, or the rest: a skipped one is asked for when a write first needs it. */ function GuidedSkip({ step, onSkip, onSkipAll }: { step: { readonly step: number; readonly of: number }; onSkip: () => void; onSkipAll: () => void }): JSX.Element { return ( @@ -255,7 +277,8 @@ function GuidedSkip({ step, onSkip, onSkipAll }: { step: { readonly step: number /** The sheet's description line for a view. */ function describeView(view: View, limitedKeys: boolean): ReactNode { if (view === 'advanced') return 'A pasted key signs for this tab only, with whatever power it has.' - if (view === 'wallet' || view === 'grant') return 'Your wallet sends this browser a key it derives for Dash Forge. Your recovery phrase and master key stay on the phone.' + if (view === 'wallet' || view === 'grant') return 'Your wallet gives this browser a key for Dash Forge. Your recovery phrase and master key stay on the phone.' + if (view === 'wallet-renew') return 'Your wallet adds a new key for this browser and disables the current one. Your recovery phrase and master key stay on the phone.' if (!limitedKeys) return `Dash Forge isn't available on ${networkName()} yet, so there's nothing to sign in to here.` const base = <>at most {BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge // Import, renew and dg offer a lifetime picker; creating an identity does not. @@ -323,7 +346,7 @@ function Tile({ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { const { limitedKeys } = useAuth() const closeLogin = useUiStore((s) => s.closeLogin) - const walletAvailable = useWalletAvailability(limitedKeys) + const { available: walletAvailable, v2: walletV2 } = useWalletAvailability(limitedKeys) const [advanced, setAdvanced] = useState(false) const creating = useCreationInProgress() // While writes are paused (a devnet move, or the operator's PAGES_NOTICE=paused), no identity is @@ -331,15 +354,18 @@ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { const pausedReason = writesPausedReason() // No forge-v2 here means no contract group to bind a key to: nothing to sign in to. if (!limitedKeys) return - // First only where Dash Wallet can answer (testnet); elsewhere last, saying why. - const walletFirst = walletSignInSupported(ACTIVE_NETWORK.network) + // First where a wallet can answer: App Connect v2 is on offer here, or Dash Wallet answers the + // older exchange (testnet). Elsewhere last, saying why. + const walletFirst = walletV2 || walletSignInSupported(ACTIVE_NETWORK.network) const walletTile = walletAvailable ? ( { if (!limitedKeys) return let cancelled = false connectPlatform(ACTIVE_NETWORK.network) - .then((sdk) => withTimeout(walletLoginAvailable(sdk, ACTIVE_NETWORK.key), PLATFORM_READ_MS, 'Finding the wallet login contract')) + .then(async (sdk) => { + // v2 needs no response contract of its own; a failed check only means "not v2". + const v2 = await withTimeout(appConnectV2Available(sdk, ACTIVE_NETWORK.network), PLATFORM_READ_MS, 'Checking what your wallet can answer').catch(() => false) + // When Platform cannot be asked, the tile shows anyway (see above). + const v1 = await withTimeout(walletLoginAvailable(sdk, ACTIVE_NETWORK.key), PLATFORM_READ_MS, 'Finding the wallet login contract').catch(() => true) + return { available: v1 || v2, v2 } + }) .then( - (ok) => !cancelled && setAvailable(ok), - () => !cancelled && setAvailable(true), + (next) => !cancelled && setState(next), + () => !cancelled && setState({ available: true, v2: false }), ) return () => { cancelled = true } }, [limitedKeys]) - return available + return state } /** A dashed "choose a file" button over a hidden file input. */ diff --git a/forge-web/components/low-funds-banner.test.tsx b/forge-web/components/low-funds-banner.test.tsx new file mode 100644 index 000000000..1b3784f5f --- /dev/null +++ b/forge-web/components/low-funds-banner.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +/** + * The low-funds banner sends a key a wallet granted (App Connect) to be renewed in that wallet; + * every other key keeps "Renew key" (the identity file). + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { useUiStore } from '@/hooks/use-ui-store' + +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const session = vi.hoisted(() => ({ origin: null as 'app-connect' | null, reason: 'key-expiry' as 'key-expiry' | 'key-budget' | 'balance', level: 'low' as 'low' | 'empty' })) + +vi.mock('@/contexts/auth-context', () => ({ + useAuth: () => ({ + identity: ID, + origin: session.origin, + funds: { level: session.level, reason: session.reason, spendable: 1_000_000_000n }, + }), +})) + +const { LowFundsBanner } = await import('./low-funds-banner') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root +const main = (): HTMLButtonElement => host.querySelector('[data-testid="low-funds-banner"] button')! + +async function show(): Promise { + act(() => root.render()) + await act(async () => Promise.resolve()) +} + +beforeEach(() => { + session.origin = null + session.reason = 'key-expiry' + session.level = 'low' + sessionStorage.clear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => useUiStore.getState().closeLogin()) + act(() => root.unmount()) + host.remove() +}) + +describe('the low-funds banner', () => { + it("renews a wallet-granted key in the wallet", async () => { + session.origin = 'app-connect' + await show() + expect(main().textContent).toBe('Renew in your wallet') + act(() => main().click()) + expect(useUiStore.getState().loginView).toBe('wallet-renew') + }) + + it('also for an empty budget', async () => { + session.origin = 'app-connect' + session.reason = 'key-budget' + session.level = 'empty' + await show() + expect(main().textContent).toBe('Renew in your wallet') + }) + + it('keeps "Renew key" and the identity file for a key this browser registered', async () => { + await show() + expect(main().textContent).toBe('Renew key') + act(() => main().click()) + expect(useUiStore.getState().loginView).toBe('import') + }) + + it('a low balance is still a top-up, whatever the key came from', async () => { + session.origin = 'app-connect' + session.reason = 'balance' + await show() + expect(main().textContent).toBe('Top up') + }) +}) diff --git a/forge-web/components/low-funds-banner.tsx b/forge-web/components/low-funds-banner.tsx index 7c9bc0b51..63206bdb1 100644 --- a/forge-web/components/low-funds-banner.tsx +++ b/forge-web/components/low-funds-banner.tsx @@ -3,9 +3,9 @@ /** * The low-balance banner (`ux-dx-spec.md` §4, low-balance states): when funds are low or empty, * one banner under the header with the specific fix — top up the identity, or renew this - * browser's key — dismissible once per state per session (sessionStorage). It shows at every - * width, so a phone, whose header only has room for the icon-sized funds cue, still says what is - * wrong and how to fix it. + * browser's key (in the wallet that granted it, when it came from one) — dismissible once per + * state per session (sessionStorage). It shows at every width, so a phone, whose header only has + * room for the icon-sized funds cue, still says what is wrong and how to fix it. */ import { useEffect, useState } from 'react' @@ -32,10 +32,10 @@ function readDismissed(identity: string): readonly string[] { } export function LowFundsBanner(): JSX.Element | null { - const { identity, funds } = useAuth() + const { identity, funds, origin } = useAuth() const openTopUp = useUiStore((s) => s.openTopUp) const openLogin = useUiStore((s) => s.openLogin) - const notice = funds ? fundsNotice(funds) : null + const notice = funds ? fundsNotice(funds, origin) : null // Read after mount (sessionStorage is browser-only), per identity; until then nothing shows, // so neither a flash nor another identity's dismissals. const [dismissed, setDismissed] = useState<{ identity: string; keys: readonly string[] } | null>(null) @@ -46,6 +46,8 @@ export function LowFundsBanner(): JSX.Element | null { if (!identity || !funds || !notice || dismissed?.identity !== identity || dismissed.keys.includes(notice.key)) return null const empty = funds.level === 'empty' const topUp = notice.fix === 'top-up' + // A key a wallet granted is renewed in that wallet; the identity file stays the other way. + const inWallet = notice.fix === 'renew-in-wallet' const dismiss = (): void => { const keys = [...dismissed.keys, notice.key] try { @@ -72,9 +74,9 @@ export function LowFundsBanner(): JSX.Element | null { + ) : null} {canTopUpKey ? ( ) : null} - diff --git a/forge-web/contexts/auth-context.tsx b/forge-web/contexts/auth-context.tsx index eed3bd566..76a9d388d 100644 --- a/forge-web/contexts/auth-context.tsx +++ b/forge-web/contexts/auth-context.tsx @@ -68,6 +68,13 @@ interface AuthContextValue { readonly signer: WriteAuth | null /** How this session's key is held: a vault-stored limited key, or a tab-only raw key. */ readonly storage: AuthSession['storage'] | null + /** + * Where the stored key came from when this browser did not register it (`app-connect`: a + * wallet's grant, renewed in that wallet), else null. + */ + readonly origin: NonNullable | null + /** Check the session's keys on chain again (a write was refused as outside the key's bounds). */ + recheckSession: () => Promise /** Whether this network supports limited keys (forge-v2, protocol 14). */ readonly limitedKeys: boolean /** Keys stored (encrypted) on this device for this network. */ @@ -237,6 +244,9 @@ export function AuthProvider({ unlock: withReload(controller.unlock.bind(controller)), loginWithRawKey: withReload(controller.loginWithRawKey.bind(controller)), refreshBalance: () => controller.refreshBalance(), + recheckSession: async () => { + await controller.recheckSession() + }, logout: () => controller.logout(), forget: withReload(controller.forget.bind(controller)), revokeStored: withReload(controller.revokeStored.bind(controller)), @@ -324,6 +334,7 @@ export function AuthProvider({ error: state.error, signer, storage: session?.storage ?? null, + origin: session?.origin ?? null, grants: session?.grants ?? null, unlimitedKey: session?.unlimited === true, unboundedKey: session?.unbounded === true, @@ -369,6 +380,7 @@ export function SignedOutView({ children }: { children: React.ReactNode }): JSX. error: null, signer: null, storage: null, + origin: null, grants: null, unlimitedKey: false, unboundedKey: false, diff --git a/forge-web/hooks/use-ui-store.ts b/forge-web/hooks/use-ui-store.ts index bbd7af6dc..94f8b3b33 100644 --- a/forge-web/hooks/use-ui-store.ts +++ b/forge-web/hooks/use-ui-store.ts @@ -15,10 +15,11 @@ export type { TopUpReason } /** * A sign-in sheet view to open on directly (`renew`: Settings → Renew key, the import form worded - * as a renewal of the signed-in identity's key, QW3-031; `grant` asks the signed-in identity's - * wallet for a key on the contract named with it, when the session lacks one). + * as a renewal of the signed-in identity's key, QW3-031; `wallet-renew` renews it in the wallet + * that granted it (App Connect); `grant` asks the signed-in identity's wallet for a key on the + * contract named with it, when the session lacks one). */ -export type LoginView = 'import' | 'renew' | 'create' | 'wallet' | 'grant' | 'unlock' | 'dg' +export type LoginView = 'import' | 'renew' | 'wallet-renew' | 'create' | 'wallet' | 'grant' | 'unlock' | 'dg' /** * What a signed-out click asked to do (L-62): the sheet says "Sign in to star this repo" and what diff --git a/forge-web/hooks/use-write-guard.test.tsx b/forge-web/hooks/use-write-guard.test.tsx index 297628507..143d22be3 100644 --- a/forge-web/hooks/use-write-guard.test.tsx +++ b/forge-web/hooks/use-write-guard.test.tsx @@ -8,14 +8,16 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const state = vi.hoisted(() => ({ paused: null as string | null })) +const state = vi.hoisted(() => ({ paused: null as string | null, origin: null as 'app-connect' | null })) const toast = vi.hoisted(() => vi.fn()) const openLogin = vi.hoisted(() => vi.fn()) +const openTopUp = vi.hoisted(() => vi.fn()) +const recheckSession = vi.hoisted(() => vi.fn()) vi.mock('@/lib/devnet-notice', () => ({ writesPausedReason: () => state.paused })) vi.mock('@/hooks/use-toasts', () => ({ toast })) vi.mock('@/hooks/use-ui-store', () => ({ - useUiStore: (select: (s: unknown) => unknown) => select({ openLogin, openTopUp: vi.fn() }), + useUiStore: (select: (s: unknown) => unknown) => select({ openLogin, openTopUp }), })) vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ @@ -25,13 +27,16 @@ vi.mock('@/contexts/auth-context', () => ({ funds: null, keyLimits: null, grants: null, - refreshBalance: vi.fn(), + refreshBalance: vi.fn(async () => undefined), + recheckSession, + origin: state.origin, resuming: false, unlockScope: null, }), })) vi.mock('@/lib/view/funds', () => ({ affordability: () => ({ ok: true }) })) +import { ConsensusRefusal } from '@/lib/sdk/write' import { useWriteGuard, type WriteGuard } from './use-write-guard' let root: Root @@ -45,6 +50,9 @@ function Probe(): null { beforeEach(() => { ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true state.paused = null + state.origin = null + openTopUp.mockClear() + recheckSession.mockReset().mockResolvedValue(undefined) toast.mockClear() openLogin.mockClear() el = document.createElement('div') @@ -72,3 +80,30 @@ describe('useWriteGuard while the devnet is moving', () => { expect(guard.disabledReason).toBe(state.paused) }) }) + +describe('useWriteGuard after a write fails on a wallet-granted key', () => { + const refusal = (code: number) => new ConsensusRefusal(code, `refused ${code}`, {}, false) + + it("reads the refusal as App Connect does: a revoked key opens the renew sheet with the wallet's words", () => { + state.origin = 'app-connect' + act(() => root.render()) + expect(guard.failed(refusal(20006))).toMatch(/^Your wallet revoked this browser's access/) + expect(openTopUp).toHaveBeenCalledWith({ blocker: 'key-disabled' }) + expect(recheckSession).not.toHaveBeenCalled() + }) + + it('checks the session again after a write outside the key\'s bounds (20014), and survives a failed read', async () => { + state.origin = 'app-connect' + recheckSession.mockRejectedValue(new Error('offline')) + act(() => root.render()) + guard.failed(refusal(20014)) + await Promise.resolve() + expect(recheckSession).toHaveBeenCalledTimes(1) + }) + + it('leaves any other key as it was', () => { + guard.failed(refusal(20014)) + expect(guard.failed(refusal(20006))).not.toMatch(/wallet revoked/) + expect(recheckSession).not.toHaveBeenCalled() + }) +}) diff --git a/forge-web/hooks/use-write-guard.ts b/forge-web/hooks/use-write-guard.ts index 3c8bc1a79..7a3d42374 100644 --- a/forge-web/hooks/use-write-guard.ts +++ b/forge-web/hooks/use-write-guard.ts @@ -13,6 +13,8 @@ * - after a failure ({@link WriteGuard.failed}): the fix Platform's answer calls for opens — * renew or top up the key, top up the balance — and the balance and key limits are read * again so the pill shows what the chain says (D-007, D-042). It returns the sentence to show. + * For a key a wallet granted through App Connect, a write refused as outside the key's bounds + * also has the session's keys checked on chain again. */ import { useCallback } from 'react' @@ -48,7 +50,7 @@ const EMPTY_REASON: Readonly s.openLogin) const openTopUp = useUiStore((s) => s.openTopUp) @@ -98,14 +100,18 @@ export function useWriteGuard(): WriteGuard { const failed = useCallback( (e: unknown): string => { - const { message, sheet } = writeFailure(e) + // A key a wallet granted reads its refusals as App Connect does (revoked, out of bounds). + const { message, sheet, recheck } = writeFailure(e, { appConnect: origin === 'app-connect' }) if (sheet !== null) { openTopUp(sheet) void refreshBalance().catch(() => undefined) } + // Refused as outside the key's bounds: read its scopes, limits and balance afresh. A read + // that fails keeps the session as it was. + if (recheck) void recheckSession().catch(() => undefined) return message }, - [openTopUp, refreshBalance], + [openTopUp, origin, recheckSession, refreshBalance], ) const disabledReason = writesPausedReason() ?? (funds?.level === 'empty' ? EMPTY_REASON[funds.reason ?? 'balance'] : null) diff --git a/forge-web/lib/auth/connect-callback.test.ts b/forge-web/lib/auth/connect-callback.test.ts new file mode 100644 index 000000000..c615b8f3c --- /dev/null +++ b/forge-web/lib/auth/connect-callback.test.ts @@ -0,0 +1,160 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { buildAppConnectUri, parseAppConnectUri } from '../vendor/platform-auth/app-connect' +import { + CALLBACK_CHANNEL, + CALLBACK_STATUS_COPY, + connectCallbackUrl, + isConnectCallbackAck, + isConnectCallbackMessage, + listenForCallback, + parseConnectCallback, +} from './connect-callback' +import { newV2LoginRequest } from './app-connect-v2' +import type { ForgeIds } from '../deployments' + +const HASH = new Uint8Array(20).fill(0xab) +const HEX = 'ab'.repeat(20) +const SITE = 'https://forge.dashhq.org/' +const FORGE: ForgeIds = { + core: 'A2KL77ngVM1ft1t1em2XKt1rWCBZANdAJMyfWrDGCcd1', + collab: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + community: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + group: '6dV3kMBWHGR7pLKrHToMBQgbTpjqeE2VAyCEWmLbrkWC', +} + +afterEach(() => vi.restoreAllMocks()) + +describe('connectCallbackUrl', () => { + it('points at /connect/ on the canonical site with the request hash', () => { + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: 'https://forge.dashhq.org', ipfs: false })).toBe(`${SITE}connect/?r=${HEX}`) + }) + + it('keeps a base path', () => { + expect(connectCallbackUrl(HASH, { siteUrl: 'https://example.org/dash-forge/', origin: 'https://example.org', ipfs: false })).toBe(`https://example.org/dash-forge/connect/?r=${HEX}`) + }) + + it('is omitted on an IPFS build', () => { + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: 'https://forge.dashhq.org', ipfs: true })).toBeNull() + }) + + it('is omitted when this page is not on the canonical origin', () => { + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: 'https://bafy.ipfs.dweb.link', ipfs: false })).toBeNull() + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: null, ipfs: false })).toBeNull() + }) + + it('is omitted when the site is not https (the profile requires it)', () => { + expect(connectCallbackUrl(HASH, { siteUrl: 'http://localhost:3000/', origin: 'http://localhost:3000', ipfs: false })).toBeNull() + }) + + it('rides on the request as cb, and only on the link', () => { + const req = newV2LoginRequest('devnet', FORGE, { + connectionId: new Uint8Array(16).fill(1), + chainNow: 1_700_000_000_000, + callbackUrl: (h) => connectCallbackUrl(h, { siteUrl: SITE, origin: 'https://forge.dashhq.org', ipfs: false }), + }) + expect(parseAppConnectUri(req.qrUri).callbackUrl).toBeUndefined() + const link = parseAppConnectUri(req.linkUri).callbackUrl + expect(link).toMatch(/^https:\/\/forge\.dashhq\.org\/connect\/\?r=[0-9a-f]{40}$/) + expect(link?.endsWith(Buffer.from(req.requestHash).toString('hex'))).toBe(true) + expect(req.linkUri).toBe(buildAppConnectUri(req.request, 'devnet', link)) + }) +}) + +describe('parseConnectCallback', () => { + it('reads the request hash and status', () => { + expect(parseConnectCallback(`?r=${HEX}&ac=ok`)).toEqual({ requestHash: HEX, status: 'ok' }) + expect(parseConnectCallback(`?ac=declined&r=${HEX.toUpperCase()}`)).toEqual({ requestHash: HEX, status: 'declined' }) + expect(parseConnectCallback(`?r=${HEX}`)).toEqual({ requestHash: HEX, status: null }) + }) + + it('refuses anything that is not a request hash', () => { + expect(parseConnectCallback('')).toBeNull() + expect(parseConnectCallback('?r=not-a-hash&ac=ok')).toBeNull() + expect(parseConnectCallback(`?r=${HEX}00`)).toBeNull() + }) + + it('drops a status of the wrong shape', () => { + expect(parseConnectCallback(`?r=${HEX}&ac=