@dxos/credentials 0.10.0 → 0.11.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.
@@ -1,1684 +0,0 @@
1
- import "@dxos/node-std/globals";
2
-
3
- // src/did.ts
4
- import { subtleCrypto } from "@dxos/crypto";
5
- import { IdentityDid, PublicKey } from "@dxos/keys";
6
- import { ComplexMap } from "@dxos/util";
7
- var IDENTITY_DIDS_CACHE = new ComplexMap(PublicKey.hash);
8
- var createDidFromIdentityKey = async (identityKey) => {
9
- const cachedValue = IDENTITY_DIDS_CACHE.get(identityKey);
10
- if (cachedValue !== void 0) {
11
- return cachedValue;
12
- }
13
- const digest = await subtleCrypto.digest("SHA-256", identityKey.asUint8Array());
14
- const bytes = new Uint8Array(digest).slice(0, IdentityDid.byteLength);
15
- const identityDid = IdentityDid.encode(bytes);
16
- IDENTITY_DIDS_CACHE.set(identityKey, identityDid);
17
- return identityDid;
18
- };
19
-
20
- // src/invitations.ts
21
- var defaultSecretProvider = async () => Buffer.from("0000");
22
- var defaultSecretValidator = async (invitation, secret) => true;
23
-
24
- // src/seedphrase.ts
25
- import { generateMnemonic, mnemonicToSeedSync } from "bip39";
26
- import { createKeyPair } from "@dxos/crypto";
27
- import { invariant } from "@dxos/invariant";
28
- var __dxlog_file = "/__w/dxos/dxos/packages/core/halo/credentials/src/seedphrase.ts";
29
- var generateSeedPhrase = () => generateMnemonic();
30
- var keyPairFromSeedPhrase = (seedPhrase) => {
31
- invariant(seedPhrase, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 13, S: void 0, A: ["seedPhrase", ""] });
32
- const seed = mnemonicToSeedSync(seedPhrase);
33
- return createKeyPair(seed);
34
- };
35
-
36
- // src/passcode.ts
37
- var generatePasscode = (length = 4) => {
38
- let passcode = "";
39
- for (let i = 0; i < length; i++) {
40
- passcode += `${Math.floor(Math.random() * 10)}`;
41
- }
42
- return passcode;
43
- };
44
-
45
- // src/credentials/signing.ts
46
- import stableStringify from "json-stable-stringify";
47
- import { PublicKey as PublicKey2 } from "@dxos/keys";
48
- import { Timeframe } from "@dxos/timeframe";
49
- import { arrayToBuffer } from "@dxos/util";
50
- var getCredentialProofPayload = (credential) => {
51
- const copy = {
52
- ...credential,
53
- proof: {
54
- ...credential.proof,
55
- value: new Uint8Array(),
56
- chain: void 0
57
- }
58
- };
59
- if (copy.parentCredentialIds?.length === 0) {
60
- delete copy.parentCredentialIds;
61
- }
62
- delete copy.id;
63
- const originalAssertion = copy.subject?.assertion;
64
- if (originalAssertion) {
65
- const normalizedAssertion = {
66
- ...originalAssertion
67
- };
68
- for (const key of Object.keys(normalizedAssertion)) {
69
- const val = normalizedAssertion[key];
70
- if (val === void 0 || val === null || val === 0 || val === "" || val === false || Array.isArray(val) && val.length === 0) {
71
- delete normalizedAssertion[key];
72
- }
73
- }
74
- copy.subject = {
75
- ...copy.subject,
76
- assertion: normalizedAssertion
77
- };
78
- }
79
- return Buffer.from(canonicalStringify(copy));
80
- };
81
- var canonicalStringify = (obj) => stableStringify(obj, {
82
- /* The point of signing and verifying is not that the internal, private state of the objects be
83
- * identical, but that the public contents can be verified not to have been altered. For that reason,
84
- * really private fields (indicated by '__') are not included in the signature.
85
- * This gives a mechanism for attaching other attributes to an object without breaking the signature.
86
- * We also skip @type.
87
- */
88
- // TODO(dmaretskyi): Should we actually skip the @type field?
89
- replacer: function(key, value) {
90
- if (key.toString().startsWith("__") || key.toString() === "@type") {
91
- return void 0;
92
- }
93
- if (value === null) {
94
- return void 0;
95
- }
96
- const original = this[key];
97
- if (value) {
98
- if (PublicKey2.isPublicKey(value)) {
99
- return value.toHex();
100
- }
101
- if (Buffer.isBuffer(value)) {
102
- return value.toString("hex");
103
- }
104
- if (value instanceof Uint8Array) {
105
- return arrayToBuffer(value).toString("hex");
106
- }
107
- if (value.data && value.type === "Buffer") {
108
- return Buffer.from(value).toString("hex");
109
- }
110
- if (original instanceof Timeframe) {
111
- return original.frames().reduce((frames, [key2, seq]) => {
112
- frames[truncateKey(key2)] = seq;
113
- return frames;
114
- }, {});
115
- }
116
- }
117
- return value;
118
- }
119
- });
120
- var truncateKey = (key) => {
121
- const str = key.toHex();
122
- return `${str.substring(0, 4)}...${str.substring(str.length - 4)}`;
123
- };
124
-
125
- // src/presentations/signing.ts
126
- var getPresentationProofPayload = (credentials, proof) => {
127
- const copy = {
128
- credentials: credentials.map((credential) => removeEmptyParentCredentialIds(credential)),
129
- proof: {
130
- ...proof,
131
- value: new Uint8Array(),
132
- chain: void 0
133
- }
134
- };
135
- return Buffer.from(canonicalStringify(copy));
136
- };
137
- var removeEmptyParentCredentialIds = (credential) => {
138
- const copy = {
139
- ...credential,
140
- proof: credential.proof ? {
141
- ...credential.proof,
142
- chain: credential.proof.chain ? {
143
- credential: removeEmptyParentCredentialIds(credential.proof.chain.credential)
144
- } : void 0
145
- } : void 0
146
- };
147
- if (copy.parentCredentialIds?.length === 0) {
148
- delete copy.parentCredentialIds;
149
- }
150
- return copy;
151
- };
152
-
153
- // src/credentials/assertions.ts
154
- var getCredentialAssertion = (credential) => credential.subject.assertion;
155
- var isValidAuthorizedDeviceCredential = (credential, identityKey, deviceKey) => {
156
- const assertion = getCredentialAssertion(credential);
157
- return credential.subject.id.equals(deviceKey) && credential.issuer.equals(identityKey) && assertion["@type"] === "dxos.halo.credentials.AuthorizedDevice" && assertion.identityKey.equals(identityKey) && assertion.deviceKey.equals(deviceKey);
158
- };
159
- var checkCredentialType = (credential, type) => credential.subject.assertion["@type"] === type;
160
- var credentialTypeFilter = (type) => (credential) => checkCredentialType(credential, type);
161
-
162
- // src/credentials/credential-factory.ts
163
- import { subtleCrypto as subtleCrypto2 } from "@dxos/crypto";
164
- import { invariant as invariant2 } from "@dxos/invariant";
165
- import { PublicKey as PublicKey3 } from "@dxos/keys";
166
-
167
- // src/credentials/verifier.ts
168
- import { verifySignature } from "@dxos/crypto";
169
- var SIGNATURE_TYPE_ED25519 = "ED25519Signature";
170
- var verifyCredential = async (credential) => {
171
- if (credential.parentCredentialIds?.length === 0) {
172
- delete credential.parentCredentialIds;
173
- }
174
- if (!credential.issuer.equals(credential.proof.signer)) {
175
- if (!credential.proof.chain) {
176
- return {
177
- kind: "fail",
178
- errors: [
179
- "Delegated credential is missing credential chain."
180
- ]
181
- };
182
- }
183
- const result2 = await verifyChain(credential.proof.chain, credential.issuer, credential.proof.signer);
184
- if (result2.kind === "fail") {
185
- return result2;
186
- }
187
- }
188
- const result = await verifyCredentialSignature(credential);
189
- if (result.kind === "fail") {
190
- return result;
191
- }
192
- return {
193
- kind: "pass"
194
- };
195
- };
196
- var verifyCredentialSignature = async (credential) => {
197
- if (credential.proof.type !== SIGNATURE_TYPE_ED25519) {
198
- return {
199
- kind: "fail",
200
- errors: [
201
- `Invalid signature type: ${credential.proof.type}`
202
- ]
203
- };
204
- }
205
- const signData = getCredentialProofPayload(credential);
206
- if (!await verifySignature(credential.proof.signer, signData, credential.proof.value)) {
207
- return {
208
- kind: "fail",
209
- errors: [
210
- "Invalid signature"
211
- ]
212
- };
213
- }
214
- return {
215
- kind: "pass"
216
- };
217
- };
218
- var verifyChain = async (chain, authority, subject) => {
219
- const result = await verifyCredential(chain.credential);
220
- if (result.kind === "fail") {
221
- return result;
222
- }
223
- if (!isValidAuthorizedDeviceCredential(chain.credential, authority, subject)) {
224
- return {
225
- kind: "fail",
226
- errors: [
227
- `Invalid credential chain: invalid assertion for key: ${subject}`
228
- ]
229
- };
230
- }
231
- return {
232
- kind: "pass"
233
- };
234
- };
235
-
236
- // src/credentials/credential-factory.ts
237
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/halo/credentials/src/credentials/credential-factory.ts";
238
- var createCredential = async ({ signer, issuer, subject, assertion, signingKey, chain, nonce, parentCredentialIds }) => {
239
- invariant2(assertion["@type"], "Invalid assertion.", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 12, S: void 0, A: ["assertion['@type']", "'Invalid assertion.'"] });
240
- invariant2(!!signingKey === !!chain, "Chain must be provided if and only if the signing key differs from the issuer.", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 13, S: void 0, A: ["!!signingKey === !!chain", "'Chain must be provided if and only if the signing key differs from the issuer.'"] });
241
- if (chain) {
242
- const result = await verifyChain(chain, issuer, signingKey);
243
- invariant2(result.kind === "pass", "Invalid chain.", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 16, S: void 0, A: ["result.kind === 'pass'", "'Invalid chain.'"] });
244
- }
245
- const credential = {
246
- issuer,
247
- issuanceDate: /* @__PURE__ */ new Date(),
248
- subject: {
249
- id: subject,
250
- assertion
251
- },
252
- parentCredentialIds,
253
- proof: {
254
- type: SIGNATURE_TYPE_ED25519,
255
- creationDate: /* @__PURE__ */ new Date(),
256
- signer: signingKey ?? issuer,
257
- value: new Uint8Array(),
258
- nonce
259
- }
260
- };
261
- const signedPayload = getCredentialProofPayload(credential);
262
- credential.proof.value = await signer.sign(signingKey ?? issuer, signedPayload);
263
- if (chain) {
264
- credential.proof.chain = chain;
265
- }
266
- credential.id = PublicKey3.from(await subtleCrypto2.digest("SHA-256", signedPayload));
267
- return credential;
268
- };
269
- var createCredentialMessage = (credential) => {
270
- return {
271
- "@type": "dxos.echo.feed.CredentialsMessage",
272
- credential
273
- };
274
- };
275
- var createCredentialSignerWithKey = (signer, issuer) => ({
276
- getIssuer: () => issuer,
277
- createCredential: ({ subject, assertion, nonce, parentCredentialIds }) => createCredential({
278
- signer,
279
- issuer,
280
- subject,
281
- assertion,
282
- nonce,
283
- parentCredentialIds
284
- })
285
- });
286
- var createCredentialSignerWithChain = (signer, chain, signingKey) => ({
287
- getIssuer: () => chain.credential.issuer,
288
- createCredential: ({ subject, assertion, nonce, parentCredentialIds }) => createCredential({
289
- signer,
290
- issuer: chain.credential.issuer,
291
- signingKey,
292
- chain,
293
- subject,
294
- assertion,
295
- nonce,
296
- parentCredentialIds
297
- })
298
- });
299
-
300
- // src/credentials/credential-generator.ts
301
- import { AdmittedFeed, MembershipPolicy, SpaceMember } from "@dxos/protocols/proto/dxos/halo/credentials";
302
- import { Timeframe as Timeframe2 } from "@dxos/timeframe";
303
- var CredentialGenerator = class {
304
- _signer;
305
- _identityKey;
306
- _deviceKey;
307
- constructor(_signer, _identityKey, _deviceKey) {
308
- this._signer = _signer;
309
- this._identityKey = _identityKey;
310
- this._deviceKey = _deviceKey;
311
- }
312
- /**
313
- * Create genesis messages for new Space.
314
- */
315
- async createSpaceGenesis(spaceKey, controlKey, creatorProfile, membershipPolicy = MembershipPolicy.INVITE) {
316
- return [
317
- await createCredential({
318
- signer: this._signer,
319
- issuer: spaceKey,
320
- subject: spaceKey,
321
- assertion: {
322
- "@type": "dxos.halo.credentials.SpaceGenesis",
323
- spaceKey,
324
- membershipPolicy
325
- }
326
- }),
327
- await createCredential({
328
- signer: this._signer,
329
- issuer: spaceKey,
330
- subject: this._identityKey,
331
- assertion: {
332
- "@type": "dxos.halo.credentials.SpaceMember",
333
- spaceKey,
334
- "role": SpaceMember.Role.ADMIN,
335
- "profile": creatorProfile,
336
- "genesisFeedKey": controlKey
337
- }
338
- }),
339
- await this.createFeedAdmission(spaceKey, controlKey, AdmittedFeed.Designation.CONTROL)
340
- ];
341
- }
342
- /**
343
- * Create invitation.
344
- * Admit identity and control and data feeds.
345
- */
346
- // TODO(burdon): Reconcile with above (esp. Signer).
347
- async createMemberInvitation(spaceKey, identityKey, deviceKey, controlKey, dataKey, genesisFeedKey) {
348
- return [
349
- await createCredential({
350
- signer: this._signer,
351
- issuer: this._identityKey,
352
- subject: identityKey,
353
- assertion: {
354
- "@type": "dxos.halo.credentials.SpaceMember",
355
- spaceKey,
356
- "role": SpaceMember.Role.EDITOR,
357
- genesisFeedKey
358
- }
359
- }),
360
- await this.createFeedAdmission(spaceKey, controlKey, AdmittedFeed.Designation.CONTROL),
361
- await this.createFeedAdmission(spaceKey, dataKey, AdmittedFeed.Designation.DATA)
362
- ];
363
- }
364
- /**
365
- * Add device to space.
366
- */
367
- // TODO(burdon): Reconcile with below.
368
- async createDeviceAuthorization(deviceKey) {
369
- return createCredential({
370
- signer: this._signer,
371
- issuer: this._identityKey,
372
- subject: deviceKey,
373
- assertion: {
374
- "@type": "dxos.halo.credentials.AuthorizedDevice",
375
- "identityKey": this._identityKey,
376
- deviceKey
377
- }
378
- });
379
- }
380
- /**
381
- * Add device metadata.
382
- */
383
- async createDeviceProfile(profile) {
384
- return createCredential({
385
- signer: this._signer,
386
- issuer: this._identityKey,
387
- subject: this._deviceKey,
388
- assertion: {
389
- "@type": "dxos.halo.credentials.DeviceProfile",
390
- profile
391
- }
392
- });
393
- }
394
- /**
395
- * Add feed to space.
396
- */
397
- async createFeedAdmission(spaceKey, feedKey, designation) {
398
- return createCredential({
399
- signer: this._signer,
400
- issuer: this._identityKey,
401
- subject: feedKey,
402
- assertion: {
403
- "@type": "dxos.halo.credentials.AdmittedFeed",
404
- spaceKey,
405
- "identityKey": this._identityKey,
406
- "deviceKey": this._deviceKey,
407
- designation
408
- }
409
- });
410
- }
411
- async createProfileCredential(profile) {
412
- return createCredential({
413
- signer: this._signer,
414
- issuer: this._identityKey,
415
- subject: this._identityKey,
416
- assertion: {
417
- "@type": "dxos.halo.credentials.IdentityProfile",
418
- profile
419
- }
420
- });
421
- }
422
- async createEpochCredential(spaceKey) {
423
- return createCredential({
424
- signer: this._signer,
425
- issuer: this._identityKey,
426
- subject: spaceKey,
427
- assertion: {
428
- "@type": "dxos.halo.credentials.Epoch",
429
- "number": 0,
430
- "timeframe": new Timeframe2()
431
- }
432
- });
433
- }
434
- };
435
- var createDeviceAuthorization = async (signer, identityKey, deviceKey) => {
436
- const credentials = await Promise.all([
437
- await signer.createCredential({
438
- subject: deviceKey,
439
- assertion: {
440
- "@type": "dxos.halo.credentials.AuthorizedDevice",
441
- identityKey,
442
- deviceKey
443
- }
444
- })
445
- ]);
446
- return credentials.map((credential) => ({
447
- "@type": "dxos.echo.feed.CredentialsMessage",
448
- credential
449
- }));
450
- };
451
- var createAdmissionCredentials = async (signer, identityKey, spaceKey, genesisFeedKey, role = SpaceMember.Role.ADMIN, membershipChainHeads = [], profile, invitationCredentialId, tags) => {
452
- const credentials = await Promise.all([
453
- await signer.createCredential({
454
- subject: identityKey,
455
- parentCredentialIds: membershipChainHeads,
456
- assertion: {
457
- "@type": "dxos.halo.credentials.SpaceMember",
458
- spaceKey,
459
- role,
460
- profile,
461
- genesisFeedKey,
462
- invitationCredentialId,
463
- "tags": tags ?? []
464
- }
465
- })
466
- ]);
467
- return credentials.map((credential) => ({
468
- credential: {
469
- credential
470
- }
471
- }));
472
- };
473
- var createDelegatedSpaceInvitationCredential = async (signer, subject, invitation) => {
474
- const credential = await signer.createCredential({
475
- subject,
476
- assertion: {
477
- "@type": "dxos.halo.invitations.DelegateSpaceInvitation",
478
- "invitationId": invitation.invitationId,
479
- "authMethod": invitation.authMethod,
480
- "swarmKey": invitation.swarmKey,
481
- "role": invitation.role,
482
- "guestKey": invitation.guestKey,
483
- "expiresOn": invitation.expiresOn,
484
- "multiUse": invitation.multiUse
485
- }
486
- });
487
- return {
488
- credential: {
489
- credential
490
- }
491
- };
492
- };
493
- var createCancelDelegatedSpaceInvitationCredential = async (signer, subject, invitationCredentialId) => {
494
- const credential = await signer.createCredential({
495
- subject,
496
- assertion: {
497
- "@type": "dxos.halo.invitations.CancelDelegatedInvitation",
498
- "credentialId": invitationCredentialId
499
- }
500
- });
501
- return {
502
- credential: {
503
- credential
504
- }
505
- };
506
- };
507
-
508
- // src/presentations/presentation.ts
509
- var signPresentation = async ({ presentation, signer, signerKey, chain, nonce }) => {
510
- const proof = {
511
- type: SIGNATURE_TYPE_ED25519,
512
- value: new Uint8Array(),
513
- creationDate: /* @__PURE__ */ new Date(),
514
- signer: signerKey,
515
- nonce
516
- };
517
- const signedPayload = getPresentationProofPayload(presentation.credentials ?? [], proof);
518
- proof.value = await signer.sign(signerKey, signedPayload);
519
- if (chain) {
520
- proof.chain = chain;
521
- }
522
- return {
523
- credentials: presentation.credentials,
524
- proofs: [
525
- ...presentation.proofs ?? [],
526
- proof
527
- ]
528
- };
529
- };
530
-
531
- // src/presentations/verifier.ts
532
- import { verifySignature as verifySignature2 } from "@dxos/crypto";
533
- var verifyPresentation = async (presentation) => {
534
- const errors = [];
535
- const credentialsVerifications = await Promise.all(presentation.credentials?.map((credential) => verifyCredential(credential)) ?? []);
536
- for (const verification of credentialsVerifications) {
537
- if (verification.kind === "fail") {
538
- errors.push(...verification.errors);
539
- }
540
- }
541
- const proofVerification = await Promise.all(presentation.proofs?.map(async (proof) => {
542
- const chainVerification = await verifyPresentationChain(presentation, proof);
543
- if (chainVerification.kind === "fail") {
544
- return chainVerification;
545
- }
546
- const signatureVerification = await verifyPresentationSignature(presentation, proof);
547
- if (signatureVerification.kind === "fail") {
548
- return signatureVerification;
549
- }
550
- return {
551
- kind: "pass"
552
- };
553
- }) ?? []);
554
- for (const verification of proofVerification) {
555
- if (verification.kind === "fail") {
556
- errors.push(...verification.errors);
557
- }
558
- }
559
- if (errors.length === 0) {
560
- return {
561
- kind: "pass"
562
- };
563
- }
564
- {
565
- return {
566
- kind: "fail",
567
- errors
568
- };
569
- }
570
- };
571
- var verifyPresentationChain = async (presentation, proof) => {
572
- for (const credential of presentation.credentials ?? []) {
573
- if (!credential.issuer.equals(proof.signer)) {
574
- if (!proof.chain) {
575
- return {
576
- kind: "fail",
577
- errors: [
578
- "Delegated credential is missing credential chain."
579
- ]
580
- };
581
- }
582
- const chainVerification = await verifyChain(proof.chain, credential.subject.id, proof.signer);
583
- if (chainVerification.kind === "fail") {
584
- return chainVerification;
585
- }
586
- }
587
- }
588
- return {
589
- kind: "pass"
590
- };
591
- };
592
- var verifyPresentationSignature = async (presentation, proof) => {
593
- if (proof.type !== SIGNATURE_TYPE_ED25519) {
594
- return {
595
- kind: "fail",
596
- errors: [
597
- `Invalid signature type: ${proof.type}`
598
- ]
599
- };
600
- }
601
- const signData = getPresentationProofPayload(presentation.credentials ?? [], proof);
602
- if (!await verifySignature2(proof.signer, signData, proof.value)) {
603
- return {
604
- kind: "fail",
605
- errors: [
606
- "Invalid signature"
607
- ]
608
- };
609
- }
610
- return {
611
- kind: "pass"
612
- };
613
- };
614
-
615
- // src/state-machine/space-state-machine.ts
616
- import { runInContextAsync, synchronized } from "@dxos/async";
617
- import { Context } from "@dxos/context";
618
- import { PublicKey as PublicKey8 } from "@dxos/keys";
619
- import { log as log3 } from "@dxos/log";
620
- import { MembershipPolicy as MembershipPolicy2, SpaceMember as SpaceMember3 } from "@dxos/protocols/proto/dxos/halo/credentials";
621
- import { Callback as Callback4, ComplexMap as ComplexMap6, ComplexSet as ComplexSet3 } from "@dxos/util";
622
-
623
- // src/state-machine/feed-state-machine.ts
624
- import { invariant as invariant3 } from "@dxos/invariant";
625
- import { PublicKey as PublicKey4 } from "@dxos/keys";
626
- import { Callback, ComplexMap as ComplexMap2 } from "@dxos/util";
627
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/halo/credentials/src/state-machine/feed-state-machine.ts";
628
- var FeedStateMachine = class {
629
- _spaceKey;
630
- _feeds = new ComplexMap2(PublicKey4.hash);
631
- onFeedAdmitted = new Callback();
632
- constructor(_spaceKey) {
633
- this._spaceKey = _spaceKey;
634
- }
635
- get feeds() {
636
- return this._feeds;
637
- }
638
- /**
639
- * Processes the AdmittedFeed credential.
640
- * Assumes the credential is already pre-verified
641
- * and the issuer has been authorized to issue credentials of this type.
642
- * @param fromFeed Key of the feed where this credential is recorded.
643
- */
644
- async process(credential, fromFeed) {
645
- const assertion = getCredentialAssertion(credential);
646
- invariant3(assertion["@type"] === "dxos.halo.credentials.AdmittedFeed", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 28, S: this, A: ["assertion['@type'] === 'dxos.halo.credentials.AdmittedFeed'", ""] });
647
- invariant3(assertion.spaceKey.equals(this._spaceKey), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 29, S: this, A: ["assertion.spaceKey.equals(this._spaceKey)", ""] });
648
- const info = {
649
- key: credential.subject.id,
650
- credential,
651
- assertion,
652
- parent: fromFeed
653
- };
654
- this._feeds.set(credential.subject.id, info);
655
- await this.onFeedAdmitted.callIfSet(info);
656
- }
657
- };
658
-
659
- // src/state-machine/invitation-state-machine.ts
660
- import { PublicKey as PublicKey5 } from "@dxos/keys";
661
- import { Callback as Callback2, ComplexMap as ComplexMap3, ComplexSet } from "@dxos/util";
662
- var InvitationStateMachine = class {
663
- _invitations = new ComplexMap3(PublicKey5.hash);
664
- _redeemedInvitationCredentialIds = new ComplexSet(PublicKey5.hash);
665
- _cancelledInvitationCredentialIds = new ComplexSet(PublicKey5.hash);
666
- onDelegatedInvitation = new Callback2();
667
- onDelegatedInvitationRemoved = new Callback2();
668
- get invitations() {
669
- return this._invitations;
670
- }
671
- async process(credential) {
672
- const credentialId = credential.id;
673
- if (credentialId == null) {
674
- return;
675
- }
676
- const assertion = getCredentialAssertion(credential);
677
- switch (assertion["@type"]) {
678
- case "dxos.halo.invitations.CancelDelegatedInvitation": {
679
- this._cancelledInvitationCredentialIds.add(assertion.credentialId);
680
- const existingInvitation = this._invitations.get(assertion.credentialId);
681
- if (existingInvitation != null) {
682
- this._invitations.delete(assertion.credentialId);
683
- await this.onDelegatedInvitationRemoved.callIfSet({
684
- credentialId: assertion.credentialId,
685
- invitation: existingInvitation
686
- });
687
- }
688
- break;
689
- }
690
- case "dxos.halo.invitations.DelegateSpaceInvitation": {
691
- if (credential.id) {
692
- const isExpired = assertion.expiresOn && assertion.expiresOn.getTime() < Date.now();
693
- const wasUsed = this._redeemedInvitationCredentialIds.has(credential.id) && !assertion.multiUse;
694
- const wasCancelled = this._cancelledInvitationCredentialIds.has(credential.id);
695
- if (isExpired || wasCancelled || wasUsed) {
696
- return;
697
- }
698
- const invitation = {
699
- ...assertion
700
- };
701
- this._invitations.set(credential.id, invitation);
702
- await this.onDelegatedInvitation.callIfSet({
703
- credentialId: credential.id,
704
- invitation
705
- });
706
- }
707
- break;
708
- }
709
- case "dxos.halo.credentials.SpaceMember": {
710
- if (assertion.invitationCredentialId != null) {
711
- this._redeemedInvitationCredentialIds.add(assertion.invitationCredentialId);
712
- const existingInvitation = this._invitations.get(assertion.invitationCredentialId);
713
- if (existingInvitation != null && !existingInvitation.multiUse) {
714
- this._invitations.delete(assertion.invitationCredentialId);
715
- await this.onDelegatedInvitationRemoved.callIfSet({
716
- credentialId: assertion.invitationCredentialId,
717
- invitation: existingInvitation
718
- });
719
- }
720
- }
721
- break;
722
- }
723
- }
724
- }
725
- };
726
-
727
- // src/state-machine/member-state-machine.ts
728
- import { invariant as invariant5 } from "@dxos/invariant";
729
- import { PublicKey as PublicKey7 } from "@dxos/keys";
730
- import { log as log2 } from "@dxos/log";
731
- import { SpaceMember as SpaceMember2 } from "@dxos/protocols/proto/dxos/halo/credentials";
732
- import { ComplexMap as ComplexMap5 } from "@dxos/util";
733
-
734
- // src/graph/credential-graph.ts
735
- import { invariant as invariant4 } from "@dxos/invariant";
736
- import { PublicKey as PublicKey6 } from "@dxos/keys";
737
- import { log } from "@dxos/log";
738
- import { Callback as Callback3, ComplexMap as ComplexMap4, ComplexSet as ComplexSet2 } from "@dxos/util";
739
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/halo/credentials/src/graph/credential-graph.ts";
740
- var CredentialGraph = class {
741
- _stateHandler;
742
- /**
743
- * Local ids are used during traversals.
744
- */
745
- _vertexIdGenerator = 1;
746
- /**
747
- * All credentials without parent references are connected to the root.
748
- */
749
- _root = {
750
- id: -1,
751
- parents: [],
752
- children: []
753
- };
754
- /**
755
- * A credential which is not a parent of any other credential has the sentinel as a child.
756
- * Sentinel is a virtual merge-point of all credentials.
757
- */
758
- _sentinel = {
759
- id: -2,
760
- parents: [],
761
- children: []
762
- };
763
- /**
764
- * Vertex references are used for fast credential inserts into the graph.
765
- */
766
- _vertexByCredentialId = new ComplexMap4(PublicKey6.hash);
767
- /**
768
- * The current state of the graph.
769
- */
770
- _subjectToVertex = new ComplexMap4(PublicKey6.hash);
771
- _subjectToState = new ComplexMap4(PublicKey6.hash);
772
- onSubjectStateChanged = new Callback3();
773
- constructor(_stateHandler) {
774
- this._stateHandler = _stateHandler;
775
- }
776
- getSubjectState(subjectId) {
777
- return this._subjectToState.get(subjectId);
778
- }
779
- getState() {
780
- return this._subjectToState;
781
- }
782
- getLeafIds() {
783
- return this._sentinel.parents.map((v) => v.credential.id);
784
- }
785
- getGlobalStateScope() {
786
- return {
787
- state: this._subjectToVertex
788
- };
789
- }
790
- addVertex(credential, assertion) {
791
- const newVertex = {
792
- id: this._vertexIdGenerator++,
793
- credential,
794
- assertion,
795
- parents: [],
796
- children: []
797
- };
798
- this._vertexByCredentialId.set(credential.id, newVertex);
799
- const parentIds = credential.parentCredentialIds ?? [];
800
- if (parentIds.length === 0) {
801
- this._root.children.push(newVertex);
802
- newVertex.parents.push(this._root);
803
- } else {
804
- for (const parentId of parentIds) {
805
- const parentVertex = this._vertexByCredentialId.get(parentId);
806
- if (parentVertex == null) {
807
- log.error("credential skipped because of the unknown parent", {
808
- credential,
809
- parentId
810
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 70, S: this });
811
- continue;
812
- }
813
- parentVertex.children.push(newVertex);
814
- newVertex.parents.push(parentVertex);
815
- this._removeSentinelConnection(parentVertex);
816
- }
817
- }
818
- newVertex.children.push(this._sentinel);
819
- this._sentinel.parents.push(newVertex);
820
- return this._onVertexInserted(newVertex);
821
- }
822
- _removeSentinelConnection(vertex) {
823
- const sentinelIdx = vertex.children.indexOf(this._sentinel);
824
- if (sentinelIdx >= 0) {
825
- vertex.children.splice(sentinelIdx, 1);
826
- const vertexInSentinelIdx = this._sentinel.parents.indexOf(vertex);
827
- invariant4(vertexInSentinelIdx >= 0, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 90, S: this, A: ["vertexInSentinelIdx >= 0", ""] });
828
- this._sentinel.parents.splice(vertexInSentinelIdx, 1);
829
- }
830
- }
831
- async _onVertexInserted(newVertex) {
832
- const { credential, assertion } = newVertex;
833
- invariant4(credential, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 96, S: this, A: ["credential", ""] });
834
- let changedSubjects = [];
835
- const isUpdateAppliedOnTopOfThePreviousState = this._sentinel.parents.length === 1;
836
- if (isUpdateAppliedOnTopOfThePreviousState) {
837
- const subjectId = credential.subject.id;
838
- if (this._stateHandler.isUpdateAllowed(this.getGlobalStateScope(), credential, assertion)) {
839
- const newSubjectState = this._stateHandler.createState(credential, newVertex.assertion);
840
- const prevSubjectState = this._subjectToState.get(subjectId);
841
- this._subjectToState.set(subjectId, newSubjectState);
842
- this._subjectToVertex.set(subjectId, newVertex);
843
- if (this._stateHandler.hasStateChanged(newSubjectState, prevSubjectState)) {
844
- changedSubjects.push(newSubjectState);
845
- }
846
- }
847
- } else {
848
- changedSubjects = this._recomputeState();
849
- }
850
- if (changedSubjects.length > 0) {
851
- await this.onSubjectStateChanged.callIfSet(changedSubjects);
852
- }
853
- }
854
- /**
855
- * DFS the graph from root to sentinel pausing on merge points (nodes with multiple parents).
856
- * Continue after all paths leading to a merge point converge by merging their states.
857
- * In case of a concurrent update paths are replayed taking into account the state set
858
- * by the winning branch.
859
- */
860
- _recomputeState() {
861
- const pendingPaths = /* @__PURE__ */ new Map();
862
- const paths = [
863
- this._createRootPath()
864
- ];
865
- let lastPath = null;
866
- while (lastPath == null) {
867
- const path = paths.pop();
868
- log("visit vertex", {
869
- id: path.head.id
870
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 131, S: this });
871
- this._updatePathState(path);
872
- const convergedPaths = this._handleMergePoint(paths, pendingPaths, path);
873
- if (convergedPaths == null) {
874
- log("waiting for other paths", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 137, S: this });
875
- continue;
876
- }
877
- const mergeResult = this._mergePaths(convergedPaths);
878
- if (mergeResult.type === "replay_required") {
879
- this._replayFailedPaths(paths, pendingPaths, mergeResult, convergedPaths);
880
- continue;
881
- }
882
- const merged = mergeResult.path;
883
- if (merged.head.children.length === 0) {
884
- lastPath = merged;
885
- } else if (merged.head.children.length === 1) {
886
- merged.head = merged.head.children[0];
887
- paths.push(merged);
888
- } else {
889
- this._forkTraversal(paths, merged);
890
- }
891
- }
892
- if (paths.length > 0) {
893
- log.error("traversal finished while there were active paths", {
894
- paths: paths.map((p) => ({
895
- path: toChosenPath(p),
896
- head: p.head.id
897
- }))
898
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 156, S: this });
899
- }
900
- return this._setCurrentState(lastPath);
901
- }
902
- _replayFailedPaths(paths, pendingPaths, mergeResult, convergedPaths) {
903
- paths.push(...mergeResult.replay.map((path) => {
904
- const stateOverrides = path.stateOverrides ?? new ComplexMap4(PublicKey6.hash);
905
- mergeResult.stateOverrides.forEach((value, key) => stateOverrides.set(key, value));
906
- return {
907
- ...mergeResult.from,
908
- chosenPath: path.chosenPath,
909
- stateOverrides
910
- };
911
- }));
912
- log("replay paths", () => ({
913
- count: paths.length,
914
- paths: paths.map((path) => ({
915
- from: mergeResult.from.head.id,
916
- path: toChosenPath(path),
917
- overrides: path?.stateOverrides?.mapValues((v) => this._stateHandler.toLogString(v.assertion))
918
- }))
919
- }), { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 175, S: this });
920
- const clearedPending = convergedPaths.filter((l) => !mergeResult.replay.includes(l));
921
- pendingPaths.set(convergedPaths[0].head.id, clearedPending);
922
- }
923
- _handleMergePoint(paths, pendingPaths, path) {
924
- const pendingList = pendingPaths.get(path.head.id) ?? [];
925
- pendingPaths.set(path.head.id, pendingList);
926
- pendingList.push(path);
927
- if (pendingList.length < path.head.parents.length) {
928
- return null;
929
- }
930
- if (path.head.id === this._sentinel.id && paths.length > 0) {
931
- log("waiting for all the active paths to converge on the sentinel", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 194, S: this });
932
- return null;
933
- }
934
- pendingPaths.delete(path.head.id);
935
- return pendingList;
936
- }
937
- _updatePathState(path) {
938
- const headCredential = path.head.credential;
939
- if (headCredential == null) {
940
- return;
941
- }
942
- const updatedSubject = headCredential.subject.id;
943
- path.credentials.add(headCredential.id);
944
- let isUpdateAllowed = this._stateHandler.isUpdateAllowed(path, headCredential, path.head.assertion);
945
- if (!isUpdateAllowed && path.head.parents[0]?.id === this._root.id) {
946
- const globalState = this.getGlobalStateScope();
947
- isUpdateAllowed = this._stateHandler.isUpdateAllowed(globalState, headCredential, path.head.assertion);
948
- }
949
- if (isUpdateAllowed) {
950
- path.forkChangedSubjects.add(updatedSubject);
951
- path.forkIssuers.add(headCredential.issuer);
952
- path.state.set(updatedSubject, path.head);
953
- log("path state updated", () => ({
954
- subject: updatedSubject,
955
- newState: this._stateHandler.toLogString(path.head.assertion)
956
- }), { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 217, S: this });
957
- }
958
- }
959
- _forkTraversal(paths, path) {
960
- const replayChoice = path.chosenPath?.[path.head.id];
961
- const choices = replayChoice ?? path.head.children;
962
- for (const choice of choices) {
963
- log("edge traversal", {
964
- from: path.head.id,
965
- to: choice.id
966
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 227, S: this });
967
- const fork = {
968
- forkPoint: path,
969
- chosenPath: {
970
- ...path.chosenPath,
971
- [path.head.id]: [
972
- choice
973
- ]
974
- },
975
- head: choice,
976
- credentials: new ComplexSet2(PublicKey6.hash, path.credentials),
977
- state: new ComplexMap4(PublicKey6.hash, [
978
- ...path.state.entries()
979
- ]),
980
- forkIssuers: new ComplexSet2(PublicKey6.hash),
981
- forkChangedSubjects: new ComplexSet2(PublicKey6.hash),
982
- stateOverrides: path.stateOverrides
983
- };
984
- paths.push(fork);
985
- }
986
- }
987
- /**
988
- * Updates the current graph state.
989
- * @returns changed states.
990
- */
991
- _setCurrentState(path) {
992
- const changedSubjects = [];
993
- const newStateMap = new ComplexMap4(PublicKey6.hash);
994
- const newVertexMap = new ComplexMap4(PublicKey6.hash);
995
- for (const [subjectKey, subjectVertex] of path.state.entries()) {
996
- const newState = this._stateHandler.createState(subjectVertex.credential, subjectVertex.assertion);
997
- const prevState = this._subjectToState.get(subjectKey);
998
- newStateMap.set(subjectKey, newState);
999
- newVertexMap.set(subjectKey, subjectVertex);
1000
- if (this._stateHandler.hasStateChanged(newState, prevState)) {
1001
- changedSubjects.push(newState);
1002
- }
1003
- }
1004
- this._subjectToState = newStateMap;
1005
- this._subjectToVertex = newVertexMap;
1006
- return changedSubjects;
1007
- }
1008
- /*
1009
- * Walk up all the fork points and return the first one present in all the paths.
1010
- * We use local id to determine vertex position in the graph, because nodes can't
1011
- * be inserted in the middle (between a parent and a child) and ids are monotonically increasing.
1012
- */
1013
- _leastCommonAncestor(paths) {
1014
- const uniqueForkPoints = paths.reduce((acc, path) => {
1015
- let it = path.forkPoint;
1016
- while (it) {
1017
- acc.set(it.head.id, it);
1018
- it = it.forkPoint;
1019
- }
1020
- return acc;
1021
- }, /* @__PURE__ */ new Map());
1022
- let maxId = this._root.id;
1023
- let maxState = null;
1024
- for (const [id, state] of uniqueForkPoints.entries()) {
1025
- const headCredential = state.head.credential;
1026
- if (headCredential != null) {
1027
- const isPointInEveryPath = paths.every((p) => p.credentials.has(headCredential.id));
1028
- if (isPointInEveryPath && id > maxId) {
1029
- maxId = id;
1030
- maxState = state;
1031
- }
1032
- }
1033
- }
1034
- return maxState ?? this._createRootPath();
1035
- }
1036
- /**
1037
- * We might be merging paths where some of them had fork points after the initial forking.
1038
- * We need all the paths to point to the least common fork point and contain all the changes
1039
- * that happened after it.
1040
- */
1041
- _moveUpToForkPoint(forkPoint, path) {
1042
- const isForkPointInPath = path.chosenPath[forkPoint.head.id] == null || path.forkPoint == null;
1043
- if (isForkPointInPath) {
1044
- return path;
1045
- }
1046
- if (forkPoint.head.id === path.forkPoint?.head.id) {
1047
- return path;
1048
- }
1049
- let it = path.forkPoint;
1050
- while (it.head.id !== forkPoint.head.id) {
1051
- it.forkIssuers.forEach((iss) => path.forkIssuers.add(iss));
1052
- it.forkChangedSubjects.forEach((m) => path.forkChangedSubjects.add(m));
1053
- it = it.forkPoint;
1054
- path.forkPoint = it;
1055
- }
1056
- return path;
1057
- }
1058
- _mergePaths(convergedPaths) {
1059
- invariant4(convergedPaths.length >= 1, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 320, S: this, A: ["convergedPaths.length >= 1", ""] });
1060
- if (convergedPaths.length === 1) {
1061
- return {
1062
- type: "merged",
1063
- path: convergedPaths[0]
1064
- };
1065
- }
1066
- const forkPoint = this._leastCommonAncestor(convergedPaths);
1067
- log("merging paths", () => ({
1068
- forkPointId: forkPoint.head.id,
1069
- pathCount: convergedPaths.length,
1070
- forkPoints: convergedPaths.map((fp) => fp.forkPoint?.head.id)
1071
- }), { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 328, S: this });
1072
- const paths = convergedPaths.map((p) => this._moveUpToForkPoint(forkPoint, p));
1073
- invariant4(forkPoint, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 334, S: this, A: ["forkPoint", ""] });
1074
- const result = {
1075
- forkPoint: forkPoint.forkPoint,
1076
- chosenPath: {
1077
- ...forkPoint.chosenPath,
1078
- [forkPoint.head.id]: []
1079
- },
1080
- stateOverrides: forkPoint.stateOverrides,
1081
- credentials: new ComplexSet2(PublicKey6.hash, forkPoint.credentials),
1082
- forkIssuers: new ComplexSet2(PublicKey6.hash, forkPoint.forkIssuers),
1083
- forkChangedSubjects: new ComplexSet2(PublicKey6.hash, forkPoint.forkChangedSubjects),
1084
- state: forkPoint.state.mapValues((v) => v),
1085
- head: paths[0].head
1086
- };
1087
- const subjectToBranch = new ComplexMap4(PublicKey6.hash);
1088
- for (const path of paths) {
1089
- log("processing a path", () => ({
1090
- choices: toChosenPath(path),
1091
- modified: path.forkChangedSubjects,
1092
- forkIssuers: path.forkIssuers,
1093
- state: path.state.mapValues((v) => this._stateHandler.toLogString(v.assertion))
1094
- }), { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 350, S: this });
1095
- path.forkIssuers.forEach((iss) => result.forkIssuers.add(iss));
1096
- path.credentials.forEach((cred) => result.credentials.add(cred));
1097
- result.chosenPath[forkPoint.head.id].push(...path.chosenPath[forkPoint.head.id] ?? []);
1098
- for (const modifiedSubject of path.forkChangedSubjects) {
1099
- const existingBranch = subjectToBranch.get(modifiedSubject);
1100
- if (existingBranch == null || this._shouldOverrideCredential(existingBranch, path, modifiedSubject)) {
1101
- subjectToBranch.set(modifiedSubject, path);
1102
- }
1103
- }
1104
- }
1105
- const replayPaths = /* @__PURE__ */ new Set();
1106
- const addReplayPath = replayPaths.add.bind(replayPaths);
1107
- for (const [subject, branch] of subjectToBranch.entries()) {
1108
- result.forkChangedSubjects.add(subject);
1109
- const vertex = branch.state.get(subject);
1110
- result.state.set(subject, vertex);
1111
- log("set subject state", () => ({
1112
- subject,
1113
- state: this._stateHandler.toLogString(vertex.assertion)
1114
- }), { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 372, S: this });
1115
- const otherPaths = paths.filter((p) => p !== branch);
1116
- this._stateHandler.getConflictingPaths(otherPaths, vertex).forEach(addReplayPath);
1117
- }
1118
- if (replayPaths.size > 0) {
1119
- return {
1120
- type: "replay_required",
1121
- replay: [
1122
- ...replayPaths.values()
1123
- ],
1124
- from: forkPoint,
1125
- stateOverrides: subjectToBranch.mapValues((v, key) => v.state.get(key))
1126
- };
1127
- }
1128
- return {
1129
- type: "merged",
1130
- path: result
1131
- };
1132
- }
1133
- /**
1134
- * A candidate credential is preferred over the existing credential if:
1135
- * 1. It is the merge-point, because it's the last credential that was issued in awareness of all
1136
- * the previously existing ones.
1137
- * 2. A path where candidate was set contains existing credential in it, which means that the candidate
1138
- * was issued after the existing credential by a legitimate issuer.
1139
- * 3. A state-specific logic (_stateHandler) is able to justify using the candidate credential.
1140
- * 4. The path where candidate was set has more issuers than the existing path (longer branch).
1141
- * 5. The issuance time of the candidate is after the issuance time of the existing credential (LWW).
1142
- */
1143
- _shouldOverrideCredential(existing, candidate, modifiedSubject) {
1144
- const candidateVertex = candidate.state.get(modifiedSubject);
1145
- const currentVertex = existing.state.get(modifiedSubject);
1146
- if (candidateVertex.id === currentVertex.id) {
1147
- return false;
1148
- }
1149
- const mergePointId = existing.head.id;
1150
- if (candidateVertex.id === mergePointId || currentVertex.id === mergePointId) {
1151
- log("merge point chosen to break the tie", {
1152
- mergePointId: existing.head.id
1153
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 412, S: this });
1154
- return mergePointId === candidateVertex.id;
1155
- }
1156
- const candidateCredential = candidateVertex.credential;
1157
- const currentCredential = currentVertex.credential;
1158
- if (existing.credentials.has(candidateCredential.id) !== candidate.credentials.has(currentCredential.id)) {
1159
- log("one of the credentials was overridden in another branch", {
1160
- current: currentVertex.id,
1161
- candidate: candidateVertex.id
1162
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 421, S: this });
1163
- return candidate.credentials.has(currentCredential.id);
1164
- }
1165
- const winningCredential = this._stateHandler.tryPickWinningUpdate(existing, currentCredential, candidate, candidateCredential);
1166
- if (winningCredential != null) {
1167
- return winningCredential === candidateCredential;
1168
- }
1169
- if (candidate.forkIssuers.size !== existing.forkIssuers.size) {
1170
- log("longer issuers branch used to break the tie", {
1171
- issuerCount: [
1172
- existing.forkIssuers.size,
1173
- candidate.forkIssuers.size
1174
- ]
1175
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 433, S: this });
1176
- return candidate.forkIssuers.size > existing.forkIssuers.size;
1177
- }
1178
- log("issuance date used to break the tie", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 441, S: this });
1179
- return candidateCredential.issuanceDate.getTime() > currentCredential.issuanceDate.getTime();
1180
- }
1181
- _createRootPath() {
1182
- return {
1183
- head: this._root,
1184
- chosenPath: {},
1185
- forkIssuers: new ComplexSet2(PublicKey6.hash),
1186
- forkChangedSubjects: new ComplexSet2(PublicKey6.hash),
1187
- state: new ComplexMap4(PublicKey6.hash),
1188
- credentials: new ComplexSet2(PublicKey6.hash)
1189
- };
1190
- }
1191
- };
1192
- var toChosenPath = (path) => {
1193
- return Object.fromEntries(Object.entries(path.chosenPath).map(([k, vs]) => [
1194
- k,
1195
- vs.map((v) => v.id)
1196
- ]));
1197
- };
1198
-
1199
- // src/state-machine/member-state-machine.ts
1200
- var __dxlog_file5 = "/__w/dxos/dxos/packages/core/halo/credentials/src/state-machine/member-state-machine.ts";
1201
- var MemberStateMachine = class {
1202
- _spaceKey;
1203
- _ownerKey;
1204
- _memberProfiles = new ComplexMap5(PublicKey7.hash);
1205
- _hashgraph = new CredentialGraph(this);
1206
- onMemberRoleChanged = this._hashgraph.onSubjectStateChanged;
1207
- constructor(_spaceKey) {
1208
- this._spaceKey = _spaceKey;
1209
- }
1210
- get creator() {
1211
- return this._ownerKey && this._hashgraph.getSubjectState(this._ownerKey);
1212
- }
1213
- get members() {
1214
- return this._hashgraph.getState();
1215
- }
1216
- get membershipChainHeads() {
1217
- return this._hashgraph.getLeafIds();
1218
- }
1219
- getRole(member) {
1220
- return this._getRole(this._hashgraph.getGlobalStateScope(), member);
1221
- }
1222
- /**
1223
- * Processes the SpaceMember credential.
1224
- * Assumes the credential is already pre-verified and the issuer has been authorized to issue credentials of this type.
1225
- */
1226
- async process(credential) {
1227
- const assertion = getCredentialAssertion(credential);
1228
- switch (assertion["@type"]) {
1229
- case "dxos.halo.credentials.SpaceMember": {
1230
- invariant5(assertion.spaceKey.equals(this._spaceKey), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 43, S: this, A: ["assertion.spaceKey.equals(this._spaceKey)", ""] });
1231
- if (this._ownerKey == null && credential.issuer === this._spaceKey) {
1232
- this._ownerKey = credential.subject.id;
1233
- }
1234
- if (assertion.profile != null) {
1235
- this._memberProfiles.set(credential.subject.id, assertion.profile);
1236
- }
1237
- await this._hashgraph.addVertex(credential, assertion);
1238
- break;
1239
- }
1240
- case "dxos.halo.credentials.MemberProfile": {
1241
- const member = this._hashgraph.getSubjectState(credential.subject.id);
1242
- if (member) {
1243
- member.profile = assertion.profile;
1244
- } else {
1245
- log2.warn("Member not found", {
1246
- id: credential.subject.id
1247
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 59, S: this });
1248
- }
1249
- this._memberProfiles.set(credential.subject.id, assertion.profile);
1250
- break;
1251
- }
1252
- default:
1253
- throw new Error("Invalid assertion type");
1254
- }
1255
- }
1256
- createState(credential, assertion) {
1257
- const memberKey = credential.subject.id;
1258
- return {
1259
- key: memberKey,
1260
- role: assertion.role,
1261
- credential,
1262
- assertion,
1263
- profile: this._memberProfiles.get(memberKey)
1264
- };
1265
- }
1266
- isUpdateAllowed(scope, credential, assertion) {
1267
- if (assertion.role === SpaceMember2.Role.OWNER) {
1268
- return credential.issuer.equals(this._spaceKey);
1269
- }
1270
- const issuer = credential.issuer;
1271
- const isChangingOwnRole = issuer.equals(credential.subject.id);
1272
- if (isChangingOwnRole) {
1273
- return false;
1274
- }
1275
- if (issuer.equals(assertion.spaceKey)) {
1276
- return true;
1277
- }
1278
- const issuerRole = this._getRole(scope, issuer);
1279
- return issuerRole === SpaceMember2.Role.ADMIN || issuerRole === SpaceMember2.Role.OWNER;
1280
- }
1281
- getConflictingPaths(paths, update) {
1282
- if (update.assertion.role !== SpaceMember2.Role.REMOVED && update.assertion.role !== SpaceMember2.Role.EDITOR) {
1283
- return [];
1284
- }
1285
- const memberId = update.credential.subject.id;
1286
- return paths.filter((p) => p.forkIssuers.has(memberId));
1287
- }
1288
- tryPickWinningUpdate(scope1, update1, scope2, update2) {
1289
- const path1IssuerRole = this._getRole(scope1, update1.issuer);
1290
- const path2IssuerRole = this._getRole(scope2, update2.issuer);
1291
- if (path2IssuerRole === SpaceMember2.Role.OWNER !== (path1IssuerRole === SpaceMember2.Role.OWNER)) {
1292
- log2("owner decision used to break the tie", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 107, S: this });
1293
- return path1IssuerRole === SpaceMember2.Role.OWNER ? update1 : update2;
1294
- }
1295
- return null;
1296
- }
1297
- toLogString(assertion) {
1298
- const role = assertion?.role ?? SpaceMember2.Role.REMOVED;
1299
- return Object.entries(SpaceMember2.Role).find(([_, value]) => value === role)[0];
1300
- }
1301
- hasStateChanged(s1, s2) {
1302
- return s1?.role !== s2?.role;
1303
- }
1304
- _getRole(scope, memberId) {
1305
- if (this._ownerKey?.equals(memberId)) {
1306
- return SpaceMember2.Role.OWNER;
1307
- }
1308
- const realRole = scope.state.get(memberId)?.assertion?.role ?? SpaceMember2.Role.REMOVED;
1309
- if (scope.stateOverrides != null) {
1310
- const override = scope.stateOverrides.get(memberId);
1311
- if (override != null) {
1312
- log2("member role overridden in path", () => ({
1313
- headId: scope.head?.id,
1314
- roleOverride: this.toLogString(override.assertion),
1315
- realRole: this.toLogString(scope.state.get(memberId)?.assertion)
1316
- }), { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 127, S: this });
1317
- return override.assertion.role;
1318
- }
1319
- }
1320
- return realRole;
1321
- }
1322
- };
1323
-
1324
- // src/state-machine/space-state-machine.ts
1325
- var __dxlog_file6 = "/__w/dxos/dxos/packages/core/halo/credentials/src/state-machine/space-state-machine.ts";
1326
- function _ts_decorate(decorators, target, key, desc) {
1327
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1328
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1329
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1330
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1331
- }
1332
- var SpaceStateMachine = class {
1333
- _spaceKey;
1334
- _members;
1335
- _feeds;
1336
- _invitations = new InvitationStateMachine();
1337
- _credentials = [];
1338
- _credentialsById = new ComplexMap6(PublicKey8.hash);
1339
- _processedCredentials = new ComplexSet3(PublicKey8.hash);
1340
- _genesisCredential;
1341
- _tags = [];
1342
- _membershipPolicy = MembershipPolicy2.INVITE;
1343
- _credentialProcessors = [];
1344
- onCredentialProcessed = new Callback4();
1345
- onMemberRoleChanged;
1346
- onFeedAdmitted;
1347
- onDelegatedInvitation = this._invitations.onDelegatedInvitation;
1348
- onDelegatedInvitationRemoved = this._invitations.onDelegatedInvitationRemoved;
1349
- constructor(_spaceKey) {
1350
- this._spaceKey = _spaceKey;
1351
- this._members = new MemberStateMachine(this._spaceKey);
1352
- this._feeds = new FeedStateMachine(this._spaceKey);
1353
- this.onMemberRoleChanged = this._members.onMemberRoleChanged;
1354
- this.onFeedAdmitted = this._feeds.onFeedAdmitted;
1355
- }
1356
- get creator() {
1357
- return this._members.creator;
1358
- }
1359
- get members() {
1360
- return this._members.members;
1361
- }
1362
- get membershipChainHeads() {
1363
- return this._members.membershipChainHeads;
1364
- }
1365
- get feeds() {
1366
- return this._feeds.feeds;
1367
- }
1368
- get credentials() {
1369
- return this._credentials.map((entry) => entry.credential);
1370
- }
1371
- get credentialEntries() {
1372
- return this._credentials;
1373
- }
1374
- get genesisCredential() {
1375
- return this._genesisCredential;
1376
- }
1377
- get tags() {
1378
- return this._tags;
1379
- }
1380
- get membershipPolicy() {
1381
- return this._membershipPolicy;
1382
- }
1383
- get invitations() {
1384
- return this._invitations.invitations;
1385
- }
1386
- async addCredentialProcessor(processor) {
1387
- if (this._credentialProcessors.find((p) => p.processor === processor)) {
1388
- throw new Error("Credential processor already added.");
1389
- }
1390
- const consumer = new CredentialConsumer(processor, async () => {
1391
- for (const credential of this.credentials) {
1392
- await consumer._process(credential);
1393
- }
1394
- consumer._isReadyForLiveCredentials = true;
1395
- }, async () => {
1396
- this._credentialProcessors = this._credentialProcessors.filter((p) => p !== consumer);
1397
- });
1398
- this._credentialProcessors.push(consumer);
1399
- await consumer.open();
1400
- }
1401
- async removeCredentialProcessor(processor) {
1402
- const consumer = this._credentialProcessors.find((p) => p.processor === processor);
1403
- await consumer?.close();
1404
- }
1405
- getCredentialsOfType(type) {
1406
- return this.credentials.filter((credential) => getCredentialAssertion(credential)["@type"] === type);
1407
- }
1408
- /**
1409
- * @param credential Message to process.
1410
- * @param fromFeed Key of the feed where this credential is recorded.
1411
- */
1412
- async process(credential, { sourceFeed, skipVerification }) {
1413
- if (credential.id) {
1414
- if (this._processedCredentials.has(credential.id)) {
1415
- return true;
1416
- }
1417
- this._processedCredentials.add(credential.id);
1418
- }
1419
- if (!skipVerification) {
1420
- const result = await verifyCredential(credential);
1421
- if (result.kind !== "pass") {
1422
- log3.warn(`Invalid credential: ${result.errors.join(", ")}`, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 116, S: this });
1423
- return false;
1424
- }
1425
- }
1426
- const assertion = getCredentialAssertion(credential);
1427
- switch (assertion["@type"]) {
1428
- case "dxos.halo.credentials.SpaceGenesis": {
1429
- if (this._genesisCredential) {
1430
- log3.warn("Space already has a genesis credential.", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 125, S: this });
1431
- return false;
1432
- }
1433
- if (!credential.issuer.equals(this._spaceKey)) {
1434
- log3.warn("Space genesis credential must be issued by space.", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 129, S: this });
1435
- return false;
1436
- }
1437
- if (!credential.subject.id.equals(this._spaceKey)) {
1438
- log3.warn("Space genesis credential must be issued to space.", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 133, S: this });
1439
- return false;
1440
- }
1441
- this._genesisCredential = credential;
1442
- this._tags = assertion.tags ?? [];
1443
- this._membershipPolicy = assertion.membershipPolicy ?? MembershipPolicy2.INVITE;
1444
- break;
1445
- }
1446
- case "dxos.halo.credentials.SpaceMember": {
1447
- if (!assertion.spaceKey.equals(this._spaceKey)) {
1448
- break;
1449
- }
1450
- if (!this._genesisCredential) {
1451
- log3.warn("Space must have a genesis credential before adding members.", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 147, S: this });
1452
- return false;
1453
- }
1454
- if (!this._canInviteNewMembers(credential.issuer)) {
1455
- log3.warn(`Space member is not authorized to invite new members: ${credential.issuer}`, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 151, S: this });
1456
- return false;
1457
- }
1458
- await this._members.process(credential);
1459
- await this._invitations.process(credential);
1460
- break;
1461
- }
1462
- case "dxos.halo.credentials.MemberProfile": {
1463
- if (!this._genesisCredential) {
1464
- log3.warn("Space must have a genesis credential before adding members.", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 161, S: this });
1465
- return false;
1466
- }
1467
- await this._members.process(credential);
1468
- break;
1469
- }
1470
- case "dxos.halo.credentials.AdmittedFeed": {
1471
- if (!this._genesisCredential) {
1472
- log3.warn("Space must have a genesis credential before admitting feeds.", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 170, S: this });
1473
- return false;
1474
- }
1475
- await this._feeds.process(credential, sourceFeed);
1476
- break;
1477
- }
1478
- case "dxos.halo.invitations.CancelDelegatedInvitation":
1479
- case "dxos.halo.invitations.DelegateSpaceInvitation": {
1480
- if (!this._canInviteNewMembers(credential.issuer)) {
1481
- log3.warn(`Invalid invitation, space member is not authorized to invite new members: ${credential.issuer}`, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 181, S: this });
1482
- return false;
1483
- }
1484
- await this._invitations.process(credential);
1485
- break;
1486
- }
1487
- }
1488
- const newEntry = {
1489
- credential,
1490
- sourceFeed,
1491
- revoked: false
1492
- };
1493
- this._credentials.push(newEntry);
1494
- if (credential.id) {
1495
- this._credentialsById.set(credential.id, newEntry);
1496
- }
1497
- for (const processor of this._credentialProcessors) {
1498
- if (processor._isReadyForLiveCredentials) {
1499
- await processor._process(credential);
1500
- }
1501
- }
1502
- await this.onCredentialProcessed.callIfSet(credential);
1503
- return true;
1504
- }
1505
- getMemberRole(memberKey) {
1506
- return this._members.getRole(memberKey);
1507
- }
1508
- hasMembershipManagementPermission(memberKey) {
1509
- return this._canInviteNewMembers(memberKey);
1510
- }
1511
- _canInviteNewMembers(key) {
1512
- if (this._membershipPolicy === MembershipPolicy2.LOCKED) {
1513
- return key.equals(this._spaceKey) && this._members.members.size === 0;
1514
- }
1515
- return key.equals(this._spaceKey) || this._members.getRole(key) === SpaceMember3.Role.ADMIN || this._members.getRole(key) === SpaceMember3.Role.OWNER;
1516
- }
1517
- };
1518
- _ts_decorate([
1519
- synchronized
1520
- ], SpaceStateMachine.prototype, "process", null);
1521
- var CredentialConsumer = class {
1522
- processor;
1523
- _onOpen;
1524
- _onClose;
1525
- _ctx = new Context(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 229 });
1526
- /**
1527
- * @internal
1528
- * Processor is ready to process live credentials.
1529
- * NOTE: Setting this flag before all existing credentials are processed will cause them to be processed out of order.
1530
- * Set externally.
1531
- */
1532
- _isReadyForLiveCredentials = false;
1533
- constructor(processor, _onOpen, _onClose) {
1534
- this.processor = processor;
1535
- this._onOpen = _onOpen;
1536
- this._onClose = _onClose;
1537
- }
1538
- /**
1539
- * @internal
1540
- */
1541
- async _process(credential) {
1542
- await runInContextAsync(this._ctx, async () => {
1543
- await this.processor.processCredential(credential);
1544
- });
1545
- }
1546
- async open() {
1547
- if (this._ctx.disposed) {
1548
- throw new Error("CredentialProcessor is disposed");
1549
- }
1550
- await this._onOpen();
1551
- }
1552
- async close() {
1553
- await this._ctx.dispose();
1554
- await this._onClose();
1555
- }
1556
- };
1557
-
1558
- // src/processor/device-state-machine.ts
1559
- import { Trigger } from "@dxos/async";
1560
- import { invariant as invariant6 } from "@dxos/invariant";
1561
- import { PublicKey as PublicKey9 } from "@dxos/keys";
1562
- import { log as log4 } from "@dxos/log";
1563
- import { ComplexMap as ComplexMap7 } from "@dxos/util";
1564
- var __dxlog_file7 = "/__w/dxos/dxos/packages/core/halo/credentials/src/processor/device-state-machine.ts";
1565
- var DeviceStateMachine = class {
1566
- _params;
1567
- // TODO(burdon): Return values via getter.
1568
- authorizedDeviceKeys = new ComplexMap7(PublicKey9.hash);
1569
- deviceChainReady = new Trigger();
1570
- deviceCredentialChain;
1571
- constructor(_params) {
1572
- this._params = _params;
1573
- }
1574
- async processCredential(credential) {
1575
- log4("processing credential...", {
1576
- identityKey: this._params.identityKey,
1577
- deviceKey: this._params.deviceKey,
1578
- credential
1579
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 22, S: this });
1580
- if (isValidAuthorizedDeviceCredential(credential, this._params.identityKey, this._params.deviceKey)) {
1581
- this.deviceCredentialChain = {
1582
- credential
1583
- };
1584
- this.deviceChainReady.wake();
1585
- }
1586
- const assertion = getCredentialAssertion(credential);
1587
- switch (assertion["@type"]) {
1588
- case "dxos.halo.credentials.AuthorizedDevice": {
1589
- this.authorizedDeviceKeys.set(assertion.deviceKey, this.authorizedDeviceKeys.get(assertion.deviceKey) ?? {});
1590
- log4("added device", {
1591
- localDeviceKey: this._params.deviceKey,
1592
- deviceKey: assertion.deviceKey,
1593
- size: this.authorizedDeviceKeys.size
1594
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 41, S: this });
1595
- this._params.onUpdate?.();
1596
- break;
1597
- }
1598
- case "dxos.halo.credentials.DeviceProfile": {
1599
- invariant6(this.authorizedDeviceKeys.has(credential.subject.id), "Device not found.", { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 51, S: this, A: ["this.authorizedDeviceKeys.has(credential.subject.id)", "'Device not found.'"] });
1600
- if (assertion && credential.subject.id.equals(this._params.deviceKey)) {
1601
- log4.trace("dxos.halo.device", {
1602
- deviceKey: credential.subject.id,
1603
- profile: assertion.profile
1604
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 53, S: this });
1605
- }
1606
- this.authorizedDeviceKeys.set(credential.subject.id, assertion.profile);
1607
- this._params.onUpdate?.();
1608
- break;
1609
- }
1610
- }
1611
- }
1612
- };
1613
-
1614
- // src/processor/profile-state-machine.ts
1615
- import { log as log5 } from "@dxos/log";
1616
- var __dxlog_file8 = "/__w/dxos/dxos/packages/core/halo/credentials/src/processor/profile-state-machine.ts";
1617
- var ProfileStateMachine = class {
1618
- _params;
1619
- // TODO(burdon): Return values via getter.
1620
- profile;
1621
- constructor(_params) {
1622
- this._params = _params;
1623
- }
1624
- async processCredential(credential) {
1625
- const assertion = getCredentialAssertion(credential);
1626
- switch (assertion["@type"]) {
1627
- case "dxos.halo.credentials.IdentityProfile": {
1628
- if (!credential.issuer.equals(this._params.identityKey) || !credential.subject.id.equals(this._params.identityKey)) {
1629
- log5.warn("Invalid profile credential", {
1630
- expectedIdentity: this._params.identityKey,
1631
- credential
1632
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 21, S: this });
1633
- return;
1634
- }
1635
- this.profile = assertion.profile;
1636
- log5("updated profile", {
1637
- identityKey: this._params.identityKey,
1638
- profile: this.profile
1639
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 29, S: this });
1640
- this._params.onUpdate?.();
1641
- break;
1642
- }
1643
- }
1644
- }
1645
- };
1646
- export {
1647
- CredentialGenerator,
1648
- DeviceStateMachine,
1649
- FeedStateMachine,
1650
- InvitationStateMachine,
1651
- MemberStateMachine,
1652
- ProfileStateMachine,
1653
- SIGNATURE_TYPE_ED25519,
1654
- SpaceStateMachine,
1655
- canonicalStringify,
1656
- checkCredentialType,
1657
- createAdmissionCredentials,
1658
- createCancelDelegatedSpaceInvitationCredential,
1659
- createCredential,
1660
- createCredentialMessage,
1661
- createCredentialSignerWithChain,
1662
- createCredentialSignerWithKey,
1663
- createDelegatedSpaceInvitationCredential,
1664
- createDeviceAuthorization,
1665
- createDidFromIdentityKey,
1666
- credentialTypeFilter,
1667
- defaultSecretProvider,
1668
- defaultSecretValidator,
1669
- generatePasscode,
1670
- generateSeedPhrase,
1671
- getCredentialAssertion,
1672
- getCredentialProofPayload,
1673
- getPresentationProofPayload,
1674
- isValidAuthorizedDeviceCredential,
1675
- keyPairFromSeedPhrase,
1676
- signPresentation,
1677
- verifyChain,
1678
- verifyCredential,
1679
- verifyCredentialSignature,
1680
- verifyPresentation,
1681
- verifyPresentationChain,
1682
- verifyPresentationSignature
1683
- };
1684
- //# sourceMappingURL=index.mjs.map