{"version":"0.1.0","commit":"ad381c8d7145e3fb73d837139da588f520a1e6f7","dependencies":[{"name":"@noble/curves","version":"2.4.0","license":"MIT","url":"https://www.npmjs.com/package/@noble/curves/v/2.4.0"},{"name":"@noble/post-quantum","version":"0.7.1","license":"MIT","url":"https://www.npmjs.com/package/@noble/post-quantum/v/0.7.1"},{"name":"@scure/base","version":"2.4.0","license":"MIT","url":"https://www.npmjs.com/package/@scure/base/v/2.4.0"},{"name":"@solana/wallet-standard-features","version":"1.5.0","license":"Apache-2.0","url":"https://www.npmjs.com/package/@solana/wallet-standard-features/v/1.5.0"},{"name":"@wallet-standard/app","version":"1.1.1","license":"Apache-2.0","url":"https://www.npmjs.com/package/@wallet-standard/app/v/1.1.1"},{"name":"@wallet-standard/base","version":"1.1.1","license":"Apache-2.0","url":"https://www.npmjs.com/package/@wallet-standard/base/v/1.1.1"},{"name":"@wallet-standard/features","version":"1.1.1","license":"Apache-2.0","url":"https://www.npmjs.com/package/@wallet-standard/features/v/1.1.1"},{"name":"fflate","version":"0.8.3","license":"MIT","url":"https://www.npmjs.com/package/fflate/v/0.8.3"},{"name":"lossless-json","version":"4.3.4","license":"MIT","url":"https://www.npmjs.com/package/lossless-json/v/4.3.4"},{"name":"typescript","version":"5.9.3","license":"Apache-2.0","url":"https://www.npmjs.com/package/typescript/v/5.9.3"},{"name":"vite","version":"7.3.7","license":"MIT","url":"https://www.npmjs.com/package/vite/v/7.3.7"},{"name":"vitest","version":"3.2.7","license":"MIT","url":"https://www.npmjs.com/package/vitest/v/3.2.7"},{"name":"zod","version":"4.6.7","license":"MIT","url":"https://www.npmjs.com/package/zod/v/4.6.7"}],"files":[{"path":"src/crypto/client.ts","content":"import type {\n  BenchmarkResult,\n  CryptoRequest,\n  CryptoResponse,\n  CryptoTask,\n  KeyResult,\n  SignResult,\n  VerifyResult,\n} from '../workers/crypto-protocol';\n\nexport type { BenchmarkResult, KeyResult, SignResult, VerifyResult } from '../workers/crypto-protocol';\n\nexport function createCryptoSession() {\n  let worker: Worker | undefined;\n  let nextId = 0;\n  const pending = new Map<number, (response: CryptoResponse) => void>();\n\n  function stop(current: Worker, error: string): void {\n    if (worker !== current) return;\n    current.terminate();\n    worker = undefined;\n    for (const [id, settle] of pending) settle({ id, ok: false, error });\n    pending.clear();\n  }\n\n  function getWorker(): Worker {\n    if (worker) return worker;\n    const current = new Worker(new URL('../workers/crypto.worker.ts', import.meta.url), { type: 'module' });\n    function fail(): void {\n      stop(current, 'The cryptographic worker stopped. Generate a fresh key to sign again.');\n    }\n    current.addEventListener('error', fail);\n    current.addEventListener('messageerror', fail);\n    current.addEventListener('message', ({ data }: MessageEvent<CryptoResponse>) => {\n      const settle = pending.get(data.id);\n      if (!settle) return;\n      pending.delete(data.id);\n      settle(data);\n    });\n    worker = current;\n    return current;\n  }\n\n  function request<Result>(task: CryptoTask): Promise<Result> {\n    return new Promise((resolve, reject) => {\n      const current = getWorker();\n      const id = ++nextId;\n      pending.set(id, (response) => {\n        if (response.ok) resolve(response.result as Result);\n        else reject(new Error(response.error));\n      });\n      try {\n        current.postMessage({ id, ...task } satisfies CryptoRequest);\n      } catch (error) {\n        pending.delete(id);\n        reject(error);\n      }\n    });\n  }\n\n  return {\n    generateKey: () => request<KeyResult>({ type: 'generate' }),\n    signMessage: (message: Uint8Array, context?: Uint8Array) => request<SignResult>({ type: 'sign', message, context }),\n    verifySignature: (publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array, context?: Uint8Array) => (\n      request<VerifyResult>({ type: 'verify', publicKey, message, signature, context })\n    ),\n    clearKey: () => worker ? request<void>({ type: 'clear' }) : Promise.resolve(),\n    dispose: () => { if (worker) stop(worker, 'The cryptographic session was closed.'); },\n    benchmark: (iterations = 5) => request<BenchmarkResult>({ type: 'benchmark', iterations }),\n  };\n}\n\nexport const { generateKey, signMessage, verifySignature, clearKey, benchmark } = createCryptoSession();\n"},{"path":"src/crypto/dual-identity.ts","content":"import { decodeWalletAddress, equalBytes, toBase64Url } from './encoding';\nimport { LEGACY_ALGORITHM, PQ_ALGORITHM } from './parameters';\nimport { canonicalize } from '../migration/canonicalize';\nimport {\n  BINDING_PURPOSE,\n  DEMO_IDENTITY_DOMAIN,\n  DEMO_NETWORK,\n  DEMO_PURPOSE,\n  DEMO_WALLET_FORMAT,\n  IDENTITY_DOMAIN,\n  identityStatementSchema,\n  NETWORK,\n  NONCE_BYTES,\n  OCMS_WALLET_FORMAT,\n  PROOF_LIFETIME_MS,\n  PROTOCOL,\n  RAW_WALLET_FORMAT,\n  SCHEMA_VERSION,\n  type IdentityStatement,\n  type WalletMessageFormat,\n} from '../migration/schema';\n\nexport type { IdentityStatement } from '../migration/schema';\n\nconst encoder = new TextEncoder();\nconst OCMS_SIGNING_DOMAIN = Uint8Array.of(0xff, ...encoder.encode('solana offchain'));\nconst OCMS_V1_HEADER_BYTES = 50;\n\nfunction makeIdentityStatement(\n  walletAddress: string,\n  pqPublicKey: Uint8Array,\n  issuedAt: Date,\n  purpose: IdentityStatement['purpose'],\n  domain: IdentityStatement['domain'],\n  network: IdentityStatement['network'],\n): IdentityStatement {\n  return identityStatementSchema.parse({\n    protocol: PROTOCOL,\n    schemaVersion: SCHEMA_VERSION,\n    purpose,\n    domain,\n    network,\n    walletAddress,\n    legacyAlgorithm: LEGACY_ALGORITHM,\n    pqAlgorithm: PQ_ALGORITHM,\n    pqPublicKey: toBase64Url(pqPublicKey),\n    nonce: toBase64Url(crypto.getRandomValues(new Uint8Array(NONCE_BYTES))),\n    issuedAt: issuedAt.toISOString(),\n    expiresAt: new Date(issuedAt.getTime() + PROOF_LIFETIME_MS).toISOString(),\n  });\n}\n\nexport function createIdentityStatement(\n  walletAddress: string,\n  pqPublicKey: Uint8Array,\n  issuedAt = new Date(),\n): IdentityStatement {\n  return makeIdentityStatement(walletAddress, pqPublicKey, issuedAt, BINDING_PURPOSE, IDENTITY_DOMAIN, NETWORK);\n}\n\nexport function createDemoIdentityStatement(\n  walletAddress: string,\n  pqPublicKey: Uint8Array,\n  issuedAt = new Date(),\n): IdentityStatement {\n  return makeIdentityStatement(walletAddress, pqPublicKey, issuedAt, DEMO_PURPOSE, DEMO_IDENTITY_DOMAIN, DEMO_NETWORK);\n}\n\nexport function identityMessage(statement: IdentityStatement): Uint8Array<ArrayBuffer> {\n  const fields = identityStatementSchema.parse(statement);\n  // The v1 prefix is part of the signature input and must be reproduced byte for byte.\n  const title = fields.purpose === DEMO_PURPOSE ? 'AFTERKEY demo / test identity binding v1' : 'AFTERKEY identity binding v1';\n  return encoder.encode(`${title}\\n${canonicalize(fields)}`);\n}\n\nexport function identityContext(domain: IdentityStatement['domain'] = IDENTITY_DOMAIN): Uint8Array<ArrayBuffer> {\n  return encoder.encode(domain);\n}\n\nexport function detectWalletMessageFormat(\n  signedMessage: Uint8Array,\n  expectedPayload: Uint8Array,\n  expectedWalletAddress: string,\n): WalletMessageFormat | undefined {\n  if (equalBytes(signedMessage, expectedPayload)) return RAW_WALLET_FORMAT;\n\n  // Solana OCMS v1 allows multiple signers. Migration proofs bind exactly one wallet.\n  if (signedMessage.length !== OCMS_V1_HEADER_BYTES + expectedPayload.length\n    || !equalBytes(signedMessage.subarray(0, 16), OCMS_SIGNING_DOMAIN)\n    || signedMessage[16] !== 1 || signedMessage[17] !== 1) return undefined;\n\n  const walletKey = decodeWalletAddress(expectedWalletAddress);\n  if (!equalBytes(signedMessage.subarray(18, OCMS_V1_HEADER_BYTES), walletKey)) return undefined;\n  return equalBytes(signedMessage.subarray(OCMS_V1_HEADER_BYTES), expectedPayload) ? OCMS_WALLET_FORMAT : undefined;\n}\n\nexport function detectIdentityMessageFormat(\n  statement: IdentityStatement,\n  signedMessage: Uint8Array,\n  expectedPayload: Uint8Array,\n): WalletMessageFormat | undefined {\n  if (statement.purpose === DEMO_PURPOSE) {\n    return equalBytes(signedMessage, expectedPayload) ? DEMO_WALLET_FORMAT : undefined;\n  }\n  return detectWalletMessageFormat(signedMessage, expectedPayload, statement.walletAddress);\n}\n"},{"path":"src/crypto/encoding.ts","content":"import { base58, base64urlnopad, hex } from '@scure/base';\nimport { ED25519_PUBLIC_KEY_BYTES } from './parameters';\n\nexport const toBase64Url = base64urlnopad.encode;\nexport const toHex = hex.encode;\n\nexport function fromBase64Url(value: string): Uint8Array<ArrayBuffer> {\n  if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error('Expected unpadded base64url.');\n  const bytes = base64urlnopad.decode(value);\n  if (toBase64Url(bytes) !== value) throw new Error('Expected canonical unpadded base64url.');\n  return new Uint8Array(bytes);\n}\n\nexport function decodeWalletAddress(address: string): Uint8Array<ArrayBuffer> {\n  if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address)) throw new Error('Invalid Solana address.');\n  const bytes = base58.decode(address);\n  if (bytes.length !== ED25519_PUBLIC_KEY_BYTES || base58.encode(bytes) !== address) {\n    throw new Error('Invalid Solana address.');\n  }\n  return new Uint8Array(bytes);\n}\n\nexport function equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n  return left.length === right.length && left.every((byte, index) => byte === right[index]);\n}\n"},{"path":"src/crypto/fingerprint.ts","content":"import { toHex } from './encoding';\n\nexport async function sha256Hex(bytes: Uint8Array): Promise<string> {\n  const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(bytes));\n  return toHex(new Uint8Array(digest));\n}\n\nexport const fingerprintPublicKey = sha256Hex;\n"},{"path":"src/crypto/keygen.ts","content":"import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';\n\n/**\n * Generates using the library's default system CSPRNG.\n * Callers own the secret buffer and keep it within worker memory in browser sessions.\n */\nexport function generateMlDsaKeyPair() {\n  const start = performance.now();\n  const { publicKey, secretKey } = ml_dsa65.keygen();\n  const durationMs = performance.now() - start;\n  return { publicKey, secretKey, durationMs };\n}\n"},{"path":"src/crypto/parameters.ts","content":"export const PQ_ALGORITHM = 'ML-DSA-65';\nexport const PQ_STANDARD = 'NIST FIPS 204';\nexport const LEGACY_ALGORITHM = 'Ed25519';\nexport const PQ_PUBLIC_KEY_BYTES = 1952;\nexport const PQ_SIGNATURE_BYTES = 3309;\nexport const ED25519_PUBLIC_KEY_BYTES = 32;\nexport const ED25519_SIGNATURE_BYTES = 64;\nexport const MAX_MESSAGE_BYTES = 256 * 1024;\nexport const MAX_BENCHMARK_ITERATIONS = 25;\n"},{"path":"src/crypto/signature.ts","content":"import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';\nimport { MAX_MESSAGE_BYTES } from './parameters';\n\nexport function signMlDsa(message: Uint8Array, secretKey: Uint8Array, context?: Uint8Array): Uint8Array {\n  if (message.length > MAX_MESSAGE_BYTES) throw new Error('Message exceeds 256 KiB.');\n  if (context && context.length > 255) throw new Error('The signing context exceeds 255 bytes.');\n\n  // The library's default hedged signing obtains fresh randomness for each signature.\n  return ml_dsa65.sign(message, secretKey, context ? { context } : undefined);\n}\n"},{"path":"src/crypto/verify.ts","content":"import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';\nimport { MAX_MESSAGE_BYTES, PQ_PUBLIC_KEY_BYTES, PQ_SIGNATURE_BYTES } from './parameters';\n\nexport function verifyMlDsa(\n  publicKey: Uint8Array,\n  message: Uint8Array,\n  signature: Uint8Array,\n  context?: Uint8Array,\n): boolean {\n  if (publicKey.length !== PQ_PUBLIC_KEY_BYTES || signature.length !== PQ_SIGNATURE_BYTES\n    || message.length > MAX_MESSAGE_BYTES || (context && context.length > 255)) return false;\n\n  try {\n    return ml_dsa65.verify(signature, message, publicKey, context ? { context } : undefined);\n  } catch {\n    return false;\n  }\n}\n"},{"path":"src/migration/canonicalize.ts","content":"type JsonScalar = string | number | boolean | null;\n\n/** Schema v1 contains flat objects with fixed ASCII property names and scalar values. */\nexport function canonicalize(fields: Readonly<Record<string, JsonScalar>>): string {\n  const entries = Object.keys(fields).sort().map((key) => {\n    const value = fields[key];\n    if (value === undefined || (typeof value === 'number' && !Number.isFinite(value))) {\n      throw new Error(`Cannot canonicalize field ${key}.`);\n    }\n    return `${JSON.stringify(key)}:${JSON.stringify(value)}`;\n  });\n  return `{${entries.join(',')}}`;\n}\n"},{"path":"src/migration/local-demo.ts","content":"import { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58 } from '@scure/base';\nimport { createCryptoSession } from '../crypto/client';\nimport { createDemoIdentityStatement, identityContext, identityMessage } from '../crypto/dual-identity';\nimport { fromBase64Url, toBase64Url } from '../crypto/encoding';\nimport { createManifest } from './manifest';\nimport { verifyManifest, type VerificationResult } from './proof-validator';\nimport type { MigrationManifest } from './schema';\n\nexport const LOCAL_DEMO_STEPS = {\n  'ed25519-key': 'Generate a temporary Ed25519 identity',\n  'ml-dsa-key': 'Generate a temporary ML-DSA-65 key',\n  statement: 'Build the canonical demo statement',\n  sign: 'Sign the same statement with both keys',\n  signatures: 'Check both detached signatures',\n  manifest: 'Create the signed demo manifest',\n  verify: 'Verify the exported proof',\n  tamper: 'Change the statement and require both checks to fail',\n} as const;\n\nexport type LocalDemoEvent = {\n  step: keyof typeof LOCAL_DEMO_STEPS;\n  status: 'running' | 'pass' | 'fail';\n};\n\nexport interface LocalDemoResult {\n  manifest: MigrationManifest;\n  verification: VerificationResult;\n  tamperedVerification: VerificationResult;\n}\n\ntype DemoSession = Pick<ReturnType<typeof createCryptoSession>, 'generateKey' | 'signMessage' | 'verifySignature' | 'clearKey' | 'dispose'>;\n\nexport async function runLocalDemo(\n  onStep?: (event: LocalDemoEvent) => void,\n  setupSession: () => DemoSession = createCryptoSession,\n): Promise<LocalDemoResult> {\n  const pqSession = setupSession();\n  let identitySecret: Uint8Array | undefined;\n\n  async function perform<T>(step: LocalDemoEvent['step'], operation: () => T | Promise<T>): Promise<T> {\n    onStep?.({ step, status: 'running' });\n    try {\n      const result = await operation();\n      onStep?.({ step, status: 'pass' });\n      return result;\n    } catch (error) {\n      onStep?.({ step, status: 'fail' });\n      throw error;\n    }\n  }\n\n  try {\n    const identityPublicKey = await perform('ed25519-key', () => {\n      identitySecret = crypto.getRandomValues(new Uint8Array(32));\n      return ed25519.getPublicKey(identitySecret);\n    });\n    const { publicKey: pqPublicKey } = await perform('ml-dsa-key', () => pqSession.generateKey());\n    const statement = await perform('statement', () => createDemoIdentityStatement(base58.encode(identityPublicKey), pqPublicKey));\n    const payload = identityMessage(statement);\n    const context = identityContext(statement.domain);\n    const { walletSignature, pqSignature } = await perform('sign', async () => {\n      if (!identitySecret) throw new Error('The demo Ed25519 key is unavailable.');\n      const walletSignature = ed25519.sign(payload, identitySecret);\n      identitySecret.fill(0);\n      const { signature: pqSignature } = await pqSession.signMessage(payload, context);\n      return { walletSignature, pqSignature };\n    });\n\n    const verifyPq: DemoSession['verifySignature'] = (...args) => pqSession.verifySignature(...args);\n    await perform('signatures', async () => {\n      const validEd25519 = ed25519.verify(walletSignature, payload, identityPublicKey, { zip215: false });\n      const { valid: validPq } = await verifyPq(pqPublicKey, payload, pqSignature, context);\n      if (!validEd25519 || !validPq) throw new Error('Both signatures must verify before creating the demo manifest.');\n    });\n\n    const manifest = await perform('manifest', () => createManifest({\n      statement, walletSignature, walletSignedMessage: payload, pqSignature,\n    }));\n    const verification = await perform('verify', async () => {\n      const result = await verifyManifest(manifest, { allowDemo: true, verifyPq });\n      if (!result.valid || result.kind !== 'demo') throw new Error('The generated demo proof failed independent verification.');\n      return result;\n    });\n\n    const tamperedVerification = await perform('tamper', async () => {\n      const changedNonce = fromBase64Url(statement.nonce);\n      changedNonce[0] ^= 1;\n      const changedStatement = { ...statement, nonce: toBase64Url(changedNonce) };\n      // Keep both old signatures, changing the statement and recalculating the public manifest hash.\n      const tamperedManifest = await createManifest({\n        statement: changedStatement,\n        walletSignature,\n        walletSignedMessage: identityMessage(changedStatement),\n        pqSignature,\n      });\n      const result = await verifyManifest(tamperedManifest, { allowDemo: true, verifyPq });\n      const failed = new Set(result.checks.filter(({ status }) => status === 'fail').map(({ name }) => name));\n      if (result.valid || !failed.has('Wallet signature') || !failed.has('PQ signature')) {\n        throw new Error('Both signatures must reject the changed statement.');\n      }\n      return result;\n    });\n    return { manifest, verification, tamperedVerification };\n  } finally {\n    identitySecret?.fill(0);\n    try {\n      await pqSession.clearKey();\n    } finally {\n      pqSession.dispose();\n    }\n  }\n}\n"},{"path":"src/migration/manifest.ts","content":"import { detectIdentityMessageFormat, identityMessage } from '../crypto/dual-identity';\nimport { toBase64Url } from '../crypto/encoding';\nimport { sha256Hex } from '../crypto/fingerprint';\nimport { canonicalize } from './canonicalize';\nimport { manifestWithoutIdSchema, type IdentityStatement, type ManifestWithoutId, type MigrationManifest } from './schema';\n\nexport type { MigrationManifest } from './schema';\n\nexport function manifestId(input: ManifestWithoutId & { manifestId?: string }): Promise<string> {\n  const fields = { ...input };\n  delete fields.manifestId;\n  return sha256Hex(new TextEncoder().encode(canonicalize(fields)));\n}\n\nexport async function createManifest(input: {\n  statement: IdentityStatement;\n  walletSignature: Uint8Array;\n  walletSignedMessage: Uint8Array;\n  pqSignature: Uint8Array;\n}): Promise<MigrationManifest> {\n  const payload = identityMessage(input.statement);\n  const walletMessageFormat = detectIdentityMessageFormat(input.statement, input.walletSignedMessage, payload);\n  if (!walletMessageFormat) throw new Error('The wallet signed bytes that do not match the identity statement.');\n\n  const fields = manifestWithoutIdSchema.parse({\n    ...input.statement,\n    walletSignature: toBase64Url(input.walletSignature),\n    pqSignature: toBase64Url(input.pqSignature),\n    signedPayload: toBase64Url(payload),\n    walletSignedMessage: toBase64Url(input.walletSignedMessage),\n    walletMessageFormat,\n  });\n  return { ...fields, manifestId: await manifestId(fields) };\n}\n"},{"path":"src/migration/proof-validator.ts","content":"import { ed25519 } from '@noble/curves/ed25519.js';\nimport { detectIdentityMessageFormat, identityContext, identityMessage } from '../crypto/dual-identity';\nimport { decodeWalletAddress, equalBytes, fromBase64Url } from '../crypto/encoding';\nimport type { verifySignature } from '../crypto/client';\nimport { manifestId } from './manifest';\nimport { CLOCK_SKEW_MS, DEMO_PURPOSE, manifestSchema, PROOF_LIFETIME_MS, type MigrationManifest } from './schema';\n\nexport type VerificationStatus = 'pass' | 'fail' | 'skip' | 'expired';\n\nexport interface VerificationCheck {\n  name: string;\n  status: VerificationStatus;\n  detail: string;\n}\n\nexport interface VerificationResult {\n  valid: boolean;\n  kind?: 'wallet' | 'demo';\n  manifest?: MigrationManifest;\n  checks: VerificationCheck[];\n}\n\nconst otherChecks = ['Payload integrity', 'Wallet signature', 'PQ signature', 'Identity binding', 'Time validity'];\n\nfunction check(name: string, valid: boolean, passing: string, failing: string): VerificationCheck {\n  return { name, status: valid ? 'pass' : 'fail', detail: valid ? passing : failing };\n}\n\nfunction verifyTime(manifest: MigrationManifest, now: Date): VerificationCheck {\n  const name = 'Time validity';\n  const issued = Date.parse(manifest.issuedAt);\n  const expires = Date.parse(manifest.expiresAt);\n  const current = now.getTime();\n  if (!Number.isFinite(current)) return { name, status: 'skip', detail: 'A valid current time is unavailable.' };\n  if (expires - issued !== PROOF_LIFETIME_MS) {\n    return { name, status: 'fail', detail: 'The validity period must be exactly 24 hours.' };\n  }\n  if (issued > current + CLOCK_SKEW_MS) {\n    return { name, status: 'fail', detail: 'The issued time is more than five minutes in the future.' };\n  }\n  if (expires <= current) return { name, status: 'expired', detail: 'The validity period has ended.' };\n  return { name, status: 'pass', detail: 'The validity period checks against the verification clock.' };\n}\n\nasync function verifyPqSignature(\n  manifest: MigrationManifest,\n  payload: Uint8Array,\n  verifyPq?: typeof verifySignature,\n): Promise<VerificationCheck> {\n  const name = 'PQ signature';\n  const publicKey = fromBase64Url(manifest.pqPublicKey);\n  const signature = fromBase64Url(manifest.pqSignature);\n  try {\n    const context = identityContext(manifest.domain);\n    const valid = verifyPq\n      ? (await verifyPq(publicKey, payload, signature, context)).valid\n      : (await import('../crypto/verify')).verifyMlDsa(publicKey, payload, signature, context);\n    return check(name, valid, 'ML-DSA-65 verifies the payload and context.', 'The ML-DSA-65 signature is invalid.');\n  } catch {\n    return { name, status: 'skip', detail: 'ML-DSA-65 verification could not run in this environment.' };\n  }\n}\n\nexport async function verifyManifest(\n  input: unknown,\n  options: { now?: Date; verifyPq?: typeof verifySignature; allowDemo?: boolean } = {},\n): Promise<VerificationResult> {\n  const parsed = manifestSchema.safeParse(input);\n  if (!parsed.success) {\n    return {\n      valid: false,\n      checks: [\n        {\n          name: 'Schema',\n          status: 'fail',\n          detail: parsed.error.issues.slice(0, 5).map((issue) => (\n            `${issue.path.map(String).join('.') || 'manifest'}: ${issue.message}`\n          )).join(' '),\n        },\n        ...otherChecks.map((name) => ({ name, status: 'skip' as const, detail: 'A valid schema is required.' })),\n      ],\n    };\n  }\n\n  const manifest = parsed.data;\n  const isDemo = manifest.purpose === DEMO_PURPOSE;\n  const kind = isDemo ? 'demo' : 'wallet';\n  const { manifestId: expectedId, ...fields } = manifest;\n  const { walletSignature, pqSignature: _pqSignature, signedPayload, walletSignedMessage, walletMessageFormat, ...statement } = fields;\n  const payload = fromBase64Url(signedPayload);\n  const signedMessage = fromBase64Url(walletSignedMessage);\n  const payloadMatches = equalBytes(payload, identityMessage(statement));\n  const formatMatches = detectIdentityMessageFormat(statement, signedMessage, payload) === walletMessageFormat;\n  const walletValid = ed25519.verify(\n    fromBase64Url(walletSignature), signedMessage, decodeWalletAddress(manifest.walletAddress), { zip215: false },\n  );\n  const walletCheck = check('Wallet signature', walletValid,\n    isDemo ? 'Ed25519 verifies the exact bytes signed by the temporary demo identity.' : 'Ed25519 verifies the exact bytes returned by the wallet.',\n    isDemo ? 'The Ed25519 demo signature is invalid for this test identity and message.' : 'The Ed25519 signature is invalid for this wallet and message.');\n  const pqCheck = await verifyPqSignature(manifest, payload, options.verifyPq);\n\n  let integrity: VerificationCheck;\n  try {\n    const hashMatches = await manifestId(fields) === expectedId;\n    integrity = check('Payload integrity', payloadMatches && hashMatches, 'The canonical payload and manifest ID match.',\n      [!payloadMatches && 'The encoded payload differs from the canonical statement.', !hashMatches && 'The manifest ID does not match the contents.'].filter(Boolean).join(' '));\n  } catch {\n    integrity = { name: 'Payload integrity', status: 'skip', detail: 'SHA-256 could not run in this environment.' };\n  }\n\n  const bindingName = 'Identity binding';\n  let binding: VerificationCheck;\n  if (isDemo && !options.allowDemo) {\n    binding = { name: bindingName, status: 'fail', detail: 'This demo proof cannot satisfy wallet identity verification. Demo verification requires explicit opt-in.' };\n  } else if (!payloadMatches || !formatMatches) {\n    binding = { name: bindingName, status: 'fail', detail: 'The wallet envelope, declared format or signed payload differs from the identity statement.' };\n  } else if (walletValid && pqCheck.status === 'skip') {\n    binding = { name: bindingName, status: 'skip', detail: 'Both signature checks are required to verify the identity binding.' };\n  } else {\n    binding = check(bindingName, walletValid && pqCheck.status === 'pass',\n      isDemo ? 'Both verified signatures bind the temporary demo identity and ML-DSA-65 key to one test statement.' : 'Both verified signatures bind the declared wallet and ML-DSA-65 key to one statement.',\n      'Both signatures must verify for the identity binding to pass.');\n  }\n  const checks: VerificationCheck[] = [\n    { name: 'Schema', status: 'pass', detail: isDemo ? 'The manifest uses the supported version 1 demo schema.' : 'The manifest uses the supported version 1 schema.' },\n    integrity,\n    walletCheck,\n    pqCheck,\n    binding,\n    verifyTime(manifest, options.now ?? new Date()),\n  ];\n  return { valid: checks.every(({ status }) => status === 'pass'), kind, manifest, checks };\n}\n"},{"path":"src/migration/schema.ts","content":"import { z } from 'zod';\nimport { decodeWalletAddress, fromBase64Url } from '../crypto/encoding';\nimport { ED25519_SIGNATURE_BYTES, LEGACY_ALGORITHM, PQ_ALGORITHM, PQ_PUBLIC_KEY_BYTES, PQ_SIGNATURE_BYTES } from '../crypto/parameters';\n\n// The v1 protocol namespace and signing domains stay stable across product branding.\nexport const PROTOCOL = 'afterkey';\nexport const SCHEMA_VERSION = 1;\nexport const BINDING_PURPOSE = 'wallet-pq-identity-binding';\nexport const IDENTITY_DOMAIN = 'afterkey:dual-identity:v1';\nexport const DEMO_PURPOSE = 'wallet-pq-identity-demo-test';\nexport const DEMO_IDENTITY_DOMAIN = 'afterkey:dual-identity-demo:v1';\nexport const NETWORK = 'solana-mainnet';\nexport const DEMO_NETWORK = 'local-demo';\nexport const NONCE_BYTES = 16;\nexport const PROOF_LIFETIME_MS = 24 * 60 * 60 * 1000;\nexport const CLOCK_SKEW_MS = 5 * 60 * 1000;\nexport const MAX_MANIFEST_BYTES = 32 * 1024;\nexport const RAW_WALLET_FORMAT = 'solana:signMessage:raw-v1';\nexport const OCMS_WALLET_FORMAT = 'solana:signOffchainMessage:ocms-v1';\nexport const DEMO_WALLET_FORMAT = 'afterkey:demo:ed25519-raw-v1';\nconst MAX_STATEMENT_BYTES = 4096;\nconst MAX_WALLET_MESSAGE_BYTES = MAX_STATEMENT_BYTES + 50;\n\nfunction base64Bytes(minBytes: number, maxBytes = minBytes) {\n  const maxChars = Math.ceil(maxBytes * 4 / 3);\n  return z.string().min(Math.ceil(minBytes * 4 / 3)).max(maxChars).refine((value) => {\n    if (value.length > maxChars) return false;\n    try {\n      const size = fromBase64Url(value).length;\n      return size >= minBytes && size <= maxBytes;\n    } catch {\n      return false;\n    }\n  }, 'Expected canonical unpadded base64url with the required byte length.');\n}\n\nconst walletAddress = z.string().min(32).max(44).refine((value) => {\n  try {\n    decodeWalletAddress(value);\n    return true;\n  } catch {\n    return false;\n  }\n}, 'Expected a canonical base58 Solana address.');\n\nconst timestamp = z.string().length(24).refine((value) => {\n  if (value.length !== 24) return false;\n  const time = new Date(value);\n  return Number.isFinite(time.getTime()) && time.toISOString() === value;\n}, 'Expected a UTC ISO 8601 timestamp with milliseconds.');\n\nconst identityStatementFields = z.strictObject({\n  protocol: z.literal(PROTOCOL),\n  schemaVersion: z.literal(SCHEMA_VERSION),\n  purpose: z.enum([BINDING_PURPOSE, DEMO_PURPOSE]),\n  domain: z.enum([IDENTITY_DOMAIN, DEMO_IDENTITY_DOMAIN]),\n  network: z.enum([NETWORK, DEMO_NETWORK]),\n  walletAddress,\n  legacyAlgorithm: z.literal(LEGACY_ALGORITHM),\n  pqAlgorithm: z.literal(PQ_ALGORITHM),\n  pqPublicKey: base64Bytes(PQ_PUBLIC_KEY_BYTES),\n  nonce: base64Bytes(NONCE_BYTES),\n  issuedAt: timestamp,\n  expiresAt: timestamp,\n});\n\nfunction matchesIdentityDomain({ purpose, domain }: Pick<z.infer<typeof identityStatementFields>, 'purpose' | 'domain'>) {\n  return domain === (purpose === DEMO_PURPOSE ? DEMO_IDENTITY_DOMAIN : IDENTITY_DOMAIN);\n}\n\nfunction matchesIdentityNetwork({ purpose, network }: Pick<z.infer<typeof identityStatementFields>, 'purpose' | 'network'>) {\n  return network === (purpose === DEMO_PURPOSE ? DEMO_NETWORK : NETWORK);\n}\n\nconst domainError = { path: ['domain'], message: 'The signing domain must match the proof purpose.' };\nconst networkError = { path: ['network'], message: 'The network must match the proof purpose.' };\nexport const identityStatementSchema = identityStatementFields\n  .refine(matchesIdentityDomain, domainError)\n  .refine(matchesIdentityNetwork, networkError);\n\nexport const manifestWithoutIdSchema = identityStatementFields.extend({\n  walletSignature: base64Bytes(ED25519_SIGNATURE_BYTES),\n  pqSignature: base64Bytes(PQ_SIGNATURE_BYTES),\n  signedPayload: base64Bytes(1, MAX_STATEMENT_BYTES),\n  walletSignedMessage: base64Bytes(1, MAX_WALLET_MESSAGE_BYTES),\n  walletMessageFormat: z.enum([RAW_WALLET_FORMAT, OCMS_WALLET_FORMAT, DEMO_WALLET_FORMAT]),\n})\n  .refine(matchesIdentityDomain, domainError)\n  .refine(matchesIdentityNetwork, networkError)\n  .refine(({ purpose, walletMessageFormat }) => (purpose === DEMO_PURPOSE) === (walletMessageFormat === DEMO_WALLET_FORMAT), {\n    path: ['walletMessageFormat'],\n    message: 'The message format must match the proof purpose.',\n  });\n\nexport const manifestSchema = manifestWithoutIdSchema.safeExtend({\n  manifestId: z.string().length(64).regex(/^[0-9a-f]{64}$/),\n});\n\nexport function parseManifestJson(raw: string): unknown {\n  if (raw.length > MAX_MANIFEST_BYTES || new TextEncoder().encode(raw).byteLength > MAX_MANIFEST_BYTES) {\n    throw new SyntaxError('The manifest exceeds the 32 KiB limit.');\n  }\n  const parsed: unknown = JSON.parse(raw);\n  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return parsed;\n\n  // Native parsing validates the grammar first. In this flat schema a complete JSON string\n  // immediately before a colon is a property name, including names written with JSON escapes.\n  const names = new Set<string>();\n  for (const [, literal, colon] of raw.matchAll(/(\"(?:[^\"\\\\]|\\\\[\\s\\S])*\")([ \\t\\r\\n]*:)?/g)) {\n    if (!colon) continue;\n    const name = JSON.parse(literal) as string;\n    if (names.has(name)) throw new SyntaxError('Duplicate property names are not allowed in a migration manifest.');\n    names.add(name);\n  }\n  return parsed;\n}\n\nexport type IdentityStatement = z.infer<typeof identityStatementSchema>;\nexport type ManifestWithoutId = z.infer<typeof manifestWithoutIdSchema>;\nexport type MigrationManifest = z.infer<typeof manifestSchema>;\nexport type WalletMessageFormat = MigrationManifest['walletMessageFormat'];\n"},{"path":"src/solana/address.ts","content":"import { ed25519 } from '@noble/curves/ed25519.js';\n\nexport const MAINNET_CHAIN = 'solana:mainnet';\nexport const SYSTEM_PROGRAM = '11111111111111111111111111111111';\nexport const TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nexport const TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';\n\nexport function isOnCurve(publicKey: Uint8Array): boolean {\n  try {\n    ed25519.Point.fromBytes(publicKey, true);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport function explorerUrl(address: string): string {\n  return `https://explorer.solana.com/address/${encodeURIComponent(address)}`;\n}\n"},{"path":"src/solana/scanner.ts","content":"import { isInteger, parse } from 'lossless-json';\nimport { z } from 'zod';\nimport { decodeWalletAddress } from '../crypto/encoding';\nimport { isOnCurve, SYSTEM_PROGRAM, TOKEN_2022_PROGRAM, TOKEN_PROGRAM } from './address';\n\nexport const MAINNET_GENESIS = '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d';\nconst commitment = { commitment: 'confirmed', encoding: 'jsonParsed' };\nconst scanTtlMs = 30_000;\nconst partialScanTtlMs = 5_000;\nconst clusterTtlMs = 300_000;\nconst fallbackRetryMs = 4_000;\nconst maxCachedScans = 24;\nconst maxActiveScans = 3;\nconst decimalsSchema = z.number().int().min(0).max(255);\nconst rawAmount = z.string().regex(/^\\d{1,20}$/);\nconst tokenAmount = z.object({ amount: rawAmount, decimals: decimalsSchema });\nconst tokenAccountInfo = z.object({\n  mint: z.string(), owner: z.string(), tokenAmount, state: z.string(),\n  delegate: z.string().optional(), closeAuthority: z.string().optional(),\n  extensions: z.array(z.object({ extension: z.string(), state: z.unknown().optional() })).optional(),\n});\nconst mintInfo = z.object({\n  supply: rawAmount, decimals: decimalsSchema, isInitialized: z.boolean(),\n  mintAuthority: z.string().nullable(), freezeAuthority: z.string().nullable(),\n  extensions: z.array(z.object({ extension: z.string(), state: z.unknown().optional() })).optional(),\n});\nconst parsedData = z.object({ parsed: z.object({ type: z.string(), info: z.unknown() }) });\nconst lamports = z.union([z.number().int().nonnegative(), z.bigint().nonnegative()]).transform(BigInt);\nconst account = z.object({\n  lamports, owner: z.string(), executable: z.boolean(), data: z.unknown(),\n  space: z.number().int().nonnegative().optional(),\n});\nconst context = z.object({ slot: z.number().int().nonnegative() });\nconst accountResult = z.object({ value: account.nullable(), context });\nconst tokenResult = z.object({\n  context,\n  value: z.array(z.object({ pubkey: z.string(), account })),\n});\nconst rpcResponse = z.object({\n  id: z.number(), jsonrpc: z.literal('2.0'), result: z.unknown().optional(),\n  error: z.object({ code: z.number(), message: z.string() }).optional(),\n});\n\nexport type TokenProgram = 'SPL Token' | 'Token-2022';\nexport type AccountKind = 'Wallet / system account' | 'Possible PDA (off curve)' | 'Mint'\n  | 'Token account' | 'Token multisig' | 'Executable program' | 'Program-owned account' | 'Empty account';\n\nexport interface HeldTokenAccount extends z.infer<typeof tokenAccountInfo> {\n  address: string;\n  program: TokenProgram;\n}\n\nexport interface ScanResult {\n  address: string;\n  slot: number;\n  fetchedAt: number;\n  cached: boolean;\n  onCurve: boolean;\n  owner: string | null;\n  lamports: bigint | null;\n  kind: AccountKind;\n  program: TokenProgram | null;\n  mint: z.infer<typeof mintInfo> | null;\n  token: z.infer<typeof tokenAccountInfo> | null;\n  holdings: { mint: string; program: TokenProgram; rawAmount: bigint; decimals: number; accounts: number }[];\n  tokenAccounts: HeldTokenAccount[];\n  tokenQueries: { program: TokenProgram; slot: number | null; error: string | null }[];\n  notices: string[];\n}\n\ntype ScanData = Omit<ScanResult, 'cached' | 'fetchedAt'>;\ntype RpcErrorKind = 'network' | 'timeout' | 'rate-limit' | 'blocked' | 'rpc' | 'response' | 'wrong-cluster' | 'busy';\n\nexport class SolanaRpcError extends Error {\n  constructor(readonly kind: RpcErrorKind, detail: string) {\n    super(detail);\n    this.name = 'SolanaRpcError';\n  }\n}\n\nfunction programName(owner: string): TokenProgram | null {\n  if (owner === TOKEN_PROGRAM) return 'SPL Token';\n  if (owner === TOKEN_2022_PROGRAM) return 'Token-2022';\n  return null;\n}\n\nexport function formatAmount(amount: bigint, decimals: number): string {\n  if (decimals === 0) return amount.toString();\n  const text = amount.toString().padStart(decimals + 1, '0');\n  const fraction = text.slice(-decimals).replace(/0+$/, '');\n  return fraction ? `${text.slice(0, -decimals)}.${fraction}` : text.slice(0, -decimals);\n}\n\nexport function errorMessage(error: unknown): string {\n  return error instanceof Error ? error.message : 'The operation failed.';\n}\n\nexport class SolanaScanner {\n  #id = 0;\n  #validatedUntil = 0;\n  #retryAt = 0;\n  #pendingCluster: Promise<void> | undefined;\n  #pendingScans = new Map<string, Promise<ScanResult>>();\n  #cache = new Map<string, { result: ScanResult; expiresAt: number }>();\n\n  constructor(\n    private readonly endpoint: string,\n    private readonly request: typeof fetch = globalThis.fetch.bind(globalThis),\n    private readonly timeoutMs = 12_000,\n  ) {}\n\n  #rateLimitError(now = Date.now()): SolanaRpcError {\n    const seconds = Math.max(1, Math.ceil((this.#retryAt - now) / 1000));\n    return new SolanaRpcError('rate-limit', `The RPC is rate limiting requests. Retry after ${seconds} seconds.`);\n  }\n\n  #acceptRateLimit(header: string | null): SolanaRpcError {\n    const now = Date.now();\n    const wait = header && /^\\d+$/.test(header)\n      ? Number(header) * 1000\n      : header ? Date.parse(header) - now : NaN;\n    const delay = Number.isFinite(wait) ? Math.max(1000, wait) : fallbackRetryMs;\n    this.#retryAt = Math.max(this.#retryAt, now + delay);\n    return this.#rateLimitError(now);\n  }\n\n  async #call<T>(method: string, params: readonly unknown[], shape: z.ZodType<T>): Promise<T> {\n    if (Date.now() < this.#retryAt) throw this.#rateLimitError();\n    const id = ++this.#id;\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n    try {\n      const response = await this.request(this.endpoint, {\n        method: 'POST', headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ jsonrpc: '2.0', id, method, params }), signal: controller.signal,\n        credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer',\n      });\n      if (response.status === 429) {\n        throw this.#acceptRateLimit(response.headers.get('Retry-After'));\n      }\n      if (response.status === 401 || response.status === 403) {\n        throw new SolanaRpcError('blocked', `The RPC denied this browser request (HTTP ${response.status}).`);\n      }\n      if (!response.ok) throw new SolanaRpcError('rpc', `The RPC returned HTTP ${response.status}.`);\n      const responseText = await response.text();\n      let decoded: unknown;\n      try {\n        decoded = parse(responseText, null, {\n          parseNumber: (value) => {\n            const number = Number(value);\n            return isInteger(value) && !Number.isSafeInteger(number) ? BigInt(value) : number;\n          },\n        });\n      } catch {\n        throw new SolanaRpcError('response', 'The RPC returned unreadable JSON.');\n      }\n      const received = rpcResponse.safeParse(decoded);\n      if (!received.success || received.data.id !== id) {\n        throw new SolanaRpcError('response', 'The RPC returned an invalid response.');\n      }\n      const { result, error } = received.data;\n      if (error) {\n        const limited = error.code === 429 || /rate limit|too many requests/i.test(error.message);\n        if (limited) throw this.#acceptRateLimit(response.headers.get('Retry-After'));\n        throw new SolanaRpcError('rpc', `The RPC rejected ${method} (${error.code}).`);\n      }\n      const validated = shape.safeParse(result);\n      if (!validated.success) throw new SolanaRpcError('response', `The RPC returned unsupported ${method} data.`);\n      return validated.data;\n    } catch (error) {\n      if (error instanceof SolanaRpcError) throw error;\n      if (controller.signal.aborted) throw new SolanaRpcError('timeout', 'The RPC request timed out. Try again.');\n      throw new SolanaRpcError('network', 'The browser could not reach the RPC. Check your connection or RPC access.');\n    } finally {\n      clearTimeout(timer);\n    }\n  }\n\n  async #verifyCluster(): Promise<void> {\n    if (this.#validatedUntil > Date.now()) return;\n    this.#pendingCluster ??= this.#call('getGenesisHash', [], z.string()).then((genesis) => {\n      if (genesis !== MAINNET_GENESIS) {\n        throw new SolanaRpcError('wrong-cluster', 'The configured RPC is not on Solana Mainnet.');\n      }\n      this.#validatedUntil = Date.now() + clusterTtlMs;\n    }).finally(() => {\n      this.#pendingCluster = undefined;\n    });\n    return this.#pendingCluster;\n  }\n\n  async scan(input: string, { refresh = false }: { refresh?: boolean } = {}): Promise<ScanResult> {\n    const address = input.trim();\n    const key = decodeWalletAddress(address);\n    const inProgress = this.#pendingScans.get(address);\n    if (inProgress) return inProgress;\n\n    const cached = this.#cache.get(address);\n    this.#cache.delete(address);\n    if (cached && cached.expiresAt > Date.now()) {\n      this.#cache.set(address, cached);\n      if (!refresh) return { ...cached.result, cached: true };\n    }\n    if (this.#pendingScans.size >= maxActiveScans) {\n      throw new SolanaRpcError('busy', 'Scans are still finishing. Wait briefly, then retry.');\n    }\n\n    const pending = this.#readAddress(address, key).then((data) => {\n      const fetchedAt = Date.now();\n      const result = { ...data, fetchedAt, cached: false };\n      const partial = data.tokenQueries.some((query) => query.error);\n      const expiresAt = fetchedAt + (partial ? partialScanTtlMs : scanTtlMs);\n      this.#cache.delete(address);\n      this.#cache.set(address, { result, expiresAt });\n      if (this.#cache.size > maxCachedScans) this.#cache.delete(this.#cache.keys().next().value!);\n      return result;\n    }).finally(() => this.#pendingScans.delete(address));\n    this.#pendingScans.set(address, pending);\n    return pending;\n  }\n\n  async #readAddress(address: string, key: Uint8Array): Promise<ScanData> {\n    await this.#verifyCluster();\n    const result = await this.#call('getAccountInfo', [address, commitment], accountResult);\n    const onCurve = isOnCurve(key);\n    const { value } = result;\n    const parsed = parsedData.safeParse(value?.data);\n    const accountType = parsed.success ? parsed.data.parsed.type : null;\n    const info = parsed.success ? parsed.data.parsed.info : null;\n    const program = value ? programName(value.owner) : null;\n    const mint = program && accountType === 'mint' ? mintInfo.safeParse(info).data ?? null : null;\n    const token = program && accountType === 'account' ? tokenAccountInfo.safeParse(info).data ?? null : null;\n    const kind = getAccountKind(value, accountType, program, onCurve);\n    const notices: string[] = [];\n    if (kind === 'Possible PDA (off curve)') {\n      notices.push('This address is off curve. PDA derivation would require its seeds and program ID.');\n    }\n    if (kind === 'Program-owned account') notices.push('Program-specific account data has no supported interpretation here.');\n    if (!value) notices.push('No account data exists at this address at confirmed commitment.');\n    if ((kind === 'Mint' && !mint) || (kind === 'Token account' && !token)) {\n      notices.push('The RPC did not provide the expected parsed token information.');\n    }\n\n    const scanned: ScanData = {\n      address, slot: result.context.slot, onCurve, owner: value?.owner ?? null,\n      lamports: value?.lamports ?? null, kind, program, mint, token,\n      holdings: [], tokenAccounts: [], tokenQueries: [], notices,\n    };\n    if (kind === 'Mint' || kind === 'Token account' || kind === 'Token multisig' || kind === 'Executable program') return scanned;\n\n    const programs = [TOKEN_PROGRAM, TOKEN_2022_PROGRAM];\n    const results = await Promise.allSettled(programs.map((programId) => this.#call(\n      'getTokenAccountsByOwner', [address, { programId }, commitment], tokenResult,\n    )));\n    for (const [index, programId] of programs.entries()) {\n      const selected = results[index];\n      const tokenProgram = programName(programId)!;\n      if (selected?.status === 'fulfilled') {\n        scanned.tokenQueries.push({ program: tokenProgram, slot: selected.value.context.slot, error: null });\n        for (const item of selected.value.value) {\n          const contents = parsedData.safeParse(item.account.data);\n          const details = tokenAccountInfo.safeParse(contents.data?.parsed.info);\n          if (item.account.owner !== programId || contents.data?.parsed.type !== 'account'\n            || !details.success || details.data.owner !== address) {\n            const warning = `${tokenProgram} returned unrecognized or mismatched token account data.`;\n            if (!notices.includes(warning)) notices.push(warning);\n            continue;\n          }\n          scanned.tokenAccounts.push({ address: item.pubkey, program: tokenProgram, ...details.data });\n        }\n      } else {\n        scanned.tokenQueries.push({ program: tokenProgram, slot: null, error: errorMessage(selected?.reason) });\n      }\n    }\n\n    const holdings = new Map<string, ScanResult['holdings'][number]>();\n    for (const tokenAccount of scanned.tokenAccounts) {\n      const { mint: tokenMint, program: tokenProgram, tokenAmount: amount } = tokenAccount;\n      const group = `${tokenProgram}:${tokenMint}:${amount.decimals}`;\n      const existing = holdings.get(group) ?? {\n        mint: tokenMint, program: tokenProgram, rawAmount: 0n, decimals: amount.decimals, accounts: 0,\n      };\n      existing.rawAmount += BigInt(amount.amount);\n      existing.accounts += 1;\n      holdings.set(group, existing);\n    }\n    scanned.holdings = [...holdings.values()].sort((first, second) => first.mint.localeCompare(second.mint));\n    return scanned;\n  }\n}\n\nfunction getAccountKind(value: z.infer<typeof account> | null, parsedType: string | null, program: TokenProgram | null,\n  onCurve: boolean): AccountKind {\n  if (!value) return 'Empty account';\n  if (value.executable) return 'Executable program';\n  if (program && parsedType === 'mint') return 'Mint';\n  if (program && parsedType === 'account') return 'Token account';\n  if (program && parsedType === 'multisig') return 'Token multisig';\n  if (!onCurve) return 'Possible PDA (off curve)';\n  if (value.owner === SYSTEM_PROGRAM && !parsedType) return 'Wallet / system account';\n  return 'Program-owned account';\n}\n"},{"path":"src/solana/wallet.ts","content":"import {\n  SolanaSignMessage,\n  SolanaSignOffchainMessage,\n  type SolanaSignMessageFeature,\n  type SolanaSignOffchainMessageFeature,\n} from '@solana/wallet-standard-features';\nimport { getWallets } from '@wallet-standard/app';\nimport type { Wallet, WalletAccount } from '@wallet-standard/base';\nimport {\n  StandardConnect,\n  StandardDisconnect,\n  StandardEvents,\n  type StandardConnectFeature,\n  type StandardDisconnectFeature,\n  type StandardEventsFeature,\n} from '@wallet-standard/features';\nimport { base58 } from '@scure/base';\nimport { MAINNET_CHAIN } from './address';\n\nexport type WalletMessageMode = 'OCMS v1' | 'Raw Ed25519 message';\n\nexport function walletRegistry() {\n  return getWallets();\n}\n\nexport function isMainnetWallet(wallet: Wallet): boolean {\n  const connect = (wallet.features as Partial<StandardConnectFeature>)[StandardConnect];\n  return wallet.chains.includes(MAINNET_CHAIN) && typeof connect?.connect === 'function';\n}\n\nexport function mainnetAccounts(accounts: readonly WalletAccount[]): WalletAccount[] {\n  return accounts.filter((account) => account.chains.includes(MAINNET_CHAIN)\n    && account.publicKey.length === 32\n    && base58.encode(Uint8Array.from(account.publicKey)) === account.address);\n}\n\nexport async function connectWallet(wallet: Wallet): Promise<WalletAccount[]> {\n  const feature = (wallet.features as Partial<StandardConnectFeature>)[StandardConnect];\n  if (!feature) throw new Error('This wallet does not support Wallet Standard connections.');\n  const { accounts } = await feature.connect();\n  return mainnetAccounts(accounts);\n}\n\nexport async function disconnectWallet(wallet: Wallet): Promise<void> {\n  await (wallet.features as Partial<StandardDisconnectFeature>)[StandardDisconnect]?.disconnect();\n}\n\nexport function subscribeToAccounts(wallet: Wallet, listener: (accounts: WalletAccount[]) => void): () => void {\n  const feature = (wallet.features as Partial<StandardEventsFeature>)[StandardEvents];\n  return feature?.on('change', ({ accounts }) => {\n    if (accounts !== undefined) listener(mainnetAccounts(accounts));\n  }) ?? (() => {});\n}\n\nfunction offchainFeature(wallet: Wallet, account: WalletAccount) {\n  const feature = (wallet.features as Partial<SolanaSignOffchainMessageFeature>)[SolanaSignOffchainMessage];\n  return account.features.includes(SolanaSignOffchainMessage) && typeof feature?.signOffchainMessage === 'function'\n    && feature.supportedMessageVersions?.includes(1)\n    ? feature : undefined;\n}\n\nfunction rawFeature(wallet: Wallet, account: WalletAccount) {\n  if (!account.features.includes(SolanaSignMessage)) return undefined;\n  const feature = (wallet.features as Partial<SolanaSignMessageFeature>)[SolanaSignMessage];\n  return typeof feature?.signMessage === 'function' ? feature : undefined;\n}\n\nexport function walletMessageMode(wallet: Wallet, account: WalletAccount): WalletMessageMode | null {\n  if (offchainFeature(wallet, account)) return 'OCMS v1';\n  return rawFeature(wallet, account) ? 'Raw Ed25519 message' : null;\n}\n\nexport async function signWalletMessage(wallet: Wallet, account: WalletAccount, message: Uint8Array) {\n  const offchain = offchainFeature(wallet, account);\n  if (offchain) {\n    const [result] = await offchain.signOffchainMessage({\n      messageVersion: 1,\n      account,\n      message: new TextDecoder('utf-8', { fatal: true }).decode(message),\n      requiredSigners: [account.publicKey],\n    });\n    return walletSignature(result?.signature, result?.signedOffchainMessage, result?.signatureType);\n  }\n\n  const raw = rawFeature(wallet, account);\n  if (!raw) throw new Error('This wallet account does not support off-chain message signing.');\n  const [result] = await raw.signMessage({ account, message: new Uint8Array(message) });\n  return walletSignature(result?.signature, result?.signedMessage, result?.signatureType);\n}\n\nfunction walletSignature(signature?: ArrayLike<number>, signedMessage?: ArrayLike<number>, signatureType?: string) {\n  if (!signature || signature.length !== 64 || !signedMessage?.length\n      || (signatureType !== undefined && signatureType !== 'ed25519')) {\n    throw new Error('The wallet returned an invalid Ed25519 signature or signed message.');\n  }\n  return { signature: Uint8Array.from(signature), signedMessage: Uint8Array.from(signedMessage) };\n}\n"},{"path":"src/workers/crypto-protocol.ts","content":"export interface KeyResult {\n  publicKey: Uint8Array;\n  fingerprint: string;\n  durationMs: number;\n}\n\nexport interface SignResult {\n  signature: Uint8Array;\n  durationMs: number;\n}\n\nexport interface VerifyResult {\n  valid: boolean;\n  durationMs: number;\n}\n\nexport interface BenchmarkResult {\n  iterations: number;\n  keyGenerationMs: number;\n  signingMs: number;\n  verificationMs: number;\n  publicKeySize: number;\n  signatureSize: number;\n}\n\nexport type CryptoTask =\n  | { type: 'generate' }\n  | { type: 'clear' }\n  | { type: 'sign'; message: Uint8Array; context?: Uint8Array }\n  | { type: 'verify'; message: Uint8Array; publicKey: Uint8Array; signature: Uint8Array; context?: Uint8Array }\n  | { type: 'benchmark'; iterations: number };\n\nexport type CryptoRequest = { id: number } & CryptoTask;\n\nexport type CryptoResponse =\n  | { id: number; ok: true; result: KeyResult | SignResult | VerifyResult | BenchmarkResult | undefined }\n  | { id: number; ok: false; error: string };\n"},{"path":"src/workers/crypto.worker.ts","content":"import { fingerprintPublicKey } from '../crypto/fingerprint';\nimport { generateMlDsaKeyPair } from '../crypto/keygen';\nimport { MAX_BENCHMARK_ITERATIONS } from '../crypto/parameters';\nimport { signMlDsa } from '../crypto/signature';\nimport { verifyMlDsa } from '../crypto/verify';\nimport type { BenchmarkResult, CryptoRequest, CryptoResponse, KeyResult } from './crypto-protocol';\n\nconst scope = self as unknown as {\n  postMessage: (response: CryptoResponse) => void;\n  addEventListener: (event: 'message', listener: (message: MessageEvent<CryptoRequest>) => void) => void;\n};\nlet sessionSecretKey: Uint8Array | undefined;\nlet incoming = Promise.resolve();\n\nfunction clearKey(): void {\n  sessionSecretKey?.fill(0);\n  sessionSecretKey = undefined;\n}\n\nasync function generateKey(): Promise<KeyResult> {\n  const generated = generateMlDsaKeyPair();\n  try {\n    const fingerprint = await fingerprintPublicKey(generated.publicKey);\n    clearKey();\n    sessionSecretKey = generated.secretKey;\n    return { publicKey: generated.publicKey, fingerprint, durationMs: generated.durationMs };\n  } catch (error) {\n    generated.secretKey.fill(0);\n    throw error;\n  }\n}\n\nfunction runBenchmark(iterations: number): BenchmarkResult {\n  if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_BENCHMARK_ITERATIONS) {\n    throw new Error(`Choose 1–${MAX_BENCHMARK_ITERATIONS} benchmark iterations.`);\n  }\n\n  const message = new TextEncoder().encode('AFTERKEY browser benchmark');\n  let keyGenerationMs = 0;\n  let signingMs = 0;\n  let verificationMs = 0;\n  let publicKeySize = 0;\n  let signatureSize = 0;\n\n  for (let index = 0; index < iterations; index += 1) {\n    const pair = generateMlDsaKeyPair();\n    keyGenerationMs += pair.durationMs;\n    try {\n      let start = performance.now();\n      const signature = signMlDsa(message, pair.secretKey);\n      signingMs += performance.now() - start;\n      start = performance.now();\n      const valid = verifyMlDsa(pair.publicKey, message, signature);\n      verificationMs += performance.now() - start;\n      if (!valid) throw new Error('Benchmark signature did not verify.');\n      publicKeySize = pair.publicKey.length;\n      signatureSize = signature.length;\n    } finally {\n      pair.secretKey.fill(0);\n    }\n  }\n\n  return {\n    iterations,\n    keyGenerationMs: keyGenerationMs / iterations,\n    signingMs: signingMs / iterations,\n    verificationMs: verificationMs / iterations,\n    publicKeySize,\n    signatureSize,\n  };\n}\n\nasync function respond(request: CryptoRequest): Promise<void> {\n  try {\n    let result: Extract<CryptoResponse, { ok: true }>['result'];\n    switch (request.type) {\n      case 'generate':\n        result = await generateKey();\n        break;\n      case 'sign': {\n        if (!sessionSecretKey) throw new Error('Generate a session key before signing.');\n        const start = performance.now();\n        const signature = signMlDsa(request.message, sessionSecretKey, request.context);\n        result = { signature, durationMs: performance.now() - start };\n        break;\n      }\n      case 'verify': {\n        const start = performance.now();\n        const valid = verifyMlDsa(request.publicKey, request.message, request.signature, request.context);\n        result = { valid, durationMs: performance.now() - start };\n        break;\n      }\n      case 'benchmark':\n        result = runBenchmark(request.iterations);\n        break;\n      case 'clear':\n        clearKey();\n        result = undefined;\n        break;\n    }\n    scope.postMessage({ id: request.id, ok: true, result } satisfies CryptoResponse);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : 'The cryptographic operation failed.';\n    scope.postMessage({ id: request.id, ok: false, error: message } satisfies CryptoResponse);\n  }\n}\n\n// A queued clear or key rotation runs in order, including while key fingerprinting awaits Web Crypto.\nscope.addEventListener('message', ({ data }: MessageEvent<CryptoRequest>) => {\n  incoming = incoming.then(() => respond(data));\n});\n"}]}
