burnledger 0.8.1 → 0.9.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 (124) hide show
  1. package/README.md +139 -2
  2. package/dist/cjs/anchor.d.ts +5 -3
  3. package/dist/cjs/anchor.d.ts.map +1 -1
  4. package/dist/cjs/anchor.js +10 -4
  5. package/dist/cjs/anchor.js.map +1 -1
  6. package/dist/cjs/client.d.ts +95 -0
  7. package/dist/cjs/client.d.ts.map +1 -1
  8. package/dist/cjs/client.js +133 -2
  9. package/dist/cjs/client.js.map +1 -1
  10. package/dist/cjs/customer-keys.d.ts +73 -1
  11. package/dist/cjs/customer-keys.d.ts.map +1 -1
  12. package/dist/cjs/customer-keys.js +329 -3
  13. package/dist/cjs/customer-keys.js.map +1 -1
  14. package/dist/cjs/enclave-registration.d.ts +153 -0
  15. package/dist/cjs/enclave-registration.d.ts.map +1 -0
  16. package/dist/cjs/enclave-registration.js +275 -0
  17. package/dist/cjs/enclave-registration.js.map +1 -0
  18. package/dist/cjs/enclave-seal.d.ts +43 -0
  19. package/dist/cjs/enclave-seal.d.ts.map +1 -1
  20. package/dist/cjs/enclave-seal.js +62 -1
  21. package/dist/cjs/enclave-seal.js.map +1 -1
  22. package/dist/cjs/errors.d.ts +10 -0
  23. package/dist/cjs/errors.d.ts.map +1 -1
  24. package/dist/cjs/errors.js +11 -1
  25. package/dist/cjs/errors.js.map +1 -1
  26. package/dist/cjs/index.browser.d.ts +7 -3
  27. package/dist/cjs/index.browser.d.ts.map +1 -1
  28. package/dist/cjs/index.browser.js +6 -3
  29. package/dist/cjs/index.browser.js.map +1 -1
  30. package/dist/cjs/index.d.ts +22 -10
  31. package/dist/cjs/index.d.ts.map +1 -1
  32. package/dist/cjs/index.js +30 -6
  33. package/dist/cjs/index.js.map +1 -1
  34. package/dist/cjs/key-group.d.ts +80 -0
  35. package/dist/cjs/key-group.d.ts.map +1 -0
  36. package/dist/cjs/key-group.js +136 -0
  37. package/dist/cjs/key-group.js.map +1 -0
  38. package/dist/cjs/models.d.ts +60 -0
  39. package/dist/cjs/models.d.ts.map +1 -1
  40. package/dist/cjs/models.js +63 -0
  41. package/dist/cjs/models.js.map +1 -1
  42. package/dist/cjs/status-document.d.ts +25 -0
  43. package/dist/cjs/status-document.d.ts.map +1 -0
  44. package/dist/cjs/status-document.js +62 -0
  45. package/dist/cjs/status-document.js.map +1 -0
  46. package/dist/cjs/verify.d.ts +108 -3
  47. package/dist/cjs/verify.d.ts.map +1 -1
  48. package/dist/cjs/verify.js +389 -146
  49. package/dist/cjs/verify.js.map +1 -1
  50. package/dist/cjs/web-verifier.d.ts +23 -3
  51. package/dist/cjs/web-verifier.d.ts.map +1 -1
  52. package/dist/cjs/web-verifier.js +31 -5
  53. package/dist/cjs/web-verifier.js.map +1 -1
  54. package/dist/esm/anchor.d.ts +5 -3
  55. package/dist/esm/anchor.d.ts.map +1 -1
  56. package/dist/esm/anchor.js +10 -4
  57. package/dist/esm/anchor.js.map +1 -1
  58. package/dist/esm/cli.d.ts +13 -19
  59. package/dist/esm/cli.d.ts.map +1 -1
  60. package/dist/esm/cli.js +88 -81
  61. package/dist/esm/cli.js.map +1 -1
  62. package/dist/esm/client.d.ts +95 -0
  63. package/dist/esm/client.d.ts.map +1 -1
  64. package/dist/esm/client.js +133 -2
  65. package/dist/esm/client.js.map +1 -1
  66. package/dist/esm/customer-keys.d.ts +73 -1
  67. package/dist/esm/customer-keys.d.ts.map +1 -1
  68. package/dist/esm/customer-keys.js +323 -3
  69. package/dist/esm/customer-keys.js.map +1 -1
  70. package/dist/esm/enclave-registration.d.ts +153 -0
  71. package/dist/esm/enclave-registration.d.ts.map +1 -0
  72. package/dist/esm/enclave-registration.js +265 -0
  73. package/dist/esm/enclave-registration.js.map +1 -0
  74. package/dist/esm/enclave-seal.d.ts +43 -0
  75. package/dist/esm/enclave-seal.d.ts.map +1 -1
  76. package/dist/esm/enclave-seal.js +61 -1
  77. package/dist/esm/enclave-seal.js.map +1 -1
  78. package/dist/esm/errors.d.ts +10 -0
  79. package/dist/esm/errors.d.ts.map +1 -1
  80. package/dist/esm/errors.js +10 -0
  81. package/dist/esm/errors.js.map +1 -1
  82. package/dist/esm/index.browser.d.ts +7 -3
  83. package/dist/esm/index.browser.d.ts.map +1 -1
  84. package/dist/esm/index.browser.js +6 -3
  85. package/dist/esm/index.browser.js.map +1 -1
  86. package/dist/esm/index.d.ts +22 -10
  87. package/dist/esm/index.d.ts.map +1 -1
  88. package/dist/esm/index.js +18 -8
  89. package/dist/esm/index.js.map +1 -1
  90. package/dist/esm/key-group.d.ts +80 -0
  91. package/dist/esm/key-group.d.ts.map +1 -0
  92. package/dist/esm/key-group.js +130 -0
  93. package/dist/esm/key-group.js.map +1 -0
  94. package/dist/esm/models.d.ts +60 -0
  95. package/dist/esm/models.d.ts.map +1 -1
  96. package/dist/esm/models.js +59 -0
  97. package/dist/esm/models.js.map +1 -1
  98. package/dist/esm/status-document.d.ts +25 -0
  99. package/dist/esm/status-document.d.ts.map +1 -0
  100. package/dist/esm/status-document.js +59 -0
  101. package/dist/esm/status-document.js.map +1 -0
  102. package/dist/esm/verify.d.ts +108 -3
  103. package/dist/esm/verify.d.ts.map +1 -1
  104. package/dist/esm/verify.js +386 -146
  105. package/dist/esm/verify.js.map +1 -1
  106. package/dist/esm/web-verifier.d.ts +23 -3
  107. package/dist/esm/web-verifier.d.ts.map +1 -1
  108. package/dist/esm/web-verifier.js +27 -5
  109. package/dist/esm/web-verifier.js.map +1 -1
  110. package/package.json +1 -1
  111. package/src/anchor.ts +10 -4
  112. package/src/cli.ts +96 -79
  113. package/src/client.ts +198 -6
  114. package/src/customer-keys.ts +373 -3
  115. package/src/enclave-registration.ts +390 -0
  116. package/src/enclave-seal.ts +108 -1
  117. package/src/errors.ts +11 -0
  118. package/src/index.browser.ts +9 -3
  119. package/src/index.ts +35 -6
  120. package/src/key-group.ts +181 -0
  121. package/src/models.ts +131 -0
  122. package/src/status-document.ts +59 -0
  123. package/src/verify.ts +499 -151
  124. package/src/web-verifier.ts +36 -3
