@bcts/xid 1.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1923 @@
1
+ import { ALLOW, CAPABILITY, DELEGATE, DENY, DEREFERENCE_VIA, ENDPOINT, KEY, NAME, NICKNAME, PRIVATE_KEY, PRIVILEGE_ACCESS, PRIVILEGE_ALL, PRIVILEGE_AUTH, PRIVILEGE_BURN, PRIVILEGE_DELEGATE, PRIVILEGE_ELECT, PRIVILEGE_ELIDE, PRIVILEGE_ENCRYPT, PRIVILEGE_ISSUE, PRIVILEGE_REVOKE, PRIVILEGE_SIGN, PRIVILEGE_TRANSFER, PRIVILEGE_UPDATE, PRIVILEGE_VERIFY, PROVENANCE, PROVENANCE_GENERATOR, SALT, SERVICE } from "@bcts/known-values";
2
+ import { Envelope, PrivateKeyBase, PublicKeyBase } from "@bcts/envelope";
3
+ import { Reference, Salt, XID } from "@bcts/components";
4
+ import { ProvenanceMark, ProvenanceMarkGenerator, ProvenanceMarkResolution } from "@bcts/provenance-mark";
5
+ import { cborData, decodeCbor } from "@bcts/dcbor";
6
+
7
+ //#region src/error.ts
8
+ /**
9
+ * XID Error Types
10
+ *
11
+ * Error types returned when operating on XID Documents.
12
+ * Ported from bc-xid-rust/src/error.rs
13
+ */
14
+ let XIDErrorCode = /* @__PURE__ */ function(XIDErrorCode$1) {
15
+ XIDErrorCode$1["DUPLICATE"] = "DUPLICATE";
16
+ XIDErrorCode$1["NOT_FOUND"] = "NOT_FOUND";
17
+ XIDErrorCode$1["STILL_REFERENCED"] = "STILL_REFERENCED";
18
+ XIDErrorCode$1["EMPTY_VALUE"] = "EMPTY_VALUE";
19
+ XIDErrorCode$1["UNKNOWN_PRIVILEGE"] = "UNKNOWN_PRIVILEGE";
20
+ XIDErrorCode$1["INVALID_XID"] = "INVALID_XID";
21
+ XIDErrorCode$1["MISSING_INCEPTION_KEY"] = "MISSING_INCEPTION_KEY";
22
+ XIDErrorCode$1["INVALID_RESOLUTION_METHOD"] = "INVALID_RESOLUTION_METHOD";
23
+ XIDErrorCode$1["MULTIPLE_PROVENANCE_MARKS"] = "MULTIPLE_PROVENANCE_MARKS";
24
+ XIDErrorCode$1["UNEXPECTED_PREDICATE"] = "UNEXPECTED_PREDICATE";
25
+ XIDErrorCode$1["UNEXPECTED_NESTED_ASSERTIONS"] = "UNEXPECTED_NESTED_ASSERTIONS";
26
+ XIDErrorCode$1["NO_PERMISSIONS"] = "NO_PERMISSIONS";
27
+ XIDErrorCode$1["NO_REFERENCES"] = "NO_REFERENCES";
28
+ XIDErrorCode$1["UNKNOWN_KEY_REFERENCE"] = "UNKNOWN_KEY_REFERENCE";
29
+ XIDErrorCode$1["UNKNOWN_DELEGATE_REFERENCE"] = "UNKNOWN_DELEGATE_REFERENCE";
30
+ XIDErrorCode$1["KEY_NOT_FOUND_IN_DOCUMENT"] = "KEY_NOT_FOUND_IN_DOCUMENT";
31
+ XIDErrorCode$1["DELEGATE_NOT_FOUND_IN_DOCUMENT"] = "DELEGATE_NOT_FOUND_IN_DOCUMENT";
32
+ XIDErrorCode$1["INVALID_PASSWORD"] = "INVALID_PASSWORD";
33
+ XIDErrorCode$1["ENVELOPE_NOT_SIGNED"] = "ENVELOPE_NOT_SIGNED";
34
+ XIDErrorCode$1["SIGNATURE_VERIFICATION_FAILED"] = "SIGNATURE_VERIFICATION_FAILED";
35
+ XIDErrorCode$1["NO_PROVENANCE_MARK"] = "NO_PROVENANCE_MARK";
36
+ XIDErrorCode$1["GENERATOR_CONFLICT"] = "GENERATOR_CONFLICT";
37
+ XIDErrorCode$1["NO_GENERATOR"] = "NO_GENERATOR";
38
+ XIDErrorCode$1["CHAIN_ID_MISMATCH"] = "CHAIN_ID_MISMATCH";
39
+ XIDErrorCode$1["SEQUENCE_MISMATCH"] = "SEQUENCE_MISMATCH";
40
+ XIDErrorCode$1["ENVELOPE_PARSING"] = "ENVELOPE_PARSING";
41
+ XIDErrorCode$1["COMPONENT"] = "COMPONENT";
42
+ XIDErrorCode$1["CBOR"] = "CBOR";
43
+ XIDErrorCode$1["PROVENANCE_MARK"] = "PROVENANCE_MARK";
44
+ return XIDErrorCode$1;
45
+ }({});
46
+ var XIDError = class XIDError extends Error {
47
+ code;
48
+ constructor(code, message, cause) {
49
+ super(message);
50
+ this.name = "XIDError";
51
+ this.code = code;
52
+ if (cause !== void 0) this.cause = cause;
53
+ if ("captureStackTrace" in Error) Error.captureStackTrace(this, XIDError);
54
+ }
55
+ /**
56
+ * Returned when attempting to add a duplicate item.
57
+ */
58
+ static duplicate(item) {
59
+ return new XIDError(XIDErrorCode.DUPLICATE, `duplicate item: ${item}`);
60
+ }
61
+ /**
62
+ * Returned when an item is not found.
63
+ */
64
+ static notFound(item) {
65
+ return new XIDError(XIDErrorCode.NOT_FOUND, `item not found: ${item}`);
66
+ }
67
+ /**
68
+ * Returned when an item is still referenced by other items.
69
+ */
70
+ static stillReferenced(item) {
71
+ return new XIDError(XIDErrorCode.STILL_REFERENCED, `item is still referenced: ${item}`);
72
+ }
73
+ /**
74
+ * Returned when a value is invalid or empty.
75
+ */
76
+ static emptyValue(field) {
77
+ return new XIDError(XIDErrorCode.EMPTY_VALUE, `invalid or empty value: ${field}`);
78
+ }
79
+ /**
80
+ * Returned when an unknown privilege is encountered.
81
+ */
82
+ static unknownPrivilege() {
83
+ return new XIDError(XIDErrorCode.UNKNOWN_PRIVILEGE, "unknown privilege");
84
+ }
85
+ /**
86
+ * Returned when the XID is invalid.
87
+ */
88
+ static invalidXid() {
89
+ return new XIDError(XIDErrorCode.INVALID_XID, "invalid XID");
90
+ }
91
+ /**
92
+ * Returned when the inception key is missing.
93
+ */
94
+ static missingInceptionKey() {
95
+ return new XIDError(XIDErrorCode.MISSING_INCEPTION_KEY, "missing inception key");
96
+ }
97
+ /**
98
+ * Returned when the resolution method is invalid.
99
+ */
100
+ static invalidResolutionMethod() {
101
+ return new XIDError(XIDErrorCode.INVALID_RESOLUTION_METHOD, "invalid resolution method");
102
+ }
103
+ /**
104
+ * Returned when multiple provenance marks are found.
105
+ */
106
+ static multipleProvenanceMarks() {
107
+ return new XIDError(XIDErrorCode.MULTIPLE_PROVENANCE_MARKS, "multiple provenance marks");
108
+ }
109
+ /**
110
+ * Returned when an unexpected predicate is encountered.
111
+ */
112
+ static unexpectedPredicate(predicate) {
113
+ return new XIDError(XIDErrorCode.UNEXPECTED_PREDICATE, `unexpected predicate: ${predicate}`);
114
+ }
115
+ /**
116
+ * Returned when unexpected nested assertions are found.
117
+ */
118
+ static unexpectedNestedAssertions() {
119
+ return new XIDError(XIDErrorCode.UNEXPECTED_NESTED_ASSERTIONS, "unexpected nested assertions");
120
+ }
121
+ /**
122
+ * Returned when a service has no permissions.
123
+ */
124
+ static noPermissions(uri) {
125
+ return new XIDError(XIDErrorCode.NO_PERMISSIONS, `no permissions in service '${uri}'`);
126
+ }
127
+ /**
128
+ * Returned when a service has no key or delegate references.
129
+ */
130
+ static noReferences(uri) {
131
+ return new XIDError(XIDErrorCode.NO_REFERENCES, `no key or delegate references in service '${uri}'`);
132
+ }
133
+ /**
134
+ * Returned when an unknown key reference is found in a service.
135
+ */
136
+ static unknownKeyReference(reference, uri) {
137
+ return new XIDError(XIDErrorCode.UNKNOWN_KEY_REFERENCE, `unknown key reference ${reference} in service '${uri}'`);
138
+ }
139
+ /**
140
+ * Returned when an unknown delegate reference is found in a service.
141
+ */
142
+ static unknownDelegateReference(reference, uri) {
143
+ return new XIDError(XIDErrorCode.UNKNOWN_DELEGATE_REFERENCE, `unknown delegate reference ${reference} in service '${uri}'`);
144
+ }
145
+ /**
146
+ * Returned when a key is not found in the XID document.
147
+ */
148
+ static keyNotFoundInDocument(key) {
149
+ return new XIDError(XIDErrorCode.KEY_NOT_FOUND_IN_DOCUMENT, `key not found in XID document: ${key}`);
150
+ }
151
+ /**
152
+ * Returned when a delegate is not found in the XID document.
153
+ */
154
+ static delegateNotFoundInDocument(delegate) {
155
+ return new XIDError(XIDErrorCode.DELEGATE_NOT_FOUND_IN_DOCUMENT, `delegate not found in XID document: ${delegate}`);
156
+ }
157
+ /**
158
+ * Returned when the password is invalid.
159
+ */
160
+ static invalidPassword() {
161
+ return new XIDError(XIDErrorCode.INVALID_PASSWORD, "invalid password");
162
+ }
163
+ /**
164
+ * Returned when the envelope is not signed.
165
+ */
166
+ static envelopeNotSigned() {
167
+ return new XIDError(XIDErrorCode.ENVELOPE_NOT_SIGNED, "envelope is not signed");
168
+ }
169
+ /**
170
+ * Returned when signature verification fails.
171
+ */
172
+ static signatureVerificationFailed() {
173
+ return new XIDError(XIDErrorCode.SIGNATURE_VERIFICATION_FAILED, "signature verification failed");
174
+ }
175
+ /**
176
+ * Returned when there is no provenance mark to advance.
177
+ */
178
+ static noProvenanceMark() {
179
+ return new XIDError(XIDErrorCode.NO_PROVENANCE_MARK, "no provenance mark to advance");
180
+ }
181
+ /**
182
+ * Returned when document already has generator but external generator was provided.
183
+ */
184
+ static generatorConflict() {
185
+ return new XIDError(XIDErrorCode.GENERATOR_CONFLICT, "document already has generator, cannot provide external generator");
186
+ }
187
+ /**
188
+ * Returned when document does not have generator but needs one.
189
+ */
190
+ static noGenerator() {
191
+ return new XIDError(XIDErrorCode.NO_GENERATOR, "document does not have generator, must provide external generator");
192
+ }
193
+ /**
194
+ * Returned when generator chain ID doesn't match.
195
+ */
196
+ static chainIdMismatch(expected, actual) {
197
+ const expectedHex = Array.from(expected).map((b) => b.toString(16).padStart(2, "0")).join("");
198
+ const actualHex = Array.from(actual).map((b) => b.toString(16).padStart(2, "0")).join("");
199
+ return new XIDError(XIDErrorCode.CHAIN_ID_MISMATCH, `generator chain ID mismatch: expected ${expectedHex}, got ${actualHex}`);
200
+ }
201
+ /**
202
+ * Returned when generator sequence doesn't match.
203
+ */
204
+ static sequenceMismatch(expected, actual) {
205
+ return new XIDError(XIDErrorCode.SEQUENCE_MISMATCH, `generator sequence mismatch: expected ${expected}, got ${actual}`);
206
+ }
207
+ /**
208
+ * Envelope parsing error wrapper.
209
+ */
210
+ static envelopeParsing(cause) {
211
+ return new XIDError(XIDErrorCode.ENVELOPE_PARSING, "envelope parsing error", cause);
212
+ }
213
+ /**
214
+ * Component error wrapper.
215
+ */
216
+ static component(cause) {
217
+ return new XIDError(XIDErrorCode.COMPONENT, "component error", cause);
218
+ }
219
+ /**
220
+ * CBOR error wrapper.
221
+ */
222
+ static cbor(cause) {
223
+ return new XIDError(XIDErrorCode.CBOR, "CBOR error", cause);
224
+ }
225
+ /**
226
+ * Provenance mark error wrapper.
227
+ */
228
+ static provenanceMark(cause) {
229
+ return new XIDError(XIDErrorCode.PROVENANCE_MARK, "provenance mark error", cause);
230
+ }
231
+ };
232
+
233
+ //#endregion
234
+ //#region src/privilege.ts
235
+ /**
236
+ * XID Privileges
237
+ *
238
+ * Defines the various privileges that can be granted to keys and delegates
239
+ * in an XID document.
240
+ *
241
+ * Ported from bc-xid-rust/src/privilege.rs
242
+ */
243
+ /**
244
+ * Enum representing XID privileges.
245
+ */
246
+ let Privilege = /* @__PURE__ */ function(Privilege$1) {
247
+ /** Allow all applicable XID operations */
248
+ Privilege$1["All"] = "All";
249
+ /** Authenticate as the subject (e.g., log into services) */
250
+ Privilege$1["Auth"] = "Auth";
251
+ /** Sign digital communications as the subject */
252
+ Privilege$1["Sign"] = "Sign";
253
+ /** Encrypt messages from the subject */
254
+ Privilege$1["Encrypt"] = "Encrypt";
255
+ /** Elide data under the subject's control */
256
+ Privilege$1["Elide"] = "Elide";
257
+ /** Issue or revoke verifiable credentials on the subject's authority */
258
+ Privilege$1["Issue"] = "Issue";
259
+ /** Access resources under the subject's control */
260
+ Privilege$1["Access"] = "Access";
261
+ /** Delegate privileges to third parties */
262
+ Privilege$1["Delegate"] = "Delegate";
263
+ /** Verify (update) the XID document */
264
+ Privilege$1["Verify"] = "Verify";
265
+ /** Update service endpoints */
266
+ Privilege$1["Update"] = "Update";
267
+ /** Remove the inception key from the XID document */
268
+ Privilege$1["Transfer"] = "Transfer";
269
+ /** Add or remove other verifiers (rotate keys) */
270
+ Privilege$1["Elect"] = "Elect";
271
+ /** Transition to a new provenance mark chain */
272
+ Privilege$1["Burn"] = "Burn";
273
+ /** Revoke the XID entirely */
274
+ Privilege$1["Revoke"] = "Revoke";
275
+ return Privilege$1;
276
+ }({});
277
+ /**
278
+ * Convert a Privilege to its corresponding KnownValue.
279
+ */
280
+ function privilegeToKnownValue(privilege) {
281
+ switch (privilege) {
282
+ case Privilege.All: return PRIVILEGE_ALL;
283
+ case Privilege.Auth: return PRIVILEGE_AUTH;
284
+ case Privilege.Sign: return PRIVILEGE_SIGN;
285
+ case Privilege.Encrypt: return PRIVILEGE_ENCRYPT;
286
+ case Privilege.Elide: return PRIVILEGE_ELIDE;
287
+ case Privilege.Issue: return PRIVILEGE_ISSUE;
288
+ case Privilege.Access: return PRIVILEGE_ACCESS;
289
+ case Privilege.Delegate: return PRIVILEGE_DELEGATE;
290
+ case Privilege.Verify: return PRIVILEGE_VERIFY;
291
+ case Privilege.Update: return PRIVILEGE_UPDATE;
292
+ case Privilege.Transfer: return PRIVILEGE_TRANSFER;
293
+ case Privilege.Elect: return PRIVILEGE_ELECT;
294
+ case Privilege.Burn: return PRIVILEGE_BURN;
295
+ case Privilege.Revoke: return PRIVILEGE_REVOKE;
296
+ default: throw XIDError.unknownPrivilege();
297
+ }
298
+ }
299
+ /**
300
+ * Convert a KnownValue to its corresponding Privilege.
301
+ */
302
+ function privilegeFromKnownValue(knownValue) {
303
+ switch (knownValue.value()) {
304
+ case PRIVILEGE_ALL.value(): return Privilege.All;
305
+ case PRIVILEGE_AUTH.value(): return Privilege.Auth;
306
+ case PRIVILEGE_SIGN.value(): return Privilege.Sign;
307
+ case PRIVILEGE_ENCRYPT.value(): return Privilege.Encrypt;
308
+ case PRIVILEGE_ELIDE.value(): return Privilege.Elide;
309
+ case PRIVILEGE_ISSUE.value(): return Privilege.Issue;
310
+ case PRIVILEGE_ACCESS.value(): return Privilege.Access;
311
+ case PRIVILEGE_DELEGATE.value(): return Privilege.Delegate;
312
+ case PRIVILEGE_VERIFY.value(): return Privilege.Verify;
313
+ case PRIVILEGE_UPDATE.value(): return Privilege.Update;
314
+ case PRIVILEGE_TRANSFER.value(): return Privilege.Transfer;
315
+ case PRIVILEGE_ELECT.value(): return Privilege.Elect;
316
+ case PRIVILEGE_BURN.value(): return Privilege.Burn;
317
+ case PRIVILEGE_REVOKE.value(): return Privilege.Revoke;
318
+ default: throw XIDError.unknownPrivilege();
319
+ }
320
+ }
321
+ /**
322
+ * Convert a Privilege to an Envelope.
323
+ */
324
+ function privilegeToEnvelope(privilege) {
325
+ return Envelope.newWithKnownValue(privilegeToKnownValue(privilege));
326
+ }
327
+ /**
328
+ * Convert an Envelope to a Privilege.
329
+ */
330
+ function privilegeFromEnvelope(envelope) {
331
+ const envelopeCase = envelope.case();
332
+ if (envelopeCase.type !== "knownValue") throw XIDError.unknownPrivilege();
333
+ return privilegeFromKnownValue(envelopeCase.value);
334
+ }
335
+
336
+ //#endregion
337
+ //#region src/permissions.ts
338
+ /**
339
+ * XID Permissions
340
+ *
341
+ * Permissions management for XID documents, including allow and deny sets
342
+ * of privileges.
343
+ *
344
+ * Ported from bc-xid-rust/src/permissions.rs
345
+ */
346
+ /**
347
+ * Helper methods for HasPermissions implementers.
348
+ */
349
+ const HasPermissionsMixin = {
350
+ allow(obj) {
351
+ return obj.permissions().allow;
352
+ },
353
+ deny(obj) {
354
+ return obj.permissions().deny;
355
+ },
356
+ addAllow(obj, privilege) {
357
+ obj.permissionsMut().allow.add(privilege);
358
+ },
359
+ addDeny(obj, privilege) {
360
+ obj.permissionsMut().deny.add(privilege);
361
+ },
362
+ removeAllow(obj, privilege) {
363
+ obj.permissionsMut().allow.delete(privilege);
364
+ },
365
+ removeDeny(obj, privilege) {
366
+ obj.permissionsMut().deny.delete(privilege);
367
+ },
368
+ clearAllPermissions(obj) {
369
+ obj.permissionsMut().allow.clear();
370
+ obj.permissionsMut().deny.clear();
371
+ }
372
+ };
373
+ /**
374
+ * Represents the permissions granted to a key or delegate.
375
+ */
376
+ var Permissions = class Permissions {
377
+ allow;
378
+ deny;
379
+ constructor(allow, deny) {
380
+ this.allow = allow ?? /* @__PURE__ */ new Set();
381
+ this.deny = deny ?? /* @__PURE__ */ new Set();
382
+ }
383
+ /**
384
+ * Create a new empty Permissions object.
385
+ */
386
+ static new() {
387
+ return new Permissions();
388
+ }
389
+ /**
390
+ * Create a new Permissions object that allows all privileges.
391
+ */
392
+ static newAllowAll() {
393
+ const allow = /* @__PURE__ */ new Set();
394
+ allow.add(Privilege.All);
395
+ return new Permissions(allow);
396
+ }
397
+ /**
398
+ * Add permissions assertions to an envelope.
399
+ */
400
+ addToEnvelope(envelope) {
401
+ let result = envelope;
402
+ for (const privilege of this.allow) result = result.addAssertion(Envelope.newWithKnownValue(ALLOW.value()), Envelope.newWithKnownValue(privilegeToKnownValue(privilege).value()));
403
+ for (const privilege of this.deny) result = result.addAssertion(Envelope.newWithKnownValue(DENY.value()), Envelope.newWithKnownValue(privilegeToKnownValue(privilege).value()));
404
+ return result;
405
+ }
406
+ /**
407
+ * Try to extract Permissions from an envelope.
408
+ */
409
+ static tryFromEnvelope(envelope) {
410
+ const allow = /* @__PURE__ */ new Set();
411
+ const deny = /* @__PURE__ */ new Set();
412
+ const allowObjects = envelope.objectsForPredicate(ALLOW);
413
+ for (const obj of allowObjects) {
414
+ const privilege = privilegeFromEnvelope(obj);
415
+ allow.add(privilege);
416
+ }
417
+ const denyObjects = envelope.objectsForPredicate(DENY);
418
+ for (const obj of denyObjects) {
419
+ const privilege = privilegeFromEnvelope(obj);
420
+ deny.add(privilege);
421
+ }
422
+ return new Permissions(allow, deny);
423
+ }
424
+ /**
425
+ * Add an allowed privilege.
426
+ */
427
+ addAllow(privilege) {
428
+ this.allow.add(privilege);
429
+ }
430
+ /**
431
+ * Add a denied privilege.
432
+ */
433
+ addDeny(privilege) {
434
+ this.deny.add(privilege);
435
+ }
436
+ /**
437
+ * Check if a specific privilege is allowed.
438
+ */
439
+ isAllowed(privilege) {
440
+ if (this.deny.has(privilege) || this.deny.has(Privilege.All)) return false;
441
+ return this.allow.has(privilege) || this.allow.has(Privilege.All);
442
+ }
443
+ /**
444
+ * Check if a specific privilege is denied.
445
+ */
446
+ isDenied(privilege) {
447
+ return this.deny.has(privilege) || this.deny.has(Privilege.All);
448
+ }
449
+ permissions() {
450
+ return this;
451
+ }
452
+ permissionsMut() {
453
+ return this;
454
+ }
455
+ /**
456
+ * Check equality with another Permissions object.
457
+ */
458
+ equals(other) {
459
+ if (this.allow.size !== other.allow.size || this.deny.size !== other.deny.size) return false;
460
+ for (const p of this.allow) if (!other.allow.has(p)) return false;
461
+ for (const p of this.deny) if (!other.deny.has(p)) return false;
462
+ return true;
463
+ }
464
+ /**
465
+ * Clone this Permissions object.
466
+ */
467
+ clone() {
468
+ return new Permissions(new Set(this.allow), new Set(this.deny));
469
+ }
470
+ };
471
+
472
+ //#endregion
473
+ //#region src/name.ts
474
+ /**
475
+ * XID Name (Nickname) Interface
476
+ *
477
+ * Provides the HasNickname interface for objects that can have a nickname.
478
+ *
479
+ * Ported from bc-xid-rust/src/name.rs
480
+ */
481
+ /**
482
+ * Helper methods for HasNickname implementers.
483
+ */
484
+ const HasNicknameMixin = { addNickname(obj, name) {
485
+ if (obj.nickname() !== "") throw XIDError.duplicate("nickname");
486
+ if (name === "") throw XIDError.emptyValue("nickname");
487
+ obj.setNickname(name);
488
+ } };
489
+
490
+ //#endregion
491
+ //#region src/shared.ts
492
+ /**
493
+ * Shared Reference Wrapper
494
+ *
495
+ * Provides a wrapper for shared references to objects.
496
+ * In TypeScript, we don't have Arc/RwLock like Rust, but we can provide
497
+ * a simple wrapper that allows shared access to a value.
498
+ *
499
+ * Ported from bc-xid-rust/src/shared.rs
500
+ */
501
+ /**
502
+ * A wrapper for shared references to objects.
503
+ *
504
+ * Unlike Rust's Arc<RwLock<T>>, JavaScript uses reference semantics for objects,
505
+ * so this is primarily a type-safe wrapper that makes the sharing explicit.
506
+ */
507
+ var Shared = class Shared {
508
+ value;
509
+ constructor(value) {
510
+ this.value = value;
511
+ }
512
+ /**
513
+ * Create a new Shared instance.
514
+ */
515
+ static new(value) {
516
+ return new Shared(value);
517
+ }
518
+ /**
519
+ * Get a read-only reference to the value.
520
+ */
521
+ read() {
522
+ return this.value;
523
+ }
524
+ /**
525
+ * Get a mutable reference to the value.
526
+ */
527
+ write() {
528
+ return this.value;
529
+ }
530
+ /**
531
+ * Check equality with another Shared instance.
532
+ */
533
+ equals(other) {
534
+ if (this.value === other.value) return true;
535
+ try {
536
+ return JSON.stringify(this.value) === JSON.stringify(other.value);
537
+ } catch {
538
+ return false;
539
+ }
540
+ }
541
+ /**
542
+ * Clone this Shared instance.
543
+ * Note: This creates a shallow copy in JS; for deep copy, implement on T.
544
+ */
545
+ clone() {
546
+ if (typeof this.value === "object" && this.value !== null && "clone" in this.value && typeof this.value.clone === "function") return new Shared(this.value.clone());
547
+ return new Shared(this.value);
548
+ }
549
+ };
550
+
551
+ //#endregion
552
+ //#region src/key.ts
553
+ /**
554
+ * XID Key
555
+ *
556
+ * Represents a key in an XID document, containing public keys, optional private keys,
557
+ * nickname, endpoints, and permissions.
558
+ *
559
+ * Ported from bc-xid-rust/src/key.rs
560
+ */
561
+ const kv$3 = (v) => v;
562
+ /**
563
+ * Options for handling private keys in envelopes.
564
+ */
565
+ let XIDPrivateKeyOptions = /* @__PURE__ */ function(XIDPrivateKeyOptions$1) {
566
+ /** Omit the private key from the envelope (default). */
567
+ XIDPrivateKeyOptions$1["Omit"] = "Omit";
568
+ /** Include the private key in plaintext (with salt for decorrelation). */
569
+ XIDPrivateKeyOptions$1["Include"] = "Include";
570
+ /** Include the private key assertion but elide it (maintains digest tree). */
571
+ XIDPrivateKeyOptions$1["Elide"] = "Elide";
572
+ /** Include the private key encrypted with a password. */
573
+ XIDPrivateKeyOptions$1["Encrypt"] = "Encrypt";
574
+ return XIDPrivateKeyOptions$1;
575
+ }({});
576
+ /**
577
+ * Represents a key in an XID document.
578
+ */
579
+ var Key = class Key {
580
+ _publicKeyBase;
581
+ _privateKeys;
582
+ _nickname;
583
+ _endpoints;
584
+ _permissions;
585
+ constructor(publicKeyBase, privateKeys, nickname = "", endpoints = /* @__PURE__ */ new Set(), permissions = Permissions.new()) {
586
+ this._publicKeyBase = publicKeyBase;
587
+ this._privateKeys = privateKeys;
588
+ this._nickname = nickname;
589
+ this._endpoints = endpoints;
590
+ this._permissions = permissions;
591
+ }
592
+ /**
593
+ * Create a new Key with only public keys.
594
+ */
595
+ static new(publicKeyBase) {
596
+ return new Key(publicKeyBase);
597
+ }
598
+ /**
599
+ * Create a new Key with public keys and allow-all permissions.
600
+ */
601
+ static newAllowAll(publicKeyBase) {
602
+ return new Key(publicKeyBase, void 0, "", /* @__PURE__ */ new Set(), Permissions.newAllowAll());
603
+ }
604
+ /**
605
+ * Create a new Key with private key base.
606
+ */
607
+ static newWithPrivateKeyBase(privateKeyBase) {
608
+ const salt = Salt.random(32);
609
+ return new Key(privateKeyBase.publicKeys(), {
610
+ data: {
611
+ type: "decrypted",
612
+ privateKeyBase
613
+ },
614
+ salt
615
+ }, "", /* @__PURE__ */ new Set(), Permissions.newAllowAll());
616
+ }
617
+ /**
618
+ * Get the public key base.
619
+ */
620
+ publicKeyBase() {
621
+ return this._publicKeyBase;
622
+ }
623
+ /**
624
+ * Get the private key base, if available and decrypted.
625
+ */
626
+ privateKeyBase() {
627
+ if (this._privateKeys === void 0) return void 0;
628
+ if (this._privateKeys.data.type === "decrypted") return this._privateKeys.data.privateKeyBase;
629
+ }
630
+ /**
631
+ * Check if this key has decrypted private keys.
632
+ */
633
+ hasPrivateKeys() {
634
+ return this._privateKeys?.data.type === "decrypted";
635
+ }
636
+ /**
637
+ * Check if this key has encrypted private keys.
638
+ */
639
+ hasEncryptedPrivateKeys() {
640
+ return this._privateKeys?.data.type === "encrypted";
641
+ }
642
+ /**
643
+ * Get the salt used for private key decorrelation.
644
+ */
645
+ privateKeySalt() {
646
+ return this._privateKeys?.salt;
647
+ }
648
+ /**
649
+ * Get the reference for this key (based on public key).
650
+ */
651
+ reference() {
652
+ return Reference.hash(this._publicKeyBase.data());
653
+ }
654
+ /**
655
+ * Get the endpoints set.
656
+ */
657
+ endpoints() {
658
+ return this._endpoints;
659
+ }
660
+ /**
661
+ * Get the endpoints set for mutation.
662
+ */
663
+ endpointsMut() {
664
+ return this._endpoints;
665
+ }
666
+ /**
667
+ * Add an endpoint.
668
+ */
669
+ addEndpoint(endpoint) {
670
+ this._endpoints.add(endpoint);
671
+ }
672
+ /**
673
+ * Add a permission.
674
+ */
675
+ addPermission(privilege) {
676
+ this._permissions.addAllow(privilege);
677
+ }
678
+ nickname() {
679
+ return this._nickname;
680
+ }
681
+ setNickname(name) {
682
+ this._nickname = name;
683
+ }
684
+ permissions() {
685
+ return this._permissions;
686
+ }
687
+ permissionsMut() {
688
+ return this._permissions;
689
+ }
690
+ /**
691
+ * Convert to envelope with specified options.
692
+ */
693
+ intoEnvelopeOpt(privateKeyOptions = XIDPrivateKeyOptions.Omit) {
694
+ let envelope = Envelope.new(this._publicKeyBase.data());
695
+ if (this._privateKeys !== void 0) {
696
+ const { data, salt } = this._privateKeys;
697
+ if (data.type === "encrypted") {
698
+ envelope = envelope.addAssertion(kv$3(PRIVATE_KEY), data.envelope);
699
+ envelope = envelope.addAssertion(kv$3(SALT), salt.toData());
700
+ } else if (data.type === "decrypted") switch (typeof privateKeyOptions === "object" ? privateKeyOptions.type : privateKeyOptions) {
701
+ case XIDPrivateKeyOptions.Include:
702
+ envelope = envelope.addAssertion(kv$3(PRIVATE_KEY), data.privateKeyBase.data());
703
+ envelope = envelope.addAssertion(kv$3(SALT), salt.toData());
704
+ break;
705
+ case XIDPrivateKeyOptions.Elide: {
706
+ const elidedAssertion = Envelope.newAssertion(kv$3(PRIVATE_KEY), data.privateKeyBase.data()).elide();
707
+ envelope = envelope.addAssertionEnvelope(elidedAssertion);
708
+ envelope = envelope.addAssertion(kv$3(SALT), salt.toData());
709
+ break;
710
+ }
711
+ case XIDPrivateKeyOptions.Encrypt:
712
+ if (typeof privateKeyOptions === "object") {
713
+ const encrypted = Envelope.new(data.privateKeyBase.data()).encryptSubject(privateKeyOptions.password);
714
+ envelope = envelope.addAssertion(kv$3(PRIVATE_KEY), encrypted);
715
+ envelope = envelope.addAssertion(kv$3(SALT), salt.toData());
716
+ }
717
+ break;
718
+ case XIDPrivateKeyOptions.Omit:
719
+ default: break;
720
+ }
721
+ }
722
+ if (this._nickname !== "") envelope = envelope.addAssertion(kv$3(NICKNAME), this._nickname);
723
+ for (const endpoint of this._endpoints) envelope = envelope.addAssertion(kv$3(ENDPOINT), endpoint);
724
+ envelope = this._permissions.addToEnvelope(envelope);
725
+ return envelope;
726
+ }
727
+ intoEnvelope() {
728
+ return this.intoEnvelopeOpt(XIDPrivateKeyOptions.Omit);
729
+ }
730
+ /**
731
+ * Try to extract a Key from an envelope, optionally with password for decryption.
732
+ */
733
+ static tryFromEnvelope(envelope, password) {
734
+ const env = envelope;
735
+ const publicKeyData = (env.case().type === "node" ? env.subject() : env).asByteString();
736
+ if (publicKeyData === void 0) throw XIDError.component(/* @__PURE__ */ new Error("Could not extract public key from envelope"));
737
+ const publicKeyBase = new PublicKeyBase(publicKeyData);
738
+ let privateKeys;
739
+ let salt = Salt.random(32);
740
+ const saltAssertions = env.assertionsWithPredicate(SALT);
741
+ if (saltAssertions.length > 0) {
742
+ const saltCase = saltAssertions[0].case();
743
+ if (saltCase.type === "assertion") {
744
+ const saltData = saltCase.assertion.object().asByteString();
745
+ if (saltData !== void 0) salt = Salt.from(saltData);
746
+ }
747
+ }
748
+ const privateKeyAssertions = env.assertionsWithPredicate(PRIVATE_KEY);
749
+ if (privateKeyAssertions.length > 0) {
750
+ const assertionCase = privateKeyAssertions[0].case();
751
+ if (assertionCase.type === "assertion") {
752
+ const privateKeyObject = assertionCase.assertion.object();
753
+ if (privateKeyObject.case().type === "encrypted") if (password !== void 0) try {
754
+ const decryptedData = privateKeyObject.decryptSubject(password).asByteString();
755
+ if (decryptedData !== void 0) privateKeys = {
756
+ data: {
757
+ type: "decrypted",
758
+ privateKeyBase: PrivateKeyBase.fromBytes(decryptedData, publicKeyData)
759
+ },
760
+ salt
761
+ };
762
+ } catch {
763
+ privateKeys = {
764
+ data: {
765
+ type: "encrypted",
766
+ envelope: privateKeyObject
767
+ },
768
+ salt
769
+ };
770
+ }
771
+ else privateKeys = {
772
+ data: {
773
+ type: "encrypted",
774
+ envelope: privateKeyObject
775
+ },
776
+ salt
777
+ };
778
+ else {
779
+ const privateKeyData = privateKeyObject.asByteString();
780
+ if (privateKeyData !== void 0) privateKeys = {
781
+ data: {
782
+ type: "decrypted",
783
+ privateKeyBase: PrivateKeyBase.fromBytes(privateKeyData, publicKeyData)
784
+ },
785
+ salt
786
+ };
787
+ }
788
+ }
789
+ }
790
+ let nickname = "";
791
+ try {
792
+ const nicknameObj = env.objectForPredicate(NICKNAME);
793
+ nickname = nicknameObj.asByteString() !== void 0 ? "" : nicknameObj.asText() ?? "";
794
+ } catch {}
795
+ const endpoints = /* @__PURE__ */ new Set();
796
+ const endpointObjects = env.objectsForPredicate(ENDPOINT);
797
+ for (const obj of endpointObjects) {
798
+ const text = obj.asText();
799
+ if (text !== void 0) endpoints.add(text);
800
+ }
801
+ const permissions = Permissions.tryFromEnvelope(envelope);
802
+ return new Key(publicKeyBase, privateKeys, nickname, endpoints, permissions);
803
+ }
804
+ /**
805
+ * Check equality with another Key.
806
+ */
807
+ equals(other) {
808
+ return this._publicKeyBase.hex() === other._publicKeyBase.hex();
809
+ }
810
+ /**
811
+ * Get a hash key for use in Sets/Maps.
812
+ */
813
+ hashKey() {
814
+ return this._publicKeyBase.hex();
815
+ }
816
+ /**
817
+ * Clone this Key.
818
+ */
819
+ clone() {
820
+ return new Key(this._publicKeyBase, this._privateKeys !== void 0 ? {
821
+ data: this._privateKeys.data,
822
+ salt: this._privateKeys.salt
823
+ } : void 0, this._nickname, new Set(this._endpoints), this._permissions.clone());
824
+ }
825
+ };
826
+
827
+ //#endregion
828
+ //#region src/service.ts
829
+ /**
830
+ * XID Service
831
+ *
832
+ * Represents a service endpoint in an XID document, containing URI, key references,
833
+ * delegate references, permissions, capability, and name.
834
+ *
835
+ * Ported from bc-xid-rust/src/service.rs
836
+ */
837
+ const kv$2 = (v) => v;
838
+ const KEY_RAW$1 = KEY.value();
839
+ const DELEGATE_RAW$1 = DELEGATE.value();
840
+ const NAME_RAW = NAME.value();
841
+ const CAPABILITY_RAW = CAPABILITY.value();
842
+ const ALLOW_RAW = ALLOW.value();
843
+ /**
844
+ * Represents a service endpoint in an XID document.
845
+ */
846
+ var Service = class Service {
847
+ _uri;
848
+ _keyReferences;
849
+ _delegateReferences;
850
+ _permissions;
851
+ _capability;
852
+ _name;
853
+ constructor(uri) {
854
+ this._uri = uri;
855
+ this._keyReferences = /* @__PURE__ */ new Set();
856
+ this._delegateReferences = /* @__PURE__ */ new Set();
857
+ this._permissions = Permissions.new();
858
+ this._capability = "";
859
+ this._name = "";
860
+ }
861
+ /**
862
+ * Create a new Service with the given URI.
863
+ */
864
+ static new(uri) {
865
+ return new Service(uri);
866
+ }
867
+ /**
868
+ * Get the service URI.
869
+ */
870
+ uri() {
871
+ return this._uri;
872
+ }
873
+ /**
874
+ * Get the capability string.
875
+ */
876
+ capability() {
877
+ return this._capability;
878
+ }
879
+ /**
880
+ * Set the capability string.
881
+ */
882
+ setCapability(capability) {
883
+ this._capability = capability;
884
+ }
885
+ /**
886
+ * Add a capability, throwing if one already exists or is empty.
887
+ */
888
+ addCapability(capability) {
889
+ if (this._capability !== "") throw XIDError.duplicate("capability");
890
+ if (capability === "") throw XIDError.emptyValue("capability");
891
+ this.setCapability(capability);
892
+ }
893
+ /**
894
+ * Get the key references set.
895
+ */
896
+ keyReferences() {
897
+ return this._keyReferences;
898
+ }
899
+ /**
900
+ * Get the key references set for mutation.
901
+ */
902
+ keyReferencesMut() {
903
+ return this._keyReferences;
904
+ }
905
+ /**
906
+ * Add a key reference by hex string.
907
+ */
908
+ addKeyReferenceHex(keyReferenceHex) {
909
+ if (this._keyReferences.has(keyReferenceHex)) throw XIDError.duplicate("key reference");
910
+ this._keyReferences.add(keyReferenceHex);
911
+ }
912
+ /**
913
+ * Add a key reference.
914
+ */
915
+ addKeyReference(keyReference) {
916
+ this.addKeyReferenceHex(keyReference.toHex());
917
+ }
918
+ /**
919
+ * Get the delegate references set.
920
+ */
921
+ delegateReferences() {
922
+ return this._delegateReferences;
923
+ }
924
+ /**
925
+ * Get the delegate references set for mutation.
926
+ */
927
+ delegateReferencesMut() {
928
+ return this._delegateReferences;
929
+ }
930
+ /**
931
+ * Add a delegate reference by hex string.
932
+ */
933
+ addDelegateReferenceHex(delegateReferenceHex) {
934
+ if (this._delegateReferences.has(delegateReferenceHex)) throw XIDError.duplicate("delegate reference");
935
+ this._delegateReferences.add(delegateReferenceHex);
936
+ }
937
+ /**
938
+ * Add a delegate reference.
939
+ */
940
+ addDelegateReference(delegateReference) {
941
+ this.addDelegateReferenceHex(delegateReference.toHex());
942
+ }
943
+ /**
944
+ * Get the name.
945
+ */
946
+ name() {
947
+ return this._name;
948
+ }
949
+ /**
950
+ * Set the name, throwing if one already exists or is empty.
951
+ */
952
+ setName(name) {
953
+ if (this._name !== "") throw XIDError.duplicate("name");
954
+ if (name === "") throw XIDError.emptyValue("name");
955
+ this._name = name;
956
+ }
957
+ permissions() {
958
+ return this._permissions;
959
+ }
960
+ permissionsMut() {
961
+ return this._permissions;
962
+ }
963
+ /**
964
+ * Convert to envelope.
965
+ */
966
+ intoEnvelope() {
967
+ let envelope = Envelope.new(this._uri);
968
+ for (const keyRef of this._keyReferences) {
969
+ const refBytes = hexToBytes$1(keyRef);
970
+ envelope = envelope.addAssertion(kv$2(KEY), refBytes);
971
+ }
972
+ for (const delegateRef of this._delegateReferences) {
973
+ const refBytes = hexToBytes$1(delegateRef);
974
+ envelope = envelope.addAssertion(kv$2(DELEGATE), refBytes);
975
+ }
976
+ if (this._capability !== "") envelope = envelope.addAssertion(kv$2(CAPABILITY), this._capability);
977
+ if (this._name !== "") envelope = envelope.addAssertion(kv$2(NAME), this._name);
978
+ envelope = this._permissions.addToEnvelope(envelope);
979
+ return envelope;
980
+ }
981
+ /**
982
+ * Try to extract a Service from an envelope.
983
+ */
984
+ static tryFromEnvelope(envelope) {
985
+ const envExt = envelope;
986
+ const uri = (envExt.case().type === "node" ? envExt.subject() : envelope).asText();
987
+ if (uri === void 0) throw XIDError.component(/* @__PURE__ */ new Error("Could not extract URI from envelope"));
988
+ const service = new Service(uri);
989
+ const assertions = envelope.assertions();
990
+ for (const assertion of assertions) {
991
+ const assertionCase = assertion.case();
992
+ if (assertionCase.type !== "assertion") continue;
993
+ const predicateCase = assertionCase.assertion.predicate().case();
994
+ if (predicateCase.type !== "knownValue") continue;
995
+ const predicate = predicateCase.value.value();
996
+ const object = assertionCase.assertion.object();
997
+ if (object.assertions().length > 0) throw XIDError.unexpectedNestedAssertions();
998
+ switch (predicate) {
999
+ case KEY_RAW$1: {
1000
+ const keyData = object.asByteString();
1001
+ if (keyData !== void 0) service.addKeyReferenceHex(bytesToHex(keyData));
1002
+ break;
1003
+ }
1004
+ case DELEGATE_RAW$1: {
1005
+ const delegateData = object.asByteString();
1006
+ if (delegateData !== void 0) service.addDelegateReferenceHex(bytesToHex(delegateData));
1007
+ break;
1008
+ }
1009
+ case CAPABILITY_RAW: {
1010
+ const capability = object.asText();
1011
+ if (capability !== void 0) service.addCapability(capability);
1012
+ break;
1013
+ }
1014
+ case NAME_RAW: {
1015
+ const name = object.asText();
1016
+ if (name !== void 0) service.setName(name);
1017
+ break;
1018
+ }
1019
+ case ALLOW_RAW: {
1020
+ const privilege = privilegeFromEnvelope(object);
1021
+ service._permissions.addAllow(privilege);
1022
+ break;
1023
+ }
1024
+ default: throw XIDError.unexpectedPredicate(String(predicate));
1025
+ }
1026
+ }
1027
+ return service;
1028
+ }
1029
+ /**
1030
+ * Check equality with another Service (based on URI).
1031
+ */
1032
+ equals(other) {
1033
+ return this._uri === other._uri;
1034
+ }
1035
+ /**
1036
+ * Get a hash key for use in Sets/Maps.
1037
+ */
1038
+ hashKey() {
1039
+ return this._uri;
1040
+ }
1041
+ /**
1042
+ * Clone this Service.
1043
+ */
1044
+ clone() {
1045
+ const clone = new Service(this._uri);
1046
+ clone._keyReferences = new Set(this._keyReferences);
1047
+ clone._delegateReferences = new Set(this._delegateReferences);
1048
+ clone._permissions = this._permissions.clone();
1049
+ clone._capability = this._capability;
1050
+ clone._name = this._name;
1051
+ return clone;
1052
+ }
1053
+ };
1054
+ function hexToBytes$1(hex) {
1055
+ const bytes = new Uint8Array(hex.length / 2);
1056
+ for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
1057
+ return bytes;
1058
+ }
1059
+ function bytesToHex(bytes) {
1060
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1061
+ }
1062
+
1063
+ //#endregion
1064
+ //#region src/delegate.ts
1065
+ let XIDDocumentClass = null;
1066
+ /**
1067
+ * Register the XIDDocument class to avoid circular dependency issues.
1068
+ * Called by xid-document.ts when it loads.
1069
+ */
1070
+ function registerXIDDocumentClass(cls) {
1071
+ XIDDocumentClass = cls;
1072
+ }
1073
+ /**
1074
+ * Represents a delegate in an XID document.
1075
+ */
1076
+ var Delegate = class Delegate {
1077
+ _controller;
1078
+ _permissions;
1079
+ constructor(controller, permissions) {
1080
+ this._controller = controller;
1081
+ this._permissions = permissions;
1082
+ }
1083
+ /**
1084
+ * Create a new Delegate with the given controller document.
1085
+ */
1086
+ static new(controller) {
1087
+ return new Delegate(Shared.new(controller), Permissions.new());
1088
+ }
1089
+ /**
1090
+ * Get the controller document.
1091
+ */
1092
+ controller() {
1093
+ return this._controller;
1094
+ }
1095
+ /**
1096
+ * Get the XID of the controller.
1097
+ */
1098
+ xid() {
1099
+ return this._controller.read().xid();
1100
+ }
1101
+ /**
1102
+ * Get the reference for this delegate.
1103
+ */
1104
+ reference() {
1105
+ return Reference.hash(this.xid().toData());
1106
+ }
1107
+ permissions() {
1108
+ return this._permissions;
1109
+ }
1110
+ permissionsMut() {
1111
+ return this._permissions;
1112
+ }
1113
+ /**
1114
+ * Convert to envelope.
1115
+ */
1116
+ intoEnvelope() {
1117
+ const envelope = this._controller.read().intoEnvelope().wrap();
1118
+ return this._permissions.addToEnvelope(envelope);
1119
+ }
1120
+ /**
1121
+ * Try to extract a Delegate from an envelope.
1122
+ */
1123
+ static tryFromEnvelope(envelope) {
1124
+ if (XIDDocumentClass === null) throw new Error("XIDDocument class not registered. Import xid-document.js first.");
1125
+ const permissions = Permissions.tryFromEnvelope(envelope);
1126
+ const inner = envelope.tryUnwrap();
1127
+ return new Delegate(Shared.new(XIDDocumentClass.tryFromEnvelope(inner)), permissions);
1128
+ }
1129
+ /**
1130
+ * Check equality with another Delegate (based on controller XID).
1131
+ */
1132
+ equals(other) {
1133
+ return this.xid().equals(other.xid());
1134
+ }
1135
+ /**
1136
+ * Get a hash key for use in Sets/Maps.
1137
+ */
1138
+ hashKey() {
1139
+ return this.xid().toHex();
1140
+ }
1141
+ /**
1142
+ * Clone this Delegate.
1143
+ */
1144
+ clone() {
1145
+ return new Delegate(Shared.new(this._controller.read().clone()), this._permissions.clone());
1146
+ }
1147
+ };
1148
+
1149
+ //#endregion
1150
+ //#region src/provenance.ts
1151
+ /**
1152
+ * XID Provenance
1153
+ *
1154
+ * Represents provenance information in an XID document, containing a provenance mark
1155
+ * and optional generator.
1156
+ *
1157
+ * Ported from bc-xid-rust/src/provenance.rs
1158
+ */
1159
+ const kv$1 = (v) => v;
1160
+ /**
1161
+ * Options for handling generators in envelopes.
1162
+ */
1163
+ let XIDGeneratorOptions = /* @__PURE__ */ function(XIDGeneratorOptions$1) {
1164
+ /** Omit the generator from the envelope (default). */
1165
+ XIDGeneratorOptions$1["Omit"] = "Omit";
1166
+ /** Include the generator in plaintext (with salt for decorrelation). */
1167
+ XIDGeneratorOptions$1["Include"] = "Include";
1168
+ /** Include the generator assertion but elide it (maintains digest tree). */
1169
+ XIDGeneratorOptions$1["Elide"] = "Elide";
1170
+ /** Include the generator encrypted with a password. */
1171
+ XIDGeneratorOptions$1["Encrypt"] = "Encrypt";
1172
+ return XIDGeneratorOptions$1;
1173
+ }({});
1174
+ /**
1175
+ * Represents provenance information in an XID document.
1176
+ */
1177
+ var Provenance = class Provenance {
1178
+ _mark;
1179
+ _generator;
1180
+ constructor(mark, generator) {
1181
+ this._mark = mark;
1182
+ this._generator = generator;
1183
+ }
1184
+ /**
1185
+ * Create a new Provenance with just a mark.
1186
+ */
1187
+ static new(mark) {
1188
+ return new Provenance(mark);
1189
+ }
1190
+ /**
1191
+ * Create a new Provenance with a generator and mark.
1192
+ */
1193
+ static newWithGenerator(generator, mark) {
1194
+ const salt = Salt.random(32);
1195
+ return new Provenance(mark, {
1196
+ data: {
1197
+ type: "decrypted",
1198
+ generator
1199
+ },
1200
+ salt
1201
+ });
1202
+ }
1203
+ /**
1204
+ * Get the provenance mark.
1205
+ */
1206
+ mark() {
1207
+ return this._mark;
1208
+ }
1209
+ /**
1210
+ * Get the generator, if available and decrypted.
1211
+ */
1212
+ generator() {
1213
+ if (this._generator === void 0) return void 0;
1214
+ if (this._generator.data.type === "decrypted") return this._generator.data.generator;
1215
+ }
1216
+ /**
1217
+ * Check if this provenance has a decrypted generator.
1218
+ */
1219
+ hasGenerator() {
1220
+ return this._generator?.data.type === "decrypted";
1221
+ }
1222
+ /**
1223
+ * Check if this provenance has an encrypted generator.
1224
+ */
1225
+ hasEncryptedGenerator() {
1226
+ return this._generator?.data.type === "encrypted";
1227
+ }
1228
+ /**
1229
+ * Get the salt used for generator decorrelation.
1230
+ */
1231
+ generatorSalt() {
1232
+ return this._generator?.salt;
1233
+ }
1234
+ /**
1235
+ * Update the provenance mark.
1236
+ */
1237
+ setMark(mark) {
1238
+ this._mark = mark;
1239
+ }
1240
+ /**
1241
+ * Set or replace the generator.
1242
+ */
1243
+ setGenerator(generator) {
1244
+ const salt = Salt.random(32);
1245
+ this._generator = {
1246
+ data: {
1247
+ type: "decrypted",
1248
+ generator
1249
+ },
1250
+ salt
1251
+ };
1252
+ }
1253
+ /**
1254
+ * Take and remove the generator.
1255
+ */
1256
+ takeGenerator() {
1257
+ const gen = this._generator;
1258
+ this._generator = void 0;
1259
+ return gen;
1260
+ }
1261
+ /**
1262
+ * Get a mutable reference to the generator, decrypting if necessary.
1263
+ */
1264
+ generatorMut(password) {
1265
+ if (this._generator === void 0) return void 0;
1266
+ if (this._generator.data.type === "decrypted") return this._generator.data.generator;
1267
+ if (password !== void 0) {
1268
+ const encryptedEnvelope = this._generator.data.envelope;
1269
+ try {
1270
+ const generatorData = encryptedEnvelope.decryptSubject(password).tryUnwrap().asByteString();
1271
+ if (generatorData !== void 0) {
1272
+ const json = decodeCbor(generatorData);
1273
+ const generator = ProvenanceMarkGenerator.fromJSON(json);
1274
+ this._generator = {
1275
+ data: {
1276
+ type: "decrypted",
1277
+ generator
1278
+ },
1279
+ salt: this._generator.salt
1280
+ };
1281
+ return generator;
1282
+ }
1283
+ } catch {
1284
+ throw XIDError.invalidPassword();
1285
+ }
1286
+ }
1287
+ throw XIDError.invalidPassword();
1288
+ }
1289
+ /**
1290
+ * Convert to envelope with specified options.
1291
+ */
1292
+ intoEnvelopeOpt(generatorOptions = XIDGeneratorOptions.Omit) {
1293
+ let envelope = Envelope.new(this._mark.toCborData());
1294
+ if (this._generator !== void 0) {
1295
+ const { data, salt } = this._generator;
1296
+ if (data.type === "encrypted") {
1297
+ envelope = envelope.addAssertion(kv$1(PROVENANCE_GENERATOR), data.envelope);
1298
+ envelope = envelope.addAssertion(kv$1(SALT), salt.toData());
1299
+ } else if (data.type === "decrypted") switch (typeof generatorOptions === "object" ? generatorOptions.type : generatorOptions) {
1300
+ case XIDGeneratorOptions.Include: {
1301
+ const generatorBytes = cborData(data.generator.toJSON());
1302
+ envelope = envelope.addAssertion(kv$1(PROVENANCE_GENERATOR), generatorBytes);
1303
+ envelope = envelope.addAssertion(kv$1(SALT), salt.toData());
1304
+ break;
1305
+ }
1306
+ case XIDGeneratorOptions.Elide: {
1307
+ const generatorBytes2 = cborData(data.generator.toJSON());
1308
+ const elidedAssertion = Envelope.newAssertion(kv$1(PROVENANCE_GENERATOR), generatorBytes2).elide();
1309
+ envelope = envelope.addAssertionEnvelope(elidedAssertion);
1310
+ envelope = envelope.addAssertion(kv$1(SALT), salt.toData());
1311
+ break;
1312
+ }
1313
+ case XIDGeneratorOptions.Encrypt:
1314
+ if (typeof generatorOptions === "object") {
1315
+ const generatorBytes3 = cborData(data.generator.toJSON());
1316
+ const encrypted = Envelope.new(generatorBytes3).wrap().encryptSubject(generatorOptions.password);
1317
+ envelope = envelope.addAssertion(kv$1(PROVENANCE_GENERATOR), encrypted);
1318
+ envelope = envelope.addAssertion(kv$1(SALT), salt.toData());
1319
+ }
1320
+ break;
1321
+ case XIDGeneratorOptions.Omit:
1322
+ default: break;
1323
+ }
1324
+ }
1325
+ return envelope;
1326
+ }
1327
+ intoEnvelope() {
1328
+ return this.intoEnvelopeOpt(XIDGeneratorOptions.Omit);
1329
+ }
1330
+ /**
1331
+ * Try to extract a Provenance from an envelope, optionally with password for decryption.
1332
+ */
1333
+ static tryFromEnvelope(envelope, password) {
1334
+ const env = envelope;
1335
+ const markData = (env.case().type === "node" ? env.subject() : envelope).asByteString();
1336
+ if (markData === void 0) throw XIDError.provenanceMark(/* @__PURE__ */ new Error("Could not extract mark from envelope"));
1337
+ const mark = ProvenanceMark.fromCborData(markData);
1338
+ let generator;
1339
+ let salt = Salt.random(32);
1340
+ const saltAssertions = env.assertionsWithPredicate(SALT);
1341
+ if (saltAssertions.length > 0) {
1342
+ const saltCase = saltAssertions[0].case();
1343
+ if (saltCase.type === "assertion") {
1344
+ const saltData = saltCase.assertion.object().asByteString();
1345
+ if (saltData !== void 0) salt = Salt.from(saltData);
1346
+ }
1347
+ }
1348
+ const generatorAssertions = env.assertionsWithPredicate(PROVENANCE_GENERATOR);
1349
+ if (generatorAssertions.length > 0) {
1350
+ const assertionCase = generatorAssertions[0].case();
1351
+ if (assertionCase.type === "assertion") {
1352
+ const generatorObject = assertionCase.assertion.object();
1353
+ if (generatorObject.case().type === "encrypted") if (password !== void 0) try {
1354
+ const generatorData = generatorObject.decryptSubject(password).tryUnwrap().asByteString();
1355
+ if (generatorData !== void 0) {
1356
+ const json = decodeCbor(generatorData);
1357
+ generator = {
1358
+ data: {
1359
+ type: "decrypted",
1360
+ generator: ProvenanceMarkGenerator.fromJSON(json)
1361
+ },
1362
+ salt
1363
+ };
1364
+ }
1365
+ } catch {
1366
+ generator = {
1367
+ data: {
1368
+ type: "encrypted",
1369
+ envelope: generatorObject
1370
+ },
1371
+ salt
1372
+ };
1373
+ }
1374
+ else generator = {
1375
+ data: {
1376
+ type: "encrypted",
1377
+ envelope: generatorObject
1378
+ },
1379
+ salt
1380
+ };
1381
+ else {
1382
+ const generatorData = generatorObject.asByteString();
1383
+ if (generatorData !== void 0) {
1384
+ const json2 = decodeCbor(generatorData);
1385
+ generator = {
1386
+ data: {
1387
+ type: "decrypted",
1388
+ generator: ProvenanceMarkGenerator.fromJSON(json2)
1389
+ },
1390
+ salt
1391
+ };
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+ return new Provenance(mark, generator);
1397
+ }
1398
+ /**
1399
+ * Check equality with another Provenance.
1400
+ */
1401
+ equals(other) {
1402
+ return this._mark.equals(other._mark);
1403
+ }
1404
+ /**
1405
+ * Clone this Provenance.
1406
+ * Note: ProvenanceMark is immutable so we can use the same instance.
1407
+ */
1408
+ clone() {
1409
+ return new Provenance(this._mark, this._generator !== void 0 ? {
1410
+ data: this._generator.data,
1411
+ salt: this._generator.salt
1412
+ } : void 0);
1413
+ }
1414
+ };
1415
+
1416
+ //#endregion
1417
+ //#region src/xid-document.ts
1418
+ /**
1419
+ * XID Document
1420
+ *
1421
+ * Represents an XID document containing keys, delegates, services, and provenance.
1422
+ *
1423
+ * Ported from bc-xid-rust/src/xid_document.rs
1424
+ */
1425
+ const kv = (v) => v;
1426
+ const KEY_RAW = KEY.value();
1427
+ const DELEGATE_RAW = DELEGATE.value();
1428
+ const SERVICE_RAW = SERVICE.value();
1429
+ const PROVENANCE_RAW = PROVENANCE.value();
1430
+ const DEREFERENCE_VIA_RAW = DEREFERENCE_VIA.value();
1431
+ /**
1432
+ * Options for verifying the signature on an envelope when loading.
1433
+ */
1434
+ let XIDVerifySignature = /* @__PURE__ */ function(XIDVerifySignature$1) {
1435
+ /** Do not verify the signature (default). */
1436
+ XIDVerifySignature$1["None"] = "None";
1437
+ /** Verify that the envelope is signed with the inception key. */
1438
+ XIDVerifySignature$1["Inception"] = "Inception";
1439
+ return XIDVerifySignature$1;
1440
+ }({});
1441
+ /**
1442
+ * Represents an XID document.
1443
+ */
1444
+ var XIDDocument = class XIDDocument {
1445
+ _xid;
1446
+ _resolutionMethods;
1447
+ _keys;
1448
+ _delegates;
1449
+ _services;
1450
+ _provenance;
1451
+ constructor(xid, resolutionMethods = /* @__PURE__ */ new Set(), keys = /* @__PURE__ */ new Map(), delegates = /* @__PURE__ */ new Map(), services = /* @__PURE__ */ new Map(), provenance) {
1452
+ this._xid = xid;
1453
+ this._resolutionMethods = resolutionMethods;
1454
+ this._keys = keys;
1455
+ this._delegates = delegates;
1456
+ this._services = services;
1457
+ this._provenance = provenance;
1458
+ }
1459
+ /**
1460
+ * Create a new XIDDocument with the given options.
1461
+ */
1462
+ static new(keyOptions = { type: "default" }, markOptions = { type: "none" }) {
1463
+ const inceptionKey = XIDDocument.inceptionKeyForOptions(keyOptions);
1464
+ const provenance = XIDDocument.genesisMarkWithOptions(markOptions);
1465
+ const doc = new XIDDocument(XID.from(hashPublicKey(inceptionKey.publicKeyBase())), /* @__PURE__ */ new Set(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), provenance);
1466
+ doc.addKey(inceptionKey);
1467
+ return doc;
1468
+ }
1469
+ static inceptionKeyForOptions(options) {
1470
+ switch (options.type) {
1471
+ case "default": {
1472
+ const privateKeyBase = PrivateKeyBase.generate();
1473
+ return Key.newWithPrivateKeyBase(privateKeyBase);
1474
+ }
1475
+ case "publicKeyBase": return Key.newAllowAll(options.publicKeyBase);
1476
+ case "privateKeyBase": return Key.newWithPrivateKeyBase(options.privateKeyBase);
1477
+ }
1478
+ }
1479
+ static genesisMarkWithOptions(options) {
1480
+ switch (options.type) {
1481
+ case "none": return;
1482
+ case "passphrase": {
1483
+ const resolution = options.resolution ?? ProvenanceMarkResolution.High;
1484
+ const generator = ProvenanceMarkGenerator.newWithPassphrase(resolution, options.passphrase);
1485
+ const date = options.date ?? /* @__PURE__ */ new Date();
1486
+ const mark = generator.next(date, options.info);
1487
+ return Provenance.newWithGenerator(generator, mark);
1488
+ }
1489
+ case "seed": {
1490
+ const resolution = options.resolution ?? ProvenanceMarkResolution.High;
1491
+ const generator = ProvenanceMarkGenerator.newUsing(resolution, options.seed);
1492
+ const date = options.date ?? /* @__PURE__ */ new Date();
1493
+ const mark = generator.next(date, options.info);
1494
+ return Provenance.newWithGenerator(generator, mark);
1495
+ }
1496
+ }
1497
+ }
1498
+ /**
1499
+ * Create an XIDDocument from just an XID.
1500
+ */
1501
+ static fromXid(xid) {
1502
+ return new XIDDocument(xid);
1503
+ }
1504
+ /**
1505
+ * Get the XID.
1506
+ */
1507
+ xid() {
1508
+ return this._xid;
1509
+ }
1510
+ /**
1511
+ * Get the resolution methods.
1512
+ */
1513
+ resolutionMethods() {
1514
+ return this._resolutionMethods;
1515
+ }
1516
+ /**
1517
+ * Add a resolution method.
1518
+ */
1519
+ addResolutionMethod(method) {
1520
+ this._resolutionMethods.add(method);
1521
+ }
1522
+ /**
1523
+ * Remove a resolution method.
1524
+ */
1525
+ removeResolutionMethod(method) {
1526
+ return this._resolutionMethods.delete(method);
1527
+ }
1528
+ /**
1529
+ * Get all keys.
1530
+ */
1531
+ keys() {
1532
+ return Array.from(this._keys.values());
1533
+ }
1534
+ /**
1535
+ * Add a key.
1536
+ */
1537
+ addKey(key) {
1538
+ const hashKey = key.hashKey();
1539
+ if (this._keys.has(hashKey)) throw XIDError.duplicate("key");
1540
+ this._keys.set(hashKey, key);
1541
+ }
1542
+ /**
1543
+ * Find a key by its public key base.
1544
+ */
1545
+ findKeyByPublicKeyBase(publicKeyBase) {
1546
+ const hashKey = publicKeyBase.hex();
1547
+ return this._keys.get(hashKey);
1548
+ }
1549
+ /**
1550
+ * Find a key by its reference.
1551
+ */
1552
+ findKeyByReference(reference) {
1553
+ for (const key of this._keys.values()) if (key.reference().equals(reference)) return key;
1554
+ }
1555
+ /**
1556
+ * Take and remove a key.
1557
+ */
1558
+ takeKey(publicKeyBase) {
1559
+ const hashKey = publicKeyBase.hex();
1560
+ const key = this._keys.get(hashKey);
1561
+ if (key !== void 0) this._keys.delete(hashKey);
1562
+ return key;
1563
+ }
1564
+ /**
1565
+ * Remove a key.
1566
+ */
1567
+ removeKey(publicKeyBase) {
1568
+ if (this.servicesReferenceKey(publicKeyBase)) throw XIDError.stillReferenced("key");
1569
+ const hashKey = publicKeyBase.hex();
1570
+ if (!this._keys.delete(hashKey)) throw XIDError.notFound("key");
1571
+ }
1572
+ /**
1573
+ * Check if the given public key is the inception signing key.
1574
+ */
1575
+ isInceptionKey(publicKeyBase) {
1576
+ return bytesEqual(hashPublicKey(publicKeyBase), this._xid.toData());
1577
+ }
1578
+ /**
1579
+ * Get the inception key, if it exists in the document.
1580
+ */
1581
+ inceptionKey() {
1582
+ for (const key of this._keys.values()) if (this.isInceptionKey(key.publicKeyBase())) return key;
1583
+ }
1584
+ /**
1585
+ * Get the inception private key base, if available.
1586
+ */
1587
+ inceptionPrivateKeyBase() {
1588
+ return this.inceptionKey()?.privateKeyBase();
1589
+ }
1590
+ /**
1591
+ * Remove the inception key from the document.
1592
+ */
1593
+ removeInceptionKey() {
1594
+ const inceptionKey = this.inceptionKey();
1595
+ if (inceptionKey !== void 0) this._keys.delete(inceptionKey.hashKey());
1596
+ return inceptionKey;
1597
+ }
1598
+ /**
1599
+ * Check if the document is empty (no keys, delegates, services, or provenance).
1600
+ */
1601
+ isEmpty() {
1602
+ return this._resolutionMethods.size === 0 && this._keys.size === 0 && this._delegates.size === 0 && this._provenance === void 0;
1603
+ }
1604
+ /**
1605
+ * Get all delegates.
1606
+ */
1607
+ delegates() {
1608
+ return Array.from(this._delegates.values());
1609
+ }
1610
+ /**
1611
+ * Add a delegate.
1612
+ */
1613
+ addDelegate(delegate) {
1614
+ const hashKey = delegate.hashKey();
1615
+ if (this._delegates.has(hashKey)) throw XIDError.duplicate("delegate");
1616
+ this._delegates.set(hashKey, delegate);
1617
+ }
1618
+ /**
1619
+ * Find a delegate by XID.
1620
+ */
1621
+ findDelegateByXid(xid) {
1622
+ return this._delegates.get(xid.toHex());
1623
+ }
1624
+ /**
1625
+ * Find a delegate by reference.
1626
+ */
1627
+ findDelegateByReference(reference) {
1628
+ for (const delegate of this._delegates.values()) if (delegate.reference().equals(reference)) return delegate;
1629
+ }
1630
+ /**
1631
+ * Take and remove a delegate.
1632
+ */
1633
+ takeDelegate(xid) {
1634
+ const hashKey = xid.toHex();
1635
+ const delegate = this._delegates.get(hashKey);
1636
+ if (delegate !== void 0) this._delegates.delete(hashKey);
1637
+ return delegate;
1638
+ }
1639
+ /**
1640
+ * Remove a delegate.
1641
+ */
1642
+ removeDelegate(xid) {
1643
+ if (this.servicesReferenceDelegate(xid)) throw XIDError.stillReferenced("delegate");
1644
+ const hashKey = xid.toHex();
1645
+ if (!this._delegates.delete(hashKey)) throw XIDError.notFound("delegate");
1646
+ }
1647
+ /**
1648
+ * Get all services.
1649
+ */
1650
+ services() {
1651
+ return Array.from(this._services.values());
1652
+ }
1653
+ /**
1654
+ * Find a service by URI.
1655
+ */
1656
+ findServiceByUri(uri) {
1657
+ return this._services.get(uri);
1658
+ }
1659
+ /**
1660
+ * Add a service.
1661
+ */
1662
+ addService(service) {
1663
+ const hashKey = service.hashKey();
1664
+ if (this._services.has(hashKey)) throw XIDError.duplicate("service");
1665
+ this._services.set(hashKey, service);
1666
+ }
1667
+ /**
1668
+ * Take and remove a service.
1669
+ */
1670
+ takeService(uri) {
1671
+ const service = this._services.get(uri);
1672
+ if (service !== void 0) this._services.delete(uri);
1673
+ return service;
1674
+ }
1675
+ /**
1676
+ * Remove a service.
1677
+ */
1678
+ removeService(uri) {
1679
+ if (!this._services.delete(uri)) throw XIDError.notFound("service");
1680
+ }
1681
+ /**
1682
+ * Check service consistency.
1683
+ */
1684
+ checkServicesConsistency() {
1685
+ for (const service of this._services.values()) this.checkServiceConsistency(service);
1686
+ }
1687
+ /**
1688
+ * Check consistency of a single service.
1689
+ */
1690
+ checkServiceConsistency(service) {
1691
+ if (service.keyReferences().size === 0 && service.delegateReferences().size === 0) throw XIDError.noReferences(service.uri());
1692
+ for (const keyRef of service.keyReferences()) {
1693
+ const refBytes = hexToBytes(keyRef);
1694
+ const ref = Reference.hash(refBytes);
1695
+ if (this.findKeyByReference(ref) === void 0) throw XIDError.unknownKeyReference(keyRef, service.uri());
1696
+ }
1697
+ for (const delegateRef of service.delegateReferences()) {
1698
+ const refBytes = hexToBytes(delegateRef);
1699
+ const ref = Reference.hash(refBytes);
1700
+ if (this.findDelegateByReference(ref) === void 0) throw XIDError.unknownDelegateReference(delegateRef, service.uri());
1701
+ }
1702
+ if (service.permissions().allow.size === 0) throw XIDError.noPermissions(service.uri());
1703
+ }
1704
+ /**
1705
+ * Check if any service references the given key.
1706
+ */
1707
+ servicesReferenceKey(publicKeyBase) {
1708
+ const keyRef = Reference.hash(publicKeyBase.data()).toHex();
1709
+ for (const service of this._services.values()) if (service.keyReferences().has(keyRef)) return true;
1710
+ return false;
1711
+ }
1712
+ /**
1713
+ * Check if any service references the given delegate.
1714
+ */
1715
+ servicesReferenceDelegate(xid) {
1716
+ const delegateRef = Reference.hash(xid.toData()).toHex();
1717
+ for (const service of this._services.values()) if (service.delegateReferences().has(delegateRef)) return true;
1718
+ return false;
1719
+ }
1720
+ /**
1721
+ * Get the provenance mark.
1722
+ */
1723
+ provenance() {
1724
+ return this._provenance?.mark();
1725
+ }
1726
+ /**
1727
+ * Get the provenance generator.
1728
+ */
1729
+ provenanceGenerator() {
1730
+ return this._provenance?.generator();
1731
+ }
1732
+ /**
1733
+ * Set the provenance.
1734
+ */
1735
+ setProvenance(provenance) {
1736
+ this._provenance = provenance !== void 0 ? Provenance.new(provenance) : void 0;
1737
+ }
1738
+ /**
1739
+ * Set provenance with generator.
1740
+ */
1741
+ setProvenanceWithGenerator(generator, mark) {
1742
+ this._provenance = Provenance.newWithGenerator(generator, mark);
1743
+ }
1744
+ /**
1745
+ * Advance the provenance mark using the embedded generator.
1746
+ */
1747
+ nextProvenanceMarkWithEmbeddedGenerator(password, date, info) {
1748
+ if (this._provenance === void 0) throw XIDError.noProvenanceMark();
1749
+ const currentMark = this._provenance.mark();
1750
+ const generator = this._provenance.generatorMut(password);
1751
+ if (generator === void 0) throw XIDError.noGenerator();
1752
+ if (!bytesEqual(generator.chainId(), currentMark.chainId())) throw XIDError.chainIdMismatch(currentMark.chainId(), generator.chainId());
1753
+ const expectedSeq = currentMark.seq() + 1;
1754
+ if (generator.nextSeq() !== expectedSeq) throw XIDError.sequenceMismatch(expectedSeq, generator.nextSeq());
1755
+ const nextDate = date ?? /* @__PURE__ */ new Date();
1756
+ const nextMark = generator.next(nextDate, info);
1757
+ this._provenance.setMark(nextMark);
1758
+ }
1759
+ /**
1760
+ * Advance the provenance mark using a provided generator.
1761
+ */
1762
+ nextProvenanceMarkWithProvidedGenerator(generator, date, info) {
1763
+ if (this._provenance === void 0) throw XIDError.noProvenanceMark();
1764
+ if (this._provenance.hasGenerator() || this._provenance.hasEncryptedGenerator()) throw XIDError.generatorConflict();
1765
+ const currentMark = this._provenance.mark();
1766
+ if (!bytesEqual(generator.chainId(), currentMark.chainId())) throw XIDError.chainIdMismatch(currentMark.chainId(), generator.chainId());
1767
+ const expectedSeq = currentMark.seq() + 1;
1768
+ if (generator.nextSeq() !== expectedSeq) throw XIDError.sequenceMismatch(expectedSeq, generator.nextSeq());
1769
+ const nextDate = date ?? /* @__PURE__ */ new Date();
1770
+ const nextMark = generator.next(nextDate, info);
1771
+ this._provenance.setMark(nextMark);
1772
+ }
1773
+ /**
1774
+ * Convert to envelope with options.
1775
+ */
1776
+ toEnvelope(privateKeyOptions = XIDPrivateKeyOptions.Omit, generatorOptions = XIDGeneratorOptions.Omit, signingOptions = { type: "none" }) {
1777
+ let envelope = Envelope.new(this._xid.toData());
1778
+ for (const method of this._resolutionMethods) envelope = envelope.addAssertion(kv(DEREFERENCE_VIA), method);
1779
+ for (const key of this._keys.values()) envelope = envelope.addAssertion(kv(KEY), key.intoEnvelopeOpt(privateKeyOptions));
1780
+ for (const delegate of this._delegates.values()) envelope = envelope.addAssertion(kv(DELEGATE), delegate.intoEnvelope());
1781
+ for (const service of this._services.values()) envelope = envelope.addAssertion(kv(SERVICE), service.intoEnvelope());
1782
+ if (this._provenance !== void 0) envelope = envelope.addAssertion(kv(PROVENANCE), this._provenance.intoEnvelopeOpt(generatorOptions));
1783
+ switch (signingOptions.type) {
1784
+ case "inception": {
1785
+ const inceptionKey = this.inceptionKey();
1786
+ if (inceptionKey === void 0) throw XIDError.missingInceptionKey();
1787
+ const privateKeyBase = inceptionKey.privateKeyBase();
1788
+ if (privateKeyBase === void 0) throw XIDError.missingInceptionKey();
1789
+ envelope = envelope.addSignature(privateKeyBase);
1790
+ break;
1791
+ }
1792
+ case "privateKeyBase":
1793
+ envelope = envelope.addSignature(signingOptions.privateKeyBase);
1794
+ break;
1795
+ case "none":
1796
+ default: break;
1797
+ }
1798
+ return envelope;
1799
+ }
1800
+ intoEnvelope() {
1801
+ return this.toEnvelope();
1802
+ }
1803
+ /**
1804
+ * Extract an XIDDocument from an envelope.
1805
+ */
1806
+ static fromEnvelope(envelope, password, verifySignature = XIDVerifySignature.None) {
1807
+ const envelopeExt = envelope;
1808
+ switch (verifySignature) {
1809
+ case XIDVerifySignature.None: {
1810
+ const subject = envelopeExt.subject();
1811
+ const envelopeToParse = subject.isWrapped() ? subject.tryUnwrap() : envelope;
1812
+ return XIDDocument.fromEnvelopeInner(envelopeToParse, password);
1813
+ }
1814
+ case XIDVerifySignature.Inception: {
1815
+ if (!envelopeExt.subject().isWrapped()) throw XIDError.envelopeNotSigned();
1816
+ const unwrapped = envelopeExt.tryUnwrap();
1817
+ const doc = XIDDocument.fromEnvelopeInner(unwrapped, password);
1818
+ const inceptionKey = doc.inceptionKey();
1819
+ if (inceptionKey === void 0) throw XIDError.missingInceptionKey();
1820
+ if (!envelopeExt.hasSignatureFrom(inceptionKey.publicKeyBase())) throw XIDError.signatureVerificationFailed();
1821
+ if (!doc.isInceptionKey(inceptionKey.publicKeyBase())) throw XIDError.invalidXid();
1822
+ return doc;
1823
+ }
1824
+ }
1825
+ }
1826
+ static fromEnvelopeInner(envelope, password) {
1827
+ const envelopeExt = envelope;
1828
+ const xidData = (envelope.case().type === "node" ? envelopeExt.subject() : envelope).asByteString();
1829
+ if (xidData === void 0) throw XIDError.invalidXid();
1830
+ const xid = XID.from(xidData);
1831
+ const doc = XIDDocument.fromXid(xid);
1832
+ for (const assertion of envelopeExt.assertions()) {
1833
+ const assertionCase = assertion.case();
1834
+ if (assertionCase.type !== "assertion") continue;
1835
+ const predicateCase = assertionCase.assertion.predicate().case();
1836
+ if (predicateCase.type !== "knownValue") continue;
1837
+ const predicate = predicateCase.value.value();
1838
+ const object = assertionCase.assertion.object();
1839
+ switch (predicate) {
1840
+ case DEREFERENCE_VIA_RAW: {
1841
+ const method = object.asText();
1842
+ if (method === void 0) throw XIDError.invalidResolutionMethod();
1843
+ doc.addResolutionMethod(method);
1844
+ break;
1845
+ }
1846
+ case KEY_RAW: {
1847
+ const key = Key.tryFromEnvelope(object, password);
1848
+ doc.addKey(key);
1849
+ break;
1850
+ }
1851
+ case DELEGATE_RAW: {
1852
+ const delegate = Delegate.tryFromEnvelope(object);
1853
+ doc.addDelegate(delegate);
1854
+ break;
1855
+ }
1856
+ case SERVICE_RAW: {
1857
+ const service = Service.tryFromEnvelope(object);
1858
+ doc.addService(service);
1859
+ break;
1860
+ }
1861
+ case PROVENANCE_RAW:
1862
+ if (doc._provenance !== void 0) throw XIDError.multipleProvenanceMarks();
1863
+ doc._provenance = Provenance.tryFromEnvelope(object, password);
1864
+ break;
1865
+ default: throw XIDError.unexpectedPredicate(String(predicate));
1866
+ }
1867
+ }
1868
+ doc.checkServicesConsistency();
1869
+ return doc;
1870
+ }
1871
+ /**
1872
+ * Create a signed envelope.
1873
+ */
1874
+ toSignedEnvelope(signingKey) {
1875
+ return this.toEnvelope(XIDPrivateKeyOptions.Omit, XIDGeneratorOptions.Omit, { type: "none" }).addSignature(signingKey);
1876
+ }
1877
+ /**
1878
+ * Get the reference for this document.
1879
+ */
1880
+ reference() {
1881
+ return Reference.hash(this._xid.toData());
1882
+ }
1883
+ /**
1884
+ * Check equality with another XIDDocument.
1885
+ */
1886
+ equals(other) {
1887
+ return this._xid.equals(other._xid);
1888
+ }
1889
+ /**
1890
+ * Clone this XIDDocument.
1891
+ */
1892
+ clone() {
1893
+ return new XIDDocument(this._xid, new Set(this._resolutionMethods), new Map(Array.from(this._keys.entries()).map(([k, v]) => [k, v.clone()])), new Map(Array.from(this._delegates.entries()).map(([k, v]) => [k, v.clone()])), new Map(Array.from(this._services.entries()).map(([k, v]) => [k, v.clone()])), this._provenance?.clone());
1894
+ }
1895
+ /**
1896
+ * Try to extract from envelope (alias for fromEnvelope with default options).
1897
+ */
1898
+ static tryFromEnvelope(envelope) {
1899
+ return XIDDocument.fromEnvelope(envelope, void 0, XIDVerifySignature.None);
1900
+ }
1901
+ };
1902
+ registerXIDDocumentClass(XIDDocument);
1903
+ function hexToBytes(hex) {
1904
+ const bytes = new Uint8Array(hex.length / 2);
1905
+ for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
1906
+ return bytes;
1907
+ }
1908
+ function bytesEqual(a, b) {
1909
+ if (a.length !== b.length) return false;
1910
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1911
+ return true;
1912
+ }
1913
+ function hashPublicKey(publicKeyBase) {
1914
+ return Reference.hash(publicKeyBase.data()).getDigest().toData();
1915
+ }
1916
+
1917
+ //#endregion
1918
+ //#region src/index.ts
1919
+ const VERSION = "1.0.0-alpha.3";
1920
+
1921
+ //#endregion
1922
+ export { Delegate, HasNicknameMixin, HasPermissionsMixin, Key, Permissions, Privilege, Provenance, Service, Shared, VERSION, XIDDocument, XIDError, XIDErrorCode, XIDGeneratorOptions, XIDPrivateKeyOptions, XIDVerifySignature, privilegeFromEnvelope, privilegeFromKnownValue, privilegeToEnvelope, privilegeToKnownValue, registerXIDDocumentClass };
1923
+ //# sourceMappingURL=index.mjs.map