@enbox/api 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +63 -0
  2. package/dist/browser.mjs +11 -28
  3. package/dist/browser.mjs.map +4 -4
  4. package/dist/esm/advanced.js +1 -1
  5. package/dist/esm/define-protocol.js +3 -3
  6. package/dist/esm/did-api.js +1 -1
  7. package/dist/esm/did-api.js.map +1 -1
  8. package/dist/esm/dwn-api.js +6 -6
  9. package/dist/esm/dwn-api.js.map +1 -1
  10. package/dist/esm/dwn-reader-api.js +2 -2
  11. package/dist/esm/enbox.js +205 -0
  12. package/dist/esm/enbox.js.map +1 -0
  13. package/dist/esm/index.js +16 -15
  14. package/dist/esm/index.js.map +1 -1
  15. package/dist/esm/protocol.js +2 -2
  16. package/dist/esm/protocol.js.map +1 -1
  17. package/dist/esm/record-data.js +79 -5
  18. package/dist/esm/record-data.js.map +1 -1
  19. package/dist/esm/record.js +49 -10
  20. package/dist/esm/record.js.map +1 -1
  21. package/dist/esm/repository.js +7 -7
  22. package/dist/esm/repository.js.map +1 -1
  23. package/dist/esm/typed-enbox.js +583 -0
  24. package/dist/esm/typed-enbox.js.map +1 -0
  25. package/dist/esm/typed-live-query.js +1 -1
  26. package/dist/esm/typed-record.js +370 -46
  27. package/dist/esm/typed-record.js.map +1 -1
  28. package/dist/esm/utils.js +25 -0
  29. package/dist/esm/utils.js.map +1 -1
  30. package/dist/esm/vc-api.js.map +1 -1
  31. package/dist/types/advanced.d.ts +1 -1
  32. package/dist/types/define-protocol.d.ts +3 -3
  33. package/dist/types/did-api.d.ts +4 -4
  34. package/dist/types/did-api.d.ts.map +1 -1
  35. package/dist/types/dwn-api.d.ts +12 -7
  36. package/dist/types/dwn-api.d.ts.map +1 -1
  37. package/dist/types/dwn-reader-api.d.ts +2 -2
  38. package/dist/types/enbox.d.ts +202 -0
  39. package/dist/types/enbox.d.ts.map +1 -0
  40. package/dist/types/grant-revocation.d.ts +2 -2
  41. package/dist/types/grant-revocation.d.ts.map +1 -1
  42. package/dist/types/index.d.ts +16 -15
  43. package/dist/types/index.d.ts.map +1 -1
  44. package/dist/types/live-query.d.ts +2 -2
  45. package/dist/types/live-query.d.ts.map +1 -1
  46. package/dist/types/permission-grant.d.ts +2 -2
  47. package/dist/types/permission-grant.d.ts.map +1 -1
  48. package/dist/types/permission-request.d.ts +2 -2
  49. package/dist/types/permission-request.d.ts.map +1 -1
  50. package/dist/types/protocol-types.d.ts +2 -2
  51. package/dist/types/protocol.d.ts +7 -7
  52. package/dist/types/protocol.d.ts.map +1 -1
  53. package/dist/types/record-data.d.ts +17 -0
  54. package/dist/types/record-data.d.ts.map +1 -1
  55. package/dist/types/record.d.ts +24 -10
  56. package/dist/types/record.d.ts.map +1 -1
  57. package/dist/types/repository-types.d.ts +19 -11
  58. package/dist/types/repository-types.d.ts.map +1 -1
  59. package/dist/types/repository.d.ts +7 -7
  60. package/dist/types/repository.d.ts.map +1 -1
  61. package/dist/types/typed-enbox.d.ts +613 -0
  62. package/dist/types/typed-enbox.d.ts.map +1 -0
  63. package/dist/types/typed-live-query.d.ts +1 -1
  64. package/dist/types/typed-record.d.ts +427 -53
  65. package/dist/types/typed-record.d.ts.map +1 -1
  66. package/dist/types/utils.d.ts +23 -0
  67. package/dist/types/utils.d.ts.map +1 -1
  68. package/dist/types/vc-api.d.ts +3 -3
  69. package/dist/types/vc-api.d.ts.map +1 -1
  70. package/package.json +12 -11
  71. package/src/advanced.ts +1 -1
  72. package/src/define-protocol.ts +3 -3
  73. package/src/did-api.ts +5 -5
  74. package/src/dwn-api.ts +22 -17
  75. package/src/dwn-reader-api.ts +2 -2
  76. package/src/enbox.ts +281 -0
  77. package/src/grant-revocation.ts +3 -3
  78. package/src/index.ts +17 -16
  79. package/src/live-query.ts +2 -2
  80. package/src/permission-grant.ts +4 -4
  81. package/src/permission-request.ts +3 -3
  82. package/src/protocol-types.ts +2 -2
  83. package/src/protocol.ts +8 -8
  84. package/src/record-data.ts +86 -5
  85. package/src/record.ts +54 -13
  86. package/src/repository-types.ts +19 -7
  87. package/src/repository.ts +15 -15
  88. package/src/typed-enbox.ts +1169 -0
  89. package/src/typed-live-query.ts +1 -1
  90. package/src/typed-record.ts +431 -53
  91. package/src/utils.ts +27 -0
  92. package/src/vc-api.ts +4 -4
  93. package/dist/esm/typed-web5.js +0 -339
  94. package/dist/esm/typed-web5.js.map +0 -1
  95. package/dist/esm/web5.js +0 -410
  96. package/dist/esm/web5.js.map +0 -1
  97. package/dist/types/typed-web5.d.ts +0 -221
  98. package/dist/types/typed-web5.d.ts.map +0 -1
  99. package/dist/types/web5.d.ts +0 -346
  100. package/dist/types/web5.d.ts.map +0 -1
  101. package/src/typed-web5.ts +0 -598
  102. package/src/web5.ts +0 -754
