@enbox/auth 0.5.0 → 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 (90) hide show
  1. package/dist/esm/auth-manager.js +240 -171
  2. package/dist/esm/auth-manager.js.map +1 -1
  3. package/dist/esm/connect/import.js +131 -0
  4. package/dist/esm/connect/import.js.map +1 -0
  5. package/dist/esm/connect/lifecycle.js +378 -0
  6. package/dist/esm/connect/lifecycle.js.map +1 -0
  7. package/dist/esm/connect/local.js +105 -0
  8. package/dist/esm/connect/local.js.map +1 -0
  9. package/dist/esm/connect/restore.js +117 -0
  10. package/dist/esm/connect/restore.js.map +1 -0
  11. package/dist/esm/connect/wallet.js +80 -0
  12. package/dist/esm/connect/wallet.js.map +1 -0
  13. package/dist/esm/{flows/dwn-discovery.js → discovery.js} +2 -2
  14. package/dist/esm/discovery.js.map +1 -0
  15. package/dist/esm/index.js +13 -19
  16. package/dist/esm/index.js.map +1 -1
  17. package/dist/esm/permissions.js +41 -0
  18. package/dist/esm/permissions.js.map +1 -0
  19. package/dist/esm/{flows/dwn-registration.js → registration.js} +2 -2
  20. package/dist/esm/registration.js.map +1 -0
  21. package/dist/esm/types.js +4 -0
  22. package/dist/esm/types.js.map +1 -1
  23. package/dist/esm/wallet-connect-client.js +188 -0
  24. package/dist/esm/wallet-connect-client.js.map +1 -0
  25. package/dist/types/auth-manager.d.ts +89 -11
  26. package/dist/types/auth-manager.d.ts.map +1 -1
  27. package/dist/types/connect/import.d.ts +25 -0
  28. package/dist/types/connect/import.d.ts.map +1 -0
  29. package/dist/types/connect/lifecycle.d.ts +199 -0
  30. package/dist/types/connect/lifecycle.d.ts.map +1 -0
  31. package/dist/types/connect/local.d.ts +23 -0
  32. package/dist/types/connect/local.d.ts.map +1 -0
  33. package/dist/types/connect/restore.d.ts +18 -0
  34. package/dist/types/connect/restore.d.ts.map +1 -0
  35. package/dist/types/connect/wallet.d.ts +21 -0
  36. package/dist/types/connect/wallet.d.ts.map +1 -0
  37. package/dist/types/{flows/dwn-discovery.d.ts → discovery.d.ts} +3 -3
  38. package/dist/types/discovery.d.ts.map +1 -0
  39. package/dist/types/index.d.ts +14 -19
  40. package/dist/types/index.d.ts.map +1 -1
  41. package/dist/types/permissions.d.ts +18 -0
  42. package/dist/types/permissions.d.ts.map +1 -0
  43. package/dist/types/{flows/dwn-registration.d.ts → registration.d.ts} +2 -2
  44. package/dist/types/registration.d.ts.map +1 -0
  45. package/dist/types/types.d.ts +154 -4
  46. package/dist/types/types.d.ts.map +1 -1
  47. package/dist/types/wallet-connect-client.d.ts +86 -0
  48. package/dist/types/wallet-connect-client.d.ts.map +1 -0
  49. package/package.json +9 -5
  50. package/src/auth-manager.ts +258 -191
  51. package/src/connect/import.ts +148 -0
  52. package/src/connect/lifecycle.ts +487 -0
  53. package/src/connect/local.ts +116 -0
  54. package/src/connect/restore.ts +133 -0
  55. package/src/connect/wallet.ts +89 -0
  56. package/src/{flows/dwn-discovery.ts → discovery.ts} +4 -3
  57. package/src/index.ts +20 -19
  58. package/src/permissions.ts +48 -0
  59. package/src/{flows/dwn-registration.ts → registration.ts} +2 -2
  60. package/src/types.ts +171 -4
  61. package/src/wallet-connect-client.ts +275 -0
  62. package/dist/esm/flows/dwn-discovery.js.map +0 -1
  63. package/dist/esm/flows/dwn-registration.js.map +0 -1
  64. package/dist/esm/flows/import-identity.js +0 -177
  65. package/dist/esm/flows/import-identity.js.map +0 -1
  66. package/dist/esm/flows/local-connect.js +0 -158
  67. package/dist/esm/flows/local-connect.js.map +0 -1
  68. package/dist/esm/flows/session-restore.js +0 -125
  69. package/dist/esm/flows/session-restore.js.map +0 -1
  70. package/dist/esm/flows/wallet-connect.js +0 -200
  71. package/dist/esm/flows/wallet-connect.js.map +0 -1
  72. package/dist/esm/vault/vault-manager.js +0 -95
  73. package/dist/esm/vault/vault-manager.js.map +0 -1
  74. package/dist/types/flows/dwn-discovery.d.ts.map +0 -1
  75. package/dist/types/flows/dwn-registration.d.ts.map +0 -1
  76. package/dist/types/flows/import-identity.d.ts +0 -35
  77. package/dist/types/flows/import-identity.d.ts.map +0 -1
  78. package/dist/types/flows/local-connect.d.ts +0 -31
  79. package/dist/types/flows/local-connect.d.ts.map +0 -1
  80. package/dist/types/flows/session-restore.d.ts +0 -29
  81. package/dist/types/flows/session-restore.d.ts.map +0 -1
  82. package/dist/types/flows/wallet-connect.d.ts +0 -44
  83. package/dist/types/flows/wallet-connect.d.ts.map +0 -1
  84. package/dist/types/vault/vault-manager.d.ts +0 -57
  85. package/dist/types/vault/vault-manager.d.ts.map +0 -1
  86. package/src/flows/import-identity.ts +0 -219
  87. package/src/flows/local-connect.ts +0 -192
  88. package/src/flows/session-restore.ts +0 -155
  89. package/src/flows/wallet-connect.ts +0 -226
  90. package/src/vault/vault-manager.ts +0 -89
