@enbox/agent 0.5.16 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/browser.mjs +11 -11
  2. package/dist/browser.mjs.map +4 -4
  3. package/dist/esm/dwn-api.js +468 -36
  4. package/dist/esm/dwn-api.js.map +1 -1
  5. package/dist/esm/dwn-encryption.js +131 -12
  6. package/dist/esm/dwn-encryption.js.map +1 -1
  7. package/dist/esm/dwn-key-delivery.js +64 -47
  8. package/dist/esm/dwn-key-delivery.js.map +1 -1
  9. package/dist/esm/dwn-protocol-cache.js +8 -6
  10. package/dist/esm/dwn-protocol-cache.js.map +1 -1
  11. package/dist/esm/enbox-connect-protocol.js +400 -3
  12. package/dist/esm/enbox-connect-protocol.js.map +1 -1
  13. package/dist/esm/permissions-api.js +11 -1
  14. package/dist/esm/permissions-api.js.map +1 -1
  15. package/dist/esm/sync-engine-level.js +407 -6
  16. package/dist/esm/sync-engine-level.js.map +1 -1
  17. package/dist/esm/sync-messages.js +10 -3
  18. package/dist/esm/sync-messages.js.map +1 -1
  19. package/dist/types/dwn-api.d.ts +159 -0
  20. package/dist/types/dwn-api.d.ts.map +1 -1
  21. package/dist/types/dwn-encryption.d.ts +39 -2
  22. package/dist/types/dwn-encryption.d.ts.map +1 -1
  23. package/dist/types/dwn-key-delivery.d.ts +1 -9
  24. package/dist/types/dwn-key-delivery.d.ts.map +1 -1
  25. package/dist/types/dwn-protocol-cache.d.ts +1 -1
  26. package/dist/types/dwn-protocol-cache.d.ts.map +1 -1
  27. package/dist/types/enbox-connect-protocol.d.ts +166 -1
  28. package/dist/types/enbox-connect-protocol.d.ts.map +1 -1
  29. package/dist/types/permissions-api.d.ts.map +1 -1
  30. package/dist/types/sync-engine-level.d.ts +45 -1
  31. package/dist/types/sync-engine-level.d.ts.map +1 -1
  32. package/dist/types/sync-messages.d.ts +2 -2
  33. package/dist/types/sync-messages.d.ts.map +1 -1
  34. package/dist/types/types/permissions.d.ts +9 -0
  35. package/dist/types/types/permissions.d.ts.map +1 -1
  36. package/dist/types/types/sync.d.ts +70 -2
  37. package/dist/types/types/sync.d.ts.map +1 -1
  38. package/package.json +5 -4
  39. package/src/dwn-api.ts +530 -39
  40. package/src/dwn-encryption.ts +160 -11
  41. package/src/dwn-key-delivery.ts +73 -61
  42. package/src/dwn-protocol-cache.ts +9 -1
  43. package/src/enbox-connect-protocol.ts +575 -6
  44. package/src/permissions-api.ts +13 -1
  45. package/src/sync-engine-level.ts +368 -4
  46. package/src/sync-messages.ts +14 -5
  47. package/src/types/permissions.ts +9 -0
  48. package/src/types/sync.ts +86 -2