package/src/web5.ts DELETED
@@ -1,754 +0,0 @@
1
- /**
2
- * NOTE: Added reference types here to avoid a `pnpm` bug during build.
3
- * https://github.com/enboxorg/enbox/pull/507
4
- */
5
- /// <reference types="@enbox/dwn-sdk-js" />
6
-
7
- import type { DidMethodResolver } from '@enbox/dids';
8
- import type { ProtocolDefinition } from '@enbox/dwn-sdk-js';
9
- import type {
10
- BearerIdentity,
11
- DwnDataEncodedRecordsWriteMessage,
12
- DwnMessagesPermissionScope,
13
- DwnProtocolDefinition,
14
- DwnRecordsPermissionScope,
15
- HdIdentityVault,
16
- Permission,
17
- WalletConnectOptions,
18
- Web5Agent,
19
- } from '@enbox/agent';
20
-
21
- import type { SchemaMap, TypedProtocol } from './protocol-types.js';
22
-
23
- import { AnonymousDwnApi, WalletConnect, Web5UserAgent } from '@enbox/agent';
24
- import { DidDht, DidJwk, DidKey, DidResolverCacheMemory, DidWeb, UniversalResolver } from '@enbox/dids';
25
- import { DwnRegistrar, Web5RpcClient } from '@enbox/dwn-clients';
26
-
27
- import { DidApi } from './did-api.js';
28
- import { DwnApi } from './dwn-api.js';
29
- import { DwnReaderApi } from './dwn-reader-api.js';
30
- import { PermissionGrant } from './permission-grant.js';
31
- import { TypedWeb5 } from './typed-web5.js';
32
- import { VcApi } from './vc-api.js';
33
-
34
- /** Override defaults configured during the technical preview phase. */
35
- export type TechPreviewOptions = {
36
- /** Override default dwnEndpoints provided for technical preview. */
37
- dwnEndpoints?: string[];
38
- };
39
-
40
- /** Override defaults for DID creation. */
41
- export type DidCreateOptions = {
42
- /** Override default dwnEndpoints provided during DID creation. */
43
- dwnEndpoints?: string[];
44
- };
45
-
46
- /**
47
- * Represents a permission request for a protocol definition.
48
- */
49
- export type ConnectPermissionRequest = {
50
- /**
51
- * The protocol definition for the protocol being requested.
52
- */
53
- protocolDefinition: DwnProtocolDefinition;
54
-
55
- /**
56
- * The permissions being requested for the protocol. If none are provided, the default is to request all permissions.
57
- */
58
- permissions?: Permission[];
59
- };
60
-
61
- /**
62
- * Options for connecting to a Web5 agent. This includes the ability to connect to an external wallet.
63
- *
64
- * NOTE: the returned `ConnectPermissionRequest` type is different to the `ConnectPermissionRequest` type in the `@enbox/agent` package.
65
- */
66
- export type ConnectOptions = Omit<WalletConnectOptions, 'permissionRequests'> & {
67
- /** The user friendly name of the client/app to be displayed when prompting end-user with permission requests. */
68
- displayName: string;
69
-
70
- /**
71
- * The permissions that are being requested for the connected DID.
72
- * This is used to create the {@link ConnectPermissionRequest} for the wallet connect flow.
73
- */
74
- permissionRequests: ConnectPermissionRequest[];
75
- };
76
-
77
- /**
78
- * Options for creating an anonymous (read-only) Web5 instance via {@link Web5.anonymous}.
79
- *
80
- * @beta
81
- */
82
- export type Web5AnonymousOptions = {
83
- /** Override the default DID method resolvers. Defaults to `[DidDht, DidJwk, DidKey, DidWeb]`. */
84
- didResolvers?: DidMethodResolver[];
85
- };
86
-
87
- /**
88
- * The result of calling {@link Web5.anonymous}.
89
- *
90
- * Contains only a read-only `dwn` property — no `did`, `vc`, or `agent`.
91
- *
92
- * @beta
93
- */
94
- export type Web5AnonymousApi = {
95
- /** A read-only DWN API for querying public data on remote DWNs. */
96
- dwn: DwnReaderApi;
97
- };
98
-
99
- /** Parameters passed to the onProviderAuthRequired callback. */
100
- export type ProviderAuthParams = {
101
- /** Full authorize URL to open in a browser (query params already appended). */
102
- authorizeUrl: string;
103
- /** The DWN endpoint URL this auth is for (informational). */
104
- dwnEndpoint: string;
105
- /** CSRF nonce — the provider will return this unchanged in the redirect. */
106
- state: string;
107
- };
108
-
109
- /** Result returned by the app after the user completes provider auth. */
110
- export type ProviderAuthResult = {
111
- /** Authorization code from the provider's redirect. */
112
- code: string;
113
- /** Must match the state from ProviderAuthParams (CSRF validation). */
114
- state: string;
115
- };
116
-
117
- /** Persisted registration token data for a DWN endpoint. */
118
- export type RegistrationTokenData = {
119
- /** Opaque registration token for POST /registration. */
120
- registrationToken: string;
121
- /** Refresh token for obtaining new registration tokens. */
122
- refreshToken?: string;
123
- /** Unix timestamp (ms) when the token expires. Undefined = never expires. */
124
- expiresAt?: number;
125
- /** Provider's token exchange URL (needed for code exchange). */
126
- tokenUrl: string;
127
- /** Provider's refresh URL (needed for token refresh). */
128
- refreshUrl?: string;
129
- };
130
-
131
- /** Optional overrides that can be provided when calling {@link Web5.connect}. */
132
- export type Web5ConnectOptions = {
133
- /**
134
- * When specified, external wallet connect flow is triggered.
135
- * This param currently will not work in apps that are currently connected.
136
- * It must only be invoked at registration with a reset and empty DWN and agent.
137
- */
138
- walletConnectOptions?: ConnectOptions;
139
-
140
- /**
141
- * Provide a {@link Web5Agent} implementation. Defaults to creating a local
142
- * {@link Web5UserAgent} if one isn't provided
143
- **/
144
- agent?: Web5Agent;
145
-
146
- /**
147
- * Provide an instance of a {@link HdIdentityVault} implementation. Defaults to
148
- * a LevelDB-backed store with an insecure, static unlock password if one
149
- * isn't provided. To allow the app user to enter a secure password of
150
- * their choosing, provide an initialized {@link HdIdentityVault} instance.
151
- **/
152
- agentVault?: HdIdentityVault;
153
-
154
- /** Specify an existing DID to connect to. */
155
- connectedDid?: string;
156
-
157
- /**
158
- * The Web5 app `password` is used to protect data on the device the application is running on.
159
- *
160
- * Only the end user should know this password: it should not be stored on the device or
161
- * transmitted over the network.
162
- *
163
- * This password is crucial for the security of an identity vault that stores the local Agent's
164
- * cryptographic keys and decentralized identifier (DID). The vault's content is encrypted using
165
- * the password, making it accessible only to those who know the password.
166
- *
167
- * App users should be advised to use a strong, unique passphrase that is not shared across
168
- * different services or applications. The password should be kept confidential and not be
169
- * exposed to unauthorized entities. Losing the password may result in irreversible loss of
170
- * access to the vault's contents.
171
- */
172
- password?: string;
173
-
174
- /**
175
- * The `recoveryPhrase` is a unique, secure key for recovering the identity vault.
176
- *
177
- * This phrase is a series of 12 words generated securely and known only to the user. It plays a
178
- * critical role in the security of the identity vault by enabling the recovery of the vault's
179
- * contents, including cryptographic keys and the Agent's decentralized identifier (DID), across
180
- * different devices or if the original device is compromised or lost.
181
- *
182
- * The recovery phrase is akin to a master key, as anyone with access to this phrase can restore
183
- * and access the vault's contents. It’s combined with the app `password` to encrypt the vault's
184
- * content.
185
- *
186
- * Unlike a password, the recovery phrase is not intended for regular use but as a secure backup
187
- * method for vault recovery. Losing this phrase can result in permanent loss of access to the
188
- * vault's contents, as it cannot be reset or retrieved if forgotten.
189
- *
190
- * Users should treat the recovery phrase with the highest level of security, ensuring it is
191
- * never shared, stored online, or exposed to potential threats. It is the user's responsibility
192
- * to keep this phrase safe to maintain the integrity and accessibility of their secured data. It
193
- * is recommended to write it down and store it in a secure location, separate from the device and
194
- * digital backups.
195
- */
196
- recoveryPhrase?: string;
197
-
198
- /**
199
- * Enable synchronization of DWN records between local and remote DWNs.
200
- *
201
- * - **Omitted / `undefined`**: Live sync mode (default). Opens real-time
202
- * `MessagesSubscribe` WebSocket subscriptions for instant pull and
203
- * push-on-write, with a background SMT integrity check every 5 minutes.
204
- * - **Interval string** (e.g. `'2m'`, `'30s'`): Poll mode. Performs a full
205
- * SMT set-reconciliation sync at the specified interval.
206
- * - **`'off'`**: Sync is disabled entirely.
207
- */
208
- sync?: string;
209
-
210
- /**
211
- * Override defaults configured during the technical preview phase.
212
- * See {@link TechPreviewOptions} for available options.
213
- */
214
- techPreview?: TechPreviewOptions;
215
-
216
- /**
217
- * Override defaults configured options for creating a DID during connect.
218
- * See {@link DidCreateOptions} for available options.
219
- */
220
- didCreateOptions?: DidCreateOptions;
221
-
222
- /**
223
- * If the `registration` option is provided, the agent DID and the connected DID will be
224
- * registered with the DWN endpoints provided by `techPreview` or `didCreateOptions`.
225
- *
226
- * If registration fails, the `onFailure` callback will be called with the error.
227
- * If registration is successful, the `onSuccess` callback will be called.
228
- */
229
- registration? : {
230
- /** Called when all of the DWN registrations are successful. */
231
- onSuccess : () => void;
232
- /** Called when any of the DWN registrations fail. */
233
- onFailure : (error: any) => void;
234
-
235
- /**
236
- * Called when a DWN endpoint requires provider auth (`'provider-auth-v0'`).
237
- * The app is responsible for opening the authorizeUrl in a browser,
238
- * capturing the redirect back, and returning the auth code.
239
- * If not provided, provider-auth endpoints fall back to PoW registration.
240
- */
241
- onProviderAuthRequired? : (params: ProviderAuthParams) => Promise<ProviderAuthResult>;
242
-
243
- /**
244
- * Pre-existing registration tokens from a previous session, keyed by DWN endpoint URL.
245
- * If a valid (non-expired) token exists for an endpoint, it is used directly.
246
- */
247
- registrationTokens? : Record<string, RegistrationTokenData>;
248
-
249
- /**
250
- * Called when new registration tokens are obtained so the app can persist them.
251
- */
252
- onRegistrationTokens? : (tokens: Record<string, RegistrationTokenData>) => void;
253
- }
254
- };
255
-
256
- /**
257
- * Represents the result of the Web5 connection process, including the Web5 instance,
258
- * the connected decentralized identifier (DID), and optionally the recovery phrase used
259
- * during the agent's initialization.
260
- */
261
- export type Web5ConnectResult = {
262
- /** The Web5 instance, providing access to the agent, DID, DWN, and VC APIs. */
263
- web5: Web5;
264
-
265
- /** The DID that has been connected or created during the connection process. */
266
- did: string;
267
-
268
- /**
269
- * The first time a Web5 agent is initialized, the recovery phrase that was used to generate the
270
- * agent's DID and keys is returned. This phrase can be used to recover the agent's vault contents
271
- * and should be stored securely by the user.
272
- */
273
- recoveryPhrase?: string;
274
-
275
- /**
276
- * The resulting did of a successful wallet connect. Only returned on success if
277
- * {@link WalletConnectOptions} was provided.
278
- */
279
- delegateDid?: string;
280
- };
281
-
282
- /**
283
- * Parameters that are passed to Web5 constructor.
284
- *
285
- * @see {@link Web5ConnectOptions}
286
- */
287
- export type Web5Params = {
288
- /**
289
- * A {@link Web5Agent} instance that handles DIDs, DWNs and VCs requests. The agent manages the
290
- * user keys and identities, and is responsible to sign and verify messages.
291
- */
292
- agent: Web5Agent;
293
-
294
- /** The DID of the tenant under which all DID, DWN, and VC requests are being performed. */
295
- connectedDid: string;
296
-
297
- /** The DID that will be signing Web5 messages using grants from the connectedDid */
298
- delegateDid?: string;
299
- };
300
-
301
- /**
302
- * The main Web5 API interface. It manages the creation of a DID if needed, the connection to the
303
- * local DWN and all the web5 main foundational APIs such as VC, syncing, etc.
304
- */
305
- export class Web5 {
306
- /**
307
- * A {@link Web5Agent} instance that handles DIDs, DWNs and VCs requests. The agent manages the
308
- * user keys and identities, and is responsible to sign and verify messages.
309
- */
310
- agent: Web5Agent;
311
-
312
- /** Exposed instance to the DID APIs, allow users to create and resolve DIDs */
313
- did: DidApi;
314
-
315
- /** Internal DWN API instance. Use {@link Web5.using} for protocol-scoped access. */
316
- private _dwn: DwnApi;
317
-
318
- /** Exposed instance to the VC APIs, allow users to issue, present and verify VCs */
319
- vc: VcApi;
320
-
321
- constructor({ agent, connectedDid, delegateDid }: Web5Params) {
322
- this.agent = agent;
323
- this.did = new DidApi({ agent, connectedDid });
324
- this._dwn = new DwnApi({ agent, connectedDid, delegateDid });
325
- this.vc = new VcApi({ agent, connectedDid });
326
- }
327
-
328
- /**
329
- * Returns a {@link TypedWeb5} instance scoped to the given protocol.
330
- *
331
- * This is the **primary developer interface** for interacting with
332
- * protocol-backed records. It auto-injects the protocol URI, protocolPath,
333
- * and schema into every operation, and provides compile-time path
334
- * autocompletion plus typed data payloads via the schema map.
335
- *
336
- * @param protocol - A typed protocol created via `defineProtocol()`.
337
- * @returns A `TypedWeb5` instance bound to the given protocol.
338
- *
339
- * @example
340
- * ```ts
341
- * const social = web5.using(SocialProtocol);
342
- *
343
- * await social.configure();
344
- *
345
- * const { record } = await social.records.write('friend', {
346
- * data: { did: 'did:example:alice', alias: 'Alice' },
347
- * });
348
- *
349
- * const { records } = await social.records.query('friend');
350
- * ```
351
- */
352
- public using<D extends ProtocolDefinition, M extends SchemaMap>(
353
- protocol: TypedProtocol<D, M>,
354
- ): TypedWeb5<D, M> {
355
- return new TypedWeb5<D, M>(this._dwn, protocol);
356
- }
357
-
358
- /**
359
- * Creates a lightweight, read-only Web5 instance for querying public DWN data.
360
- *
361
- * No identity, vault, password, or signing keys are required. The returned
362
- * API supports querying and reading published records and protocols from any
363
- * remote DWN, using **unsigned** (anonymous) DWN messages.
364
- *
365
- * @param options - Optional configuration overrides.
366
- * @returns A {@link Web5AnonymousApi} with a read-only `dwn` property.
367
- *
368
- * @example
369
- * ```ts
370
- * const { dwn } = Web5.anonymous();
371
- *
372
- * const { records } = await dwn.records.query({
373
- * from: 'did:dht:alice...',
374
- * filter: { protocol: 'https://social.example/posts', protocolPath: 'post' },
375
- * });
376
- *
377
- * for (const record of records) {
378
- * console.log(record.id, await record.data.text());
379
- * }
380
- * ```
381
- *
382
- * @beta
383
- */
384
- static anonymous(options?: Web5AnonymousOptions): Web5AnonymousApi {
385
- const didResolver = new UniversalResolver({
386
- didResolvers : options?.didResolvers ?? [DidDht, DidJwk, DidKey, DidWeb],
387
- cache : new DidResolverCacheMemory(),
388
- });
389
-
390
- const rpcClient = new Web5RpcClient();
391
- const anonymousDwn = new AnonymousDwnApi({ didResolver, rpcClient });
392
-
393
- return {
394
- dwn: new DwnReaderApi(anonymousDwn),
395
- };
396
- }
397
-
398
- /**
399
- * Connects to a {@link Web5Agent}. Defaults to creating a local {@link Web5UserAgent} if one
400
- * isn't provided.
401
- *
402
- * If `walletConnectOptions` are provided, a WalletConnect flow will be initiated to import a delegated DID from an external wallet.
403
- * If there is a failure at any point during connecting and processing grants, all created DIDs and Identities as well as the provided grants
404
- * will be cleaned up and an error thrown. This allows for subsequent Connect attempts to be made without any errors.
405
- *
406
- * @param options - Optional overrides that can be provided when calling {@link Web5.connect}.
407
- * @returns A promise that resolves to a {@link Web5} instance and the connected DID.
408
- */
409
- static async connect({
410
- agent,
411
- agentVault,
412
- connectedDid,
413
- password,
414
- recoveryPhrase,
415
- sync,
416
- techPreview,
417
- didCreateOptions,
418
- registration,
419
- walletConnectOptions,
420
- }: Web5ConnectOptions = {}): Promise<Web5ConnectResult> {
421
- let delegateDid: string | undefined;
422
- if (agent === undefined) {
423
- let registerSync = false;
424
- // A custom Web5Agent implementation was not specified, so use default managed user agent.
425
- const userAgent = await Web5UserAgent.create({ agentVault });
426
- agent = userAgent;
427
-
428
- // Warn the developer and application user of the security risks of using a static password.
429
- if (password === undefined) {
430
- password = 'insecure-static-phrase';
431
- console.warn(
432
- '%cSECURITY WARNING:%c ' +
433
- 'You have not set a password, which defaults to a static, guessable value. ' +
434
- 'This significantly compromises the security of your data. ' +
435
- 'Please configure a secure, unique password.',
436
- 'font-weight: bold; color: red;',
437
- 'font-weight: normal; color: inherit;'
438
- );
439
- }
440
-
441
- // Use the specified DWN endpoints or the latest TBD hosted DWN
442
- const serviceEndpointNodes = techPreview?.dwnEndpoints ?? didCreateOptions?.dwnEndpoints ?? ['https://enbox-dwn.fly.dev'];
443
-
444
- // Initialize, if necessary, and start the agent.
445
- if (await userAgent.firstLaunch()) {
446
- recoveryPhrase = await userAgent.initialize({ password, recoveryPhrase, dwnEndpoints: serviceEndpointNodes });
447
- }
448
- await userAgent.start({ password });
449
- // Attempt to retrieve the connected Identity if it exists.
450
- const connectedIdentity: BearerIdentity = await userAgent.identity.connectedIdentity();
451
- let identity: BearerIdentity;
452
- let connectedProtocols: string[] = [];
453
- if (connectedIdentity) {
454
- // if a connected identity is found, use it
455
- // TODO: In the future, implement a way to re-connect an already connected identity and apply additional grants/protocols
456
- identity = connectedIdentity;
457
- } else if (walletConnectOptions) {
458
- if (sync === 'off') {
459
- // Currently we require sync to be enabled when using WalletConnect
460
- // This is to ensure a connected app is not in a disjointed state from any other clients/app using the connectedDid
461
- throw new Error('Sync must not be disabled when using WalletConnect');
462
- }
463
-
464
- // Since we are connecting a new identity, we will want to register sync for the connectedDid
465
- registerSync = true;
466
-
467
- // No connected identity found and connectOptions are provided, attempt to import a delegated DID from an external wallet
468
- try {
469
- const { permissionRequests, ...connectOptions } = walletConnectOptions;
470
- const walletPermissionRequests = permissionRequests.map(
471
- ({ protocolDefinition, permissions }) =>
472
- WalletConnect.createPermissionRequestForProtocol({
473
- definition : protocolDefinition,
474
- permissions : permissions ?? [
475
- 'read', 'write', 'delete', 'query', 'subscribe',
476
- ],
477
- })
478
- );
479
-
480
- const { delegatePortableDid, connectedDid, delegateGrants } = await WalletConnect.initClient({
481
- ...connectOptions,
482
- permissionRequests: walletPermissionRequests,
483
- });
484
-
485
- // Import the delegated DID as an Identity in the User Agent.
486
- // Setting the connectedDID in the metadata applies a relationship between the signer identity and the one it is impersonating.
487
- identity = await userAgent.identity.import({ portableIdentity: {
488
- portableDid : delegatePortableDid,
489
- metadata : {
490
- connectedDid,
491
- name : 'Default',
492
- uri : delegatePortableDid.uri,
493
- tenant : agent.agentDid.uri,
494
- }
495
- } });
496
-
497
- // Attempts to process the connected grants to be used by the delegateDID
498
- // If the process fails, we want to clean up the identity
499
- // the connected grants will return a de-duped array of protocol URIs that are used to register sync for those protocols
500
- connectedProtocols = await this.processConnectedGrants({ agent, delegateDid: delegatePortableDid.uri, grants: delegateGrants });
501
- } catch (error:any) {
502
- // clean up the DID and Identity if import fails and throw
503
- // TODO: Implement the ability to purge all of our messages as a tenant
504
- await this.cleanUpIdentity({ identity, userAgent });
505
- throw new Error(`Failed to connect to wallet: ${error.message}`);
506
- }
507
- } else {
508
- // No connected (WalletConnect) identity and no walletConnectOptions provided.
509
- // Look for an existing local identity, or create one on first use.
510
- const identities = await userAgent.identity.list();
511
-
512
- if (identities.length === 0) {
513
- registerSync = true;
514
-
515
- // First use — generate a new Identity for the end-user.
516
- identity = await userAgent.identity.create({
517
- didMethod : 'dht',
518
- metadata : { name: 'Default' },
519
- didOptions : {
520
- services: [
521
- {
522
- id : 'dwn',
523
- type : 'DecentralizedWebNode',
524
- serviceEndpoint : serviceEndpointNodes,
525
- enc : '#enc',
526
- sig : '#sig',
527
- }
528
- ],
529
- verificationMethods: [
530
- {
531
- algorithm : 'Ed25519',
532
- id : 'sig',
533
- purposes : ['assertionMethod', 'authentication']
534
- },
535
- {
536
- algorithm : 'X25519',
537
- id : 'enc',
538
- purposes : ['keyAgreement']
539
- }
540
- ]
541
- }
542
- });
543
-
544
- } else {
545
- // Reconnecting — use the first local identity. When the agent manages
546
- // multiple identities (e.g. created via agent.identity.create()), the
547
- // first one returned by the store is used as the default for connect().
548
- identity = identities[0];
549
- }
550
- }
551
-
552
- // If the stored identity has a connected DID, use it as the connected DID, otherwise use the identity's DID.
553
- connectedDid = identity.metadata.connectedDid ?? identity.did.uri;
554
- // If the stored identity has a connected DID, use the identity DID as the delegated DID, otherwise it is undefined.
555
- delegateDid = identity.metadata.connectedDid ? identity.did.uri : undefined;
556
- if (registration !== undefined) {
557
- const updatedTokens: Record<string, RegistrationTokenData> = {
558
- ...(registration.registrationTokens ?? {}),
559
- };
560
-
561
- try {
562
- for (const dwnEndpoint of serviceEndpointNodes) {
563
- const serverInfo = await userAgent.rpc.getServerInfo(dwnEndpoint);
564
-
565
- if (serverInfo.registrationRequirements.length === 0) {
566
- continue;
567
- }
568
-
569
- // Deduplicate DIDs to register.
570
- const didsToRegister = [agent.agentDid.uri, connectedDid]
571
- .filter((did, i, arr): did is string => arr.indexOf(did) === i);
572
-
573
- const hasProviderAuth = serverInfo.registrationRequirements.includes('provider-auth-v0')
574
- && serverInfo.providerAuth !== undefined;
575
-
576
- if (hasProviderAuth && registration.onProviderAuthRequired) {
577
- // --- Provider Auth Path ---
578
- let tokenData = updatedTokens[dwnEndpoint];
579
-
580
- // Refresh expired tokens.
581
- if (tokenData?.expiresAt !== undefined && tokenData.expiresAt < Date.now()) {
582
- if (tokenData.refreshUrl && tokenData.refreshToken) {
583
- const refreshed = await DwnRegistrar.refreshRegistrationToken(
584
- tokenData.refreshUrl, tokenData.refreshToken,
585
- );
586
- tokenData = {
587
- registrationToken : refreshed.registrationToken,
588
- refreshToken : refreshed.refreshToken,
589
- expiresAt : refreshed.expiresIn !== undefined
590
- ? Date.now() + (refreshed.expiresIn * 1000) : undefined,
591
- tokenUrl : tokenData.tokenUrl,
592
- refreshUrl : tokenData.refreshUrl,
593
- };
594
- updatedTokens[dwnEndpoint] = tokenData;
595
- } else {
596
- tokenData = undefined;
597
- }
598
- }
599
-
600
- // Run the auth flow if no valid token exists.
601
- if (tokenData === undefined) {
602
- const state = crypto.randomUUID();
603
- const providerAuth = serverInfo.providerAuth!;
604
- const separator = providerAuth.authorizeUrl.includes('?') ? '&' : '?';
605
- const authorizeUrl = `${providerAuth.authorizeUrl}${separator}`
606
- + `redirect_uri=${encodeURIComponent(dwnEndpoint)}`
607
- + `&state=${encodeURIComponent(state)}`;
608
-
609
- const authResult = await registration.onProviderAuthRequired({
610
- authorizeUrl,
611
- dwnEndpoint,
612
- state,
613
- });
614
-
615
- if (authResult.state !== state) {
616
- throw new Error('Provider auth state mismatch — possible CSRF attack.');
617
- }
618
-
619
- const tokenResponse = await DwnRegistrar.exchangeAuthCode(
620
- providerAuth.tokenUrl, authResult.code, dwnEndpoint,
621
- );
622
-
623
- tokenData = {
624
- registrationToken : tokenResponse.registrationToken,
625
- refreshToken : tokenResponse.refreshToken,
626
- expiresAt : tokenResponse.expiresIn !== undefined
627
- ? Date.now() + (tokenResponse.expiresIn * 1000) : undefined,
628
- tokenUrl : providerAuth.tokenUrl,
629
- refreshUrl : providerAuth.refreshUrl,
630
- };
631
- updatedTokens[dwnEndpoint] = tokenData;
632
- }
633
-
634
- // Register each DID using the provider auth token.
635
- for (const did of didsToRegister) {
636
- await DwnRegistrar.registerTenantWithToken(
637
- dwnEndpoint, did, tokenData.registrationToken,
638
- );
639
- }
640
-
641
- } else {
642
- // --- Default Path (PoW / general registration) ---
643
- for (const did of didsToRegister) {
644
- await DwnRegistrar.registerTenant(dwnEndpoint, did);
645
- }
646
- }
647
- }
648
-
649
- // Notify app of updated tokens for persistence.
650
- if (registration.onRegistrationTokens) {
651
- registration.onRegistrationTokens(updatedTokens);
652
- }
653
-
654
- registration.onSuccess();
655
- } catch (error) {
656
- registration.onFailure(error);
657
- }
658
- }
659
-
660
- // Enable sync, unless explicitly disabled.
661
- if (sync !== 'off') {
662
- // First, register the user identity for sync.
663
- // The connected protocols are used to register sync for only a subset of protocols from the connectedDid's DWN
664
-
665
- if (registerSync) {
666
- await userAgent.sync.registerIdentity({
667
- did : connectedDid,
668
- options : {
669
- delegateDid,
670
- protocols: connectedProtocols
671
- }
672
- });
673
-
674
- if (walletConnectOptions !== undefined) {
675
- // If we are using WalletConnect, we should do a one-shot sync to pull down any messages that are associated with the connectedDid
676
- await userAgent.sync.sync('pull');
677
- }
678
- }
679
-
680
- // Enable sync using the specified interval or default.
681
- // When sync is unset (undefined), default to live mode.
682
- // When sync is an interval string (e.g. '2m', '30s'), use poll mode with that interval.
683
- const syncMode = sync === undefined ? 'live' : 'poll';
684
- const syncInterval = sync ?? (syncMode === 'live' ? '5m' : '2m');
685
- userAgent.sync.startSync({ mode: syncMode, interval: syncInterval })
686
- .catch((error: any) => {
687
- console.error(`Sync failed: ${error}`);
688
- });
689
- }
690
- }
691
-
692
- const web5 = new Web5({ agent, connectedDid, delegateDid });
693
-
694
- return { web5, did: connectedDid, delegateDid, recoveryPhrase };
695
- }
696
-
697
- /**
698
- * Cleans up the DID, Keys and Identity. Primarily used by a failed WalletConnect import.
699
- * Does not throw on error, but logs to console.
700
- */
701
- private static async cleanUpIdentity({ identity, userAgent }:{
702
- identity: BearerIdentity,
703
- userAgent: Web5UserAgent
704
- }): Promise<void> {
705
- try {
706
- // Delete the DID and the Associated Keys
707
- await userAgent.did.delete({
708
- didUri : identity.did.uri,
709
- tenant : identity.metadata.tenant,
710
- deleteKey : true,
711
- });
712
- } catch (error: any) {
713
- console.error(`Failed to delete DID ${identity.did.uri}: ${error.message}`);
714
- }
715
-
716
- try {
717
- // Delete the Identity
718
- await userAgent.identity.delete({ didUri: identity.did.uri });
719
- } catch (error: any) {
720
- console.error(`Failed to delete Identity ${identity.metadata.name}: ${error.message}`);
721
- }
722
- }
723
-
724
- /**
725
- * A static method to process connected grants for a delegate DID.
726
- *
727
- * This will store the grants as the DWN owner to be used later when impersonating the connected DID.
728
- */
729
- static async processConnectedGrants({ grants, agent, delegateDid }: {
730
- grants: DwnDataEncodedRecordsWriteMessage[],
731
- agent: Web5Agent,
732
- delegateDid: string,
733
- }): Promise<string[]> {
734
- const connectedProtocols = new Set<string>();
735
- for (const grantMessage of grants) {
736
- // use the delegateDid as the connectedDid of the grant as they do not yet support impersonation/delegation
737
- const grant = PermissionGrant.parse({ connectedDid: delegateDid, agent, message: grantMessage });
738
- // store the grant as the owner of the DWN, this will allow the delegateDid to use the grant when impersonating the connectedDid
739
- const { status } = await grant.store(true);
740
- if (status.code !== 202) {
741
- throw new Error(`AgentDwnApi: Failed to process connected grant: ${status.detail}`);
742
- }
743
-
744
- const protocol = (grant.scope as DwnMessagesPermissionScope | DwnRecordsPermissionScope).protocol;
745
- if (protocol) {
746
- connectedProtocols.add(protocol);
747
- }
748
- }
749
-
750
- // currently we return a de-duped set of protocols represented by these grants, this is used to register protocols for sync
751
- // we expect that any connected protocols will include MessagesSync and MessagesRead grants that will allow it to sync
752
- return [...connectedProtocols];
753
- }
754
- }