@tinycloudlabs/web-sdk 0.2.1 → 1.0.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 (69) hide show
  1. package/LICENSE.md +320 -0
  2. package/dist/625.index.js +1 -0
  3. package/dist/authorization/WebSpaceCreationHandler.d.ts +40 -0
  4. package/dist/authorization/WebSpaceCreationHandler.d.ts.map +1 -0
  5. package/dist/authorization/WebUserAuthorization.d.ts +295 -0
  6. package/dist/authorization/WebUserAuthorization.d.ts.map +1 -0
  7. package/dist/authorization/index.d.ts +12 -0
  8. package/dist/authorization/index.d.ts.map +1 -0
  9. package/dist/delegation.d.ts +85 -0
  10. package/dist/delegation.d.ts.map +1 -0
  11. package/dist/index.d.ts +12 -10
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/modules/Storage/index.d.ts +1 -2
  15. package/dist/modules/Storage/index.d.ts.map +1 -1
  16. package/dist/modules/Storage/tinycloud/KVServiceAdapter.d.ts +24 -0
  17. package/dist/modules/Storage/tinycloud/KVServiceAdapter.d.ts.map +1 -0
  18. package/dist/modules/Storage/tinycloud/index.d.ts +1 -4
  19. package/dist/modules/Storage/tinycloud/index.d.ts.map +1 -1
  20. package/dist/modules/Storage/tinycloud/module.d.ts +1 -1
  21. package/dist/modules/Storage/tinycloud/types.d.ts +7 -9
  22. package/dist/modules/Storage/tinycloud/types.d.ts.map +1 -1
  23. package/dist/modules/Storage/tinycloud/types.schema.d.ts +159 -0
  24. package/dist/modules/Storage/tinycloud/types.schema.d.ts.map +1 -0
  25. package/dist/modules/UserAuthorization.d.ts +191 -58
  26. package/dist/modules/UserAuthorization.d.ts.map +1 -1
  27. package/dist/modules/WasmInitializer.d.ts +26 -0
  28. package/dist/modules/WasmInitializer.d.ts.map +1 -0
  29. package/dist/modules/index.d.ts +1 -0
  30. package/dist/modules/index.d.ts.map +1 -1
  31. package/dist/modules/keys/WasmKeyProvider.d.ts +126 -0
  32. package/dist/modules/keys/WasmKeyProvider.d.ts.map +1 -0
  33. package/dist/modules/keys/index.d.ts +7 -0
  34. package/dist/modules/keys/index.d.ts.map +1 -0
  35. package/dist/modules/registry/Registry.d.ts +59 -0
  36. package/dist/modules/registry/Registry.d.ts.map +1 -0
  37. package/dist/modules/tcw.d.ts +649 -53
  38. package/dist/modules/tcw.d.ts.map +1 -1
  39. package/dist/notifications/ModalManager.d.ts +6 -3
  40. package/dist/notifications/ModalManager.d.ts.map +1 -1
  41. package/dist/notifications/NodeSelectionModal.d.ts +29 -0
  42. package/dist/notifications/NodeSelectionModal.d.ts.map +1 -0
  43. package/dist/notifications/{OrbitCreationModal.d.ts → SpaceCreationModal.d.ts} +8 -8
  44. package/dist/notifications/{OrbitCreationModal.d.ts.map → SpaceCreationModal.d.ts.map} +1 -1
  45. package/dist/notifications/index.d.ts +3 -2
  46. package/dist/notifications/index.d.ts.map +1 -1
  47. package/dist/notifications/types.schema.d.ts +224 -0
  48. package/dist/notifications/types.schema.d.ts.map +1 -0
  49. package/dist/utils/debug.d.ts +9 -0
  50. package/dist/utils/debug.d.ts.map +1 -0
  51. package/dist/utils/multiaddr.d.ts +36 -0
  52. package/dist/utils/multiaddr.d.ts.map +1 -0
  53. package/package.json +14 -6
  54. package/dist/modules/Storage/TinyCloudStorage.d.ts +0 -182
  55. package/dist/modules/Storage/TinyCloudStorage.d.ts.map +0 -1
  56. package/dist/modules/Storage/interfaces.d.ts +0 -119
  57. package/dist/modules/Storage/interfaces.d.ts.map +0 -1
  58. package/dist/modules/Storage/tinycloud/authenticator.d.ts +0 -12
  59. package/dist/modules/Storage/tinycloud/authenticator.d.ts.map +0 -1
  60. package/dist/modules/Storage/tinycloud/capabilities.d.ts +0 -25
  61. package/dist/modules/Storage/tinycloud/capabilities.d.ts.map +0 -1
  62. package/dist/modules/Storage/tinycloud/kv.d.ts +0 -18
  63. package/dist/modules/Storage/tinycloud/kv.d.ts.map +0 -1
  64. package/dist/modules/Storage/tinycloud/orbit.d.ts +0 -167
  65. package/dist/modules/Storage/tinycloud/orbit.d.ts.map +0 -1
  66. package/dist/modules/Storage/tinycloud/tinycloud.d.ts +0 -43
  67. package/dist/modules/Storage/tinycloud/tinycloud.d.ts.map +0 -1
  68. package/dist/modules/Storage/tinycloud/walletProvider.d.ts +0 -19
  69. package/dist/modules/Storage/tinycloud/walletProvider.d.ts.map +0 -1
