@tinycloud/node-sdk 1.6.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.d.ts ADDED
@@ -0,0 +1,1114 @@
1
+ import { ISessionStorage, PersistedSessionData, AutoSignStrategy, AutoRejectStrategy, CallbackStrategy, IUserAuthorization, ISigner, ISpaceCreationHandler, IWasmBindings, ClientSession, TinyCloudSession, Extension, Delegation, IKVService, ISQLService, IDuckDbService, INotificationHandler, IENSResolver, IDataVaultService, ICapabilityKeyRegistry, DelegationManager, ISpaceService, ISharingService, CreateDelegationParams, DelegationResult, KeyProvider, ISessionManager, JWK } from '@tinycloud/sdk-core';
2
+ export { AutoApproveSpaceCreationHandler, AutoRejectStrategy, AutoSignStrategy, BatchOptions, BatchResponse, CallbackStrategy, CapabilityEntry, CapabilityKeyRegistry, CapabilityKeyRegistryErrorCode, CapabilityKeyRegistryErrorCodes, ClientSession, ColumnInfo, CreateDelegationParams, 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, PersistedSessionData, PrefixedKVService, ProtocolMismatchError, QueryOptions, QueryResponse, ReceiveOptions, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SchemaInfo, ServiceContext, ServiceContextConfig, ServiceSession, ShareAccess, ShareLink, ShareLinkData, ShareSchema, SharingService, SharingServiceConfig, SignCallback, SignRequest, SignResponse, SilentNotificationHandler, Space, 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, createCapabilityKeyRegistry, createSharingService, createSpaceService, createVaultCrypto, defaultSpaceCreationHandler, makePublicSpaceId, parseSpaceUri } 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
+ /**
201
+ * Node.js implementation of IUserAuthorization.
202
+ *
203
+ * Supports multiple sign strategies for different use cases:
204
+ * - auto-sign: Automatically approve all sign requests (trusted backends)
205
+ * - auto-reject: Reject all sign requests (read-only mode)
206
+ * - callback: Delegate to a custom callback function (CLI prompts)
207
+ * - event-emitter: Emit sign requests as events (async workflows)
208
+ *
209
+ * @example
210
+ * ```typescript
211
+ * // Auto-sign for backend services
212
+ * const auth = new NodeUserAuthorization({
213
+ * signer: new PrivateKeySigner(process.env.PRIVATE_KEY),
214
+ * signStrategy: { type: 'auto-sign' },
215
+ * domain: 'api.myapp.com',
216
+ * });
217
+ *
218
+ * // Callback for CLI prompts
219
+ * const auth = new NodeUserAuthorization({
220
+ * signer,
221
+ * signStrategy: {
222
+ * type: 'callback',
223
+ * handler: async (req) => {
224
+ * const approved = await promptUser(`Sign for ${req.address}?`);
225
+ * return { approved };
226
+ * }
227
+ * },
228
+ * domain: 'cli.myapp.com',
229
+ * });
230
+ * ```
231
+ */
232
+ declare class NodeUserAuthorization implements IUserAuthorization {
233
+ private readonly signer;
234
+ private readonly signStrategy;
235
+ private readonly sessionStorage;
236
+ private readonly domain;
237
+ private readonly uri;
238
+ private readonly statement?;
239
+ private readonly spacePrefix;
240
+ private readonly defaultActions;
241
+ private readonly sessionExpirationMs;
242
+ private readonly autoCreateSpace;
243
+ private readonly spaceCreationHandler?;
244
+ private readonly tinycloudHosts;
245
+ private readonly enablePublicSpace;
246
+ private readonly wasm;
247
+ private sessionManager;
248
+ private extensions;
249
+ private _session?;
250
+ private _tinyCloudSession?;
251
+ private _address?;
252
+ private _chainId?;
253
+ private _nodeFeatures;
254
+ constructor(config: NodeUserAuthorizationConfig);
255
+ /**
256
+ * The current active session (web-core compatible).
257
+ */
258
+ get session(): ClientSession | undefined;
259
+ /**
260
+ * The current TinyCloud session with full delegation data.
261
+ * Includes spaceId, delegationHeader, and delegationCid.
262
+ */
263
+ get tinyCloudSession(): TinyCloudSession | undefined;
264
+ get nodeFeatures(): string[];
265
+ /**
266
+ * Add an extension to the authorization flow.
267
+ */
268
+ extend(extension: Extension): void;
269
+ /**
270
+ * Get the space ID for the current session.
271
+ */
272
+ getSpaceId(): string | undefined;
273
+ /**
274
+ * Create the space on the TinyCloud server (host delegation).
275
+ * This registers the user as the owner of the space.
276
+ */
277
+ private hostSpace;
278
+ /**
279
+ * Create a specific space on the server via host delegation.
280
+ * Used for lazy creation of additional spaces (e.g., public).
281
+ */
282
+ hostPublicSpace(spaceId: string): Promise<boolean>;
283
+ /**
284
+ * Ensure the user's space exists on the TinyCloud server.
285
+ * Creates the space if it doesn't exist and autoCreateSpace is enabled.
286
+ * If autoCreateSpace is false and space doesn't exist, silently returns
287
+ * (user may be using delegations to access other spaces).
288
+ *
289
+ * @throws Error if space creation fails
290
+ */
291
+ ensureSpaceExists(): Promise<void>;
292
+ /**
293
+ * Sign in and create a new session.
294
+ *
295
+ * This follows the correct SIWE-ReCap flow:
296
+ * 1. Create session key and get JWK
297
+ * 2. Call prepareSession() which generates the SIWE with ReCap capabilities
298
+ * 3. Sign the SIWE string from prepareSession
299
+ * 4. Call completeSessionSetup() with the prepared session + signature
300
+ */
301
+ signIn(): Promise<ClientSession>;
302
+ /**
303
+ * Sign out and clear the current session.
304
+ */
305
+ signOut(): Promise<void>;
306
+ /**
307
+ * Get the current wallet/signer address.
308
+ */
309
+ address(): string | undefined;
310
+ /**
311
+ * Get the current chain ID.
312
+ */
313
+ chainId(): number | undefined;
314
+ /**
315
+ * Sign a message with the connected signer.
316
+ */
317
+ signMessage(message: string): Promise<string>;
318
+ /**
319
+ * Prepare a session for external signing.
320
+ *
321
+ * Use this method when you need to sign the SIWE message externally (e.g., via
322
+ * a hardware wallet, multi-sig, or external service). After obtaining the signature,
323
+ * call `signInWithPreparedSession()` to complete the sign-in.
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * const { prepared, keyId, jwk } = await auth.prepareSessionForSigning();
328
+ * const signature = await externalSigner.signMessage(prepared.siwe);
329
+ * const session = await auth.signInWithPreparedSession(prepared, signature, keyId, jwk);
330
+ * ```
331
+ */
332
+ prepareSessionForSigning(): Promise<{
333
+ prepared: {
334
+ siwe: string;
335
+ jwk: Record<string, unknown>;
336
+ spaceId: string;
337
+ verificationMethod: string;
338
+ };
339
+ keyId: string;
340
+ jwk: Record<string, unknown>;
341
+ address: string;
342
+ chainId: number;
343
+ }>;
344
+ /**
345
+ * Complete sign-in with a prepared session and signature.
346
+ *
347
+ * Use this method after obtaining a signature for the SIWE message from
348
+ * `prepareSessionForSigning()`. The signature MUST be over `prepared.siwe`.
349
+ *
350
+ * @param prepared - The prepared session from `prepareSessionForSigning()`
351
+ * @param signature - The signature over `prepared.siwe`
352
+ * @param keyId - The session key ID from `prepareSessionForSigning()`
353
+ * @param jwk - The JWK from `prepareSessionForSigning()`
354
+ */
355
+ signInWithPreparedSession(prepared: {
356
+ siwe: string;
357
+ jwk: Record<string, unknown>;
358
+ spaceId: string;
359
+ verificationMethod: string;
360
+ }, signature: string, keyId: string, jwk: Record<string, unknown>): Promise<ClientSession>;
361
+ /**
362
+ * Clear persisted session data.
363
+ */
364
+ clearPersistedSession(address?: string): Promise<void>;
365
+ /**
366
+ * Check if a session is persisted for an address.
367
+ */
368
+ isSessionPersisted(address: string): boolean;
369
+ /**
370
+ * Request a signature based on the configured strategy.
371
+ */
372
+ private requestSignature;
373
+ /**
374
+ * Request signature via event emitter with timeout.
375
+ */
376
+ private requestSignatureViaEmitter;
377
+ }
378
+
379
+ /**
380
+ * A portable delegation that can be transported between users.
381
+ * Extends the base Delegation type with fields required for transport.
382
+ *
383
+ * @remarks
384
+ * PortableDelegation adds transport fields to Delegation:
385
+ * - `delegationHeader`: Structured authorization header for API calls
386
+ * - `ownerAddress`: Space owner's address for session creation
387
+ * - `chainId`: Chain ID for session creation
388
+ * - `host`: Optional server URL
389
+ */
390
+ interface PortableDelegation extends Omit<Delegation, "isRevoked"> {
391
+ /** The authorization header for this delegation (structured format) */
392
+ delegationHeader: {
393
+ Authorization: string;
394
+ };
395
+ /** The address of the space owner */
396
+ ownerAddress: string;
397
+ /** The chain ID */
398
+ chainId: number;
399
+ /** TinyCloud server URL where this delegation was created */
400
+ host?: string;
401
+ /** Whether the recipient is prevented from creating sub-delegations */
402
+ disableSubDelegation?: boolean;
403
+ /** Companion delegation for the user's public space (auto-created when includePublicSpace is true) */
404
+ publicDelegation?: PortableDelegation;
405
+ }
406
+ /**
407
+ * Serialize a PortableDelegation for transport (e.g., over network).
408
+ */
409
+ declare function serializeDelegation(delegation: PortableDelegation): string;
410
+ /**
411
+ * Deserialize a PortableDelegation from transport.
412
+ */
413
+ declare function deserializeDelegation(data: string): PortableDelegation;
414
+
415
+ /**
416
+ * Provides access to a space via a received delegation.
417
+ *
418
+ * This is returned by TinyCloudNode.useDelegation() and provides
419
+ * KV operations on the delegated space.
420
+ */
421
+ declare class DelegatedAccess {
422
+ private session;
423
+ private _delegation;
424
+ private host;
425
+ private _serviceContext;
426
+ private _kv;
427
+ private _sql;
428
+ private _duckdb;
429
+ constructor(session: TinyCloudSession, delegation: PortableDelegation, host: string, invoke: InvokeFunction);
430
+ /**
431
+ * Get the delegation this access was created from.
432
+ */
433
+ get delegation(): PortableDelegation;
434
+ /**
435
+ * The space ID this access is for.
436
+ */
437
+ get spaceId(): string;
438
+ /**
439
+ * The path this access is scoped to.
440
+ */
441
+ get path(): string;
442
+ /**
443
+ * KV operations on the delegated space.
444
+ */
445
+ get kv(): IKVService;
446
+ /**
447
+ * SQL operations on the delegated space.
448
+ */
449
+ get sql(): ISQLService;
450
+ /**
451
+ * DuckDB operations on the delegated space.
452
+ */
453
+ get duckdb(): IDuckDbService;
454
+ }
455
+
456
+ /**
457
+ * TinyCloudNode - High-level API for Node.js users.
458
+ *
459
+ * Each user has their own TinyCloudNode instance with their own key.
460
+ * This class provides a simplified interface for:
461
+ * - Signing in and managing sessions
462
+ * - Key-value storage operations on own space
463
+ * - Creating and using delegations
464
+ *
465
+ * @example
466
+ * ```typescript
467
+ * const alice = new TinyCloudNode({
468
+ * privateKey: process.env.ALICE_PRIVATE_KEY,
469
+ * host: "https://node.tinycloud.xyz",
470
+ * prefix: "myapp",
471
+ * });
472
+ *
473
+ * await alice.signIn();
474
+ * await alice.kv.put("greeting", "Hello, world!");
475
+ *
476
+ * // Delegate access to Bob
477
+ * const delegation = await alice.createDelegation({
478
+ * path: "shared/",
479
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
480
+ * delegateDID: bob.did,
481
+ * });
482
+ *
483
+ * // Bob uses the delegation
484
+ * const access = await bob.useDelegation(delegation);
485
+ * const data = await access.kv.get("shared/data");
486
+ * ```
487
+ */
488
+
489
+ /**
490
+ * Configuration for TinyCloudNode.
491
+ * All fields are optional - TinyCloudNode can work with zero configuration.
492
+ */
493
+ interface TinyCloudNodeConfig {
494
+ /** Hex-encoded private key (with or without 0x prefix). Optional - only needed for wallet mode and signIn() */
495
+ privateKey?: string;
496
+ /** Custom signer implementation. If provided, takes precedence over privateKey. */
497
+ signer?: ISigner;
498
+ /** TinyCloud server URL (default: "https://node.tinycloud.xyz") */
499
+ host?: string;
500
+ /** Space prefix for this user's space. Optional - only needed for signIn() */
501
+ prefix?: string;
502
+ /** Domain for SIWE messages (default: derived from host) */
503
+ domain?: string;
504
+ /** Session expiration time in milliseconds (default: 1 hour) */
505
+ sessionExpirationMs?: number;
506
+ /** Whether to automatically create space if it doesn't exist (default: false) */
507
+ autoCreateSpace?: boolean;
508
+ /** Custom session storage implementation (default: MemorySessionStorage) */
509
+ sessionStorage?: ISessionStorage;
510
+ /** Whether to include public space capabilities in the session (default: true).
511
+ * When true, signIn() automatically includes capabilities for the user's public space,
512
+ * accessible via spaces.get('public').kv */
513
+ enablePublicSpace?: boolean;
514
+ /** Custom WASM bindings (default: @tinycloud/node-sdk-wasm). Used by browser wrapper. */
515
+ wasmBindings?: IWasmBindings;
516
+ /** Notification handler for sign-in/sign-out/error events (default: SilentNotificationHandler) */
517
+ notificationHandler?: INotificationHandler;
518
+ /** ENS resolver for resolving .eth names in delegation methods */
519
+ ensResolver?: IENSResolver;
520
+ /** Custom space creation handler (default: auto-approve when autoCreateSpace is true) */
521
+ spaceCreationHandler?: ISpaceCreationHandler;
522
+ }
523
+ /**
524
+ * High-level TinyCloud API for Node.js environments.
525
+ *
526
+ * Each user creates their own TinyCloudNode instance with their private key.
527
+ * The instance manages the user's session and provides access to their space.
528
+ */
529
+ /** @internal */
530
+ interface NodeDefaults {
531
+ createWasmBindings: () => IWasmBindings;
532
+ createSigner: (privateKey: string, chainId?: number) => ISigner;
533
+ }
534
+ declare class TinyCloudNode {
535
+ /** @internal Registered by importing @tinycloud/node-sdk (not /core) */
536
+ private static nodeDefaults?;
537
+ /** @internal Register Node.js-specific defaults (NodeWasmBindings, PrivateKeySigner) */
538
+ static registerNodeDefaults(defaults: NodeDefaults): void;
539
+ private config;
540
+ private signer;
541
+ private auth;
542
+ private tc;
543
+ private _address?;
544
+ private _chainId;
545
+ private wasmBindings;
546
+ private sessionManager;
547
+ private _serviceContext?;
548
+ private _kv?;
549
+ private _sql?;
550
+ private _duckdb?;
551
+ private _vault?;
552
+ /** Cached public KV with proper delegation (set by ensurePublicSpace) */
553
+ private _publicKV?;
554
+ /** Session key ID - always available */
555
+ private sessionKeyId;
556
+ /** Session key JWK as object - always available */
557
+ private sessionKeyJwk;
558
+ /** Notification handler for user-facing events */
559
+ private notificationHandler;
560
+ private _capabilityRegistry;
561
+ private _keyProvider;
562
+ private _sharingService;
563
+ private _delegationManager?;
564
+ private _spaceService?;
565
+ private get nodeFeatures();
566
+ /**
567
+ * Create a new TinyCloudNode instance.
568
+ *
569
+ * All configuration is optional. Without a privateKey, the instance operates
570
+ * in "session-only" mode where it can receive delegations but cannot create
571
+ * its own space via signIn().
572
+ *
573
+ * @param config - Configuration options (all optional)
574
+ *
575
+ * @example
576
+ * ```typescript
577
+ * // Session-only mode - can receive delegations
578
+ * const bob = new TinyCloudNode();
579
+ * console.log(bob.did); // did:key:z6Mk... - available immediately
580
+ *
581
+ * // Wallet mode - can create own space
582
+ * const alice = new TinyCloudNode({
583
+ * privateKey: process.env.ALICE_PRIVATE_KEY,
584
+ * prefix: "myapp",
585
+ * });
586
+ * await alice.signIn();
587
+ * ```
588
+ */
589
+ constructor(config?: TinyCloudNodeConfig);
590
+ /**
591
+ * Set up authorization handler and TinyCloud instance.
592
+ * @internal
593
+ */
594
+ private setupAuth;
595
+ /**
596
+ * Get the primary identity DID for this user.
597
+ * - If wallet connected and signed in: returns PKH DID (did:pkh:eip155:{chainId}:{address})
598
+ * - If session-only mode: returns session key DID (did:key:z6Mk...)
599
+ *
600
+ * Use this for delegations - it always returns the appropriate identity.
601
+ */
602
+ get did(): string;
603
+ /**
604
+ * Get the session key DID. Always available.
605
+ * Format: did:key:z6Mk...#z6Mk...
606
+ *
607
+ * Use this when you specifically need the session key, not the user identity.
608
+ */
609
+ get sessionDid(): string;
610
+ /**
611
+ * Get the Ethereum address for this user.
612
+ */
613
+ get address(): string | undefined;
614
+ /**
615
+ * Check if this instance is in session-only mode (no wallet).
616
+ * In session-only mode, the instance can receive delegations but cannot
617
+ * create its own space via signIn().
618
+ */
619
+ get isSessionOnly(): boolean;
620
+ /**
621
+ * Get the space ID for this user.
622
+ * Available after signIn().
623
+ */
624
+ get spaceId(): string | undefined;
625
+ /**
626
+ * Get the current TinyCloud session.
627
+ * Available after signIn().
628
+ */
629
+ get session(): TinyCloudSession | undefined;
630
+ /**
631
+ * Sign in and create a new session.
632
+ * This creates the user's space if it doesn't exist.
633
+ * Requires wallet mode (privateKey in config).
634
+ */
635
+ signIn(): Promise<void>;
636
+ /**
637
+ * Restore a previously established session from stored delegation data.
638
+ *
639
+ * This is used by the CLI to restore a session that was created via the
640
+ * browser-based delegation flow (OpenKey `/delegate` page). Instead of
641
+ * signing in with a private key, it injects the delegation data directly.
642
+ *
643
+ * @param sessionData - The stored delegation data from the browser flow
644
+ */
645
+ restoreSession(sessionData: {
646
+ delegationHeader: {
647
+ Authorization: string;
648
+ };
649
+ delegationCid: string;
650
+ spaceId: string;
651
+ jwk: object;
652
+ verificationMethod: string;
653
+ address?: string;
654
+ chainId?: number;
655
+ }): Promise<void>;
656
+ /**
657
+ * Connect a wallet to upgrade from session-only mode to wallet mode.
658
+ *
659
+ * This allows a user who started in session-only mode to later connect
660
+ * a wallet and gain the ability to create their own space.
661
+ *
662
+ * Note: This does NOT automatically sign in. Call signIn() after connecting
663
+ * the wallet to create your space.
664
+ *
665
+ * @param privateKey - The Ethereum private key (hex string, no 0x prefix)
666
+ * @param options - Optional configuration
667
+ * @param options.prefix - Space name prefix (defaults to "default")
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * // Start in session-only mode
672
+ * const node = new TinyCloudNode({ host: "https://node.tinycloud.xyz" });
673
+ * console.log(node.did); // did:key:z6Mk... (session key)
674
+ *
675
+ * // Later, connect a wallet
676
+ * node.connectWallet(privateKey);
677
+ * await node.signIn();
678
+ * console.log(node.did); // did:pkh:eip155:1:0x... (PKH)
679
+ * ```
680
+ */
681
+ connectWallet(privateKey: string, options?: {
682
+ prefix?: string;
683
+ sessionStorage?: ISessionStorage;
684
+ }): void;
685
+ /**
686
+ * Connect any ISigner to upgrade from session-only mode to wallet mode.
687
+ *
688
+ * Same as connectWallet() but accepts any ISigner implementation instead
689
+ * of a raw private key string. Use this for browser wallets, hardware wallets,
690
+ * or custom signing backends.
691
+ *
692
+ * Note: This does NOT automatically sign in. Call signIn() after connecting.
693
+ *
694
+ * @param signer - Any ISigner implementation
695
+ * @param options - Optional configuration
696
+ * @param options.prefix - Space name prefix (defaults to "default")
697
+ */
698
+ connectSigner(signer: ISigner, options?: {
699
+ prefix?: string;
700
+ sessionStorage?: ISessionStorage;
701
+ }): void;
702
+ /**
703
+ * Initialize the service context and KV service after sign-in.
704
+ * @internal
705
+ */
706
+ private initializeServices;
707
+ /**
708
+ * Initialize the v2 delegation system services.
709
+ * @internal
710
+ */
711
+ private initializeV2Services;
712
+ /**
713
+ * Get the session expiry time.
714
+ * @internal
715
+ */
716
+ private getSessionExpiry;
717
+ /**
718
+ * Wrapper for the WASM createDelegation function.
719
+ * Adapts the WASM interface to what SharingService expects.
720
+ * @internal
721
+ */
722
+ private createDelegationWrapper;
723
+ /**
724
+ * Create a direct root delegation from the wallet to a share key.
725
+ * This bypasses the session delegation chain, allowing share links
726
+ * with expiry longer than the current session.
727
+ * @internal
728
+ */
729
+ private createRootDelegationForSharing;
730
+ /**
731
+ * Track a received delegation in the capability registry.
732
+ * @internal
733
+ */
734
+ private trackReceivedDelegation;
735
+ /**
736
+ * Key-value storage operations on this user's space.
737
+ */
738
+ get kv(): IKVService;
739
+ /**
740
+ * SQL database operations on this user's space.
741
+ */
742
+ get sql(): ISQLService;
743
+ /**
744
+ * DuckDB database operations on this user's space.
745
+ */
746
+ get duckdb(): IDuckDbService;
747
+ /**
748
+ * Data Vault operations - client-side encrypted KV storage.
749
+ * Call `vault.unlock(signer)` after signIn() to derive encryption keys.
750
+ */
751
+ get vault(): IDataVaultService;
752
+ /**
753
+ * Get the CapabilityKeyRegistry for managing keys and their capabilities.
754
+ *
755
+ * The registry tracks keys (session, main, ingested) and their associated
756
+ * delegations, enabling automatic key selection for operations.
757
+ *
758
+ * @example
759
+ * ```typescript
760
+ * const registry = alice.capabilityRegistry;
761
+ *
762
+ * // Get the best key for an operation
763
+ * const key = registry.getKeyForCapability(
764
+ * "tinycloud://my-space/kv/data",
765
+ * "tinycloud.kv/get"
766
+ * );
767
+ *
768
+ * // List all capabilities
769
+ * const capabilities = registry.getAllCapabilities();
770
+ * ```
771
+ */
772
+ get capabilityRegistry(): ICapabilityKeyRegistry;
773
+ /**
774
+ * Access received delegations (recipient view).
775
+ *
776
+ * Use this to see what delegations have been received via useDelegation().
777
+ *
778
+ * @example
779
+ * ```typescript
780
+ * // List all received delegations
781
+ * const received = bob.delegations.list();
782
+ * console.log("I have access to:", received.length, "spaces");
783
+ *
784
+ * // Get a specific delegation by CID
785
+ * const delegation = bob.delegations.get(cid);
786
+ * ```
787
+ */
788
+ get delegations(): {
789
+ /** List all received delegations */
790
+ list: () => Delegation[];
791
+ /** Get a delegation by CID */
792
+ get: (cid: string) => Delegation | undefined;
793
+ };
794
+ /**
795
+ * Get the DelegationManager for delegation CRUD operations.
796
+ *
797
+ * This is the v2 delegation service providing a cleaner API than
798
+ * the legacy createDelegation/useDelegation methods.
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * const delegations = alice.delegationManager;
803
+ *
804
+ * // Create a delegation
805
+ * const result = await delegations.create({
806
+ * delegateDID: bob.did,
807
+ * path: "shared/",
808
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
809
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
810
+ * });
811
+ *
812
+ * // List delegations
813
+ * const listResult = await delegations.list();
814
+ *
815
+ * // Revoke a delegation
816
+ * await delegations.revoke(delegationCid);
817
+ * ```
818
+ */
819
+ get delegationManager(): DelegationManager;
820
+ /**
821
+ * Get the SpaceService for managing spaces.
822
+ *
823
+ * The SpaceService provides access to owned and delegated spaces,
824
+ * including space creation, listing, and scoped operations.
825
+ *
826
+ * @example
827
+ * ```typescript
828
+ * const spaces = alice.spaces;
829
+ *
830
+ * // List all accessible spaces
831
+ * const result = await spaces.list();
832
+ *
833
+ * // Create a new space
834
+ * const createResult = await spaces.create('photos');
835
+ *
836
+ * // Get a space object for operations
837
+ * const mySpace = spaces.get('default');
838
+ * await mySpace.kv.put('key', 'value');
839
+ *
840
+ * // Check if a space exists
841
+ * const exists = await spaces.exists('photos');
842
+ * ```
843
+ */
844
+ get spaces(): ISpaceService;
845
+ /**
846
+ * Alias for `spaces` - get the SpaceService.
847
+ * @see spaces
848
+ */
849
+ get spaceService(): ISpaceService;
850
+ /**
851
+ * Get the SharingService for creating and receiving v2 sharing links.
852
+ *
853
+ * The SharingService creates sharing links with embedded private keys,
854
+ * allowing recipients to exercise delegations without prior session setup.
855
+ *
856
+ * @example
857
+ * ```typescript
858
+ * const sharing = alice.sharing;
859
+ *
860
+ * // Generate a sharing link
861
+ * const result = await sharing.generate({
862
+ * path: "/kv/documents/report.pdf",
863
+ * actions: ["tinycloud.kv/get"],
864
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
865
+ * });
866
+ *
867
+ * if (result.ok) {
868
+ * console.log("Share URL:", result.data.url);
869
+ * // Send the URL to the recipient
870
+ * }
871
+ *
872
+ * // Receive a sharing link
873
+ * const receiveResult = await sharing.receive(shareUrl);
874
+ * if (receiveResult.ok) {
875
+ * // Use the pre-configured KV service
876
+ * const data = await receiveResult.data.kv.get("report.pdf");
877
+ * }
878
+ * ```
879
+ */
880
+ get sharing(): ISharingService;
881
+ /**
882
+ * Alias for `sharing` - get the SharingService.
883
+ * @see sharing
884
+ */
885
+ get sharingService(): ISharingService;
886
+ /**
887
+ * Ensure the user's public space exists and is accessible.
888
+ * Creates the space and activates a session delegation for it.
889
+ * This is the trigger for lazy public space creation — call it
890
+ * before writing to spaces.get('public').kv.
891
+ */
892
+ ensurePublicSpace(): Promise<void>;
893
+ /**
894
+ * Get a KVService scoped to the user's own public space.
895
+ * Writes require authentication (owner/delegate).
896
+ */
897
+ get publicKV(): IKVService;
898
+ /**
899
+ * Create a delegation using the v2 DelegationManager.
900
+ *
901
+ * This is a convenience method that wraps DelegationManager.create().
902
+ * For more control, use `this.delegationManager` directly.
903
+ *
904
+ * @param params - Delegation parameters
905
+ * @returns Result containing the created Delegation
906
+ *
907
+ * @example
908
+ * ```typescript
909
+ * const result = await alice.delegate({
910
+ * delegateDID: bob.did,
911
+ * path: "shared/",
912
+ * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
913
+ * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
914
+ * });
915
+ *
916
+ * if (result.ok) {
917
+ * console.log("Delegation created:", result.data.cid);
918
+ * }
919
+ * ```
920
+ */
921
+ delegate(params: CreateDelegationParams): Promise<DelegationResult<Delegation>>;
922
+ /**
923
+ * Revoke a delegation using the v2 DelegationManager.
924
+ *
925
+ * @param cid - The CID of the delegation to revoke
926
+ * @returns Result indicating success or failure
927
+ */
928
+ revokeDelegation(cid: string): Promise<DelegationResult<void>>;
929
+ /**
930
+ * List all delegations for the current session's space.
931
+ *
932
+ * @returns Result containing an array of Delegations
933
+ */
934
+ listDelegations(): Promise<DelegationResult<Delegation[]>>;
935
+ /**
936
+ * Check if the current session has permission for a path and action.
937
+ *
938
+ * @param path - The resource path to check
939
+ * @param action - The action to check (e.g., "tinycloud.kv/get")
940
+ * @returns Result containing boolean permission status
941
+ */
942
+ checkPermission(path: string, action: string): Promise<DelegationResult<boolean>>;
943
+ /**
944
+ * Create a delegation from this user to another user.
945
+ *
946
+ * The delegation grants the recipient access to a specific path and actions
947
+ * within this user's space.
948
+ *
949
+ * @param params - Delegation parameters
950
+ * @returns A portable delegation that can be sent to the recipient
951
+ */
952
+ createDelegation(params: {
953
+ /** Path within the space to delegate access to */
954
+ path: string;
955
+ /** Actions to allow (e.g., ["tinycloud.kv/get", "tinycloud.kv/put"]) */
956
+ actions: string[];
957
+ /** DID of the recipient (from their TinyCloudNode.did) */
958
+ delegateDID: string;
959
+ /** Whether to prevent the recipient from creating sub-delegations (default: false) */
960
+ disableSubDelegation?: boolean;
961
+ /** Expiration time in milliseconds from now (default: 1 hour) */
962
+ expiryMs?: number;
963
+ /** Override space ID (for creating delegations to non-primary spaces like public) */
964
+ spaceIdOverride?: string;
965
+ /** Include a companion delegation for the user's public space (default: true) */
966
+ includePublicSpace?: boolean;
967
+ }): Promise<PortableDelegation>;
968
+ /**
969
+ * Use a delegation received from another user.
970
+ *
971
+ * This creates a new session key for this user that chains from the
972
+ * received delegation, allowing operations on the delegator's space.
973
+ *
974
+ * Works in both modes:
975
+ * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key
976
+ * - **Session-only mode**: Uses the delegation directly (must target session key DID)
977
+ *
978
+ * @param delegation - The PortableDelegation to use (from createDelegation or transport)
979
+ * @returns A DelegatedAccess instance for performing operations
980
+ */
981
+ useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess>;
982
+ /**
983
+ * Create a sub-delegation from a received delegation.
984
+ *
985
+ * This allows further delegating access that was received from another user,
986
+ * if the original delegation allows sub-delegation.
987
+ *
988
+ * @param parentDelegation - The delegation received from another user
989
+ * @param params - Sub-delegation parameters (must be within parent's scope)
990
+ * @returns A portable delegation for the sub-delegate
991
+ */
992
+ createSubDelegation(parentDelegation: PortableDelegation, params: {
993
+ /** Path within the delegated path to sub-delegate */
994
+ path: string;
995
+ /** Actions to allow (must be subset of parent's actions) */
996
+ actions: string[];
997
+ /** DID of the recipient */
998
+ delegateDID: string;
999
+ /** Whether to prevent the recipient from creating further sub-delegations */
1000
+ disableSubDelegation?: boolean;
1001
+ /** Expiration time in milliseconds from now (must be before parent's expiry) */
1002
+ expiryMs?: number;
1003
+ }): Promise<PortableDelegation>;
1004
+ }
1005
+
1006
+ /**
1007
+ * WasmKeyProvider - KeyProvider implementation using WASM session manager.
1008
+ *
1009
+ * This provider wraps the SessionManager from node-sdk-wasm to provide
1010
+ * cryptographic key operations required by the SharingService.
1011
+ *
1012
+ * @packageDocumentation
1013
+ */
1014
+
1015
+ /**
1016
+ * Extended session manager with optional key listing support.
1017
+ * The base ISessionManager doesn't include listSessionKeys(),
1018
+ * but concrete implementations (e.g., TCWSessionManager) may provide it.
1019
+ */
1020
+ interface SessionManagerWithListing extends ISessionManager {
1021
+ listSessionKeys?(): string[];
1022
+ }
1023
+ /**
1024
+ * Configuration for WasmKeyProvider.
1025
+ */
1026
+ interface WasmKeyProviderConfig {
1027
+ /**
1028
+ * The WASM session manager instance.
1029
+ * Must be created before constructing the KeyProvider.
1030
+ */
1031
+ sessionManager: SessionManagerWithListing;
1032
+ }
1033
+ /**
1034
+ * KeyProvider implementation that wraps the WASM session manager.
1035
+ *
1036
+ * This allows the SharingService to create new session keys for sharing links
1037
+ * using the same cryptographic operations as the main session management.
1038
+ *
1039
+ * @example
1040
+ * ```typescript
1041
+ * // sessionManager from wasmBindings.createSessionManager()
1042
+ * import { WasmKeyProvider } from "@tinycloud/node-sdk";
1043
+ *
1044
+ * const sessionManager = new SessionManager();
1045
+ * const keyProvider = new WasmKeyProvider({ sessionManager });
1046
+ *
1047
+ * // Create a session key for a sharing link
1048
+ * const keyId = await keyProvider.createSessionKey("share:abc123");
1049
+ * const jwk = keyProvider.getJWK(keyId);
1050
+ * const did = await keyProvider.getDID(keyId);
1051
+ * ```
1052
+ */
1053
+ declare class WasmKeyProvider implements KeyProvider {
1054
+ private sessionManager;
1055
+ /**
1056
+ * Create a new WasmKeyProvider.
1057
+ *
1058
+ * @param config - Configuration with the WASM session manager
1059
+ */
1060
+ constructor(config: WasmKeyProviderConfig);
1061
+ /**
1062
+ * Generate a new session key with the given name.
1063
+ *
1064
+ * This creates a new Ed25519 key pair in the WASM session manager.
1065
+ * The key can then be used for signing delegations in sharing links.
1066
+ *
1067
+ * @param name - A unique name/ID for the key (e.g., "share:timestamp:random")
1068
+ * @returns The key ID (same as the name provided)
1069
+ */
1070
+ createSessionKey(name: string): Promise<string>;
1071
+ /**
1072
+ * Get the JWK (JSON Web Key) for a key.
1073
+ *
1074
+ * Returns the full JWK including the private key (d parameter),
1075
+ * which is required for signing and for embedding in sharing links.
1076
+ *
1077
+ * @param keyId - The key ID to retrieve
1078
+ * @returns The JWK object with public and private key components
1079
+ * @throws Error if the key is not found
1080
+ */
1081
+ getJWK(keyId: string): JWK;
1082
+ /**
1083
+ * Get the DID (Decentralized Identifier) for a key.
1084
+ *
1085
+ * Returns the did:key format DID derived from the key's public key.
1086
+ * This DID can be used as the delegatee in delegations.
1087
+ *
1088
+ * @param keyId - The key ID to retrieve
1089
+ * @returns The DID in did:key format (e.g., "did:key:z6Mk...")
1090
+ */
1091
+ getDID(keyId: string): Promise<string>;
1092
+ /**
1093
+ * List all session keys currently held by the provider.
1094
+ *
1095
+ * @returns Array of key IDs
1096
+ */
1097
+ listKeys(): string[];
1098
+ /**
1099
+ * Check if a key exists in the provider.
1100
+ *
1101
+ * @param keyId - The key ID to check
1102
+ * @returns True if the key exists
1103
+ */
1104
+ hasKey(keyId: string): boolean;
1105
+ }
1106
+ /**
1107
+ * Create a new WasmKeyProvider instance.
1108
+ *
1109
+ * @param sessionManager - The WASM session manager
1110
+ * @returns A new WasmKeyProvider instance
1111
+ */
1112
+ declare function createWasmKeyProvider(sessionManager: SessionManagerWithListing): WasmKeyProvider;
1113
+
1114
+ export { DelegatedAccess, FileSessionStorage, MemorySessionStorage, type NodeEventEmitterStrategy, NodeUserAuthorization, type NodeUserAuthorizationConfig, type PortableDelegation, type SignStrategy, TinyCloudNode, type TinyCloudNodeConfig, WasmKeyProvider, type WasmKeyProviderConfig, createWasmKeyProvider, defaultSignStrategy, deserializeDelegation, serializeDelegation };