@soropass/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/checkAuth-C2AcXqFe.d.cts +110 -0
  2. package/dist/checkAuth-C2AcXqFe.d.ts +110 -0
  3. package/dist/chunk-AHFGTIBY.js +36 -0
  4. package/dist/chunk-AHFGTIBY.js.map +1 -0
  5. package/dist/chunk-AMYFJQAC.js +29 -0
  6. package/dist/chunk-AMYFJQAC.js.map +1 -0
  7. package/dist/chunk-BIRF5I6I.js +265 -0
  8. package/dist/chunk-BIRF5I6I.js.map +1 -0
  9. package/dist/chunk-JNJ2FY45.js +209 -0
  10. package/dist/chunk-JNJ2FY45.js.map +1 -0
  11. package/dist/chunk-LB4HOTLV.js +135 -0
  12. package/dist/chunk-LB4HOTLV.js.map +1 -0
  13. package/dist/chunk-LM2AZXKZ.js +108 -0
  14. package/dist/chunk-LM2AZXKZ.js.map +1 -0
  15. package/dist/chunk-LUDXP56M.js +3 -0
  16. package/dist/chunk-LUDXP56M.js.map +1 -0
  17. package/dist/chunk-MMB4ZIW3.js +48 -0
  18. package/dist/chunk-MMB4ZIW3.js.map +1 -0
  19. package/dist/chunk-MOLZIRIH.js +22 -0
  20. package/dist/chunk-MOLZIRIH.js.map +1 -0
  21. package/dist/chunk-OGSUGATA.js +3 -0
  22. package/dist/chunk-OGSUGATA.js.map +1 -0
  23. package/dist/chunk-TPBBZNPP.js +30 -0
  24. package/dist/chunk-TPBBZNPP.js.map +1 -0
  25. package/dist/chunk-UQKNPO44.js +32 -0
  26. package/dist/chunk-UQKNPO44.js.map +1 -0
  27. package/dist/chunk-UV5HORMF.js +175 -0
  28. package/dist/chunk-UV5HORMF.js.map +1 -0
  29. package/dist/chunk-W75OQKHR.js +133 -0
  30. package/dist/chunk-W75OQKHR.js.map +1 -0
  31. package/dist/connect.cjs +166 -0
  32. package/dist/connect.cjs.map +1 -0
  33. package/dist/connect.d.cts +24 -0
  34. package/dist/connect.d.ts +24 -0
  35. package/dist/connect.js +6 -0
  36. package/dist/connect.js.map +1 -0
  37. package/dist/create.cjs +483 -0
  38. package/dist/create.cjs.map +1 -0
  39. package/dist/create.d.cts +106 -0
  40. package/dist/create.d.ts +106 -0
  41. package/dist/create.js +8 -0
  42. package/dist/create.js.map +1 -0
  43. package/dist/index.cjs +1542 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.cts +197 -0
  46. package/dist/index.d.ts +197 -0
  47. package/dist/index.js +354 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/recover-0wbOXDjR.d.cts +23 -0
  50. package/dist/recover-COnsxhYk.d.ts +23 -0
  51. package/dist/recover.cjs +802 -0
  52. package/dist/recover.cjs.map +1 -0
  53. package/dist/recover.d.cts +49 -0
  54. package/dist/recover.d.ts +49 -0
  55. package/dist/recover.js +10 -0
  56. package/dist/recover.js.map +1 -0
  57. package/dist/sign-Cfg0NM0T.d.cts +73 -0
  58. package/dist/sign-Cfg0NM0T.d.ts +73 -0
  59. package/dist/sign.cjs +883 -0
  60. package/dist/sign.cjs.map +1 -0
  61. package/dist/sign.d.cts +143 -0
  62. package/dist/sign.d.ts +143 -0
  63. package/dist/sign.js +8 -0
  64. package/dist/sign.js.map +1 -0
  65. package/dist/submit-BDKADQq0.d.cts +112 -0
  66. package/dist/submit-BO0Nh49I.d.ts +112 -0
  67. package/dist/testing.cjs +955 -0
  68. package/dist/testing.cjs.map +1 -0
  69. package/dist/testing.d.cts +86 -0
  70. package/dist/testing.d.ts +86 -0
  71. package/dist/testing.js +235 -0
  72. package/dist/testing.js.map +1 -0
  73. package/dist/types--WNl-Sda.d.cts +125 -0
  74. package/dist/types--WNl-Sda.d.ts +125 -0
  75. package/dist/types-dMRWEEo0.d.cts +73 -0
  76. package/dist/types-lW2h8Uxn.d.ts +73 -0
  77. package/dist/types.cjs +44 -0
  78. package/dist/types.cjs.map +1 -0
  79. package/dist/types.d.cts +5 -0
  80. package/dist/types.d.ts +5 -0
  81. package/dist/types.js +5 -0
  82. package/dist/types.js.map +1 -0
  83. package/package.json +117 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/webauthn/signature.ts","../src/internal/bytes.ts","../src/webauthn/payload.ts","../src/internal/encoding.ts","../src/webauthn/clientData.ts","../src/internal/cbor.ts","../src/webauthn/authData.ts","../src/webauthn/verify.ts","../src/ceremonies/random.ts","../src/ceremonies/browserClient.ts","../src/ceremonies/browserSigner.ts","../src/soroban/preimage.ts","../src/soroban/assemble.ts","../src/soroban/smartWallet.ts","../src/soroban/sign.ts","../src/soroban/signer.ts","../src/soroban/checkAuth.ts","../src/adapters/direct.ts","../src/soroban/submit.ts"],"names":["p256","sha256","xdr","hash","nativeToScVal","Contract","rpc","TransactionBuilder","Keypair"],"mappings":";;;;;;;AAoBO,IAAM,QAAA,GAAN,MAAM,SAAA,SAAiB,KAAA,CAAM;AAAA,EACzB,IAAA;AAAA,EACS,IAAA,GAAO,UAAA;AAAA,EAEzB,WAAA,CAAY,IAAA,EAAoB,OAAA,EAAkB,OAAA,EAA+B;AAC/E,IAAA,KAAA,CAAM,OAAA,IAAW,MAAM,OAAO,CAAA;AAC9B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAGZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,SAAA,CAAS,SAAS,CAAA;AAAA,EAChD;AACF,CAAA;;;AC3BA,IAAM,cAAA,GAAiB,EAAA;AAUhB,SAAS,aAAa,GAAA,EAA6B;AACxD,EAAA,IAAI,GAAA,CAAI,SAAS,cAAA,EAAgB;AAC/B,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,uBAAA;AAAA,MACA,CAAA,iBAAA,EAAoB,GAAA,CAAI,MAAM,CAAA,oBAAA,EAAuB,cAAc,CAAA;AAAA,KACrE;AAAA,EACF;AACA,EAAA,IAAI;AACF,IAAA,OAAOA,SAAA,CAAK,SAAA,CAAU,OAAA,CAAQ,GAA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AA,CAAQ,iBAAA;AAAA,IAC3B,WAAW,OAAA,CAAQ;AAAA,GACpB,CAAA;AACH,EAAA,OAAO,UAAA,CAAW,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,CAAA;AACxC","file":"sign.cjs","sourcesContent":["/**\n * The frozen taxonomy of error codes the SDK can throw. This union is\n * deliberately closed — every failure path maps to exactly one of these.\n */\nexport const KIT_ERROR_CODES = Object.freeze([\n 'USER_CANCELLED',\n 'ES256_NOT_SUPPORTED',\n 'RP_ID_MISMATCH',\n 'ORIGIN_MISMATCH',\n 'CHALLENGE_MISMATCH',\n 'INVALID_SIGNATURE_DER',\n 'INVALID_PUBLIC_KEY',\n 'CONTRACT_AUTH_FAILED',\n 'NETWORK_ERROR',\n 'UNSUPPORTED_AUTHENTICATOR',\n] as const);\n\nexport type KitErrorCode = (typeof KIT_ERROR_CODES)[number];\n\n/** Structured error carrying a machine-readable {@link KitErrorCode}. */\nexport class KitError extends Error {\n readonly code: KitErrorCode;\n override readonly name = 'KitError';\n\n constructor(code: KitErrorCode, message?: string, options?: { cause?: unknown }) {\n super(message ?? code, options);\n this.code = code;\n // Restore the prototype chain so `instanceof KitError` works after\n // down-level transpilation to CJS.\n Object.setPrototypeOf(this, KitError.prototype);\n }\n}\n\nexport function isKitError(value: unknown): value is KitError {\n return value instanceof KitError;\n}\n","import { p256 } from '@noble/curves/nist';\nimport { KitError } from '../errors';\n\n/** Maximum DER length of a P-256 ECDSA signature: SEQ + two 33-byte INTEGERs. */\nconst MAX_DER_LENGTH = 72;\n\n/**\n * Convert an ASN.1 DER ECDSA signature to the 64-byte raw `R‖S` form Soroban's\n * `secp256r1_verify` expects, using noble's audited DER parser (R and S are\n * left-padded to 32 bytes big-endian). Rejects malformed or over-long input.\n *\n * Note: this does NOT enforce low-S — that normalization is added in S04\n * (YK-430). The output here mirrors the signature exactly as parsed.\n */\nexport function derToCompact(der: Uint8Array): Uint8Array {\n if (der.length > MAX_DER_LENGTH) {\n throw new KitError(\n 'INVALID_SIGNATURE_DER',\n `DER signature is ${der.length} bytes, exceeds max ${MAX_DER_LENGTH}`,\n );\n }\n try {\n return p256.Signature.fromDER(der).toCompactRawBytes();\n } catch (cause) {\n throw new KitError('INVALID_SIGNATURE_DER', 'failed to parse DER signature', { cause });\n }\n}\n\nfunction assertCompactLength(compactSignature: Uint8Array): void {\n if (compactSignature.length !== 64) {\n throw new KitError(\n 'INVALID_SIGNATURE_DER',\n `compact signature must be 64 bytes, got ${compactSignature.length}`,\n );\n }\n}\n\n/** True if a 64-byte compact signature is in canonical low-S form (S ≤ n/2). */\nexport function isLowS(compactSignature: Uint8Array): boolean {\n assertCompactLength(compactSignature);\n return !p256.Signature.fromCompact(compactSignature).hasHighS();\n}\n\n/**\n * Normalize a 64-byte compact signature to canonical low-S: if S > n/2, replace\n * S with n − S (anchor LOW_S_NORMALIZATION, invariant #2). ~50% of Apple Touch\n * ID / Face ID assertions are high-S and Soroban's `secp256r1_verify` does not\n * enforce low-S, so the SDK MUST emit low-S before a signature reaches a\n * contract. Idempotent: low-S input is returned unchanged.\n */\nexport function normalizeLowS(compactSignature: Uint8Array): Uint8Array {\n assertCompactLength(compactSignature);\n return p256.Signature.fromCompact(compactSignature).normalizeS().toCompactRawBytes();\n}\n\n/** DER → 64-byte canonical low-S compact — the conversion the signing ceremony uses. */\nexport function derToCompactLowS(der: Uint8Array): Uint8Array {\n return normalizeLowS(derToCompact(der));\n}\n","/** Concatenate byte arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const total = arrays.reduce((n, a) => n + a.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const a of arrays) {\n out.set(a, offset);\n offset += a.length;\n }\n return out;\n}\n\n/** Length-safe, constant-time-ish byte equality. */\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i += 1) diff |= (a[i] ?? 0) ^ (b[i] ?? 0);\n return diff === 0;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n","import { sha256 } from '../internal/sha256';\nimport { concatBytes } from '../internal/bytes';\n\n/**\n * Reconstruct the 32-byte payload the authenticator signed and that Soroban's\n * `__check_auth` re-derives on-chain:\n *\n * SHA256( authenticatorData ‖ SHA256(clientDataJSON) )\n */\nexport function reconstructSignedPayload(input: {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n}): Uint8Array {\n const clientDataHash = sha256(input.clientDataJSON);\n return sha256(concatBytes(input.authenticatorData, clientDataHash));\n}\n","/**\n * Isomorphic base64url + UTF-8 codecs. `atob`/`btoa`/`TextEncoder`/`TextDecoder`\n * are globals in modern browsers and Node >= 16, so no platform branch is\n * needed and nothing is bundled.\n */\n\n/** Encode bytes as unpadded base64url. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decode base64 or base64url (padding optional) to bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array<ArrayBuffer> {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/');\n const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);\n const binary = atob(padded);\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nexport function utf8ToBytes(text: string): Uint8Array {\n return new TextEncoder().encode(text);\n}\n\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n","import { KitError } from '../errors';\nimport { base64UrlToBytes, bytesToBase64Url, bytesToUtf8 } from '../internal/encoding';\n\n/** The subset of clientDataJSON fields we rely on. */\nexport interface ClientData {\n type: string;\n /** base64url-encoded challenge as embedded by the client. */\n challenge: string;\n origin: string;\n crossOrigin?: boolean;\n}\n\n/** Encode a raw challenge as the base64url string embedded in clientDataJSON. */\nexport function encodeChallenge(challenge: Uint8Array): string {\n return bytesToBase64Url(challenge);\n}\n\n/** Decode the base64url challenge embedded in clientDataJSON back to bytes. */\nexport function decodeChallenge(challenge: string): Uint8Array {\n return base64UrlToBytes(challenge);\n}\n\n/** Parse clientDataJSON bytes into a typed, validated-shape object. */\nexport function parseClientDataJSON(clientDataJSON: Uint8Array): ClientData {\n let raw: unknown;\n try {\n raw = JSON.parse(bytesToUtf8(clientDataJSON));\n } catch (cause) {\n throw new KitError('UNSUPPORTED_AUTHENTICATOR', 'clientDataJSON is not valid JSON', { cause });\n }\n if (typeof raw !== 'object' || raw === null) {\n throw new KitError('UNSUPPORTED_AUTHENTICATOR', 'clientDataJSON is not a JSON object');\n }\n const obj = raw as Record<string, unknown>;\n const { type, challenge, origin, crossOrigin } = obj;\n if (typeof type !== 'string' || typeof challenge !== 'string' || typeof origin !== 'string') {\n throw new KitError('UNSUPPORTED_AUTHENTICATOR', 'clientDataJSON is missing required fields');\n }\n return {\n type,\n challenge,\n origin,\n crossOrigin: typeof crossOrigin === 'boolean' ? crossOrigin : undefined,\n };\n}\n\n/**\n * Parse and verify clientDataJSON for an authentication (`webauthn.get`)\n * assertion: the ceremony type, the origin (exact match against one or more\n * allowed origins), and the embedded challenge (base64url string).\n */\nexport function verifyClientDataJSON(\n clientDataJSON: Uint8Array,\n expected: { origin: string | string[]; challenge: string },\n): ClientData {\n const data = parseClientDataJSON(clientDataJSON);\n if (data.type !== 'webauthn.get') {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n `clientDataJSON.type \"${data.type}\" is not \"webauthn.get\"`,\n );\n }\n const allowed = Array.isArray(expected.origin) ? expected.origin : [expected.origin];\n if (!allowed.includes(data.origin)) {\n throw new KitError('ORIGIN_MISMATCH', `origin \"${data.origin}\" not in [${allowed.join(', ')}]`);\n }\n if (data.challenge !== expected.challenge) {\n throw new KitError('CHALLENGE_MISMATCH', 'clientDataJSON challenge does not match expected');\n }\n return data;\n}\n","/**\n * A minimal CBOR (RFC 8949) decoder — only the major types WebAuthn needs:\n * unsigned ints, negative ints, byte strings, text strings, arrays and maps,\n * with 1/2/4-byte length prefixes. Indefinite lengths, tags, floats and\n * 8-byte lengths are intentionally unsupported (COSE keys and attestation\n * objects never use them) and throw. This keeps the SDK dependency-free while\n * staying robust — it is fully fixture-tested. It replaces passkey-kit's\n * hardcoded byte-offset scanning, which had no bounds checks.\n */\nexport type CborValue = number | bigint | Uint8Array | string | CborValue[] | CborMap;\nexport type CborMap = Map<number | string, CborValue>;\n\ninterface Decoded {\n value: CborValue;\n /** Total bytes consumed starting at the requested offset. */\n length: number;\n}\n\nfunction byteAt(bytes: Uint8Array, index: number): number {\n const value = bytes[index];\n if (value === undefined) throw new Error(`CBOR: unexpected end of input at byte ${index}`);\n return value;\n}\n\n/** Decode the first CBOR item at `offset`, returning its value and byte length. */\nconst MAX_DEPTH = 16; // COSE keys / attestation objects nest at most ~3 levels.\n\nexport function decodeCbor(bytes: Uint8Array, offset = 0, depth = 0): Decoded {\n if (depth > MAX_DEPTH) throw new Error('CBOR: maximum nesting depth exceeded');\n const first = byteAt(bytes, offset);\n const major = first >> 5;\n const info = first & 0x1f;\n let pos = offset + 1;\n\n let argument: number;\n if (info < 24) {\n argument = info;\n } else if (info === 24) {\n argument = byteAt(bytes, pos);\n pos += 1;\n } else if (info === 25) {\n argument = (byteAt(bytes, pos) << 8) | byteAt(bytes, pos + 1);\n pos += 2;\n } else if (info === 26) {\n argument =\n byteAt(bytes, pos) * 0x1000000 +\n (byteAt(bytes, pos + 1) << 16) +\n (byteAt(bytes, pos + 2) << 8) +\n byteAt(bytes, pos + 3);\n pos += 4;\n } else {\n throw new Error(`CBOR: unsupported length encoding (additional info ${info})`);\n }\n\n switch (major) {\n case 0: // unsigned integer\n return { value: argument, length: pos - offset };\n case 1: // negative integer\n return { value: -1 - argument, length: pos - offset };\n case 2: {\n // byte string\n const end = pos + argument;\n if (end > bytes.length) throw new Error('CBOR: byte string exceeds input');\n return { value: bytes.slice(pos, end), length: end - offset };\n }\n case 3: {\n // text string (UTF-8)\n const end = pos + argument;\n if (end > bytes.length) throw new Error('CBOR: text string exceeds input');\n return { value: new TextDecoder().decode(bytes.slice(pos, end)), length: end - offset };\n }\n case 4: {\n // array\n const items: CborValue[] = [];\n let cursor = pos;\n for (let i = 0; i < argument; i += 1) {\n const item = decodeCbor(bytes, cursor, depth + 1);\n items.push(item.value);\n cursor += item.length;\n }\n return { value: items, length: cursor - offset };\n }\n case 5: {\n // map\n const map: CborMap = new Map();\n let cursor = pos;\n for (let i = 0; i < argument; i += 1) {\n const key = decodeCbor(bytes, cursor, depth + 1);\n cursor += key.length;\n const val = decodeCbor(bytes, cursor, depth + 1);\n cursor += val.length;\n if (typeof key.value !== 'number' && typeof key.value !== 'string') {\n throw new Error('CBOR: unsupported map key type');\n }\n if (map.has(key.value)) {\n throw new Error('CBOR: duplicate map key (non-canonical)');\n }\n map.set(key.value, val.value);\n }\n return { value: map, length: cursor - offset };\n }\n default:\n throw new Error(`CBOR: unsupported major type ${major}`);\n }\n}\n\nexport function decodeCborFirst(bytes: Uint8Array): CborValue {\n return decodeCbor(bytes, 0).value;\n}\n","import { KitError } from '../errors';\nimport { decodeCbor } from '../internal/cbor';\nimport { sha256 } from '../internal/sha256';\nimport { equalBytes } from '../internal/bytes';\nimport { utf8ToBytes } from '../internal/encoding';\n\nexport interface AuthenticatorDataFlags {\n /** User Present */\n up: boolean;\n /** User Verified */\n uv: boolean;\n /** Backup Eligible */\n be: boolean;\n /** Backup State */\n bs: boolean;\n /** Attested credential data present */\n at: boolean;\n /** Extension data present */\n ed: boolean;\n /** Raw flags byte. */\n bits: number;\n}\n\nexport interface ParsedAuthenticatorData {\n rpIdHash: Uint8Array;\n flags: AuthenticatorDataFlags;\n signCount: number;\n aaguid?: Uint8Array;\n credentialId?: Uint8Array;\n /** Raw CBOR-encoded COSE public key (exact bytes), if attested data present. */\n credentialPublicKey?: Uint8Array;\n}\n\nconst MIN_LENGTH = 37; // rpIdHash(32) + flags(1) + signCount(4)\n\n/** Parse the authenticatorData byte structure (WebAuthn §6.1). */\nexport function parseAuthenticatorData(authData: Uint8Array): ParsedAuthenticatorData {\n if (authData.length < MIN_LENGTH) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n `authenticatorData is ${authData.length} bytes, expected at least ${MIN_LENGTH}`,\n );\n }\n const view = new DataView(authData.buffer, authData.byteOffset, authData.byteLength);\n const rpIdHash = authData.slice(0, 32);\n const bits = authData[32] ?? 0;\n const flags: AuthenticatorDataFlags = {\n up: (bits & 0x01) !== 0,\n uv: (bits & 0x04) !== 0,\n be: (bits & 0x08) !== 0,\n bs: (bits & 0x10) !== 0,\n at: (bits & 0x40) !== 0,\n ed: (bits & 0x80) !== 0,\n bits,\n };\n const signCount = view.getUint32(33, false);\n\n const result: ParsedAuthenticatorData = { rpIdHash, flags, signCount };\n\n if (flags.at) {\n if (authData.length < 55) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'authenticatorData truncated in attested data',\n );\n }\n result.aaguid = authData.slice(37, 53);\n const credIdLength = view.getUint16(53, false);\n const credIdEnd = 55 + credIdLength;\n if (authData.length < credIdEnd) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'authenticatorData truncated in credentialId',\n );\n }\n result.credentialId = authData.slice(55, credIdEnd);\n // The COSE public key is the next CBOR item; capture its exact bytes so we\n // stop cleanly before any extension data (when flags.ed is set).\n const rest = authData.slice(credIdEnd);\n const { length } = decodeCbor(rest, 0);\n result.credentialPublicKey = rest.slice(0, length);\n }\n\n return result;\n}\n\n/** Verify that authenticatorData's rpIdHash equals SHA-256(rpId). */\nexport function verifyRpIdHash(authData: Uint8Array, rpId: string): void {\n const actual = parseAuthenticatorData(authData).rpIdHash;\n const expected = sha256(utf8ToBytes(rpId));\n if (!equalBytes(actual, expected)) {\n throw new KitError(\n 'RP_ID_MISMATCH',\n `authenticatorData rpIdHash does not match SHA-256(\"${rpId}\")`,\n );\n }\n}\n","import { p256 } from '@noble/curves/nist';\nimport { reconstructSignedPayload } from './payload';\nimport { derToCompact } from './signature';\n\nexport interface VerifyAssertionInput {\n /** SEC-1 uncompressed public key (65 bytes, `0x04 ‖ X ‖ Y`). */\n publicKey: Uint8Array;\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n /** DER-encoded (≤72 B) or already-compact (64 B) signature. */\n signature: Uint8Array;\n}\n\n/**\n * Verify a WebAuthn assertion the way the on-chain `secp256r1_verify` does:\n * reconstruct `SHA256(authData ‖ SHA256(cdj))` and check ECDSA. `lowS: false`\n * mirrors the host function, which does NOT enforce low-S (we normalize\n * separately before submitting — see S04/YK-430).\n */\nexport function verifyAssertionSignature(input: VerifyAssertionInput): boolean {\n const payload = reconstructSignedPayload(input);\n const compact = input.signature.length === 64 ? input.signature : derToCompact(input.signature);\n // `format: 'compact'` pins the 64-byte interpretation — without it noble tries\n // DER-first and could misread a compact signature that happens to start 0x30.\n return p256.verify(compact, payload, input.publicKey, { lowS: false, format: 'compact' });\n}\n","import { KitError } from '../errors';\n\n/**\n * Cryptographically-random bytes, isomorphic (browser + Node global crypto).\n * Throws instead of silently returning all-zero bytes when no secure RNG is\n * present — an all-zero challenge would be catastrophic, not a soft fallback.\n */\nexport function randomBytes(length: number): Uint8Array<ArrayBuffer> {\n const webcrypto = globalThis.crypto as Crypto | undefined;\n if (typeof webcrypto?.getRandomValues !== 'function') {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'no secure random source (globalThis.crypto.getRandomValues) is available in this environment',\n );\n }\n const out = new Uint8Array(new ArrayBuffer(length));\n webcrypto.getRandomValues(out);\n return out;\n}\n","import { KitError } from '../errors';\nimport { base64UrlToBytes } from '../internal/encoding';\nimport type { PublicKeyCredentialCreationOptionsJSON } from '../webauthn/createOptions';\nimport { randomBytes } from './random';\nimport type {\n CredentialStorage,\n WebAuthnClient,\n WebAuthnCreateResult,\n WebAuthnGetOptions,\n WebAuthnGetResult,\n} from './types';\n\n/**\n * Map a `navigator.credentials` rejection to a `KitError`. Dismissing the OS\n * passkey sheet rejects with a `NotAllowedError` (a DOMException) — surface that\n * as `USER_CANCELLED` so the UI shows the true \"you cancelled\" copy instead of\n * the generic unsupported-authenticator fallback (S20 / S04 polish).\n */\nfunction asKitError(error: unknown): KitError {\n if (error instanceof KitError) return error;\n const name =\n typeof error === 'object' && error !== null && 'name' in error\n ? (error as { name?: unknown }).name\n : undefined;\n if (name === 'NotAllowedError') {\n return new KitError('USER_CANCELLED', 'The passkey prompt was dismissed.', { cause: error });\n }\n const message = error instanceof Error ? error.message : 'WebAuthn request failed';\n // Preserve the original DOMException name (e.g. InvalidStateError / ConstraintError)\n // in the message so diagnostics show the true cause, not just the generic bucket.\n const detail = typeof name === 'string' ? `${name}: ${message}` : message;\n return new KitError('UNSUPPORTED_AUTHENTICATOR', detail, { cause: error });\n}\n\n/** The browser `WebAuthnClient` backed by `navigator.credentials`. */\nexport function browserWebAuthnClient(): WebAuthnClient {\n const credentials = (globalThis as { navigator?: Navigator }).navigator?.credentials;\n if (!credentials) {\n throw new KitError('UNSUPPORTED_AUTHENTICATOR', 'navigator.credentials is unavailable');\n }\n return {\n async create(options: PublicKeyCredentialCreationOptionsJSON): Promise<WebAuthnCreateResult> {\n const publicKey: PublicKeyCredentialCreationOptions = {\n challenge: base64UrlToBytes(options.challenge),\n rp: options.rp,\n user: {\n id: base64UrlToBytes(options.user.id),\n name: options.user.name,\n displayName: options.user.displayName,\n },\n pubKeyCredParams: options.pubKeyCredParams,\n authenticatorSelection: options.authenticatorSelection,\n attestation: options.attestation,\n timeout: options.timeout,\n };\n let credential: PublicKeyCredential | null;\n try {\n credential = (await credentials.create({ publicKey })) as PublicKeyCredential | null;\n } catch (error) {\n throw asKitError(error);\n }\n if (!credential) throw new KitError('USER_CANCELLED', 'credential creation returned null');\n const response = credential.response as AuthenticatorAttestationResponse;\n return {\n id: credential.id,\n rawId: new Uint8Array(credential.rawId),\n attestationObject: new Uint8Array(response.attestationObject),\n };\n },\n async get(options: WebAuthnGetOptions): Promise<WebAuthnGetResult> {\n const publicKey: PublicKeyCredentialRequestOptions = {\n rpId: options.rpId,\n challenge: options.challenge ? new Uint8Array(options.challenge) : randomBytes(32),\n allowCredentials: (options.allowCredentials ?? []).map((id) => ({\n type: 'public-key',\n id: base64UrlToBytes(id),\n })),\n userVerification: options.userVerification,\n };\n const request: CredentialRequestOptions = { publicKey };\n if (options.mediation) request.mediation = options.mediation;\n let credential: PublicKeyCredential | null;\n try {\n credential = (await credentials.get(request)) as PublicKeyCredential | null;\n } catch (error) {\n throw asKitError(error);\n }\n if (!credential) throw new KitError('USER_CANCELLED', 'assertion returned null');\n const response = credential.response as AuthenticatorAssertionResponse;\n return {\n id: credential.id,\n rawId: new Uint8Array(credential.rawId),\n authenticatorData: new Uint8Array(response.authenticatorData),\n clientDataJSON: new Uint8Array(response.clientDataJSON),\n signature: new Uint8Array(response.signature),\n };\n },\n };\n}\n\n/** localStorage-backed credential store, with an in-memory fallback (Node/SSR). */\nexport function defaultCredentialStorage(): CredentialStorage {\n const key = (rpId: string): string => `stellar-passkey:${rpId}`;\n const ls = (globalThis as { localStorage?: Storage }).localStorage;\n if (ls) {\n return {\n get: (rpId) => ls.getItem(key(rpId)),\n set: (rpId, credentialId) => {\n ls.setItem(key(rpId), credentialId);\n },\n };\n }\n const memory = new Map<string, string>();\n return {\n get: (rpId) => memory.get(rpId) ?? null,\n set: (rpId, credentialId) => {\n memory.set(rpId, credentialId);\n },\n };\n}\n","import { base64UrlToBytes } from '../internal/encoding';\nimport type { AssertionResult, WebAuthnSigner } from '../soroban/sign';\nimport { browserWebAuthnClient } from './browserClient';\nimport type { WebAuthnClient } from './types';\n\nexport interface BrowserPasskeySignerOptions {\n /** The Relying Party ID (your site's registrable domain). */\n rpId: string;\n /**\n * Restrict the prompt to specific credential ids (base64url) — pass the\n * `credentialId` from `create` / `connect` so the OS offers the right passkey.\n * Omit (or leave empty) for a discoverable prompt over any resident passkey.\n */\n allowCredentials?: string[];\n userVerification?: 'discouraged' | 'preferred' | 'required';\n /** Inject a custom client (tests / non-browser). Defaults to `browserWebAuthnClient()`. */\n webauthn?: WebAuthnClient;\n}\n\n/**\n * Adapt `navigator.credentials.get` into the `WebAuthnSigner` that\n * `signTransaction` / `signAuthEntry` expect — so wiring a passkey is one line:\n *\n * ```ts\n * const sign = browserPasskeySigner({ rpId, allowCredentials: [credentialId] });\n * const signedXdr = await signTransaction(txXdr, { networkPassphrase, sign });\n * ```\n *\n * The SDK hands the signer a base64url challenge (the Soroban auth preimage);\n * this decodes it to the raw bytes WebAuthn signs over, runs the assertion, and\n * returns the fields the auth assembler needs. The DER signature is low-S\n * normalized downstream (invariant #2) — nothing here weakens that.\n */\nexport function browserPasskeySigner(options: BrowserPasskeySignerOptions): WebAuthnSigner {\n const webauthn = options.webauthn ?? browserWebAuthnClient();\n return async (challenge: string): Promise<AssertionResult> => {\n const assertion = await webauthn.get({\n rpId: options.rpId,\n challenge: base64UrlToBytes(challenge),\n allowCredentials: options.allowCredentials ?? [],\n userVerification: options.userVerification ?? 'preferred',\n });\n return {\n authenticatorData: assertion.authenticatorData,\n clientDataJSON: assertion.clientDataJSON,\n signature: assertion.signature,\n credentialId: assertion.rawId,\n };\n };\n}\n","import { xdr, hash } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { bytesToBase64Url, utf8ToBytes } from '../internal/encoding';\n\n/**\n * Compute the auth-entry preimage hash that `__check_auth` reconstructs and that\n * becomes the WebAuthn `challenge`:\n * SHA256( XDR( HashIdPreimage::SorobanAuthorization{ networkId, nonce,\n * signatureExpirationLedger, invocation } ) )\n * where networkId = SHA256(networkPassphrase).\n */\nexport function authEntryChallengeBytes(\n entry: xdr.SorobanAuthorizationEntry,\n networkPassphrase: string,\n): Uint8Array {\n const credentials = entry.credentials();\n if (credentials.switch().name !== 'sorobanCredentialsAddress') {\n throw new KitError('CONTRACT_AUTH_FAILED', 'auth entry has no address credentials to sign');\n }\n const address = credentials.address();\n const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId: Buffer.from(hash(Buffer.from(utf8ToBytes(networkPassphrase)))),\n nonce: address.nonce(),\n signatureExpirationLedger: address.signatureExpirationLedger(),\n invocation: entry.rootInvocation(),\n }),\n );\n return new Uint8Array(hash(preimage.toXDR()));\n}\n\n/** The base64url challenge string the authenticator signs (43 chars). */\nexport function authEntryChallenge(\n entry: xdr.SorobanAuthorizationEntry,\n networkPassphrase: string,\n): string {\n return bytesToBase64Url(authEntryChallengeBytes(entry, networkPassphrase));\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport type { AssertionResult } from './sign';\n\n/**\n * Set an address-credential auth entry's signature to the `Secp256r1Signature`\n * struct the on-chain `__check_auth` consumes:\n *\n * ScVal::Map { authenticator_data: Bytes, client_data_json: Bytes, signature: BytesN<64> }\n *\n * Map keys are alphabetical, so the ScMap is canonically sorted as Soroban\n * requires. `signature` MUST already be 64-byte low-S compact (`signAuthEntry`\n * normalizes before calling this). This is the exact shape the audited\n * webauthn-verifier reference expects — proven on testnet by the on-chain\n * integration test (scripts/onchain-e2e.ts).\n */\nexport function applyAssertionToEntry(\n entry: xdr.SorobanAuthorizationEntry,\n assertion: AssertionResult,\n): xdr.SorobanAuthorizationEntry {\n entry.credentials().address().signature(buildSignatureScVal(assertion));\n return entry;\n}\n\n/** The `Secp256r1Signature` ScVal — a contracttype struct → sorted ScMap. */\nexport function buildSignatureScVal(assertion: AssertionResult): xdr.ScVal {\n return xdr.ScVal.scvMap([\n bytesField('authenticator_data', assertion.authenticatorData),\n bytesField('client_data_json', assertion.clientDataJSON),\n bytesField('signature', assertion.signature),\n ]);\n}\n\nfunction bytesField(name: string, bytes: Uint8Array): xdr.ScMapEntry {\n return new xdr.ScMapEntry({\n key: xdr.ScVal.scvSymbol(name),\n val: xdr.ScVal.scvBytes(Buffer.from(bytes)),\n });\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { buildSignatureScVal } from './assemble';\nimport type { AssertionResult } from './sign';\n\n/**\n * The passkey-kit / `webauthn-wallet` smart-wallet ABI target.\n *\n * Our own single-signer account declares `type Signature = Secp256r1Signature`\n * and consumes the bare struct (see `assemble.ts`). passkey-kit's smart-wallet\n * declares `type Signature = Signatures`, so authorizing it needs the assertion\n * wrapped as `Signatures(Map<SignerKey, Signature>)`. The exact shape, the raw-\n * credential-id key, and the canonical map ordering below are confirmed by\n * kalepail (passkey-kit author) in issue #32 against v1 / v0.13.0 (Protocol 27,\n * independently audited); the wire shape is unchanged from v0.12.\n */\n\n/**\n * `SignerKey::Secp256r1(Bytes)` → `scvVec([Symbol(\"Secp256r1\"), Bytes(rawId)])`.\n * The key is the RAW WebAuthn credential-id bytes (base64url-decoded `rawId`):\n * never hashed, never the UTF-8 of the base64url string, and never the public\n * key — the SEC-1 public key lives in `SignerVal` on-chain, not in the key.\n */\nexport function buildSignerKeyScVal(credentialId: Uint8Array): xdr.ScVal {\n return xdr.ScVal.scvVec([\n xdr.ScVal.scvSymbol('Secp256r1'),\n xdr.ScVal.scvBytes(Buffer.from(credentialId)),\n ]);\n}\n\n/** `Signature::Secp256r1(Secp256r1Signature)` → `scvVec([Symbol(\"Secp256r1\"), <bare struct map>])`. */\nexport function buildSmartWalletSignatureVariant(assertion: AssertionResult): xdr.ScVal {\n return xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Secp256r1'), buildSignatureScVal(assertion)]);\n}\n\nfunction decomposeSignerKey(key: xdr.ScVal): { variant: string; payload: Uint8Array } {\n const vec = key.vec();\n if (!vec || vec.length < 2) {\n throw new KitError('CONTRACT_AUTH_FAILED', 'malformed SignerKey (expected an enum vec)');\n }\n const variant = vec[0]!.sym().toString();\n const el = vec[1]!;\n // Secp256r1(Bytes) and Ed25519(BytesN<32>) are scvBytes; Policy(Address) falls\n // back to its XDR bytes (rare in a passkey SDK — see the ordering note below).\n const payload =\n el.switch().name === 'scvBytes' ? new Uint8Array(el.bytes()) : new Uint8Array(el.toXDR());\n return { variant, payload };\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n if (a[i] !== b[i]) return a[i]! < b[i]! ? -1 : 1;\n }\n return a.length - b.length;\n}\n\n/**\n * Canonical Soroban-host ordering for `SignerKey` map keys. The host requires\n * `Map<SignerKey, _>` entries sorted by ScVal `Ord` — an **element-wise byte\n * comparison**, NOT a length-major XDR-hex / `localeCompare` string sort. This is\n * the one correctness landmine kalepail flagged in #32: passkey-kit v1 replaced\n * its old string sort with exactly this because the old approach could mis-order\n * same-variant keys of differing length, producing a map the host rejects.\n *\n * We compare the enum variant symbol first, then the payload bytes element-wise,\n * so homogeneous `Secp256r1` keys (the multi-passkey case) sort purely by their\n * raw credential-id bytes. (Ordering across mixed variant types relies on the\n * variant names being capitalized single words, which matches the host's symbol\n * order; a Policy/Address-keyed multi-sig is out of scope for this passkey SDK.)\n */\nexport function compareSignerKeyScVal(a: xdr.ScVal, b: xdr.ScVal): number {\n const ka = decomposeSignerKey(a);\n const kb = decomposeSignerKey(b);\n if (ka.variant !== kb.variant) return ka.variant < kb.variant ? -1 : 1;\n return compareBytes(ka.payload, kb.payload);\n}\n\n/**\n * Assemble/merge a passkey assertion into an address-credential auth entry as the\n * smart-wallet `Signatures(Map<SignerKey, Signature>)` wire shape\n * (`ScVal::Vec([ScVal::Map(...)])`). `assertion.signature` MUST already be 64-byte\n * low-S compact (`signAuthEntry` normalizes first). Existing map entries — a\n * partially-signed multi-sig entry — are preserved; an entry for the same signer\n * key is replaced; then the whole map is canonically sorted.\n *\n * Use this for the passkey-kit / webauthn-wallet ABI. For our own single-signer\n * account (`type Signature = Secp256r1Signature`) use `applyAssertionToEntry`.\n */\nexport function applyAssertionToSmartWalletEntry(\n entry: xdr.SorobanAuthorizationEntry,\n assertion: AssertionResult,\n): xdr.SorobanAuthorizationEntry {\n const credentials = entry.credentials();\n if (credentials.switch().name !== 'sorobanCredentialsAddress') {\n throw new KitError('CONTRACT_AUTH_FAILED', 'auth entry has no address credentials to sign');\n }\n const key = buildSignerKeyScVal(assertion.credentialId);\n const newEntry = new xdr.ScMapEntry({ key, val: buildSmartWalletSignatureVariant(assertion) });\n\n const current = credentials.address().signature();\n let mapEntries: xdr.ScMapEntry[];\n switch (current.switch().name) {\n case 'scvVoid':\n mapEntries = [newEntry];\n break;\n case 'scvVec': {\n // Preserve any existing signatures (partial multi-sig); replace same key.\n const existing = current.vec()?.[0]?.map() ?? [];\n mapEntries = existing.filter((e) => compareSignerKeyScVal(e.key(), key) !== 0);\n mapEntries.push(newEntry);\n break;\n }\n default:\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'unexpected existing signature shape for a smart-wallet entry',\n );\n }\n mapEntries.sort((a, b) => compareSignerKeyScVal(a.key(), b.key()));\n credentials.address().signature(xdr.ScVal.scvVec([xdr.ScVal.scvMap(mapEntries)]));\n return entry;\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { derToCompactLowS } from '../webauthn/signature';\nimport { parseClientDataJSON, verifyClientDataJSON, type ClientData } from '../webauthn/clientData';\nimport { parseAuthenticatorData, verifyRpIdHash } from '../webauthn/authData';\nimport { verifyAssertionSignature } from '../webauthn/verify';\nimport { authEntryChallenge } from './preimage';\nimport { applyAssertionToEntry } from './assemble';\nimport { applyAssertionToSmartWalletEntry } from './smartWallet';\n\n/**\n * Which contract ABI the assembled signature targets:\n * - `single-signer` (default): the bare `Secp256r1Signature` struct our own\n * webauthn-account consumes (`type Signature = Secp256r1Signature`).\n * - `smart-wallet`: passkey-kit's `Signatures(Map<SignerKey, Signature>)`\n * (`type Signature = Signatures`) — see `smartWallet.ts` / kalepail #32.\n * Both reuse the identical low-S, field-packing, and challenge-binding core;\n * only the outer wrapper differs, so the two stay separate ABI targets behind\n * one signing interface.\n */\nexport type WalletTarget = 'single-signer' | 'smart-wallet';\n\n/** The raw WebAuthn assertion a signer returns for a given challenge. */\nexport interface AssertionResult {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n /** DER-encoded (≤72B) or already-compact (64B) ECDSA signature. */\n signature: Uint8Array;\n /** base64url credential id → the SignerKey. */\n credentialId: Uint8Array;\n}\n\n/** Produce a WebAuthn assertion over the base64url `challenge` (e.g. navigator.credentials.get). */\nexport type WebAuthnSigner = (challenge: string) => Promise<AssertionResult> | AssertionResult;\n\n/**\n * Opt-in pre-flight validation of the returned assertion, run BEFORE the entry\n * is assembled and submitted. On-chain `__check_auth` is the real gate, but\n * catching these client-side turns an opaque on-chain failure into a typed\n * `KitError` at the call site. Providing this object always enforces the\n * `webauthn.get` type, the User-Present (UP) flag (required by passkey-kit v1),\n * and challenge-binding; `rpId` / `origin` / `publicKey` add their checks when\n * supplied. Omit the object entirely to skip pre-flight (the default).\n */\nexport interface SignVerifyOptions {\n /** Verify `authenticatorData.rpIdHash === SHA-256(rpId)`. */\n rpId?: string;\n /** Verify `clientDataJSON.origin` is one of these exact origins. */\n origin?: string | string[];\n /** SEC-1 (65-byte) public key → verify the ECDSA assertion signature. */\n publicKey?: Uint8Array;\n /** Also require the User-Verified (UV) flag (biometric / PIN). Default false. */\n requireUserVerification?: boolean;\n /** Allow an assertion made in a cross-origin context (crossOrigin=true). Default false. */\n allowCrossOrigin?: boolean;\n}\n\nexport interface SorobanSignOptions {\n networkPassphrase: string;\n sign: WebAuthnSigner;\n /** Contract ABI to assemble for. Defaults to `single-signer` (our account). */\n target?: WalletTarget;\n /** Opt-in pre-flight assertion validation. Omit to skip. */\n verify?: SignVerifyOptions;\n /**\n * Stamp this `signatureExpirationLedger` onto every address-credential auth\n * entry BEFORE the challenge is computed, so the signature binds the exact\n * expiration the contract re-derives in `__check_auth`. Needed for smart-wallet\n * writes (add/remove signer) where the caller learns the ledger at sign time;\n * omit when the entry already carries the intended expiration.\n */\n signatureExpirationLedger?: number;\n}\n\n/** Validate an assertion against the expected challenge + RP context. Throws KitError. */\nfunction preflightAssertion(\n assertion: AssertionResult,\n challenge: string,\n verify: SignVerifyOptions,\n): void {\n // Ceremony type + challenge-binding (+ origin when provided).\n let clientData: ClientData;\n if (verify.origin !== undefined) {\n clientData = verifyClientDataJSON(assertion.clientDataJSON, {\n origin: verify.origin,\n challenge,\n });\n } else {\n clientData = parseClientDataJSON(assertion.clientDataJSON);\n if (clientData.type !== 'webauthn.get') {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n `clientDataJSON.type \"${clientData.type}\" is not \"webauthn.get\"`,\n );\n }\n if (clientData.challenge !== challenge) {\n throw new KitError('CHALLENGE_MISMATCH', 'assertion challenge does not match the auth entry');\n }\n }\n if (clientData.crossOrigin === true && !verify.allowCrossOrigin) {\n throw new KitError(\n 'ORIGIN_MISMATCH',\n 'assertion was made in a cross-origin context (crossOrigin=true)',\n );\n }\n // User-Present is mandatory (passkey-kit v1 hardening); UV is opt-in.\n const parsed = parseAuthenticatorData(assertion.authenticatorData);\n if (!parsed.flags.up) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'assertion is missing the User-Present (UP) flag',\n );\n }\n if (verify.requireUserVerification && !parsed.flags.uv) {\n throw new KitError(\n 'UNSUPPORTED_AUTHENTICATOR',\n 'assertion is missing the required User-Verified (UV) flag',\n );\n }\n if (verify.rpId !== undefined) {\n verifyRpIdHash(assertion.authenticatorData, verify.rpId);\n }\n if (verify.publicKey !== undefined) {\n const ok = verifyAssertionSignature({\n publicKey: verify.publicKey,\n authenticatorData: assertion.authenticatorData,\n clientDataJSON: assertion.clientDataJSON,\n signature: assertion.signature,\n });\n if (!ok) {\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'assertion signature failed pre-flight verification',\n );\n }\n }\n}\n\nasync function signEntryInPlace(\n entry: xdr.SorobanAuthorizationEntry,\n options: SorobanSignOptions,\n): Promise<void> {\n // Stamp the expiration first: the challenge preimage includes\n // signatureExpirationLedger, so it must be final before we compute it.\n if (options.signatureExpirationLedger !== undefined) {\n const creds = entry.credentials();\n if (creds.switch().name === 'sorobanCredentialsAddress') {\n creds.address().signatureExpirationLedger(options.signatureExpirationLedger);\n }\n }\n const challenge = authEntryChallenge(entry, options.networkPassphrase);\n const assertion = await options.sign(challenge);\n if (options.verify) preflightAssertion(assertion, challenge, options.verify);\n const signature =\n assertion.signature.length === 64 ? assertion.signature : derToCompactLowS(assertion.signature);\n const normalized = {\n credentialId: assertion.credentialId,\n authenticatorData: assertion.authenticatorData,\n clientDataJSON: assertion.clientDataJSON,\n signature,\n };\n if (options.target === 'smart-wallet') {\n applyAssertionToSmartWalletEntry(entry, normalized);\n } else {\n applyAssertionToEntry(entry, normalized);\n }\n}\n\n/**\n * Sign a single `SorobanAuthorizationEntry` (base64 XDR): compute the challenge,\n * obtain a WebAuthn assertion, low-S-normalize, and assemble the contract\n * signature. Returns the signed entry as base64 XDR.\n */\nexport async function signAuthEntry(\n entryXdr: string,\n options: SorobanSignOptions,\n): Promise<string> {\n const entry = xdr.SorobanAuthorizationEntry.fromXDR(entryXdr, 'base64');\n await signEntryInPlace(entry, options);\n return entry.toXDR('base64');\n}\n\n/**\n * The operations whose Soroban auth entries we sign, for a v1 or a fee-bump\n * envelope. (Sign the Soroban auth entries before adding classic tx signatures\n * or fee-bumping; a fee-bump around an already-classic-signed inner tx is the\n * caller's sequencing concern.)\n */\nfunction operationsForSigning(envelope: xdr.TransactionEnvelope): xdr.Operation[] {\n const kind = envelope.switch().name;\n if (kind === 'envelopeTypeTx') return envelope.v1().tx().operations();\n if (kind === 'envelopeTypeTxFeeBump') {\n const inner = envelope.feeBump().tx().innerTx();\n if (inner.switch().name !== 'envelopeTypeTx') {\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'signTransaction: fee-bump inner transaction is not a v1 transaction',\n );\n }\n return inner.v1().tx().operations();\n }\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n `signTransaction: unsupported envelope type \"${kind}\" (expected v1 or fee-bump)`,\n );\n}\n\n/**\n * Sign every address-credential Soroban auth entry carried by the InvokeHostFunction\n * operations of a transaction (base64 XDR envelope — v1 or fee-bump). Returns the\n * signed envelope XDR.\n */\nexport async function signTransaction(txXdr: string, options: SorobanSignOptions): Promise<string> {\n const envelope = xdr.TransactionEnvelope.fromXDR(txXdr, 'base64');\n for (const op of operationsForSigning(envelope)) {\n if (op.body().switch().name !== 'invokeHostFunction') continue;\n const entries = op.body().invokeHostFunctionOp().auth();\n for (const entry of entries) {\n if (entry.credentials().switch().name !== 'sorobanCredentialsAddress') continue;\n await signEntryInPlace(entry, options);\n }\n }\n return envelope.toXDR('base64');\n}\n","import { Contract, nativeToScVal, xdr } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { buildSignerKeyScVal } from './smartWallet';\n\n/**\n * passkey-kit v1 (v0.13.0, Protocol 27) smart-wallet SIGNER encoders — the WRITE\n * path (what `add_signer` / `remove_signer` consume), complementing\n * `smartWallet.ts` (the signature READ path the wallet's `__check_auth` reads).\n *\n * A signer is added on-chain as\n *\n * Signer::Secp256r1(Bytes id, BytesN<65> public_key,\n * SignerExpiration, SignerLimits, SignerStorage)\n *\n * which `process_signer` reduces to `SignerKey::Secp256r1(id) ->\n * SignerVal::Secp256r1(public_key, ..)`: the raw credential id is the key, the\n * SEC-1 public key lives in the value. Shape + field order confirmed by kalepail\n * (passkey-kit author) in issue #32 and proven on testnet against the audited v1\n * wasm (`scripts/smartwallet-v1-e2e.ts`).\n *\n * v1 note: `SignerExpiration` is a UNIX-seconds `u64` timestamp (Protocol 27),\n * NOT a ledger sequence as in the pre-v1 kit.\n */\n\n/** `SignerStorage` — where the contract persists the signer entry. */\nexport type SignerStorage = 'Persistent' | 'Temporary';\n\nexport interface Secp256r1SignerSpec {\n /** Raw WebAuthn credential-id bytes (base64url-decoded `rawId`) — becomes the SignerKey. */\n credentialId: Uint8Array;\n /** SEC-1 uncompressed public key (65 bytes, `0x04 ‖ X ‖ Y`) — stored in SignerVal. */\n publicKey: Uint8Array;\n /**\n * `SignerExpiration` — a UNIX-seconds timestamp (v1 / Protocol 27) after which\n * the signer stops being valid. Omit for `None` (a non-expiring signer, the\n * usual choice for a recovery / second device).\n */\n expiration?: number | bigint;\n /** `SignerStorage` — defaults to `Persistent`. */\n storage?: SignerStorage;\n}\n\n/** A tuple-struct `Option` field set to `None` → `scvVec([Void])`. */\nfunction noneTuple(): xdr.ScVal {\n return xdr.ScVal.scvVec([xdr.ScVal.scvVoid()]);\n}\n\n/** `SignerExpiration(Option<u64>)` — `None` or `Some(unixSeconds)`. */\nfunction expirationScVal(expiration?: number | bigint): xdr.ScVal {\n if (expiration === undefined) return noneTuple();\n const ts = BigInt(expiration);\n if (ts < 0n) {\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n 'signer expiration must be a non-negative UNIX-seconds timestamp (v1)',\n );\n }\n return xdr.ScVal.scvVec([nativeToScVal(ts, { type: 'u64' })]);\n}\n\n/** `SignerStorage::Persistent | Temporary` → `scvVec([Symbol(variant)])`. */\nfunction storageScVal(storage: SignerStorage = 'Persistent'): xdr.ScVal {\n return xdr.ScVal.scvVec([xdr.ScVal.scvSymbol(storage)]);\n}\n\n/**\n * Encode a `Signer::Secp256r1(..)` for `add_signer`. `SignerLimits` is always\n * `None` (unrestricted) — policy/limited signers are out of scope for this\n * minimal passkey SDK. Validates the credential id and the SEC-1 public key so a\n * malformed signer can never be handed to the contract.\n */\nexport function buildSecp256r1Signer(spec: Secp256r1SignerSpec): xdr.ScVal {\n if (spec.credentialId.length === 0) {\n throw new KitError('CONTRACT_AUTH_FAILED', 'buildSecp256r1Signer: empty credential id');\n }\n if (spec.publicKey.length !== 65 || spec.publicKey[0] !== 0x04) {\n throw new KitError(\n 'INVALID_PUBLIC_KEY',\n 'buildSecp256r1Signer: publicKey must be a 65-byte SEC-1 uncompressed point (0x04-prefixed)',\n );\n }\n return xdr.ScVal.scvVec([\n xdr.ScVal.scvSymbol('Secp256r1'),\n xdr.ScVal.scvBytes(Buffer.from(spec.credentialId)),\n xdr.ScVal.scvBytes(Buffer.from(spec.publicKey)),\n expirationScVal(spec.expiration), // SignerExpiration\n noneTuple(), // SignerLimits(None)\n storageScVal(spec.storage), // SignerStorage\n ]);\n}\n\nfunction contractCall(contractId: string, method: string, ...args: xdr.ScVal[]): xdr.Operation {\n let contract: Contract;\n try {\n contract = new Contract(contractId);\n } catch (cause) {\n throw new KitError('CONTRACT_AUTH_FAILED', `invalid smart-wallet contract id \"${contractId}\"`, {\n cause,\n });\n }\n return contract.call(method, ...args);\n}\n\nexport interface BuildAddSignerOptions {\n /** The smart-wallet C-address the signer is being added to. */\n walletContractId: string;\n /** The signer to add — a `Secp256r1SignerSpec`, or a pre-built `Signer` ScVal. */\n signer: Secp256r1SignerSpec | xdr.ScVal;\n}\n\n/**\n * Build the `wallet.add_signer(signer)` invocation. The resulting invoke-host\n * operation requires the wallet's OWN auth: an EXISTING signer authorizes adding\n * the new one, which is what keeps a lost device from locking the user out.\n * Sign the produced transaction's auth entry with\n * `signTransaction(.., { target: 'smart-wallet' })`.\n */\nexport function buildAddSignerOperation(options: BuildAddSignerOptions): xdr.Operation {\n const signerScVal =\n options.signer instanceof xdr.ScVal ? options.signer : buildSecp256r1Signer(options.signer);\n return contractCall(options.walletContractId, 'add_signer', signerScVal);\n}\n\nexport interface BuildRemoveSignerOptions {\n walletContractId: string;\n /** Raw credential-id bytes of the signer to remove (its `SignerKey`). */\n credentialId: Uint8Array;\n}\n\n/** Build the `wallet.remove_signer(SignerKey::Secp256r1(id))` invocation (wallet-authorized). */\nexport function buildRemoveSignerOperation(options: BuildRemoveSignerOptions): xdr.Operation {\n if (options.credentialId.length === 0) {\n throw new KitError('CONTRACT_AUTH_FAILED', 'buildRemoveSignerOperation: empty credential id');\n }\n return contractCall(\n options.walletContractId,\n 'remove_signer',\n buildSignerKeyScVal(options.credentialId),\n );\n}\n","import { xdr } from '@stellar/stellar-sdk';\nimport { p256 } from '@noble/curves/nist';\nimport { sha256 } from '../internal/sha256';\nimport { concatBytes } from '../internal/bytes';\nimport { bytesToBase64Url, bytesToUtf8 } from '../internal/encoding';\nimport { authEntryChallengeBytes } from './preimage';\n\nexport interface CheckAuthResult {\n success: boolean;\n /** clientDataJSON.challenge === base64url(preimage hash). */\n challengeBound: boolean;\n /** secp256r1_verify over SHA256(authData ‖ SHA256(cdj)) passed. */\n signatureValid: boolean;\n reason?: string;\n}\n\nfunction fail(reason: string): CheckAuthResult {\n return { success: false, challengeBound: false, signatureValid: false, reason };\n}\n\n/**\n * Verify a bare `Secp256r1Signature` ScMap ({ authenticator_data,\n * client_data_json, signature }) against a public key + the expected signature\n * payload. Shared by the single-signer and smart-wallet reference verifiers.\n */\nfunction verifySecp256r1StructMap(\n structMap: xdr.ScMapEntry[],\n publicKey: Uint8Array,\n signaturePayload: Uint8Array,\n): { ok: boolean; challengeBound: boolean; signatureValid: boolean; reason?: string } {\n const field = (name: string): Uint8Array | undefined => {\n const e = structMap.find((x) => x.key().sym().toString() === name);\n return e ? new Uint8Array(e.val().bytes()) : undefined;\n };\n const authenticatorData = field('authenticator_data');\n const clientDataJSON = field('client_data_json');\n const signature = field('signature');\n if (!authenticatorData || !clientDataJSON || !signature) {\n return { ok: false, challengeBound: false, signatureValid: false, reason: 'missing fields' };\n }\n if (signature.length !== 64) {\n return {\n ok: false,\n challengeBound: false,\n signatureValid: false,\n reason: 'not 64-byte compact',\n };\n }\n let challengeBound = false;\n try {\n const cdj = JSON.parse(bytesToUtf8(clientDataJSON)) as { challenge?: string };\n challengeBound = cdj.challenge === bytesToBase64Url(signaturePayload);\n } catch {\n challengeBound = false;\n }\n // Host fn semantics: no low-S enforcement (lowS:false), compact format.\n const digest = sha256(concatBytes(authenticatorData, sha256(clientDataJSON)));\n const signatureValid = p256.verify(signature, digest, publicKey, {\n lowS: false,\n format: 'compact',\n });\n return { ok: challengeBound && signatureValid, challengeBound, signatureValid };\n}\n\n/**\n * A faithful JavaScript model of the on-chain `__check_auth` (kalepail\n * `webauthn-wallet` `verify.rs`): reconstruct `SHA256(authenticator_data ‖\n * SHA256(client_data_json))`, run `secp256r1_verify` (which does NOT enforce\n * low-S — hence the client-side normalization), and assert challenge-binding\n * (`clientDataJSON.challenge === base64url(signature_payload)`). Lets us prove\n * the assembly without a live Soroban RPC; the real on-chain run is exercised\n * by the kit integration (S17) and the demo (S21).\n */\nexport function referenceCheckAuth(\n entry: xdr.SorobanAuthorizationEntry,\n publicKey: Uint8Array,\n networkPassphrase: string,\n): CheckAuthResult {\n if (entry.credentials().switch().name !== 'sorobanCredentialsAddress') {\n return fail('no address credentials');\n }\n // The signature is the Secp256r1Signature struct directly: a sorted ScMap\n // { authenticator_data, client_data_json, signature } (see assemble.ts).\n const structMap = entry.credentials().address().signature().map();\n if (!structMap) return fail('signature is not a Secp256r1Signature map');\n\n const signaturePayload = authEntryChallengeBytes(entry, networkPassphrase);\n const r = verifySecp256r1StructMap(structMap, publicKey, signaturePayload);\n return { success: r.ok, challengeBound: r.challengeBound, signatureValid: r.signatureValid };\n}\n\nexport interface SmartWalletCheckAuthResult {\n success: boolean;\n signers: { credentialId: string; challengeBound: boolean; signatureValid: boolean }[];\n reason?: string;\n}\n\n/**\n * A reference model of passkey-kit's smart-wallet `__check_auth`: unwrap the\n * `Signatures(Map<SignerKey, Signature>)` value (`ScVal::Vec([ScVal::Map(...)])`),\n * and for each `SignerKey::Secp256r1(id) => Signature::Secp256r1(struct)` entry,\n * look up that credential id's SEC-1 public key and verify the struct. Succeeds\n * only when the map is non-empty and every signer verifies + is challenge-bound.\n * `publicKeyFor` receives the lowercase-hex credential id.\n */\nexport function referenceSmartWalletCheckAuth(\n entry: xdr.SorobanAuthorizationEntry,\n publicKeyFor: (credentialIdHex: string) => Uint8Array | undefined,\n networkPassphrase: string,\n): SmartWalletCheckAuthResult {\n if (entry.credentials().switch().name !== 'sorobanCredentialsAddress') {\n return { success: false, signers: [], reason: 'no address credentials' };\n }\n const sig = entry.credentials().address().signature();\n const map = sig.switch().name === 'scvVec' ? sig.vec()?.[0]?.map() : undefined;\n if (!map) {\n return { success: false, signers: [], reason: 'signature is not a Signatures(Map) vec' };\n }\n if (map.length === 0) return { success: false, signers: [], reason: 'empty signatures map' };\n\n const signaturePayload = authEntryChallengeBytes(entry, networkPassphrase);\n const signers: SmartWalletCheckAuthResult['signers'] = [];\n let allOk = true;\n\n for (const e of map) {\n const keyVec = e.key().vec();\n const idBytes = keyVec?.[1]?.bytes();\n const credentialId = idBytes ? Buffer.from(idBytes).toString('hex') : '';\n // Signature::Secp256r1(struct) → scvVec([Symbol, structMap]).\n const structMap = e.val().vec()?.[1]?.map();\n const publicKey = publicKeyFor(credentialId);\n if (!structMap || !publicKey) {\n allOk = false;\n signers.push({ credentialId, challengeBound: false, signatureValid: false });\n continue;\n }\n const r = verifySecp256r1StructMap(structMap, publicKey, signaturePayload);\n if (!r.ok) allOk = false;\n signers.push({\n credentialId,\n challengeBound: r.challengeBound,\n signatureValid: r.signatureValid,\n });\n }\n return { success: allOk, signers };\n}\n","import { rpc, TransactionBuilder } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport type { SubmissionAdapter, SubmitResult } from './types';\n\nexport interface DirectSubmissionOptions {\n rpcUrl: string;\n networkPassphrase: string;\n allowHttp?: boolean;\n /** Max confirmation-poll attempts before failing with NETWORK_ERROR (default 30). */\n pollAttempts?: number;\n /** Delay between confirmation polls, in ms (default 1000). */\n pollIntervalMs?: number;\n}\n\n/**\n * Default, zero-infra submission: send straight to soroban-rpc and poll. No\n * relayer, no API key. Swappable with `launchtube`/`openzeppelinRelayer` with\n * zero ceremony changes (same `SubmissionAdapter` shape).\n */\nexport function directSubmission(options: DirectSubmissionOptions): SubmissionAdapter {\n const server = new rpc.Server(options.rpcUrl, {\n allowHttp: options.allowHttp ?? options.rpcUrl.startsWith('http://'),\n });\n const attempts = options.pollAttempts ?? 30;\n const intervalMs = options.pollIntervalMs ?? 1000;\n return {\n async send(signedTxXdr: string): Promise<SubmitResult> {\n const tx = TransactionBuilder.fromXDR(signedTxXdr, options.networkPassphrase);\n let sent;\n try {\n sent = await server.sendTransaction(tx);\n } catch (cause) {\n throw new KitError('NETWORK_ERROR', 'failed to submit transaction to soroban-rpc', {\n cause,\n });\n }\n if (sent.status === 'ERROR') {\n return {\n status: 'FAILED',\n hash: sent.hash,\n errorResultXdr: sent.errorResult?.toXDR('base64'),\n };\n }\n // Bounded polling: give up (NETWORK_ERROR) instead of hanging forever.\n let final;\n try {\n final = await server.pollTransaction(sent.hash, {\n attempts,\n sleepStrategy: () => intervalMs,\n });\n } catch (cause) {\n throw new KitError(\n 'NETWORK_ERROR',\n `transaction ${sent.hash} was not confirmed after ${String(attempts)} polls`,\n { cause },\n );\n }\n if (final.status === rpc.Api.GetTransactionStatus.NOT_FOUND) {\n throw new KitError(\n 'NETWORK_ERROR',\n `transaction ${sent.hash} still NOT_FOUND after ${String(attempts)} polls`,\n );\n }\n const success = final.status === rpc.Api.GetTransactionStatus.SUCCESS;\n return {\n status: success ? 'SUCCESS' : 'FAILED',\n hash: sent.hash,\n returnValue: success ? (final as { returnValue?: unknown }).returnValue : undefined,\n };\n },\n };\n}\n","import { Keypair, TransactionBuilder, rpc, xdr } from '@stellar/stellar-sdk';\nimport { KitError } from '../errors';\nimport { directSubmission } from '../adapters/direct';\nimport type { SubmissionAdapter, SubmitResult } from '../adapters/types';\nimport { signTransaction, type SignVerifyOptions, type WebAuthnSigner } from './sign';\n\nexport interface SendSmartWalletTxOptions {\n /** The single wallet-authorized invocation to run (SAC transfer, contract call, add_signer, …). */\n operation: xdr.Operation;\n networkPassphrase: string;\n rpcUrl: string;\n /**\n * Secret of the funded classic account that pays the fee + sequences the tx. The\n * passkey provides the wallet's AUTH; this only sponsors the envelope\n * (ephemeral/friendbot-funded in a demo; a relayer key otherwise).\n */\n sourceSecret: string;\n /** The wallet's passkey signer that authorizes the invocation. */\n sign: WebAuthnSigner;\n /** Where the signed tx is submitted. Defaults to `direct` (soroban-rpc). */\n submission?: SubmissionAdapter;\n /** Opt-in pre-flight validation of the authorizing assertion. */\n verify?: SignVerifyOptions;\n fee?: string;\n timeoutSeconds?: number;\n /** Ledgers ahead of `latestLedger` to expire the auth signature at (default 60). */\n signatureExpirationLedgerOffset?: number;\n allowHttp?: boolean;\n}\n\nconst DEFAULT_EXPIRATION_OFFSET = 60;\n\n/**\n * Sign and submit a single passkey-authorized smart-wallet transaction — the\n * general primitive behind every smart-wallet action (payment, contract call,\n * add/remove signer). The full dance:\n *\n * 1. recording sim → assemble (discovers the wallet's auth requirement);\n * 2. sign the wallet auth entry with the passkey (smart-wallet Signatures map),\n * binding the expiration ledger the contract re-derives;\n * 3. enforcing re-sim of the SIGNED tx — recording auth never runs the custom\n * account's `__check_auth`, so it misses the signer-storage reads and\n * under-counts instructions; the enforcing pass yields the true footprint +\n * resources, and doubles as a client-side proof the auth is accepted;\n * 4. pay the fee from the classic source and submit via the pluggable adapter.\n *\n * tx.fee + sorobanData are outside the auth preimage, so re-assembling with the\n * enforcing resources never invalidates the signature. Throws a typed KitError on\n * any simulation/validation failure.\n */\nexport async function sendSmartWalletTx(options: SendSmartWalletTxOptions): Promise<SubmitResult> {\n const server = new rpc.Server(options.rpcUrl, {\n allowHttp: options.allowHttp ?? options.rpcUrl.startsWith('http://'),\n });\n let source: Keypair;\n try {\n source = Keypair.fromSecret(options.sourceSecret);\n } catch (cause) {\n throw new KitError('CONTRACT_AUTH_FAILED', 'invalid fee-source secret', { cause });\n }\n\n const account = await server.getAccount(source.publicKey());\n const tx = new TransactionBuilder(account, {\n fee: options.fee ?? '2000000',\n networkPassphrase: options.networkPassphrase,\n })\n .addOperation(options.operation)\n .setTimeout(options.timeoutSeconds ?? 120)\n .build();\n\n const recSim = await server.simulateTransaction(tx);\n if (!rpc.Api.isSimulationSuccess(recSim)) {\n const detail = 'error' in recSim ? String(recSim.error) : 'unknown simulation error';\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n `smart-wallet tx simulation failed: ${detail.slice(0, 300)}`,\n );\n }\n const prepared = rpc.assembleTransaction(tx, recSim).build();\n\n const signatureExpirationLedger =\n (await server.getLatestLedger()).sequence +\n (options.signatureExpirationLedgerOffset ?? DEFAULT_EXPIRATION_OFFSET);\n const signedAuthXdr = await signTransaction(prepared.toXDR(), {\n networkPassphrase: options.networkPassphrase,\n sign: options.sign,\n target: 'smart-wallet',\n signatureExpirationLedger,\n verify: options.verify,\n });\n\n const signedTx = TransactionBuilder.fromXDR(signedAuthXdr, options.networkPassphrase);\n const enfSim = await server.simulateTransaction(signedTx);\n if (!rpc.Api.isSimulationSuccess(enfSim)) {\n const detail = 'error' in enfSim ? String(enfSim.error) : 'unknown simulation error';\n throw new KitError(\n 'CONTRACT_AUTH_FAILED',\n `signed smart-wallet tx failed enforcing simulation (auth rejected?): ${detail.slice(0, 300)}`,\n );\n }\n\n const finalTx = rpc.assembleTransaction(signedTx, enfSim).build();\n finalTx.sign(source);\n const submission =\n options.submission ??\n directSubmission({\n rpcUrl: options.rpcUrl,\n networkPassphrase: options.networkPassphrase,\n allowHttp: options.allowHttp,\n });\n return submission.send(finalTx.toXDR());\n}\n"]}
@@ -0,0 +1,143 @@
1
+ export { S as SmartWalletCheckAuthResult, d as decodeChallenge, e as encodeChallenge, p as parseAuthenticatorData, b as parseClientDataJSON, r as referenceCheckAuth, c as referenceSmartWalletCheckAuth, v as verifyAssertionSignature, f as verifyClientDataJSON, g as verifyRpIdHash } from './checkAuth-C2AcXqFe.cjs';
2
+ import { b as WebAuthnSigner, A as AssertionResult } from './sign-Cfg0NM0T.cjs';
3
+ export { S as SignVerifyOptions, a as SorobanSignOptions, W as WalletTarget, s as signAuthEntry, c as signTransaction } from './sign-Cfg0NM0T.cjs';
4
+ import { W as WebAuthnClient } from './types--WNl-Sda.cjs';
5
+ import { xdr } from '@stellar/stellar-sdk';
6
+ export { B as BuildAddSignerOptions, a as BuildRemoveSignerOptions, S as Secp256r1SignerSpec, b as SendSmartWalletTxOptions, c as SignerStorage, d as buildAddSignerOperation, e as buildRemoveSignerOperation, f as buildSecp256r1Signer, s as sendSmartWalletTx } from './submit-BDKADQq0.cjs';
7
+
8
+ /**
9
+ * Convert an ASN.1 DER ECDSA signature to the 64-byte raw `R‖S` form Soroban's
10
+ * `secp256r1_verify` expects, using noble's audited DER parser (R and S are
11
+ * left-padded to 32 bytes big-endian). Rejects malformed or over-long input.
12
+ *
13
+ * Note: this does NOT enforce low-S — that normalization is added in S04
14
+ * (YK-430). The output here mirrors the signature exactly as parsed.
15
+ */
16
+ declare function derToCompact(der: Uint8Array): Uint8Array;
17
+ /** True if a 64-byte compact signature is in canonical low-S form (S ≤ n/2). */
18
+ declare function isLowS(compactSignature: Uint8Array): boolean;
19
+ /**
20
+ * Normalize a 64-byte compact signature to canonical low-S: if S > n/2, replace
21
+ * S with n − S (anchor LOW_S_NORMALIZATION, invariant #2). ~50% of Apple Touch
22
+ * ID / Face ID assertions are high-S and Soroban's `secp256r1_verify` does not
23
+ * enforce low-S, so the SDK MUST emit low-S before a signature reaches a
24
+ * contract. Idempotent: low-S input is returned unchanged.
25
+ */
26
+ declare function normalizeLowS(compactSignature: Uint8Array): Uint8Array;
27
+ /** DER → 64-byte canonical low-S compact — the conversion the signing ceremony uses. */
28
+ declare function derToCompactLowS(der: Uint8Array): Uint8Array;
29
+
30
+ /**
31
+ * Reconstruct the 32-byte payload the authenticator signed and that Soroban's
32
+ * `__check_auth` re-derives on-chain:
33
+ *
34
+ * SHA256( authenticatorData ‖ SHA256(clientDataJSON) )
35
+ */
36
+ declare function reconstructSignedPayload(input: {
37
+ authenticatorData: Uint8Array;
38
+ clientDataJSON: Uint8Array;
39
+ }): Uint8Array;
40
+
41
+ interface BrowserPasskeySignerOptions {
42
+ /** The Relying Party ID (your site's registrable domain). */
43
+ rpId: string;
44
+ /**
45
+ * Restrict the prompt to specific credential ids (base64url) — pass the
46
+ * `credentialId` from `create` / `connect` so the OS offers the right passkey.
47
+ * Omit (or leave empty) for a discoverable prompt over any resident passkey.
48
+ */
49
+ allowCredentials?: string[];
50
+ userVerification?: 'discouraged' | 'preferred' | 'required';
51
+ /** Inject a custom client (tests / non-browser). Defaults to `browserWebAuthnClient()`. */
52
+ webauthn?: WebAuthnClient;
53
+ }
54
+ /**
55
+ * Adapt `navigator.credentials.get` into the `WebAuthnSigner` that
56
+ * `signTransaction` / `signAuthEntry` expect — so wiring a passkey is one line:
57
+ *
58
+ * ```ts
59
+ * const sign = browserPasskeySigner({ rpId, allowCredentials: [credentialId] });
60
+ * const signedXdr = await signTransaction(txXdr, { networkPassphrase, sign });
61
+ * ```
62
+ *
63
+ * The SDK hands the signer a base64url challenge (the Soroban auth preimage);
64
+ * this decodes it to the raw bytes WebAuthn signs over, runs the assertion, and
65
+ * returns the fields the auth assembler needs. The DER signature is low-S
66
+ * normalized downstream (invariant #2) — nothing here weakens that.
67
+ */
68
+ declare function browserPasskeySigner(options: BrowserPasskeySignerOptions): WebAuthnSigner;
69
+
70
+ /**
71
+ * Compute the auth-entry preimage hash that `__check_auth` reconstructs and that
72
+ * becomes the WebAuthn `challenge`:
73
+ * SHA256( XDR( HashIdPreimage::SorobanAuthorization{ networkId, nonce,
74
+ * signatureExpirationLedger, invocation } ) )
75
+ * where networkId = SHA256(networkPassphrase).
76
+ */
77
+ declare function authEntryChallengeBytes(entry: xdr.SorobanAuthorizationEntry, networkPassphrase: string): Uint8Array;
78
+ /** The base64url challenge string the authenticator signs (43 chars). */
79
+ declare function authEntryChallenge(entry: xdr.SorobanAuthorizationEntry, networkPassphrase: string): string;
80
+
81
+ /**
82
+ * Set an address-credential auth entry's signature to the `Secp256r1Signature`
83
+ * struct the on-chain `__check_auth` consumes:
84
+ *
85
+ * ScVal::Map { authenticator_data: Bytes, client_data_json: Bytes, signature: BytesN<64> }
86
+ *
87
+ * Map keys are alphabetical, so the ScMap is canonically sorted as Soroban
88
+ * requires. `signature` MUST already be 64-byte low-S compact (`signAuthEntry`
89
+ * normalizes before calling this). This is the exact shape the audited
90
+ * webauthn-verifier reference expects — proven on testnet by the on-chain
91
+ * integration test (scripts/onchain-e2e.ts).
92
+ */
93
+ declare function applyAssertionToEntry(entry: xdr.SorobanAuthorizationEntry, assertion: AssertionResult): xdr.SorobanAuthorizationEntry;
94
+
95
+ /**
96
+ * The passkey-kit / `webauthn-wallet` smart-wallet ABI target.
97
+ *
98
+ * Our own single-signer account declares `type Signature = Secp256r1Signature`
99
+ * and consumes the bare struct (see `assemble.ts`). passkey-kit's smart-wallet
100
+ * declares `type Signature = Signatures`, so authorizing it needs the assertion
101
+ * wrapped as `Signatures(Map<SignerKey, Signature>)`. The exact shape, the raw-
102
+ * credential-id key, and the canonical map ordering below are confirmed by
103
+ * kalepail (passkey-kit author) in issue #32 against v1 / v0.13.0 (Protocol 27,
104
+ * independently audited); the wire shape is unchanged from v0.12.
105
+ */
106
+ /**
107
+ * `SignerKey::Secp256r1(Bytes)` → `scvVec([Symbol("Secp256r1"), Bytes(rawId)])`.
108
+ * The key is the RAW WebAuthn credential-id bytes (base64url-decoded `rawId`):
109
+ * never hashed, never the UTF-8 of the base64url string, and never the public
110
+ * key — the SEC-1 public key lives in `SignerVal` on-chain, not in the key.
111
+ */
112
+ declare function buildSignerKeyScVal(credentialId: Uint8Array): xdr.ScVal;
113
+ /** `Signature::Secp256r1(Secp256r1Signature)` → `scvVec([Symbol("Secp256r1"), <bare struct map>])`. */
114
+ declare function buildSmartWalletSignatureVariant(assertion: AssertionResult): xdr.ScVal;
115
+ /**
116
+ * Canonical Soroban-host ordering for `SignerKey` map keys. The host requires
117
+ * `Map<SignerKey, _>` entries sorted by ScVal `Ord` — an **element-wise byte
118
+ * comparison**, NOT a length-major XDR-hex / `localeCompare` string sort. This is
119
+ * the one correctness landmine kalepail flagged in #32: passkey-kit v1 replaced
120
+ * its old string sort with exactly this because the old approach could mis-order
121
+ * same-variant keys of differing length, producing a map the host rejects.
122
+ *
123
+ * We compare the enum variant symbol first, then the payload bytes element-wise,
124
+ * so homogeneous `Secp256r1` keys (the multi-passkey case) sort purely by their
125
+ * raw credential-id bytes. (Ordering across mixed variant types relies on the
126
+ * variant names being capitalized single words, which matches the host's symbol
127
+ * order; a Policy/Address-keyed multi-sig is out of scope for this passkey SDK.)
128
+ */
129
+ declare function compareSignerKeyScVal(a: xdr.ScVal, b: xdr.ScVal): number;
130
+ /**
131
+ * Assemble/merge a passkey assertion into an address-credential auth entry as the
132
+ * smart-wallet `Signatures(Map<SignerKey, Signature>)` wire shape
133
+ * (`ScVal::Vec([ScVal::Map(...)])`). `assertion.signature` MUST already be 64-byte
134
+ * low-S compact (`signAuthEntry` normalizes first). Existing map entries — a
135
+ * partially-signed multi-sig entry — are preserved; an entry for the same signer
136
+ * key is replaced; then the whole map is canonically sorted.
137
+ *
138
+ * Use this for the passkey-kit / webauthn-wallet ABI. For our own single-signer
139
+ * account (`type Signature = Secp256r1Signature`) use `applyAssertionToEntry`.
140
+ */
141
+ declare function applyAssertionToSmartWalletEntry(entry: xdr.SorobanAuthorizationEntry, assertion: AssertionResult): xdr.SorobanAuthorizationEntry;
142
+
143
+ export { type BrowserPasskeySignerOptions, applyAssertionToEntry, applyAssertionToSmartWalletEntry, authEntryChallenge, authEntryChallengeBytes, browserPasskeySigner, buildSignerKeyScVal, buildSmartWalletSignatureVariant, compareSignerKeyScVal, derToCompact, derToCompactLowS, isLowS, normalizeLowS, reconstructSignedPayload };
package/dist/sign.d.ts ADDED
@@ -0,0 +1,143 @@
1
+ export { S as SmartWalletCheckAuthResult, d as decodeChallenge, e as encodeChallenge, p as parseAuthenticatorData, b as parseClientDataJSON, r as referenceCheckAuth, c as referenceSmartWalletCheckAuth, v as verifyAssertionSignature, f as verifyClientDataJSON, g as verifyRpIdHash } from './checkAuth-C2AcXqFe.js';
2
+ import { b as WebAuthnSigner, A as AssertionResult } from './sign-Cfg0NM0T.js';
3
+ export { S as SignVerifyOptions, a as SorobanSignOptions, W as WalletTarget, s as signAuthEntry, c as signTransaction } from './sign-Cfg0NM0T.js';
4
+ import { W as WebAuthnClient } from './types--WNl-Sda.js';
5
+ import { xdr } from '@stellar/stellar-sdk';
6
+ export { B as BuildAddSignerOptions, a as BuildRemoveSignerOptions, S as Secp256r1SignerSpec, b as SendSmartWalletTxOptions, c as SignerStorage, d as buildAddSignerOperation, e as buildRemoveSignerOperation, f as buildSecp256r1Signer, s as sendSmartWalletTx } from './submit-BO0Nh49I.js';
7
+
8
+ /**
9
+ * Convert an ASN.1 DER ECDSA signature to the 64-byte raw `R‖S` form Soroban's
10
+ * `secp256r1_verify` expects, using noble's audited DER parser (R and S are
11
+ * left-padded to 32 bytes big-endian). Rejects malformed or over-long input.
12
+ *
13
+ * Note: this does NOT enforce low-S — that normalization is added in S04
14
+ * (YK-430). The output here mirrors the signature exactly as parsed.
15
+ */
16
+ declare function derToCompact(der: Uint8Array): Uint8Array;
17
+ /** True if a 64-byte compact signature is in canonical low-S form (S ≤ n/2). */
18
+ declare function isLowS(compactSignature: Uint8Array): boolean;
19
+ /**
20
+ * Normalize a 64-byte compact signature to canonical low-S: if S > n/2, replace
21
+ * S with n − S (anchor LOW_S_NORMALIZATION, invariant #2). ~50% of Apple Touch
22
+ * ID / Face ID assertions are high-S and Soroban's `secp256r1_verify` does not
23
+ * enforce low-S, so the SDK MUST emit low-S before a signature reaches a
24
+ * contract. Idempotent: low-S input is returned unchanged.
25
+ */
26
+ declare function normalizeLowS(compactSignature: Uint8Array): Uint8Array;
27
+ /** DER → 64-byte canonical low-S compact — the conversion the signing ceremony uses. */
28
+ declare function derToCompactLowS(der: Uint8Array): Uint8Array;
29
+
30
+ /**
31
+ * Reconstruct the 32-byte payload the authenticator signed and that Soroban's
32
+ * `__check_auth` re-derives on-chain:
33
+ *
34
+ * SHA256( authenticatorData ‖ SHA256(clientDataJSON) )
35
+ */
36
+ declare function reconstructSignedPayload(input: {
37
+ authenticatorData: Uint8Array;
38
+ clientDataJSON: Uint8Array;
39
+ }): Uint8Array;
40
+
41
+ interface BrowserPasskeySignerOptions {
42
+ /** The Relying Party ID (your site's registrable domain). */
43
+ rpId: string;
44
+ /**
45
+ * Restrict the prompt to specific credential ids (base64url) — pass the
46
+ * `credentialId` from `create` / `connect` so the OS offers the right passkey.
47
+ * Omit (or leave empty) for a discoverable prompt over any resident passkey.
48
+ */
49
+ allowCredentials?: string[];
50
+ userVerification?: 'discouraged' | 'preferred' | 'required';
51
+ /** Inject a custom client (tests / non-browser). Defaults to `browserWebAuthnClient()`. */
52
+ webauthn?: WebAuthnClient;
53
+ }
54
+ /**
55
+ * Adapt `navigator.credentials.get` into the `WebAuthnSigner` that
56
+ * `signTransaction` / `signAuthEntry` expect — so wiring a passkey is one line:
57
+ *
58
+ * ```ts
59
+ * const sign = browserPasskeySigner({ rpId, allowCredentials: [credentialId] });
60
+ * const signedXdr = await signTransaction(txXdr, { networkPassphrase, sign });
61
+ * ```
62
+ *
63
+ * The SDK hands the signer a base64url challenge (the Soroban auth preimage);
64
+ * this decodes it to the raw bytes WebAuthn signs over, runs the assertion, and
65
+ * returns the fields the auth assembler needs. The DER signature is low-S
66
+ * normalized downstream (invariant #2) — nothing here weakens that.
67
+ */
68
+ declare function browserPasskeySigner(options: BrowserPasskeySignerOptions): WebAuthnSigner;
69
+
70
+ /**
71
+ * Compute the auth-entry preimage hash that `__check_auth` reconstructs and that
72
+ * becomes the WebAuthn `challenge`:
73
+ * SHA256( XDR( HashIdPreimage::SorobanAuthorization{ networkId, nonce,
74
+ * signatureExpirationLedger, invocation } ) )
75
+ * where networkId = SHA256(networkPassphrase).
76
+ */
77
+ declare function authEntryChallengeBytes(entry: xdr.SorobanAuthorizationEntry, networkPassphrase: string): Uint8Array;
78
+ /** The base64url challenge string the authenticator signs (43 chars). */
79
+ declare function authEntryChallenge(entry: xdr.SorobanAuthorizationEntry, networkPassphrase: string): string;
80
+
81
+ /**
82
+ * Set an address-credential auth entry's signature to the `Secp256r1Signature`
83
+ * struct the on-chain `__check_auth` consumes:
84
+ *
85
+ * ScVal::Map { authenticator_data: Bytes, client_data_json: Bytes, signature: BytesN<64> }
86
+ *
87
+ * Map keys are alphabetical, so the ScMap is canonically sorted as Soroban
88
+ * requires. `signature` MUST already be 64-byte low-S compact (`signAuthEntry`
89
+ * normalizes before calling this). This is the exact shape the audited
90
+ * webauthn-verifier reference expects — proven on testnet by the on-chain
91
+ * integration test (scripts/onchain-e2e.ts).
92
+ */
93
+ declare function applyAssertionToEntry(entry: xdr.SorobanAuthorizationEntry, assertion: AssertionResult): xdr.SorobanAuthorizationEntry;
94
+
95
+ /**
96
+ * The passkey-kit / `webauthn-wallet` smart-wallet ABI target.
97
+ *
98
+ * Our own single-signer account declares `type Signature = Secp256r1Signature`
99
+ * and consumes the bare struct (see `assemble.ts`). passkey-kit's smart-wallet
100
+ * declares `type Signature = Signatures`, so authorizing it needs the assertion
101
+ * wrapped as `Signatures(Map<SignerKey, Signature>)`. The exact shape, the raw-
102
+ * credential-id key, and the canonical map ordering below are confirmed by
103
+ * kalepail (passkey-kit author) in issue #32 against v1 / v0.13.0 (Protocol 27,
104
+ * independently audited); the wire shape is unchanged from v0.12.
105
+ */
106
+ /**
107
+ * `SignerKey::Secp256r1(Bytes)` → `scvVec([Symbol("Secp256r1"), Bytes(rawId)])`.
108
+ * The key is the RAW WebAuthn credential-id bytes (base64url-decoded `rawId`):
109
+ * never hashed, never the UTF-8 of the base64url string, and never the public
110
+ * key — the SEC-1 public key lives in `SignerVal` on-chain, not in the key.
111
+ */
112
+ declare function buildSignerKeyScVal(credentialId: Uint8Array): xdr.ScVal;
113
+ /** `Signature::Secp256r1(Secp256r1Signature)` → `scvVec([Symbol("Secp256r1"), <bare struct map>])`. */
114
+ declare function buildSmartWalletSignatureVariant(assertion: AssertionResult): xdr.ScVal;
115
+ /**
116
+ * Canonical Soroban-host ordering for `SignerKey` map keys. The host requires
117
+ * `Map<SignerKey, _>` entries sorted by ScVal `Ord` — an **element-wise byte
118
+ * comparison**, NOT a length-major XDR-hex / `localeCompare` string sort. This is
119
+ * the one correctness landmine kalepail flagged in #32: passkey-kit v1 replaced
120
+ * its old string sort with exactly this because the old approach could mis-order
121
+ * same-variant keys of differing length, producing a map the host rejects.
122
+ *
123
+ * We compare the enum variant symbol first, then the payload bytes element-wise,
124
+ * so homogeneous `Secp256r1` keys (the multi-passkey case) sort purely by their
125
+ * raw credential-id bytes. (Ordering across mixed variant types relies on the
126
+ * variant names being capitalized single words, which matches the host's symbol
127
+ * order; a Policy/Address-keyed multi-sig is out of scope for this passkey SDK.)
128
+ */
129
+ declare function compareSignerKeyScVal(a: xdr.ScVal, b: xdr.ScVal): number;
130
+ /**
131
+ * Assemble/merge a passkey assertion into an address-credential auth entry as the
132
+ * smart-wallet `Signatures(Map<SignerKey, Signature>)` wire shape
133
+ * (`ScVal::Vec([ScVal::Map(...)])`). `assertion.signature` MUST already be 64-byte
134
+ * low-S compact (`signAuthEntry` normalizes first). Existing map entries — a
135
+ * partially-signed multi-sig entry — are preserved; an entry for the same signer
136
+ * key is replaced; then the whole map is canonically sorted.
137
+ *
138
+ * Use this for the passkey-kit / webauthn-wallet ABI. For our own single-signer
139
+ * account (`type Signature = Secp256r1Signature`) use `applyAssertionToEntry`.
140
+ */
141
+ declare function applyAssertionToSmartWalletEntry(entry: xdr.SorobanAuthorizationEntry, assertion: AssertionResult): xdr.SorobanAuthorizationEntry;
142
+
143
+ export { type BrowserPasskeySignerOptions, applyAssertionToEntry, applyAssertionToSmartWalletEntry, authEntryChallenge, authEntryChallengeBytes, browserPasskeySigner, buildSignerKeyScVal, buildSmartWalletSignatureVariant, compareSignerKeyScVal, derToCompact, derToCompactLowS, isLowS, normalizeLowS, reconstructSignedPayload };
package/dist/sign.js ADDED
@@ -0,0 +1,8 @@
1
+ export { browserPasskeySigner, referenceCheckAuth, referenceSmartWalletCheckAuth } from './chunk-LM2AZXKZ.js';
2
+ export { buildAddSignerOperation, buildRemoveSignerOperation, buildSecp256r1Signer, sendSmartWalletTx } from './chunk-UV5HORMF.js';
3
+ export { applyAssertionToEntry, applyAssertionToSmartWalletEntry, authEntryChallenge, authEntryChallengeBytes, buildSignerKeyScVal, buildSmartWalletSignatureVariant, compareSignerKeyScVal, derToCompact, derToCompactLowS, isLowS, normalizeLowS, reconstructSignedPayload, signAuthEntry, signTransaction, verifyAssertionSignature } from './chunk-BIRF5I6I.js';
4
+ export { decodeChallenge, encodeChallenge, parseAuthenticatorData, parseClientDataJSON, verifyClientDataJSON, verifyRpIdHash } from './chunk-JNJ2FY45.js';
5
+ import './chunk-LB4HOTLV.js';
6
+ import './chunk-AMYFJQAC.js';
7
+ //# sourceMappingURL=sign.js.map
8
+ //# sourceMappingURL=sign.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"sign.js"}