package/src/types.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  * Public types for the authentication and identity management SDK.
4
4
  */
5
5
 
6
- import type { ConnectPermissionRequest, EnboxUserAgent, HdIdentityVault, LocalDwnStrategy, PortableIdentity } from '@enbox/agent';
6
+ import type { PortableDid } from '@enbox/dids';
7
+ import type { ConnectPermissionRequest, DwnDataEncodedRecordsWriteMessage, DwnProtocolDefinition, EnboxUserAgent, HdIdentityVault, LocalDwnStrategy, PortableIdentity } from '@enbox/agent';
7
8
 
8
9
  import type { PasswordProvider } from './password-provider.js';
9
10
 
@@ -210,6 +211,55 @@ export interface RegistrationOptions {
210
211
  persistTokens?: boolean;
211
212
  }
212
213
 
214
+ // ─── Connect Handler ─────────────────────────────────────────────
215
+
216
+ /**
217
+ * Result of a successful connect handler invocation.
218
+ *
219
+ * Contains the delegated credentials returned by the wallet.
220
+ * All connect handlers (browser popup, relay, CLI, etc.) must
221
+ * return this shape on success.
222
+ */
223
+ export interface ConnectResult {
224
+ /** The portable delegate DID (includes private keys). */
225
+ delegatePortableDid: PortableDid;
226
+
227
+ /** Permission grants for the requested protocols. */
228
+ delegateGrants: DwnDataEncodedRecordsWriteMessage[];
229
+
230
+ /** The DID of the identity the user approved (the wallet owner's DID). */
231
+ connectedDid: string;
232
+ }
233
+
234
+ /**
235
+ * A connect handler obtains delegated credentials from a wallet.
236
+ *
237
+ * Different environments provide different implementations:
238
+ * - **Browser**: popup + postMessage (`BrowserConnectHandler` from `@enbox/browser`)
239
+ * - **Relay**: QR/PIN relay flow (`WalletConnect.initClient` from `@enbox/auth`)
240
+ * - **CLI**: terminal QR/URL + polling (custom handler)
241
+ * - **Desktop**: native window management (custom handler)
242
+ *
243
+ * @example
244
+ * ```ts
245
+ * import { BrowserConnectHandler } from '@enbox/browser';
246
+ * const auth = await AuthManager.create({
247
+ * connectHandler: BrowserConnectHandler(),
248
+ * });
249
+ * ```
250
+ */
251
+ export interface ConnectHandler {
252
+ /**
253
+ * Obtain delegated credentials from a wallet.
254
+ *
255
+ * @param params.permissionRequests - Agent-level permission requests.
256
+ * @returns The delegate credentials, or `undefined` if the user denied.
257
+ */
258
+ requestAccess(params: {
259
+ permissionRequests: ConnectPermissionRequest[];
260
+ }): Promise<ConnectResult | undefined>;
261
+ }
262
+
213
263
  /** Options for {@link AuthManager.create}. */
