@tinycloud/node-sdk 2.2.0-beta.0 → 2.2.0-beta.10

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