@spfn/auth 0.2.0-beta.83 → 0.2.0-beta.85
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.
- package/README.md +40 -6
- package/dist/client-proof.d.ts +412 -0
- package/dist/client-proof.js +1225 -0
- package/dist/client-proof.js.map +1 -0
- package/dist/server.js +29 -2
- package/dist/server.js.map +1 -1
- package/package.json +6 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/client-proof/canonical-json.ts","../src/server/client-proof/proof.ts","../src/server/client-proof/refusal.ts","../src/server/client-proof/state.ts","../src/server/client-proof/admission.ts","../src/server/client-proof/contract-types.ts","../src/server/client-proof/dev-control.ts","../src/server/client-proof/dev-handler.ts","../src/server/client-proof/guard.ts"],"sourcesContent":["/**\n * SPFN-CANON-JSON-1 — the canonical JSON form the mobile contract pins.\n *\n * The rules (Contracts/spfn-mobile-contract.v1.json `canonicalJson`):\n * - object keys sorted ascending by UTF-8 byte sequence\n * - no insignificant whitespace\n * - numbers are signed 64-bit integers only\n * - string escapes: `\"` and `\\` escaped; C0 controls use \\b \\f \\n \\r \\t where\n * defined and lowercase \\u00XX otherwise; every other scalar is emitted\n * literally as UTF-8\n * - absent optional fields are omitted, never null\n *\n * JSON.parse cannot implement this: it loses int64 precision, accepts duplicate\n * keys and (in V8) raw control characters, so both directions are hand-rolled.\n * A proof binds the received bytes — parse-then-re-encode equality is what makes\n * canonicity a rule a client can actually break.\n *\n * @module server/client-proof/canonical-json\n */\n\nexport type CanonicalObject = Map<string, CanonicalValue>;\n\nexport type CanonicalValue = null | boolean | bigint | string | CanonicalValue[] | CanonicalObject;\n\n/**\n * Parse failures carry the code the mobile conformance fixtures name\n * (Contracts/fixtures/canonical/rejects.json), so the fixtures can assert on it.\n */\nexport type CanonicalJsonErrorCode =\n | 'DUPLICATE_KEY'\n | 'NON_INTEGER_NUMBER'\n | 'TRAILING_CONTENT'\n | 'UNEXPECTED_END'\n | 'INVALID_TOKEN'\n | 'INVALID_ESCAPE'\n | 'INTEGER_OUT_OF_RANGE'\n | 'INVALID_UTF8';\n\nexport class CanonicalJsonError extends Error\n{\n constructor(readonly code: CanonicalJsonErrorCode)\n {\n super(`canonical JSON: ${code}`);\n this.name = 'CanonicalJsonError';\n }\n}\n\nconst INT64_MIN = -(2n ** 63n);\nconst INT64_MAX = 2n ** 63n - 1n;\n\n// ============================================================================\n// Parsing\n// ============================================================================\n\n/**\n * Parse bytes as SPFN-CANON-JSON-1.\n *\n * Arbitrary whitespace and key order are accepted here — parsing alone proves\n * nothing about canonicity. Callers that must enforce it re-encode the result\n * and compare bytes (see `isCanonicalBytes`).\n */\nexport function parseCanonicalJson(bytes: Uint8Array): CanonicalValue\n{\n let text: string;\n try\n {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n }\n catch\n {\n throw new CanonicalJsonError('INVALID_UTF8');\n }\n\n const parser = new Parser(text);\n const value = parser.parseValue();\n parser.skipWhitespace();\n if (!parser.atEnd())\n {\n throw new CanonicalJsonError('TRAILING_CONTENT');\n }\n\n return value;\n}\n\n/** True when `bytes` are exactly the canonical encoding of the value they parse to. */\nexport function isCanonicalBytes(bytes: Uint8Array, value: CanonicalValue): boolean\n{\n const encoded = encodeCanonicalJson(value);\n if (encoded.length !== bytes.length)\n {\n return false;\n }\n for (let i = 0; i < encoded.length; i++)\n {\n if (encoded[i] !== bytes[i])\n {\n return false;\n }\n }\n\n return true;\n}\n\nclass Parser\n{\n private pos = 0;\n\n constructor(private readonly text: string) \n {}\n\n atEnd(): boolean\n {\n return this.pos >= this.text.length;\n }\n\n skipWhitespace(): void\n {\n while (!this.atEnd())\n {\n const c = this.text[this.pos];\n if (c === ' ' || c === '\\t' || c === '\\n' || c === '\\r')\n {\n this.pos++;\n continue;\n }\n break;\n }\n }\n\n parseValue(): CanonicalValue\n {\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const c = this.text[this.pos];\n if (c === '{')\n {\n return this.parseObject();\n }\n if (c === '[')\n {\n return this.parseArray();\n }\n if (c === '\"')\n {\n return this.parseString();\n }\n if (c === '-' || (c >= '0' && c <= '9'))\n {\n return this.parseNumber();\n }\n if (this.text.startsWith('null', this.pos))\n {\n this.pos += 4;\n\n return null;\n }\n if (this.text.startsWith('true', this.pos))\n {\n this.pos += 4;\n\n return true;\n }\n if (this.text.startsWith('false', this.pos))\n {\n this.pos += 5;\n\n return false;\n }\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n\n private parseObject(): CanonicalObject\n {\n this.pos++; // '{'\n const members: CanonicalObject = new Map();\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n if (this.text[this.pos] === '}')\n {\n this.pos++;\n\n return members;\n }\n for (;;)\n {\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n if (this.text[this.pos] !== '\"')\n {\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n const key = this.parseString();\n if (members.has(key))\n {\n throw new CanonicalJsonError('DUPLICATE_KEY');\n }\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n if (this.text[this.pos] !== ':')\n {\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n this.pos++;\n members.set(key, this.parseValue());\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const next = this.text[this.pos];\n if (next === ',')\n {\n this.pos++;\n continue;\n }\n if (next === '}')\n {\n this.pos++;\n\n return members;\n }\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n }\n\n private parseArray(): CanonicalValue[]\n {\n this.pos++; // '['\n const items: CanonicalValue[] = [];\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n if (this.text[this.pos] === ']')\n {\n this.pos++;\n\n return items;\n }\n for (;;)\n {\n items.push(this.parseValue());\n this.skipWhitespace();\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const next = this.text[this.pos];\n if (next === ',')\n {\n this.pos++;\n continue;\n }\n if (next === ']')\n {\n this.pos++;\n\n return items;\n }\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n }\n\n private parseString(): string\n {\n this.pos++; // '\"'\n let out = '';\n for (;;)\n {\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const c = this.text[this.pos];\n const code = this.text.charCodeAt(this.pos);\n if (c === '\"')\n {\n this.pos++;\n\n return out;\n }\n if (c === '\\\\')\n {\n out += this.parseEscape();\n continue;\n }\n if (code < 0x20)\n {\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n out += c;\n this.pos++;\n }\n }\n\n private parseEscape(): string\n {\n this.pos++; // '\\'\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const c = this.text[this.pos];\n this.pos++;\n switch (c)\n {\n case '\"': return '\"';\n case '\\\\': return '\\\\';\n case '/': return '/';\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'u': return this.parseUnicodeEscape();\n default: throw new CanonicalJsonError('INVALID_ESCAPE');\n }\n }\n\n private parseUnicodeEscape(): string\n {\n const high = this.readHex4();\n if (high >= 0xdc00 && high <= 0xdfff)\n {\n // A low surrogate with no preceding high surrogate.\n throw new CanonicalJsonError('INVALID_ESCAPE');\n }\n if (high < 0xd800 || high > 0xdbff)\n {\n return String.fromCharCode(high);\n }\n // A high surrogate must be completed by an escaped low surrogate.\n if (this.text[this.pos] !== '\\\\' || this.text[this.pos + 1] !== 'u')\n {\n throw new CanonicalJsonError('INVALID_ESCAPE');\n }\n this.pos += 2;\n const low = this.readHex4();\n if (low < 0xdc00 || low > 0xdfff)\n {\n throw new CanonicalJsonError('INVALID_ESCAPE');\n }\n\n return String.fromCharCode(high, low);\n }\n\n private readHex4(): number\n {\n if (this.pos + 4 > this.text.length)\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const hex = this.text.slice(this.pos, this.pos + 4);\n if (!/^[0-9a-fA-F]{4}$/.test(hex))\n {\n throw new CanonicalJsonError('INVALID_ESCAPE');\n }\n this.pos += 4;\n\n return parseInt(hex, 16);\n }\n\n private parseNumber(): bigint\n {\n const start = this.pos;\n if (this.text[this.pos] === '-')\n {\n this.pos++;\n }\n if (this.atEnd())\n {\n throw new CanonicalJsonError('UNEXPECTED_END');\n }\n const first = this.text[this.pos];\n if (first < '0' || first > '9')\n {\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n if (first === '0')\n {\n this.pos++;\n }\n else\n {\n while (!this.atEnd() && this.text[this.pos] >= '0' && this.text[this.pos] <= '9')\n {\n this.pos++;\n }\n }\n if (!this.atEnd())\n {\n const next = this.text[this.pos];\n if (next >= '0' && next <= '9')\n {\n // A leading zero followed by more digits.\n throw new CanonicalJsonError('INVALID_TOKEN');\n }\n if (next === '.' || next === 'e' || next === 'E')\n {\n throw new CanonicalJsonError('NON_INTEGER_NUMBER');\n }\n }\n const value = BigInt(this.text.slice(start, this.pos));\n if (value < INT64_MIN || value > INT64_MAX)\n {\n throw new CanonicalJsonError('INTEGER_OUT_OF_RANGE');\n }\n\n return value;\n }\n}\n\n// ============================================================================\n// Encoding\n// ============================================================================\n\n/** Encode a value as SPFN-CANON-JSON-1 bytes. */\nexport function encodeCanonicalJson(value: CanonicalValue): Uint8Array\n{\n return new TextEncoder().encode(encodeToString(value));\n}\n\nfunction encodeToString(value: CanonicalValue): string\n{\n if (value === null)\n {\n return 'null';\n }\n if (typeof value === 'boolean')\n {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'bigint')\n {\n return value.toString();\n }\n if (typeof value === 'string')\n {\n return encodeString(value);\n }\n if (Array.isArray(value))\n {\n return `[${value.map(encodeToString).join(',')}]`;\n }\n const keys = [...value.keys()].sort(compareByCodePoints);\n const members = keys.map((key) => `${encodeString(key)}:${encodeToString(value.get(key)!)}`);\n\n return `{${members.join(',')}}`;\n}\n\n/**\n * UTF-8 byte order equals code point order, so keys are compared by code\n * points rather than UTF-16 code units (which would misorder U+E000..U+FFFF\n * against supplementary-plane characters).\n */\nfunction compareByCodePoints(a: string, b: string): number\n{\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length)\n {\n const ca = a.codePointAt(i)!;\n const cb = b.codePointAt(j)!;\n if (ca !== cb)\n {\n return ca - cb;\n }\n i += ca > 0xffff ? 2 : 1;\n j += cb > 0xffff ? 2 : 1;\n }\n\n return (a.length - i) - (b.length - j);\n}\n\nfunction encodeString(value: string): string\n{\n let out = '\"';\n for (const ch of value)\n {\n const code = ch.codePointAt(0)!;\n if (ch === '\"')\n {\n out += '\\\\\"';\n }\n else if (ch === '\\\\')\n {\n out += '\\\\\\\\';\n }\n else if (code === 0x08)\n {\n out += '\\\\b';\n }\n else if (code === 0x0c)\n {\n out += '\\\\f';\n }\n else if (code === 0x0a)\n {\n out += '\\\\n';\n }\n else if (code === 0x0d)\n {\n out += '\\\\r';\n }\n else if (code === 0x09)\n {\n out += '\\\\t';\n }\n else if (code < 0x20)\n {\n out += `\\\\u00${code.toString(16).padStart(2, '0')}`;\n }\n else\n {\n out += ch;\n }\n }\n\n return out + '\"';\n}\n","/**\n * SPFN-PROOF-INPUT-1 — proof-input assembly and verification for clientProofV1.\n *\n * The proof input is 8 fields joined by `\\n` in fixed order: profile, method,\n * path, clientId, keyId, nonce, issuedAtMillis, bodySha256. Any C0 control\n * character in any field is a hard refusal (the separator would otherwise be\n * ambiguous), never something to escape. The MAC is HMAC-SHA-256 over the\n * canonical input's UTF-8 bytes, encoded base16-lower.\n *\n * @module server/client-proof/proof\n */\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto';\n\n/** The only auth profile this module implements. */\nexport const CLIENT_PROOF_PROFILE = 'clientProofV1';\n\n/** `bodySha256` when an operation carries no body: 64 zero characters. */\nexport const ABSENT_BODY_SHA256 = '0'.repeat(64);\n\n/** The contract's `clientProofV1.replayWindowMillis`. */\nexport const DEFAULT_REPLAY_WINDOW_MILLIS = 300_000;\n\nexport interface ClientProofInput\n{\n method: string;\n path: string;\n clientId: string;\n keyId: string;\n nonce: string;\n issuedAtMillis: bigint;\n bodySha256: string;\n}\n\n/** A C0 control character appeared in a proof field. */\nexport class ProofInputError extends Error\n{\n constructor()\n {\n super('proof input field contains a C0 control character');\n this.name = 'ProofInputError';\n }\n}\n\n/**\n * The canonical proof-input string the MAC is taken over.\n *\n * @throws ProofInputError when any field contains a C0 control character.\n */\nexport function canonicalProofInput(input: ClientProofInput): string\n{\n const fields = [\n CLIENT_PROOF_PROFILE,\n input.method,\n input.path,\n input.clientId,\n input.keyId,\n input.nonce,\n input.issuedAtMillis.toString(),\n input.bodySha256,\n ];\n for (const field of fields)\n {\n for (const ch of field)\n {\n if (ch.codePointAt(0)! < 0x20)\n {\n throw new ProofInputError();\n }\n }\n }\n\n return fields.join('\\n');\n}\n\n/** The base16-lower HMAC-SHA-256 proof for `input` under `key`. */\nexport function computeClientProof(input: ClientProofInput, key: Uint8Array): string\n{\n return createHmac('sha256', key).update(canonicalProofInput(input), 'utf8').digest('hex');\n}\n\n/** Lowercase base16 SHA-256 of `bytes`. */\nexport function sha256Hex(bytes: Uint8Array): string\n{\n return createHash('sha256').update(bytes).digest('hex');\n}\n\n/**\n * Constant-time comparison of two proof strings.\n *\n * Length is checked first (its leak reveals nothing — the expected length is\n * public), then the bytes are compared with `timingSafeEqual`.\n */\nexport function constantTimeEqualsProof(expected: string, presented: string): boolean\n{\n const a = Buffer.from(expected, 'utf8');\n const b = Buffer.from(presented, 'utf8');\n if (a.length !== b.length)\n {\n return false;\n }\n\n return timingSafeEqual(a, b);\n}\n","/**\n * Every way a clientProofV1 server refuses a request.\n *\n * The contract declares six error codes and forbids inventing a seventh, so\n * every refusal here is one of the six. Two rules decide which code a refusal\n * gets (mirroring the spfn-mobile reference server, the executable spec):\n *\n * 1. A refusal a new session could clear is an auth-family code (401). The SDK\n * re-handshakes exactly once on those.\n * 2. Everything else — the request is not the shape the contract describes —\n * is CONTRACT_UNSUPPORTED: the two ends do not agree on what the contract\n * is. PROOF_INVALID would provoke a pointless re-handshake and\n * PROFILE_REJECTED names one specific thing (a profile outside the\n * allowlist), used for exactly and only that.\n *\n * Every message is a fixed string: a message assembled from the request would\n * put a nonce, session id or body fragment into an error the client may log.\n *\n * @module server/client-proof/refusal\n */\nimport { randomBytes } from 'node:crypto';\n\nimport { encodeCanonicalJson, type CanonicalObject, type CanonicalValue } from './canonical-json';\n\n/** The six wire codes. The SDKs classify by code, never HTTP status. */\nexport type ClientProofErrorCode =\n | 'PROOF_INVALID'\n | 'PROOF_REPLAYED'\n | 'PROOF_EXPIRED'\n | 'SESSION_REVOKED'\n | 'PROFILE_REJECTED'\n | 'CONTRACT_UNSUPPORTED';\n\nconst HTTP_STATUS: Record<ClientProofErrorCode, number> = {\n PROOF_INVALID: 401,\n PROOF_REPLAYED: 401,\n PROOF_EXPIRED: 401,\n SESSION_REVOKED: 401,\n PROFILE_REJECTED: 400,\n CONTRACT_UNSUPPORTED: 409,\n};\n\n/** 128 random bits as lowercase base16 — request ids and control tokens. */\nexport function newHexId(): string\n{\n return randomBytes(16).toString('hex');\n}\n\nexport class ClientProofRefusal\n{\n constructor(\n readonly code: ClientProofErrorCode,\n readonly message: string,\n ) \n {}\n\n get httpStatus(): number\n {\n return HTTP_STATUS[this.code];\n }\n\n /** The canonical bytes of `{\"error\":{\"code\":…,\"message\":…,\"requestId\":…}}`. */\n envelopeBytes(requestId: string): Uint8Array\n {\n const error: CanonicalObject = new Map<string, CanonicalValue>([\n ['code', this.code],\n ['message', this.message],\n ['requestId', requestId],\n ]);\n\n return encodeCanonicalJson(new Map<string, CanonicalValue>([['error', error]]));\n }\n\n /** Nothing request-derived reaches a log through this. */\n toString(): string\n {\n return `ClientProofRefusal(${this.code})`;\n }\n\n // ---- shape: what arrived is not the contract (rule 2) -------------------\n\n static unroutable(): ClientProofRefusal\n {\n return contractViolation('no operation in this contract answers that method and path');\n }\n\n static malformedHeaders(): ClientProofRefusal\n {\n return contractViolation('the request does not carry the contract header fields exactly once each');\n }\n\n static missingContentType(): ClientProofRefusal\n {\n return contractViolation('a request that carries a body must declare the contract content type');\n }\n\n static bodyTooLarge(): ClientProofRefusal\n {\n return contractViolation('the request body exceeds the size this server accepts');\n }\n\n /**\n * The body parsed but its bytes are not the canonical form of what it\n * parsed to. Not PROOF_INVALID even though it is discovered next to the\n * proof: the proof over these bytes verifies perfectly well, and an\n * auth-family answer would tell the client to re-handshake and send the\n * same non-canonical bytes again.\n */\n static bodyNotCanonical(): ClientProofRefusal\n {\n return contractViolation('the request body is not the canonical JSON form of the value it encodes');\n }\n\n static bodyNotTheDeclaredType(): ClientProofRefusal\n {\n return contractViolation('the request body is not the request type this operation declares');\n }\n\n static sessionHeaderMisplaced(): ClientProofRefusal\n {\n return contractViolation('the session header is present exactly on the operations that require one');\n }\n\n static unprocessable(): ClientProofRefusal\n {\n return contractViolation('the request could not be processed');\n }\n\n // ---- the profile allowlist ----------------------------------------------\n\n static profileRejected(): ClientProofRefusal\n {\n return new ClientProofRefusal('PROFILE_REJECTED', \"the named auth profile is not on this contract's allowlist\");\n }\n\n // ---- auth: a new session might clear it (rule 1) -------------------------\n\n static sessionRevoked(): ClientProofRefusal\n {\n return new ClientProofRefusal('SESSION_REVOKED', 'the key or session was revoked');\n }\n\n static proofExpired(): ClientProofRefusal\n {\n return new ClientProofRefusal('PROOF_EXPIRED', 'issuedAtMillis falls outside the replay window');\n }\n\n static proofReplayed(): ClientProofRefusal\n {\n return new ClientProofRefusal('PROOF_REPLAYED', 'the nonce was already used inside the replay window');\n }\n\n static proofInvalid(): ClientProofRefusal\n {\n return new ClientProofRefusal('PROOF_INVALID', 'the client proof did not verify');\n }\n}\n\nfunction contractViolation(message: string): ClientProofRefusal\n{\n return new ClientProofRefusal('CONTRACT_UNSUPPORTED', message);\n}\n","/**\n * Everything a clientProofV1 server remembers between requests: issued\n * sessions, the replay ledger, revoked keys and the key directory.\n *\n * The admission order is the contract's, not this file's invention\n * (`clientProofV1.revocationRule` + the replay fixtures):\n *\n * 1. revoked keyId / invalid session → SESSION_REVOKED — before proof\n * verification, so revocation stays distinguishable from a bad proof;\n * 2. issuedAtMillis outside the replay window (0 <= age <= window) → PROOF_EXPIRED;\n * 3. a repeated (clientId, nonce) pair inside the window → PROOF_REPLAYED;\n * 4. only then HMAC verification → PROOF_INVALID on mismatch.\n *\n * A nonce is recorded as spent only on admission: a request refused for any\n * earlier reason has not spent anything, so a client that fixes the reason and\n * retries with the same nonce is not punished twice for one mistake. This is\n * why core's `NonceStore.checkAndSet` (which records on check) is not reused\n * here — its semantics would spend a nonce on a refused request.\n *\n * `admit` is synchronous, so on Node's single thread the whole sequence is\n * atomic: two requests presenting the same nonce cannot interleave inside it.\n *\n * @module server/client-proof/state\n */\nimport {\n computeClientProof,\n constantTimeEqualsProof,\n DEFAULT_REPLAY_WINDOW_MILLIS,\n type ClientProofInput,\n} from './proof';\nimport { ClientProofRefusal, newHexId } from './refusal';\n\n/** Millisecond clock. Injectable so expiry paths are testable without waiting. */\nexport interface ClientProofClock\n{\n nowMillis(): number;\n}\n\nexport function systemClock(): ClientProofClock\n{\n return { nowMillis: () => Date.now() };\n}\n\n/** A clock a test (or the dev control surface) can move forward. */\nexport class TestClock implements ClientProofClock\n{\n constructor(private millis: number) \n {}\n\n nowMillis(): number\n {\n return this.millis;\n }\n\n advance(byMillis: number): void\n {\n this.millis += byMillis;\n }\n}\n\n/** What `stats()` reports. Counters only; nothing a request carried. */\nexport interface ClientProofStats\n{\n requestCount: number;\n handshakeCount: number;\n echoCount: number;\n itemsListCount: number;\n refusalCount: number;\n liveSessionCount: number;\n spentNonceCount: number;\n}\n\ninterface ClientProofSession\n{\n clientId: string;\n keyId: string;\n expiresAtMillis: number;\n}\n\ninterface PathHold\n{\n millis: number;\n remaining: number;\n}\n\nexport interface ClientProofStateOptions\n{\n /**\n * keyId → HMAC key. A string is taken as UTF-8 bytes. Dev provisioning is\n * injection at construction; any issuance flow works as long as\n * clientId/keyId/key triples exist on both ends.\n */\n keys: Record<string, string | Uint8Array>;\n\n clock?: ClientProofClock;\n\n /** @default 600000 */\n sessionTtlMillis?: number;\n\n /** The contract's replay window. @default 300000 */\n replayWindowMillis?: number;\n}\n\nexport const DEFAULT_SESSION_TTL_MILLIS = 600_000;\n\n/** The ledger key: joined with a C0 control, which no proof field may contain. */\nfunction replayKeyOf(clientId: string, nonce: string): string\n{\n return `${clientId}\u001f${nonce}`;\n}\n\nexport class ClientProofState\n{\n readonly replayWindowMillis: number;\n\n private readonly clock: ClientProofClock;\n private readonly keys = new Map<string, Uint8Array>();\n private readonly sessions = new Map<string, ClientProofSession>();\n\n /** replayKeyOf(...) → the issuedAtMillis it was spent at. */\n private readonly spentNonces = new Map<string, number>();\n\n private readonly revokedKeyIds = new Set<string>();\n private readonly holds = new Map<string, PathHold>();\n\n private readonly initialSessionTtlMillis: number;\n private sessionTtlMillis: number;\n\n private requestCount = 0;\n private handshakeCount = 0;\n private echoCount = 0;\n private itemsListCount = 0;\n private refusalCount = 0;\n\n constructor(options: ClientProofStateOptions)\n {\n this.clock = options.clock ?? systemClock();\n this.initialSessionTtlMillis = options.sessionTtlMillis ?? DEFAULT_SESSION_TTL_MILLIS;\n this.sessionTtlMillis = this.initialSessionTtlMillis;\n this.replayWindowMillis = options.replayWindowMillis ?? DEFAULT_REPLAY_WINDOW_MILLIS;\n for (const [keyId, key] of Object.entries(options.keys))\n {\n this.keys.set(keyId, typeof key === 'string' ? new TextEncoder().encode(key) : key);\n }\n }\n\n // ---- admission ---------------------------------------------------------\n\n /**\n * Runs the contract's checks in the contract's order and returns the\n * refusal, or null when the request is admitted (spending its nonce).\n */\n admit(args: {\n clientId: string;\n keyId: string;\n presentedSessionId: string | null;\n requiresSession: boolean;\n proofInput: ClientProofInput;\n presentedProof: string;\n }): ClientProofRefusal | null\n {\n const now = this.clock.nowMillis();\n this.prune(now);\n\n // 1. Revocation, before anything the proof could explain. A revoked key\n // and a dropped session are the same answer on purpose: both are\n // cleared by opening a new session.\n if (this.revokedKeyIds.has(args.keyId))\n {\n return ClientProofRefusal.sessionRevoked();\n }\n if (args.requiresSession)\n {\n const session = args.presentedSessionId === null ? undefined : this.sessions.get(args.presentedSessionId);\n if (session === undefined || session.expiresAtMillis <= now\n || session.keyId !== args.keyId || session.clientId !== args.clientId)\n {\n return ClientProofRefusal.sessionRevoked();\n }\n }\n\n // 2. The replay window, judged against this server's clock.\n const age = now - Number(args.proofInput.issuedAtMillis);\n if (age < 0 || age > this.replayWindowMillis)\n {\n return ClientProofRefusal.proofExpired();\n }\n\n // 3. One acceptance per (clientId, nonce) inside that window.\n const replayKey = replayKeyOf(args.clientId, args.proofInput.nonce);\n if (this.spentNonces.has(replayKey))\n {\n return ClientProofRefusal.proofReplayed();\n }\n\n // 4. The proof itself, last, so the three answers above stay\n // distinguishable. An unrecognised keyId lands here rather than in\n // step 1: it was never issued, so it was never revoked, and there is\n // nothing for a new session to fix.\n const key = this.keys.get(args.keyId);\n if (key === undefined)\n {\n return ClientProofRefusal.proofInvalid();\n }\n if (!constantTimeEqualsProof(computeClientProof(args.proofInput, key), args.presentedProof))\n {\n return ClientProofRefusal.proofInvalid();\n }\n\n this.spentNonces.set(replayKey, Number(args.proofInput.issuedAtMillis));\n\n return null;\n }\n\n // ---- sessions ----------------------------------------------------------\n\n /** Opens a session and returns its id and the expiry the server advertises. */\n openSession(clientId: string, keyId: string): { sessionId: string; expiresAtMillis: number }\n {\n const now = this.clock.nowMillis();\n this.prune(now);\n const sessionId = newHexId();\n const expiresAtMillis = now + this.sessionTtlMillis;\n this.sessions.set(sessionId, { clientId, keyId, expiresAtMillis });\n\n return { sessionId, expiresAtMillis };\n }\n\n /** Test hook: installs a session with a chosen id (wire-fixture replays). */\n seedSession(sessionId: string, clientId: string, keyId: string, expiresAtMillis: number): void\n {\n this.sessions.set(sessionId, { clientId, keyId, expiresAtMillis });\n }\n\n /** Drops every session, as a restart would. Advertised expiries stay told. */\n expireSessions(): void\n {\n this.sessions.clear();\n }\n\n /** Revokes a key and drops the sessions it opened. */\n revokeKey(keyId: string): void\n {\n this.revokedKeyIds.add(keyId);\n for (const [sessionId, session] of this.sessions)\n {\n if (session.keyId === keyId)\n {\n this.sessions.delete(sessionId);\n }\n }\n }\n\n setSessionTtlMillis(millis: number): void\n {\n this.sessionTtlMillis = millis;\n }\n\n /** Returns the state to how it started, counters included. */\n reset(): void\n {\n this.sessions.clear();\n this.spentNonces.clear();\n this.revokedKeyIds.clear();\n this.holds.clear();\n this.sessionTtlMillis = this.initialSessionTtlMillis;\n this.requestCount = 0;\n this.handshakeCount = 0;\n this.echoCount = 0;\n this.itemsListCount = 0;\n this.refusalCount = 0;\n }\n\n // ---- delays (dev/test only) --------------------------------------------\n\n /** Makes the next `count` requests to `path` wait `millis` before processing. */\n holdPath(path: string, millis: number, count: number): void\n {\n this.holds.set(path, { millis, remaining: count });\n }\n\n /** Consumes one configured delay for `path`; returns how long to wait, or 0. */\n takeHoldMillis(path: string): number\n {\n const hold = this.holds.get(path);\n if (hold === undefined)\n {\n return 0;\n }\n hold.remaining -= 1;\n if (hold.remaining <= 0)\n {\n this.holds.delete(path);\n }\n\n return hold.millis;\n }\n\n // ---- counters ----------------------------------------------------------\n\n recordRequest(): void\n {\n this.requestCount += 1;\n }\n\n recordOperation(operationId: string): void\n {\n if (operationId === 'auth.clientProof.handshake')\n {\n this.handshakeCount += 1;\n }\n else if (operationId === 'echo.send')\n {\n this.echoCount += 1;\n }\n else if (operationId === 'items.list')\n {\n this.itemsListCount += 1;\n }\n }\n\n recordRefusal(): void\n {\n this.refusalCount += 1;\n }\n\n stats(): ClientProofStats\n {\n this.prune(this.clock.nowMillis());\n\n return {\n requestCount: this.requestCount,\n handshakeCount: this.handshakeCount,\n echoCount: this.echoCount,\n itemsListCount: this.itemsListCount,\n refusalCount: this.refusalCount,\n liveSessionCount: this.sessions.size,\n spentNonceCount: this.spentNonces.size,\n };\n }\n\n nowMillis(): number\n {\n return this.clock.nowMillis();\n }\n\n /** The clock, exposed for the dev control surface's advance-clock route. */\n get clockRef(): ClientProofClock\n {\n return this.clock;\n }\n\n // ---- housekeeping ------------------------------------------------------\n\n /**\n * Drops what can no longer affect an answer. The nonce predicate is the\n * exact negation of the window check in `admit`: an entry is dropped only\n * once a proof carrying that issuedAtMillis would be refused as expired\n * anyway. Dropping one moment earlier would let a nonce inside the window\n * be spent twice.\n */\n private prune(nowMillis: number): void\n {\n for (const [sessionId, session] of this.sessions)\n {\n if (session.expiresAtMillis <= nowMillis)\n {\n this.sessions.delete(sessionId);\n }\n }\n for (const [key, issuedAtMillis] of this.spentNonces)\n {\n if (nowMillis - issuedAtMillis > this.replayWindowMillis)\n {\n this.spentNonces.delete(key);\n }\n }\n }\n}\n","/**\n * The checks between a clientProofV1 request arriving and being applied.\n *\n * Shape first, then the profile allowlist, then the proof. That order is\n * forced: none of the proof checks can run until the fields they read are\n * known to be present and the body is known to be the bytes the digest is\n * supposed to cover. The order *inside* the proof checks is the contract's and\n * lives in `ClientProofState.admit`.\n *\n * @module server/client-proof/admission\n */\nimport { isCanonicalBytes, parseCanonicalJson, type CanonicalValue } from './canonical-json';\nimport { CLIENT_PROOF_PROFILE, sha256Hex, type ClientProofInput } from './proof';\nimport { ClientProofRefusal } from './refusal';\nimport type { ClientProofState } from './state';\n\n/** D23 wire-header names, ratified as proposed by the mobile dev bundle. */\nexport const CLIENT_PROOF_HEADERS = {\n profile: 'x-spfn-auth-profile',\n clientId: 'x-spfn-client-id',\n keyId: 'x-spfn-key-id',\n nonce: 'x-spfn-nonce',\n issuedAtMillis: 'x-spfn-issued-at',\n proof: 'x-spfn-proof',\n session: 'x-spfn-session',\n} as const;\n\nexport const CLIENT_PROOF_CONTENT_TYPE = 'application/json';\n\nconst INT64_MIN = -(2n ** 63n);\nconst INT64_MAX = 2n ** 63n - 1n;\n\n/** The contract header fields one request presented. */\nexport interface ClientProofCredentials\n{\n profile: string;\n clientId: string;\n keyId: string;\n nonce: string;\n issuedAtMillis: bigint;\n proof: string;\n sessionId: string | null;\n}\n\nexport type Admission =\n | { admitted: false; refusal: ClientProofRefusal }\n | { admitted: true; value: CanonicalValue; credentials: ClientProofCredentials };\n\n/**\n * Runs every check for one operation over already-read body bytes.\n *\n * `path` must be the operation's contract path (what the client signed), not a\n * proxied or rewritten one.\n */\nexport function admitClientProofRequest(args: {\n state: ClientProofState;\n headers: Headers;\n method: string;\n path: string;\n requiresSession: boolean;\n body: Uint8Array;\n}): Admission\n{\n const credentials = readCredentials(args.headers);\n if (credentials === null)\n {\n return refused(ClientProofRefusal.malformedHeaders());\n }\n if (credentials.profile !== CLIENT_PROOF_PROFILE)\n {\n return refused(ClientProofRefusal.profileRejected());\n }\n if (!isRequestContentType(args.headers.get('content-type')))\n {\n return refused(ClientProofRefusal.missingContentType());\n }\n if (args.requiresSession !== (credentials.sessionId !== null))\n {\n return refused(ClientProofRefusal.sessionHeaderMisplaced());\n }\n\n let value: CanonicalValue;\n try\n {\n value = parseCanonicalJson(args.body);\n }\n catch\n {\n return refused(ClientProofRefusal.bodyNotCanonical());\n }\n // The proof binds the received bytes; accepting a re-serialization would\n // let two implementations disagree about what was signed.\n if (!isCanonicalBytes(args.body, value))\n {\n return refused(ClientProofRefusal.bodyNotCanonical());\n }\n\n const proofInput: ClientProofInput = {\n method: args.method,\n path: args.path,\n clientId: credentials.clientId,\n keyId: credentials.keyId,\n nonce: credentials.nonce,\n issuedAtMillis: credentials.issuedAtMillis,\n bodySha256: sha256Hex(args.body),\n };\n\n let refusal: ClientProofRefusal | null;\n try\n {\n refusal = args.state.admit({\n clientId: credentials.clientId,\n keyId: credentials.keyId,\n presentedSessionId: credentials.sessionId,\n requiresSession: args.requiresSession,\n proofInput,\n presentedProof: credentials.proof,\n });\n }\n catch\n {\n // A C0 control character in a header field makes the proof input\n // unassemblable — the request is not the shape the contract describes.\n return refused(ClientProofRefusal.unprocessable());\n }\n if (refusal !== null)\n {\n return refused(refusal);\n }\n\n return { admitted: true, value, credentials };\n}\n\nfunction refused(refusal: ClientProofRefusal): Admission\n{\n return { admitted: false, refusal };\n}\n\n/**\n * The contract header fields, or null when any is absent or malformed.\n *\n * Fetch `Headers` folds a repeated field into one comma-joined value, so\n * \"sent more than once\" is not directly observable here; a folded value fails\n * either the issuedAt grammar or proof verification instead.\n */\nfunction readCredentials(headers: Headers): ClientProofCredentials | null\n{\n const profile = headers.get(CLIENT_PROOF_HEADERS.profile);\n const clientId = headers.get(CLIENT_PROOF_HEADERS.clientId);\n const keyId = headers.get(CLIENT_PROOF_HEADERS.keyId);\n const nonce = headers.get(CLIENT_PROOF_HEADERS.nonce);\n const issuedAtRaw = headers.get(CLIENT_PROOF_HEADERS.issuedAtMillis);\n const proof = headers.get(CLIENT_PROOF_HEADERS.proof);\n if (profile === null || clientId === null || keyId === null\n || nonce === null || issuedAtRaw === null || proof === null)\n {\n return null;\n }\n const issuedAtMillis = parseInt64(issuedAtRaw);\n if (issuedAtMillis === null)\n {\n return null;\n }\n\n return {\n profile,\n clientId,\n keyId,\n nonce,\n issuedAtMillis,\n proof,\n sessionId: headers.get(CLIENT_PROOF_HEADERS.session),\n };\n}\n\nfunction parseInt64(raw: string): bigint | null\n{\n if (!/^[+-]?\\d{1,19}$/.test(raw))\n {\n return null;\n }\n const value = BigInt(raw);\n if (value < INT64_MIN || value > INT64_MAX)\n {\n return null;\n }\n\n return value;\n}\n\nfunction isRequestContentType(value: string | null): boolean\n{\n if (value === null)\n {\n return false;\n }\n\n return value.split(';')[0].trim().toLowerCase() === CLIENT_PROOF_CONTENT_TYPE;\n}\n","/**\n * The mobile dev-contract types and operations, decoded from / encoded to\n * canonical values. Strict on purpose: a missing required field, a wrong type\n * or an unknown field is \"not the request type this operation declares\".\n *\n * Source of truth: spfn-mobile Contracts/spfn-mobile-contract.v1.json\n * (dev bundle sha256 07fd8268…a433e45) — `types` and `operations`.\n *\n * @module server/client-proof/contract-types\n */\nimport type { CanonicalObject, CanonicalValue } from './canonical-json';\n\nexport interface ContractOperation\n{\n id: 'auth.clientProof.handshake' | 'echo.send' | 'items.list';\n method: 'POST';\n path: string;\n requiresSession: boolean;\n}\n\nexport const CONTRACT_OPERATIONS: readonly ContractOperation[] = [\n { id: 'auth.clientProof.handshake', method: 'POST', path: '/v1/auth/client-proof/handshake', requiresSession: false },\n { id: 'echo.send', method: 'POST', path: '/v1/echo', requiresSession: true },\n { id: 'items.list', method: 'POST', path: '/v1/items/list', requiresSession: true },\n];\n\n/** The body is canonical JSON but not the declared request type. */\nexport class ContractTypeError extends Error\n{\n constructor()\n {\n super('not the declared contract type');\n this.name = 'ContractTypeError';\n }\n}\n\nexport interface HandshakeRequest\n{\n clientId: string;\n keyId: string;\n nonce: string;\n issuedAtMillis: bigint;\n}\n\nexport interface EchoRequest\n{\n message: string;\n sequence: bigint;\n}\n\nexport interface ListItemsRequest\n{\n limit: bigint;\n cursor?: string;\n}\n\nexport interface ContractItem\n{\n id: string;\n name: string;\n updatedAtMillis: bigint;\n}\n\n// ============================================================================\n// Decoding\n// ============================================================================\n\nexport function decodeHandshakeRequest(value: CanonicalValue): HandshakeRequest\n{\n const members = objectWithKeys(value, ['clientId', 'keyId', 'nonce', 'issuedAtMillis'], []);\n\n return {\n clientId: text(members.get('clientId')),\n keyId: text(members.get('keyId')),\n nonce: text(members.get('nonce')),\n issuedAtMillis: integer(members.get('issuedAtMillis')),\n };\n}\n\nexport function decodeEchoRequest(value: CanonicalValue): EchoRequest\n{\n const members = objectWithKeys(value, ['message', 'sequence'], []);\n\n return {\n message: text(members.get('message')),\n sequence: integer(members.get('sequence')),\n };\n}\n\nexport function decodeListItemsRequest(value: CanonicalValue): ListItemsRequest\n{\n const members = objectWithKeys(value, ['limit'], ['cursor']);\n const request: ListItemsRequest = { limit: integer(members.get('limit')) };\n if (members.has('cursor'))\n {\n request.cursor = text(members.get('cursor'));\n }\n\n return request;\n}\n\nfunction objectWithKeys(\n value: CanonicalValue,\n required: string[],\n optional: string[],\n): CanonicalObject\n{\n if (!(value instanceof Map))\n {\n throw new ContractTypeError();\n }\n for (const key of required)\n {\n if (!value.has(key))\n {\n throw new ContractTypeError();\n }\n }\n for (const key of value.keys())\n {\n if (!required.includes(key) && !optional.includes(key))\n {\n throw new ContractTypeError();\n }\n }\n\n return value;\n}\n\nfunction text(value: CanonicalValue | undefined): string\n{\n if (typeof value !== 'string')\n {\n throw new ContractTypeError();\n }\n\n return value;\n}\n\nfunction integer(value: CanonicalValue | undefined): bigint\n{\n if (typeof value !== 'bigint')\n {\n throw new ContractTypeError();\n }\n\n return value;\n}\n\n// ============================================================================\n// Encoding\n// ============================================================================\n\nexport function encodeHandshakeResponse(sessionId: string, expiresAtMillis: bigint): CanonicalValue\n{\n return new Map<string, CanonicalValue>([\n ['sessionId', sessionId],\n ['expiresAtMillis', expiresAtMillis],\n ]);\n}\n\nexport function encodeEchoResponse(message: string, sequence: bigint, serverTimeMillis: bigint): CanonicalValue\n{\n return new Map<string, CanonicalValue>([\n ['message', message],\n ['sequence', sequence],\n ['serverTimeMillis', serverTimeMillis],\n ]);\n}\n\nexport function encodeListItemsResponse(items: ContractItem[], nextCursor: string | null): CanonicalValue\n{\n const encodedItems: CanonicalValue = items.map((item) => new Map<string, CanonicalValue>([\n ['id', item.id],\n ['name', item.name],\n ['updatedAtMillis', item.updatedAtMillis],\n ]));\n const members = new Map<string, CanonicalValue>([['items', encodedItems]]);\n if (nextCursor !== null)\n {\n members.set('nextCursor', nextCursor);\n }\n\n return members;\n}\n","/**\n * The dev server's test hooks, mirroring the spfn-mobile reference server's\n * `/control` surface route for route so the mobile integration suites can\n * drive either server with only a URL change.\n *\n * `/control` is NOT part of the contract: nothing under it appears in the\n * bundle, no SDK knows it exists, and its answers are plain objects rather\n * than contract envelopes. Every route except the readiness probe requires\n * the per-launch token; the token is never logged.\n *\n * @module server/client-proof/dev-control\n */\nimport { encodeCanonicalJson, parseCanonicalJson, type CanonicalValue } from './canonical-json';\nimport { ClientProofState, TestClock } from './state';\n\nexport const CONTROL_PREFIX = '/control/';\n\nexport const CONTROL_TOKEN_HEADER = 'x-spfn-reference-control';\n\nconst HTTP_OK = 200;\nconst HTTP_BAD_REQUEST = 400;\nconst HTTP_FORBIDDEN = 403;\nconst HTTP_NOT_FOUND = 404;\nconst HTTP_CONFLICT = 409;\n\nconst MAX_CONTROL_BODY_BYTES = 4096;\n\nexport async function handleControlRequest(\n state: ClientProofState,\n controlToken: string,\n path: string,\n request: Request,\n): Promise<Response>\n{\n if (path === '/control/health')\n {\n return answer(HTTP_OK, new Map<string, CanonicalValue>([['status', 'ok']]));\n }\n if (request.headers.get(CONTROL_TOKEN_HEADER) !== controlToken)\n {\n return answer(HTTP_FORBIDDEN, failure('control token'));\n }\n\n const raw = new Uint8Array(await request.arrayBuffer());\n const body = raw.length > MAX_CONTROL_BODY_BYTES ? raw.slice(0, MAX_CONTROL_BODY_BYTES) : raw;\n\n switch (path)\n {\n case '/control/stats':\n return stats(state);\n case '/control/reset':\n state.reset();\n\n return ok();\n case '/control/expire-sessions':\n state.expireSessions();\n\n return ok();\n case '/control/revoke-key':\n return revokeKey(state, body);\n case '/control/session-ttl':\n return sessionTtl(state, body);\n case '/control/hold':\n return hold(state, body);\n case '/control/advance-clock':\n return advanceClock(state, body);\n default:\n return answer(HTTP_NOT_FOUND, failure('unknown control route'));\n }\n}\n\n// ---- routes ----------------------------------------------------------------\n\nfunction stats(state: ClientProofState): Response\n{\n const counters = state.stats();\n\n return answer(HTTP_OK, withOk(new Map<string, CanonicalValue>([\n ['echoCount', BigInt(counters.echoCount)],\n ['handshakeCount', BigInt(counters.handshakeCount)],\n ['itemsListCount', BigInt(counters.itemsListCount)],\n ['liveSessionCount', BigInt(counters.liveSessionCount)],\n ['refusalCount', BigInt(counters.refusalCount)],\n ['requestCount', BigInt(counters.requestCount)],\n ['spentNonceCount', BigInt(counters.spentNonceCount)],\n ])));\n}\n\nfunction revokeKey(state: ClientProofState, body: Uint8Array): Response\n{\n const keyId = stringField(body, 'keyId');\n if (keyId === null)\n {\n return badRequest('keyId');\n }\n state.revokeKey(keyId);\n\n return ok();\n}\n\nfunction sessionTtl(state: ClientProofState, body: Uint8Array): Response\n{\n const ttlMillis = integerField(body, 'ttlMillis');\n if (ttlMillis === null)\n {\n return badRequest('ttlMillis');\n }\n state.setSessionTtlMillis(Number(ttlMillis));\n\n return ok();\n}\n\nfunction hold(state: ClientProofState, body: Uint8Array): Response\n{\n const path = stringField(body, 'path');\n const millis = integerField(body, 'millis');\n const count = integerField(body, 'count');\n if (path === null)\n {\n return badRequest('path');\n }\n if (millis === null)\n {\n return badRequest('millis');\n }\n if (count === null)\n {\n return badRequest('count');\n }\n state.holdPath(path, Number(millis), Number(count));\n\n return ok();\n}\n\n/**\n * Moves a test clock forward. Refused when the server runs on the wall clock,\n * because silently doing nothing is how a test passes for the wrong reason.\n */\nfunction advanceClock(state: ClientProofState, body: Uint8Array): Response\n{\n const clock = state.clockRef;\n if (!(clock instanceof TestClock))\n {\n return answer(HTTP_CONFLICT, failure('server is running on the system clock'));\n }\n const millis = integerField(body, 'millis');\n if (millis === null)\n {\n return badRequest('millis');\n }\n clock.advance(Number(millis));\n\n return ok();\n}\n\n// ---- plumbing --------------------------------------------------------------\n\nfunction members(body: Uint8Array): Map<string, CanonicalValue> | null\n{\n if (body.length === 0)\n {\n return new Map();\n }\n let parsed: CanonicalValue;\n try\n {\n parsed = parseCanonicalJson(body);\n }\n catch\n {\n return null;\n }\n\n return parsed instanceof Map ? parsed : null;\n}\n\nfunction stringField(body: Uint8Array, field: string): string | null\n{\n const value = members(body)?.get(field);\n\n return typeof value === 'string' ? value : null;\n}\n\nfunction integerField(body: Uint8Array, field: string): bigint | null\n{\n const value = members(body)?.get(field);\n\n return typeof value === 'bigint' ? value : null;\n}\n\nfunction badRequest(field: string): Response\n{\n return answer(HTTP_BAD_REQUEST, failure(`missing or malformed field: ${field}`));\n}\n\nfunction ok(): Response\n{\n return answer(HTTP_OK, withOk(new Map()));\n}\n\nfunction failure(reason: string): Map<string, CanonicalValue>\n{\n return new Map<string, CanonicalValue>([['ok', false], ['reason', reason]]);\n}\n\nfunction withOk(extra: Map<string, CanonicalValue>): Map<string, CanonicalValue>\n{\n extra.set('ok', true);\n\n return extra;\n}\n\nfunction answer(status: number, value: Map<string, CanonicalValue>): Response\n{\n const bytes = encodeCanonicalJson(value);\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n\n return new Response(buffer, { status, headers: { 'content-type': 'application/json' } });\n}\n","/**\n * The mobile-contract dev surface: a fetch-style handler exposing the three\n * dev operations (handshake / echo.send / items.list) plus the `/control`\n * test hooks the spfn-mobile integration suites drive.\n *\n * Framework-free on purpose — `fetch(request) => Response` plugs into\n * `@hono/node-server`'s `serve({ fetch })` or any Web-standard runtime, and\n * the contract needs byte-exact control over bodies and envelopes that a\n * validating router would take away.\n *\n * This is a dev/test surface, not a production deployment target: keys are\n * injected at construction, state is in-memory, and `/control` mutates it.\n *\n * @module server/client-proof/dev-handler\n */\nimport { encodeCanonicalJson, type CanonicalValue } from './canonical-json';\nimport { admitClientProofRequest, type Admission } from './admission';\nimport {\n CONTRACT_OPERATIONS,\n ContractTypeError,\n decodeEchoRequest,\n decodeHandshakeRequest,\n decodeListItemsRequest,\n encodeEchoResponse,\n encodeHandshakeResponse,\n encodeListItemsResponse,\n type ContractItem,\n type ContractOperation,\n type ListItemsRequest,\n} from './contract-types';\nimport { ClientProofRefusal, newHexId } from './refusal';\nimport { ClientProofState, type ClientProofStateOptions, TestClock } from './state';\nimport { handleControlRequest, CONTROL_PREFIX } from './dev-control';\n\n/** Far above any contract request and far below anything worth buffering. */\nconst MAX_BODY_BYTES = 1 << 20;\n\nconst HTTP_OK = 200;\n\n/**\n * The items `items.list` pages through — fixed and small on purpose, matching\n * the spfn-mobile reference catalogue byte for byte so an integration test can\n * assert exact values against either server.\n */\nexport const DEV_CATALOGUE: readonly ContractItem[] = [\n { id: 'item-0001', name: 'alpha', updatedAtMillis: 1_750_000_000_001n },\n { id: 'item-0002', name: 'bravo', updatedAtMillis: 1_750_000_000_002n },\n { id: 'item-0003', name: 'charlie', updatedAtMillis: 1_750_000_000_003n },\n { id: 'item-0004', name: 'delta', updatedAtMillis: 1_750_000_000_004n },\n { id: 'item-0005', name: 'echo', updatedAtMillis: 1_750_000_000_005n },\n];\n\n/** The largest `items.list` page this server will answer with. */\nexport const DEV_MAX_LIMIT = 100n;\n\nexport interface ClientProofDevHandlerOptions extends ClientProofStateOptions\n{\n /**\n * Token the `/control` routes require (header `x-spfn-reference-control`).\n * Generated per construction when omitted; never logged.\n */\n controlToken?: string;\n\n /** Disables the `/control` surface entirely. @default true */\n enableControl?: boolean;\n\n /** One line per request: method, path, status. Nothing a request carried. */\n log?: (line: string) => void;\n}\n\nexport interface ClientProofDevHandler\n{\n fetch(request: Request): Promise<Response>;\n state: ClientProofState;\n controlToken: string;\n}\n\nexport function createClientProofDevHandler(options: ClientProofDevHandlerOptions): ClientProofDevHandler\n{\n const state = new ClientProofState(options);\n const controlToken = options.controlToken ?? newHexId();\n const enableControl = options.enableControl ?? true;\n const log = options.log ?? (() => undefined);\n\n async function dispatch(request: Request): Promise<Response>\n {\n state.recordRequest();\n const url = new URL(request.url);\n\n if (enableControl && url.pathname.startsWith(CONTROL_PREFIX))\n {\n return handleControlRequest(state, controlToken, url.pathname, request);\n }\n\n // A query string is refused by omission: no contract path carries one,\n // and a proof is taken over the path alone.\n const operation = url.search === ''\n ? CONTRACT_OPERATIONS.find((op) => op.path === url.pathname && op.method === request.method)\n : undefined;\n if (operation === undefined)\n {\n return refuse(ClientProofRefusal.unroutable());\n }\n\n const body = await readBodyCapped(request);\n if (body === null)\n {\n return refuse(ClientProofRefusal.bodyTooLarge());\n }\n\n // Before verification, so a request a test is holding open has not\n // spent its nonce by the time the client gives up waiting for it.\n await waitOutHold(url.pathname);\n\n const admission = admitClientProofRequest({\n state,\n headers: request.headers,\n method: operation.method,\n path: operation.path,\n requiresSession: operation.requiresSession,\n body,\n });\n if (!admission.admitted)\n {\n return refuse(admission.refusal);\n }\n\n return apply(operation, admission);\n }\n\n function apply(operation: ContractOperation, admission: Extract<Admission, { admitted: true }>): Response\n {\n let value: CanonicalValue;\n try\n {\n if (operation.id === 'auth.clientProof.handshake')\n {\n const request = decodeHandshakeRequest(admission.value);\n // The proof already binds the header identity to the key that\n // signed it, so a body naming a different client is a request\n // whose two halves disagree about who sent it.\n if (request.clientId !== admission.credentials.clientId\n || request.keyId !== admission.credentials.keyId)\n {\n return refuse(ClientProofRefusal.bodyNotTheDeclaredType());\n }\n const opened = state.openSession(request.clientId, request.keyId);\n value = encodeHandshakeResponse(opened.sessionId, BigInt(opened.expiresAtMillis));\n }\n else if (operation.id === 'echo.send')\n {\n const request = decodeEchoRequest(admission.value);\n value = encodeEchoResponse(request.message, request.sequence, BigInt(state.nowMillis()));\n }\n else\n {\n const listed = listItems(decodeListItemsRequest(admission.value));\n if (listed === null)\n {\n return refuse(ClientProofRefusal.bodyNotTheDeclaredType());\n }\n value = listed;\n }\n }\n catch (error)\n {\n if (error instanceof ContractTypeError)\n {\n return refuse(ClientProofRefusal.bodyNotTheDeclaredType());\n }\n\n return refuse(ClientProofRefusal.unprocessable());\n }\n\n state.recordOperation(operation.id);\n\n return contractResponse(HTTP_OK, encodeCanonicalJson(value));\n }\n\n function refuse(refusal: ClientProofRefusal): Response\n {\n state.recordRefusal();\n\n return contractResponse(refusal.httpStatus, refusal.envelopeBytes(newHexId()));\n }\n\n async function waitOutHold(path: string): Promise<void>\n {\n const millis = state.takeHoldMillis(path);\n if (millis > 0)\n {\n await new Promise((resolve) => setTimeout(resolve, millis));\n }\n }\n\n return {\n state,\n controlToken,\n fetch: async (request: Request): Promise<Response> =>\n {\n try\n {\n const response = await dispatch(request);\n log(`${request.method} ${new URL(request.url).pathname} -> ${response.status}`);\n\n return response;\n }\n catch\n {\n // A contract answer rather than a stack trace: an exception\n // message can quote the request that produced it.\n return refuse(ClientProofRefusal.unprocessable());\n }\n },\n };\n}\n\n/**\n * One page of the catalogue, or null when the request is not one this\n * contract describes. An unknown cursor and a limit outside 1…MAX are refused\n * rather than clamped — a server that quietly repaired a request would hide\n * the client bug that produced it.\n */\nfunction listItems(request: ListItemsRequest): CanonicalValue | null\n{\n if (request.limit < 1n || request.limit > DEV_MAX_LIMIT)\n {\n return null;\n }\n let start = 0;\n if (request.cursor !== undefined)\n {\n const index = DEV_CATALOGUE.findIndex((item) => item.id === request.cursor);\n if (index < 0)\n {\n return null;\n }\n start = index + 1;\n }\n const end = Math.min(DEV_CATALOGUE.length, start + Number(request.limit));\n const page = DEV_CATALOGUE.slice(start, end);\n // Present only when a further page exists, so \"nextCursor is absent\" is a\n // fact about the data rather than a value the client has to interpret.\n const nextCursor = end < DEV_CATALOGUE.length && page.length > 0 ? page[page.length - 1].id : null;\n\n return encodeListItemsResponse([...page], nextCursor);\n}\n\nfunction contractResponse(status: number, body: Uint8Array): Response\n{\n return new Response(toArrayBuffer(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n}\n\n/** The body, or null when it is larger than this server will read. */\nasync function readBodyCapped(request: Request): Promise<Uint8Array | null>\n{\n if (request.body === null)\n {\n return new Uint8Array(0);\n }\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;)\n {\n const { done, value } = await reader.read();\n if (done)\n {\n break;\n }\n total += value.length;\n if (total > MAX_BODY_BYTES)\n {\n await reader.cancel();\n\n return null;\n }\n chunks.push(value);\n }\n const body = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks)\n {\n body.set(chunk, offset);\n offset += chunk.length;\n }\n\n return body;\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer\n{\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n}\n\nexport { TestClock };\n","/**\n * Hono middleware adapter for clientProofV1 — the `requiresSession` guard for\n * SPFN servers that mount contract operations as ordinary routes.\n *\n * Runs the full admission sequence over the raw request bytes and, on\n * acceptance, tags the request `clientType: 'mobile'` (the attestation slot\n * PROXY-BACKEND-AUTH-SPEC reserved) and exposes the parsed canonical body and\n * credentials under the `clientProof` context key.\n *\n * hono is imported as types only — the middleware itself is a plain async\n * function, so this module adds no runtime dependency.\n *\n * @module server/client-proof/guard\n */\nimport type { Context, MiddlewareHandler, Next } from 'hono';\n\nimport { admitClientProofRequest, type ClientProofCredentials } from './admission';\nimport type { CanonicalValue } from './canonical-json';\nimport { newHexId } from './refusal';\nimport type { ClientProofState } from './state';\n\n/** What the guard leaves in the context for the route handler. */\nexport interface ClientProofContext\n{\n credentials: ClientProofCredentials;\n\n /** The request body as a canonical value (already byte-verified). */\n value: CanonicalValue;\n}\n\nexport interface ClientProofGuardOptions\n{\n /**\n * The contract path the client signed, when it differs from the mounted\n * path (e.g. behind a stripped ingress prefix). Defaults to the request\n * path.\n */\n contractPath?: string;\n}\n\n/**\n * A guard for operations with `requiresSession: true`.\n *\n * Refusals are answered with the contract envelope and never reach the route.\n */\nexport function createClientProofGuard(\n state: ClientProofState,\n options: ClientProofGuardOptions = {},\n): MiddlewareHandler\n{\n return async (c: Context, next: Next) =>\n {\n const body = new Uint8Array(await c.req.arrayBuffer());\n const admission = admitClientProofRequest({\n state,\n headers: c.req.raw.headers,\n method: c.req.method,\n path: options.contractPath ?? c.req.path,\n requiresSession: true,\n body,\n });\n if (!admission.admitted)\n {\n state.recordRefusal();\n const bytes = admission.refusal.envelopeBytes(newHexId());\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n\n return c.newResponse(buffer, admission.refusal.httpStatus as 401, {\n 'content-type': 'application/json',\n });\n }\n c.set('clientType', 'mobile');\n c.set('clientProof', {\n credentials: admission.credentials,\n value: admission.value,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SAC1B;AACI,UAAM,OAAO,IAAI,WAAW,MAAM,EAAE,IAAI,YAAY,CAAC;AACrD,UAAM,YAAY,wBAAwB;AAAA,MACtC;AAAA,MACA,SAAS,EAAE,IAAI,IAAI;AAAA,MACnB,QAAQ,EAAE,IAAI;AAAA,MACd,MAAM,QAAQ,gBAAgB,EAAE,IAAI;AAAA,MACpC,iBAAiB;AAAA,MACjB;AAAA,IACJ,CAAC;AACD,QAAI,CAAC,UAAU,UACf;AACI,YAAM,cAAc;AACpB,YAAM,QAAQ,UAAU,QAAQ,cAAc,SAAS,CAAC;AACxD,YAAM,SAAS,MAAM,OAAO,MAAM,MAAM,YAAY,MAAM,aAAa,MAAM,UAAU;AAEvF,aAAO,EAAE,YAAY,QAAQ,UAAU,QAAQ,YAAmB;AAAA,QAC9D,gBAAgB;AAAA,MACpB,CAAC;AAAA,IACL;AACA,MAAE,IAAI,cAAc,QAAQ;AAC5B,MAAE,IAAI,eAAe;AAAA,MACjB,aAAa,UAAU;AAAA,MACvB,OAAO,UAAU;AAAA,IACrB,CAA8B;AAC9B,UAAM,KAAK;AAEX,WAAO;AAAA,EACX;AACJ;","names":["text","members","hold","INT64_MIN","INT64_MAX","members","HTTP_OK"]}
|
package/dist/server.js
CHANGED
|
@@ -10097,8 +10097,9 @@ var naverProvider = {
|
|
|
10097
10097
|
return {
|
|
10098
10098
|
providerUserId: profile.id,
|
|
10099
10099
|
email: typeof profile.email === "string" ? profile.email : null,
|
|
10100
|
-
//
|
|
10101
|
-
|
|
10100
|
+
// 네이버 프로필 이메일은 네이버 계정 이메일이거나 인증 절차를 거친 연락처
|
|
10101
|
+
// 이메일이다 — 존재하면 검증된 것으로 취급한다(카카오와 같은 신뢰 수준).
|
|
10102
|
+
emailVerified: typeof profile.email === "string",
|
|
10102
10103
|
name: typeof profile.name === "string" ? profile.name : typeof profile.nickname === "string" ? profile.nickname : void 0,
|
|
10103
10104
|
avatar: typeof profile.profile_image === "string" ? profile.profile_image : void 0
|
|
10104
10105
|
};
|
|
@@ -10223,6 +10224,7 @@ async function oauthCallbackService(params) {
|
|
|
10223
10224
|
refreshToken: tokens.refreshToken ?? existingSocialAccount.refreshToken,
|
|
10224
10225
|
tokenExpiresAt: tokenExpiryDate(tokens.expiresIn)
|
|
10225
10226
|
});
|
|
10227
|
+
await backfillVerifiedEmail(userId, identity);
|
|
10226
10228
|
} else {
|
|
10227
10229
|
const result = await createOrLinkUser(provider, identity, tokens, stateData.metadata);
|
|
10228
10230
|
userId = result.userId;
|
|
@@ -10280,6 +10282,30 @@ async function assertActiveForOAuthSession(userId) {
|
|
|
10280
10282
|
}
|
|
10281
10283
|
throw new AccountDisabledError2({ status: user.status });
|
|
10282
10284
|
}
|
|
10285
|
+
async function backfillVerifiedEmail(userId, identity) {
|
|
10286
|
+
if (!identity.email || !identity.emailVerified) {
|
|
10287
|
+
return;
|
|
10288
|
+
}
|
|
10289
|
+
const user = await usersRepository.findById(userId);
|
|
10290
|
+
if (!user || user.email) {
|
|
10291
|
+
return;
|
|
10292
|
+
}
|
|
10293
|
+
const emailOwner = await usersRepository.findByEmail(identity.email);
|
|
10294
|
+
if (emailOwner && emailOwner.id !== userId) {
|
|
10295
|
+
return;
|
|
10296
|
+
}
|
|
10297
|
+
try {
|
|
10298
|
+
await usersRepository.updateById(userId, {
|
|
10299
|
+
email: identity.email,
|
|
10300
|
+
emailVerifiedAt: /* @__PURE__ */ new Date()
|
|
10301
|
+
});
|
|
10302
|
+
} catch (error) {
|
|
10303
|
+
authLogger.service.warn("Verified-email backfill failed; continuing login", {
|
|
10304
|
+
userId: String(userId),
|
|
10305
|
+
error: error instanceof Error ? error.message : String(error)
|
|
10306
|
+
});
|
|
10307
|
+
}
|
|
10308
|
+
}
|
|
10283
10309
|
async function createOrLinkUser(provider, identity, tokens, metadata) {
|
|
10284
10310
|
const existingUser = identity.email ? await usersRepository.findByEmail(identity.email) : null;
|
|
10285
10311
|
let userId;
|
|
@@ -10425,6 +10451,7 @@ async function persistNativeLogin(identity, params) {
|
|
|
10425
10451
|
let isNewUser = false;
|
|
10426
10452
|
if (existing) {
|
|
10427
10453
|
userId = existing.userId;
|
|
10454
|
+
await backfillVerifiedEmail(userId, identity);
|
|
10428
10455
|
} else {
|
|
10429
10456
|
const result = await createOrLinkUser(params.provider, identity, void 0, params.metadata);
|
|
10430
10457
|
userId = result.userId;
|