@@ -1,27 +1,149 @@
1
- import { TCWRPCProviders, TCWEnsData } from '@tinycloudlabs/web-core';
2
- import { IUserAuthorization, TinyCloudStorage } from '.';
3
- import { TCWClientConfig, TCWClientSession, TCWExtension } from '@tinycloudlabs/web-core/client';
4
- import type { providers, Signer } from 'ethers';
1
+ import { RPCProviders } from '@tinycloudlabs/web-core';
2
+ import { IUserAuthorization } from '.';
3
+ import { WebUserAuthorization, WebSignStrategy } from '../authorization';
4
+ import { ClientConfig, ClientSession, Extension } from '@tinycloudlabs/web-core/client';
5
+ import type { providers } from 'ethers';
5
6
  import type { NotificationConfig } from '../notifications/types';
6
- import { SiweMessage } from 'siwe';
7
+ import { IKVService, ICapabilityKeyRegistry, DelegationManager, ISpaceService, ISpace, Delegation, Result, DelegationError, ISharingService, CreateDelegationParams, ISpaceCreationHandler } from '@tinycloudlabs/sdk-core';
8
+ import { PortableDelegation, DelegatedAccess } from '../delegation';
7
9
  declare global {
8
10
  interface Window {
9
11
  ethereum?: any;
10
12
  }
11
13
  }
12
14
  /**
13
- * Configuration for managing TCW Modules
15
+ * Configuration for TinyCloudWeb.
16
+ *
17
+ * Extends ClientConfig with notification options and the new unified auth module.
18
+ *
19
+ * ## New Auth Module (1.0.0)
20
+ *
21
+ * Set `useNewAuth: true` to enable the new unified auth architecture with:
22
+ * - **SignStrategy pattern**: Control how sign requests are handled
23
+ * - **Session-only mode**: Receive delegations without a wallet
24
+ * - **`did` vs `sessionDid` model**: Clear identity distinction
25
+ * - **`connectWallet()` upgrade pattern**: Upgrade from session-only to full auth
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * // Legacy mode (default)
30
+ * const tcw = new TinyCloudWeb({
31
+ * providers: { web3: { driver: window.ethereum } }
32
+ * });
33
+ *
34
+ * // New auth mode (recommended for new projects)
35
+ * const tcw = new TinyCloudWeb({
36
+ * useNewAuth: true,
37
+ * signStrategy: { type: 'wallet-popup' },
38
+ * spaceCreationHandler: new ModalSpaceCreationHandler()
39
+ * });
40
+ *
41
+ * // Session-only mode (no wallet required)
42
+ * const tcw = new TinyCloudWeb({ useNewAuth: true });
43
+ * console.log(tcw.sessionDid); // did:key:z6Mk...
44
+ * ```
14
45
  */