214
264
  export interface AuthManagerOptions {
215
265
  /**
@@ -298,6 +348,26 @@ export interface AuthManagerOptions {
298
348
 
299
349
  /** DWN registration configuration. */
300
350
  registration?: RegistrationOptions;
351
+
352
+ /**
353
+ * Default connect handler for delegated connect flows.
354
+ *
355
+ * Used by `connect()` when the caller provides `protocols` (or other
356
+ * non-local-connect options) but does not pass a per-call handler.
357
+ *
358
+ * @example
359
+ * ```ts
360
+ * import { BrowserConnectHandler } from '@enbox/browser';
361
+ *
362
+ * const auth = await AuthManager.create({
363
+ * connectHandler: BrowserConnectHandler(),
364
+ * });
365
+ *
366
+ * // Later — uses the default handler automatically
367
+ * const session = await auth.connect({ protocols: [NotesProtocol] });
368
+ * ```
369
+ */
370
+ connectHandler?: ConnectHandler;
301
371
  }
302
372
 
303
373
  /** Options for {@link AuthManager.connect}. */
@@ -316,8 +386,101 @@ export interface LocalConnectOptions {
316
386
 
317
387
  /** Identity metadata. */
318
388
  metadata?: { name?: string };
389
+
390
+ /**
391
+ * Whether to create a default identity if none exist.
392
+ *
393
+ * - `false` (default) — Skip automatic identity creation. The session is
394
+ * returned with the **agent DID** as the connected DID and no identity
395
+ * metadata. Use this when the app manages identity creation separately
396
+ * (e.g. a web wallet with an explicit "Create Identity" flow after
397
+ * vault setup).
398
+ *
399
+ * - `true` — If no identities exist after vault initialisation, a new
400
+ * `did:dht` identity is created automatically. Use this when vault
401
+ * setup and identity creation are combined into a single step (e.g.
402
+ * Electrobun's create wizard).
403
+ *
404
+ * @default false
405
+ */
406
+ createIdentity?: boolean;
319
407
  }
320
408
 
409
+ // ─── DWeb Connect ────────────────────────────────────────────────
410
+
411
+ /**
412
+ * A protocol permission request in simplified form.
413
+ *
414
+ * Dapp developers can pass just a protocol definition (default permissions:
415
+ * `['read', 'write', 'query', 'subscribe']`), or an object with explicit
416
+ * permissions.
417
+ */
418
+ export type ProtocolRequest =
419
+ | DwnProtocolDefinition
420
+ | { definition: DwnProtocolDefinition; permissions: Permission[] };
421
+
422
+ /** Shorthand permission names for DWN protocol scopes. */
423
+ export type Permission = 'write' | 'read' | 'delete' | 'query' | 'subscribe' | 'configure';
424
+
425
+ /** Default permissions granted when only a protocol definition is provided. */
426
+ export const DEFAULT_PERMISSIONS: Permission[] = ['read', 'write', 'query', 'subscribe'];
427
+
428
+ /**
429
+ * Options for a handler-based (delegated) connect flow.
430
+ *
431
+ * Used when `connect()` delegates credential acquisition to a
432
+ * {@link ConnectHandler}. The handler is responsible for the
433
+ * environment-specific transport (popup, relay, CLI, etc.).
434
+ */
435
+ export interface HandlerConnectOptions {
436
+ /**
437
+ * Protocols to request access to.
438
+ *
439
+ * Each entry can be either a protocol definition (uses default permissions)
440
+ * or an object with `{ definition, permissions }` for explicit control.
441
+ *
442
+ * @example
443
+ * ```ts
444
+ * // Default permissions (read, write, query, subscribe)
445
+ * protocols: [NotesProtocol]
446
+ *
447
+ * // Explicit permissions
448
+ * protocols: [
449
+ * { definition: NotesProtocol, permissions: ['read', 'write'] },
450
+ * { definition: PhotosProtocol, permissions: ['read'] },
451
+ * ]
452
+ * ```
453
+ */
454
+ protocols?: ProtocolRequest[];
455
+
456
+ /**
457
+ * Connect handler for this call. Overrides the default handler set
458
+ * on `AuthManager.create()`.
459
+ */
460
+ connectHandler?: ConnectHandler;
461
+
462
+ /** Override manager default sync interval. */
463
+ sync?: SyncOption;
464
+ }
465
+
466
+ /**
467
+ * Unified options for {@link AuthManager.connect}.
468
+ *
469
+ * `connect()` routes to the appropriate flow based on the options:
470
+ *
471
+ * - **Handler-based connect** (dapps): triggered when `protocols` or
472
+ * `connectHandler` is provided. Delegates to the connect handler
473
+ * for credential acquisition.
474
+ *
475
+ * - **Local connect** (wallets / CLI): triggered when `password`,
476
+ * `createIdentity`, or `recoveryPhrase` is provided.
477
+ *
478
+ * In both cases, `connect()` first attempts to restore a previous session
479
+ * from storage. If a valid session exists, it is returned immediately
480
+ * without any user interaction.
481
+ */
482
+ export type ConnectOptions = HandlerConnectOptions | LocalConnectOptions;
483
+
321
484
  /** Options for {@link AuthManager.walletConnect}. */
