@enbox/agent 0.5.15 → 0.6.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.
- package/dist/browser.mjs +11 -11
- package/dist/browser.mjs.map +4 -4
- package/dist/esm/dwn-api.js +433 -33
- package/dist/esm/dwn-api.js.map +1 -1
- package/dist/esm/dwn-encryption.js +131 -12
- package/dist/esm/dwn-encryption.js.map +1 -1
- package/dist/esm/dwn-key-delivery.js +64 -47
- package/dist/esm/dwn-key-delivery.js.map +1 -1
- package/dist/esm/enbox-connect-protocol.js +400 -3
- package/dist/esm/enbox-connect-protocol.js.map +1 -1
- package/dist/esm/permissions-api.js +11 -1
- package/dist/esm/permissions-api.js.map +1 -1
- package/dist/esm/sync-closure-resolver.js +8 -1
- package/dist/esm/sync-closure-resolver.js.map +1 -1
- package/dist/esm/sync-engine-level.js +407 -6
- package/dist/esm/sync-engine-level.js.map +1 -1
- package/dist/esm/sync-messages.js +10 -3
- package/dist/esm/sync-messages.js.map +1 -1
- package/dist/types/dwn-api.d.ts +159 -0
- package/dist/types/dwn-api.d.ts.map +1 -1
- package/dist/types/dwn-encryption.d.ts +39 -2
- package/dist/types/dwn-encryption.d.ts.map +1 -1
- package/dist/types/dwn-key-delivery.d.ts +1 -9
- package/dist/types/dwn-key-delivery.d.ts.map +1 -1
- package/dist/types/enbox-connect-protocol.d.ts +166 -1
- package/dist/types/enbox-connect-protocol.d.ts.map +1 -1
- package/dist/types/permissions-api.d.ts.map +1 -1
- package/dist/types/sync-closure-resolver.d.ts.map +1 -1
- package/dist/types/sync-engine-level.d.ts +45 -1
- package/dist/types/sync-engine-level.d.ts.map +1 -1
- package/dist/types/sync-messages.d.ts +2 -2
- package/dist/types/sync-messages.d.ts.map +1 -1
- package/dist/types/types/permissions.d.ts +9 -0
- package/dist/types/types/permissions.d.ts.map +1 -1
- package/dist/types/types/sync.d.ts +70 -2
- package/dist/types/types/sync.d.ts.map +1 -1
- package/package.json +5 -4
- package/src/dwn-api.ts +494 -38
- package/src/dwn-encryption.ts +160 -11
- package/src/dwn-key-delivery.ts +73 -61
- package/src/enbox-connect-protocol.ts +575 -6
- package/src/permissions-api.ts +13 -1
- package/src/sync-closure-resolver.ts +7 -1
- package/src/sync-engine-level.ts +368 -4
- package/src/sync-messages.ts +14 -5
- package/src/types/permissions.ts +9 -0
- package/src/types/sync.ts +86 -2
package/dist/esm/dwn-api.js
CHANGED
|
@@ -7,10 +7,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
7
7
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
|
-
import { TtlCache } from '@enbox/common';
|
|
11
10
|
import { Cid, ContentEncryptionAlgorithm, DataStoreLevel, DataStream, Dwn, DwnMethodName, EventEmitterEventLog, Jws, KeyDerivationScheme, Message, MessageStoreLevel, Protocols, Records, ResumableTaskStoreLevel, StateIndexLevel, } from '@enbox/dwn-sdk-js';
|
|
11
|
+
import { Convert, TtlCache } from '@enbox/common';
|
|
12
12
|
import { CryptoUtils, X25519 } from '@enbox/crypto';
|
|
13
13
|
import { DidDht, DidJwk, DidResolverCacheLevel, UniversalResolver } from '@enbox/dids';
|
|
14
|
+
import { AgentPermissionsApi } from './permissions-api.js';
|
|
14
15
|
import { DwnDiscoveryFile } from './dwn-discovery-file.js';
|
|
15
16
|
import { KeyDeliveryProtocolDefinition } from './store-data-protocols.js';
|
|
16
17
|
import { LocalDwnDiscovery } from './local-dwn.js';
|
|
@@ -53,6 +54,41 @@ export class AgentDwnApi {
|
|
|
53
54
|
this._contextDerivedKeyCache = new TtlCache({
|
|
54
55
|
ttl: 30 * 60 * 1000
|
|
55
56
|
});
|
|
57
|
+
/**
|
|
58
|
+
* Delegate decryption key cache — stores scope-aware decryption keys
|
|
59
|
+
* delivered to delegates during the connect flow. These keys enable
|
|
60
|
+
* delegates to decrypt encrypted records without possessing the owner's
|
|
61
|
+
* root X25519 private key.
|
|
62
|
+
*
|
|
63
|
+
* Keyed by `ddk~${delegateDid}`. Each entry is an array covering all
|
|
64
|
+
* granted read scopes for that delegate session.
|
|
65
|
+
* TTL 24 hours (keys are re-populated on session restore).
|
|
66
|
+
*/
|
|
67
|
+
this._delegateDecryptionKeyCache = new TtlCache({
|
|
68
|
+
ttl: 24 * 60 * 60 * 1000
|
|
69
|
+
});
|
|
70
|
+
/**
|
|
71
|
+
* Delegate context key cache — stores ProtocolContext decryption keys for
|
|
72
|
+
* multi-party encrypted protocols. Each key is scoped to one rootContextId.
|
|
73
|
+
* Keyed by `dctx~${delegateDid}~${protocol}~${rootContextId}`.
|
|
74
|
+
* TTL 24 hours (re-populated on session restore).
|
|
75
|
+
*/
|
|
76
|
+
this._delegateContextKeyCache = new TtlCache({
|
|
77
|
+
ttl: 24 * 60 * 60 * 1000
|
|
78
|
+
});
|
|
79
|
+
/** Tracks which context key cache entries belong to which delegate DID. */
|
|
80
|
+
this._delegateContextKeyCacheIndex = new Map();
|
|
81
|
+
/**
|
|
82
|
+
* Explicit registry of which multi-party protocols each delegate has
|
|
83
|
+
* protocol-wide read-like access to. Populated at connect time (even
|
|
84
|
+
* when zero contexts exist) and used by postWriteKeyDelivery() to
|
|
85
|
+
* decide whether to deliver new context keys.
|
|
86
|
+
*
|
|
87
|
+
* Keyed by delegateDid. Each entry is a Set of protocol URIs.
|
|
88
|
+
* Unlike the context key cache, this registry is NOT time-limited —
|
|
89
|
+
* it persists for the lifetime of the session.
|
|
90
|
+
*/
|
|
91
|
+
this._delegateMultiPartyProtocols = new Map();
|
|
56
92
|
/**
|
|
57
93
|
* Cache of locally-managed DIDs (agent DID + identities). Used to decide
|
|
58
94
|
* whether a target DID should be routed through the local DWN server.
|
|
@@ -174,6 +210,16 @@ export class AgentDwnApi {
|
|
|
174
210
|
return [...uniqueEndpoints];
|
|
175
211
|
});
|
|
176
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* Returns only the DWN service endpoints from the DID document (no local
|
|
215
|
+
* discovery endpoint). Use this when you need to confirm that a message
|
|
216
|
+
* reached the owner's actual remote DWN, not just the delegate's local server.
|
|
217
|
+
*/
|
|
218
|
+
getRemoteDwnEndpointUrls(targetDid) {
|
|
219
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
220
|
+
return getDwnServiceEndpointUrls(targetDid, this.agent.did);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
177
223
|
/** Lazily retrieves the local DWN server endpoint via discovery. */
|
|
178
224
|
getLocalDwnEndpoint() {
|
|
179
225
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -490,11 +536,17 @@ export class AgentDwnApi {
|
|
|
490
536
|
tenantDid: request.target,
|
|
491
537
|
authorDid: isExternallyAuthored ? authorDid : undefined,
|
|
492
538
|
});
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
539
|
+
// Compute rootContextId for both participant and delegate delivery.
|
|
540
|
+
const rootContextId = ((_a = recordsWriteMessage.contextId) === null || _a === void 0 ? void 0 : _a.split('/')[0])
|
|
541
|
+
|| recordsWriteMessage.contextId
|
|
542
|
+
|| recordsWriteMessage.recordId;
|
|
543
|
+
// Determine if delegate delivery is needed: new multi-party root
|
|
544
|
+
// record created by the owner with active delegate sessions.
|
|
545
|
+
const needsDelegateDelivery = isMultiParty && isRootRecord
|
|
546
|
+
&& !isExternallyAuthored
|
|
547
|
+
&& this.hasEligibleDelegatesForProtocol(writeParams.protocol);
|
|
548
|
+
if (newParticipants.size > 0 || needsDelegateDelivery) {
|
|
549
|
+
// Derive the context key once (shared for participant + delegate delivery).
|
|
498
550
|
const { keyId, keyUri } = yield getEncryptionKeyInfoFn(this.agent, request.target);
|
|
499
551
|
const contextDerivationPath = [
|
|
500
552
|
KeyDerivationScheme.ProtocolContext,
|
|
@@ -511,32 +563,66 @@ export class AgentDwnApi {
|
|
|
511
563
|
derivationPath: contextDerivationPath,
|
|
512
564
|
derivedPrivateKey: contextDerivedPrivateJwk,
|
|
513
565
|
};
|
|
514
|
-
//
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
`
|
|
566
|
+
// --- Participant key delivery (existing) ---
|
|
567
|
+
if (newParticipants.size > 0) {
|
|
568
|
+
// Extract the author's key delivery public key from the record
|
|
569
|
+
// so we can encrypt the contextKey directly to the external author.
|
|
570
|
+
const authorKeyDeliveryPubKey = (_b = recordsWriteMessage.authorization) === null || _b === void 0 ? void 0 : _b.authorKeyDeliveryPublicKey;
|
|
571
|
+
for (const participantDid of newParticipants) {
|
|
572
|
+
try {
|
|
573
|
+
// Use the author's key delivery public key when delivering
|
|
574
|
+
// to the external author; for other participants (e.g.
|
|
575
|
+
// recipient, role holders) fall back to owner-key encryption.
|
|
576
|
+
const recipientKey = (participantDid === authorDid && authorKeyDeliveryPubKey)
|
|
577
|
+
? authorKeyDeliveryPubKey
|
|
578
|
+
: undefined;
|
|
579
|
+
yield this.writeContextKeyRecord({
|
|
580
|
+
tenantDid: request.target,
|
|
581
|
+
recipientDid: participantDid,
|
|
582
|
+
contextKeyData: contextKeyPayload,
|
|
583
|
+
sourceProtocol: writeParams.protocol,
|
|
584
|
+
sourceContextId: rootContextId,
|
|
585
|
+
recipientKeyDeliveryPublicKey: recipientKey,
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
catch (keyDeliveryError) {
|
|
589
|
+
console.warn(`AgentDwnApi: Key delivery to '${participantDid}' for context ` +
|
|
590
|
+
`'${rootContextId}' failed: ${keyDeliveryError.message}. ` +
|
|
591
|
+
`The participant may not be able to decrypt records in this context.`);
|
|
592
|
+
}
|
|
538
593
|
}
|
|
539
594
|
}
|
|
595
|
+
// --- Post-connect delegate context key delivery (#824) ---
|
|
596
|
+
// Same-process: direct cache injection (fast, no network).
|
|
597
|
+
if (needsDelegateDelivery) {
|
|
598
|
+
this.deliverContextKeyToDelegates(writeParams.protocol, rootContextId, contextKeyPayload);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
// --- Cross-device delegate context key delivery (#826) ---
|
|
602
|
+
// Query grants to find ALL eligible delegates (including those on
|
|
603
|
+
// other agents) and write contextKey records to the DWN.
|
|
604
|
+
// This is separate from same-process delivery: it discovers delegates
|
|
605
|
+
// from the owner's DWN grants, not just in-memory caches. It must
|
|
606
|
+
// run even when no same-process delegates or participants exist.
|
|
607
|
+
if (isMultiParty && isRootRecord && !isExternallyAuthored) {
|
|
608
|
+
// Derive the context key if not already done above.
|
|
609
|
+
const { keyId: xdKeyId, keyUri: xdKeyUri } = yield getEncryptionKeyInfoFn(this.agent, request.target);
|
|
610
|
+
const xdContextDerivationPath = [
|
|
611
|
+
KeyDerivationScheme.ProtocolContext,
|
|
612
|
+
rootContextId,
|
|
613
|
+
];
|
|
614
|
+
const xdContextDerivedPrivateKeyBytes = yield this.agent.keyManager.derivePrivateKeyBytes({
|
|
615
|
+
keyUri: xdKeyUri,
|
|
616
|
+
derivationPath: xdContextDerivationPath,
|
|
617
|
+
});
|
|
618
|
+
const xdContextDerivedPrivateJwk = yield X25519.bytesToPrivateKey({ privateKeyBytes: xdContextDerivedPrivateKeyBytes });
|
|
619
|
+
const xdContextKeyPayload = {
|
|
620
|
+
rootKeyId: xdKeyId,
|
|
621
|
+
derivationScheme: KeyDerivationScheme.ProtocolContext,
|
|
622
|
+
derivationPath: xdContextDerivationPath,
|
|
623
|
+
derivedPrivateKey: xdContextDerivedPrivateJwk,
|
|
624
|
+
};
|
|
625
|
+
yield this.deliverContextKeyToDelegatesViaDwn(request.target, writeParams.protocol, rootContextId, xdContextKeyPayload);
|
|
540
626
|
}
|
|
541
627
|
}
|
|
542
628
|
catch (detectionError) {
|
|
@@ -596,6 +682,7 @@ export class AgentDwnApi {
|
|
|
596
682
|
}
|
|
597
683
|
constructDwnMessage(_a) {
|
|
598
684
|
return __awaiter(this, arguments, void 0, function* ({ request }) {
|
|
685
|
+
var _b, _c;
|
|
599
686
|
// if the request has a granteeDid, ensure the messageParams include the proper grant parameters
|
|
600
687
|
if (request.granteeDid && !this.hasGrantParams(request.messageParams)) {
|
|
601
688
|
throw new Error('AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request');
|
|
@@ -832,7 +919,29 @@ export class AgentDwnApi {
|
|
|
832
919
|
const signer = request.granteeDid ?
|
|
833
920
|
yield this.getSigner(request.granteeDid) :
|
|
834
921
|
yield this.getSigner(request.author);
|
|
835
|
-
|
|
922
|
+
// When signing as a delegate with a permissionGrantId, fetch the full
|
|
923
|
+
// grant message and pass it as `delegatedGrant` so the DWN SDK correctly
|
|
924
|
+
// sets `authorization.authorDelegatedGrant` and resolves the logical
|
|
925
|
+
// author to the grantor (owner) rather than the signer (delegate).
|
|
926
|
+
const params = Object.assign({}, request.messageParams);
|
|
927
|
+
if (request.granteeDid && params.permissionGrantId && !params.delegatedGrant
|
|
928
|
+
&& isDwnRequest(request, DwnInterface.RecordsWrite)) {
|
|
929
|
+
// Read as the grantee (delegate), not the owner. The delegate is
|
|
930
|
+
// the grant's recipient so the permissions protocol authorizes the
|
|
931
|
+
// read. The owner's signing key may not be available on the
|
|
932
|
+
// delegate agent in real wallet-connect flows.
|
|
933
|
+
const { reply: grantReply } = yield this.processRequest({
|
|
934
|
+
author: request.granteeDid,
|
|
935
|
+
target: request.author,
|
|
936
|
+
messageType: DwnInterface.RecordsRead,
|
|
937
|
+
messageParams: { filter: { recordId: params.permissionGrantId } },
|
|
938
|
+
});
|
|
939
|
+
if (grantReply.status.code === 200 && ((_b = grantReply.entry) === null || _b === void 0 ? void 0 : _b.recordsWrite) && ((_c = grantReply.entry) === null || _c === void 0 ? void 0 : _c.data)) {
|
|
940
|
+
const grantDataBytes = yield DataStream.toBytes(grantReply.entry.data);
|
|
941
|
+
params.delegatedGrant = Object.assign(Object.assign({}, grantReply.entry.recordsWrite), { encodedData: Convert.uint8Array(grantDataBytes).toBase64Url() });
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
dwnMessage = yield dwnMessageConstructor.create(Object.assign(Object.assign({}, params), { signer }));
|
|
836
945
|
// Deferred context encryption for root multi-party records (Component 9).
|
|
837
946
|
// Now that the message exists, we know recordId = contextId.
|
|
838
947
|
// Following the SDK two-pass pattern: encryptSymmetricEncryptionKey -> sign.
|
|
@@ -1033,7 +1142,7 @@ export class AgentDwnApi {
|
|
|
1033
1142
|
*/
|
|
1034
1143
|
maybeDecryptReply(request, reply) {
|
|
1035
1144
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1036
|
-
return maybeDecryptReplyFn(request, reply, this.agent, this._contextDerivedKeyCache, this.fetchContextKeyRecord.bind(this));
|
|
1145
|
+
return maybeDecryptReplyFn(request, reply, this.agent, this._contextDerivedKeyCache, this.fetchContextKeyRecord.bind(this), this._delegateDecryptionKeyCache, this._delegateContextKeyCache);
|
|
1037
1146
|
});
|
|
1038
1147
|
}
|
|
1039
1148
|
getDwnMessage(_a) {
|
|
@@ -1088,6 +1197,297 @@ export class AgentDwnApi {
|
|
|
1088
1197
|
return ensureKeyDeliveryProtocolFn(this.agent, tenantDid, this.processRequest.bind(this), this.getProtocolDefinition.bind(this), this._keyDeliveryProtocolInstalledCache, this._protocolDefinitionCache);
|
|
1089
1198
|
});
|
|
1090
1199
|
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Imports scope-aware decryption keys for delegate sessions.
|
|
1202
|
+
*
|
|
1203
|
+
* Called during the connect flow when the wallet delivers decryption keys
|
|
1204
|
+
* for encrypted protocols. Keys are derived only for read-like scopes
|
|
1205
|
+
* (Read/Query/Subscribe) — write-only delegates receive no keys.
|
|
1206
|
+
*
|
|
1207
|
+
* The keys are cached and used by `resolveKeyDecrypter()` to decrypt
|
|
1208
|
+
* records when the delegate does not possess the owner's root X25519
|
|
1209
|
+
* private key.
|
|
1210
|
+
*
|
|
1211
|
+
* @param delegateDid - The delegate DID for this session (unique per connect)
|
|
1212
|
+
* @param keys - Array of scope-aware decryption key entries
|
|
1213
|
+
*/
|
|
1214
|
+
/**
|
|
1215
|
+
* Sets a callback invoked whenever post-connect context keys are
|
|
1216
|
+
* delivered to a delegate. The auth layer uses this to persist
|
|
1217
|
+
* updated context keys so they survive restart.
|
|
1218
|
+
*
|
|
1219
|
+
* @param callback - Called with the delegateDid that received new keys.
|
|
1220
|
+
* Set to `undefined` to unregister.
|
|
1221
|
+
*/
|
|
1222
|
+
set onDelegateContextKeysChanged(callback) {
|
|
1223
|
+
this._onDelegateContextKeysChanged = callback;
|
|
1224
|
+
}
|
|
1225
|
+
importDelegateDecryptionKeys(delegateDid, keys) {
|
|
1226
|
+
const cacheKey = `ddk~${delegateDid}`;
|
|
1227
|
+
this._delegateDecryptionKeyCache.set(cacheKey, keys);
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Imports ProtocolContext decryption keys for multi-party encrypted protocols.
|
|
1231
|
+
* Each key is scoped to one rootContextId within one protocol.
|
|
1232
|
+
*
|
|
1233
|
+
* @param delegateDid - The delegate DID for this session
|
|
1234
|
+
* @param keys - Array of `{ protocol, contextId, derivedPrivateKey }` entries
|
|
1235
|
+
*/
|
|
1236
|
+
importDelegateContextKeys(delegateDid, keys, multiPartyProtocols) {
|
|
1237
|
+
// Clear any previously indexed entries for this delegate first,
|
|
1238
|
+
// so a re-import (e.g. session restore) doesn't leave stale entries.
|
|
1239
|
+
const previousKeys = this._delegateContextKeyCacheIndex.get(delegateDid);
|
|
1240
|
+
if (previousKeys) {
|
|
1241
|
+
for (const ck of previousKeys) {
|
|
1242
|
+
this._delegateContextKeyCache.delete(ck);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
const cacheKeys = [];
|
|
1246
|
+
for (const key of keys) {
|
|
1247
|
+
const ck = `dctx~${delegateDid}~${key.protocol}~${key.contextId}`;
|
|
1248
|
+
this._delegateContextKeyCache.set(ck, key.derivedPrivateKey);
|
|
1249
|
+
cacheKeys.push(ck);
|
|
1250
|
+
}
|
|
1251
|
+
this._delegateContextKeyCacheIndex.set(delegateDid, cacheKeys);
|
|
1252
|
+
// Populate the explicit multi-party protocol registry.
|
|
1253
|
+
// Sources: explicit parameter (always wins) + protocols from delivered keys.
|
|
1254
|
+
const protocols = new Set(multiPartyProtocols !== null && multiPartyProtocols !== void 0 ? multiPartyProtocols : []);
|
|
1255
|
+
for (const key of keys) {
|
|
1256
|
+
protocols.add(key.protocol);
|
|
1257
|
+
}
|
|
1258
|
+
if (protocols.size > 0) {
|
|
1259
|
+
this._delegateMultiPartyProtocols.set(delegateDid, protocols);
|
|
1260
|
+
}
|
|
1261
|
+
else {
|
|
1262
|
+
this._delegateMultiPartyProtocols.delete(delegateDid);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Clears all delegate decryption keys (both ProtocolPath and ProtocolContext)
|
|
1267
|
+
* from the in-memory cache. Called on disconnect to prevent stale keys from
|
|
1268
|
+
* persisting across sessions.
|
|
1269
|
+
*
|
|
1270
|
+
* @param delegateDid - If provided, clears keys for that delegate session only.
|
|
1271
|
+
* If omitted, clears all delegate keys.
|
|
1272
|
+
*/
|
|
1273
|
+
clearDelegateDecryptionKeys(delegateDid) {
|
|
1274
|
+
if (delegateDid) {
|
|
1275
|
+
this._delegateDecryptionKeyCache.delete(`ddk~${delegateDid}`);
|
|
1276
|
+
// Delete only context keys belonging to this delegate.
|
|
1277
|
+
const cacheKeys = this._delegateContextKeyCacheIndex.get(delegateDid);
|
|
1278
|
+
if (cacheKeys) {
|
|
1279
|
+
for (const ck of cacheKeys) {
|
|
1280
|
+
this._delegateContextKeyCache.delete(ck);
|
|
1281
|
+
}
|
|
1282
|
+
this._delegateContextKeyCacheIndex.delete(delegateDid);
|
|
1283
|
+
}
|
|
1284
|
+
this._delegateMultiPartyProtocols.delete(delegateDid);
|
|
1285
|
+
}
|
|
1286
|
+
else {
|
|
1287
|
+
this._delegateDecryptionKeyCache.clear();
|
|
1288
|
+
this._delegateContextKeyCache.clear();
|
|
1289
|
+
this._delegateContextKeyCacheIndex.clear();
|
|
1290
|
+
this._delegateMultiPartyProtocols.clear();
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* Exports the current set of delegate context keys for a specific delegate.
|
|
1295
|
+
* Returns an array of `{ protocol, contextId, derivedPrivateKey }` entries
|
|
1296
|
+
* suitable for serialization and persistence.
|
|
1297
|
+
*
|
|
1298
|
+
* Called by the auth layer to persist context keys (including keys delivered
|
|
1299
|
+
* post-connect) so they survive agent restarts.
|
|
1300
|
+
*
|
|
1301
|
+
* @param delegateDid - The delegate DID whose context keys to export
|
|
1302
|
+
* @returns Array of context key entries (may be empty)
|
|
1303
|
+
*/
|
|
1304
|
+
exportDelegateContextKeys(delegateDid) {
|
|
1305
|
+
const cacheKeys = this._delegateContextKeyCacheIndex.get(delegateDid);
|
|
1306
|
+
if (!cacheKeys) {
|
|
1307
|
+
return [];
|
|
1308
|
+
}
|
|
1309
|
+
const result = [];
|
|
1310
|
+
const prefix = `dctx~${delegateDid}~`;
|
|
1311
|
+
for (const ck of cacheKeys) {
|
|
1312
|
+
const key = this._delegateContextKeyCache.get(ck);
|
|
1313
|
+
if (!key || !ck.startsWith(prefix)) {
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
// Parse protocol and contextId from cache key:
|
|
1317
|
+
// format is `dctx~<delegateDid>~<protocol>~<contextId>`
|
|
1318
|
+
// contextId is always the last segment; protocol is everything between.
|
|
1319
|
+
const rest = ck.slice(prefix.length);
|
|
1320
|
+
const lastTilde = rest.lastIndexOf('~');
|
|
1321
|
+
if (lastTilde === -1) {
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
result.push({
|
|
1325
|
+
protocol: rest.slice(0, lastTilde),
|
|
1326
|
+
contextId: rest.slice(lastTilde + 1),
|
|
1327
|
+
derivedPrivateKey: key,
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
return result;
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Exports the registered multi-party protocol URIs for a delegate.
|
|
1334
|
+
* Used by the auth layer for persistence.
|
|
1335
|
+
*/
|
|
1336
|
+
exportDelegateMultiPartyProtocols(delegateDid) {
|
|
1337
|
+
const protocols = this._delegateMultiPartyProtocols.get(delegateDid);
|
|
1338
|
+
return protocols ? [...protocols] : [];
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Checks whether any active delegate session has context keys for the
|
|
1342
|
+
* given protocol. Used by `postWriteKeyDelivery()` to determine if
|
|
1343
|
+
* delegate delivery is needed.
|
|
1344
|
+
*/
|
|
1345
|
+
hasEligibleDelegatesForProtocol(protocol) {
|
|
1346
|
+
for (const [, protocols] of this._delegateMultiPartyProtocols) {
|
|
1347
|
+
if (protocols.has(protocol)) {
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
return false;
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Delivers a newly created multi-party context key to all active delegate
|
|
1355
|
+
* sessions that have existing context keys for the given protocol.
|
|
1356
|
+
*
|
|
1357
|
+
* This is same-process delivery: the context key is injected directly
|
|
1358
|
+
* into `_delegateContextKeyCache`. It works when the delegate cache is
|
|
1359
|
+
* on the same agent instance that creates the root record.
|
|
1360
|
+
*
|
|
1361
|
+
* Cross-device DWN-based delivery (where the owner's agent and the
|
|
1362
|
+
* delegate's agent are separate processes) is a documented follow-up.
|
|
1363
|
+
*
|
|
1364
|
+
* @param protocol - The protocol URI
|
|
1365
|
+
* @param rootContextId - The root context ID of the new context
|
|
1366
|
+
* @param contextKey - The derived context key (`DerivedPrivateJwk`)
|
|
1367
|
+
*/
|
|
1368
|
+
deliverContextKeyToDelegates(protocol, rootContextId, contextKey) {
|
|
1369
|
+
var _a, _b;
|
|
1370
|
+
for (const [delegateDid, protocols] of this._delegateMultiPartyProtocols) {
|
|
1371
|
+
if (!protocols.has(protocol)) {
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
// Skip if this delegate already has a key for this context (idempotent).
|
|
1375
|
+
const newCacheKey = `dctx~${delegateDid}~${protocol}~${rootContextId}`;
|
|
1376
|
+
if (this._delegateContextKeyCache.get(newCacheKey)) {
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
this._delegateContextKeyCache.set(newCacheKey, contextKey);
|
|
1380
|
+
const indexKeys = (_a = this._delegateContextKeyCacheIndex.get(delegateDid)) !== null && _a !== void 0 ? _a : [];
|
|
1381
|
+
indexKeys.push(newCacheKey);
|
|
1382
|
+
this._delegateContextKeyCacheIndex.set(delegateDid, indexKeys);
|
|
1383
|
+
// Notify the auth layer so it can persist the updated keys.
|
|
1384
|
+
(_b = this._onDelegateContextKeysChanged) === null || _b === void 0 ? void 0 : _b.call(this, delegateDid);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Delivers a newly created multi-party context key to eligible delegates
|
|
1389
|
+
* by writing `contextKey` records to the owner's DWN via the key-delivery
|
|
1390
|
+
* protocol. This enables cross-device delivery: the delegate can later
|
|
1391
|
+
* fetch the record from the owner's DWN and decrypt it.
|
|
1392
|
+
*
|
|
1393
|
+
* Eligible delegates are discovered by querying the owner's DWN for
|
|
1394
|
+
* active permission grants with read-like scopes on the given protocol.
|
|
1395
|
+
*
|
|
1396
|
+
* The contextKey record is encrypted using the delegate's pre-derived
|
|
1397
|
+
* key-delivery leaf public key, which is stored in the grant's tags
|
|
1398
|
+
* during `submitConnectResponse()`.
|
|
1399
|
+
*
|
|
1400
|
+
* @param tenantDid - The owner's DID
|
|
1401
|
+
* @param protocol - The protocol URI
|
|
1402
|
+
* @param rootContextId - The root context ID of the new context
|
|
1403
|
+
* @param contextKey - The derived context key (`DerivedPrivateJwk`)
|
|
1404
|
+
*/
|
|
1405
|
+
deliverContextKeyToDelegatesViaDwn(tenantDid, protocol, rootContextId, contextKey) {
|
|
1406
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1407
|
+
try {
|
|
1408
|
+
const permissionsApi = new AgentPermissionsApi({ agent: this.agent });
|
|
1409
|
+
const grants = yield permissionsApi.fetchGrants({
|
|
1410
|
+
author: tenantDid,
|
|
1411
|
+
target: tenantDid,
|
|
1412
|
+
grantor: tenantDid,
|
|
1413
|
+
protocol,
|
|
1414
|
+
checkRevoked: true,
|
|
1415
|
+
});
|
|
1416
|
+
const readMethods = new Set(['Read', 'Query', 'Subscribe']);
|
|
1417
|
+
const nowMs = Date.now();
|
|
1418
|
+
// Deduplicate: one contextKey per delegate, not per grant.
|
|
1419
|
+
// Multiple grants (Read, Query, Subscribe) for the same delegate
|
|
1420
|
+
// should produce exactly one contextKey record.
|
|
1421
|
+
// IMPORTANT: dedup happens AFTER tag validation so that an older
|
|
1422
|
+
// untagged grant doesn't shadow a valid tagged grant for the same delegate.
|
|
1423
|
+
const deliveredDelegates = new Set();
|
|
1424
|
+
for (const grant of grants) {
|
|
1425
|
+
// Only delegated grants are eligible. Non-delegated grants (direct
|
|
1426
|
+
// access without a delegate session) should not trigger cross-device
|
|
1427
|
+
// context key delivery.
|
|
1428
|
+
if (!grant.grant.delegated) {
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
// Filter expired grants. fetchGrants checks revocation but does
|
|
1432
|
+
// NOT filter by dateExpires. Use numeric comparison for safety.
|
|
1433
|
+
if (new Date(grant.grant.dateExpires).getTime() <= nowMs) {
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
const scope = grant.grant.scope;
|
|
1437
|
+
if (scope.interface !== 'Records' || !readMethods.has(scope.method)) {
|
|
1438
|
+
continue;
|
|
1439
|
+
}
|
|
1440
|
+
// Narrow scopes (protocolPath, contextId) are not supported for
|
|
1441
|
+
// multi-party delegate delivery — skip them silently.
|
|
1442
|
+
if (scope.protocolPath || scope.contextId) {
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1445
|
+
const delegateDid = grant.grant.grantee;
|
|
1446
|
+
// Read the pre-derived key-delivery leaf public key from the
|
|
1447
|
+
// grant data payload. This was computed during submitConnectResponse()
|
|
1448
|
+
// and stored alongside the grant's standard fields.
|
|
1449
|
+
const keyDelivery = grant.grant.delegateKeyDelivery;
|
|
1450
|
+
if (!(keyDelivery === null || keyDelivery === void 0 ? void 0 : keyDelivery.rootKeyId) || !(keyDelivery === null || keyDelivery === void 0 ? void 0 : keyDelivery.publicKeyJwk)) {
|
|
1451
|
+
// Grant was created before key-delivery was supported, or
|
|
1452
|
+
// is not a read-like grant. Skip — do NOT dedup yet.
|
|
1453
|
+
continue;
|
|
1454
|
+
}
|
|
1455
|
+
// Dedup check — skip if already delivered via an earlier grant.
|
|
1456
|
+
if (deliveredDelegates.has(delegateDid)) {
|
|
1457
|
+
continue;
|
|
1458
|
+
}
|
|
1459
|
+
const leafPublicKeyJwk = keyDelivery.publicKeyJwk;
|
|
1460
|
+
try {
|
|
1461
|
+
yield this.writeContextKeyRecord({
|
|
1462
|
+
tenantDid,
|
|
1463
|
+
recipientDid: delegateDid,
|
|
1464
|
+
contextKeyData: contextKey,
|
|
1465
|
+
sourceProtocol: protocol,
|
|
1466
|
+
sourceContextId: rootContextId,
|
|
1467
|
+
recipientKeyDeliveryPublicKey: {
|
|
1468
|
+
rootKeyId: keyDelivery.rootKeyId,
|
|
1469
|
+
publicKeyJwk: leafPublicKeyJwk,
|
|
1470
|
+
},
|
|
1471
|
+
});
|
|
1472
|
+
// Mark as delivered ONLY after the write succeeds. If the write
|
|
1473
|
+
// fails, a later valid grant for the same delegate can still try.
|
|
1474
|
+
deliveredDelegates.add(delegateDid);
|
|
1475
|
+
}
|
|
1476
|
+
catch (delegateError) {
|
|
1477
|
+
console.warn(`AgentDwnApi: Cross-device key delivery to delegate ` +
|
|
1478
|
+
`'${delegateDid}' for context '${rootContextId}' failed: ` +
|
|
1479
|
+
`${delegateError.message}. The delegate may need to reconnect.`);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
catch (discoveryError) {
|
|
1484
|
+
// Grant discovery failure is non-fatal — same-process delivery may
|
|
1485
|
+
// still have succeeded, and sync will eventually deliver the record.
|
|
1486
|
+
console.warn(`AgentDwnApi: Delegate grant discovery for protocol ` +
|
|
1487
|
+
`'${protocol}' failed: ${discoveryError.message}`);
|
|
1488
|
+
}
|
|
1489
|
+
});
|
|
1490
|
+
}
|
|
1091
1491
|
/**
|
|
1092
1492
|
* Writes a `contextKey` record to the owner's DWN, delivering an encrypted
|
|
1093
1493
|
* context key to a participant.
|
|
@@ -1118,7 +1518,7 @@ export class AgentDwnApi {
|
|
|
1118
1518
|
*/
|
|
1119
1519
|
fetchContextKeyRecord(params) {
|
|
1120
1520
|
return __awaiter(this, void 0, void 0, function* () {
|
|
1121
|
-
return fetchContextKeyRecordFn(this.agent, params, this.processRequest.bind(this)
|
|
1521
|
+
return fetchContextKeyRecordFn(this.agent, params, this.processRequest.bind(this));
|
|
1122
1522
|
});
|
|
1123
1523
|
}
|
|
1124
1524
|
}
|