15
- interface TCWModuleConfig {
16
- storage?: boolean | {
17
- [key: string]: any;
18
- };
19
- }
20
- interface TCWConfig extends TCWClientConfig {
21
- modules?: TCWModuleConfig;
46
+ export interface Config extends ClientConfig {
47
+ /** Notification configuration for error popups and toasts */
22
48
  notifications?: NotificationConfig;
49
+ /** Optional prefix for KV service keys */
50
+ kvPrefix?: string;
51
+ /**
52
+ * Prefix for space names when creating spaces.
53
+ * @example 'myapp' results in spaces like 'myapp-default'
54
+ */
55
+ spacePrefix?: string;
56
+ /**
57
+ * TinyCloud server hosts.
58
+ * @default ['https://node.tinycloud.xyz']
59
+ */
60
+ tinycloudHosts?: string[];
61
+ /**
62
+ * Whether to auto-create space on sign-in if it doesn't exist.
63
+ * @default true
64
+ */
65
+ autoCreateSpace?: boolean;
66
+ /**
67
+ * Whether to use the new WebUserAuthorization class.
68
+ *
69
+ * When `true`, uses the new unified auth module architecture featuring:
70
+ * - SignStrategy pattern for controlling sign requests
71
+ * - Session-only mode (receive delegations without wallet)
72
+ * - Clear `did` vs `sessionDid` model
73
+ * - `connectWallet()` upgrade pattern
74
+ *
75
+ * When `false` (default), uses the legacy UserAuthorization for backward compatibility.
76
+ *
77
+ * **Recommended**: Set to `true` for new projects or when migrating to 1.0.0.
78
+ *
79
+ * @default false
80
+ */
81
+ useNewAuth?: boolean;
82
+ /**
83
+ * Sign strategy for handling sign requests.
84
+ *
85
+ * Only used when `useNewAuth: true`. Determines how SIWE signing is handled:
86
+ * - `'wallet-popup'` (default): Show browser wallet popup
87
+ * - `{ type: 'auto-sign' }`: Automatically sign (requires external signer setup)
88
+ * - `{ type: 'callback', handler: fn }`: Custom callback for sign requests
89
+ * - `{ type: 'event-emitter', emitter: ee }`: Emit events for external handling
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * // Default: wallet popup
94
+ * signStrategy: 'wallet-popup'
95
+ *
96
+ * // Custom callback for approval UI
97
+ * signStrategy: {
98
+ * type: 'callback',
99
+ * handler: async (req) => {
100
+ * const approved = await showCustomApprovalDialog(req.message);
101
+ * return { approved };
102
+ * }
103
+ * }
104
+ * ```
105
+ */
106
+ signStrategy?: WebSignStrategy;
107
+ /**
108
+ * Handler for space creation confirmation.
109
+ *
110
+ * Only used when `useNewAuth: true`. Controls how space creation is confirmed:
111
+ * - `ModalSpaceCreationHandler` (default): Shows a modal dialog
112
+ * - `{ confirmSpaceCreation: async () => true }`: Auto-approve
113
+ * - Custom implementation of `ISpaceCreationHandler`
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * // Default: modal confirmation
118
+ * spaceCreationHandler: new ModalSpaceCreationHandler()
119
+ *
120
+ * // Auto-approve (no UI)
121
+ * spaceCreationHandler: { confirmSpaceCreation: async () => true }
122
+ *
123
+ * // Custom handler
124
+ * spaceCreationHandler: {
125
+ * confirmSpaceCreation: async (context) => {
126
+ * return await showCustomDialog(`Create space: ${context.spaceId}?`);
127
+ * }
128
+ * }
129
+ * ```
130
+ */
131
+ spaceCreationHandler?: ISpaceCreationHandler;
132
+ }
133
+ /**
134
+ * Result of receiving a share link.
135
+ */
136
+ export interface ShareReceiveResult<T = unknown> {
137
+ /** The retrieved data */
138
+ data: T;
139
+ /** The delegation that authorized access */
140
+ delegation: Delegation;
141
+ /** The path the share grants access to */
142
+ path: string;
143
+ /** The space ID */
144
+ spaceId: string;
23
145
  }
24
- /** TCW: TinyCloud Web SDK
146
+ /** TinyCloud Web SDK
25
147
  *
26
148
  * An SDK for building user-controlled web apps.
27
149
  */
@@ -30,7 +152,36 @@ export declare class TinyCloudWeb {
30
152
  /** The Ethereum provider */
31
153
  provider: providers.Web3Provider;
32
154
  /** Supported RPC Providers */
33
- static RPCProviders: typeof TCWRPCProviders;
155
+ static RPCProviders: typeof RPCProviders;
156
+ /**
157
+ * Receive and retrieve data from a v2 share link.
158
+ *
159
+ * This static method allows receiving shared data without being signed in.
160
+ * The share link contains an embedded private key and delegation that
161
+ * grants access to the shared resource.
162
+ *
163
+ * @param link - The share link (tc1:... format or full URL)
164
+ * @param key - Optional specific key to retrieve within the shared path
165
+ * @returns Result containing the data or an error
166
+ *
167
+ * @example
168
+ * ```typescript
169
+ * // Receive shared data using just the link
170
+ * const result = await TinyCloudWeb.receiveShare('tc1:...');
171
+ * if (result.ok) {
172
+ * console.log('Data:', result.data.data);
173
+ * console.log('Path:', result.data.path);
174
+ * } else {
175
+ * console.error('Error:', result.error.message);
176
+ * }
177
+ *
178
+ * // Or from a full URL
179
+ * const result = await TinyCloudWeb.receiveShare(
180
+ * 'https://share.example.com/share/tc1:...'
181
+ * );
182
+ * ```
183
+ */
184
+ static receiveShare<T = unknown>(link: string, key?: string): Promise<Result<ShareReceiveResult<T>, DelegationError>>;
34
185
  /** UserAuthorization Module
35
186
  *
36
187
  * Handles the capabilities that a user can provide a app, specifically
@@ -40,22 +191,244 @@ export declare class TinyCloudWeb {
40
191
  * - session key management
41
192
  * - creates, manages, and handles session data
42
193
  * - manages/provides capabilities
194
+ *
195
+ * NOTE: When useNewAuth is true, this is a WebUserAuthorization instance.
196
+ * The type is `any` to allow both legacy and new auth modules.
197
+ * Use `webAuth` getter for typed access to WebUserAuthorization.
43
198
  */
44
- userAuthorization: IUserAuthorization;
45
- /** Storage Module */
46
- storage: TinyCloudStorage;
199
+ userAuthorization: IUserAuthorization | WebUserAuthorization;
47
200
  /** Error Handler for Notifications */
48
201
  private errorHandler;
49
- constructor(config?: TCWConfig);
202
+ /** Service Context for sdk-services */
203
+ private _serviceContext?;
204
+ /** KV Service instance */
205
+ private _kvService?;
206
+ /** Capability Key Registry for automatic key selection */
207
+ private _capabilityRegistry?;
208
+ /** Delegation Manager for CRUD operations on delegations */
209
+ private _delegationManager?;
210
+ /** Space Service for managing spaces */
211
+ private _spaceService?;
212
+ /** KeyProvider for SharingService */
213
+ private _keyProvider?;
214
+ /** SharingService for generating/receiving share links */
215
+ private _sharingService?;
216
+ constructor(config?: Config);
217
+ /**
218
+ * Create a WebUserAuthorization instance from the config.
219
+ * Maps legacy config options to new WebUserAuthorizationConfig.
220
+ * @private
221
+ */
222
+ private createWebUserAuthorization;
223
+ /**
224
+ * Get the KV service.
225
+ *
226
+ * Returns the new sdk-services KVService with Result pattern.
227
+ * Must be signed in for the service to be available.
228
+ *
229
+ * @throws Error if not signed in
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * const result = await tcw.kv.get('key');
234
+ * if (result.ok) {
235
+ * console.log(result.data.data);
236
+ * } else {
237
+ * console.error(result.error.code, result.error.message);
238
+ * }
239
+ * ```
240
+ */
241
+ get kv(): IKVService;
242
+ /**
243
+ * Get the KV prefix configured for this instance.
244
+ */
245
+ get kvPrefix(): string;
246
+ /**
247
+ * Get the capability key registry for automatic key selection.
248
+ * This registry tracks keys and their associated delegations,
249
+ * enabling automatic selection of the best key for operations.
250
+ *
251
+ * Must be signed in for the registry to be available.
252
+ *
253
+ * @throws Error if not signed in
254
+ *
255
+ * @example
256
+ * ```typescript
257
+ * // Get the best key for an operation
258
+ * const key = tcw.capabilityRegistry.getKeyForCapability(
259
+ * 'tinycloud://my-space/kv/data',
260
+ * 'tinycloud.kv/get'
261
+ * );
262
+ *
263
+ * // List all capabilities
264
+ * const capabilities = tcw.capabilityRegistry.getAllCapabilities();
265
+ * ```
266
+ */
267
+ get capabilityRegistry(): ICapabilityKeyRegistry;
268
+ /**
269
+ * Get the delegation manager for CRUD operations on delegations.
270
+ * Handles creating, revoking, listing, and querying delegations.
271
+ *
272
+ * Must be signed in for the manager to be available.
273
+ *
274
+ * @throws Error if not signed in
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * // Create a delegation
279
+ * const result = await tcw.delegations.create({
280
+ * delegateDID: 'did:pkh:eip155:1:0x...',
281
+ * path: 'shared/',
282
+ * actions: ['tinycloud.kv/get', 'tinycloud.kv/list'],
283
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
284
+ * });
285
+ *
286
+ * // List all delegations
287
+ * const listResult = await tcw.delegations.list();
288
+ *
289
+ * // Revoke a delegation
290
+ * await tcw.delegations.revoke('bafy...');
291
+ * ```
292
+ */
293
+ get delegations(): DelegationManager;
50
294
  /**
51
- * Extends TCW with a functions that are called after connecting and signing in.
295
+ * Get the space service for managing spaces (owned and delegated).
296
+ * Provides listing, creation, and access to space-scoped operations.
297
+ *
298
+ * Must be signed in for the service to be available.
299
+ *
300
+ * @throws Error if not signed in
301
+ *
302
+ * @example
303
+ * ```typescript
304
+ * // List all accessible spaces
305
+ * const result = await tcw.spaces.list();
306
+ * if (result.ok) {
307
+ * for (const space of result.data) {
308
+ * console.log(`${space.name} (${space.type})`);
309
+ * }
310
+ * }
311
+ *
312
+ * // Create a new space
313
+ * const createResult = await tcw.spaces.create('photos');
314
+ *
315
+ * // Get a space object for operations
316
+ * const space = tcw.spaces.get('photos');
317
+ * await space.kv.put('album/vacation', { photos: [...] });
318
+ * ```
319
+ */
320
+ get spaces(): ISpaceService;
321
+ /**
322
+ * Get a specific space by name or URI.
323
+ * Shorthand for `tcw.spaces.get(nameOrUri)`.
324
+ *
325
+ * Must be signed in for the service to be available.
326
+ *
327
+ * @param nameOrUri - Short name or full space URI
328
+ * @returns Space object with scoped operations
329
+ * @throws Error if not signed in
330
+ *
331
+ * @example
332
+ * ```typescript
333
+ * // Get an owned space by short name
334
+ * const photos = tcw.space('photos');
335
+ * await photos.kv.put('vacation/photo1.jpg', imageData);
336
+ *
337
+ * // Get a delegated space by full URI
338
+ * const shared = tcw.space('tinycloud:pkh:eip155:1:0x...:shared');
339
+ * const data = await shared.kv.get('document.json');
340
+ * ```
341
+ */
342
+ space(nameOrUri: string): ISpace;
343
+ /**
344
+ * Get the sharing service for generating and managing share links.
345
+ * Provides v2 sharing links with embedded private keys.
346
+ *
347
+ * Must be signed in for the service to be available.
348
+ *
349
+ * @throws Error if not signed in
350
+ *
351
+ * @example
352
+ * ```typescript
353
+ * // Generate a sharing link for a key
354
+ * const result = await tcw.sharing.generate({
355
+ * path: 'shared/document.json',
356
+ * actions: ['tinycloud.kv/get'],
357
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
358
+ * });
359
+ * if (result.ok) {
360
+ * console.log('Share link:', result.data.link);
361
+ * }
362
+ *
363
+ * // Receive a share (static method, no auth needed)
364
+ * const shareResult = await TinyCloudWeb.receiveShare('tc1:...');
365
+ * ```
366
+ */
367
+ get sharing(): ISharingService;
368
+ /**
369
+ * Initialize the sdk-services KVService and other services.
370
+ * Called internally after sign-in when the session is established.
371
+ *
372
+ * @internal
52
373
  */
53
- extend(extension: TCWExtension): void;
374
+ private initializeKVService;
375
+ /**
376
+ * Initialize the delegation system services.
377
+ * Called internally after sign-in when the session is established.
378
+ *
379
+ * @param hosts - TinyCloud host URLs
380
+ * @param serviceSession - The service session
381
+ * @internal
382
+ */
383
+ private initializeDelegationServices;
384
+ /**
385
+ * Create a delegation for sharing using the WASM /delegate endpoint.
386
+ * @internal
387
+ */
388
+ private createDelegationForSharing;
389
+ /**
390
+ * Wrapper for the WASM createDelegation function.
391
+ * Adapts the WASM interface to what SharingService expects.
392
+ * @internal
393
+ */
394
+ private createDelegationWrapper;
395
+ /**
396
+ * Get the session expiry time.
397
+ * @internal
398
+ */
399
+ private getSessionExpiry;
400
+ /**
401
+ * Create a delegation using SIWE-based flow.
402
+ * This method implements the correct delegation creation pattern:
403
+ * 1. Use prepareSession() to build the delegation
404
+ * 2. Sign the SIWE message with the user's wallet
405
+ * 3. Use completeSessionSetup() to get the delegation header
406
+ * 4. Activate the delegation with the server
407
+ *
408
+ * @param params - Delegation parameters including spaceId
409
+ * @param session - The TinyCloud session
410
+ * @param address - User's address
411
+ * @param chainId - Chain ID
412
+ * @param hosts - TinyCloud host URLs
413
+ * @returns Result containing the created Delegation or an error
414
+ * @internal
415
+ */
416
+ private createDelegationWithSIWE;
417
+ /**
418
+ * Convert TinyCloud session to ServiceSession.
419
+ * Gets session from UserAuthorization.
420
+ * @internal
421
+ */
422
+ private toServiceSession;
423
+ /**
424
+ * Extends TinyCloudWeb with functions that are called after connecting and signing in.
425
+ */
426
+ extend(extension: Extension): void;
54
427
  /**
55
428
  * Request the user to sign in, and start the session.
56
429
  * @returns Object containing information about the session
57
430
  */
58
- signIn: () => Promise<TCWClientSession>;
431
+ signIn: () => Promise<ClientSession>;
59
432
  /**
60
433
  * Invalidates user's session.
61
434
  */
@@ -65,20 +438,11 @@ export declare class TinyCloudWeb {
65
438
  * Should be called when the SDK is no longer needed.
66
439
  */
67
440
  cleanup(): void;
68
- /**
69
- * ENS data supported by TCW.
70
- * @param address - User address.
71
- * @param resolveEnsOpts - Options to resolve ENS.
72
- * @returns Object containing ENS data.
73
- */
74
- resolveEns(
75
- /** User address */
76
- address: string): Promise<TCWEnsData>;
77
441
  /**
78
442
  * Gets the session representation (once signed in).
79
- * @returns Address.
443
+ * @returns Session object.
80
444
  */
81
- session: () => TCWClientSession | undefined;
445
+ session: () => ClientSession | undefined;
82
446
  /**
83
447
  * Gets the address that is connected and signed in.
84
448
  * @returns Address.
@@ -90,33 +454,265 @@ export declare class TinyCloudWeb {
90
454
  */
91
455
  chainId: () => number | undefined;
92
456
  /**
93
- * Gets the provider that is connected and signed in.
94
- * @returns Provider.
457
+ * Check if the new auth module is being used.
458
+ * @returns true if using WebUserAuthorization, false if using legacy UserAuthorization
95
459
  */
96
- getProvider(): providers.Web3Provider | undefined;
460
+ get isNewAuthEnabled(): boolean;
97
461
  /**
98
- * Returns the signer of the connected address.
99
- * @returns ethers.Signer
100
- * @see https://docs.ethers.io/v5/api/signer/#Signer
462
+ * Get the WebUserAuthorization instance (new auth module only).
463
+ * Throws if not using new auth module.
464
+ *
465
+ * @throws Error if useNewAuth is false
101
466
  */
102
- getSigner(): Signer;
467
+ get webAuth(): WebUserAuthorization;
103
468
  /**
104
- * Generates a SIWE message for authentication with session key capabilities.
105
- * This method delegates to the UserAuthorization module.
469
+ * Get the primary DID for this user (new auth module only).
470
+ *
471
+ * - If wallet connected and signed in: returns PKH DID (persistent identity)
472
+ * - If session-only mode: returns session key DID (ephemeral)
106
473
  *
107
- * @param address - Ethereum address performing the signing
108
- * @param partialSiweMessage - Optional partial SIWE message to override defaults
109
- * @returns SiweMessage object ready for signing
474
+ * @throws Error if useNewAuth is false
110
475
  */
111
- generateSiweMessage(address: string, partialSiweMessage?: Partial<SiweMessage>): Promise<SiweMessage>;
476
+ get did(): string;
112
477
  /**
113
- * Sign in using a pre-signed SIWE message.
114
- * This method delegates to the UserAuthorization module.
115
- * @param siweMessage - The SIWE message that was generated
116
- * @param signature - The signature of the SIWE message
117
- * @returns Object containing information about the session
478
+ * Get the session key DID (new auth module only).
479
+ * Always available, even before sign-in.
480
+ *
481
+ * Format: `did:key:z6Mk...#z6Mk...`
482
+ *
483
+ * @throws Error if useNewAuth is false
484
+ */
485
+ get sessionDid(): string;
486
+ /**
487
+ * Check if in session-only mode (new auth module only).
488
+ * Session-only mode means no wallet is connected, but delegations can be received.
489
+ *
490
+ * @throws Error if useNewAuth is false
491
+ */
492
+ get isSessionOnly(): boolean;
493
+ /**
494
+ * Check if a wallet is connected (new auth module only).
495
+ * Wallet may be connected but not signed in.
496
+ *
497
+ * @throws Error if useNewAuth is false
498
+ */
499
+ get isWalletConnected(): boolean;
500
+ /**
501
+ * Connect a wallet to upgrade from session-only mode (new auth module only).
502
+ *
503
+ * This allows users who started in session-only mode (e.g., received
504
+ * delegations) to later connect a wallet and create their own space.
505
+ *
506
+ * @param provider - Web3 provider (e.g., window.ethereum)
507
+ * @param options - Optional configuration
508
+ *
509
+ * @throws Error if useNewAuth is false
510
+ *
511
+ * @example
512
+ * ```typescript
513
+ * // Create in session-only mode
514
+ * const tcw = new TinyCloudWeb({ useNewAuth: true });
515
+ * console.log(tcw.isSessionOnly); // true
516
+ *
517
+ * // User clicks "Connect Wallet"
518
+ * tcw.connectWallet(window.ethereum);
519
+ * console.log(tcw.isSessionOnly); // false
520
+ *
521
+ * // Now can sign in
522
+ * await tcw.signIn();
523
+ * ```
524
+ */
525
+ connectWallet(provider: providers.ExternalProvider | providers.Web3Provider, options?: {
526
+ spacePrefix?: string;
527
+ }): void;
528
+ /**
529
+ * Use a delegation received from another user.
530
+ *
531
+ * This creates a session that chains from the received delegation,
532
+ * allowing operations on the delegator's space.
533
+ *
534
+ * Works in both modes:
535
+ * - **Session-only mode**: Uses the delegation directly (must target session key DID)
536
+ * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key
537
+ *
538
+ * @param delegation - The PortableDelegation to use (from createDelegation or transport)
539
+ * @returns A DelegatedAccess instance for performing operations
540
+ *
541
+ * @throws Error if useNewAuth is false (legacy auth not supported)
542
+ * @throws Error if in session-only mode and delegation doesn't target this user's DID
543
+ * @throws Error if in wallet mode and not signed in
544
+ *
545
+ * @example
546
+ * ```typescript
547
+ * // Session-only mode (most common for receiving delegations)
548
+ * const tcw = new TinyCloudWeb({ useNewAuth: true });
549
+ * const delegation = deserializeDelegation(receivedData);
550
+ *
551
+ * // The delegation must target tcw.did (session key DID in session-only mode)
552
+ * const access = await tcw.useDelegation(delegation);
553
+ *
554
+ * // Perform KV operations on the delegated space
555
+ * const data = await access.kv.get("shared/document.json");
556
+ * await access.kv.put("shared/notes.txt", "Hello!");
557
+ *
558
+ * // Wallet mode (signed in user receiving delegation)
559
+ * const tcw = new TinyCloudWeb({ useNewAuth: true, providers: { web3: { driver: window.ethereum } } });
560
+ * await tcw.signIn();
561
+ *
562
+ * // The delegation should target tcw.did (PKH DID when signed in)
563
+ * const access = await tcw.useDelegation(delegation);
564
+ * ```
565
+ */
566
+ useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess>;
567
+ /**
568
+ * Convenience method to create a delegation via the delegation manager.
569
+ * For creating PortableDelegations, use createDelegation() instead.
570
+ *
571
+ * @param params - Delegation parameters
572
+ * @returns Result containing the created Delegation or an error
573
+ *
574
+ * @example
575
+ * ```typescript
576
+ * const result = await tcw.delegate({
577
+ * delegateDID: 'did:pkh:eip155:1:0x...',
578
+ * path: 'shared/',
579
+ * actions: ['tinycloud.kv/get', 'tinycloud.kv/put'],
580
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
581
+ * });
582
+ *
583
+ * if (result.ok) {
584
+ * console.log('Delegation created:', result.data.cid);
585
+ * }
586
+ * ```
587
+ */
588
+ delegate(params: CreateDelegationParams): Promise<Result<Delegation, DelegationError>>;
589
+ /**
590
+ * Revoke a delegation by CID.
591
+ *
592
+ * @param cid - The CID of the delegation to revoke
593
+ * @returns Result indicating success or failure
594
+ *
595
+ * @example
596
+ * ```typescript
597
+ * const result = await tcw.revokeDelegation('bafy...');
598
+ * if (result.ok) {
599
+ * console.log('Delegation revoked');
600
+ * }
601
+ * ```
602
+ */
603
+ revokeDelegation(cid: string): Promise<Result<void, DelegationError>>;
604
+ /**
605
+ * List all delegations for the current space.
606
+ *
607
+ * @returns Result containing an array of Delegations
608
+ *
609
+ * @example
610
+ * ```typescript
611
+ * const result = await tcw.listDelegations();
612
+ * if (result.ok) {
613
+ * console.log('Delegations:', result.data.length);
614
+ * }
615
+ * ```
616
+ */
617
+ listDelegations(): Promise<Result<Delegation[], DelegationError>>;
618
+ /**
619
+ * Check if the current session has permission for a path and action.
620
+ *
621
+ * @param path - The resource path to check
622
+ * @param action - The action to check (e.g., 'tinycloud.kv/get')
623
+ * @returns Result containing boolean permission status
624
+ *
625
+ * @example
626
+ * ```typescript
627
+ * const result = await tcw.checkPermission('shared/docs', 'tinycloud.kv/get');
628
+ * if (result.ok && result.data) {
629
+ * console.log('Permission granted');
630
+ * }
631
+ * ```
632
+ */
633
+ checkPermission(path: string, action: string): Promise<Result<boolean, DelegationError>>;
634
+ /**
635
+ * Create a delegation to grant access to another user.
636
+ * Returns a PortableDelegation that can be serialized and sent to the recipient.
637
+ *
638
+ * @param params - Delegation parameters
639
+ * @returns A portable delegation that can be sent to the recipient
640
+ *
641
+ * @throws Error if not signed in
642
+ * @throws Error if using legacy auth mode (requires useNewAuth: true)
643
+ *
644
+ * @example
645
+ * ```typescript
646
+ * const delegation = await tcw.createDelegation({
647
+ * path: "shared/",
648
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/list"],
649
+ * delegateDID: recipientDid,
650
+ * expiryMs: 7 * 24 * 60 * 60 * 1000, // 7 days
651
+ * });
652
+ *
653
+ * // Send to recipient
654
+ * const token = serializeDelegation(delegation);
655
+ * ```
656
+ */
657
+ createDelegation(params: {
658
+ /** Path within the space to delegate access to */
659
+ path: string;
660
+ /** Actions to allow (e.g., ["tinycloud.kv/get", "tinycloud.kv/put"]) */
661
+ actions: string[];
662
+ /** DID of the recipient (from their TinyCloudWeb.did) */
663
+ delegateDID: string;
664
+ /** Whether to prevent the recipient from creating sub-delegations (default: false) */
665
+ disableSubDelegation?: boolean;
666
+ /** Expiration time in milliseconds from now (default: 1 hour) */
667
+ expiryMs?: number;
668
+ }): Promise<PortableDelegation>;
669
+ /**
670
+ * Track a received delegation in the capability registry.
671
+ * @private
672
+ */
673
+ private trackReceivedDelegation;
674
+ /**
675
+ * Create a sub-delegation from a received delegation.
676
+ * Allows chaining delegations (Alice -> Bob -> Carol).
677
+ *
678
+ * This allows further delegating access that was received from another user,
679
+ * if the original delegation allows sub-delegation.
680
+ *
681
+ * @param parentDelegation - The delegation received from another user
682
+ * @param params - Sub-delegation parameters (must be within parent's scope)
683
+ * @returns A portable delegation for the sub-delegate
684
+ *
685
+ * @throws Error if useNewAuth is false (legacy auth not supported)
686
+ * @throws Error if in session-only mode (requires wallet)
687
+ * @throws Error if not signed in
688
+ * @throws Error if parent delegation does not allow sub-delegation
689
+ * @throws Error if sub-delegation path is outside parent's path
690
+ * @throws Error if sub-delegation actions are not a subset of parent's actions
691
+ *
692
+ * @example
693
+ * ```typescript
694
+ * // Bob received a delegation from Alice
695
+ * const access = await tcw.useDelegation(aliceDelegation);
696
+ *
697
+ * // Bob creates sub-delegation for Carol
698
+ * const subDelegation = await tcw.createSubDelegation(aliceDelegation, {
699
+ * path: "shared/subset/",
700
+ * actions: ["tinycloud.kv/get"],
701
+ * delegateDID: carolDid,
702
+ * });
703
+ * ```
118
704
  */
119
- signInWithSignature(siweMessage: SiweMessage, signature: string): Promise<TCWClientSession>;
705
+ createSubDelegation(parentDelegation: PortableDelegation, params: {
706
+ /** Path within the delegated path to sub-delegate */
707
+ path: string;
708
+ /** Actions to allow (must be subset of parent's actions) */
709
+ actions: string[];
710
+ /** DID of the recipient */
711
+ delegateDID: string;
712
+ /** Whether to prevent the recipient from creating further sub-delegations */
713
+ disableSubDelegation?: boolean;
714
+ /** Expiration time in milliseconds from now (must be before parent's expiry) */
715
+ expiryMs?: number;
716
+ }): Promise<PortableDelegation>;
120
717
  }
121
- export {};
122
718
  //# sourceMappingURL=tcw.d.ts.map