322
485
  export interface WalletConnectOptions {
323
486
  /** Display name shown in the wallet during the connect flow. */
@@ -332,9 +495,10 @@ export interface WalletConnectOptions {
332
495
  /**
333
496
  * Protocol permission requests for the wallet connect flow.
334
497
  *
335
- * Each entry is a `ConnectPermissionRequest` from `@enbox/agent` containing
336
- * a `protocolDefinition` and `permissionScopes`. Use
337
- * `WalletConnect.createPermissionRequestForProtocol()` to build these.
498
+ * Each entry is a `ConnectPermissionRequest` containing a
499
+ * `protocolDefinition` and `permissionScopes`. Use
500
+ * `WalletConnect.createPermissionRequestForProtocol()` from `@enbox/auth`
501
+ * to build these.
338
502
  */
339
503
  permissionRequests: ConnectPermissionRequest[];
340
504
 
@@ -464,6 +628,9 @@ export interface StorageAdapter {
464
628
  /** The insecure default password used when none is provided. */
465
629
  export const INSECURE_DEFAULT_PASSWORD = 'insecure-static-phrase';
466
630
 
631
+ /** Default DWN endpoints for new identities when none are configured. */
632
+ export const DEFAULT_DWN_ENDPOINTS = ['https://enbox-dwn.fly.dev'];
633
+
467
634
  /**
468
635
  * Storage keys used by the auth manager for session persistence.
469
636
  * @internal
@@ -0,0 +1,275 @@
1
+ /**
2
+ * WalletConnect client — initiates the relay-mediated connect flow.
3
+ *
4
+ * Moved from `@enbox/agent/src/connect.ts` because `initClient` has zero
5
+ * coupling to agent internals (no vault, no key store, no DWN processing,
6
+ * no sync). Its only consumer is `auth/src/connect/wallet.ts`.
7
+ *
8
+ * The server-side counterpart (`EnboxConnectProtocol`) correctly stays in
9
+ * `@enbox/agent` because it uses `agent.processDwnRequest()`,
10
+ * `agent.sendDwnRequest()`, and `AgentPermissionsApi`.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ import type { ConnectPermissionRequest, DwnPermissionScope, DwnProtocolDefinition } from '@enbox/agent';
16
+ import type { ConnectPushedResponse, EnboxConnectResponse } from '@enbox/agent';
17
+
18
+ import { CryptoUtils } from '@enbox/crypto';
19
+ import { DidJwk } from '@enbox/dids';
20
+ import { Convert, logger } from '@enbox/common';
21
+ import { DwnInterfaceName, DwnMethodName } from '@enbox/dwn-sdk-js';
22
+ import { EnboxConnectProtocol, pollWithTtl } from '@enbox/agent';
23
+
24
+ /**
25
+ * Options for initiating a wallet connect flow (remote, relay-mediated).
26
+ *
27
+ * This is the agent-level options type used by `initClient()`. The auth-level
28
+ * `WalletConnectOptions` (in `types.ts`) wraps this with additional fields
29
+ * like `sync`.
30
+ */
31
+ export type WalletConnectClientOptions = {
32
+ /** The user-friendly name of the app, displayed in the wallet consent UI. */
33
+ displayName: string;
34
+
35
+ /** The URL of the connect server which relays messages between the app and wallet. */
36
+ connectServerUrl: string;
37
+
38
+ /**
39
+ * The URI of the wallet app. Query params (`request_uri`, `encryption_key`)
40
+ * are appended and passed to `onWalletUriReady`.
41
+ * @example `enbox://connect` or `http://localhost:3000/`
42
+ */
43
+ walletUri: string;
44
+
45
+ /**
46
+ * The protocols of permissions requested, along with the definition and
47
+ * permission scopes for each protocol. The key is the protocol URL and
48
+ * the value is an object with the protocol definition and the permission scopes.
49
+ */
50
+ permissionRequests: ConnectPermissionRequest[];
51
+
52
+ /**
53
+ * Called with the wallet URI including query params (`request_uri`, `encryption_key`).
54
+ * The app should render this as a QR code or use it as a deep link.
55
+ *
56
+ * @param uri - The wallet URI with connect payload.
57
+ */
58
+ onWalletUriReady: (uri: string) => void;
59
+
60
+ /**
61
+ * Called to collect the PIN from the user. The PIN is used as AAD
62
+ * when decrypting the connect response from the relay.
63
+ *
64
+ * @returns A promise that resolves to the PIN as a string.
65
+ */
66
+ validatePin: () => Promise<string>;
67
+ };
68
+
69
+ import type { Permission } from './types.js';
70
+
71
+ /**
72
+ * The options for creating a permission request for a given protocol.
73
+ */
74
+ export type ProtocolPermissionOptions = {
75
+ /** The protocol definition for the protocol being requested */
76
+ definition: DwnProtocolDefinition;
77
+
78
+ /** The permissions being requested for the protocol */
79
+ permissions: Permission[];
80
+ };
81
+
82
+ /**
83
+ * Initiates the wallet connect process. Used when a client wants to obtain
84
+ * a did from a provider.
85
+ */
86
+ async function initClient({
87
+ displayName,
88
+ connectServerUrl,
89
+ walletUri,
90
+ permissionRequests,
91
+ onWalletUriReady,
92
+ validatePin,
93
+ }: WalletConnectClientOptions): Promise<{
94
+ delegateGrants: EnboxConnectResponse['delegateGrants'];
95
+ delegatePortableDid: EnboxConnectResponse['delegatePortableDid'];
96
+ connectedDid: string;
97
+ } | undefined> {
98
+ // ephemeral client did for ECDH, signing, verification
99
+ const clientDid = await DidJwk.create();
100
+
101
+ // TODO: properly implement PKCE. this implementation is lacking server side validations and more.
102
+ // https://github.com/enboxorg/enbox/issues/829
103
+ // Derive the code challenge based on the code verifier
104
+ // const { codeChallengeBytes, codeChallengeBase64Url } =
105
+ // await Oidc.generateCodeChallenge();
106
+ const encryptionKey = CryptoUtils.randomBytes(32);
107
+
108
+ // Build callback URL for the connect request.
109
+ const callbackEndpoint = EnboxConnectProtocol.buildConnectUrl({
110
+ baseURL : connectServerUrl,
111
+ endpoint : 'callback',
112
+ });
113
+
114
+ // Build the connect request.
115
+ const request = await EnboxConnectProtocol.createConnectRequest({
116
+ clientDid : clientDid.uri,
117
+ callbackUrl : callbackEndpoint,
118
+ permissionRequests : permissionRequests,
119
+ appName : displayName,
120
+ });
121
+
122
+ // Sign the request as a JWT.
123
+ const requestJwt = await EnboxConnectProtocol.signJwt({
124
+ did : clientDid,
125
+ data : request as unknown as Record<string, unknown>,
126
+ });
127
+
128
+ if (!requestJwt) {
129
+ throw new Error('Unable to sign requestObject');
130
+ }
131
+ // Encrypt the request JWT with the symmetric key.
132
+ const requestObjectJwe = await EnboxConnectProtocol.encryptRequest({
133
+ jwt: requestJwt,
134
+ encryptionKey,
135
+ });
136
+
137
+ const pushedAuthorizationRequestEndpoint = EnboxConnectProtocol.buildConnectUrl({
138
+ baseURL : connectServerUrl,
139
+ endpoint : 'pushedAuthorizationRequest',
140
+ });
141
+
142
+ const parResponse = await fetch(pushedAuthorizationRequestEndpoint, {
143
+ body : JSON.stringify({ request: requestObjectJwe }),
144
+ method : 'POST',
145
+ headers : {
146
+ 'Content-Type': 'application/json',
147
+ },
148
+ signal: AbortSignal.timeout(30_000),
149
+ });
150
+
151
+ if (!parResponse.ok) {
152
+ throw new Error(`${parResponse.status}: ${parResponse.statusText}`);
153
+ }
154
+
155
+ const parData: ConnectPushedResponse = await parResponse.json();
156
+
157
+ // a deeplink to a compatible wallet. if the wallet scans this link it should receive
158
+ // a route to its Connect provider flow and the params of where to fetch the auth request.
159
+ logger.log(`Wallet URI: ${walletUri}`);
160
+ const generatedWalletUri = new URL(walletUri);
161
+ generatedWalletUri.searchParams.set('request_uri', parData.request_uri);
162
+ generatedWalletUri.searchParams.set(
163
+ 'encryption_key',
164
+ Convert.uint8Array(encryptionKey).toBase64Url()
165
+ );
166
+
167
+ // call user's callback so they can send the URI to the wallet as they see fit
168
+ onWalletUriReady(generatedWalletUri.toString());
169
+
170
+ const tokenUrl = EnboxConnectProtocol.buildConnectUrl({
171
+ baseURL : connectServerUrl,
172
+ endpoint : 'token',
173
+ tokenParam : request.state,
174
+ });
175
+
176
+ // subscribe to receiving a response from the wallet with default TTL. receive ciphertext of {@link EnboxConnectResponse}
177
+ const authResponse = await pollWithTtl(() => fetch(tokenUrl, { signal: AbortSignal.timeout(30_000) }));
178
+
179
+ if (authResponse) {
180
+ const jwe = await authResponse?.text();
181
+
182
+ // Get the PIN from the user and use it as AAD to decrypt.
183
+ const pin = await validatePin();
184
+ const jwt = await EnboxConnectProtocol.decryptResponse(clientDid, jwe, pin);
185
+ const verifiedResponse = (await EnboxConnectProtocol.verifyJwt({
186
+ jwt,
187
+ })) as unknown as EnboxConnectResponse;
188
+
189
+ return {
190
+ delegateGrants : verifiedResponse.delegateGrants,
191
+ delegatePortableDid : verifiedResponse.delegatePortableDid,
192
+ connectedDid : verifiedResponse.providerDid,
193
+ };
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Creates a set of Dwn Permission Scopes to request for a given protocol.
199
+ *
200
+ * If no permissions are provided, the default is to request all relevant record permissions (write, read, delete, query, subscribe).
201
+ * 'configure' is not included by default, as this gives the application a lot of control over the protocol.
202
+ */
203
+ function createPermissionRequestForProtocol({ definition, permissions }: ProtocolPermissionOptions): ConnectPermissionRequest {
204
+ const requests: DwnPermissionScope[] = [];
205
+
206
+ // Add the ability to query for the specific protocol
207
+ requests.push({
208
+ protocol : definition.protocol,
209
+ interface : DwnInterfaceName.Protocols,
210
+ method : DwnMethodName.Query,
211
+ });
212
+
213
+ // A Messages.Read grant is a unified scope that covers MessagesRead, MessagesSync, and MessagesSubscribe.
214
+ // This single grant enables sync and real-time subscriptions for the protocol.
215
+ requests.push({
216
+ protocol : definition.protocol,
217
+ interface : DwnInterfaceName.Messages,
218
+ method : DwnMethodName.Read,
219
+ });
220
+
221
+ // We also request any additional permissions the user has requested for this protocol
222
+ for (const permission of permissions) {
223
+ switch (permission) {
224
+ case 'write':
225
+ requests.push({
226
+ protocol : definition.protocol,
227
+ interface : DwnInterfaceName.Records,
228
+ method : DwnMethodName.Write,
229
+ });
230
+ break;
231
+ case 'read':
232
+ requests.push({
233
+ protocol : definition.protocol,
234
+ interface : DwnInterfaceName.Records,
235
+ method : DwnMethodName.Read,
236
+ });
237
+ break;
238
+ case 'delete':
239
+ requests.push({
240
+ protocol : definition.protocol,
241
+ interface : DwnInterfaceName.Records,
242
+ method : DwnMethodName.Delete,
243
+ });
244
+ break;
245
+ case 'query':
246
+ requests.push({
247
+ protocol : definition.protocol,
248
+ interface : DwnInterfaceName.Records,
249
+ method : DwnMethodName.Query,
250
+ });
251
+ break;
252
+ case 'subscribe':
253
+ requests.push({
254
+ protocol : definition.protocol,
255
+ interface : DwnInterfaceName.Records,
256
+ method : DwnMethodName.Subscribe,
257
+ });
258
+ break;
259
+ case 'configure':
260
+ requests.push({
261
+ protocol : definition.protocol,
262
+ interface : DwnInterfaceName.Protocols,
263
+ method : DwnMethodName.Configure,
264
+ });
265
+ break;
266
+ }
267
+ }
268
+
269
+ return {
270
+ protocolDefinition : definition,
271
+ permissionScopes : requests,
272
+ };
273
+ }
274
+
275
+ export const WalletConnect = { initClient, createPermissionRequestForProtocol };
@@ -1 +0,0 @@
1
- {"version":3,"file":"dwn-discovery.js","sourceRoot":"","sources":["../../../src/flows/dwn-discovery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;;;;;;;;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,8BAA8B,EAAE,MAAM,cAAc,CAAC;AAGxH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG3C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,8BAA8B;IAC5C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O,EAAE,CAAC;gBAC1C,MAAM,mBAAmB,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;YACpD,CAAC;YAED,oEAAoE;YACpE,IAAI,YAAY,CAAC,oBAAoB,EAAE,CAAC;gBACtC,YAAY,CAAC,oBAAoB,CAAC,aAAa,CAAC,CAAC;YACnD,CAAC;YAED,YAAY,CAAC,SAAS,EAAE,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAc,EAAE,CAAC;YACxB,YAAY,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;CAAA;AAED,qEAAqE;AAErE;;;;;;;GAOG;AACH,MAAM,UAAgB,qBAAqB,CACzC,OAAuB;;QAEvB,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,mBAAmB,CAAC,CAAC;YAChE,IAAI,CAAC,GAAG,EAAE,CAAC;gBAAC,OAAO,EAAE,CAAC;YAAC,CAAC;YACxB,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAA0C,CAAC;QAClE,CAAC;QAAC,WAAM,CAAC;YACP,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CAAA;AAED;;;GAGG;AACH,MAAM,UAAgB,mBAAmB,CACvC,OAAuB,EACvB,MAA6C;;QAE7C,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,mBAAmB,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAC9E,CAAC;CAAA"}
@@ -1,177 +0,0 @@
1
- /**
2
- * Identity import flows.
3
- *
4
- * - Import from BIP-39 recovery phrase (re-derive vault + identity).
5
- * - Import from PortableIdentity JSON.
6
- * @module
7
- */
8
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
- return new (P || (P = Promise))(function (resolve, reject) {
11
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
- step((generator = generator.apply(thisArg, _arguments || [])).next());
15
- });
16
- };
17
- import { AuthSession } from '../identity-session.js';
18
- import { registerWithDwnEndpoints } from './dwn-registration.js';
19
- import { STORAGE_KEYS } from '../types.js';
20
- /**
21
- * Import (or recover) an identity from a BIP-39 recovery phrase.
22
- *
23
- * This re-initializes the vault with the given phrase and password,
24
- * recovering the agent DID and all derived keys.
25
- */
26
- export function importFromPhrase(ctx, options) {
27
- return __awaiter(this, void 0, void 0, function* () {
28
- var _a, _b, _c;
29
- const { userAgent, emitter, storage } = ctx;
30
- const { recoveryPhrase, password } = options;
31
- const sync = (_a = options.sync) !== null && _a !== void 0 ? _a : ctx.defaultSync;
32
- const dwnEndpoints = (_c = (_b = options.dwnEndpoints) !== null && _b !== void 0 ? _b : ctx.defaultDwnEndpoints) !== null && _c !== void 0 ? _c : ['https://enbox-dwn.fly.dev'];
33
- // Initialize the vault with the recovery phrase.
34
- // This re-derives the same agent DID and CEK from the mnemonic.
35
- if (yield userAgent.firstLaunch()) {
36
- yield userAgent.initialize({
37
- password,
38
- recoveryPhrase,
39
- dwnEndpoints,
40
- });
41
- }
42
- yield userAgent.start({ password });
43
- emitter.emit('vault-unlocked', {});
44
- // The recovery phrase re-derives the same agent DID,
45
- // but the user identity might not exist yet — create one if needed.
46
- const identities = yield userAgent.identity.list();
47
- let identity = identities[0];
48
- let isNewIdentity = false;
49
- if (!identity) {
50
- isNewIdentity = true;
51
- identity = yield userAgent.identity.create({
52
- didMethod: 'dht',
53
- metadata: { name: 'Default' },
54
- didOptions: {
55
- services: [
56
- {
57
- id: 'dwn',
58
- type: 'DecentralizedWebNode',
59
- serviceEndpoint: dwnEndpoints,
60
- enc: '#enc',
61
- sig: '#sig',
62
- }
63
- ],
64
- verificationMethods: [
65
- {
66
- algorithm: 'Ed25519',
67
- id: 'sig',
68
- purposes: ['assertionMethod', 'authentication'],
69
- },
70
- {
71
- algorithm: 'X25519',
72
- id: 'enc',
73
- purposes: ['keyAgreement'],
74
- },
75
- ],
76
- },
77
- });
78
- }
79
- const connectedDid = identity.did.uri;
80
- // Register with DWN endpoints (if registration options are provided).
81
- if (ctx.registration) {
82
- yield registerWithDwnEndpoints({
83
- userAgent: userAgent,
84
- dwnEndpoints,
85
- agentDid: userAgent.agentDid.uri,
86
- connectedDid,
87
- storage: storage,
88
- }, ctx.registration);
89
- }
90
- // Register and start sync.
91
- if (isNewIdentity && sync !== 'off') {
92
- yield userAgent.sync.registerIdentity({ did: connectedDid, options: { protocols: [] } });
93
- }
94
- if (sync !== 'off') {
95
- const syncMode = sync === undefined ? 'live' : 'poll';
96
- const syncInterval = sync !== null && sync !== void 0 ? sync : (syncMode === 'live' ? '5m' : '2m');
97
- userAgent.sync.startSync({ mode: syncMode, interval: syncInterval })
98
- .catch((err) => console.error('[@enbox/auth] Sync failed:', err));
99
- }
100
- yield storage.set(STORAGE_KEYS.PREVIOUSLY_CONNECTED, 'true');
101
- yield storage.set(STORAGE_KEYS.ACTIVE_IDENTITY, connectedDid);
102
- const identityInfo = {
103
- didUri: connectedDid,
104
- name: identity.metadata.name,
105
- };
106
- const session = new AuthSession({
107
- agent: userAgent,
108
- did: connectedDid,
109
- identity: identityInfo,
110
- });
111
- emitter.emit('identity-added', { identity: identityInfo });
112
- emitter.emit('session-start', {
113
- session: { did: connectedDid, identity: identityInfo },
114
- });
115
- return session;
116
- });
117
- }
118
- /**
119
- * Import an identity from a PortableIdentity JSON object.
120
- *
121
- * The portable identity contains the DID's private keys and metadata,
122
- * allowing it to be used on this device.
123
- */
124
- export function importFromPortable(ctx, options) {
125
- return __awaiter(this, void 0, void 0, function* () {
126
- var _a, _b, _c;
127
- const { userAgent, emitter, storage } = ctx;
128
- const sync = (_a = options.sync) !== null && _a !== void 0 ? _a : ctx.defaultSync;
129
- const identity = yield userAgent.identity.import({
130
- portableIdentity: options.portableIdentity,
131
- });
132
- const connectedDid = (_b = identity.metadata.connectedDid) !== null && _b !== void 0 ? _b : identity.did.uri;
133
- const delegateDid = identity.metadata.connectedDid ? identity.did.uri : undefined;
134
- // Register with DWN endpoints (if registration options are provided).
135
- // For portable imports, extract endpoints from the DID document's DWN service.
136
- if (ctx.registration) {
137
- const dwnEndpoints = (_c = ctx.defaultDwnEndpoints) !== null && _c !== void 0 ? _c : ['https://enbox-dwn.fly.dev'];
138
- yield registerWithDwnEndpoints({
139
- userAgent: userAgent,
140
- dwnEndpoints,
141
- agentDid: userAgent.agentDid.uri,
142
- connectedDid,
143
- storage: storage,
144
- }, ctx.registration);
145
- }
146
- // Register and start sync.
147
- if (sync !== 'off') {
148
- yield userAgent.sync.registerIdentity({
149
- did: connectedDid,
150
- options: { delegateDid, protocols: [] },
151
- });
152
- const syncMode = sync === undefined ? 'live' : 'poll';
153
- const syncInterval = sync !== null && sync !== void 0 ? sync : (syncMode === 'live' ? '5m' : '2m');
154
- userAgent.sync.startSync({ mode: syncMode, interval: syncInterval })
155
- .catch((err) => console.error('[@enbox/auth] Sync failed:', err));
156
- }
157
- yield storage.set(STORAGE_KEYS.PREVIOUSLY_CONNECTED, 'true');
158
- yield storage.set(STORAGE_KEYS.ACTIVE_IDENTITY, connectedDid);
159
- const identityInfo = {
160
- didUri: connectedDid,
161
- name: identity.metadata.name,
162
- connectedDid: identity.metadata.connectedDid,
163
- };
164
- const session = new AuthSession({
165
- agent: userAgent,
166
- did: connectedDid,
167
- delegateDid,
168
- identity: identityInfo,
169
- });
170
- emitter.emit('identity-added', { identity: identityInfo });
171
- emitter.emit('session-start', {
172
- session: { did: connectedDid, delegateDid, identity: identityInfo },
173
- });
174
- return session;
175
- });
176
- }
177
- //# sourceMappingURL=import-identity.js.map