package/src/dwn-api.ts CHANGED
@@ -13,7 +13,6 @@ import type {
13
13
  import type { DwnSubscriptionHandler, ResubscribeFactory } from '@enbox/dwn-clients';
14
14
  import type { KeyIdentifier, PrivateKeyJwk, PublicKeyJwk } from '@enbox/crypto';
15
15
 
16
- import { TtlCache } from '@enbox/common';
17
16
  import {
18
17
  Cid,
19
18
  ContentEncryptionAlgorithm,
@@ -31,6 +30,7 @@ import {
31
30
  ResumableTaskStoreLevel,
32
31
  StateIndexLevel,
33
32
  } from '@enbox/dwn-sdk-js';
33
+ import { Convert, TtlCache } from '@enbox/common';
34
34
  import { CryptoUtils, X25519 } from '@enbox/crypto';
35
35
  import { DidDht, DidJwk, DidResolverCacheLevel, UniversalResolver } from '@enbox/dids';
36
36
 
@@ -49,6 +49,7 @@ import type {
49
49
  SendDwnRequest,
50
50
  } from './types/dwn.js';
51
51
 
52
+ import { AgentPermissionsApi } from './permissions-api.js';
52
53
  import { DwnDiscoveryFile } from './dwn-discovery-file.js';
53
54
  import { KeyDeliveryProtocolDefinition } from './store-data-protocols.js';
54
55
  import { LocalDwnDiscovery } from './local-dwn.js';
@@ -165,6 +166,55 @@ export class AgentDwnApi {
165
166
  ttl: 30 * 60 * 1000
166
167
  });
167
168
 
169
+ /**
170
+ * Delegate decryption key cache — stores scope-aware decryption keys
171
+ * delivered to delegates during the connect flow. These keys enable
172
+ * delegates to decrypt encrypted records without possessing the owner's
173
+ * root X25519 private key.
174
+ *
175
+ * Keyed by `ddk~${delegateDid}`. Each entry is an array covering all
176
+ * granted read scopes for that delegate session.
177
+ * TTL 24 hours (keys are re-populated on session restore).
178
+ */
179
+ private _delegateDecryptionKeyCache = new TtlCache<string, {
180
+ protocol: string;
181
+ scope: { kind: 'protocol' } | { kind: 'protocolPath'; protocolPath: string; match: 'exact' };
182
+ derivedPrivateKey: DerivedPrivateJwk;
183
+ }[]>({
184
+ ttl: 24 * 60 * 60 * 1000
185
+ });
186
+
187
+ /**
188
+ * Delegate context key cache — stores ProtocolContext decryption keys for
189
+ * multi-party encrypted protocols. Each key is scoped to one rootContextId.
190
+ * Keyed by `dctx~${delegateDid}~${protocol}~${rootContextId}`.
191
+ * TTL 24 hours (re-populated on session restore).
192
+ */
193
+ private _delegateContextKeyCache = new TtlCache<string, DerivedPrivateJwk>({
194
+ ttl: 24 * 60 * 60 * 1000
195
+ });
196
+
197
+ /** Tracks which context key cache entries belong to which delegate DID. */
198
+ private _delegateContextKeyCacheIndex = new Map<string, string[]>();
199
+
200
+ /**
201
+ * Explicit registry of which multi-party protocols each delegate has
202
+ * protocol-wide read-like access to. Populated at connect time (even
203
+ * when zero contexts exist) and used by postWriteKeyDelivery() to
204
+ * decide whether to deliver new context keys.
205
+ *
206
+ * Keyed by delegateDid. Each entry is a Set of protocol URIs.
207
+ * Unlike the context key cache, this registry is NOT time-limited —
208
+ * it persists for the lifetime of the session.
209
+ */
210
+ private _delegateMultiPartyProtocols = new Map<string, Set<string>>();
211
+
212
+ /**
213
+ * Optional callback invoked when post-connect context keys are delivered
214
+ * to a delegate. The auth layer sets this to persist updated keys.
215
+ */
216
+ private _onDelegateContextKeysChanged?: (delegateDid: string) => void;
217
+
168
218
  /**
169
219
  * Cache of locally-managed DIDs (agent DID + identities). Used to decide
170
220
  * whether a target DID should be routed through the local DWN server.
@@ -312,6 +362,15 @@ export class AgentDwnApi {
312
362
  return [...uniqueEndpoints];
313
363
  }
314
364
 
365
+ /**
366
+ * Returns only the DWN service endpoints from the DID document (no local
367
+ * discovery endpoint). Use this when you need to confirm that a message
368
+ * reached the owner's actual remote DWN, not just the delegate's local server.
369
+ */
370
+ public async getRemoteDwnEndpointUrls(targetDid: string): Promise<string[]> {
371
+ return getDwnServiceEndpointUrls(targetDid, this.agent.did);
372
+ }
373
+
315
374
  /** Lazily retrieves the local DWN server endpoint via discovery. */
316
375
  private async getLocalDwnEndpoint(): Promise<string | undefined> {
317
376
  // In remote mode, the endpoint is always known.
@@ -686,12 +745,19 @@ export class AgentDwnApi {
686
745
  authorDid : isExternallyAuthored ? authorDid : undefined,
687
746
  });
688
747
 
689
- if (newParticipants.size > 0) {
690
- // Derive the context key to deliver to participants
691
- const rootContextId = recordsWriteMessage.contextId?.split('/')[0]
692
- || recordsWriteMessage.contextId
693
- || recordsWriteMessage.recordId;
748
+ // Compute rootContextId for both participant and delegate delivery.
749
+ const rootContextId = recordsWriteMessage.contextId?.split('/')[0]
750
+ || recordsWriteMessage.contextId
751
+ || recordsWriteMessage.recordId;
694
752
 
753
+ // Determine if delegate delivery is needed: new multi-party root
754
+ // record created by the owner with active delegate sessions.
755
+ const needsDelegateDelivery = isMultiParty && isRootRecord
756
+ && !isExternallyAuthored
757
+ && this.hasEligibleDelegatesForProtocol(writeParams.protocol);
758
+
759
+ if (newParticipants.size > 0 || needsDelegateDelivery) {
760
+ // Derive the context key once (shared for participant + delegate delivery).
695
761
  const { keyId, keyUri } = await getEncryptionKeyInfoFn(this.agent, request.target);
696
762
  const contextDerivationPath = [
697
763
  KeyDerivationScheme.ProtocolContext,
@@ -711,36 +777,79 @@ export class AgentDwnApi {
711
777
  derivedPrivateKey : contextDerivedPrivateJwk as PrivateKeyJwk,
712
778
  };
713
779
 
714
- // Extract the author's key delivery public key from the record
715
- // so we can encrypt the contextKey directly to the external author.
716
- const authorKeyDeliveryPubKey =
717
- recordsWriteMessage.authorization?.authorKeyDeliveryPublicKey;
718
-
719
- for (const participantDid of newParticipants) {
720
- try {
721
- // Use the author's key delivery public key when delivering
722
- // to the external author; for other participants (e.g.
723
- // recipient, role holders) fall back to owner-key encryption.
724
- const recipientKey = (participantDid === authorDid && authorKeyDeliveryPubKey)
725
- ? authorKeyDeliveryPubKey
726
- : undefined;
727
-
728
- await this.writeContextKeyRecord({
729
- tenantDid : request.target,
730
- recipientDid : participantDid,
731
- contextKeyData : contextKeyPayload,
732
- sourceProtocol : writeParams.protocol,
733
- sourceContextId : rootContextId,
734
- recipientKeyDeliveryPublicKey : recipientKey,
735
- });
736
- } catch (keyDeliveryError: any) {
737
- console.warn(
738
- `AgentDwnApi: Key delivery to '${participantDid}' for context ` +
739
- `'${rootContextId}' failed: ${keyDeliveryError.message}. ` +
740
- `The participant may not be able to decrypt records in this context.`
741
- );
780
+ // --- Participant key delivery (existing) ---
781
+ if (newParticipants.size > 0) {
782
+ // Extract the author's key delivery public key from the record
783
+ // so we can encrypt the contextKey directly to the external author.
784
+ const authorKeyDeliveryPubKey =
785
+ recordsWriteMessage.authorization?.authorKeyDeliveryPublicKey;
786
+
787
+ for (const participantDid of newParticipants) {
788
+ try {
789
+ // Use the author's key delivery public key when delivering
790
+ // to the external author; for other participants (e.g.
791
+ // recipient, role holders) fall back to owner-key encryption.
792
+ const recipientKey = (participantDid === authorDid && authorKeyDeliveryPubKey)
793
+ ? authorKeyDeliveryPubKey
794
+ : undefined;
795
+
796
+ await this.writeContextKeyRecord({
797
+ tenantDid : request.target,
798
+ recipientDid : participantDid,
799
+ contextKeyData : contextKeyPayload,
800
+ sourceProtocol : writeParams.protocol,
801
+ sourceContextId : rootContextId,
802
+ recipientKeyDeliveryPublicKey : recipientKey,
803
+ });
804
+ } catch (keyDeliveryError: any) {
805
+ console.warn(
806
+ `AgentDwnApi: Key delivery to '${participantDid}' for context ` +
807
+ `'${rootContextId}' failed: ${keyDeliveryError.message}. ` +
808
+ `The participant may not be able to decrypt records in this context.`
809
+ );
810
+ }
742
811
  }
743
812
  }
813
+
814
+ // --- Post-connect delegate context key delivery (#824) ---
815
+ // Same-process: direct cache injection (fast, no network).
816
+ if (needsDelegateDelivery) {
817
+ this.deliverContextKeyToDelegates(
818
+ writeParams.protocol, rootContextId, contextKeyPayload,
819
+ );
820
+ }
821
+ }
822
+
823
+ // --- Cross-device delegate context key delivery (#826) ---
824
+ // Query grants to find ALL eligible delegates (including those on
825
+ // other agents) and write contextKey records to the DWN.
826
+ // This is separate from same-process delivery: it discovers delegates
827
+ // from the owner's DWN grants, not just in-memory caches. It must
828
+ // run even when no same-process delegates or participants exist.
829
+ if (isMultiParty && isRootRecord && !isExternallyAuthored) {
830
+ // Derive the context key if not already done above.
831
+ const { keyId: xdKeyId, keyUri: xdKeyUri } = await getEncryptionKeyInfoFn(this.agent, request.target);
832
+ const xdContextDerivationPath = [
833
+ KeyDerivationScheme.ProtocolContext,
834
+ rootContextId,
835
+ ];
836
+ const xdContextDerivedPrivateKeyBytes =
837
+ await this.agent.keyManager.derivePrivateKeyBytes({
838
+ keyUri : xdKeyUri,
839
+ derivationPath : xdContextDerivationPath,
840
+ });
841
+ const xdContextDerivedPrivateJwk =
842
+ await X25519.bytesToPrivateKey({ privateKeyBytes: xdContextDerivedPrivateKeyBytes });
843
+ const xdContextKeyPayload: DerivedPrivateJwk = {
844
+ rootKeyId : xdKeyId,
845
+ derivationScheme : KeyDerivationScheme.ProtocolContext,
846
+ derivationPath : xdContextDerivationPath,
847
+ derivedPrivateKey : xdContextDerivedPrivateJwk as PrivateKeyJwk,
848
+ };
849
+
850
+ await this.deliverContextKeyToDelegatesViaDwn(
851
+ request.target, writeParams.protocol, rootContextId, xdContextKeyPayload,
852
+ );
744
853
  }
745
854
  } catch (detectionError: any) {
746
855
  // Participant detection failure is non-fatal — the record is still stored.
@@ -875,6 +984,20 @@ export class AgentDwnApi {
875
984
  );
876
985
  }
877
986
 
987
+ // When a ProtocolsConfigure is processed WITHOUT the encryption flag
988
+ // (e.g. a delegate installing the owner's protocol definition that
989
+ // already contains `$encryption` keys from the remote DWN), cache the
990
+ // definition so that subsequent RecordsWrite encryption can find it
991
+ // without re-querying the local DWN (which would fail for delegates
992
+ // because the query author doesn't match the unpublished protocol's
993
+ // tenant).
994
+ if (isDwnRequest(request, DwnInterface.ProtocolsConfigure) && !request.encryption && !rawMessage) {
995
+ const def = request.messageParams?.definition;
996
+ if (def?.protocol) {
997
+ this._protocolDefinitionCache.set(`${request.target}~${def.protocol}`, def);
998
+ }
999
+ }
1000
+
878
1001
  // Auto-encrypt data on RecordsWrite.
879
1002
  //
880
1003
  // Encryption scheme decision (unified key delivery):
@@ -923,7 +1046,7 @@ export class AgentDwnApi {
923
1046
  );
924
1047
  } else {
925
1048
  protocolDefinition = await this.getProtocolDefinition(
926
- request.target, messageParams.protocol,
1049
+ request.target, messageParams.protocol, request.granteeDid,
927
1050
  );
928
1051
  }
929
1052
 
@@ -1115,8 +1238,34 @@ export class AgentDwnApi {
1115
1238
  await this.getSigner(request.granteeDid) :
1116
1239
  await this.getSigner(request.author);
1117
1240
 
1241
+ // When signing as a delegate with a permissionGrantId, fetch the full
1242
+ // grant message and pass it as `delegatedGrant` so the DWN SDK correctly
1243
+ // sets `authorization.authorDelegatedGrant` and resolves the logical
1244
+ // author to the grantor (owner) rather than the signer (delegate).
1245
+ const params = { ...request.messageParams } as any;
1246
+ if (request.granteeDid && params.permissionGrantId && !params.delegatedGrant
1247
+ && isDwnRequest(request, DwnInterface.RecordsWrite)) {
1248
+ // Read as the grantee (delegate), not the owner. The delegate is
1249
+ // the grant's recipient so the permissions protocol authorizes the
1250
+ // read. The owner's signing key may not be available on the
1251
+ // delegate agent in real wallet-connect flows.
1252
+ const { reply: grantReply } = await this.processRequest({
1253
+ author : request.granteeDid,
1254
+ target : request.author,
1255
+ messageType : DwnInterface.RecordsRead,
1256
+ messageParams : { filter: { recordId: params.permissionGrantId } },
1257
+ });
1258
+ if (grantReply.status.code === 200 && grantReply.entry?.recordsWrite && grantReply.entry?.data) {
1259
+ const grantDataBytes = await DataStream.toBytes(grantReply.entry.data);
1260
+ params.delegatedGrant = {
1261
+ ...grantReply.entry.recordsWrite,
1262
+ encodedData: Convert.uint8Array(grantDataBytes).toBase64Url(),
1263
+ };
1264
+ }
1265
+ }
1266
+
1118
1267
  dwnMessage = await dwnMessageConstructor.create({
1119
- ...request.messageParams,
1268
+ ...params,
1120
1269
  signer
1121
1270
  });
1122
1271
 
@@ -1293,6 +1442,7 @@ export class AgentDwnApi {
1293
1442
  private async getProtocolDefinition(
1294
1443
  tenantDid: string,
1295
1444
  protocolUri: string,
1445
+ granteeDid?: string,
1296
1446
  ): Promise<ProtocolDefinition | undefined> {
1297
1447
  if (!this._dwn) {
1298
1448
  // Remote mode: query via RPC (same as fetchRemoteProtocolDefinition,
@@ -1312,9 +1462,29 @@ export class AgentDwnApi {
1312
1462
  throw error;
1313
1463
  }
1314
1464
  }
1465
+ // When operating as a delegate, resolve the ProtocolsQuery grant so
1466
+ // the local DWN authorises the query for unpublished protocols.
1467
+ let permissionGrantId: string | undefined;
1468
+ if (granteeDid) {
1469
+ try {
1470
+ const permissionsApi = new AgentPermissionsApi({ agent: this.agent });
1471
+ const { grant } = await permissionsApi.getPermissionForRequest({
1472
+ connectedDid : tenantDid,
1473
+ delegateDid : granteeDid,
1474
+ protocol : protocolUri,
1475
+ cached : true,
1476
+ messageType : DwnInterface.ProtocolsQuery,
1477
+ });
1478
+ permissionGrantId = grant.id;
1479
+ } catch {
1480
+ // No grant found — try without (works for published protocols).
1481
+ }
1482
+ }
1483
+
1315
1484
  return getProtocolDefinitionFn(
1316
1485
  tenantDid, protocolUri, this._dwn,
1317
1486
  this.getSigner.bind(this), this._protocolDefinitionCache,
1487
+ granteeDid, permissionGrantId,
1318
1488
  );
1319
1489
  }
1320
1490
 
@@ -1369,6 +1539,8 @@ export class AgentDwnApi {
1369
1539
  request, reply, this.agent,
1370
1540
  this._contextDerivedKeyCache,
1371
1541
  this.fetchContextKeyRecord.bind(this),
1542
+ this._delegateDecryptionKeyCache,
1543
+ this._delegateContextKeyCache,
1372
1544
  );
1373
1545
  }
1374
1546
 
@@ -1452,6 +1624,328 @@ export class AgentDwnApi {
1452
1624
  );
1453
1625
  }
1454
1626
 
1627
+ /**
1628
+ * Imports scope-aware decryption keys for delegate sessions.
1629
+ *
1630
+ * Called during the connect flow when the wallet delivers decryption keys
1631
+ * for encrypted protocols. Keys are derived only for read-like scopes
1632
+ * (Read/Query/Subscribe) — write-only delegates receive no keys.
1633
+ *
1634
+ * The keys are cached and used by `resolveKeyDecrypter()` to decrypt
1635
+ * records when the delegate does not possess the owner's root X25519
1636
+ * private key.
1637
+ *
1638
+ * @param delegateDid - The delegate DID for this session (unique per connect)
1639
+ * @param keys - Array of scope-aware decryption key entries
1640
+ */
1641
+
1642
+ /**
1643
+ * Sets a callback invoked whenever post-connect context keys are
1644
+ * delivered to a delegate. The auth layer uses this to persist
1645
+ * updated context keys so they survive restart.
1646
+ *
1647
+ * @param callback - Called with the delegateDid that received new keys.
1648
+ * Set to `undefined` to unregister.
1649
+ */
1650
+ public set onDelegateContextKeysChanged(
1651
+ callback: ((delegateDid: string) => void) | undefined,
1652
+ ) {
1653
+ this._onDelegateContextKeysChanged = callback;
1654
+ }
1655
+
1656
+ public importDelegateDecryptionKeys(
1657
+ delegateDid: string,
1658
+ keys: {
1659
+ protocol: string;
1660
+ scope: { kind: 'protocol' } | { kind: 'protocolPath'; protocolPath: string; match: 'exact' };
1661
+ derivedPrivateKey: DerivedPrivateJwk;
1662
+ }[],
1663
+ ): void {
1664
+ const cacheKey = `ddk~${delegateDid}`;
1665
+ this._delegateDecryptionKeyCache.set(cacheKey, keys);
1666
+ }
1667
+
1668
+ /**
1669
+ * Imports ProtocolContext decryption keys for multi-party encrypted protocols.
1670
+ * Each key is scoped to one rootContextId within one protocol.
1671
+ *
1672
+ * @param delegateDid - The delegate DID for this session
1673
+ * @param keys - Array of `{ protocol, contextId, derivedPrivateKey }` entries
1674
+ */
1675
+ public importDelegateContextKeys(
1676
+ delegateDid: string,
1677
+ keys: {
1678
+ protocol: string;
1679
+ contextId: string;
1680
+ derivedPrivateKey: DerivedPrivateJwk;
1681
+ }[],
1682
+ multiPartyProtocols?: string[],
1683
+ ): void {
1684
+ // Clear any previously indexed entries for this delegate first,
1685
+ // so a re-import (e.g. session restore) doesn't leave stale entries.
1686
+ const previousKeys = this._delegateContextKeyCacheIndex.get(delegateDid);
1687
+ if (previousKeys) {
1688
+ for (const ck of previousKeys) { this._delegateContextKeyCache.delete(ck); }
1689
+ }
1690
+
1691
+ const cacheKeys: string[] = [];
1692
+ for (const key of keys) {
1693
+ const ck = `dctx~${delegateDid}~${key.protocol}~${key.contextId}`;
1694
+ this._delegateContextKeyCache.set(ck, key.derivedPrivateKey);
1695
+ cacheKeys.push(ck);
1696
+ }
1697
+ this._delegateContextKeyCacheIndex.set(delegateDid, cacheKeys);
1698
+
1699
+ // Populate the explicit multi-party protocol registry.
1700
+ // Sources: explicit parameter (always wins) + protocols from delivered keys.
1701
+ const protocols = new Set<string>(multiPartyProtocols ?? []);
1702
+ for (const key of keys) { protocols.add(key.protocol); }
1703
+ if (protocols.size > 0) {
1704
+ this._delegateMultiPartyProtocols.set(delegateDid, protocols);
1705
+ } else {
1706
+ this._delegateMultiPartyProtocols.delete(delegateDid);
1707
+ }
1708
+ }
1709
+
1710
+ /**
1711
+ * Clears all delegate decryption keys (both ProtocolPath and ProtocolContext)
1712
+ * from the in-memory cache. Called on disconnect to prevent stale keys from
1713
+ * persisting across sessions.
1714
+ *
1715
+ * @param delegateDid - If provided, clears keys for that delegate session only.
1716
+ * If omitted, clears all delegate keys.
1717
+ */
1718
+ public clearDelegateDecryptionKeys(delegateDid?: string): void {
1719
+ if (delegateDid) {
1720
+ this._delegateDecryptionKeyCache.delete(`ddk~${delegateDid}`);
1721
+ // Delete only context keys belonging to this delegate.
1722
+ const cacheKeys = this._delegateContextKeyCacheIndex.get(delegateDid);
1723
+ if (cacheKeys) {
1724
+ for (const ck of cacheKeys) { this._delegateContextKeyCache.delete(ck); }
1725
+ this._delegateContextKeyCacheIndex.delete(delegateDid);
1726
+ }
1727
+ this._delegateMultiPartyProtocols.delete(delegateDid);
1728
+ } else {
1729
+ this._delegateDecryptionKeyCache.clear();
1730
+ this._delegateContextKeyCache.clear();
1731
+ this._delegateContextKeyCacheIndex.clear();
1732
+ this._delegateMultiPartyProtocols.clear();
1733
+ }
1734
+ }
1735
+
1736
+ /**
1737
+ * Exports the current set of delegate context keys for a specific delegate.
1738
+ * Returns an array of `{ protocol, contextId, derivedPrivateKey }` entries
1739
+ * suitable for serialization and persistence.
1740
+ *
1741
+ * Called by the auth layer to persist context keys (including keys delivered
1742
+ * post-connect) so they survive agent restarts.
1743
+ *
1744
+ * @param delegateDid - The delegate DID whose context keys to export
1745
+ * @returns Array of context key entries (may be empty)
1746
+ */
1747
+ public exportDelegateContextKeys(
1748
+ delegateDid: string,
1749
+ ): { protocol: string; contextId: string; derivedPrivateKey: DerivedPrivateJwk }[] {
1750
+ const cacheKeys = this._delegateContextKeyCacheIndex.get(delegateDid);
1751
+ if (!cacheKeys) { return []; }
1752
+
1753
+ const result: { protocol: string; contextId: string; derivedPrivateKey: DerivedPrivateJwk }[] = [];
1754
+ const prefix = `dctx~${delegateDid}~`;
1755
+
1756
+ for (const ck of cacheKeys) {
1757
+ const key = this._delegateContextKeyCache.get(ck);
1758
+ if (!key || !ck.startsWith(prefix)) { continue; }
1759
+
1760
+ // Parse protocol and contextId from cache key:
1761
+ // format is `dctx~<delegateDid>~<protocol>~<contextId>`
1762
+ // contextId is always the last segment; protocol is everything between.
1763
+ const rest = ck.slice(prefix.length);
1764
+ const lastTilde = rest.lastIndexOf('~');
1765
+ if (lastTilde === -1) { continue; }
1766
+
1767
+ result.push({
1768
+ protocol : rest.slice(0, lastTilde),
1769
+ contextId : rest.slice(lastTilde + 1),
1770
+ derivedPrivateKey : key,
1771
+ });
1772
+ }
1773
+
1774
+ return result;
1775
+ }
1776
+
1777
+ /**
1778
+ * Exports the registered multi-party protocol URIs for a delegate.
1779
+ * Used by the auth layer for persistence.
1780
+ */
1781
+ public exportDelegateMultiPartyProtocols(delegateDid: string): string[] {
1782
+ const protocols = this._delegateMultiPartyProtocols.get(delegateDid);
1783
+ return protocols ? [...protocols] : [];
1784
+ }
1785
+
1786
+ /**
1787
+ * Checks whether any active delegate session has context keys for the
1788
+ * given protocol. Used by `postWriteKeyDelivery()` to determine if
1789
+ * delegate delivery is needed.
1790
+ */
1791
+ private hasEligibleDelegatesForProtocol(protocol: string): boolean {
1792
+ for (const [, protocols] of this._delegateMultiPartyProtocols) {
1793
+ if (protocols.has(protocol)) {
1794
+ return true;
1795
+ }
1796
+ }
1797
+ return false;
1798
+ }
1799
+
1800
+ /**
1801
+ * Delivers a newly created multi-party context key to all active delegate
1802
+ * sessions that have existing context keys for the given protocol.
1803
+ *
1804
+ * This is same-process delivery: the context key is injected directly
1805
+ * into `_delegateContextKeyCache`. It works when the delegate cache is
1806
+ * on the same agent instance that creates the root record.
1807
+ *
1808
+ * Cross-device DWN-based delivery (where the owner's agent and the
1809
+ * delegate's agent are separate processes) is a documented follow-up.
1810
+ *
1811
+ * @param protocol - The protocol URI
1812
+ * @param rootContextId - The root context ID of the new context
1813
+ * @param contextKey - The derived context key (`DerivedPrivateJwk`)
1814
+ */
1815
+ private deliverContextKeyToDelegates(
1816
+ protocol: string,
1817
+ rootContextId: string,
1818
+ contextKey: DerivedPrivateJwk,
1819
+ ): void {
1820
+ for (const [delegateDid, protocols] of this._delegateMultiPartyProtocols) {
1821
+ if (!protocols.has(protocol)) { continue; }
1822
+
1823
+ // Skip if this delegate already has a key for this context (idempotent).
1824
+ const newCacheKey = `dctx~${delegateDid}~${protocol}~${rootContextId}`;
1825
+ if (this._delegateContextKeyCache.get(newCacheKey)) { continue; }
1826
+
1827
+ this._delegateContextKeyCache.set(newCacheKey, contextKey);
1828
+ const indexKeys = this._delegateContextKeyCacheIndex.get(delegateDid) ?? [];
1829
+ indexKeys.push(newCacheKey);
1830
+ this._delegateContextKeyCacheIndex.set(delegateDid, indexKeys);
1831
+
1832
+ // Notify the auth layer so it can persist the updated keys.
1833
+ this._onDelegateContextKeysChanged?.(delegateDid);
1834
+ }
1835
+ }
1836
+
1837
+ /**
1838
+ * Delivers a newly created multi-party context key to eligible delegates
1839
+ * by writing `contextKey` records to the owner's DWN via the key-delivery
1840
+ * protocol. This enables cross-device delivery: the delegate can later
1841
+ * fetch the record from the owner's DWN and decrypt it.
1842
+ *
1843
+ * Eligible delegates are discovered by querying the owner's DWN for
1844
+ * active permission grants with read-like scopes on the given protocol.
1845
+ *
1846
+ * The contextKey record is encrypted using the delegate's pre-derived
1847
+ * key-delivery leaf public key, which is stored in the grant's tags
1848
+ * during `submitConnectResponse()`.
1849
+ *
1850
+ * @param tenantDid - The owner's DID
1851
+ * @param protocol - The protocol URI
1852
+ * @param rootContextId - The root context ID of the new context
1853
+ * @param contextKey - The derived context key (`DerivedPrivateJwk`)
1854
+ */
1855
+ private async deliverContextKeyToDelegatesViaDwn(
1856
+ tenantDid: string,
1857
+ protocol: string,
1858
+ rootContextId: string,
1859
+ contextKey: DerivedPrivateJwk,
1860
+ ): Promise<void> {
1861
+ try {
1862
+ const permissionsApi = new AgentPermissionsApi({ agent: this.agent });
1863
+ const grants = await permissionsApi.fetchGrants({
1864
+ author : tenantDid,
1865
+ target : tenantDid,
1866
+ grantor : tenantDid,
1867
+ protocol,
1868
+ checkRevoked : true,
1869
+ });
1870
+
1871
+ const readMethods = new Set(['Read', 'Query', 'Subscribe']);
1872
+ const nowMs = Date.now();
1873
+
1874
+ // Deduplicate: one contextKey per delegate, not per grant.
1875
+ // Multiple grants (Read, Query, Subscribe) for the same delegate
1876
+ // should produce exactly one contextKey record.
1877
+ // IMPORTANT: dedup happens AFTER tag validation so that an older
1878
+ // untagged grant doesn't shadow a valid tagged grant for the same delegate.
1879
+ const deliveredDelegates = new Set<string>();
1880
+
1881
+ for (const grant of grants) {
1882
+ // Only delegated grants are eligible. Non-delegated grants (direct
1883
+ // access without a delegate session) should not trigger cross-device
1884
+ // context key delivery.
1885
+ if (!grant.grant.delegated) { continue; }
1886
+
1887
+ // Filter expired grants. fetchGrants checks revocation but does
1888
+ // NOT filter by dateExpires. Use numeric comparison for safety.
1889
+ if (new Date(grant.grant.dateExpires).getTime() <= nowMs) { continue; }
1890
+
1891
+ const scope = grant.grant.scope as any;
1892
+ if (scope.interface !== 'Records' || !readMethods.has(scope.method)) { continue; }
1893
+
1894
+ // Narrow scopes (protocolPath, contextId) are not supported for
1895
+ // multi-party delegate delivery — skip them silently.
1896
+ if (scope.protocolPath || scope.contextId) { continue; }
1897
+
1898
+ const delegateDid = grant.grant.grantee;
1899
+
1900
+ // Read the pre-derived key-delivery leaf public key from the
1901
+ // grant data payload. This was computed during submitConnectResponse()
1902
+ // and stored alongside the grant's standard fields.
1903
+ const keyDelivery = grant.grant.delegateKeyDelivery;
1904
+ if (!keyDelivery?.rootKeyId || !keyDelivery?.publicKeyJwk) {
1905
+ // Grant was created before key-delivery was supported, or
1906
+ // is not a read-like grant. Skip — do NOT dedup yet.
1907
+ continue;
1908
+ }
1909
+
1910
+ // Dedup check — skip if already delivered via an earlier grant.
1911
+ if (deliveredDelegates.has(delegateDid)) { continue; }
1912
+
1913
+ const leafPublicKeyJwk = keyDelivery.publicKeyJwk as PublicKeyJwk;
1914
+
1915
+ try {
1916
+ await this.writeContextKeyRecord({
1917
+ tenantDid,
1918
+ recipientDid : delegateDid,
1919
+ contextKeyData : contextKey,
1920
+ sourceProtocol : protocol,
1921
+ sourceContextId : rootContextId,
1922
+ recipientKeyDeliveryPublicKey : {
1923
+ rootKeyId : keyDelivery.rootKeyId,
1924
+ publicKeyJwk : leafPublicKeyJwk,
1925
+ },
1926
+ });
1927
+
1928
+ // Mark as delivered ONLY after the write succeeds. If the write
1929
+ // fails, a later valid grant for the same delegate can still try.
1930
+ deliveredDelegates.add(delegateDid);
1931
+ } catch (delegateError: any) {
1932
+ console.warn(
1933
+ `AgentDwnApi: Cross-device key delivery to delegate ` +
1934
+ `'${delegateDid}' for context '${rootContextId}' failed: ` +
1935
+ `${delegateError.message}. The delegate may need to reconnect.`
1936
+ );
1937
+ }
1938
+ }
1939
+ } catch (discoveryError: any) {
1940
+ // Grant discovery failure is non-fatal — same-process delivery may
1941
+ // still have succeeded, and sync will eventually deliver the record.
1942
+ console.warn(
1943
+ `AgentDwnApi: Delegate grant discovery for protocol ` +
1944
+ `'${protocol}' failed: ${discoveryError.message}`
1945
+ );
1946
+ }
1947
+ }
1948
+
1455
1949
  /**
1456
1950
  * Writes a `contextKey` record to the owner's DWN, delivering an encrypted
1457
1951
  * context key to a participant.
@@ -1507,9 +2001,6 @@ export class AgentDwnApi {
1507
2001
  return fetchContextKeyRecordFn(
1508
2002
  this.agent, params,
1509
2003
  this.processRequest.bind(this),
1510
- this.getSigner.bind(this),
1511
- this.sendDwnRpcRequest.bind(this),
1512
- this.getDwnEndpointUrlsForTarget.bind(this),
1513
2004
  );
1514
2005
  }
1515
2006
  }