@spfn/auth 0.2.0-beta.9 → 0.2.0-beta.90

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 (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +984 -1743
  3. package/dist/authenticate-CnccboAg.d.ts +1383 -0
  4. package/dist/client-proof.d.ts +677 -0
  5. package/dist/client-proof.js +1814 -0
  6. package/dist/client-proof.js.map +1 -0
  7. package/dist/config.d.ts +487 -39
  8. package/dist/config.js +243 -29
  9. package/dist/config.js.map +1 -1
  10. package/dist/errors.d.ts +208 -3
  11. package/dist/errors.js +140 -1
  12. package/dist/errors.js.map +1 -1
  13. package/dist/index.d.ts +391 -109
  14. package/dist/index.js +186 -7
  15. package/dist/index.js.map +1 -1
  16. package/dist/nextjs/api.js +591 -61
  17. package/dist/nextjs/api.js.map +1 -1
  18. package/dist/nextjs/client.d.ts +28 -0
  19. package/dist/nextjs/client.js +80 -0
  20. package/dist/nextjs/client.js.map +1 -0
  21. package/dist/nextjs/server.d.ts +92 -3
  22. package/dist/nextjs/server.js +288 -24
  23. package/dist/nextjs/server.js.map +1 -1
  24. package/dist/server.d.ts +2495 -1089
  25. package/dist/server.js +6212 -1499
  26. package/dist/server.js.map +1 -1
  27. package/dist/session-CFK4BT25.d.ts +53 -0
  28. package/dist/types-CD95yudz.d.ts +98 -0
  29. package/migrations/20251125021229_premium_famine/snapshot.json +2641 -0
  30. package/migrations/20260225130050_smooth_the_fury/migration.sql +3 -0
  31. package/migrations/20260225130050_smooth_the_fury/snapshot.json +2686 -0
  32. package/migrations/20260308141417_deep_iceman/migration.sql +11 -0
  33. package/migrations/20260308141417_deep_iceman/snapshot.json +2686 -0
  34. package/migrations/20260308151309_perfect_deathbird/migration.sql +3 -0
  35. package/migrations/20260308151309_perfect_deathbird/snapshot.json +2731 -0
  36. package/migrations/20260308201135_concerned_rawhide_kid/migration.sql +5 -0
  37. package/migrations/20260308201135_concerned_rawhide_kid/snapshot.json +2786 -0
  38. package/migrations/20260629103209_lethal_lifeguard/migration.sql +32 -0
  39. package/migrations/20260629103209_lethal_lifeguard/snapshot.json +2786 -0
  40. package/migrations/20260709073531_easy_hardball/migration.sql +24 -0
  41. package/migrations/20260709073531_easy_hardball/snapshot.json +3119 -0
  42. package/migrations/20260714081434_glossy_major_mapleleaf/migration.sql +1 -0
  43. package/migrations/20260714081434_glossy_major_mapleleaf/snapshot.json +3112 -0
  44. package/migrations/20260804105939_amazing_bushwacker/migration.sql +3 -0
  45. package/migrations/20260804105939_amazing_bushwacker/snapshot.json +3112 -0
  46. package/migrations/20260804110033_fat_piledriver/migration.sql +2 -0
  47. package/migrations/20260804110033_fat_piledriver/snapshot.json +3138 -0
  48. package/package.json +60 -46
  49. package/dist/dto-CRlgoCP5.d.ts +0 -645
  50. package/migrations/meta/0000_snapshot.json +0 -1632
  51. package/migrations/meta/_journal.json +0 -13
  52. /package/migrations/{0000_premium_famine.sql → 20251125021229_premium_famine/migration.sql} +0 -0
@@ -0,0 +1,677 @@
1
+ import { KeyObject } from 'node:crypto';
2
+ import { MiddlewareHandler } from 'hono';
3
+
4
+ /**
5
+ * SPFN-CANON-JSON-1 — the canonical JSON form the mobile contract pins.
6
+ *
7
+ * The rules (contracts/mobile/spfn-mobile-contract.json `canonicalJson`):
8
+ * - object keys sorted ascending by UTF-8 byte sequence
9
+ * - no insignificant whitespace
10
+ * - numbers are signed 64-bit integers only
11
+ * - string escapes: `"` and `\` escaped; C0 controls use \b \f \n \r \t where
12
+ * defined and lowercase \u00XX otherwise; every other scalar is emitted
13
+ * literally as UTF-8
14
+ * - absent optional fields are omitted, never null
15
+ *
16
+ * JSON.parse cannot implement this: it loses int64 precision, accepts duplicate
17
+ * keys and (in V8) raw control characters, so both directions are hand-rolled.
18
+ * A proof binds the received bytes — parse-then-re-encode equality is what makes
19
+ * canonicity a rule a client can actually break.
20
+ *
21
+ * @module server/client-proof/canonical-json
22
+ */
23
+ type CanonicalObject = Map<string, CanonicalValue>;
24
+ type CanonicalValue = null | boolean | bigint | string | CanonicalValue[] | CanonicalObject;
25
+ /**
26
+ * Parse failures carry the code the mobile conformance fixtures name
27
+ * (Contracts/fixtures/canonical/rejects.json), so the fixtures can assert on it.
28
+ */
29
+ type CanonicalJsonErrorCode = 'DUPLICATE_KEY' | 'NON_INTEGER_NUMBER' | 'TRAILING_CONTENT' | 'UNEXPECTED_END' | 'INVALID_TOKEN' | 'INVALID_ESCAPE' | 'INTEGER_OUT_OF_RANGE' | 'INVALID_UTF8';
30
+ declare class CanonicalJsonError extends Error {
31
+ readonly code: CanonicalJsonErrorCode;
32
+ constructor(code: CanonicalJsonErrorCode);
33
+ }
34
+ /**
35
+ * Parse bytes as SPFN-CANON-JSON-1.
36
+ *
37
+ * Arbitrary whitespace and key order are accepted here — parsing alone proves
38
+ * nothing about canonicity. Callers that must enforce it re-encode the result
39
+ * and compare bytes (see `isCanonicalBytes`).
40
+ */
41
+ declare function parseCanonicalJson(bytes: Uint8Array): CanonicalValue;
42
+ /** True when `bytes` are exactly the canonical encoding of the value they parse to. */
43
+ declare function isCanonicalBytes(bytes: Uint8Array, value: CanonicalValue): boolean;
44
+ /** Encode a value as SPFN-CANON-JSON-1 bytes. */
45
+ declare function encodeCanonicalJson(value: CanonicalValue): Uint8Array;
46
+
47
+ /**
48
+ * SPFN-PROOF-INPUT-1 — proof-input assembly and verification for clientProofV1.
49
+ *
50
+ * The proof input is 8 fields joined by `\n` in fixed order: profile, method,
51
+ * path, clientId, keyId, nonce, issuedAtMillis, bodySha256. Any C0 control
52
+ * character in any field is a hard refusal (the separator would otherwise be
53
+ * ambiguous), never something to escape. The proof is an ECDSA P-256 signature
54
+ * with SHA-256 over the canonical input's UTF-8 bytes, wire-encoded as the raw
55
+ * `r ‖ s` 64 bytes in base16-lower (128 hex characters). DER is never accepted
56
+ * on the wire: a platform signer that emits DER (Java `Signature`) converts to
57
+ * raw before sending. Low-S normalization is not required — uniqueness is owned
58
+ * by the nonce and replay window, so signature malleability cannot replay.
59
+ *
60
+ * @module server/client-proof/proof
61
+ */
62
+
63
+ /** The only auth profile this module implements. */
64
+ declare const CLIENT_PROOF_PROFILE = "clientProofV1";
65
+ /** `bodySha256` when an operation carries no body: 64 zero characters. */
66
+ declare const ABSENT_BODY_SHA256: string;
67
+ /** The contract's `clientProofV1.replayWindowMillis`. */
68
+ declare const DEFAULT_REPLAY_WINDOW_MILLIS = 300000;
69
+ /** Raw `r ‖ s`: two 32-byte big-endian integers, always exactly this long. */
70
+ declare const PROOF_SIGNATURE_BYTES = 64;
71
+ /** The wire form is base16-lower of the raw signature: 128 hex characters. */
72
+ declare const PROOF_SIGNATURE_HEX_LENGTH: number;
73
+ interface ClientProofInput {
74
+ method: string;
75
+ path: string;
76
+ clientId: string;
77
+ keyId: string;
78
+ nonce: string;
79
+ issuedAtMillis: bigint;
80
+ bodySha256: string;
81
+ }
82
+ /** A C0 control character appeared in a proof field. */
83
+ declare class ProofInputError extends Error {
84
+ constructor();
85
+ }
86
+ /**
87
+ * The canonical proof-input string the signature is taken over.
88
+ *
89
+ * @throws ProofInputError when any field contains a C0 control character.
90
+ */
91
+ declare function canonicalProofInput(input: ClientProofInput): string;
92
+ /**
93
+ * The contract's public-key representation — SPKI DER, base64 (the same
94
+ * representation `user_public_keys` and the web ES256 path store) — as a key
95
+ * object. Anything that is not a P-256 EC key is refused at parse time, so a
96
+ * key that could never verify a proof is never registered.
97
+ *
98
+ * @throws when the input is not base64 SPKI DER naming a P-256 key.
99
+ */
100
+ declare function parseClientProofPublicKey(spkiDerBase64: string): KeyObject;
101
+ /**
102
+ * Verifies a presented proof against `input` and a registered public key.
103
+ *
104
+ * The input is assembled first, so a C0 control character throws no matter
105
+ * what was presented — an unassemblable input is a contract violation, never
106
+ * a proof answer. Then the wire-format gate: a value that is not exactly 128
107
+ * lowercase hex characters — a DER signature, a truncated one, uppercase hex —
108
+ * is invalid before any cryptography happens.
109
+ *
110
+ * @throws ProofInputError when an input field contains a C0 control character.
111
+ */
112
+ declare function verifyClientProof(input: ClientProofInput, presentedProof: string, publicKey: KeyObject): boolean;
113
+ /**
114
+ * Signs `input` with a PKCS#8 DER base64 private key, producing the wire form
115
+ * (raw `r ‖ s`, base16-lower).
116
+ *
117
+ * The verifying half's counterpart, here for tests and dev clients — a
118
+ * production signer lives in the mobile SDKs against hardware-held keys.
119
+ */
120
+ declare function signClientProof(input: ClientProofInput, privateKeyPkcs8DerBase64: string): string;
121
+ /** Lowercase base16 SHA-256 of `bytes`. */
122
+ declare function sha256Hex(bytes: Uint8Array): string;
123
+
124
+ /** The six wire codes. The SDKs classify by code, never HTTP status. */
125
+ type ClientProofErrorCode = 'PROOF_INVALID' | 'PROOF_REPLAYED' | 'PROOF_EXPIRED' | 'SESSION_REVOKED' | 'PROFILE_REJECTED' | 'CONTRACT_UNSUPPORTED';
126
+ /** 128 random bits as lowercase base16 — request ids and control tokens. */
127
+ declare function newHexId(): string;
128
+ declare class ClientProofRefusal {
129
+ readonly code: ClientProofErrorCode;
130
+ readonly message: string;
131
+ constructor(code: ClientProofErrorCode, message: string);
132
+ get httpStatus(): number;
133
+ /** The canonical bytes of `{"error":{"code":…,"message":…,"requestId":…}}`. */
134
+ envelopeBytes(requestId: string): Uint8Array;
135
+ /** Nothing request-derived reaches a log through this. */
136
+ toString(): string;
137
+ static unroutable(): ClientProofRefusal;
138
+ static malformedHeaders(): ClientProofRefusal;
139
+ static missingContentType(): ClientProofRefusal;
140
+ static bodyTooLarge(): ClientProofRefusal;
141
+ /**
142
+ * The body parsed but its bytes are not the canonical form of what it
143
+ * parsed to. Not PROOF_INVALID even though it is discovered next to the
144
+ * proof: the proof over these bytes verifies perfectly well, and an
145
+ * auth-family answer would tell the client to re-handshake and send the
146
+ * same non-canonical bytes again.
147
+ */
148
+ static bodyNotCanonical(): ClientProofRefusal;
149
+ static bodyNotTheDeclaredType(): ClientProofRefusal;
150
+ static sessionHeaderMisplaced(): ClientProofRefusal;
151
+ static unprocessable(): ClientProofRefusal;
152
+ /**
153
+ * A client that ships separately from the server said nothing about which
154
+ * contract it was built against. Without it the server cannot tell whether
155
+ * the two ends agree, and answering as though they do is what produces the
156
+ * undecodable body this check exists to replace.
157
+ */
158
+ static contractVersionMissing(): ClientProofRefusal;
159
+ static contractVersionUnsupported(): ClientProofRefusal;
160
+ static profileRejected(): ClientProofRefusal;
161
+ static sessionRevoked(): ClientProofRefusal;
162
+ static proofExpired(): ClientProofRefusal;
163
+ static proofReplayed(): ClientProofRefusal;
164
+ static proofInvalid(): ClientProofRefusal;
165
+ }
166
+
167
+ /** Millisecond clock. Injectable so expiry paths are testable without waiting. */
168
+ interface ClientProofClock {
169
+ nowMillis(): number;
170
+ }
171
+ declare function systemClock(): ClientProofClock;
172
+ /** A clock a test (or the dev control surface) can move forward. */
173
+ declare class TestClock implements ClientProofClock {
174
+ private millis;
175
+ constructor(millis: number);
176
+ nowMillis(): number;
177
+ advance(byMillis: number): void;
178
+ }
179
+ /** What `stats()` reports. Counters only; nothing a request carried. */
180
+ interface ClientProofStats {
181
+ requestCount: number;
182
+ handshakeCount: number;
183
+ echoCount: number;
184
+ itemsListCount: number;
185
+ refusalCount: number;
186
+ liveSessionCount: number;
187
+ spentNonceCount: number;
188
+ }
189
+ interface ClientProofStateOptions {
190
+ /**
191
+ * keyId → registered public key, as SPKI DER base64. The private half
192
+ * never reaches the server: a client generates its keypair (hardware-held
193
+ * on mobile) and only the public key is registered — at construction here,
194
+ * or later through `registerPublicKey` (the dev `/control/register-key`
195
+ * route).
196
+ */
197
+ publicKeys: Record<string, string>;
198
+ clock?: ClientProofClock;
199
+ /** @default 600000 */
200
+ sessionTtlMillis?: number;
201
+ /** The contract's replay window. @default 300000 */
202
+ replayWindowMillis?: number;
203
+ }
204
+ declare const DEFAULT_SESSION_TTL_MILLIS = 600000;
205
+ declare class ClientProofState {
206
+ readonly replayWindowMillis: number;
207
+ private readonly clock;
208
+ private readonly initialPublicKeys;
209
+ private readonly publicKeys;
210
+ private readonly sessions;
211
+ /** The replay ledger — the shared memory implementation, used dev-only here. */
212
+ private readonly spentNonces;
213
+ private readonly revokedKeyIds;
214
+ private readonly holds;
215
+ private readonly initialSessionTtlMillis;
216
+ private sessionTtlMillis;
217
+ private requestCount;
218
+ private handshakeCount;
219
+ private echoCount;
220
+ private itemsListCount;
221
+ private refusalCount;
222
+ constructor(options: ClientProofStateOptions);
223
+ /**
224
+ * Registers (or replaces) the public key `keyId` presents proofs under.
225
+ *
226
+ * @throws when the key is not base64 SPKI DER naming a P-256 key.
227
+ */
228
+ registerPublicKey(keyId: string, publicKeySpkiDerBase64: string): void;
229
+ /**
230
+ * Runs the contract's checks in the contract's order and returns the
231
+ * refusal, or null when the request is admitted (spending its nonce).
232
+ */
233
+ admit(args: {
234
+ clientId: string;
235
+ keyId: string;
236
+ presentedSessionId: string | null;
237
+ requiresSession: boolean;
238
+ proofInput: ClientProofInput;
239
+ presentedProof: string;
240
+ }): ClientProofRefusal | null;
241
+ /** Opens a session and returns its id and the expiry the server advertises. */
242
+ openSession(clientId: string, keyId: string): {
243
+ sessionId: string;
244
+ expiresAtMillis: number;
245
+ };
246
+ /** Test hook: installs a session with a chosen id (wire-fixture replays). */
247
+ seedSession(sessionId: string, clientId: string, keyId: string, expiresAtMillis: number): void;
248
+ /** Drops every session, as a restart would. Advertised expiries stay told. */
249
+ expireSessions(): void;
250
+ /** Revokes a key and drops the sessions it opened. */
251
+ revokeKey(keyId: string): void;
252
+ setSessionTtlMillis(millis: number): void;
253
+ /** Returns the state to how it started, counters and registered keys included. */
254
+ reset(): void;
255
+ /** Makes the next `count` requests to `path` wait `millis` before processing. */
256
+ holdPath(path: string, millis: number, count: number): void;
257
+ /** Consumes one configured delay for `path`; returns how long to wait, or 0. */
258
+ takeHoldMillis(path: string): number;
259
+ recordRequest(): void;
260
+ recordOperation(operationId: string): void;
261
+ recordRefusal(): void;
262
+ stats(): ClientProofStats;
263
+ nowMillis(): number;
264
+ /** The clock, exposed for the dev control surface's advance-clock route. */
265
+ get clockRef(): ClientProofClock;
266
+ /**
267
+ * Drops what can no longer affect an answer. The nonce predicate is the
268
+ * exact negation of the window check in `admit`: an entry is dropped only
269
+ * once a proof carrying that issuedAtMillis would be refused as expired
270
+ * anyway. Dropping one moment earlier would let a nonce inside the window
271
+ * be spent twice.
272
+ */
273
+ private prune;
274
+ }
275
+
276
+ /**
277
+ * The checks between a clientProofV1 request arriving and being applied.
278
+ *
279
+ * Shape first, then the profile allowlist, then the proof. That order is
280
+ * forced: none of the proof checks can run until the fields they read are
281
+ * known to be present and the body is known to be the bytes the digest is
282
+ * supposed to cover. The order *inside* the proof checks is the contract's and
283
+ * lives in `ClientProofState.admit`.
284
+ *
285
+ * @module server/client-proof/admission
286
+ */
287
+
288
+ /** D23 wire-header names, ratified as proposed by the mobile dev bundle. */
289
+ declare const CLIENT_PROOF_HEADERS: {
290
+ readonly profile: "x-spfn-auth-profile";
291
+ readonly clientId: "x-spfn-client-id";
292
+ readonly keyId: "x-spfn-key-id";
293
+ readonly nonce: "x-spfn-nonce";
294
+ readonly issuedAtMillis: "x-spfn-issued-at";
295
+ readonly proof: "x-spfn-proof";
296
+ readonly session: "x-spfn-session";
297
+ };
298
+ declare const CLIENT_PROOF_CONTENT_TYPE = "application/json";
299
+ /** The contract header fields one request presented. */
300
+ interface ClientProofCredentials {
301
+ profile: string;
302
+ clientId: string;
303
+ keyId: string;
304
+ nonce: string;
305
+ issuedAtMillis: bigint;
306
+ proof: string;
307
+ sessionId: string | null;
308
+ }
309
+ type Admission = {
310
+ admitted: false;
311
+ refusal: ClientProofRefusal;
312
+ } | {
313
+ admitted: true;
314
+ value: CanonicalValue;
315
+ credentials: ClientProofCredentials;
316
+ };
317
+ /**
318
+ * Runs every check for one operation over already-read body bytes.
319
+ *
320
+ * `path` must be the operation's contract path (what the client signed), not a
321
+ * proxied or rewritten one.
322
+ */
323
+ declare function admitClientProofRequest(args: {
324
+ state: ClientProofState;
325
+ headers: Headers;
326
+ method: string;
327
+ path: string;
328
+ requiresSession: boolean;
329
+ body: Uint8Array;
330
+ }): Admission;
331
+ /**
332
+ * The contract header fields, or null when any is absent or malformed.
333
+ *
334
+ * Fetch `Headers` folds a repeated field into one comma-joined value, so
335
+ * "sent more than once" is not directly observable here; a folded value fails
336
+ * either the issuedAt grammar or proof verification instead.
337
+ *
338
+ * Exported for the authenticate middleware's profile path, which runs the
339
+ * same shape checks over arbitrary routes.
340
+ */
341
+ declare function readCredentials(headers: Headers): ClientProofCredentials | null;
342
+ /** Exported for the authenticate middleware's profile path. */
343
+ declare function isRequestContentType(value: string | null): boolean;
344
+
345
+ /**
346
+ * The ledger key. `JSON.stringify` of the pair, so no crafted clientId/nonce
347
+ * concatenation can collide with another pair — the fields are checked for C0
348
+ * controls only later, at proof verification, so the key must be unambiguous
349
+ * for arbitrary strings.
350
+ */
351
+ declare function replayLedgerKey(clientId: string, nonce: string): string;
352
+ /**
353
+ * What the middleware's replay ledger must answer. Both methods may reject;
354
+ * the caller refuses the request when they do (fail-closed).
355
+ */
356
+ interface ClientProofReplayStore {
357
+ /** True when (clientId, nonce) was already spent inside the window. */
358
+ isSpent(clientId: string, nonce: string): Promise<boolean>;
359
+ /**
360
+ * Records the pair as spent. False when it was already spent — the caller
361
+ * lost a race and must answer PROOF_REPLAYED, not accept twice.
362
+ */
363
+ spend(clientId: string, nonce: string): Promise<boolean>;
364
+ }
365
+ /**
366
+ * The in-memory ledger — the single implementation of the window semantics.
367
+ *
368
+ * Entries carry the millisecond they were recorded at; `prune` drops an entry
369
+ * only once a proof carrying that timestamp would be refused as expired
370
+ * anyway (the exact negation of the admission window check). All methods are
371
+ * synchronous so `ClientProofState.admit` can stay atomic on Node's single
372
+ * thread.
373
+ */
374
+ declare class MemoryReplayLedger {
375
+ /** replayLedgerKey(...) → the millis it was spent at. */
376
+ private readonly spent;
377
+ isSpent(clientId: string, nonce: string): boolean;
378
+ /** Records the pair at `atMillis`; false when it was already spent. */
379
+ spend(clientId: string, nonce: string, atMillis: number): boolean;
380
+ /** Drops entries older than the window, judged against `nowMillis`. */
381
+ prune(nowMillis: number, windowMillis: number): void;
382
+ get size(): number;
383
+ clear(): void;
384
+ }
385
+ /**
386
+ * The default store: a process-local `MemoryReplayLedger` on the wall clock.
387
+ *
388
+ * Correct for a single process. Behind a multi-instance deployment each
389
+ * instance keeps its own ledger, so a replay against a *different* instance
390
+ * is not seen — that deployment opts into `RedisReplayStore`.
391
+ */
392
+ declare class MemoryReplayStore implements ClientProofReplayStore {
393
+ private readonly windowMillis;
394
+ private readonly ledger;
395
+ constructor(windowMillis?: number);
396
+ isSpent(clientId: string, nonce: string): Promise<boolean>;
397
+ spend(clientId: string, nonce: string): Promise<boolean>;
398
+ }
399
+ /**
400
+ * The opt-in shared ledger over `getCache()` (ioredis): `SET NX PX <window>`.
401
+ *
402
+ * The key hashes the pair, so arbitrary clientId/nonce strings become short,
403
+ * safe Redis keys with no ambiguity. `PX` makes Redis expire the entry itself
404
+ * exactly when a proof reusing the nonce would pass the window check again.
405
+ *
406
+ * Fail-closed by construction: when the cache is not configured or a command
407
+ * rejects, the error propagates and the caller refuses the request. Nothing
408
+ * here answers "not spent" on a store it could not reach.
409
+ */
410
+ declare class RedisReplayStore implements ClientProofReplayStore {
411
+ private readonly windowMillis;
412
+ constructor(windowMillis?: number);
413
+ isSpent(clientId: string, nonce: string): Promise<boolean>;
414
+ spend(clientId: string, nonce: string): Promise<boolean>;
415
+ private cache;
416
+ private key;
417
+ }
418
+ /**
419
+ * Installs the replay store the authenticate middleware uses. Pass
420
+ * `new RedisReplayStore()` to opt into the shared ledger; pass null to return
421
+ * to the in-memory default.
422
+ */
423
+ declare function configureClientProofReplayStore(store: ClientProofReplayStore | null): void;
424
+ /** The configured store, or a lazily created in-memory default. */
425
+ declare function getClientProofReplayStore(): ClientProofReplayStore;
426
+
427
+ /**
428
+ * The mobile dev-contract types and operations, decoded from / encoded to
429
+ * canonical values. Strict on purpose: a missing required field, a wrong type
430
+ * or an unknown field is "not the request type this operation declares".
431
+ *
432
+ * This module is the source of truth for `operations`. The exported contract
433
+ * bundle (`contracts/mobile/spfn-mobile-contract.json`) is generated from it
434
+ * by `contract-bundle.ts`; spfn-mobile consumes that export rather than the
435
+ * other way round.
436
+ *
437
+ * @module server/client-proof/contract-types
438
+ */
439
+
440
+ interface ContractOperation {
441
+ id: 'auth.clientProof.handshake' | 'echo.send' | 'items.list' | 'auth.enroll.register' | 'auth.enroll.login' | 'auth.enroll.oauthNative' | 'auth.keys.rotate' | 'auth.keys.list' | 'auth.keys.revoke' | 'auth.keys.revokeAll';
442
+ method: 'POST';
443
+ path: string;
444
+ /**
445
+ * How a call is admitted. `clientProofV1` operations run the proof
446
+ * admission order; `none` operations are the unproven class — accepted
447
+ * with neither proof headers nor a session header, because enrollment is
448
+ * called before any key exists to sign with.
449
+ */
450
+ authProfile: 'clientProofV1' | 'none';
451
+ requiresSession: boolean;
452
+ requestType: string;
453
+ responseType: string;
454
+ summary: string;
455
+ }
456
+ declare const CONTRACT_OPERATIONS: readonly ContractOperation[];
457
+ /**
458
+ * The `/_auth` surface exported into the mobile contract: enrollment, login
459
+ * and key rotation. These are ordinary SPFN REST routes, not canonical-JSON
460
+ * operations — the dev handler never serves them, and their wire rules are
461
+ * the `restOperations` section of the bundle, not `canonicalJson`.
462
+ *
463
+ * The three `authProfile: 'none'` operations are the unproven class: they are
464
+ * accepted with neither proof headers nor a session header, because they are
465
+ * how a client obtains a key in the first place. `auth.keys.rotate` requires
466
+ * an authenticated caller (a clientProofV1 proof on this surface); an
467
+ * unproven call to it is refused like any failed admission.
468
+ */
469
+ declare const AUTH_SURFACE_OPERATIONS: readonly ContractOperation[];
470
+ /** The body is canonical JSON but not the declared request type. */
471
+ declare class ContractTypeError extends Error {
472
+ constructor();
473
+ }
474
+ interface HandshakeRequest {
475
+ clientId: string;
476
+ keyId: string;
477
+ nonce: string;
478
+ issuedAtMillis: bigint;
479
+ }
480
+ interface EchoRequest {
481
+ message: string;
482
+ sequence: bigint;
483
+ }
484
+ interface ListItemsRequest {
485
+ limit: bigint;
486
+ cursor?: string;
487
+ }
488
+ interface ContractItem {
489
+ id: string;
490
+ name: string;
491
+ updatedAtMillis: bigint;
492
+ }
493
+ declare function decodeHandshakeRequest(value: CanonicalValue): HandshakeRequest;
494
+ declare function decodeEchoRequest(value: CanonicalValue): EchoRequest;
495
+ declare function decodeListItemsRequest(value: CanonicalValue): ListItemsRequest;
496
+ declare function encodeHandshakeResponse(sessionId: string, expiresAtMillis: bigint): CanonicalValue;
497
+ declare function encodeEchoResponse(message: string, sequence: bigint, serverTimeMillis: bigint): CanonicalValue;
498
+ declare function encodeListItemsResponse(items: ContractItem[], nextCursor: string | null): CanonicalValue;
499
+
500
+ /**
501
+ * The items `items.list` pages through — fixed and small on purpose, matching
502
+ * the spfn-mobile reference catalogue byte for byte so an integration test can
503
+ * assert exact values against either server.
504
+ */
505
+ declare const DEV_CATALOGUE: readonly ContractItem[];
506
+ /** The largest `items.list` page this server will answer with. */
507
+ declare const DEV_MAX_LIMIT = 100n;
508
+ interface ClientProofDevHandlerOptions extends ClientProofStateOptions {
509
+ /**
510
+ * Token the `/control` routes require (header `x-spfn-reference-control`).
511
+ * Generated per construction when omitted; never logged.
512
+ */
513
+ controlToken?: string;
514
+ /** Disables the `/control` surface entirely. @default true */
515
+ enableControl?: boolean;
516
+ /** One line per request: method, path, status. Nothing a request carried. */
517
+ log?: (line: string) => void;
518
+ }
519
+ interface ClientProofDevHandler {
520
+ fetch(request: Request): Promise<Response>;
521
+ state: ClientProofState;
522
+ controlToken: string;
523
+ }
524
+ declare function createClientProofDevHandler(options: ClientProofDevHandlerOptions): ClientProofDevHandler;
525
+
526
+ declare const CONTROL_PREFIX = "/control/";
527
+ declare const CONTROL_TOKEN_HEADER = "x-spfn-reference-control";
528
+
529
+ /**
530
+ * Hono middleware adapter for clientProofV1 — the `requiresSession` guard for
531
+ * SPFN servers that mount contract operations as ordinary routes.
532
+ *
533
+ * Runs the full admission sequence over the raw request bytes and, on
534
+ * acceptance, tags the request `clientType: 'mobile'` (the attestation slot
535
+ * PROXY-BACKEND-AUTH-SPEC reserved) and exposes the parsed canonical body and
536
+ * credentials under the `clientProof` context key.
537
+ *
538
+ * hono is imported as types only — the middleware itself is a plain async
539
+ * function, so this module adds no runtime dependency.
540
+ *
541
+ * @module server/client-proof/guard
542
+ */
543
+
544
+ /** What the guard leaves in the context for the route handler. */
545
+ interface ClientProofContext {
546
+ credentials: ClientProofCredentials;
547
+ /** The request body as a canonical value (already byte-verified). */
548
+ value: CanonicalValue;
549
+ }
550
+ interface ClientProofGuardOptions {
551
+ /**
552
+ * The contract path the client signed, when it differs from the mounted
553
+ * path (e.g. behind a stripped ingress prefix). Defaults to the request
554
+ * path.
555
+ */
556
+ contractPath?: string;
557
+ }
558
+ /**
559
+ * A guard for operations with `requiresSession: true`.
560
+ *
561
+ * Refusals are answered with the contract envelope and never reach the route.
562
+ */
563
+ declare function createClientProofGuard(state: ClientProofState, options?: ClientProofGuardOptions): MiddlewareHandler;
564
+
565
+ /**
566
+ * The header names each end announces itself under.
567
+ *
568
+ * Separated from the logic that reads them so the contract bundle can name them
569
+ * without importing the version comparison, which reads the bundle back. These
570
+ * are declarations and depend on nothing.
571
+ *
572
+ * @module server/client-proof/wire-headers
573
+ */
574
+ /** What a client says about itself, one header each. */
575
+ declare const CLIENT_IDENTITY_HEADERS: {
576
+ readonly kind: "x-spfn-client-kind";
577
+ readonly version: "x-spfn-client-version";
578
+ readonly contractVersion: "x-spfn-client-contract-version";
579
+ };
580
+ /**
581
+ * What the server says about itself, on every response.
582
+ *
583
+ * Distinct names from the request headers on purpose: a proxy that echoes a
584
+ * request header into the response would otherwise make the client's own
585
+ * version look like the server's.
586
+ */
587
+ declare const SERVER_CONTRACT_HEADERS: {
588
+ readonly version: "x-spfn-server-contract-version";
589
+ readonly supportedRange: "x-spfn-supported-contract-range";
590
+ };
591
+ /**
592
+ * The client kinds the server distinguishes.
593
+ *
594
+ * `web` is separated from the two app kinds because it carries no contract
595
+ * version: a browser bundle is deployed with the server that serves it, so
596
+ * there is no second version to reconcile.
597
+ */
598
+ declare const CLIENT_KINDS: readonly ["web", "ios", "android"];
599
+ type ClientKind = typeof CLIENT_KINDS[number];
600
+ /** A kind that ships independently of the server, so its contract version matters. */
601
+ declare function isAppKind(kind: ClientKind): boolean;
602
+
603
+ /** What one request announced about the client that sent it. */
604
+ interface ClientIdentity {
605
+ kind: ClientKind;
606
+ /** The client's own release — a store version, or a bundle build. */
607
+ version: string | null;
608
+ /** The contract version the client was generated from. Never set for `web`. */
609
+ contractVersion: string | null;
610
+ }
611
+ /**
612
+ * Reads the identity headers, or null when the kind is absent or unrecognised.
613
+ *
614
+ * Null is not by itself a refusal — a request from something that predates
615
+ * these headers reaches here too. `judgeClientIdentity` decides.
616
+ */
617
+ declare function readClientIdentity(headers: Headers): ClientIdentity | null;
618
+ /**
619
+ * Whether the server serves what the client was generated against.
620
+ *
621
+ * Under 0.x the minor carries breaking changes, so a supported client agrees on
622
+ * major and minor. From 1.0.0 the major alone decides. This is the rule
623
+ * `CONTRACT_SUPPORTED_RANGE` spells out; keeping it as a comparison rather than
624
+ * parsing that string leaves one place to change when the line reaches 1.0.0.
625
+ */
626
+ declare function isContractVersionSupported(clientVersion: string): boolean;
627
+ /**
628
+ * The refusal a request's announced identity earns, or null to let it through.
629
+ *
630
+ * An app kind must state a contract version this server serves. A version it
631
+ * does not serve, and the absence of one, are the same answer: the two ends do
632
+ * not agree on what the contract is, which is what CONTRACT_UNSUPPORTED means.
633
+ * The response carries the server's version and range, so the client can say
634
+ * which way the gap runs.
635
+ *
636
+ * `web` is exempt from the contract check by construction, not by leniency.
637
+ *
638
+ * A request with no recognised kind passes. The check is on what a client says
639
+ * about itself, and a caller that says nothing — a curl, a health probe, a
640
+ * server-to-server call — is not a deployed client this rule is about.
641
+ */
642
+ declare function judgeClientIdentity(identity: ClientIdentity | null): ClientProofRefusal | null;
643
+ /** Writes the server's own announcement onto a response's headers. */
644
+ declare function applyServerContractHeaders(headers: Headers): void;
645
+ /** The same announcement as a plain object, for a response built from one. */
646
+ declare function serverContractHeaders(): Record<string, string>;
647
+
648
+ /**
649
+ * The version announcement, applied to every request rather than to the proven
650
+ * ones.
651
+ *
652
+ * Enrollment and login are the first calls a client makes and they carry no
653
+ * proof — there is no key to sign with yet. A check that lives inside proof
654
+ * admission therefore never sees the client it is meant to catch: an outdated
655
+ * app fails at login, before it reaches anything proven. This runs ahead of all
656
+ * of it.
657
+ *
658
+ * hono is imported as types only, so this module adds no runtime dependency.
659
+ *
660
+ * @module server/client-proof/version-middleware
661
+ */
662
+
663
+ /** The context key the identity is left under, for a handler that wants it. */
664
+ declare const CLIENT_IDENTITY_CONTEXT_KEY = "clientIdentity";
665
+ /**
666
+ * Announces the server's contract version on every response and refuses a
667
+ * client whose own contract version this server does not serve.
668
+ *
669
+ * The announcement goes out either way. A refused client needs it most — the
670
+ * refusal says the two ends disagree, and the range is what says how.
671
+ *
672
+ * Mount this before authentication, not after: the point is to answer a stale
673
+ * client before anything else has a chance to fail confusingly.
674
+ */
675
+ declare function createClientVersionMiddleware(): MiddlewareHandler;
676
+
677
+ export { ABSENT_BODY_SHA256, AUTH_SURFACE_OPERATIONS, type Admission, CLIENT_IDENTITY_CONTEXT_KEY, CLIENT_IDENTITY_HEADERS, CLIENT_KINDS, CLIENT_PROOF_CONTENT_TYPE, CLIENT_PROOF_HEADERS, CLIENT_PROOF_PROFILE, CONTRACT_OPERATIONS, CONTROL_PREFIX, CONTROL_TOKEN_HEADER, CanonicalJsonError, type CanonicalJsonErrorCode, type CanonicalObject, type CanonicalValue, type ClientIdentity, type ClientKind, type ClientProofClock, type ClientProofContext, type ClientProofCredentials, type ClientProofDevHandler, type ClientProofDevHandlerOptions, type ClientProofErrorCode, type ClientProofGuardOptions, type ClientProofInput, ClientProofRefusal, type ClientProofReplayStore, ClientProofState, type ClientProofStateOptions, type ClientProofStats, type ContractItem, type ContractOperation, ContractTypeError, DEFAULT_REPLAY_WINDOW_MILLIS, DEFAULT_SESSION_TTL_MILLIS, DEV_CATALOGUE, DEV_MAX_LIMIT, type EchoRequest, type HandshakeRequest, type ListItemsRequest, MemoryReplayLedger, MemoryReplayStore, PROOF_SIGNATURE_BYTES, PROOF_SIGNATURE_HEX_LENGTH, ProofInputError, RedisReplayStore, SERVER_CONTRACT_HEADERS, TestClock, admitClientProofRequest, applyServerContractHeaders, canonicalProofInput, configureClientProofReplayStore, createClientProofDevHandler, createClientProofGuard, createClientVersionMiddleware, decodeEchoRequest, decodeHandshakeRequest, decodeListItemsRequest, encodeCanonicalJson, encodeEchoResponse, encodeHandshakeResponse, encodeListItemsResponse, getClientProofReplayStore, isAppKind, isCanonicalBytes, isContractVersionSupported, isRequestContentType, judgeClientIdentity, newHexId, parseCanonicalJson, parseClientProofPublicKey, readClientIdentity, readCredentials, replayLedgerKey, serverContractHeaders, sha256Hex, signClientProof, systemClock, verifyClientProof };