@intentic/sandbox-contract 1.432.0 → 1.434.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +15 -0
  2. package/dist/contracts/agent.contract.d.ts +252 -72
  3. package/dist/contracts/agent.contract.d.ts.map +1 -1
  4. package/dist/contracts/agents.contract.d.ts +67 -0
  5. package/dist/contracts/agents.contract.d.ts.map +1 -1
  6. package/dist/contracts/approvals.contract.d.ts +35 -0
  7. package/dist/contracts/approvals.contract.d.ts.map +1 -1
  8. package/dist/contracts/approvals.contract.js +13 -3
  9. package/dist/contracts/approvals.contract.js.map +1 -1
  10. package/dist/contracts/automations.contract.d.ts +1 -0
  11. package/dist/contracts/automations.contract.d.ts.map +1 -1
  12. package/dist/contracts/capabilities.contract.d.ts +3 -0
  13. package/dist/contracts/capabilities.contract.d.ts.map +1 -1
  14. package/dist/contracts/extensions.contract.d.ts +4 -0
  15. package/dist/contracts/extensions.contract.d.ts.map +1 -1
  16. package/dist/contracts/needs.contract.d.ts +198 -0
  17. package/dist/contracts/needs.contract.d.ts.map +1 -1
  18. package/dist/contracts/runner.contract.d.ts +156 -36
  19. package/dist/contracts/runner.contract.d.ts.map +1 -1
  20. package/dist/contracts/seal.contract.d.ts +5 -0
  21. package/dist/contracts/seal.contract.d.ts.map +1 -1
  22. package/dist/contracts/sessions.contract.d.ts +22 -0
  23. package/dist/contracts/sessions.contract.d.ts.map +1 -1
  24. package/dist/contracts/settings.contract.d.ts +16 -0
  25. package/dist/contracts/settings.contract.d.ts.map +1 -1
  26. package/dist/contracts/stack-grants.contract.d.ts +22 -0
  27. package/dist/contracts/stack-grants.contract.d.ts.map +1 -1
  28. package/dist/contracts/system.contract.d.ts +7 -4
  29. package/dist/contracts/system.contract.d.ts.map +1 -1
  30. package/dist/events/agent-events.d.ts +88 -0
  31. package/dist/events/agent-events.d.ts.map +1 -1
  32. package/dist/events/agent-transcript.d.ts +22 -0
  33. package/dist/events/agent-transcript.d.ts.map +1 -1
  34. package/dist/events/system-events.d.ts +4 -0
  35. package/dist/events/system-events.d.ts.map +1 -1
  36. package/dist/events/transcript.d.ts +110 -0
  37. package/dist/events/transcript.d.ts.map +1 -1
  38. package/dist/ids/conversation-ids.d.ts.map +1 -1
  39. package/dist/ids/conversation-ids.js.map +1 -1
  40. package/dist/protocol/raw/extension-protocol.d.ts +116 -0
  41. package/dist/protocol/raw/extension-protocol.d.ts.map +1 -1
  42. package/dist/protocol/raw/extension-protocol.js +17 -1
  43. package/dist/protocol/raw/extension-protocol.js.map +1 -1
  44. package/dist/protocol/raw/raw-json-routes.d.ts +2974 -0
  45. package/dist/protocol/raw/raw-json-routes.d.ts.map +1 -1
  46. package/dist/protocol/raw/raw-json-routes.js +39 -0
  47. package/dist/protocol/raw/raw-json-routes.js.map +1 -1
  48. package/dist/protocol/raw/raw-routes.d.ts +179 -0
  49. package/dist/protocol/raw/raw-routes.d.ts.map +1 -1
  50. package/dist/protocol/raw/raw-routes.js +41 -0
  51. package/dist/protocol/raw/raw-routes.js.map +1 -1
  52. package/dist/protocol/s2s/address.d.ts +53 -0
  53. package/dist/protocol/s2s/address.d.ts.map +1 -0
  54. package/dist/protocol/s2s/address.js +111 -0
  55. package/dist/protocol/s2s/address.js.map +1 -0
  56. package/dist/protocol/s2s/attestation.d.ts +41 -0
  57. package/dist/protocol/s2s/attestation.d.ts.map +1 -0
  58. package/dist/protocol/s2s/attestation.js +96 -0
  59. package/dist/protocol/s2s/attestation.js.map +1 -0
  60. package/dist/protocol/s2s/canonical.d.ts +10 -0
  61. package/dist/protocol/s2s/canonical.d.ts.map +1 -0
  62. package/dist/protocol/s2s/canonical.js +94 -0
  63. package/dist/protocol/s2s/canonical.js.map +1 -0
  64. package/dist/protocol/s2s/envelope.d.ts +40 -0
  65. package/dist/protocol/s2s/envelope.d.ts.map +1 -0
  66. package/dist/protocol/s2s/envelope.js +116 -0
  67. package/dist/protocol/s2s/envelope.js.map +1 -0
  68. package/dist/protocol/s2s/extension-sign.d.ts +21 -0
  69. package/dist/protocol/s2s/extension-sign.d.ts.map +1 -0
  70. package/dist/protocol/s2s/extension-sign.js +41 -0
  71. package/dist/protocol/s2s/extension-sign.js.map +1 -0
  72. package/dist/protocol/s2s/identity-doc.d.ts +50 -0
  73. package/dist/protocol/s2s/identity-doc.d.ts.map +1 -0
  74. package/dist/protocol/s2s/identity-doc.js +89 -0
  75. package/dist/protocol/s2s/identity-doc.js.map +1 -0
  76. package/dist/protocol/s2s/index.d.ts +12 -0
  77. package/dist/protocol/s2s/index.d.ts.map +1 -0
  78. package/dist/protocol/s2s/index.js +12 -0
  79. package/dist/protocol/s2s/index.js.map +1 -0
  80. package/dist/protocol/s2s/kem.d.ts +15 -0
  81. package/dist/protocol/s2s/kem.d.ts.map +1 -0
  82. package/dist/protocol/s2s/kem.js +34 -0
  83. package/dist/protocol/s2s/kem.js.map +1 -0
  84. package/dist/protocol/s2s/keys.d.ts +34 -0
  85. package/dist/protocol/s2s/keys.d.ts.map +1 -0
  86. package/dist/protocol/s2s/keys.js +81 -0
  87. package/dist/protocol/s2s/keys.js.map +1 -0
  88. package/dist/protocol/s2s/passkey-cosign.d.ts +44 -0
  89. package/dist/protocol/s2s/passkey-cosign.d.ts.map +1 -0
  90. package/dist/protocol/s2s/passkey-cosign.js +139 -0
  91. package/dist/protocol/s2s/passkey-cosign.js.map +1 -0
  92. package/dist/protocol/s2s/session.d.ts +61 -0
  93. package/dist/protocol/s2s/session.d.ts.map +1 -0
  94. package/dist/protocol/s2s/session.js +98 -0
  95. package/dist/protocol/s2s/session.js.map +1 -0
  96. package/dist/protocol/s2s/sign.d.ts +12 -0
  97. package/dist/protocol/s2s/sign.d.ts.map +1 -0
  98. package/dist/protocol/s2s/sign.js +33 -0
  99. package/dist/protocol/s2s/sign.js.map +1 -0
  100. package/dist/schemas/agents-list.d.ts +2 -0
  101. package/dist/schemas/agents-list.d.ts.map +1 -1
  102. package/dist/schemas/agents.d.ts +4 -0
  103. package/dist/schemas/agents.d.ts.map +1 -1
  104. package/dist/schemas/approvals.d.ts +100 -0
  105. package/dist/schemas/approvals.d.ts.map +1 -1
  106. package/dist/schemas/approvals.js +21 -0
  107. package/dist/schemas/approvals.js.map +1 -1
  108. package/dist/schemas/automations.d.ts +2 -0
  109. package/dist/schemas/automations.d.ts.map +1 -1
  110. package/dist/schemas/automations.js +1 -1
  111. package/dist/schemas/automations.js.map +1 -1
  112. package/dist/schemas/capabilities.d.ts +1 -0
  113. package/dist/schemas/capabilities.d.ts.map +1 -1
  114. package/dist/schemas/command-admission.d.ts +6 -0
  115. package/dist/schemas/command-admission.d.ts.map +1 -1
  116. package/dist/schemas/command-admission.js +2 -1
  117. package/dist/schemas/command-admission.js.map +1 -1
  118. package/dist/schemas/contact-need.d.ts +50 -0
  119. package/dist/schemas/contact-need.d.ts.map +1 -0
  120. package/dist/schemas/contact-need.js +19 -0
  121. package/dist/schemas/contact-need.js.map +1 -0
  122. package/dist/schemas/contacts-settings.d.ts +5 -0
  123. package/dist/schemas/contacts-settings.d.ts.map +1 -0
  124. package/dist/schemas/contacts-settings.js +11 -0
  125. package/dist/schemas/contacts-settings.js.map +1 -0
  126. package/dist/schemas/extension-updates.d.ts +8 -0
  127. package/dist/schemas/extension-updates.d.ts.map +1 -1
  128. package/dist/schemas/issues.d.ts +2 -0
  129. package/dist/schemas/issues.d.ts.map +1 -1
  130. package/dist/schemas/issues.js +1 -0
  131. package/dist/schemas/issues.js.map +1 -1
  132. package/dist/schemas/links.d.ts +8 -0
  133. package/dist/schemas/links.d.ts.map +1 -1
  134. package/dist/schemas/links.js +4 -0
  135. package/dist/schemas/links.js.map +1 -1
  136. package/dist/schemas/need-kinds.d.ts +2 -1
  137. package/dist/schemas/need-kinds.d.ts.map +1 -1
  138. package/dist/schemas/need-kinds.js +2 -2
  139. package/dist/schemas/need-kinds.js.map +1 -1
  140. package/dist/schemas/needs.d.ts +156 -13
  141. package/dist/schemas/needs.d.ts.map +1 -1
  142. package/dist/schemas/needs.js +5 -12
  143. package/dist/schemas/needs.js.map +1 -1
  144. package/dist/schemas/redirect-need.d.ts +15 -0
  145. package/dist/schemas/redirect-need.d.ts.map +1 -0
  146. package/dist/schemas/redirect-need.js +14 -0
  147. package/dist/schemas/redirect-need.js.map +1 -0
  148. package/dist/schemas/s2s-identity.d.ts +521 -0
  149. package/dist/schemas/s2s-identity.d.ts.map +1 -0
  150. package/dist/schemas/s2s-identity.js +208 -0
  151. package/dist/schemas/s2s-identity.js.map +1 -0
  152. package/dist/schemas/s2s-views.d.ts +2127 -0
  153. package/dist/schemas/s2s-views.d.ts.map +1 -0
  154. package/dist/schemas/s2s-views.js +217 -0
  155. package/dist/schemas/s2s-views.js.map +1 -0
  156. package/dist/schemas/s2s-wire.d.ts +1616 -0
  157. package/dist/schemas/s2s-wire.d.ts.map +1 -0
  158. package/dist/schemas/s2s-wire.js +276 -0
  159. package/dist/schemas/s2s-wire.js.map +1 -0
  160. package/dist/schemas/s2s.d.ts +5 -0
  161. package/dist/schemas/s2s.d.ts.map +1 -0
  162. package/dist/schemas/s2s.js +5 -0
  163. package/dist/schemas/s2s.js.map +1 -0
  164. package/dist/schemas/settings.d.ts +16 -0
  165. package/dist/schemas/settings.d.ts.map +1 -1
  166. package/dist/schemas/settings.js +2 -0
  167. package/dist/schemas/settings.js.map +1 -1
  168. package/dist/schemas/terminal.d.ts +2 -0
  169. package/dist/schemas/terminal.d.ts.map +1 -1
  170. package/dist/schemas/terminal.js +4 -0
  171. package/dist/schemas/terminal.js.map +1 -1
  172. package/dist/schemas/vpn.d.ts +4 -0
  173. package/dist/schemas/vpn.d.ts.map +1 -1
  174. package/dist/schemas/vpn.js +9 -0
  175. package/dist/schemas/vpn.js.map +1 -1
  176. package/dist/state/auth-state.d.ts.map +1 -1
  177. package/dist/state/auth-state.js +7 -0
  178. package/dist/state/auth-state.js.map +1 -1
  179. package/dist/state/definition.d.ts +18 -0
  180. package/dist/state/definition.d.ts.map +1 -1
  181. package/package.json +20 -5
  182. package/src/contracts/approvals.contract.ts +24 -3
  183. package/src/ids/conversation-ids.test.ts +22 -3
  184. package/src/ids/conversation-ids.ts +5 -7
  185. package/src/protocol/ingress-contract.fixture.json +6 -1
  186. package/src/protocol/raw/extension-protocol.ts +45 -1
  187. package/src/protocol/raw/raw-json-routes.ts +85 -0
  188. package/src/protocol/raw/raw-routes.ts +66 -3
  189. package/src/protocol/s2s/address.test.ts +157 -0
  190. package/src/protocol/s2s/address.ts +193 -0
  191. package/src/protocol/s2s/attestation.test.ts +262 -0
  192. package/src/protocol/s2s/attestation.ts +173 -0
  193. package/src/protocol/s2s/canonical.test.ts +70 -0
  194. package/src/protocol/s2s/canonical.ts +119 -0
  195. package/src/protocol/s2s/envelope.test.ts +162 -0
  196. package/src/protocol/s2s/envelope.ts +194 -0
  197. package/src/protocol/s2s/extension-sign.test.ts +117 -0
  198. package/src/protocol/s2s/extension-sign.ts +76 -0
  199. package/src/protocol/s2s/identity-doc.test.ts +187 -0
  200. package/src/protocol/s2s/identity-doc.ts +169 -0
  201. package/src/protocol/s2s/index.ts +15 -0
  202. package/src/protocol/s2s/kem.ts +62 -0
  203. package/src/protocol/s2s/keys.test.ts +76 -0
  204. package/src/protocol/s2s/keys.ts +155 -0
  205. package/src/protocol/s2s/passkey-cosign.test.ts +98 -0
  206. package/src/protocol/s2s/passkey-cosign.testing.ts +86 -0
  207. package/src/protocol/s2s/passkey-cosign.ts +192 -0
  208. package/src/protocol/s2s/s2s.testing.ts +22 -0
  209. package/src/protocol/s2s/session.test.ts +133 -0
  210. package/src/protocol/s2s/session.ts +179 -0
  211. package/src/protocol/s2s/sign.test.ts +66 -0
  212. package/src/protocol/s2s/sign.ts +53 -0
  213. package/src/schemas/approvals.ts +41 -0
  214. package/src/schemas/automations.ts +4 -3
  215. package/src/schemas/command-admission.ts +4 -1
  216. package/src/schemas/contact-need.ts +26 -0
  217. package/src/schemas/contacts-settings.ts +16 -0
  218. package/src/schemas/issues.ts +1 -0
  219. package/src/schemas/links.ts +4 -0
  220. package/src/schemas/need-kinds.ts +2 -2
  221. package/src/schemas/needs.ts +5 -18
  222. package/src/schemas/redirect-need.ts +19 -0
  223. package/src/schemas/s2s-identity.ts +329 -0
  224. package/src/schemas/s2s-views.ts +326 -0
  225. package/src/schemas/s2s-wire.ts +401 -0
  226. package/src/schemas/s2s.test.ts +175 -0
  227. package/src/schemas/s2s.ts +9 -0
  228. package/src/schemas/settings.ts +2 -0
  229. package/src/schemas/terminal.ts +6 -0
  230. package/src/schemas/version-seam.test.ts +9 -0
  231. package/src/schemas/vpn.ts +13 -0
  232. package/src/state/auth-state.ts +13 -0
