@tinycloud/node-sdk 2.2.0-beta.1 → 2.2.0-beta.2

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.
@@ -0,0 +1,1453 @@
1
+ import { ISessionStorage, PersistedSessionData, AutoSignStrategy, AutoRejectStrategy, CallbackStrategy, IUserAuthorization, ISigner, ISpaceCreationHandler, IWasmBindings, SiweConfig, Manifest, ComposedManifestRequest, ClientSession, TinyCloudSession, Extension, SignInOptions, Delegation, DelegatedResource, IKVService, ISQLService, IDuckDbService, IHooksService, INotificationHandler, IENSResolver, IDataVaultService, ICapabilityKeyRegistry, DelegationManager, ISpaceService, ISharingService, CreateDelegationParams, DelegationResult, PermissionEntry, ResolvedDelegate, KeyProvider, ISessionManager, JWK } from '@tinycloud/sdk-core';
2
+ import { EventEmitter } from 'events';
3
+ import { InvokeFunction } from '@tinycloud/sdk-services';
4
+
5
+ /**
6
+ * In-memory session storage for Node.js.
7
+ *
8
+ * Sessions are stored in memory and lost when the process exits.
9
+ * Suitable for:
10
+ * - Development and testing
11
+ * - Stateless server deployments
12
+ * - Short-lived processes
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const storage = new MemorySessionStorage();
17
+ * await storage.save("0x123...", sessionData);
18
+ * const session = await storage.load("0x123...");
19
+ * ```
20
+ */
21
+ declare class MemorySessionStorage implements ISessionStorage {
22
+ private sessions;
23
+ /**
24
+ * Save a session for an address.
25
+ */
26
+ save(address: string, session: PersistedSessionData): Promise<void>;
27
+ /**
28
+ * Load a session for an address.
29
+ */
30
+ load(address: string): Promise<PersistedSessionData | null>;
31
+ /**
32
+ * Clear a session for an address.
33
+ */
34
+ clear(address: string): Promise<void>;
35
+ /**
36
+ * Check if a session exists for an address.
37
+ */
38
+ exists(address: string): boolean;
39
+ /**
40
+ * Memory storage is always available.
41
+ */
42
+ isAvailable(): boolean;
43
+ /**
44
+ * Clear all sessions.
45
+ */
46
+ clearAll(): void;
47
+ /**
48
+ * Get the number of stored sessions.
49
+ */
50
+ size(): number;
51
+ }
52
+
53
+ /**
54
+ * File-based session storage for Node.js.
55
+ *
56
+ * Sessions are persisted to the file system and survive process restarts.
57
+ * Suitable for:
58
+ * - CLI applications
59
+ * - Long-running server processes
60
+ * - Development environments
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * const storage = new FileSessionStorage("/tmp/tinycloud-sessions");
65
+ * await storage.save("0x123...", sessionData);
66
+ * // Session persists across process restarts
67
+ * ```
68
+ */
69
+ declare class FileSessionStorage implements ISessionStorage {
70
+ private readonly baseDir;
71
+ /**
72
+ * Create a new FileSessionStorage.
73
+ *
74
+ * @param baseDir - Directory to store session files (default: ~/.tinycloud/sessions)
75
+ */
76
+ constructor(baseDir?: string);
77
+ /**
78
+ * Get the default session storage directory.
79
+ */
80
+ private getDefaultDir;
81
+ /**
82
+ * Ensure the storage directory exists.
83
+ */
84
+ private ensureDirectoryExists;
85
+ /**
86
+ * Get the file path for an address.
87
+ */
88
+ private getFilePath;
89
+ /**
90
+ * Save a session for an address.
91
+ */
92
+ save(address: string, session: PersistedSessionData): Promise<void>;
93
+ /**
94
+ * Load a session for an address.
95
+ */
96
+ load(address: string): Promise<PersistedSessionData | null>;
97
+ /**
98
+ * Clear a session for an address.
99
+ */
100
+ clear(address: string): Promise<void>;
101
+ /**
102
+ * Check if a session exists for an address.
103
+ */
104
+ exists(address: string): boolean;
105
+ /**
106
+ * Check if file system storage is available.
107
+ */
108
+ isAvailable(): boolean;
109
+ }
110
+
111
+ /**
112
+ * Node.js-specific SignStrategy types for TinyCloud authorization.
113
+ *
114
+ * This module re-exports common types from sdk-core and provides
115
+ * Node.js-specific implementations (e.g., NodeEventEmitterStrategy
116
+ * using Node's EventEmitter instead of browser EventTarget).
117
+ *
118
+ * @packageDocumentation
119
+ */
120
+
121
+ /**
122
+ * Node.js event emitter strategy: emits sign requests as events.
123
+ *
124
+ * Uses Node.js EventEmitter for compatibility with Node.js applications.
125
+ * For browser environments, use the EventEmitterStrategy from sdk-core
126
+ * which uses EventTarget.
127
+ *
128
+ * Events emitted:
129
+ * - 'sign-request': When a sign request is received
130
+ *
131
+ * Use cases:
132
+ * - Async approval workflows in Node.js
133
+ * - External signing services
134
+ * - Multi-step authorization flows
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * const emitter = new EventEmitter();
139
+ * const strategy: NodeEventEmitterStrategy = { type: 'event-emitter', emitter };
140
+ *
141
+ * emitter.on('sign-request', async (req, respond) => {
142
+ * const approved = await externalApprovalService.check(req);
143
+ * respond({ approved, signature: approved ? await sign(req.message) : undefined });
144
+ * });
145
+ * ```
146
+ */
147
+ interface NodeEventEmitterStrategy {
148
+ type: "event-emitter";
149
+ emitter: EventEmitter;
150
+ /** Timeout in milliseconds for waiting on event response (default: 60000) */
151
+ timeout?: number;
152
+ }
153
+ /**
154
+ * Node.js sign strategy union type.
155
+ *
156
+ * Determines how sign requests are handled in NodeUserAuthorization.
157
+ * Uses Node.js EventEmitter for the event-emitter strategy.
158
+ */
159
+ type SignStrategy = AutoSignStrategy | AutoRejectStrategy | CallbackStrategy | NodeEventEmitterStrategy;
160
+ /**
161
+ * Default sign strategy is auto-sign for convenience.
162
+ * This is the Node.js-specific version typed with SignStrategy.
163
+ */
164
+ declare const defaultSignStrategy: SignStrategy;
165
+
166
+ /**
167
+ * Configuration for NodeUserAuthorization.
168
+ */
169
+ interface NodeUserAuthorizationConfig {
170
+ /** The signer used for signing messages */
171
+ signer: ISigner;
172
+ /** Sign strategy for handling sign requests */
173
+ signStrategy?: SignStrategy;
174
+ /** Session storage implementation */
175
+ sessionStorage?: ISessionStorage;
176
+ /** Domain for SIWE messages */
177
+ domain: string;
178
+ /** URI for SIWE messages (default: domain) */
179
+ uri?: string;
180
+ /** Statement included in SIWE messages */
181
+ statement?: string;
182
+ /** Space prefix for new sessions */
183
+ spacePrefix?: string;
184
+ /** Default actions for sessions */
185
+ defaultActions?: Record<string, Record<string, string[]>>;
186
+ /** Session expiration time in milliseconds (default: 1 hour) */
187
+ sessionExpirationMs?: number;
188
+ /** Automatically create space if it doesn't exist (default: false) */
189
+ autoCreateSpace?: boolean;
190
+ /** Custom space creation handler. If provided, takes precedence over autoCreateSpace. */
191
+ spaceCreationHandler?: ISpaceCreationHandler;
192
+ /** TinyCloud server endpoints (default: ["https://node.tinycloud.xyz"]) */
193
+ tinycloudHosts?: string[];
194
+ /** Whether to include public space capabilities in the session (default: true) */
195
+ enablePublicSpace?: boolean;
196
+ /** WASM bindings for cryptographic operations. Required. */
197
+ wasmBindings: IWasmBindings;
198
+ /**
199
+ * SIWE nonce override. If omitted, the WASM layer generates a random nonce.
200
+ * If `siweConfig.nonce` is also provided, `siweConfig.nonce` wins.
201
+ */
202
+ nonce?: string;
203
+ /** Optional SIWE configuration overrides (e.g., nonce for server-provided nonces) */
204
+ siweConfig?: SiweConfig;
205
+ /**
206
+ * App manifest used to drive the SIWE recap at sign-in.
207
+ *
208
+ * When set, `signIn` resolves the manifest (via
209
+ * {@link resolveManifest}), unions the app's own permissions with
210
+ * every `delegations[*].permissions` list, converts to the WASM
211
+ * abilities shape, and uses that map as the session's granted
212
+ * capabilities — *instead* of `defaultActions`.
213
+ *
214
+ * This is what makes manifest-declared pre-delegations usable: the
215
+ * session key's recap covers both the app's runtime needs and the
216
+ * downstream delegation targets, so `delegateTo` can issue the
217
+ * sub-delegation via the session-key UCAN path without a wallet
218
+ * prompt.
219
+ *
220
+ * When omitted, `signIn` falls back to `defaultActions` for
221
+ * backwards compatibility.
222
+ */
223
+ manifest?: Manifest | Manifest[];
224
+ /** Pre-composed manifest request. Takes precedence over `manifest`. */
225
+ capabilityRequest?: ComposedManifestRequest;
226
+ /** Include implicit account registry permissions when composing `manifest`. Default true. */
227
+ includeAccountRegistryPermissions?: boolean;
228
+ }
229
+ /**
230
+ * Node.js implementation of IUserAuthorization.
231
+ *
232
+ * Supports multiple sign strategies for different use cases:
233
+ * - auto-sign: Automatically approve all sign requests (trusted backends)
234
+ * - auto-reject: Reject all sign requests (read-only mode)
235
+ * - callback: Delegate to a custom callback function (CLI prompts)
236
+ * - event-emitter: Emit sign requests as events (async workflows)
237
+ *
238
+ * @example
239
+ * ```typescript
240
+ * // Auto-sign for backend services
241
+ * const auth = new NodeUserAuthorization({
242
+ * signer: new PrivateKeySigner(process.env.PRIVATE_KEY),
243
+ * signStrategy: { type: 'auto-sign' },
244
+ * domain: 'api.myapp.com',
245
+ * });
246
+ *
247
+ * // Callback for CLI prompts
248
+ * const auth = new NodeUserAuthorization({
249
+ * signer,
250
+ * signStrategy: {
251
+ * type: 'callback',
252
+ * handler: async (req) => {
253
+ * const approved = await promptUser(`Sign for ${req.address}?`);
254
+ * return { approved };
255
+ * }
256
+ * },
257
+ * domain: 'cli.myapp.com',
258
+ * });
259
+ * ```
260
+ */
261
+ declare class NodeUserAuthorization implements IUserAuthorization {
262
+ private readonly signer;
263
+ private readonly signStrategy;
264
+ private readonly sessionStorage;
265
+ private readonly domain;
266
+ private readonly uri;
267
+ private readonly statement?;
268
+ private readonly spacePrefix;
269
+ private readonly defaultActions;
270
+ private readonly sessionExpirationMs;
271
+ private readonly autoCreateSpace;
272
+ private readonly spaceCreationHandler?;
273
+ private readonly tinycloudHosts;
274
+ private readonly enablePublicSpace;
275
+ private readonly nonce?;
276
+ private readonly siweConfig?;
277
+ private readonly wasm;
278
+ /**
279
+ * Stored manifest, if one was provided at construction time. Used by
280
+ * {@link signIn} to derive the session's granted capabilities instead
281
+ * of falling back to {@link defaultActions}.
282
+ */
283
+ private _manifest?;
284
+ private _capabilityRequest?;
285
+ private readonly includeAccountRegistryPermissions;
286
+ private sessionManager;
287
+ private extensions;
288
+ private _session?;
289
+ private _tinyCloudSession?;
290
+ private _address?;
291
+ private _chainId?;
292
+ private _nodeFeatures;
293
+ constructor(config: NodeUserAuthorizationConfig);
294
+ /**
295
+ * Return the manifest currently driving sign-in behavior, or
296
+ * `undefined` if none is set. Used by TinyCloudWeb/TinyCloudNode
297
+ * internals to surface the manifest for requestPermissions flows
298
+ * without forcing the caller to track it separately.
299
+ */
300
+ get manifest(): Manifest | Manifest[] | undefined;
301
+ get capabilityRequest(): ComposedManifestRequest | undefined;
302
+ /**
303
+ * Install or replace the stored manifest. Takes effect on the next
304
+ * `signIn()` call — the current session (if any) is not touched.
305
+ */
306
+ setManifest(manifest: Manifest | Manifest[] | undefined): void;
307
+ setCapabilityRequest(request: ComposedManifestRequest | undefined): void;
308
+ /**
309
+ * The current active session (web-core compatible).
310
+ */
311
+ get session(): ClientSession | undefined;
312
+ /**
313
+ * The current TinyCloud session with full delegation data.
314
+ * Includes spaceId, delegationHeader, and delegationCid.
315
+ */
316
+ get tinyCloudSession(): TinyCloudSession | undefined;
317
+ get nodeFeatures(): string[];
318
+ /**
319
+ * Compute the `abilities` map the WASM `prepareSession` call should
320
+ * see at sign-in time.
321
+ *
322
+ * When a manifest is installed, we resolve it and union together:
323
+ * - the app's own `resources` (what it needs at runtime)
324
+ * - every `additionalDelegates[*].permissions` list (what it will
325
+ * re-delegate to other DIDs post sign-in)
326
+ *
327
+ * into the short-service / path / full-URN-actions shape the WASM
328
+ * layer expects. This is the key invariant that lets
329
+ * {@link TinyCloudNode.delegateTo} issue manifest-declared
330
+ * delegations via the session key (no wallet prompt): the session's
331
+ * own recap already covers every action those delegations need.
332
+ *
333
+ * When no manifest is installed, we fall back to the
334
+ * {@link defaultActions} table so existing callers see no change.
335
+ *
336
+ * This is a pure function of `this._manifest` + `this.defaultActions`
337
+ * — the manifest resolution performs no I/O and throws a
338
+ * {@link ManifestValidationError} on structural problems (missing
339
+ * id/name, unparseable expiry, etc), which will surface at sign-in
340
+ * rather than being silently swallowed.
341
+ *
342
+ * @internal
343
+ */
344
+ private getCapabilityRequest;
345
+ private resolveSpaceName;
346
+ private resolveSignInCapabilities;
347
+ /**
348
+ * Build SIWE overrides from the top-level nonce and siweConfig.
349
+ * - Top-level `nonce` is seeded first so `siweConfig.nonce` wins if both are set.
350
+ * - statement is prepended to the default statement
351
+ * - resources are appended to the default resources
352
+ * - uri triggers a warning (overwriting delegation target)
353
+ * - all other fields override directly
354
+ * - per-call nonce overrides siweConfig.nonce when provided
355
+ */
356
+ private buildSiweOverrides;
357
+ /**
358
+ * Add an extension to the authorization flow.
359
+ */
360
+ extend(extension: Extension): void;
361
+ /**
362
+ * Get the space ID for the current session.
363
+ */
364
+ getSpaceId(): string | undefined;
365
+ /**
366
+ * Create the space on the TinyCloud server (host delegation).
367
+ * This registers the user as the owner of the space.
368
+ */
369
+ private hostSpace;
370
+ /**
371
+ * Create a specific space on the server via host delegation.
372
+ * Used for lazy creation of additional spaces (e.g., public).
373
+ */
374
+ hostPublicSpace(spaceId: string): Promise<boolean>;
375
+ /**
376
+ * Create a specific owned space on the server via host delegation.
377
+ * Used by manifest registry setup for the account space.
378
+ */
379
+ hostOwnedSpace(spaceId: string): Promise<boolean>;
380
+ /**
381
+ * Ensure the user's space exists on the TinyCloud server.
382
+ * Creates the space if it doesn't exist and autoCreateSpace is enabled.
383
+ * If autoCreateSpace is false and space doesn't exist, silently returns
384
+ * (user may be using delegations to access other spaces).
385
+ *
386
+ * @throws Error if space creation fails
387
+ */
388
+ ensureSpaceExists(): Promise<void>;
389
+ /**
390
+ * Sign in and create a new session.
391
+ *
392
+ * This follows the correct SIWE-ReCap flow:
393
+ * 1. Create session key and get JWK
394
+ * 2. Call prepareSession() which generates the SIWE with ReCap capabilities
395
+ * 3. Sign the SIWE string from prepareSession
396
+ * 4. Call completeSessionSetup() with the prepared session + signature
397
+ *
398
+ * @param options - Optional per-call SIWE overrides for this sign-in only
399
+ */
400
+ signIn(options?: SignInOptions): Promise<ClientSession>;
401
+ /**
402
+ * Sign out and clear the current session.
403
+ */
404
+ signOut(): Promise<void>;
405
+ /**
406
+ * Get the current wallet/signer address.
407
+ */
408
+ address(): string | undefined;
409
+ /**
410
+ * Get the current chain ID.
411
+ */
412
+ chainId(): number | undefined;
413
+ /**
414
+ * Sign a message with the connected signer.
415
+ */
416
+ signMessage(message: string): Promise<string>;
417
+ /**
418
+ * Prepare a session for external signing.
419
+ *
420
+ * Use this method when you need to sign the SIWE message externally (e.g., via
421
+ * a hardware wallet, multi-sig, or external service). After obtaining the signature,
422
+ * call `signInWithPreparedSession()` to complete the sign-in.
423
+ *
424
+ * @example
425
+ * ```typescript
426
+ * const { prepared, keyId, jwk } = await auth.prepareSessionForSigning();
427
+ * const signature = await externalSigner.signMessage(prepared.siwe);
428
+ * const session = await auth.signInWithPreparedSession(prepared, signature, keyId, jwk);
429
+ * ```
430
+ */
431
+ prepareSessionForSigning(): Promise<{
432
+ prepared: {
433
+ siwe: string;
434
+ jwk: Record<string, unknown>;
435
+ spaceId: string;
436
+ verificationMethod: string;
437
+ };
438
+ keyId: string;
439
+ jwk: Record<string, unknown>;
440
+ address: string;
441
+ chainId: number;
442
+ }>;
443
+ /**
444
+ * Complete sign-in with a prepared session and signature.
445
+ *
446
+ * Use this method after obtaining a signature for the SIWE message from
447
+ * `prepareSessionForSigning()`. The signature MUST be over `prepared.siwe`.
448
+ *
449
+ * @param prepared - The prepared session from `prepareSessionForSigning()`
450
+ * @param signature - The signature over `prepared.siwe`
451
+ * @param keyId - The session key ID from `prepareSessionForSigning()`
452
+ * @param jwk - The JWK from `prepareSessionForSigning()`
453
+ */
454
+ signInWithPreparedSession(prepared: {
455
+ siwe: string;
456
+ jwk: Record<string, unknown>;
457
+ spaceId: string;
458
+ verificationMethod: string;
459
+ }, signature: string, keyId: string, jwk: Record<string, unknown>): Promise<ClientSession>;
460
+ /**
461
+ * Clear persisted session data.
462
+ */
463
+ clearPersistedSession(address?: string): Promise<void>;
464
+ /**
465
+ * Check if a session is persisted for an address.
466
+ */
467
+ isSessionPersisted(address: string): boolean;
468
+ /**
469
+ * Request a signature based on the configured strategy.
470
+ */
471
+ private requestSignature;
472
+ /**
473
+ * Request signature via event emitter with timeout.
474
+ */
475
+ private requestSignatureViaEmitter;
476
+ }
477
+
478
+ /**
479
+ * A portable delegation that can be transported between users.
480
+ * Extends the base Delegation type with fields required for transport.
481
+ *
482
+ * @remarks
483
+ * PortableDelegation adds transport fields to Delegation:
484
+ * - `delegationHeader`: Structured authorization header for API calls
485
+ * - `ownerAddress`: Space owner's address for session creation
486
+ * - `chainId`: Chain ID for session creation
487
+ * - `host`: Optional server URL
488
+ * - `resources`: Multi-resource grant breakdown (present when the
489
+ * delegation was issued via the multi-resource WASM path, i.e. one
490
+ * UCAN covering multiple `(service, path, actions)` entries). The
491
+ * flat `path` + `actions` fields mirror the first entry for
492
+ * single-resource callers; consumers that need the full picture
493
+ * read `resources`.
494
+ */
495
+ interface PortableDelegation extends Omit<Delegation, "isRevoked"> {
496
+ /** The authorization header for this delegation (structured format) */
497
+ delegationHeader: {
498
+ Authorization: string;
499
+ };
500
+ /** The address of the space owner */
501
+ ownerAddress: string;
502
+ /** The chain ID */
503
+ chainId: number;
504
+ /** TinyCloud server URL where this delegation was created */
505
+ host?: string;
506
+ /** Whether the recipient is prevented from creating sub-delegations */
507
+ disableSubDelegation?: boolean;
508
+ /** Companion delegation for the user's public space (auto-created when includePublicSpace is true) */
509
+ publicDelegation?: PortableDelegation;
510
+ /**
511
+ * Full multi-resource grant breakdown. Present when the delegation
512
+ * was issued via the multi-resource WASM path; each entry describes
513
+ * one `(service, space, path, actions)` grant carried by the single
514
+ * underlying UCAN. When absent, only the flat `path` + `actions`
515
+ * fields are authoritative (legacy single-resource shape).
516
+ */
517
+ resources?: DelegatedResource[];
518
+ }
519
+ /**
520
+ * Serialize a PortableDelegation for transport (e.g., over network).
521
+ */
522
+ declare function serializeDelegation(delegation: PortableDelegation): string;
523
+ /**
524
+ * Deserialize a PortableDelegation from transport.
525
+ */
526
+ declare function deserializeDelegation(data: string): PortableDelegation;
527
+
528
+ /**
529
+ * The handles needed to rehydrate this delegation activation in a fresh
530
+ * `TinyCloudNode` via `TinyCloudNode.restoreSession(...)` in another process
531
+ * or after a restart.
532
+ *
533
+ * In wallet mode, `delegationHeader` and `delegationCid` are bound to the
534
+ * session key that ran `useDelegation`. They are NOT intrinsic to the
535
+ * portable delegation — they expire with the server-side session (typically
536
+ * ~1h). To keep a restored node alive longer, re-run `useDelegation` with
537
+ * the original portable delegation and call `restoreSession` again with the
538
+ * fresh `RestorableSession`.
539
+ */
540
+ interface RestorableSession {
541
+ delegationHeader: {
542
+ Authorization: string;
543
+ };
544
+ delegationCid: string;
545
+ spaceId: string;
546
+ jwk: object;
547
+ verificationMethod: string;
548
+ address: string;
549
+ chainId: number;
550
+ }
551
+ /**
552
+ * Provides access to a space via a received delegation.
553
+ *
554
+ * This is returned by TinyCloudNode.useDelegation() and provides
555
+ * KV operations on the delegated space.
556
+ */
557
+ declare class DelegatedAccess {
558
+ private session;
559
+ private _delegation;
560
+ private host;
561
+ private _serviceContext;
562
+ private _kv;
563
+ private _sql;
564
+ private _duckdb;
565
+ private _hooks;
566
+ constructor(session: TinyCloudSession, delegation: PortableDelegation, host: string, invoke: InvokeFunction);
567
+ /**
568
+ * Get the delegation this access was created from.
569
+ */
570
+ get delegation(): PortableDelegation;
571
+ /**
572
+ * The space ID this access is for.
573
+ */
574
+ get spaceId(): string;
575
+ /**
576
+ * The path this access is scoped to.
577
+ */
578
+ get path(): string;
579
+ /**
580
+ * KV operations on the delegated space.
581
+ */
582
+ get kv(): IKVService;
583
+ /**
584
+ * SQL operations on the delegated space.
585
+ */
586
+ get sql(): ISQLService;
587
+ /**
588
+ * DuckDB operations on the delegated space.
589
+ */
590
+ get duckdb(): IDuckDbService;
591
+ /**
592
+ * Hooks write-stream subscriptions on the delegated space.
593
+ */
594
+ get hooks(): IHooksService;
595
+ /**
596
+ * Export the handles needed to rehydrate this activated delegation via
597
+ * `TinyCloudNode.restoreSession(...)` in another process or after a
598
+ * restart.
599
+ *
600
+ * See `RestorableSession` for lifetime caveats.
601
+ */
602
+ get restorable(): RestorableSession;
603
+ }
604
+
605
+ /**
606
+ * TinyCloudNode - High-level API for Node.js users.
607
+ *
608
+ * Each user has their own TinyCloudNode instance with their own key.
609
+ * This class provides a simplified interface for:
610
+ * - Signing in and managing sessions
611
+ * - Key-value storage operations on own space
612
+ * - Creating and using delegations
613
+ *
614
+ * @example
615
+ * ```typescript
616
+ * const alice = new TinyCloudNode({
617
+ * privateKey: process.env.ALICE_PRIVATE_KEY,
618
+ * host: "https://node.tinycloud.xyz",
619
+ * prefix: "myapp",
620
+ * });
621
+ *
622
+ * await alice.signIn();
623
+ * await alice.kv.put("greeting", "Hello, world!");
624
+ *
625
+ * // Delegate access to Bob
626
+ * const delegation = await alice.createDelegation({
627
+ * path: "shared/",
628
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
629
+ * delegateDID: bob.did,
630
+ * });
631
+ *
632
+ * // Bob uses the delegation
633
+ * const access = await bob.useDelegation(delegation);
634
+ * const data = await access.kv.get("shared/data");
635
+ * ```
636
+ */
637
+
638
+ /**
639
+ * Configuration for TinyCloudNode.
640
+ * All fields are optional - TinyCloudNode can work with zero configuration.
641
+ */
642
+ interface TinyCloudNodeConfig {
643
+ /** Hex-encoded private key (with or without 0x prefix). Optional - only needed for wallet mode and signIn() */
644
+ privateKey?: string;
645
+ /** Custom signer implementation. If provided, takes precedence over privateKey. */
646
+ signer?: ISigner;
647
+ /** TinyCloud server URL (default: "https://node.tinycloud.xyz") */
648
+ host?: string;
649
+ /** Space prefix for this user's space. Optional - only needed for signIn() */
650
+ prefix?: string;
651
+ /** Domain for SIWE messages (default: derived from host) */
652
+ domain?: string;
653
+ /** Session expiration time in milliseconds (default: 1 hour) */
654
+ sessionExpirationMs?: number;
655
+ /** Whether to automatically create space if it doesn't exist (default: false) */
656
+ autoCreateSpace?: boolean;
657
+ /** Custom session storage implementation (default: MemorySessionStorage) */
658
+ sessionStorage?: ISessionStorage;
659
+ /** Whether to include public space capabilities in the session (default: true).
660
+ * When true, signIn() automatically includes capabilities for the user's public space,
661
+ * accessible via spaces.get('public').kv */
662
+ enablePublicSpace?: boolean;
663
+ /** Custom WASM bindings (default: @tinycloud/node-sdk-wasm). Used by browser wrapper. */
664
+ wasmBindings?: IWasmBindings;
665
+ /** Notification handler for sign-in/sign-out/error events (default: SilentNotificationHandler) */
666
+ notificationHandler?: INotificationHandler;
667
+ /** ENS resolver for resolving .eth names in delegation methods */
668
+ ensResolver?: IENSResolver;
669
+ /** Custom space creation handler (default: auto-approve when autoCreateSpace is true) */
670
+ spaceCreationHandler?: ISpaceCreationHandler;
671
+ /**
672
+ * SIWE nonce override. If omitted, the WASM layer generates a random nonce.
673
+ * If `siweConfig.nonce` is also provided, `siweConfig.nonce` wins.
674
+ */
675
+ nonce?: string;
676
+ /** Optional SIWE configuration overrides (e.g., nonce for server-provided nonces) */
677
+ siweConfig?: SiweConfig;
678
+ /**
679
+ * App manifest driving the SIWE recap at sign-in.
680
+ *
681
+ * When set, `signIn()` resolves the manifest, unions the app's own
682
+ * permissions with every manifest-declared delegation's permissions,
683
+ * and uses that union as the session's granted capabilities — NOT
684
+ * the legacy `defaultActions` table. This is what makes
685
+ * `delegateTo(manifestDeclaredDid, permissions)` work without a
686
+ * wallet prompt: the session key's recap already covers the
687
+ * delegation target's needs at sign-in time.
688
+ *
689
+ * When omitted, `signIn()` falls back to `defaultActions` for
690
+ * backwards compatibility with callers that pre-date the manifest
691
+ * flow.
692
+ */
693
+ manifest?: Manifest | Manifest[];
694
+ /** Pre-composed manifest request. Takes precedence over `manifest`. */
695
+ capabilityRequest?: ComposedManifestRequest;
696
+ /** Include implicit account registry permissions when composing `manifest`. Default true. */
697
+ includeAccountRegistryPermissions?: boolean;
698
+ }
699
+ /**
700
+ * Options for {@link TinyCloudNode.delegateTo}.
701
+ *
702
+ * `expiry` accepts either an ms-format duration string (e.g. `"7d"`, `"1h"`)
703
+ * or a raw number of milliseconds. When omitted, the default is 1 hour.
704
+ *
705
+ * `forceWalletSign` bypasses the derivability check and sends the
706
+ * delegation through the legacy wallet-signed SIWE path, which always
707
+ * triggers a wallet prompt. Used for testing, for explicit wallet
708
+ * confirmation flows, and by the legacy `createDelegation` fallback.
709
+ */
710
+ interface DelegateToOptions {
711
+ /** Override expiry. ms-format string ("7d", "1h") or raw milliseconds. */
712
+ expiry?: string | number;
713
+ /** Force the wallet-signed SIWE path even if the caps are derivable. Default false. */
714
+ forceWalletSign?: boolean;
715
+ }
716
+ /**
717
+ * Result of {@link TinyCloudNode.delegateTo}.
718
+ *
719
+ * `prompted` indicates whether a wallet prompt was shown — `true` for the
720
+ * legacy wallet path (always), `false` for the session-key UCAN path (never).
721
+ * Callers wiring single-prompt sign-in flows use this to assert that their
722
+ * capability chain was derivable.
723
+ */
724
+ interface DelegateToResult {
725
+ delegation: PortableDelegation;
726
+ prompted: boolean;
727
+ }
728
+ /**
729
+ * High-level TinyCloud API for Node.js environments.
730
+ *
731
+ * Each user creates their own TinyCloudNode instance with their private key.
732
+ * The instance manages the user's session and provides access to their space.
733
+ */
734
+ /** @internal */
735
+ interface NodeDefaults {
736
+ createWasmBindings: () => IWasmBindings;
737
+ createSigner: (privateKey: string, chainId?: number) => ISigner;
738
+ }
739
+ declare class TinyCloudNode {
740
+ /** @internal Registered by importing @tinycloud/node-sdk (not /core) */
741
+ private static nodeDefaults?;
742
+ /** @internal Register Node.js-specific defaults (NodeWasmBindings, PrivateKeySigner) */
743
+ static registerNodeDefaults(defaults: NodeDefaults): void;
744
+ private config;
745
+ private signer;
746
+ private auth;
747
+ private tc;
748
+ private _address?;
749
+ private _chainId;
750
+ private wasmBindings;
751
+ private sessionManager;
752
+ private _serviceContext?;
753
+ private _kv?;
754
+ private _sql?;
755
+ private _duckdb?;
756
+ private _hooks?;
757
+ private _vault?;
758
+ /** Cached public KV with proper delegation (set by ensurePublicSpace) */
759
+ private _publicKV?;
760
+ /** Session key ID - always available */
761
+ private sessionKeyId;
762
+ /** Session key JWK as object - always available */
763
+ private sessionKeyJwk;
764
+ /** Notification handler for user-facing events */
765
+ private notificationHandler;
766
+ private _capabilityRegistry;
767
+ private _keyProvider;
768
+ private _sharingService;
769
+ private _delegationManager?;
770
+ private _spaceService?;
771
+ private get nodeFeatures();
772
+ /** SIWE domain — uses config override or defaults to app.tinycloud.xyz */
773
+ private get siweDomain();
774
+ /**
775
+ * Create a new TinyCloudNode instance.
776
+ *
777
+ * All configuration is optional. Without a privateKey, the instance operates
778
+ * in "session-only" mode where it can receive delegations but cannot create
779
+ * its own space via signIn().
780
+ *
781
+ * @param config - Configuration options (all optional)
782
+ *
783
+ * @example
784
+ * ```typescript
785
+ * // Session-only mode - can receive delegations
786
+ * const bob = new TinyCloudNode();
787
+ * console.log(bob.did); // did:key:z6Mk... - available immediately
788
+ *
789
+ * // Wallet mode - can create own space
790
+ * const alice = new TinyCloudNode({
791
+ * privateKey: process.env.ALICE_PRIVATE_KEY,
792
+ * prefix: "myapp",
793
+ * });
794
+ * await alice.signIn();
795
+ * ```
796
+ */
797
+ constructor(config?: TinyCloudNodeConfig);
798
+ /**
799
+ * Set up authorization handler and TinyCloud instance.
800
+ * @internal
801
+ */
802
+ private setupAuth;
803
+ /**
804
+ * Install or replace the manifest that drives the SIWE recap at
805
+ * sign-in. Takes effect on the next `signIn()` call — the current
806
+ * session (if any) is not touched. Wire this up from a higher
807
+ * layer (e.g. TinyCloudWeb.setManifest) so the manifest is kept
808
+ * in sync across the stack.
809
+ */
810
+ setManifest(manifest: Manifest | Manifest[] | undefined): void;
811
+ setCapabilityRequest(request: ComposedManifestRequest | undefined): void;
812
+ /**
813
+ * Return the manifest currently installed on the auth handler,
814
+ * or `undefined` if none is set.
815
+ */
816
+ get manifest(): Manifest | Manifest[] | undefined;
817
+ get capabilityRequest(): ComposedManifestRequest | undefined;
818
+ /**
819
+ * Get the primary identity DID for this user.
820
+ * - If wallet connected and signed in: returns PKH DID (did:pkh:eip155:{chainId}:{address})
821
+ * - If session-only mode: returns session key DID (did:key:z6Mk...)
822
+ *
823
+ * Use this for delegations - it always returns the appropriate identity.
824
+ */
825
+ get did(): string;
826
+ /**
827
+ * Get the session key DID. Always available.
828
+ * Format: did:key:z6Mk...#z6Mk...
829
+ *
830
+ * Use this when you specifically need the session key, not the user identity.
831
+ */
832
+ get sessionDid(): string;
833
+ /**
834
+ * Get the Ethereum address for this user.
835
+ */
836
+ get address(): string | undefined;
837
+ /**
838
+ * Check if this instance is in session-only mode (no wallet).
839
+ * In session-only mode, the instance can receive delegations but cannot
840
+ * create its own space via signIn().
841
+ */
842
+ get isSessionOnly(): boolean;
843
+ /**
844
+ * Get the space ID for this user.
845
+ * Available after signIn().
846
+ */
847
+ get spaceId(): string | undefined;
848
+ /**
849
+ * Get the current TinyCloud session.
850
+ * Available after signIn().
851
+ */
852
+ get session(): TinyCloudSession | undefined;
853
+ /**
854
+ * Sign in and create a new session.
855
+ * This creates the user's space if it doesn't exist.
856
+ * Requires wallet mode (privateKey in config).
857
+ *
858
+ * @param options - Optional per-call SIWE overrides for this sign-in only
859
+ */
860
+ signIn(options?: SignInOptions): Promise<void>;
861
+ private ownedSpaceId;
862
+ private writeManifestRegistryRecords;
863
+ /**
864
+ * Restore a previously established session from stored delegation data.
865
+ *
866
+ * This is used by the CLI to restore a session that was created via the
867
+ * browser-based delegation flow (OpenKey `/delegate` page). Instead of
868
+ * signing in with a private key, it injects the delegation data directly.
869
+ *
870
+ * @param sessionData - The stored delegation data from the browser flow
871
+ */
872
+ restoreSession(sessionData: {
873
+ delegationHeader: {
874
+ Authorization: string;
875
+ };
876
+ delegationCid: string;
877
+ spaceId: string;
878
+ jwk: object;
879
+ verificationMethod: string;
880
+ address?: string;
881
+ chainId?: number;
882
+ }): Promise<void>;
883
+ /**
884
+ * Connect a wallet to upgrade from session-only mode to wallet mode.
885
+ *
886
+ * This allows a user who started in session-only mode to later connect
887
+ * a wallet and gain the ability to create their own space.
888
+ *
889
+ * Note: This does NOT automatically sign in. Call signIn() after connecting
890
+ * the wallet to create your space.
891
+ *
892
+ * @param privateKey - The Ethereum private key (hex string, no 0x prefix)
893
+ * @param options - Optional configuration
894
+ * @param options.prefix - Space name prefix (defaults to "default")
895
+ *
896
+ * @example
897
+ * ```typescript
898
+ * // Start in session-only mode
899
+ * const node = new TinyCloudNode({ host: "https://node.tinycloud.xyz" });
900
+ * console.log(node.did); // did:key:z6Mk... (session key)
901
+ *
902
+ * // Later, connect a wallet
903
+ * node.connectWallet(privateKey);
904
+ * await node.signIn();
905
+ * console.log(node.did); // did:pkh:eip155:1:0x... (PKH)
906
+ * ```
907
+ */
908
+ connectWallet(privateKey: string, options?: {
909
+ prefix?: string;
910
+ sessionStorage?: ISessionStorage;
911
+ }): void;
912
+ /**
913
+ * Connect any ISigner to upgrade from session-only mode to wallet mode.
914
+ *
915
+ * Same as connectWallet() but accepts any ISigner implementation instead
916
+ * of a raw private key string. Use this for browser wallets, hardware wallets,
917
+ * or custom signing backends.
918
+ *
919
+ * Note: This does NOT automatically sign in. Call signIn() after connecting.
920
+ *
921
+ * @param signer - Any ISigner implementation
922
+ * @param options - Optional configuration
923
+ * @param options.prefix - Space name prefix (defaults to "default")
924
+ */
925
+ connectSigner(signer: ISigner, options?: {
926
+ prefix?: string;
927
+ sessionStorage?: ISessionStorage;
928
+ }): void;
929
+ /**
930
+ * Initialize the service context and KV service after sign-in.
931
+ * @internal
932
+ */
933
+ private initializeServices;
934
+ /**
935
+ * Initialize the v2 delegation system services.
936
+ * @internal
937
+ */
938
+ private initializeV2Services;
939
+ /**
940
+ * Get the session expiry time.
941
+ * @internal
942
+ */
943
+ private getSessionExpiry;
944
+ /**
945
+ * Wrapper for the WASM createDelegation function.
946
+ *
947
+ * The WASM call now takes a multi-resource `abilities` map
948
+ * (matching `prepareSession`'s shape) and emits ONE UCAN that
949
+ * covers every `(service, path, actions)` entry. We mirror the raw
950
+ * result back through `CreateDelegationWasmResult`, converting the
951
+ * seconds-since-epoch `expiry` to a Date and normalizing the
952
+ * `delegateDid` → `delegateDID` case.
953
+ *
954
+ * Both SharingService (single-entry) and
955
+ * {@link TinyCloudNode.delegateTo} (multi-entry) drive this through
956
+ * the same code path so there's exactly one place that touches the
957
+ * WASM boundary.
958
+ *
959
+ * @internal
960
+ */
961
+ private createDelegationWrapper;
962
+ /**
963
+ * Create a direct root delegation from the wallet to a share key.
964
+ * This bypasses the session delegation chain, allowing share links
965
+ * with expiry longer than the current session.
966
+ * @internal
967
+ */
968
+ private createRootDelegationForSharing;
969
+ /**
970
+ * Track a received delegation in the capability registry.
971
+ * @internal
972
+ */
973
+ private trackReceivedDelegation;
974
+ /**
975
+ * Key-value storage operations on this user's space.
976
+ */
977
+ get kv(): IKVService;
978
+ /**
979
+ * SQL database operations on this user's space.
980
+ */
981
+ get sql(): ISQLService;
982
+ /**
983
+ * DuckDB database operations on this user's space.
984
+ */
985
+ get duckdb(): IDuckDbService;
986
+ /**
987
+ * Data Vault operations - client-side encrypted KV storage.
988
+ * Call `vault.unlock(signer)` after signIn() to derive encryption keys.
989
+ */
990
+ get vault(): IDataVaultService;
991
+ /**
992
+ * Hooks write stream subscription API.
993
+ */
994
+ get hooks(): IHooksService;
995
+ /**
996
+ * Get the CapabilityKeyRegistry for managing keys and their capabilities.
997
+ *
998
+ * The registry tracks keys (session, main, ingested) and their associated
999
+ * delegations, enabling automatic key selection for operations.
1000
+ *
1001
+ * @example
1002
+ * ```typescript
1003
+ * const registry = alice.capabilityRegistry;
1004
+ *
1005
+ * // Get the best key for an operation
1006
+ * const key = registry.getKeyForCapability(
1007
+ * "tinycloud://my-space/kv/data",
1008
+ * "tinycloud.kv/get"
1009
+ * );
1010
+ *
1011
+ * // List all capabilities
1012
+ * const capabilities = registry.getAllCapabilities();
1013
+ * ```
1014
+ */
1015
+ get capabilityRegistry(): ICapabilityKeyRegistry;
1016
+ /**
1017
+ * Access received delegations (recipient view).
1018
+ *
1019
+ * Use this to see what delegations have been received via useDelegation().
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * // List all received delegations
1024
+ * const received = bob.delegations.list();
1025
+ * console.log("I have access to:", received.length, "spaces");
1026
+ *
1027
+ * // Get a specific delegation by CID
1028
+ * const delegation = bob.delegations.get(cid);
1029
+ * ```
1030
+ */
1031
+ get delegations(): {
1032
+ /** List all received delegations */
1033
+ list: () => Delegation[];
1034
+ /** Get a delegation by CID */
1035
+ get: (cid: string) => Delegation | undefined;
1036
+ };
1037
+ /**
1038
+ * Get the DelegationManager for delegation CRUD operations.
1039
+ *
1040
+ * This is the v2 delegation service providing a cleaner API than
1041
+ * the legacy createDelegation/useDelegation methods.
1042
+ *
1043
+ * @example
1044
+ * ```typescript
1045
+ * const delegations = alice.delegationManager;
1046
+ *
1047
+ * // Create a delegation
1048
+ * const result = await delegations.create({
1049
+ * delegateDID: bob.did,
1050
+ * path: "shared/",
1051
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
1052
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
1053
+ * });
1054
+ *
1055
+ * // List delegations
1056
+ * const listResult = await delegations.list();
1057
+ *
1058
+ * // Revoke a delegation
1059
+ * await delegations.revoke(delegationCid);
1060
+ * ```
1061
+ */
1062
+ get delegationManager(): DelegationManager;
1063
+ /**
1064
+ * Get the SpaceService for managing spaces.
1065
+ *
1066
+ * The SpaceService provides access to owned and delegated spaces,
1067
+ * including space creation, listing, and scoped operations.
1068
+ *
1069
+ * @example
1070
+ * ```typescript
1071
+ * const spaces = alice.spaces;
1072
+ *
1073
+ * // List all accessible spaces
1074
+ * const result = await spaces.list();
1075
+ *
1076
+ * // Create a new space
1077
+ * const createResult = await spaces.create('photos');
1078
+ *
1079
+ * // Get a space object for operations
1080
+ * const mySpace = spaces.get('default');
1081
+ * await mySpace.kv.put('key', 'value');
1082
+ *
1083
+ * // Check if a space exists
1084
+ * const exists = await spaces.exists('photos');
1085
+ * ```
1086
+ */
1087
+ get spaces(): ISpaceService;
1088
+ /**
1089
+ * Alias for `spaces` - get the SpaceService.
1090
+ * @see spaces
1091
+ */
1092
+ get spaceService(): ISpaceService;
1093
+ /**
1094
+ * Get the SharingService for creating and receiving v2 sharing links.
1095
+ *
1096
+ * The SharingService creates sharing links with embedded private keys,
1097
+ * allowing recipients to exercise delegations without prior session setup.
1098
+ *
1099
+ * @example
1100
+ * ```typescript
1101
+ * const sharing = alice.sharing;
1102
+ *
1103
+ * // Generate a sharing link
1104
+ * const result = await sharing.generate({
1105
+ * path: "/kv/documents/report.pdf",
1106
+ * actions: ["tinycloud.kv/get"],
1107
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
1108
+ * });
1109
+ *
1110
+ * if (result.ok) {
1111
+ * console.log("Share URL:", result.data.url);
1112
+ * // Send the URL to the recipient
1113
+ * }
1114
+ *
1115
+ * // Receive a sharing link
1116
+ * const receiveResult = await sharing.receive(shareUrl);
1117
+ * if (receiveResult.ok) {
1118
+ * // Use the pre-configured KV service
1119
+ * const data = await receiveResult.data.kv.get("report.pdf");
1120
+ * }
1121
+ * ```
1122
+ */
1123
+ get sharing(): ISharingService;
1124
+ /**
1125
+ * Alias for `sharing` - get the SharingService.
1126
+ * @see sharing
1127
+ */
1128
+ get sharingService(): ISharingService;
1129
+ /**
1130
+ * Ensure the user's public space exists and is accessible.
1131
+ * Creates the space and activates a session delegation for it.
1132
+ * This is the trigger for lazy public space creation — call it
1133
+ * before writing to spaces.get('public').kv.
1134
+ */
1135
+ ensurePublicSpace(): Promise<void>;
1136
+ /**
1137
+ * Get a KVService scoped to the user's own public space.
1138
+ * Writes require authentication (owner/delegate).
1139
+ */
1140
+ get publicKV(): IKVService;
1141
+ /**
1142
+ * Create a delegation using the v2 DelegationManager.
1143
+ *
1144
+ * This is a convenience method that wraps DelegationManager.create().
1145
+ * For more control, use `this.delegationManager` directly.
1146
+ *
1147
+ * @param params - Delegation parameters
1148
+ * @returns Result containing the created Delegation
1149
+ *
1150
+ * @example
1151
+ * ```typescript
1152
+ * const result = await alice.delegate({
1153
+ * delegateDID: bob.did,
1154
+ * path: "shared/",
1155
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
1156
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
1157
+ * });
1158
+ *
1159
+ * if (result.ok) {
1160
+ * console.log("Delegation created:", result.data.cid);
1161
+ * }
1162
+ * ```
1163
+ */
1164
+ delegate(params: CreateDelegationParams): Promise<DelegationResult<Delegation>>;
1165
+ /**
1166
+ * Revoke a delegation using the v2 DelegationManager.
1167
+ *
1168
+ * @param cid - The CID of the delegation to revoke
1169
+ * @returns Result indicating success or failure
1170
+ */
1171
+ revokeDelegation(cid: string): Promise<DelegationResult<void>>;
1172
+ /**
1173
+ * List all delegations for the current session's space.
1174
+ *
1175
+ * @returns Result containing an array of Delegations
1176
+ */
1177
+ listDelegations(): Promise<DelegationResult<Delegation[]>>;
1178
+ /**
1179
+ * Check if the current session has permission for a path and action.
1180
+ *
1181
+ * @param path - The resource path to check
1182
+ * @param action - The action to check (e.g., "tinycloud.kv/get")
1183
+ * @returns Result containing boolean permission status
1184
+ */
1185
+ checkPermission(path: string, action: string): Promise<DelegationResult<boolean>>;
1186
+ /**
1187
+ * Safety margin before the session's own expiry at which {@link delegateTo}
1188
+ * will refuse to issue a derived delegation. Prevents issuing sub-delegations
1189
+ * that would be invalid by the time the recipient used them. Spec: 60 seconds.
1190
+ *
1191
+ * @internal
1192
+ */
1193
+ private static readonly SESSION_EXPIRY_SAFETY_MARGIN_MS;
1194
+ /**
1195
+ * Issue a delegation using the capability-chain flow.
1196
+ *
1197
+ * When every requested permission is a subset of the current
1198
+ * session's recap, the delegation is signed by the session key via
1199
+ * WASM — no wallet prompt. When at least one is NOT derivable, a
1200
+ * {@link PermissionNotInManifestError} is raised (carrying the
1201
+ * missing entries) so the caller can trigger an escalation flow
1202
+ * (e.g. `TinyCloudWeb.requestPermissions`). Passing
1203
+ * `forceWalletSign: true` bypasses the derivability check and
1204
+ * always uses the wallet-signed SIWE path — used by the legacy
1205
+ * `createDelegation` fallback and by callers that want explicit
1206
+ * wallet confirmation.
1207
+ *
1208
+ * Multi-entry delegations are now emitted as **one** signed UCAN:
1209
+ * the underlying WASM `createDelegation` takes a full
1210
+ * `HashMap<Service, HashMap<Path, Vec<Ability>>>` abilities map
1211
+ * and produces a single attenuation carrying every
1212
+ * `(service, path, actions)` entry. The returned
1213
+ * {@link DelegateToResult.delegation} is that single blob, and
1214
+ * apps can POST it to their backend exactly like a single-entry
1215
+ * delegation (the server verifies all granted resources from one
1216
+ * UCAN).
1217
+ *
1218
+ * For single-entry requests the `PortableDelegation.path` and
1219
+ * `.actions` fields mirror the one granted entry. For
1220
+ * multi-entry requests they mirror the **first** entry (stable
1221
+ * lexicographic order from the Rust side); consumers that need
1222
+ * the full picture read `PortableDelegation.resources`.
1223
+ *
1224
+ * @throws {@link SessionExpiredError} when there is no session or
1225
+ * the current session has expired (or will within the 60s
1226
+ * safety margin).
1227
+ * @throws {@link PermissionNotInManifestError} when any requested
1228
+ * entry is not a subset of the granted session capabilities and
1229
+ * `forceWalletSign` is not set.
1230
+ */
1231
+ delegateTo(did: string, permissions: PermissionEntry[], options?: DelegateToOptions): Promise<DelegateToResult>;
1232
+ /**
1233
+ * Materialize one manifest-declared delegation using the current session key.
1234
+ * Delivery is intentionally out of band; callers decide how to transmit the
1235
+ * returned UCAN to the delegate.
1236
+ */
1237
+ materializeDelegation(did: string, request?: ComposedManifestRequest | undefined): Promise<DelegateToResult & {
1238
+ target: ResolvedDelegate;
1239
+ }>;
1240
+ /**
1241
+ * Materialize every delegation target declared by the composed manifest
1242
+ * request. This does not deliver the delegations anywhere.
1243
+ */
1244
+ materializeDelegations(request?: ComposedManifestRequest | undefined): Promise<Array<DelegateToResult & {
1245
+ target: ResolvedDelegate;
1246
+ }>>;
1247
+ /**
1248
+ * Issue a delegation via the session-key UCAN WASM path.
1249
+ *
1250
+ * The caller has already verified every entry is derivable from
1251
+ * the current session; we build one multi-resource abilities map
1252
+ * and emit one signed UCAN covering them all.
1253
+ *
1254
+ * All entries must share the same target space (the UCAN is
1255
+ * scoped to a single space). If they don't, this throws — mixing
1256
+ * spaces in a single delegation is not supported by the underlying
1257
+ * Rust create_delegation call and the resulting UCAN would be
1258
+ * under-specified.
1259
+ *
1260
+ * @internal
1261
+ */
1262
+ private createDelegationViaWasmPath;
1263
+ private resolvePermissionSpace;
1264
+ /**
1265
+ * Issue a delegation via the legacy wallet-signed SIWE path for a single
1266
+ * {@link PermissionEntry}. Shares the implementation with the public
1267
+ * `createDelegation` method via {@link createDelegationWalletPath} so
1268
+ * both entry points hit exactly the same SIWE / signer / public-space
1269
+ * logic without mutual recursion.
1270
+ *
1271
+ * @internal
1272
+ */
1273
+ private createDelegationLegacyWalletPath;
1274
+ /**
1275
+ * Create a delegation from this user to another user.
1276
+ *
1277
+ * The delegation grants the recipient access to a specific path and actions
1278
+ * within this user's space.
1279
+ *
1280
+ * @param params - Delegation parameters
1281
+ * @returns A portable delegation that can be sent to the recipient
1282
+ */
1283
+ createDelegation(params: {
1284
+ /** Path within the space to delegate access to */
1285
+ path: string;
1286
+ /** Actions to allow (e.g., ["tinycloud.kv/get", "tinycloud.kv/put"]) */
1287
+ actions: string[];
1288
+ /** DID of the recipient (from their TinyCloudNode.did) */
1289
+ delegateDID: string;
1290
+ /** Whether to prevent the recipient from creating sub-delegations (default: false) */
1291
+ disableSubDelegation?: boolean;
1292
+ /** Expiration time in milliseconds from now (default: 1 hour) */
1293
+ expiryMs?: number;
1294
+ /** Override space ID (for creating delegations to non-primary spaces like public) */
1295
+ spaceIdOverride?: string;
1296
+ /** Include a companion delegation for the user's public space (default: true) */
1297
+ includePublicSpace?: boolean;
1298
+ }): Promise<PortableDelegation>;
1299
+ /**
1300
+ * Legacy wallet-signed SIWE delegation path. Lifted from the original
1301
+ * `createDelegation` body verbatim so both the legacy public method and
1302
+ * `delegateTo({ forceWalletSign: true })` hit the same code.
1303
+ *
1304
+ * @internal
1305
+ */
1306
+ private createDelegationWalletPath;
1307
+ /**
1308
+ * Use a delegation received from another user.
1309
+ *
1310
+ * This creates a new session key for this user that chains from the
1311
+ * received delegation, allowing operations on the delegator's space.
1312
+ *
1313
+ * Works in both modes:
1314
+ * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key
1315
+ * - **Session-only mode**: Uses the delegation directly (must target session key DID)
1316
+ *
1317
+ * @param delegation - The PortableDelegation to use (from createDelegation or transport)
1318
+ * @returns A DelegatedAccess instance for performing operations
1319
+ */
1320
+ useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess>;
1321
+ /**
1322
+ * Create a sub-delegation from a received delegation.
1323
+ *
1324
+ * This allows further delegating access that was received from another user,
1325
+ * if the original delegation allows sub-delegation.
1326
+ *
1327
+ * @param parentDelegation - The delegation received from another user
1328
+ * @param params - Sub-delegation parameters (must be within parent's scope)
1329
+ * @returns A portable delegation for the sub-delegate
1330
+ */
1331
+ createSubDelegation(parentDelegation: PortableDelegation, params: {
1332
+ /** Path within the delegated path to sub-delegate */
1333
+ path: string;
1334
+ /** Actions to allow (must be subset of parent's actions) */
1335
+ actions: string[];
1336
+ /** DID of the recipient */
1337
+ delegateDID: string;
1338
+ /** Whether to prevent the recipient from creating further sub-delegations */
1339
+ disableSubDelegation?: boolean;
1340
+ /** Expiration time in milliseconds from now (must be before parent's expiry) */
1341
+ expiryMs?: number;
1342
+ }): Promise<PortableDelegation>;
1343
+ }
1344
+
1345
+ /**
1346
+ * WasmKeyProvider - KeyProvider implementation using WASM session manager.
1347
+ *
1348
+ * This provider wraps the SessionManager from node-sdk-wasm to provide
1349
+ * cryptographic key operations required by the SharingService.
1350
+ *
1351
+ * @packageDocumentation
1352
+ */
1353
+
1354
+ /**
1355
+ * Extended session manager with optional key listing support.
1356
+ * The base ISessionManager doesn't include listSessionKeys(),
1357
+ * but concrete implementations (e.g., TCWSessionManager) may provide it.
1358
+ */
1359
+ interface SessionManagerWithListing extends ISessionManager {
1360
+ listSessionKeys?(): string[];
1361
+ }
1362
+ /**
1363
+ * Configuration for WasmKeyProvider.
1364
+ */
1365
+ interface WasmKeyProviderConfig {
1366
+ /**
1367
+ * The WASM session manager instance.
1368
+ * Must be created before constructing the KeyProvider.
1369
+ */
1370
+ sessionManager: SessionManagerWithListing;
1371
+ }
1372
+ /**
1373
+ * KeyProvider implementation that wraps the WASM session manager.
1374
+ *
1375
+ * This allows the SharingService to create new session keys for sharing links
1376
+ * using the same cryptographic operations as the main session management.
1377
+ *
1378
+ * @example
1379
+ * ```typescript
1380
+ * // sessionManager from wasmBindings.createSessionManager()
1381
+ * import { WasmKeyProvider } from "@tinycloud/node-sdk";
1382
+ *
1383
+ * const sessionManager = new SessionManager();
1384
+ * const keyProvider = new WasmKeyProvider({ sessionManager });
1385
+ *
1386
+ * // Create a session key for a sharing link
1387
+ * const keyId = await keyProvider.createSessionKey("share:abc123");
1388
+ * const jwk = keyProvider.getJWK(keyId);
1389
+ * const did = await keyProvider.getDID(keyId);
1390
+ * ```
1391
+ */
1392
+ declare class WasmKeyProvider implements KeyProvider {
1393
+ private sessionManager;
1394
+ /**
1395
+ * Create a new WasmKeyProvider.
1396
+ *
1397
+ * @param config - Configuration with the WASM session manager
1398
+ */
1399
+ constructor(config: WasmKeyProviderConfig);
1400
+ /**
1401
+ * Generate a new session key with the given name.
1402
+ *
1403
+ * This creates a new Ed25519 key pair in the WASM session manager.
1404
+ * The key can then be used for signing delegations in sharing links.
1405
+ *
1406
+ * @param name - A unique name/ID for the key (e.g., "share:timestamp:random")
1407
+ * @returns The key ID (same as the name provided)
1408
+ */
1409
+ createSessionKey(name: string): Promise<string>;
1410
+ /**
1411
+ * Get the JWK (JSON Web Key) for a key.
1412
+ *
1413
+ * Returns the full JWK including the private key (d parameter),
1414
+ * which is required for signing and for embedding in sharing links.
1415
+ *
1416
+ * @param keyId - The key ID to retrieve
1417
+ * @returns The JWK object with public and private key components
1418
+ * @throws Error if the key is not found
1419
+ */
1420
+ getJWK(keyId: string): JWK;
1421
+ /**
1422
+ * Get the DID (Decentralized Identifier) for a key.
1423
+ *
1424
+ * Returns the did:key format DID derived from the key's public key.
1425
+ * This DID can be used as the delegatee in delegations.
1426
+ *
1427
+ * @param keyId - The key ID to retrieve
1428
+ * @returns The DID in did:key format (e.g., "did:key:z6Mk...")
1429
+ */
1430
+ getDID(keyId: string): Promise<string>;
1431
+ /**
1432
+ * List all session keys currently held by the provider.
1433
+ *
1434
+ * @returns Array of key IDs
1435
+ */
1436
+ listKeys(): string[];
1437
+ /**
1438
+ * Check if a key exists in the provider.
1439
+ *
1440
+ * @param keyId - The key ID to check
1441
+ * @returns True if the key exists
1442
+ */
1443
+ hasKey(keyId: string): boolean;
1444
+ }
1445
+ /**
1446
+ * Create a new WasmKeyProvider instance.
1447
+ *
1448
+ * @param sessionManager - The WASM session manager
1449
+ * @returns A new WasmKeyProvider instance
1450
+ */
1451
+ declare function createWasmKeyProvider(sessionManager: SessionManagerWithListing): WasmKeyProvider;
1452
+
1453
+ export { type DelegateToOptions as D, FileSessionStorage as F, MemorySessionStorage as M, type NodeEventEmitterStrategy as N, type PortableDelegation as P, type RestorableSession as R, type SignStrategy as S, TinyCloudNode as T, WasmKeyProvider as W, type DelegateToResult as a, DelegatedAccess as b, NodeUserAuthorization as c, type NodeUserAuthorizationConfig as d, type TinyCloudNodeConfig as e, type WasmKeyProviderConfig as f, createWasmKeyProvider as g, defaultSignStrategy as h, deserializeDelegation as i, serializeDelegation as s };