@@ -0,0 +1,390 @@
1
+ /**
2
+ * The customer's side of ADR-025: verify the enclave, enrol a key group, rotate
3
+ * it, register a system under it.
4
+ *
5
+ * Request-building and response-checking for the BurnLedger client's methods of
6
+ * the same names, kept in a Node-only module the client imports lazily — the
7
+ * client is also the browser entry's, and these need node:crypto. Nothing here
8
+ * holds a private key: every signature comes from a {@link KeyGroupSigner} (see
9
+ * key-group.ts for why, and for what losing a key costs).
10
+ *
11
+ * WHAT THE CHECKS ON EACH RESPONSE ARE FOR. The API relays every byte, so the
12
+ * documents it returns are only worth what the client checks, and it checks two
13
+ * things. First, that the enclave signed them — under the signing key of an
14
+ * enclave the caller attested against its own pinned PCR0. Without that, a relay
15
+ * could hand the customer a forged enrolment and they would believe themselves
16
+ * registered when nothing was. The key set at /.well-known/burnledger-keys is not
17
+ * the anchor for this: the same API serves it, so a relay that forged a document
18
+ * could publish the forging key beside it. Second, that they are about what the
19
+ * caller asked for. ADR-025 §2 names the load-bearing comparison: the enrolment
20
+ * statement must name the key group the customer generated. A relay that enrolled
21
+ * its own group instead would hand back a genuine, enclave-signed statement
22
+ * naming a key the customer does not hold; this comparison is where that stops
23
+ * being invisible. The enrolment and the authorization must also be for the team
24
+ * the customer named, and the authorization must end exactly at the `not_after`
25
+ * the customer signed and not start in the future: a relay that replayed an
26
+ * older genuine answer, or another team's, would otherwise have the caller
27
+ * believe a fresh window exists. The registration must name this key, this
28
+ * system, this config digest and this connector, or it registered something
29
+ * else.
30
+ */
31
+
32
+ import { createHash, webcrypto } from "node:crypto";
33
+ import { nodeCrypto } from "./crypto-node.js";
34
+ import {
35
+ buildKeyEnrollmentRequestPayload,
36
+ buildKeyRotationRequestPayload,
37
+ buildSystemRegistrationRequestPayload,
38
+ customerKeyId,
39
+ keyTime,
40
+ verifyKeyEnrollmentStatement,
41
+ verifySystemRegistration,
42
+ verifyTeamAuthorization,
43
+ type CustomerKeyGroup,
44
+ } from "./customer-keys.js";
45
+ import {
46
+ IDENTITY_NONCE_SIZE,
47
+ verifyEnclaveIdentity,
48
+ type EnclaveIdentity,
49
+ type SealOptions,
50
+ } from "./enclave-seal.js";
51
+ import { VerificationError } from "./errors.js";
52
+ import { signWithGroup, type KeyGroupSigner } from "./key-group.js";
53
+ import {
54
+ parseKeyEnrollmentResult,
55
+ parseSystemRegistrationCertificate,
56
+ type KeyEnrollmentResult,
57
+ type System,
58
+ type SystemRegistrationCertificate,
59
+ } from "./models.js";
60
+ import { formatTimestamp } from "./verify.js";
61
+
62
+ type Raw = Record<string, unknown>;
63
+
64
+ /** How to check the enclave: the PCR0 you pinned out of band, and optionally
65
+ * your own challenge (otherwise 32 bytes are drawn from the OS CSPRNG). */
66
+ export interface EnclavePinOptions extends SealOptions {
67
+ nonce?: Uint8Array;
68
+ }
69
+
70
+ /** What `createRegisteredSystem` did, in order. */
71
+ export interface RegisteredSystem {
72
+ /** The system, created with its config sealed so the API never read it. */
73
+ readonly system: System;
74
+ /** The enclave's registration of that system under your key group. */
75
+ readonly registration: SystemRegistrationCertificate;
76
+ }
77
+
78
+ /** Mirrors core.DefaultAuthorizationWindow, the longest window the enclave
79
+ * grants: a request that names no `notAfter` asks for all of it. */
80
+ const DEFAULT_AUTHORIZATION_WINDOW_MS = 90 * 24 * 60 * 60 * 1000;
81
+
82
+ /** How far ahead of this machine's clock an authorization may start: room for
83
+ * an enclave clock that runs a little ahead, as core's notAfterSkew leaves room
84
+ * for a customer clock that does. Not room for a document from the future. */
85
+ const NOT_BEFORE_SKEW_MS = 5 * 60 * 1000;
86
+
87
+ function toHex(bytes: Uint8Array): string {
88
+ return Buffer.from(bytes).toString("hex");
89
+ }
90
+
91
+ function sha256(bytes: Uint8Array): Uint8Array {
92
+ return new Uint8Array(createHash("sha256").update(bytes).digest());
93
+ }
94
+
95
+ function boundOf(notAfter: Date | undefined): Date {
96
+ return notAfter ?? new Date(Date.now() + DEFAULT_AUTHORIZATION_WINDOW_MS);
97
+ }
98
+
99
+ // --- ATTEST_IDENTITY ----------------------------------------------------------
100
+
101
+ /**
102
+ * The challenge and the query string that carries it. A nonce the checked party
103
+ * chose — including one the API suggested — proves nothing about when the
104
+ * document was produced, so it is drawn here unless the caller brings its own.
105
+ */
106
+ export function attestationParams(nonce?: Uint8Array): {
107
+ nonce: Uint8Array;
108
+ params: Record<string, string>;
109
+ } {
110
+ const drawn = nonce ?? webcrypto.getRandomValues(new Uint8Array(IDENTITY_NONCE_SIZE));
111
+ return { nonce: drawn, params: { nonce: Buffer.from(drawn).toString("base64url") } };
112
+ }
113
+
114
+ /**
115
+ * Verify the document the API returned against this caller's own challenge. The
116
+ * `nonce` the API echoes beside the document is ignored: nothing signs it. The
117
+ * check is against the nonce inside the document, under AWS's signature.
118
+ */
119
+ export async function identityFromResponse(
120
+ data: unknown,
121
+ options: SealOptions & { nonce: Uint8Array },
122
+ ): Promise<EnclaveIdentity> {
123
+ const raw = (data as Raw | null)?.nsm_attestation;
124
+ if (typeof raw !== "string") {
125
+ throw new VerificationError("the attestation response carries no nsm_attestation");
126
+ }
127
+ return verifyEnclaveIdentity(new Uint8Array(Buffer.from(raw, "base64")), options);
128
+ }
129
+
130
+ // --- ENROLL_KEY / ROTATE_KEY --------------------------------------------------
131
+
132
+ function groupBody(group: CustomerKeyGroup, signatures: Record<string, string>): Raw {
133
+ return {
134
+ threshold: group.threshold,
135
+ member_keys: group.members.map(toHex),
136
+ signatures,
137
+ };
138
+ }
139
+
140
+ /**
141
+ * The ENROLL_KEY request, the key id it enrols and the `not_after` it signs.
142
+ * EVERY member signs.
143
+ */
144
+ export async function enrollBody(opts: {
145
+ teamId: string;
146
+ group: CustomerKeyGroup;
147
+ signers: readonly KeyGroupSigner[];
148
+ notAfter?: Date;
149
+ }): Promise<{ body: Raw; keyId: string; notAfter: string }> {
150
+ const keyId = await customerKeyId(nodeCrypto, opts.group);
151
+ const bound = boundOf(opts.notAfter);
152
+ const payload = buildKeyEnrollmentRequestPayload({
153
+ assertedTeamId: opts.teamId,
154
+ customerKeyId: keyId,
155
+ notAfter: bound,
156
+ });
157
+ const signatures = await signWithGroup(payload, opts.group, opts.signers, opts.group.members.length);
158
+ const notAfter = keyTime(bound);
159
+ return {
160
+ body: {
161
+ asserted_team_id: opts.teamId.toLowerCase(),
162
+ not_after: notAfter,
163
+ ...groupBody(opts.group, signatures),
164
+ },
165
+ keyId,
166
+ notAfter,
167
+ };
168
+ }
169
+
170
+ /**
171
+ * The ROTATE_KEY request. Both groups sign the same key_rotation_request.v2: the
172
+ * OUTGOING group at its threshold, to spend its authority, and EVERY incoming
173
+ * member, to prove it holds its key.
174
+ */
175
+ export async function rotateBody(opts: {
176
+ teamId: string;
177
+ previousGroup: CustomerKeyGroup;
178
+ previousSigners: readonly KeyGroupSigner[];
179
+ nextGroup: CustomerKeyGroup;
180
+ nextSigners: readonly KeyGroupSigner[];
181
+ notAfter?: Date;
182
+ }): Promise<{ body: Raw; prevKeyId: string; nextKeyId: string; notAfter: string }> {
183
+ const prevKeyId = await customerKeyId(nodeCrypto, opts.previousGroup);
184
+ const nextKeyId = await customerKeyId(nodeCrypto, opts.nextGroup);
185
+ const bound = boundOf(opts.notAfter);
186
+ const payload = buildKeyRotationRequestPayload({
187
+ assertedTeamId: opts.teamId,
188
+ prevKeyId,
189
+ nextKeyId,
190
+ notAfter: bound,
191
+ });
192
+ const signatures = await signWithGroup(
193
+ payload,
194
+ opts.previousGroup,
195
+ opts.previousSigners,
196
+ opts.previousGroup.threshold,
197
+ );
198
+ const nextSignatures = await signWithGroup(
199
+ payload,
200
+ opts.nextGroup,
201
+ opts.nextSigners,
202
+ opts.nextGroup.members.length,
203
+ );
204
+ const notAfter = keyTime(bound);
205
+ return {
206
+ body: {
207
+ asserted_team_id: opts.teamId.toLowerCase(),
208
+ prev_key_id: prevKeyId,
209
+ not_after: notAfter,
210
+ next_signatures: nextSignatures,
211
+ ...groupBody(opts.nextGroup, signatures),
212
+ },
213
+ prevKeyId,
214
+ nextKeyId,
215
+ notAfter,
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Verify both documents ENROLL_KEY and ROTATE_KEY return under the attested
221
+ * enclave's signing key, then refuse them unless they name the group this caller
222
+ * holds and the team it asked for, link to the predecessor it expects, end
223
+ * exactly at the `notAfter` (whole-second UTC) it signed, and do not start in
224
+ * the future. `teamId` is the team the request asserted; the SDK always asserts
225
+ * one, so there is no request this check has no team for.
226
+ *
227
+ * The end must be EXACT. A protocol-12 enclave ends the grant at the signed
228
+ * bound, to the second, so any other end answers some other request -- which is
229
+ * what a relay replaying an older genuine response, or dropping a renewal,
230
+ * hands back.
231
+ */
232
+ export async function checkEnrollment(
233
+ data: unknown,
234
+ opts: {
235
+ enclave: EnclaveIdentity;
236
+ keyId: string;
237
+ prevKeyId: string | undefined;
238
+ teamId: string;
239
+ notAfter: string;
240
+ /** The time to judge `not_before` against. Defaults to this machine's clock. */
241
+ now?: Date;
242
+ },
243
+ ): Promise<KeyEnrollmentResult> {
244
+ const raw = (data ?? {}) as Raw;
245
+ await verifyKeyEnrollmentStatement(nodeCrypto, raw.enrollment, opts.enclave.signingKey);
246
+ await verifyTeamAuthorization(nodeCrypto, raw.authorization, opts.enclave.signingKey);
247
+ const result = parseKeyEnrollmentResult(raw);
248
+ const { enrollment, authorization } = result;
249
+ // One comparison covers the members and threshold too: a key id is a hash
250
+ // over both, and a verified statement's id is the one its own group derives.
251
+ if (enrollment.customerKeyId !== opts.keyId || authorization.customerKeyId !== opts.keyId) {
252
+ throw new VerificationError(
253
+ `the enclave's statement names key ${JSON.stringify(enrollment.customerKeyId)} ` +
254
+ `(authorization ${JSON.stringify(authorization.customerKeyId)}), not the group you ` +
255
+ `enrolled (${JSON.stringify(opts.keyId)}). Do not use it: this is what a substituted key looks like.`,
256
+ );
257
+ }
258
+ if (authorization.prevKeyId !== opts.prevKeyId) {
259
+ throw new VerificationError(
260
+ `the authorization links to predecessor ${JSON.stringify(authorization.prevKeyId ?? null)}, ` +
261
+ `expected ${JSON.stringify(opts.prevKeyId ?? null)}`,
262
+ );
263
+ }
264
+ const team = opts.teamId.toLowerCase();
265
+ for (const [what, named] of [
266
+ ["enrolment statement", enrollment.assertedTeamId],
267
+ ["authorization", authorization.assertedTeamId],
268
+ ] as const) {
269
+ if (named.toLowerCase() !== team) {
270
+ throw new VerificationError(
271
+ `the ${what} is for team ${named}, not the team you asked for (${team}). ` +
272
+ "Do not use it: a relay replaying another team's answer would produce exactly this.",
273
+ );
274
+ }
275
+ }
276
+ // Compared as the whole-second strings both sides sign, not as parsed
277
+ // dates: a Date has milliseconds, and a fraction on the wire is nobody's.
278
+ const granted = formatTimestamp((raw.authorization as Raw).not_after, "authorization.not_after");
279
+ if (granted !== opts.notAfter) {
280
+ throw new VerificationError(
281
+ `the authorization ends at ${granted}, not at the not_after you signed (${opts.notAfter}). ` +
282
+ "The enclave ends the grant exactly there, so this answers some other request; " +
283
+ "a relay replaying an older response would produce exactly this.",
284
+ );
285
+ }
286
+ const now = opts.now ?? new Date();
287
+ if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
288
+ throw new TypeError("now must be a valid Date");
289
+ }
290
+ if (authorization.notBefore.getTime() > now.getTime() + NOT_BEFORE_SKEW_MS) {
291
+ const starts = formatTimestamp((raw.authorization as Raw).not_before, "authorization.not_before");
292
+ throw new VerificationError(
293
+ `the authorization starts at ${starts}, more than five minutes after this machine's clock ` +
294
+ `(${keyTime(now)}): the answer to a request just made cannot start in the future`,
295
+ );
296
+ }
297
+ return result;
298
+ }
299
+
300
+ // --- REGISTER_SYSTEM ----------------------------------------------------------
301
+
302
+ /** The exact bytes sealed, and therefore the bytes `config_digest` is over. */
303
+ export function configBytes(config: Record<string, unknown>): Uint8Array {
304
+ return new TextEncoder().encode(JSON.stringify(config));
305
+ }
306
+
307
+ /**
308
+ * The REGISTER_SYSTEM request, its key id and the config digest it signs.
309
+ *
310
+ * `config` must be the EXACT bytes submitted when the system was created — the
311
+ * plaintext that was sealed, or the `connection_config` JSON text as sent. An
312
+ * object is refused: re-serializing it produces bytes that may differ by one
313
+ * space from what the enclave decrypts, and the refusal would be a 401 with no
314
+ * way to see why.
315
+ */
316
+ export async function registrationBody(opts: {
317
+ teamId: string;
318
+ group: CustomerKeyGroup;
319
+ signers: readonly KeyGroupSigner[];
320
+ systemId: string;
321
+ config: Uint8Array | string;
322
+ queryTemplate: string;
323
+ connectorType: string;
324
+ }): Promise<{ body: Raw; keyId: string; configDigest: Uint8Array }> {
325
+ const config =
326
+ typeof opts.config === "string" ? new TextEncoder().encode(opts.config) : opts.config;
327
+ if (!(config instanceof Uint8Array)) {
328
+ throw new TypeError(
329
+ "config must be the exact bytes (or text) submitted when the system was created, " +
330
+ "not a re-serializable object",
331
+ );
332
+ }
333
+ const keyId = await customerKeyId(nodeCrypto, opts.group);
334
+ const configDigest = sha256(config);
335
+ const payload = buildSystemRegistrationRequestPayload({
336
+ assertedTeamId: opts.teamId,
337
+ systemId: opts.systemId,
338
+ configDigest,
339
+ queryTemplateSha256: sha256(new TextEncoder().encode(opts.queryTemplate)),
340
+ connectorType: opts.connectorType,
341
+ customerKeyId: keyId,
342
+ });
343
+ const signatures = await signWithGroup(payload, opts.group, opts.signers, opts.group.threshold);
344
+ return {
345
+ body: {
346
+ asserted_team_id: opts.teamId.toLowerCase(),
347
+ system_id: opts.systemId.toLowerCase(),
348
+ query_template: opts.queryTemplate,
349
+ ...groupBody(opts.group, signatures),
350
+ },
351
+ keyId,
352
+ configDigest,
353
+ };
354
+ }
355
+
356
+ /** Verify the registration under the attested enclave's signing key, then
357
+ * refuse it unless it binds what this caller signed. */
358
+ export async function checkRegistration(
359
+ data: unknown,
360
+ opts: {
361
+ enclave: EnclaveIdentity;
362
+ keyId: string;
363
+ systemId: string;
364
+ configDigest: Uint8Array;
365
+ connectorType: string;
366
+ },
367
+ ): Promise<SystemRegistrationCertificate> {
368
+ const raw = (data as Raw | null)?.registration;
369
+ await verifySystemRegistration(nodeCrypto, raw, opts.enclave.signingKey);
370
+ const registration = parseSystemRegistrationCertificate(raw as Raw);
371
+ const wrong: string[] = [];
372
+ if (registration.customerKeyId !== opts.keyId) {
373
+ wrong.push(`customer_key_id is ${JSON.stringify(registration.customerKeyId)}, expected ${JSON.stringify(opts.keyId)}`);
374
+ }
375
+ if (String(registration.systemId).toLowerCase() !== opts.systemId.toLowerCase()) {
376
+ wrong.push(`system_id is ${JSON.stringify(registration.systemId)}, expected ${JSON.stringify(opts.systemId)}`);
377
+ }
378
+ if (toHex(registration.configDigest) !== toHex(opts.configDigest)) {
379
+ wrong.push(`config_digest is ${toHex(registration.configDigest)}, expected ${toHex(opts.configDigest)}`);
380
+ }
381
+ if (registration.connectorType !== opts.connectorType) {
382
+ wrong.push(`connector_type is ${JSON.stringify(registration.connectorType)}, expected ${JSON.stringify(opts.connectorType)}`);
383
+ }
384
+ if (wrong.length > 0) {
385
+ throw new VerificationError(
386
+ `the enclave's registration does not bind what you signed: ${wrong.join(", ")}`,
387
+ );
388
+ }
389
+ return registration;
390
+ }
@@ -34,7 +34,13 @@
34
34
  * point.
35
35
  */
36
36
 
37
- import { X509Certificate, verify as nodeVerify, webcrypto } from "node:crypto";
37
+ import {
38
+ X509Certificate,
39
+ createHash,
40
+ timingSafeEqual,
41
+ verify as nodeVerify,
42
+ webcrypto,
43
+ } from "node:crypto";
38
44
 
39
45
  /**
40
46
  * Envelope wire format (v1). Must match enclave/configsealkey.go byte for byte:
@@ -183,6 +189,103 @@ export async function verifyEnclaveConfigSealKey(
183
189
  attestationDocument: Uint8Array,
184
190
  options: SealOptions,
185
191
  ): Promise<Uint8Array> {
192
+ return configSealKeyOf(verifyDocument(attestationDocument, options));
193
+ }
194
+
195
+ /** Mirrors enclave.AttestIdentityNonceSize. */
196
+ export const IDENTITY_NONCE_SIZE = 32;
197
+
198
+ /**
199
+ * What an ATTEST_IDENTITY document establishes once verified: which keys, held
200
+ * by an enclave running which image, answering THIS caller's challenge.
201
+ */
202
+ export interface EnclaveIdentity {
203
+ /** The X25519 key to seal connection configs to. */
204
+ readonly configSealKey: Uint8Array;
205
+ /** The enclave's Ed25519 signing key, read out of the signed document. */
206
+ readonly signingKey: Uint8Array;
207
+ /** `dp_k_` + hex(SHA-256(signingKey)) — the id /.well-known/burnledger-keys publishes. */
208
+ readonly signingKeyId: string;
209
+ /** The PCR0 the document reports, hex. Equal to the one pinned, or this would have thrown. */
210
+ readonly pcr0: string;
211
+ }
212
+
213
+ export interface IdentityOptions extends SealOptions {
214
+ /**
215
+ * The 32-byte challenge sent with the request. Draw it from your own entropy:
216
+ * a nonce the party being checked chose proves nothing about when the
217
+ * document was produced.
218
+ */
219
+ nonce: Uint8Array;
220
+ }
221
+
222
+ /**
223
+ * Verify an ATTEST_IDENTITY document (`GET /v1/enclave/attestation?nonce=`).
224
+ *
225
+ * Port of enclave.VerifyIdentityAttestation: everything
226
+ * {@link verifyEnclaveConfigSealKey} checks, and then that the document carries
227
+ * exactly the nonce this caller sent and binds a 32-byte Ed25519 signing key in
228
+ * `user_data`.
229
+ *
230
+ * THE NONCE CHECK IS THE POINT. The other checks pass for every document this
231
+ * enclave image has ever produced, including one captured months ago and
232
+ * replayed by a relay that has since swapped keys. Only a document carrying the
233
+ * challenge this caller drew, under AWS's signature, is a statement about now.
234
+ *
235
+ * What a pass means, and no more: these keys are held by an AWS Nitro Enclave
236
+ * running an image that measures to the pinned PCR0, and it answered this
237
+ * challenge within five minutes of `now`. It does not mean the image was built
238
+ * from any particular source.
239
+ */
240
+ export async function verifyEnclaveIdentity(
241
+ attestationDocument: Uint8Array,
242
+ options: IdentityOptions,
243
+ ): Promise<EnclaveIdentity> {
244
+ const sent = options.nonce;
245
+ if (!(sent instanceof Uint8Array) || sent.length !== IDENTITY_NONCE_SIZE) {
246
+ throw new EnclaveAttestationError(
247
+ `challenge nonce is ${sent instanceof Uint8Array ? sent.length : 0} bytes, want exactly ` +
248
+ `${IDENTITY_NONCE_SIZE} (this is a bug in the caller, not a bad document)`,
249
+ );
250
+ }
251
+ const payload = verifyDocument(attestationDocument, options);
252
+ const carried = payload.get("nonce");
253
+ if (
254
+ !(carried instanceof Uint8Array) ||
255
+ carried.length !== sent.length ||
256
+ !timingSafeEqual(carried, sent)
257
+ ) {
258
+ throw new EnclaveAttestationError(
259
+ `the document answers a different challenge than the one sent (sent ${toHex(sent)}, ` +
260
+ `document carries ${carried instanceof Uint8Array ? toHex(carried) : "none"}) — a genuine ` +
261
+ "document replayed for someone else's nonce proves nothing about now",
262
+ );
263
+ }
264
+ const signingKey = payload.get("user_data");
265
+ if (!(signingKey instanceof Uint8Array) || signingKey.length !== 32) {
266
+ const got = signingKey instanceof Uint8Array ? signingKey.length : 0;
267
+ throw new EnclaveAttestationError(
268
+ `the document binds ${got} bytes where an Ed25519 public key belongs, want 32`,
269
+ );
270
+ }
271
+ const pcr0 = (payload.get("pcrs") as Map<unknown, unknown>).get(0) as Uint8Array;
272
+ return {
273
+ configSealKey: configSealKeyOf(payload),
274
+ signingKey,
275
+ signingKeyId: "dp_k_" + createHash("sha256").update(signingKey).digest("hex"),
276
+ pcr0: toHex(pcr0),
277
+ };
278
+ }
279
+
280
+ /**
281
+ * The checks every enclave document gets, whatever is read out of it after:
282
+ * COSE structure and algorithm, the chain to the pinned root, the signature, the
283
+ * AWS timestamp against `now`, and the pinned PCRs. Returns the verified payload.
284
+ */
285
+ function verifyDocument(
286
+ attestationDocument: Uint8Array,
287
+ options: SealOptions,
288
+ ): Map<unknown, unknown> {
186
289
  if (!attestationDocument || attestationDocument.length === 0) {
187
290
  throw new EnclaveAttestationError(
188
291
  "no attestation document (nothing to verify — this is not a pass)",
@@ -218,7 +321,11 @@ export async function verifyEnclaveConfigSealKey(
218
321
  verifyCoseSignature(leaf, protectedBytes, payloadBytes, signature);
219
322
  checkClock(payload.get("timestamp"), now);
220
323
  matchPcrs(pcrs, expected);
324
+ return payload;
325
+ }
221
326
 
327
+ /** The 32-byte X25519 config-seal key a verified payload binds in `public_key`. */
328
+ function configSealKeyOf(payload: Map<unknown, unknown>): Uint8Array {
222
329
  const publicKey = payload.get("public_key");
223
330
  if (!(publicKey instanceof Uint8Array) || publicKey.length !== KEY_SIZE) {
224
331
  const got = publicKey instanceof Uint8Array ? publicKey.length : 0;
package/src/errors.ts CHANGED
@@ -125,6 +125,17 @@ export class VerificationError extends BurnLedgerError {
125
125
  /** {@link VerificationError.code} for a verified statement that says REVOKED. */
126
126
  export const CERTIFICATE_REVOKED = "CERTIFICATE_REVOKED";
127
127
 
128
+ /**
129
+ * {@link VerificationError.code} when a record verified but does not meet the
130
+ * `requireAuthorization` policy the caller asked for: a system that is not
131
+ * `certified`, one certified under a key the caller does not accept, a required
132
+ * system the record does not cover, a format that predates registration, or a
133
+ * record from an enclave image that could say `certified` without the customer's
134
+ * signature (protocol 11 or earlier, or none named). A fact about the record,
135
+ * not a failure to read it.
136
+ */
137
+ export const AUTHORIZATION_POLICY_FAILED = "AUTHORIZATION_POLICY_FAILED";
138
+
128
139
  /**
129
140
  * The record is in a format this SDK does not know how to read.
130
141
  *
@@ -69,17 +69,23 @@ import {
69
69
  verifyConsistency as _verifyConsistency,
70
70
  publicKeyFromHex as _publicKeyFromHex,
71
71
  } from "./verify.js";
72
- import type { PublicKeyInfo, PublicKeyOptions } from "./verify.js";
72
+ import type { PublicKeyInfo, PublicKeyOptions, VerifyOptions } from "./verify.js";
73
73
  import type { VerificationResult, TransparencyResult } from "./models.js";
74
74
 
75
+ export type { AuthorizationPolicy, VerifyOptions } from "./verify.js";
76
+
75
77
  type Cert = Record<string, unknown>;
76
78
 
77
- /** Verify all signatures on a deletion certificate offline. */
79
+ /** Verify all signatures on a deletion certificate offline. Pass
80
+ * `{ requireAuthorization }` to refuse a record unless its systems are certified
81
+ * under a key id you name, by an enclave image that requires that key group's
82
+ * signature to register a system (ADR-025). */
78
83
  export function verifyCertificate(
79
84
  certificate: Cert,
80
85
  publicKeys: Map<string, PublicKeyInfo>,
86
+ options?: VerifyOptions,
81
87
  ): Promise<VerificationResult> {
82
- return _verifyCertificate(browserCrypto, certificate, publicKeys);
88
+ return _verifyCertificate(browserCrypto, certificate, publicKeys, options);
83
89
  }
84
90
 
85
91
  /** Verify the transparency proof embedded in a certificate. */
package/src/index.ts CHANGED
@@ -14,6 +14,7 @@ export {
14
14
  ServerError,
15
15
  TimeoutError,
16
16
  VerificationError,
17
+ AUTHORIZATION_POLICY_FAILED,
17
18
  CERTIFICATE_REVOKED,
18
19
  UNSUPPORTED_FORMAT_VERSION,
19
20
  } from "./errors.js";
@@ -21,7 +22,7 @@ export {
21
22
  export { Transport } from "./http.js";
22
23
  export type { TransportOptions } from "./http.js";
23
24
 
24
- export type { PublicKeyOptions } from "./verify.js";
25
+ export type { AuthorizationPolicy, PublicKeyOptions, VerifyOptions } from "./verify.js";
25
26
 
26
27
  export type {
27
28
  ProofMode,
@@ -62,6 +63,10 @@ export type {
62
63
  PlanUsage,
63
64
  Profile,
64
65
  SystemHealth,
66
+ KeyEnrollmentStatement,
67
+ TeamAuthorizationCertificate,
68
+ SystemRegistrationCertificate,
69
+ KeyEnrollmentResult,
65
70
  } from "./models.js";
66
71
 
67
72
  // Raw-JSON → model parsers, for consumers that fetch API responses outside
@@ -82,17 +87,21 @@ import {
82
87
  verifyConsistency as _verifyConsistency,
83
88
  publicKeyFromHex as _publicKeyFromHex,
84
89
  } from "./verify.js";
85
- import type { PublicKeyInfo, PublicKeyOptions } from "./verify.js";
90
+ import type { PublicKeyInfo, PublicKeyOptions, VerifyOptions } from "./verify.js";
86
91
  import type { VerificationResult, TransparencyResult } from "./models.js";
87
92
 
88
93
  type Cert = Record<string, unknown>;
89
94
 
90
- /** Verify all signatures on a deletion certificate offline. */
95
+ /** Verify all signatures on a deletion certificate offline. Pass
96
+ * `{ requireAuthorization }` to refuse a record unless its systems are certified
97
+ * under a key id you name, by an enclave image that requires that key group's
98
+ * signature to register a system (ADR-025). */
91
99
  export function verifyCertificate(
92
100
  certificate: Cert,
93
101
  publicKeys: Map<string, PublicKeyInfo>,
102
+ options?: VerifyOptions,
94
103
  ): Promise<VerificationResult> {
95
- return _verifyCertificate(nodeCrypto, certificate, publicKeys);
104
+ return _verifyCertificate(nodeCrypto, certificate, publicKeys, options);
96
105
  }
97
106
 
98
107
  /**
@@ -106,8 +115,9 @@ export function verifyCertificateWithStatus(
106
115
  publicKeys: Map<string, PublicKeyInfo>,
107
116
  status?: Record<string, unknown> | null,
108
117
  now?: Date,
118
+ options?: VerifyOptions,
109
119
  ): Promise<string> {
110
- return _verifyCertificateWithStatus(nodeCrypto, certificate, publicKeys, status, now);
120
+ return _verifyCertificateWithStatus(nodeCrypto, certificate, publicKeys, status, now, options);
111
121
  }
112
122
 
113
123
  /** Verify the transparency proof embedded in a certificate. */
@@ -159,22 +169,41 @@ export {
159
169
  EnclaveAttestationError,
160
170
  ENVELOPE_MAGIC,
161
171
  HEADER_SIZE,
172
+ IDENTITY_NONCE_SIZE,
162
173
  NITRO_ROOT_G1_PEM,
163
174
  sealConnectionConfig,
164
175
  sealToKey,
165
176
  verifyEnclaveConfigSealKey,
177
+ verifyEnclaveIdentity,
166
178
  } from "./enclave-seal.js";
167
- export type { SealOptions } from "./enclave-seal.js";
179
+ export type { EnclaveIdentity, IdentityOptions, SealOptions } from "./enclave-seal.js";
168
180
 
169
181
  export {
170
182
  CUSTOMER_KEY_ID_PREFIX,
171
183
  InvalidKeyGroupError,
172
184
  MAX_CUSTOMER_KEY_GROUP_MEMBERS,
185
+ PAYLOAD_TYPE_KEY_ENROLLMENT_REQUEST,
173
186
  PAYLOAD_TYPE_KEY_ROTATION_REQUEST,
187
+ PAYLOAD_TYPE_SYSTEM_REGISTRATION_REQUEST,
188
+ buildKeyEnrollmentRequestPayload,
174
189
  buildKeyRotationRequestPayload,
190
+ buildSystemRegistrationRequestPayload,
175
191
  customerKeyId,
176
192
  memberFingerprint,
177
193
  memberFingerprints,
178
194
  validateKeyGroup,
195
+ verifyKeyEnrollmentStatement,
196
+ verifySystemRegistration,
197
+ verifyTeamAuthorization,
179
198
  } from "./customer-keys.js";
180
199
  export type { CustomerKeyGroup } from "./customer-keys.js";
200
+
201
+ /**
202
+ * Customer key group members as signers (ADR-025). Node only. The SDK never
203
+ * holds a private key: every signature comes from a KeyGroupSigner, and
204
+ * InMemorySigner is the convenience for keys kept on this machine. Read the
205
+ * custody note in key-group.ts before generating a group.
206
+ */
207
+ export { InMemorySigner, generateKeyGroup, signWithGroup } from "./key-group.js";
208
+ export type { GeneratedKeyGroup, KeyGroupSigner } from "./key-group.js";
209
+ export type { EnclavePinOptions, RegisteredSystem } from "./enclave-registration.js";