@intentic/sandbox-contract 1.432.0 → 1.433.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 +6 -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 +10 -0
@@ -0,0 +1,262 @@
1
+ import {
2
+ S2S_ATTESTATION_VALID_MAX_MS,
3
+ S2S_ATTESTATIONS_KEPT_MAX,
4
+ S2S_CLAIM_VALUE_MAX,
5
+ S2S_CLAIMS_BYTES_MAX,
6
+ S2S_CLAIMS_MAX,
7
+ S2S_DOMAINS_MAX,
8
+ S2S_IDENTITY_MAX_BYTES,
9
+ type S2sAttestation,
10
+ S2sAttestationSchema,
11
+ type S2sSandboxVouch,
12
+ SandboxIdentitySchema,
13
+ } from "../../schemas/s2s-identity.js";
14
+ import { type AttestationInput, attestationIdOf, sandboxVouchOf, signAttestation, verifyAttestation, verifyAttestations } from "./attestation.js";
15
+ import { canonicalBytes, canonicalJson } from "./canonical.js";
16
+ import { type IdentityFacts, signIdentity, verifyIdentity, vouchFor } from "./identity-doc.js";
17
+ import { secretKeysOf } from "./keys.js";
18
+ import { keySetFor, recoveryKeyFor } from "./s2s.testing.js";
19
+ import { hybridSign } from "./sign.js";
20
+
21
+ const NOW = 1_800_000_000_000;
22
+ const DAY = 24 * 60 * 60 * 1000;
23
+ const issuerKeys = keySetFor(`notary`);
24
+ const first = keySetFor(`subject first`);
25
+ const second = keySetFor(`subject second`);
26
+ const third = keySetFor(`subject third`);
27
+ const recovery = recoveryKeyFor(`subject`);
28
+ const facts: IdentityFacts = { sandbox: `0123456789ab`, name: `ops`, host: `0123456789ab.sandbox.example`, domains: [], recovery: recovery.fingerprint, issuedAt: NOW };
29
+
30
+ const subjectDoc = signIdentity(facts, first);
31
+ const rotatedOnce = signIdentity({ ...facts, issuedAt: NOW + 1 }, second, vouchFor(facts.sandbox, second, { by: `key`, keySet: first }, NOW + 1));
32
+ const rotatedTwice = signIdentity({ ...facts, issuedAt: NOW + 2 }, third, vouchFor(facts.sandbox, third, { by: `key`, keySet: second }, NOW + 2));
33
+ const recovered = signIdentity({ ...facts, issuedAt: NOW + 3 }, second, vouchFor(facts.sandbox, second, { by: `recovery`, recovery }, NOW + 3));
34
+
35
+ const input: AttestationInput = {
36
+ issuer: { sandbox: `notary-sandbox`, address: `notary.example`, name: `Notary` },
37
+ subject: { sandbox: facts.sandbox, address: facts.host, fingerprint: first.fingerprint },
38
+ claims: { kind: `organisation`, verifiedBy: `document`, country: `PL`, over18: true },
39
+ issuedAt: NOW,
40
+ validUntil: NOW + 90 * DAY,
41
+ };
42
+ const vouch = signAttestation(input, issuerKeys);
43
+ const at = { now: NOW + DAY };
44
+
45
+ // The vouch with a change made after signing, which its signature no longer covers.
46
+ const tampered = (change: Partial<S2sSandboxVouch>): S2sSandboxVouch => ({ ...vouch, ...change });
47
+
48
+ // A vouch signed over whatever fields are given, as a later or a careless issuer might make one.
49
+ const signedAs = (fields: Readonly<Record<string, unknown>>): S2sAttestation => {
50
+ const unsigned = { ...fields };
51
+ return S2sAttestationSchema.parse({ ...unsigned, sig: hybridSign(`attestation`, canonicalBytes(unsigned), secretKeysOf(issuerKeys.secret)) });
52
+ };
53
+
54
+ describe("a sandbox vouch", () => {
55
+ it("carries its issuer's four public keys and fingerprint, the subject's key, the claims and the dates", () => {
56
+ expect(vouch).toMatchObject({
57
+ v: 1,
58
+ type: `sandbox-vouch`,
59
+ issuer: { sandbox: `notary-sandbox`, address: `notary.example`, name: `Notary`, fingerprint: issuerKeys.fingerprint, keys: issuerKeys.public },
60
+ subject: { sandbox: facts.sandbox, address: facts.host, fingerprint: first.fingerprint },
61
+ claims: { kind: `organisation`, verifiedBy: `document`, country: `PL`, over18: true },
62
+ issuedAt: NOW,
63
+ validUntil: NOW + 90 * DAY,
64
+ });
65
+ expect(Object.keys(vouch.issuer.keys).toSorted()).toEqual([`ed25519`, `mldsa65`, `mlkem768`, `x25519`]);
66
+ });
67
+
68
+ it("verifies against its subject's document, trusted only by a reader who lists its issuer", () => {
69
+ expect(verifyAttestation(vouch, subjectDoc, at)).toEqual({ ok: true, trusted: false });
70
+ expect(verifyAttestation(vouch, subjectDoc, { ...at, trustedIssuers: [issuerKeys.fingerprint] })).toEqual({ ok: true, trusted: true });
71
+ expect(verifyAttestation(vouch, subjectDoc, { ...at, trustedIssuers: new Set([second.fingerprint]) })).toEqual({ ok: true, trusted: false });
72
+ });
73
+
74
+ it("survives JSON and the schema whole, and is read back as a vouch", () => {
75
+ const arrived = S2sAttestationSchema.parse(JSON.parse(JSON.stringify(vouch)));
76
+ expect(arrived).toEqual(vouch);
77
+ expect(sandboxVouchOf(arrived)).toEqual(vouch);
78
+ expect(verifyAttestation(arrived, subjectDoc, at)).toEqual({ ok: true, trusted: false });
79
+ });
80
+
81
+ it("lapses at validUntil and is not taken from ahead of the reader's clock", () => {
82
+ expect(verifyAttestation(vouch, subjectDoc, { now: input.validUntil - 1 })).toEqual({ ok: true, trusted: false });
83
+ expect(verifyAttestation(vouch, subjectDoc, { now: input.validUntil })).toEqual({ ok: false, trusted: false, reason: `it lapsed at ${new Date(input.validUntil).toISOString()}` });
84
+ expect(verifyAttestation(vouch, subjectDoc, { now: NOW - 5 * 60 * 1000 })).toEqual({ ok: true, trusted: false });
85
+ expect(verifyAttestation(vouch, subjectDoc, { now: NOW - 5 * 60 * 1000 - 1 })).toEqual({
86
+ ok: false,
87
+ trusted: false,
88
+ reason: `it is dated ${new Date(NOW).toISOString()}, ahead of this clock`,
89
+ });
90
+ });
91
+
92
+ it("is never signed or taken for longer than a year", () => {
93
+ expect(signAttestation({ ...input, validUntil: NOW + S2S_ATTESTATION_VALID_MAX_MS }, issuerKeys).validUntil).toBe(NOW + S2S_ATTESTATION_VALID_MAX_MS);
94
+ expect(() => signAttestation({ ...input, validUntil: NOW + S2S_ATTESTATION_VALID_MAX_MS + 1 }, issuerKeys)).toThrow(
95
+ `an attestation cannot be signed: it claims to be valid for more than a year`,
96
+ );
97
+ expect(() => signAttestation({ ...input, validUntil: NOW }, issuerKeys)).toThrow(`an attestation cannot be signed: it lapses before it was made`);
98
+ const { sig: _sig, ...unsigned } = vouch;
99
+ const long = signedAs({ ...unsigned, validUntil: NOW + S2S_ATTESTATION_VALID_MAX_MS + 1 });
100
+ expect(verifyAttestation(long, subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `it claims to be valid for more than a year` });
101
+ });
102
+
103
+ it("fails once any claim, date or party is changed after signing", () => {
104
+ const changes: readonly Partial<S2sSandboxVouch>[] = [
105
+ { claims: { ...vouch.claims, over18: false } },
106
+ { claims: { ...vouch.claims, country: `DE` } },
107
+ { claims: { ...vouch.claims, extra: `added` } },
108
+ { validUntil: vouch.validUntil + 1 },
109
+ { issuedAt: vouch.issuedAt - 1 },
110
+ { subject: { ...vouch.subject, address: `elsewhere.example` } },
111
+ { issuer: { ...vouch.issuer, name: `Notary Inc.` } },
112
+ ];
113
+ for (const change of changes) {
114
+ expect(verifyAttestation(tampered(change), subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `its signature does not verify` });
115
+ }
116
+ });
117
+
118
+ it("fails when its issuer's keys are not the ones its fingerprint is over, or another's keys signed it", () => {
119
+ const other = keySetFor(`impostor`);
120
+ expect(verifyAttestation(tampered({ issuer: { ...vouch.issuer, keys: other.public } }), subjectDoc, at)).toEqual({
121
+ ok: false,
122
+ trusted: false,
123
+ reason: `its issuer's fingerprint is not over the keys it carries`,
124
+ });
125
+ const forged = signAttestation(input, other);
126
+ expect(verifyAttestation({ ...forged, issuer: vouch.issuer }, subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `its signature does not verify` });
127
+ });
128
+
129
+ it("fails against another sandbox's document, or a key of this one it does not name", () => {
130
+ const elsewhere = signIdentity({ ...facts, sandbox: `ba9876543210` }, first);
131
+ expect(verifyAttestation(vouch, elsewhere, at)).toEqual({ ok: false, trusted: false, reason: `it is about sandbox ${facts.sandbox}, not ba9876543210` });
132
+ const rekeyed = signIdentity(facts, second);
133
+ expect(verifyAttestation(vouch, rekeyed, at)).toEqual({
134
+ ok: false,
135
+ trusted: false,
136
+ reason: `it names key ${first.fingerprint}, which is neither this sandbox's key nor the one before it: its issuer has to vouch again`,
137
+ });
138
+ });
139
+
140
+ it("still holds after the subject rotated once, and not after a second rotation or a recovery", () => {
141
+ expect(verifyAttestation(vouch, rotatedOnce, at)).toEqual({ ok: true, trusted: false });
142
+ const twice = verifyAttestation(vouch, rotatedTwice, at);
143
+ expect(twice).toEqual({ ok: false, trusted: false, reason: `it names key ${first.fingerprint}, which is neither this sandbox's key nor the one before it: its issuer has to vouch again` });
144
+ expect(verifyAttestation(vouch, recovered, at).ok).toBe(false);
145
+ });
146
+
147
+ it("is refused from the subject itself, under its key or the one before", () => {
148
+ const own = signAttestation({ ...input, issuer: { sandbox: facts.sandbox, address: facts.host } }, first);
149
+ expect(verifyAttestation(own, subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `a sandbox cannot vouch for itself` });
150
+ const before = signAttestation({ ...input, subject: { ...input.subject, fingerprint: second.fingerprint } }, first);
151
+ expect(verifyAttestation(before, rotatedOnce, at)).toEqual({ ok: false, trusted: false, reason: `a sandbox cannot vouch for itself` });
152
+ });
153
+
154
+ it("has one id for what it says, whoever re-signs it, and another once anything it says changes", () => {
155
+ const again = signAttestation(input, issuerKeys);
156
+ expect(attestationIdOf(again)).toBe(attestationIdOf(vouch));
157
+ expect(attestationIdOf(vouch)).toMatch(/^[a-z2-7]{26}$/u);
158
+ expect(attestationIdOf(signAttestation({ ...input, claims: { kind: `person` } }, issuerKeys))).not.toBe(attestationIdOf(vouch));
159
+ });
160
+ });
161
+
162
+ describe("other attestation types", () => {
163
+ const eudi = S2sAttestationSchema.parse({
164
+ v: 1,
165
+ type: `eudi-pid`,
166
+ format: `dc+sd-jwt`,
167
+ presentation: `eyJhbGciOiJFUzI1NiJ9.e30.c2ln~`,
168
+ subject: input.subject,
169
+ issuedAt: NOW,
170
+ validUntil: NOW + DAY * 30,
171
+ });
172
+ const future = S2sAttestationSchema.parse({ type: `zk-uniqueness`, v: 3, proof: `AAEC`, nested: { deep: [1, 2] } });
173
+
174
+ it("parses an EU wallet's slot and says it is not supported yet", () => {
175
+ expect(eudi.type).toBe(`eudi-pid`);
176
+ expect(verifyAttestation(eudi, subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `an EU wallet attestation is not supported yet` });
177
+ });
178
+
179
+ it("keeps a type this build does not know whole, and never takes it", () => {
180
+ expect(future).toEqual({ type: `zk-uniqueness`, v: 3, proof: `AAEC`, nested: { deep: [1, 2] } });
181
+ expect(verifyAttestation(future, subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `a zk-uniqueness attestation is not one this build reads` });
182
+ expect(sandboxVouchOf(future)).toBe(undefined);
183
+ });
184
+
185
+ it("keeps a vouch it cannot read whole too, a later version or a field nested deeper", () => {
186
+ const later = S2sAttestationSchema.parse({ ...vouch, v: 2 });
187
+ expect(later).toEqual({ ...vouch, v: 2 });
188
+ expect(verifyAttestation(later, subjectDoc, at)).toEqual({ ok: false, trusted: false, reason: `it does not read as a sandbox vouch` });
189
+ const deeper = S2sAttestationSchema.parse({ ...vouch, issuer: { ...vouch.issuer, keys: { ...vouch.issuer.keys, slhdsa: `AAAA` } } });
190
+ expect(canonicalJson(deeper)).toBe(canonicalJson({ ...vouch, issuer: { ...vouch.issuer, keys: { ...vouch.issuer.keys, slhdsa: `AAAA` } } }));
191
+ });
192
+ });
193
+
194
+ describe("an identity document carrying attestations", () => {
195
+ const later = S2sAttestationSchema.parse({ type: `zk-uniqueness`, v: 3, proof: `AAEC` });
196
+ const carrying = signIdentity({ ...facts, attestations: [vouch, later] }, first);
197
+ // The schema of a build from before attestations: the same loose document, without the field.
198
+ const EarlierSchema = SandboxIdentitySchema.omit({ attestations: true }).loose();
199
+
200
+ it("lists them in its signed body, and leaves the field out when there are none, as before attestations", () => {
201
+ expect(carrying.attestations).toEqual([vouch, later]);
202
+ expect(verifyIdentity(carrying)).toEqual({ ok: true });
203
+ expect(Object.keys(signIdentity({ ...facts, attestations: [] }, first))).not.toContain(`attestations`);
204
+ // ML-DSA signs with fresh randomness, so the bodies are compared: the very bytes signed before attestations existed.
205
+ const { sig: _none, ...withNone } = signIdentity({ ...facts, attestations: [] }, first);
206
+ const { sig: _before, ...before } = subjectDoc;
207
+ expect(canonicalJson(withNone)).toBe(canonicalJson(before));
208
+ });
209
+
210
+ it("parses and verifies under this build's schema and an earlier build's, which keeps the field it does not know", () => {
211
+ const wire = JSON.parse(JSON.stringify(carrying));
212
+ const here = SandboxIdentitySchema.parse(wire);
213
+ expect(here).toEqual(carrying);
214
+ expect(verifyIdentity(here)).toEqual({ ok: true });
215
+ const earlier = EarlierSchema.parse(wire);
216
+ expect(earlier[`attestations`]).toEqual(wire.attestations);
217
+ expect(verifyIdentity(SandboxIdentitySchema.parse(earlier))).toEqual({ ok: true });
218
+ });
219
+
220
+ it("has each checked against it once the document itself verifies", () => {
221
+ expect(verifyAttestations(carrying, { ...at, trustedIssuers: [issuerKeys.fingerprint] })).toEqual([
222
+ { id: attestationIdOf(vouch), attestation: vouch, check: { ok: true, trusted: true } },
223
+ { id: attestationIdOf(later), attestation: later, check: { ok: false, trusted: false, reason: `a zk-uniqueness attestation is not one this build reads` } },
224
+ ]);
225
+ expect(verifyAttestations({ ...carrying, name: `opz` }, at).map((checked) => checked.check)).toEqual([
226
+ { ok: false, trusted: false, reason: `the document carrying it does not verify: its signature does not verify` },
227
+ { ok: false, trusted: false, reason: `the document carrying it does not verify: its signature does not verify` },
228
+ ]);
229
+ });
230
+
231
+ it("fits the most this sandbox keeps, each as large as a vouch gets, beside the largest document, inside what a daemon reads", () => {
232
+ const longest = (label: string): string => `${label}${`a`.repeat(63 - label.length)}`;
233
+ const domains = Array.from({ length: S2S_DOMAINS_MAX }, (_, index) => `${longest(`d${index}`)}.${longest(`x`)}.${longest(`y`)}.${`z`.repeat(53)}.example`);
234
+ // Claims filled to the last byte they may take.
235
+ const claims: Record<string, string> = {};
236
+ for (let index = 0; index < S2S_CLAIMS_MAX; index++) {
237
+ const room = S2S_CLAIMS_BYTES_MAX - JSON.stringify({ ...claims, [`claim${index}`]: `` }).length;
238
+ if (room > 0) {
239
+ claims[`claim${index}`] = `x`.repeat(Math.min(S2S_CLAIM_VALUE_MAX, room));
240
+ }
241
+ }
242
+ expect(JSON.stringify(claims).length).toBe(S2S_CLAIMS_BYTES_MAX);
243
+ const largest = Array.from({ length: S2S_ATTESTATIONS_KEPT_MAX }, (_, index) =>
244
+ signAttestation(
245
+ {
246
+ ...input,
247
+ issuer: { sandbox: `i`.repeat(100), address: domains[index] ?? ``, name: `n`.repeat(120) },
248
+ subject: { sandbox: `s`.repeat(100), address: domains[index] ?? ``, fingerprint: second.fingerprint },
249
+ claims,
250
+ },
251
+ keySetFor(`issuer ${index}`),
252
+ ),
253
+ );
254
+ const fullest = signIdentity(
255
+ { ...facts, name: `n`.repeat(120), domains, attestations: largest },
256
+ second,
257
+ vouchFor(facts.sandbox, second, { by: `key`, keySet: first }, NOW),
258
+ );
259
+ expect(SandboxIdentitySchema.parse(fullest).domains.map((domain) => domain.length)).toEqual(Array.from({ length: S2S_DOMAINS_MAX }, () => 253));
260
+ expect(new TextEncoder().encode(JSON.stringify(fullest)).length).toBeLessThanOrEqual(S2S_IDENTITY_MAX_BYTES);
261
+ });
262
+ });
@@ -0,0 +1,173 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import {
3
+ S2S_ATTESTATION_VALID_MAX_MS,
4
+ type S2sAttestation,
5
+ type S2sClaims,
6
+ S2sClaimsSchema,
7
+ type S2sSandboxVouch,
8
+ S2sSandboxVouchSchema,
9
+ type SandboxIdentity,
10
+ } from "../../schemas/s2s-identity.js";
11
+ import { canonicalBytes, toBase32 } from "./canonical.js";
12
+ import { verifyIdentity } from "./identity-doc.js";
13
+ import { fingerprintOf, type S2sKeySet, secretKeysOf } from "./keys.js";
14
+ import { hybridSign, hybridVerify } from "./sign.js";
15
+
16
+ // ATTESTATIONS (schemas/s2s-identity.ts S2sAttestationSchema, docs/architecture/messages.md "Attestations"): one sandbox's
17
+ // signed word about another, which the other carries in its own identity document. Pure: making one under a key set,
18
+ // and checking one against the document of the sandbox it is about. A check says whether it is what it says (the
19
+ // issuer's keys, its signature, its dates, its subject), and separately whether the reader trusts its issuer, which only
20
+ // the reader's own list of fingerprints decides: nothing here vouches for any issuer.
21
+
22
+ // How far ahead of the reader's clock an attestation may be dated, as for an envelope.
23
+ const ISSUED_AHEAD_MAX_MS = 5 * 60 * 1000;
24
+
25
+ // Who signs, as the issuing sandbox's own document says it.
26
+ export interface AttestationIssuer {
27
+ readonly sandbox: string;
28
+ readonly address: string;
29
+ readonly name?: string | undefined;
30
+ }
31
+
32
+ // What the issuer vouches for, about which sandbox under which key, and for how long.
33
+ export interface AttestationInput {
34
+ readonly issuer: AttestationIssuer;
35
+ readonly subject: { readonly sandbox: string; readonly address: string; readonly fingerprint: string };
36
+ readonly claims: S2sClaims;
37
+ readonly issuedAt: number;
38
+ readonly validUntil: number;
39
+ }
40
+
41
+ // Why the dates cannot be: none, or the reason in words.
42
+ const datesProblem = (issuedAt: number, validUntil: number): string | undefined => {
43
+ if (validUntil <= issuedAt) {
44
+ return "it lapses before it was made";
45
+ }
46
+ return validUntil - issuedAt > S2S_ATTESTATION_VALID_MAX_MS ? "it claims to be valid for more than a year" : undefined;
47
+ };
48
+
49
+ // The bytes a signature is over: the attestation without `sig`, every field this build does not know included.
50
+ const signedBodyOf = (attestation: S2sAttestation): Uint8Array => {
51
+ if (!("sig" in attestation)) {
52
+ return canonicalBytes(attestation);
53
+ }
54
+ const { sig: _sig, ...rest } = attestation;
55
+ return canonicalBytes(rest);
56
+ };
57
+
58
+ /**
59
+ * A `sandbox-vouch` for the input, signed by this key set for `attestation`, carrying its public keys and fingerprint
60
+ * so a reader checks it with nothing else. Throws on claims the schema refuses or dates past a year.
61
+ */
62
+ export const signAttestation = (input: AttestationInput, keySet: S2sKeySet): S2sSandboxVouch => {
63
+ const problem = datesProblem(input.issuedAt, input.validUntil);
64
+ if (problem !== undefined) {
65
+ throw new RangeError(`an attestation cannot be signed: ${problem}`);
66
+ }
67
+ const issuer: S2sSandboxVouch["issuer"] = { sandbox: input.issuer.sandbox, address: input.issuer.address, fingerprint: keySet.fingerprint, keys: { ...keySet.public } };
68
+ if (input.issuer.name !== undefined) {
69
+ issuer.name = input.issuer.name;
70
+ }
71
+ const unsigned: Omit<S2sSandboxVouch, "sig"> = {
72
+ v: 1,
73
+ type: "sandbox-vouch",
74
+ issuer,
75
+ subject: { sandbox: input.subject.sandbox, address: input.subject.address, fingerprint: input.subject.fingerprint },
76
+ claims: S2sClaimsSchema.parse(input.claims),
77
+ issuedAt: input.issuedAt,
78
+ validUntil: input.validUntil,
79
+ };
80
+ return { ...unsigned, sig: hybridSign("attestation", canonicalBytes(unsigned), secretKeysOf(keySet.secret)) };
81
+ };
82
+
83
+ /** An attestation's id: the base32 of the SHA-256 over it without `sig`, cut to 26 characters (130 bits). */
84
+ export const attestationIdOf = (attestation: S2sAttestation): string => toBase32(sha256(signedBodyOf(attestation))).slice(0, 26);
85
+
86
+ /** The attestation as a `sandbox-vouch` this build reads, or undefined when it is another type or does not parse as one. */
87
+ export const sandboxVouchOf = (attestation: S2sAttestation): S2sSandboxVouch | undefined =>
88
+ attestation.type === "sandbox-vouch" ? S2sSandboxVouchSchema.safeParse(attestation).data : undefined;
89
+
90
+ // `trusted` only ever with `ok`: an attestation that is not what it says is trusted by nobody.
91
+ export type AttestationCheck = { readonly ok: true; readonly trusted: boolean } | { readonly ok: false; readonly reason: string; readonly trusted: false };
92
+
93
+ export interface AttestationCheckOptions {
94
+ // The reader's clock, in epoch milliseconds.
95
+ readonly now: number;
96
+ // The issuers this reader trusts, by fingerprint; absent, none.
97
+ readonly trustedIssuers?: Iterable<string> | undefined;
98
+ }
99
+
100
+ const failed = (reason: string): AttestationCheck => ({ ok: false, reason, trusted: false });
101
+
102
+ // The key set fingerprints a document stands for: its own, and the one its `prev` names when the previous key vouched.
103
+ const keysOfDocument = (doc: SandboxIdentity): readonly string[] => (doc.prev?.by === "key" ? [doc.fingerprint, doc.prev.fingerprint] : [doc.fingerprint]);
104
+
105
+ // What is wrong with a vouch about this document as of `now`, cheapest first, the signature last.
106
+ const vouchProblem = (vouch: S2sSandboxVouch, subject: SandboxIdentity, now: number): string | undefined => {
107
+ const keys = keysOfDocument(subject);
108
+ if (fingerprintOf(vouch.issuer.keys) !== vouch.issuer.fingerprint) {
109
+ return "its issuer's fingerprint is not over the keys it carries";
110
+ }
111
+ if (vouch.subject.sandbox !== subject.sandbox) {
112
+ return `it is about sandbox ${vouch.subject.sandbox}, not ${subject.sandbox}`;
113
+ }
114
+ if (keys.includes(vouch.issuer.fingerprint)) {
115
+ return "a sandbox cannot vouch for itself";
116
+ }
117
+ if (!keys.includes(vouch.subject.fingerprint)) {
118
+ return `it names key ${vouch.subject.fingerprint}, which is neither this sandbox's key nor the one before it: its issuer has to vouch again`;
119
+ }
120
+ const dates = datesProblem(vouch.issuedAt, vouch.validUntil);
121
+ if (dates !== undefined) {
122
+ return dates;
123
+ }
124
+ if (vouch.issuedAt > now + ISSUED_AHEAD_MAX_MS) {
125
+ return `it is dated ${new Date(vouch.issuedAt).toISOString()}, ahead of this clock`;
126
+ }
127
+ if (vouch.validUntil <= now) {
128
+ return `it lapsed at ${new Date(vouch.validUntil).toISOString()}`;
129
+ }
130
+ return hybridVerify("attestation", signedBodyOf(vouch), vouch.sig, vouch.issuer.keys) ? undefined : "its signature does not verify";
131
+ };
132
+
133
+ /**
134
+ * Whether an attestation is what it says about the sandbox whose document is given (one the caller already verified,
135
+ * verifyIdentity, or took from verifyAttestations): its issuer's fingerprint is over the keys it carries, its signature
136
+ * verifies under them, it is current, it is about this sandbox, and about this document's key or the one its `prev` was
137
+ * vouched for by (so one rotation keeps it; a second, or a recovery, needs it issued again). `trusted` when, besides, the
138
+ * reader lists its issuer. An `eudi-pid` or a type this build does not know is never `ok`.
139
+ */
140
+ export const verifyAttestation = (attestation: S2sAttestation, subject: SandboxIdentity, opts: AttestationCheckOptions): AttestationCheck => {
141
+ if (attestation.type === "eudi-pid") {
142
+ return failed("an EU wallet attestation is not supported yet");
143
+ }
144
+ if (attestation.type !== "sandbox-vouch") {
145
+ return failed(`a ${attestation.type.slice(0, 64)} attestation is not one this build reads`);
146
+ }
147
+ const vouch = sandboxVouchOf(attestation);
148
+ if (vouch === undefined) {
149
+ return failed("it does not read as a sandbox vouch");
150
+ }
151
+ const problem = vouchProblem(vouch, subject, opts.now);
152
+ if (problem !== undefined) {
153
+ return failed(problem);
154
+ }
155
+ return { ok: true, trusted: new Set(opts.trustedIssuers ?? []).has(vouch.issuer.fingerprint) };
156
+ };
157
+
158
+ // One attestation a document carries, with its id and what checking it came to.
159
+ export interface CheckedAttestation {
160
+ readonly id: string;
161
+ readonly attestation: S2sAttestation;
162
+ readonly check: AttestationCheck;
163
+ }
164
+
165
+ /** Every attestation a document carries, each checked against it, once the document itself verifies; else each fails so. */
166
+ export const verifyAttestations = (doc: SandboxIdentity, opts: AttestationCheckOptions): readonly CheckedAttestation[] => {
167
+ const own = verifyIdentity(doc);
168
+ return (doc.attestations ?? []).map((attestation) => ({
169
+ id: attestationIdOf(attestation),
170
+ attestation,
171
+ check: own.ok ? verifyAttestation(attestation, doc, opts) : failed(`the document carrying it does not verify: ${own.reason}`),
172
+ }));
173
+ };
@@ -0,0 +1,70 @@
1
+ import { canonicalBytes, canonicalJson, equalBytes, fromBase64Url, toBase32, toBase64Url, utf8 } from "./canonical.js";
2
+
3
+ describe("canonical JSON", () => {
4
+ it("sorts keys at every depth and writes no whitespace", () => {
5
+ expect(canonicalJson({ b: 1, a: { d: [3, { z: true, y: null }], c: "x" } })).toBe(`{"a":{"c":"x","d":[3,{"y":null,"z":true}]},"b":1}`);
6
+ });
7
+
8
+ it("sorts by UTF-16 code units, so an uppercase key comes before a lowercase one and é after z", () => {
9
+ expect(canonicalJson({ é: 1, z: 2, Z: 3, a: 4 })).toBe(`{"Z":3,"a":4,"z":2,"é":1}`);
10
+ });
11
+
12
+ it("spells numbers and strings as JSON.stringify does", () => {
13
+ expect(canonicalJson([1e21, 0.1, -0, 5, "a\"b\n", "é"])).toBe(`[1e+21,0.1,0,5,"a\\"b\\n","é"]`);
14
+ });
15
+
16
+ it("refuses undefined, even as a member, and NaN and the infinities", () => {
17
+ const refusal = `canonical JSON: the value is not JSON (an undefined, a NaN or an infinity in it?)`;
18
+ expect(() => canonicalJson({ a: { b: undefined } })).toThrow(refusal);
19
+ expect(() => canonicalJson([1, Number.NaN])).toThrow(refusal);
20
+ expect(() => canonicalJson({ n: Number.POSITIVE_INFINITY })).toThrow(refusal);
21
+ expect(() => canonicalJson(undefined)).toThrow(refusal);
22
+ });
23
+
24
+ it("gives the same bytes whatever order an object was built in", () => {
25
+ expect(equalBytes(canonicalBytes({ x: 1, y: [2] }), canonicalBytes({ y: [2], x: 1 }))).toBe(true);
26
+ expect(equalBytes(canonicalBytes({ x: 1 }), canonicalBytes({ x: 2 }))).toBe(false);
27
+ });
28
+ });
29
+
30
+ describe("base64url", () => {
31
+ it("round-trips every length around a block boundary without padding", () => {
32
+ for (const length of [0, 1, 2, 3, 4, 5, 31, 32, 33]) {
33
+ const bytes = Uint8Array.from({ length }, (_, index) => (index * 37 + 250) % 256);
34
+ const text = toBase64Url(bytes);
35
+ expect(text.includes(`=`)).toBe(false);
36
+ expect(fromBase64Url(text)).toEqual(bytes);
37
+ }
38
+ });
39
+
40
+ it("encodes the RFC 4648 test vectors in the url alphabet", () => {
41
+ expect(toBase64Url(utf8(`foobar`))).toBe(`Zm9vYmFy`);
42
+ expect(toBase64Url(utf8(`fo`))).toBe(`Zm8`);
43
+ expect(toBase64Url(Uint8Array.from([0xfb, 0xff]))).toBe(`-_8`);
44
+ });
45
+
46
+ it("refuses padding, the standard alphabet, an impossible length, and stray low bits", () => {
47
+ expect(fromBase64Url(`Zm8=`)).toBeUndefined();
48
+ expect(fromBase64Url(`+/8`)).toBeUndefined();
49
+ expect(fromBase64Url(`Zm9vY`)).toBeUndefined();
50
+ // `Zm8` is "fo", its last character's two low bits zero; `Zm9` sets one, which no encoder writes.
51
+ expect(fromBase64Url(`Zm8`)).toEqual(utf8(`fo`));
52
+ expect(fromBase64Url(`Zm9`)).toBeUndefined();
53
+ });
54
+ });
55
+
56
+ describe("base32", () => {
57
+ it("encodes the RFC 4648 test vectors, lowercase and unpadded", () => {
58
+ expect(toBase32(utf8(``))).toBe(``);
59
+ expect(toBase32(utf8(`f`))).toBe(`my`);
60
+ expect(toBase32(utf8(`fo`))).toBe(`mzxq`);
61
+ expect(toBase32(utf8(`foo`))).toBe(`mzxw6`);
62
+ expect(toBase32(utf8(`foob`))).toBe(`mzxw6yq`);
63
+ expect(toBase32(utf8(`fooba`))).toBe(`mzxw6ytb`);
64
+ expect(toBase32(utf8(`foobar`))).toBe(`mzxw6ytboi`);
65
+ });
66
+
67
+ it("spells a SHA-256 in 52 characters", () => {
68
+ expect(toBase32(new Uint8Array(32)).length).toBe(52);
69
+ });
70
+ });
@@ -0,0 +1,119 @@
1
+ import { z } from "zod";
2
+
3
+ // The bytes every s2s signature and key derivation is over, and the encodings keys and signatures travel in. Pure
4
+ // functions on Uint8Array, no Buffer and no node:crypto, so they read the same under Node, Bun and a browser.
5
+
6
+ const JsonSchema = z.json();
7
+ type Json = z.infer<typeof JsonSchema>;
8
+
9
+ const byKey = ([a]: readonly [string, Json], [b]: readonly [string, Json]): number => (a < b ? -1 : a > b ? 1 : 0);
10
+
11
+ const serialize = (value: Json): string => {
12
+ if (Array.isArray(value)) {
13
+ return `[${value.map((item) => serialize(item)).join(",")}]`;
14
+ }
15
+ if (value === null || !(value instanceof Object)) {
16
+ return JSON.stringify(value);
17
+ }
18
+ // Sorted by UTF-16 code units, JSON.stringify's own string order (RFC 8785).
19
+ const members = Object.entries(value).toSorted(byKey);
20
+ return `{${members.map(([key, member]) => `${JSON.stringify(key)}:${serialize(member)}`).join(",")}}`;
21
+ };
22
+
23
+ // One spelling per value: keys sorted at every depth, no whitespace, numbers and strings as JSON.stringify writes them.
24
+ // Throws on anything JSON cannot carry exactly (undefined, even as a member: leave the key out; NaN; the infinities), since
25
+ // each would sign a value other than the one meant.
26
+ export const canonicalJson = <T>(value: T): string => {
27
+ const parsed = JsonSchema.safeParse(value);
28
+ if (!parsed.success) {
29
+ throw new TypeError("canonical JSON: the value is not JSON (an undefined, a NaN or an infinity in it?)");
30
+ }
31
+ return serialize(parsed.data);
32
+ };
33
+
34
+ const encoder = new TextEncoder();
35
+ export const utf8 = (text: string): Uint8Array => encoder.encode(text);
36
+ export const fromUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8", { fatal: true }).decode(bytes);
37
+
38
+ // The canonical JSON's UTF-8 bytes: what is signed and hashed.
39
+ export const canonicalBytes = <T>(value: T): Uint8Array => utf8(canonicalJson(value));
40
+
41
+ export const concatBytes = (...parts: readonly Uint8Array[]): Uint8Array => {
42
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
43
+ let at = 0;
44
+ for (const part of parts) {
45
+ out.set(part, at);
46
+ at += part.length;
47
+ }
48
+ return out;
49
+ };
50
+
51
+ export const equalBytes = (left: Uint8Array, right: Uint8Array): boolean => {
52
+ if (left.length !== right.length) {
53
+ return false;
54
+ }
55
+ let diff = 0;
56
+ for (let index = 0; index < left.length; index++) {
57
+ diff |= (left[index] ?? 0) ^ (right[index] ?? 0);
58
+ }
59
+ return diff === 0;
60
+ };
61
+
62
+ const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
63
+ const BASE64URL_INDEX = new Map([...BASE64URL].map((char, index) => [char, index]));
64
+
65
+ // Base64url (RFC 4648 §5), no padding.
66
+ export const toBase64Url = (bytes: Uint8Array): string => {
67
+ let out = "";
68
+ for (let at = 0; at < bytes.length; at += 3) {
69
+ const chunk = ((bytes[at] ?? 0) << 16) | ((bytes[at + 1] ?? 0) << 8) | (bytes[at + 2] ?? 0);
70
+ const chars = Math.min(4, Math.ceil(((bytes.length - at) * 8) / 6));
71
+ for (let index = 0; index < chars; index++) {
72
+ out += BASE64URL[(chunk >> (18 - index * 6)) & 63];
73
+ }
74
+ }
75
+ return out;
76
+ };
77
+
78
+ // The bytes of a base64url string, or undefined for anything but the one spelling toBase64Url gives them: no padding, no
79
+ // other alphabet, and no stray bits in the last character, so two strings never stand for the same bytes.
80
+ export const fromBase64Url = (text: string): Uint8Array | undefined => {
81
+ if (text.length % 4 === 1) {
82
+ return undefined;
83
+ }
84
+ const out = new Uint8Array(Math.floor((text.length * 6) / 8));
85
+ let buffer = 0;
86
+ let bits = 0;
87
+ let at = 0;
88
+ for (const char of text) {
89
+ const value = BASE64URL_INDEX.get(char);
90
+ if (value === undefined) {
91
+ return undefined;
92
+ }
93
+ buffer = ((buffer << 6) | value) & 0xffffff;
94
+ bits += 6;
95
+ if (bits >= 8) {
96
+ bits -= 8;
97
+ out[at++] = (buffer >> bits) & 0xff;
98
+ }
99
+ }
100
+ return (buffer & ((1 << bits) - 1)) === 0 ? out : undefined;
101
+ };
102
+
103
+ const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
104
+
105
+ // Base32 (RFC 4648 §6), lowercase, no padding: what a fingerprint is spelled in, so a person can read it aloud.
106
+ export const toBase32 = (bytes: Uint8Array): string => {
107
+ let out = "";
108
+ let buffer = 0;
109
+ let bits = 0;
110
+ for (const byte of bytes) {
111
+ buffer = ((buffer << 8) | byte) & 0xffff;
112
+ bits += 8;
113
+ while (bits >= 5) {
114
+ bits -= 5;
115
+ out += BASE32[(buffer >> bits) & 31];
116
+ }
117
+ }
118
+ return bits > 0 ? out + BASE32[(buffer << (5 - bits)) & 31] : out;
119
+ };