@@ -0,0 +1,98 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { canonicalBytes, fromBase64Url, toBase64Url } from "./canonical.js";
3
+ import { cosignChallenge, cosignChallengeBytes, type PasskeyCosign, PasskeyCosignSchema, verifyPasskeyCosign } from "./passkey-cosign.js";
4
+ import { softCosign, softPasskey } from "./passkey-cosign.testing.js";
5
+
6
+ const DIGEST = "a".repeat(64);
7
+ const CHALLENGE = { v: 1 as const, sandbox: "sbx-1", item: "book-flight", digest: DIGEST };
8
+ const EXPECTED = { sandbox: "sbx-1", digest: DIGEST, item: "book-flight" };
9
+
10
+ describe("the co-signature's challenge", () => {
11
+ it("is SHA-256 over the canonical JSON of the challenge and the purpose, and nothing else", () => {
12
+ const bytes = cosignChallengeBytes(CHALLENGE);
13
+ expect(bytes).toEqual(sha256(canonicalBytes({ digest: DIGEST, item: "book-flight", purpose: "intentic-approval/1", sandbox: "sbx-1", v: 1 })));
14
+ expect(new TextDecoder().decode(canonicalBytes({ ...CHALLENGE, purpose: "intentic-approval/1" }))).toBe(
15
+ `{"digest":"${DIGEST}","item":"book-flight","purpose":"intentic-approval/1","sandbox":"sbx-1","v":1}`,
16
+ );
17
+ expect(cosignChallenge(CHALLENGE)).toBe(toBase64Url(bytes));
18
+ expect(bytes).toHaveLength(32);
19
+ });
20
+
21
+ it("moves with every field, so no two approvals share one", () => {
22
+ const others = [{ sandbox: "sbx-2" }, { item: "book-hotel" }, { digest: "b".repeat(64) }].map((change) => cosignChallenge({ ...CHALLENGE, ...change }));
23
+ expect(new Set([cosignChallenge(CHALLENGE), ...others]).size).toBe(4);
24
+ });
25
+ });
26
+
27
+ describe("verifyPasskeyCosign", () => {
28
+ test.each([
29
+ ["ES256", -7],
30
+ ["EdDSA", -8],
31
+ ["RS256", -257],
32
+ ] as const)("accepts a %s passkey's assertion over the approval it names", async (_name, alg) => {
33
+ const cosign = softCosign(softPasskey(alg), CHALLENGE);
34
+ expect(PasskeyCosignSchema.parse(cosign)).toEqual(cosign);
35
+ expect(await verifyPasskeyCosign(cosign, EXPECTED)).toEqual({ ok: true });
36
+ // The item is the caller's to pin or leave open.
37
+ expect(await verifyPasskeyCosign(cosign, { sandbox: "sbx-1", digest: DIGEST })).toEqual({ ok: true });
38
+ });
39
+
40
+ test("refuses an approval of another sandbox, item or digest than the one expected", async () => {
41
+ const cosign = softCosign(softPasskey(), CHALLENGE);
42
+ const another = { ok: false, reason: "it approved another sandbox, item or digest" };
43
+ expect(await verifyPasskeyCosign(cosign, { ...EXPECTED, digest: "b".repeat(64) })).toEqual(another);
44
+ expect(await verifyPasskeyCosign(cosign, { ...EXPECTED, sandbox: "sbx-2" })).toEqual(another);
45
+ expect(await verifyPasskeyCosign(cosign, { ...EXPECTED, item: "book-hotel" })).toEqual(another);
46
+ });
47
+
48
+ test("refuses a challenge whose digest was changed after the passkey signed", async () => {
49
+ const cosign = softCosign(softPasskey(), CHALLENGE);
50
+ const tampered: PasskeyCosign = { ...cosign, challenge: { ...CHALLENGE, digest: "b".repeat(64) } };
51
+ expect(await verifyPasskeyCosign(tampered, { ...EXPECTED, digest: "b".repeat(64) })).toEqual({
52
+ ok: false,
53
+ reason: "the passkey signed another challenge than this approval's",
54
+ });
55
+ });
56
+
57
+ test("refuses a passkey scoped to another site than the rpId it claims", async () => {
58
+ const cosign = softCosign(softPasskey(), CHALLENGE, "sbx-1.intentic.app", { scopedTo: "evil.example" });
59
+ expect(await verifyPasskeyCosign(cosign, EXPECTED)).toEqual({ ok: false, reason: "the passkey is scoped to another site than sbx-1.intentic.app" });
60
+ const claimed: PasskeyCosign = { ...softCosign(softPasskey(), CHALLENGE), rpId: "other.intentic.app" };
61
+ expect(await verifyPasskeyCosign(claimed, EXPECTED)).toEqual({ ok: false, reason: "the passkey is scoped to another site than other.intentic.app" });
62
+ });
63
+
64
+ test("refuses an assertion without user verification, or without presence", async () => {
65
+ const refusal = { ok: false, reason: "the authenticator did not confirm the person was present and verified" };
66
+ expect(await verifyPasskeyCosign(softCosign(softPasskey(), CHALLENGE, undefined, { userVerified: false }), EXPECTED)).toEqual(refusal);
67
+ expect(await verifyPasskeyCosign(softCosign(softPasskey(-8), CHALLENGE, undefined, { userPresent: false }), EXPECTED)).toEqual(refusal);
68
+ });
69
+
70
+ test("refuses a registration's client data, or anything not a webauthn.get", async () => {
71
+ const cosign = softCosign(softPasskey(), CHALLENGE, undefined, { type: "webauthn.create" });
72
+ expect(await verifyPasskeyCosign(cosign, EXPECTED)).toEqual({ ok: false, reason: "its client data is not a WebAuthn assertion (webauthn.get)" });
73
+ });
74
+
75
+ test.each([
76
+ ["ES256", -7],
77
+ ["EdDSA", -8],
78
+ ["RS256", -257],
79
+ ] as const)("refuses a %s signature under another key, and one with a byte changed", async (_name, alg) => {
80
+ const cosign = softCosign(softPasskey(alg), CHALLENGE);
81
+ const refusal = { ok: false, reason: "the signature does not verify under its key" };
82
+ expect(await verifyPasskeyCosign({ ...cosign, publicKey: softPasskey(alg).publicKey }, EXPECTED)).toEqual(refusal);
83
+ const bytes = fromBase64Url(cosign.signature) ?? new Uint8Array();
84
+ bytes[bytes.length - 1] = (bytes.at(-1) ?? 0) ^ 0x01;
85
+ expect(await verifyPasskeyCosign({ ...cosign, signature: toBase64Url(bytes) }, EXPECTED)).toEqual(refusal);
86
+ });
87
+
88
+ test("refuses a key whose JWK is not its algorithm's, and a body that is not a co-signature", async () => {
89
+ const cosign = softCosign(softPasskey(-7), CHALLENGE);
90
+ expect(await verifyPasskeyCosign({ ...cosign, publicKey: { alg: -8, jwk: cosign.publicKey.jwk } }, EXPECTED)).toEqual({
91
+ ok: false,
92
+ reason: "the signature does not verify under its key",
93
+ });
94
+ // SAFETY: a co-signature read off the wire may be anything; the verifier parses it before trusting a field.
95
+ const junk = JSON.parse(`{"v":2}`) as PasskeyCosign;
96
+ expect(await verifyPasskeyCosign(junk, EXPECTED)).toEqual({ ok: false, reason: "not a passkey co-signature" });
97
+ });
98
+ });
@@ -0,0 +1,86 @@
1
+ import { createHash, generateKeyPairSync, type KeyObject, randomBytes, sign as signWith } from "node:crypto";
2
+ import { cosignChallenge, type PasskeyCosign, type PasskeyCosignChallenge } from "./passkey-cosign.js";
3
+
4
+ // A passkey in software, for the co-signature's tests: the assertion bytes a browser hands back (the authenticator data
5
+ // with its flag byte, clientDataJSON, a DER ES256, an RS256 or an EdDSA signature), with the knobs a test turns wrong.
6
+ // The approach of the daemon's harness (_sandbox/sandbox/src/harness/passkey-authenticator.testing.ts), which the
7
+ // contract cannot import; only the assertion half, since a co-signature carries the key the sandbox already stored.
8
+ // Not part of the build.
9
+
10
+ export type SoftPasskeyAlg = -7 | -8 | -257;
11
+
12
+ export interface SoftAssertion {
13
+ readonly rpId: string;
14
+ readonly challenge: string;
15
+ readonly type?: string;
16
+ readonly userPresent?: boolean;
17
+ readonly userVerified?: boolean;
18
+ // The rpId the authenticator data is scoped to, when it should differ from the one claimed.
19
+ readonly scopedTo?: string;
20
+ }
21
+
22
+ export interface SoftPasskey {
23
+ readonly credentialId: string;
24
+ readonly publicKey: PasskeyCosign["publicKey"];
25
+ readonly assert: (input: SoftAssertion) => Pick<PasskeyCosign, "authenticatorData" | "clientDataJSON" | "signature">;
26
+ }
27
+
28
+ const sha256 = (bytes: Uint8Array): Buffer => createHash("sha256").update(bytes).digest();
29
+
30
+ const keyPairFor = (alg: SoftPasskeyAlg): { publicKey: KeyObject; privateKey: KeyObject } => {
31
+ if (alg === -7) {
32
+ return generateKeyPairSync("ec", { namedCurve: "P-256" });
33
+ }
34
+ if (alg === -257) {
35
+ return generateKeyPairSync("rsa", { modulusLength: 2048 });
36
+ }
37
+ return generateKeyPairSync("ed25519");
38
+ };
39
+
40
+ // The key as the sandbox stores it: node's JWK, only the members each algorithm's key has.
41
+ const jwkOf = (alg: SoftPasskeyAlg, publicKey: KeyObject) => {
42
+ const { kty = "", crv = "", x = "", y = "", n = "", e = "" } = publicKey.export({ format: "jwk" });
43
+ if (alg === -7) {
44
+ return { kty, crv, x, y };
45
+ }
46
+ return alg === -257 ? { kty, n, e } : { kty, crv, x };
47
+ };
48
+
49
+ export const softPasskey = (alg: SoftPasskeyAlg = -7): SoftPasskey => {
50
+ const { publicKey, privateKey } = keyPairFor(alg);
51
+ return {
52
+ credentialId: randomBytes(16).toString("base64url"),
53
+ publicKey: { alg, jwk: jwkOf(alg, publicKey) },
54
+ assert: (input) => {
55
+ const flags = (input.userPresent === false ? 0 : 0x01) | (input.userVerified === false ? 0 : 0x04);
56
+ const authData = Buffer.concat([sha256(Buffer.from(input.scopedTo ?? input.rpId, "utf8")), Buffer.from([flags]), Buffer.alloc(4)]);
57
+ const clientData = Buffer.from(
58
+ JSON.stringify({ type: input.type ?? "webauthn.get", challenge: input.challenge, origin: `https://${input.rpId}`, crossOrigin: false }),
59
+ "utf8",
60
+ );
61
+ const signed = Buffer.concat([authData, sha256(clientData)]);
62
+ const signature = alg === -8 ? signWith(undefined, signed, privateKey) : signWith("sha256", signed, privateKey);
63
+ return {
64
+ authenticatorData: authData.toString("base64url"),
65
+ clientDataJSON: clientData.toString("base64url"),
66
+ signature: signature.toString("base64url"),
67
+ };
68
+ },
69
+ };
70
+ };
71
+
72
+ // A whole co-signature by `passkey` over `challenge`, as the daemon records it; `assertion` turns a knob wrong.
73
+ export const softCosign = (
74
+ passkey: SoftPasskey,
75
+ challenge: PasskeyCosignChallenge,
76
+ rpId = "sbx-1.intentic.app",
77
+ assertion: Partial<SoftAssertion> = {},
78
+ ): PasskeyCosign => ({
79
+ v: 1,
80
+ challenge,
81
+ credentialId: passkey.credentialId,
82
+ publicKey: passkey.publicKey,
83
+ rpId,
84
+ ...passkey.assert({ rpId, challenge: cosignChallenge(challenge), ...assertion }),
85
+ label: "Laptop",
86
+ });
@@ -0,0 +1,192 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { z } from "zod";
3
+ import { S2sBase64UrlSchema } from "../../schemas/s2s-identity.js";
4
+ import { canonicalBytes, concatBytes, equalBytes, fromBase64Url, fromUtf8, toBase64Url, utf8 } from "./canonical.js";
5
+
6
+ // A PASSKEY CO-SIGNATURE ON AN APPROVAL (2026-11-28, docs/architecture/messages.md "Identity"): proof that a person
7
+ // approved one item of the approvals queue with their own passkey, which anyone holding it can check without the
8
+ // sandbox. The daemon runs an ordinary WebAuthn assertion whose challenge is not a random nonce but the digest of what
9
+ // was approved (cosignChallengeBytes), keeps the assertion with the recorded yes, and hands it to the extension carrying
10
+ // the item out (`ApprovedAction.cosign`), which may publish it beside what it did.
11
+ //
12
+ // The challenge is SHA-256 over the canonical JSON (canonical.ts) of
13
+ // { v: 1, sandbox, item, digest, purpose: "intentic-approval/1" }
14
+ // where `sandbox` is the sandbox's id as its identity document names it, `item` the approval's id and `digest` the
15
+ // performer's SHA-256 of exactly what it will do. The browser signs `authenticatorData || SHA-256(clientDataJSON)`, and
16
+ // clientDataJSON carries that challenge in base64url; so the signature binds the passkey to this sandbox, this item and
17
+ // this digest, and to nothing else. Pure: WebCrypto (`globalThis.crypto.subtle`) verifies the signature under Node, Bun
18
+ // and a browser alike, and no curve library loads with the schema.
19
+
20
+ // Mixed into the challenge so no other WebAuthn ceremony's challenge (a sign-in's random 32 bytes) is ever this one.
21
+ export const PASSKEY_COSIGN_PURPOSE = "intentic-approval/1";
22
+
23
+ // COSE algorithm ids a passkey signs with: ES256, EdDSA (Ed25519) and RS256, the three the sandbox registers.
24
+ export const PasskeyCosignAlgSchema = z.union([z.literal(-7), z.literal(-8), z.literal(-257)]);
25
+
26
+ export const PasskeyCosignChallengeSchema = z
27
+ .object({
28
+ v: z.literal(1),
29
+ sandbox: z.string().min(1).max(200).describe("The sandbox's id, as its identity document names it."),
30
+ item: z.string().min(1).max(200).describe("The approval's id in the queue."),
31
+ digest: z.string().min(1).max(200).describe("The performer's SHA-256 of exactly what it will do, hex."),
32
+ })
33
+ .describe("What the passkey approved: which sandbox, which item, which digest.");
34
+ export type PasskeyCosignChallenge = z.infer<typeof PasskeyCosignChallengeSchema>;
35
+
36
+ export const PasskeyCosignSchema = z
37
+ .object({
38
+ v: z.literal(1),
39
+ challenge: PasskeyCosignChallengeSchema,
40
+ credentialId: S2sBase64UrlSchema.describe("The passkey's credential id."),
41
+ publicKey: z
42
+ .object({ alg: PasskeyCosignAlgSchema, jwk: z.record(z.string(), z.string()) })
43
+ .describe("The passkey's public key as the sandbox registered it: a COSE algorithm and the key as a JWK."),
44
+ rpId: z.string().min(1).max(253).describe("The site the passkey is scoped to (the editor's host)."),
45
+ authenticatorData: S2sBase64UrlSchema,
46
+ clientDataJSON: S2sBase64UrlSchema,
47
+ signature: S2sBase64UrlSchema,
48
+ label: z.string().max(200).optional().describe("The passkey's name, as its holder gave it. Never their email."),
49
+ })
50
+ .describe("A person's passkey assertion over an approval: anyone verifies it with verifyPasskeyCosign, no sandbox needed.");
51
+ export type PasskeyCosign = z.infer<typeof PasskeyCosignSchema>;
52
+
53
+ // The 32 bytes the authenticator is handed as its challenge for this approval.
54
+ export const cosignChallengeBytes = (challenge: PasskeyCosignChallenge): Uint8Array =>
55
+ sha256(canonicalBytes({ v: challenge.v, sandbox: challenge.sandbox, item: challenge.item, digest: challenge.digest, purpose: PASSKEY_COSIGN_PURPOSE }));
56
+
57
+ // What WebAuthn's options carry as `challenge` and clientDataJSON repeats back: the bytes in base64url.
58
+ export const cosignChallenge = (challenge: PasskeyCosignChallenge): string => toBase64Url(cosignChallengeBytes(challenge));
59
+
60
+ export type PasskeyCosignCheck = { readonly ok: true } | { readonly ok: false; readonly reason: string };
61
+
62
+ const refuse = (reason: string): PasskeyCosignCheck => ({ ok: false, reason });
63
+
64
+ // An ES256 signature as WebAuthn sends it (ASN.1 DER: SEQUENCE { INTEGER r, INTEGER s }) in the raw r ‖ s form
65
+ // WebCrypto verifies, each 32 bytes; undefined for anything that is not exactly that.
66
+ const rawEcdsa = (der: Uint8Array): Uint8Array | undefined => {
67
+ let at = 0;
68
+ const take = (): number | undefined => (at < der.length ? der[at++] : undefined);
69
+ const integer = (): Uint8Array | undefined => {
70
+ const length = take() === 0x02 ? take() : undefined;
71
+ if (length === undefined || length < 1 || length > 33 || at + length > der.length) {
72
+ return undefined;
73
+ }
74
+ const bytes = der.slice(at, at + length);
75
+ at += length;
76
+ const trimmed = bytes.length === 33 && bytes[0] === 0 ? bytes.slice(1) : bytes;
77
+ if (trimmed.length > 32) {
78
+ return undefined;
79
+ }
80
+ const out = new Uint8Array(32);
81
+ out.set(trimmed, 32 - trimmed.length);
82
+ return out;
83
+ };
84
+ if (take() !== 0x30 || take() !== der.length - 2) {
85
+ return undefined;
86
+ }
87
+ const r = integer();
88
+ const s = integer();
89
+ return r === undefined || s === undefined || at !== der.length ? undefined : concatBytes(r, s);
90
+ };
91
+
92
+ // A copy into a fresh ArrayBuffer, the BufferSource every WebCrypto signature takes whatever view it was handed.
93
+ const buffer = (bytes: Uint8Array): ArrayBuffer => {
94
+ const out = new ArrayBuffer(bytes.length);
95
+ new Uint8Array(out).set(bytes);
96
+ return out;
97
+ };
98
+
99
+ // The JWK WebCrypto imports for a stored key, its members checked to be what its algorithm needs; undefined otherwise.
100
+ const importable = (publicKey: PasskeyCosign["publicKey"]): JsonWebKey | undefined => {
101
+ const { kty, crv, x, y, n, e } = publicKey.jwk;
102
+ if (publicKey.alg === -7) {
103
+ return kty === "EC" && crv === "P-256" && x !== undefined && y !== undefined ? { kty, crv, x, y } : undefined;
104
+ }
105
+ if (publicKey.alg === -8) {
106
+ return kty === "OKP" && crv === "Ed25519" && x !== undefined ? { kty, crv, x } : undefined;
107
+ }
108
+ return kty === "RSA" && n !== undefined && e !== undefined ? { kty, n, e } : undefined;
109
+ };
110
+
111
+ // Whether `signature` is the key's over `signed`, by its algorithm; false for a key or signature that does not import.
112
+ const signatureVerifies = async (publicKey: PasskeyCosign["publicKey"], signed: Uint8Array, signature: Uint8Array): Promise<boolean> => {
113
+ const { subtle } = globalThis.crypto;
114
+ const jwk = importable(publicKey);
115
+ if (jwk === undefined) {
116
+ return false;
117
+ }
118
+ try {
119
+ if (publicKey.alg === -7) {
120
+ const raw = rawEcdsa(signature);
121
+ const key = await subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
122
+ return raw !== undefined && (await subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, buffer(raw), buffer(signed)));
123
+ }
124
+ if (publicKey.alg === -8) {
125
+ const key = await subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, ["verify"]);
126
+ return await subtle.verify({ name: "Ed25519" }, key, buffer(signature), buffer(signed));
127
+ }
128
+ const key = await subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
129
+ return await subtle.verify({ name: "RSASSA-PKCS1-v1_5" }, key, buffer(signature), buffer(signed));
130
+ } catch {
131
+ // allow(silent-catch): a key WebCrypto cannot import, or a signature it cannot read, verifies nothing
132
+ return false;
133
+ }
134
+ };
135
+
136
+ // clientDataJSON's type and challenge, or undefined when it is not JSON naming both as strings.
137
+ const clientDataOf = (bytes: Uint8Array): { readonly type: string; readonly challenge: string } | undefined => {
138
+ try {
139
+ const parsed = z.object({ type: z.string(), challenge: z.string() }).safeParse(JSON.parse(fromUtf8(bytes)));
140
+ return parsed.success ? parsed.data : undefined;
141
+ } catch {
142
+ // allow(silent-catch): bytes that are not UTF-8 JSON are no client data, which the caller refuses
143
+ return undefined;
144
+ }
145
+ };
146
+
147
+ // The authenticator data's flag byte: user present, user verified (a PIN or biometric).
148
+ const USER_PRESENT = 0x01;
149
+ const USER_VERIFIED = 0x04;
150
+
151
+ /**
152
+ * Whether `cosign` is a passkey's approval of `expected`: the challenge it embeds names this sandbox, this digest (and
153
+ * this item, when given); clientDataJSON is a `webauthn.get` over that challenge; the authenticator data is scoped to
154
+ * `rpId` with the person present and verified; and the signature over `authenticatorData || SHA-256(clientDataJSON)`
155
+ * verifies under the embedded key. It does not say whose key that is (compare `credentialId` or the key with one you
156
+ * trust) nor which origin ran the ceremony, which only the sandbox that asked could check.
157
+ */
158
+ export const verifyPasskeyCosign = async (
159
+ cosign: PasskeyCosign,
160
+ expected: { readonly sandbox: string; readonly digest: string; readonly item?: string | undefined },
161
+ ): Promise<PasskeyCosignCheck> => {
162
+ const parsed = PasskeyCosignSchema.safeParse(cosign);
163
+ if (!parsed.success) {
164
+ return refuse("not a passkey co-signature");
165
+ }
166
+ const { challenge, rpId, publicKey } = parsed.data;
167
+ if (challenge.sandbox !== expected.sandbox || challenge.digest !== expected.digest || (expected.item !== undefined && challenge.item !== expected.item)) {
168
+ return refuse("it approved another sandbox, item or digest");
169
+ }
170
+ const authenticatorData = fromBase64Url(parsed.data.authenticatorData);
171
+ const clientDataJSON = fromBase64Url(parsed.data.clientDataJSON);
172
+ const signature = fromBase64Url(parsed.data.signature);
173
+ if (authenticatorData === undefined || clientDataJSON === undefined || signature === undefined) {
174
+ return refuse("a part of it is not base64url");
175
+ }
176
+ const clientData = clientDataOf(clientDataJSON);
177
+ if (clientData?.type !== "webauthn.get") {
178
+ return refuse("its client data is not a WebAuthn assertion (webauthn.get)");
179
+ }
180
+ if (clientData.challenge !== cosignChallenge(challenge)) {
181
+ return refuse("the passkey signed another challenge than this approval's");
182
+ }
183
+ if (authenticatorData.length < 37 || !equalBytes(authenticatorData.slice(0, 32), sha256(utf8(rpId)))) {
184
+ return refuse(`the passkey is scoped to another site than ${rpId}`);
185
+ }
186
+ const flags = authenticatorData[32] ?? 0;
187
+ if ((flags & USER_PRESENT) === 0 || (flags & USER_VERIFIED) === 0) {
188
+ return refuse("the authenticator did not confirm the person was present and verified");
189
+ }
190
+ const signed = concatBytes(authenticatorData, sha256(clientDataJSON));
191
+ return (await signatureVerifies(publicKey, signed, signature)) ? { ok: true } : refuse("the signature does not verify under its key");
192
+ };
@@ -0,0 +1,22 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { concatBytes, utf8 } from "./canonical.js";
3
+ import { generateKeySet, generateRecoveryKey, type RandomBytes, type S2sKeySet, type S2sRecoveryKey } from "./keys.js";
4
+
5
+ // Test fixtures for the s2s primitives: randomness a test can name, so a key set, a nonce or an envelope id is the same
6
+ // on every run and a test can assert it by value. Never for anything that ships.
7
+
8
+ // SHA-256 in counter mode over the seed: the same bytes for the same seed, every run.
9
+ export const seededRandom = (seed: string): RandomBytes => {
10
+ let counter = 0;
11
+ return (length) => {
12
+ const blocks: Uint8Array[] = [];
13
+ for (let made = 0; made < length; made += 32) {
14
+ blocks.push(sha256(concatBytes(utf8(seed), utf8(`:${counter++}`))));
15
+ }
16
+ return concatBytes(...blocks).slice(0, length);
17
+ };
18
+ };
19
+
20
+ // A key set, or a recovery key, that is the same for the same name.
21
+ export const keySetFor = (name: string): S2sKeySet => generateKeySet(seededRandom(`key set ${name}`));
22
+ export const recoveryKeyFor = (name: string): S2sRecoveryKey => generateRecoveryKey(seededRandom(`recovery ${name}`));
@@ -0,0 +1,133 @@
1
+ import { S2S_CALL_SKEW_MS, type S2sCallSealed, S2sSessionOpenSchema } from "../../schemas/s2s-wire.js";
2
+ import { equalBytes, fromBase64Url, toBase64Url } from "./canonical.js";
3
+ import { keySetFor, seededRandom } from "./s2s.testing.js";
4
+ import {
5
+ acceptSession,
6
+ type CallContext,
7
+ confirmsSession,
8
+ createReplayWindow,
9
+ openCall,
10
+ openSession,
11
+ sealCall,
12
+ sessionConfirm,
13
+ } from "./session.js";
14
+
15
+ const NOW = 1_800_000_000_000;
16
+ const caller = keySetFor(`caller`);
17
+ const callee = keySetFor(`callee`);
18
+ const calleeBefore = keySetFor(`callee before`);
19
+ const mallory = keySetFor(`mallory`);
20
+ const opening = openSession({ from: `caller.example`, to: `callee.example`, caller, callee: callee.public, now: NOW, random: seededRandom(`open`) });
21
+
22
+ const call: CallContext = { session: `s-1`, method: `operate.read`, leg: { direction: `call` } };
23
+
24
+ const flipByte = (text: string, at: number): string => {
25
+ const bytes = fromBase64Url(text) ?? new Uint8Array();
26
+ bytes[at] = (bytes[at] ?? 0) ^ 0x01;
27
+ return toBase64Url(bytes);
28
+ };
29
+
30
+ describe("a call session", () => {
31
+ it("gives the callee the caller's key, after JSON and the schema", () => {
32
+ const arrived = S2sSessionOpenSchema.parse(JSON.parse(JSON.stringify(opening.request)));
33
+ const accepted = acceptSession(arrived, { caller: caller.public, keys: [callee], now: NOW + 1_000 });
34
+ expect(accepted.ok).toBe(true);
35
+ expect(accepted.ok && equalBytes(accepted.key, opening.key)).toBe(true);
36
+ expect(opening.key.length).toBe(32);
37
+ expect(opening.request).toMatchObject({ v: 1, from: `caller.example`, fromFp: caller.fingerprint, to: `callee.example`, toFp: callee.fingerprint, at: NOW });
38
+ });
39
+
40
+ it("opens with a kept previous key set it was made to", () => {
41
+ const late = openSession({ from: `caller.example`, to: `callee.example`, caller, callee: calleeBefore.public, now: NOW });
42
+ const accepted = acceptSession(late.request, { caller: caller.public, keys: [callee, calleeBefore], now: NOW });
43
+ expect(accepted.ok && equalBytes(accepted.key, late.key)).toBe(true);
44
+ expect(acceptSession(late.request, { caller: caller.public, keys: [callee], now: NOW })).toEqual({ ok: false, reason: `recipient` });
45
+ });
46
+
47
+ it("refuses another caller's keys and any changed field", () => {
48
+ expect(acceptSession(opening.request, { caller: mallory.public, keys: [callee], now: NOW })).toEqual({ ok: false, reason: `signature` });
49
+ for (const change of [{ at: NOW + 1 }, { from: `mallory.example` }, { as: `ada@acme.example` }, { nonce: flipByte(opening.request.nonce, 0) }]) {
50
+ expect(acceptSession({ ...opening.request, ...change }, { caller: caller.public, keys: [callee], now: NOW })).toEqual({ ok: false, reason: `signature` });
51
+ }
52
+ const enc = { ...opening.request.enc, mlkem768: flipByte(opening.request.enc.mlkem768, 7) };
53
+ expect(acceptSession({ ...opening.request, enc }, { caller: caller.public, keys: [callee], now: NOW })).toEqual({ ok: false, reason: `signature` });
54
+ });
55
+
56
+ it("refuses a request whose time is past the skew either way, and admits one at its edge", () => {
57
+ const accept = (now: number) => acceptSession(opening.request, { caller: caller.public, keys: [callee], now });
58
+ expect(accept(NOW + S2S_CALL_SKEW_MS).ok).toBe(true);
59
+ expect(accept(NOW - S2S_CALL_SKEW_MS).ok).toBe(true);
60
+ expect(accept(NOW + S2S_CALL_SKEW_MS + 1)).toEqual({ ok: false, reason: `stale` });
61
+ expect(accept(NOW - S2S_CALL_SKEW_MS - 1)).toEqual({ ok: false, reason: `stale` });
62
+ });
63
+
64
+ it("confirms the session only under the same key and the same id", () => {
65
+ const confirm = sessionConfirm(opening.key, `s-1`);
66
+ expect(confirmsSession(opening.key, `s-1`, confirm)).toBe(true);
67
+ expect(confirmsSession(opening.key, `s-2`, confirm)).toBe(false);
68
+ expect(confirmsSession(new Uint8Array(32), `s-1`, confirm)).toBe(false);
69
+ });
70
+ });
71
+
72
+ describe("a sealed call", () => {
73
+ const input = { path: `README.md`, limit: 20 };
74
+ const sealed = sealCall(opening.key, call, input, NOW, seededRandom(`call`));
75
+
76
+ it("opens to its JSON under the session key, once", () => {
77
+ const window = createReplayWindow();
78
+ expect(openCall(opening.key, call, sealed, NOW + 500, window)).toEqual({ ok: true, json: JSON.stringify(input) });
79
+ expect(openCall(opening.key, call, sealed, NOW + 600, window)).toEqual({ ok: false, reason: `replay` });
80
+ });
81
+
82
+ it("refuses another session's key, session id, method or leg", () => {
83
+ expect(openCall(new Uint8Array(32), call, sealed, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
84
+ expect(openCall(opening.key, { ...call, session: `s-2` }, sealed, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
85
+ expect(openCall(opening.key, { ...call, method: `operate.write` }, sealed, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
86
+ expect(openCall(opening.key, { ...call, leg: { direction: `answer`, re: sealed.nonce } }, sealed, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
87
+ });
88
+
89
+ it("binds an answer to the call it answers", () => {
90
+ const answerLeg: CallContext = { ...call, leg: { direction: `answer`, re: sealed.nonce } };
91
+ const answer = sealCall(opening.key, answerLeg, { content: `# hi` }, NOW + 10);
92
+ expect(openCall(opening.key, answerLeg, answer, NOW + 20, createReplayWindow())).toEqual({ ok: true, json: `{"content":"# hi"}` });
93
+ expect(openCall(opening.key, { ...call, leg: { direction: `answer`, re: `another` } }, answer, NOW + 20, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
94
+ });
95
+
96
+ it("refuses every changed byte of its body and its nonce, and a changed time", () => {
97
+ const bodyBytes = fromBase64Url(sealed.body)?.length ?? 0;
98
+ for (let at = 0; at < bodyBytes; at++) {
99
+ expect(openCall(opening.key, call, { ...sealed, body: flipByte(sealed.body, at) }, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
100
+ }
101
+ for (let at = 0; at < 12; at++) {
102
+ expect(openCall(opening.key, call, { ...sealed, nonce: flipByte(sealed.nonce, at) }, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
103
+ }
104
+ const later: S2sCallSealed = { ...sealed, at: NOW + 1 };
105
+ expect(openCall(opening.key, call, later, NOW, createReplayWindow())).toEqual({ ok: false, reason: `decrypt` });
106
+ });
107
+
108
+ it("refuses one sealed too long ago or too far ahead", () => {
109
+ expect(openCall(opening.key, call, sealed, NOW + S2S_CALL_SKEW_MS + 1, createReplayWindow())).toEqual({ ok: false, reason: `stale` });
110
+ expect(openCall(opening.key, call, sealed, NOW - S2S_CALL_SKEW_MS - 1, createReplayWindow())).toEqual({ ok: false, reason: `stale` });
111
+ });
112
+ });
113
+
114
+ describe("a replay window", () => {
115
+ it("admits a nonce once, refuses it again within the window, and refuses times outside it", () => {
116
+ const window = createReplayWindow(1_000);
117
+ expect(window.admit(`n1`, NOW, NOW)).toBe(`fresh`);
118
+ expect(window.admit(`n1`, NOW, NOW + 10)).toBe(`replay`);
119
+ expect(window.admit(`n2`, NOW + 1_000, NOW)).toBe(`fresh`);
120
+ expect(window.admit(`n3`, NOW + 1_001, NOW)).toBe(`stale`);
121
+ expect(window.admit(`n4`, NOW - 1_001, NOW)).toBe(`stale`);
122
+ });
123
+
124
+ it("forgets what would be stale anyway, so it stays small", () => {
125
+ const window = createReplayWindow(1_000);
126
+ for (let index = 0; index < 50; index++) {
127
+ window.admit(`n${index}`, NOW + index * 100, NOW + index * 100);
128
+ }
129
+ // At NOW + 4900, everything made before NOW + 3900 is past the window.
130
+ expect(window.size()).toBe(11);
131
+ expect(window.admit(`n49`, NOW + 4_900, NOW + 4_950)).toBe(`replay`);
132
+ });
133
+ });