@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/index.d.cts CHANGED
@@ -1,7 +1,9 @@
1
- import { ISigner, Bytes, ISessionStorage, PersistedSessionData, AutoSignStrategy, AutoRejectStrategy, CallbackStrategy, IUserAuthorization, ClientSession, TinyCloudSession, Extension, Delegation, IKVService, ISQLService, IDuckDbService, IDataVaultService, ICapabilityKeyRegistry, DelegationManager, ISpaceService, ISharingService, CreateDelegationParams, DelegationResult, KeyProvider, JWK } from '@tinycloud/sdk-core';
2
- export { 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, IKVService, IPrefixedKVService, ISQLService, ISessionStorage, ISharingService, ISigner, ISpace, ISpaceScopedDelegations, ISpaceScopedSharing, ISpaceService, IUserAuthorization, 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, Space, SpaceConfig, SpaceErrorCode, SpaceErrorCodes, SpaceInfo, SpaceOwnership, SpaceService, SpaceServiceConfig, SqlStatement, SqlValue, StoredDelegationChain, TableInfo, TinyCloud, TinyCloudConfig, TinyCloudSession, UnsupportedFeatureError, VaultAction, VaultCrypto, VaultEntry, VaultError, VaultGetOptions, VaultGrantOptions, VaultHeaders, VaultListOptions, VaultPutOptions, VersionCheckError, ViewInfo, WasmVaultFunctions, buildSpaceUri, checkNodeVersion, createCapabilityKeyRegistry, createSharingService, createSpaceService, createVaultCrypto, makePublicSpaceId, parseSpaceUri } from '@tinycloud/sdk-core';
3
- import { EventEmitter } from 'events';
4
- import { TCWSessionManager } from '@tinycloud/node-sdk-wasm';
1
+ import { ISigner, Bytes, IWasmBindings, ISessionManager } 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
+ export { DelegatedAccess, FileSessionStorage, MemorySessionStorage, NodeEventEmitterStrategy, NodeUserAuthorization, NodeUserAuthorizationConfig, PortableDelegation, SignStrategy, TinyCloudNode, TinyCloudNodeConfig, WasmKeyProvider, WasmKeyProviderConfig, createWasmKeyProvider, defaultSignStrategy, deserializeDelegation, serializeDelegation } from './core.cjs';
4
+ import { invoke, prepareSession, completeSessionSetup, ensureEip55, makeSpaceId, createDelegation, generateHostSIWEMessage, siweToDelegationHeaders, protocolVersion, vault_encrypt, vault_decrypt, vault_derive_key, vault_x25519_from_seed, vault_x25519_dh, vault_random_bytes, vault_sha256 } from '@tinycloud/node-sdk-wasm';
5
+ import 'events';
6
+ import '@tinycloud/sdk-services';
5
7
 
6
8
  /**
7
9
  * Private key signer for Node.js environments.
@@ -50,1046 +52,40 @@ declare class PrivateKeySigner implements ISigner {
50
52
  }
51
53
 
52
54
  /**
53
- * In-memory session storage for Node.js.
55
+ * NodeWasmBindings - Default IWasmBindings implementation for Node.js.
54
56
  *
55
- * Sessions are stored in memory and lost when the process exits.
56
- * Suitable for:
57
- * - Development and testing
58
- * - Stateless server deployments
59
- * - Short-lived processes
60
- *
61
- * @example
62
- * ```typescript
63
- * const storage = new MemorySessionStorage();
64
- * await storage.save("0x123...", sessionData);
65
- * const session = await storage.load("0x123...");
66
- * ```
67
- */
68
- declare class MemorySessionStorage implements ISessionStorage {
69
- private sessions;
70
- /**
71
- * Save a session for an address.
72
- */
73
- save(address: string, session: PersistedSessionData): Promise<void>;
74
- /**
75
- * Load a session for an address.
76
- */
77
- load(address: string): Promise<PersistedSessionData | null>;
78
- /**
79
- * Clear a session for an address.
80
- */
81
- clear(address: string): Promise<void>;
82
- /**
83
- * Check if a session exists for an address.
84
- */
85
- exists(address: string): boolean;
86
- /**
87
- * Memory storage is always available.
88
- */
89
- isAvailable(): boolean;
90
- /**
91
- * Clear all sessions.
92
- */
93
- clearAll(): void;
94
- /**
95
- * Get the number of stored sessions.
96
- */
97
- size(): number;
98
- }
99
-
100
- /**
101
- * File-based session storage for Node.js.
102
- *
103
- * Sessions are persisted to the file system and survive process restarts.
104
- * Suitable for:
105
- * - CLI applications
106
- * - Long-running server processes
107
- * - Development environments
108
- *
109
- * @example
110
- * ```typescript
111
- * const storage = new FileSessionStorage("/tmp/tinycloud-sessions");
112
- * await storage.save("0x123...", sessionData);
113
- * // Session persists across process restarts
114
- * ```
115
- */
116
- declare class FileSessionStorage implements ISessionStorage {
117
- private readonly baseDir;
118
- /**
119
- * Create a new FileSessionStorage.
120
- *
121
- * @param baseDir - Directory to store session files (default: ~/.tinycloud/sessions)
122
- */
123
- constructor(baseDir?: string);
124
- /**
125
- * Get the default session storage directory.
126
- */
127
- private getDefaultDir;
128
- /**
129
- * Ensure the storage directory exists.
130
- */
131
- private ensureDirectoryExists;
132
- /**
133
- * Get the file path for an address.
134
- */
135
- private getFilePath;
136
- /**
137
- * Save a session for an address.
138
- */
139
- save(address: string, session: PersistedSessionData): Promise<void>;
140
- /**
141
- * Load a session for an address.
142
- */
143
- load(address: string): Promise<PersistedSessionData | null>;
144
- /**
145
- * Clear a session for an address.
146
- */
147
- clear(address: string): Promise<void>;
148
- /**
149
- * Check if a session exists for an address.
150
- */
151
- exists(address: string): boolean;
152
- /**
153
- * Check if file system storage is available.
154
- */
155
- isAvailable(): boolean;
156
- }
157
-
158
- /**
159
- * Node.js-specific SignStrategy types for TinyCloud authorization.
160
- *
161
- * This module re-exports common types from sdk-core and provides
162
- * Node.js-specific implementations (e.g., NodeEventEmitterStrategy
163
- * using Node's EventEmitter instead of browser EventTarget).
57
+ * Wraps @tinycloud/node-sdk-wasm functions into the IWasmBindings interface.
58
+ * This is used as the default when no custom wasmBindings is provided in config.
164
59
  *
165
60
  * @packageDocumentation
166
61
  */
167
62
 
168
63
  /**
169
- * Node.js event emitter strategy: emits sign requests as events.
170
- *
171
- * Uses Node.js EventEmitter for compatibility with Node.js applications.
172
- * For browser environments, use the EventEmitterStrategy from sdk-core
173
- * which uses EventTarget.
174
- *
175
- * Events emitted:
176
- * - 'sign-request': When a sign request is received
177
- *
178
- * Use cases:
179
- * - Async approval workflows in Node.js
180
- * - External signing services
181
- * - Multi-step authorization flows
182
- *
183
- * @example
184
- * ```typescript
185
- * const emitter = new EventEmitter();
186
- * const strategy: NodeEventEmitterStrategy = { type: 'event-emitter', emitter };
187
- *
188
- * emitter.on('sign-request', async (req, respond) => {
189
- * const approved = await externalApprovalService.check(req);
190
- * respond({ approved, signature: approved ? await sign(req.message) : undefined });
191
- * });
192
- * ```
193
- */
194
- interface NodeEventEmitterStrategy {
195
- type: "event-emitter";
196
- emitter: EventEmitter;
197
- /** Timeout in milliseconds for waiting on event response (default: 60000) */
198
- timeout?: number;
199
- }
200
- /**
201
- * Node.js sign strategy union type.
202
- *
203
- * Determines how sign requests are handled in NodeUserAuthorization.
204
- * Uses Node.js EventEmitter for the event-emitter strategy.
205
- */
206
- type SignStrategy = AutoSignStrategy | AutoRejectStrategy | CallbackStrategy | NodeEventEmitterStrategy;
207
- /**
208
- * Default sign strategy is auto-sign for convenience.
209
- * This is the Node.js-specific version typed with SignStrategy.
210
- */
211
- declare const defaultSignStrategy: SignStrategy;
212
-
213
- /**
214
- * Configuration for NodeUserAuthorization.
215
- */
216
- interface NodeUserAuthorizationConfig {
217
- /** The signer used for signing messages */
218
- signer: ISigner;
219
- /** Sign strategy for handling sign requests */
220
- signStrategy?: SignStrategy;
221
- /** Session storage implementation */
222
- sessionStorage?: ISessionStorage;
223
- /** Domain for SIWE messages */
224
- domain: string;
225
- /** URI for SIWE messages (default: domain) */
226
- uri?: string;
227
- /** Statement included in SIWE messages */
228
- statement?: string;
229
- /** Space prefix for new sessions */
230
- spacePrefix?: string;
231
- /** Default actions for sessions */
232
- defaultActions?: Record<string, Record<string, string[]>>;
233
- /** Session expiration time in milliseconds (default: 1 hour) */
234
- sessionExpirationMs?: number;
235
- /** Automatically create space if it doesn't exist (default: false) */
236
- autoCreateSpace?: boolean;
237
- /** TinyCloud server endpoints (default: ["https://node.tinycloud.xyz"]) */
238
- tinycloudHosts?: string[];
239
- /** Whether to include public space capabilities in the session (default: true) */
240
- enablePublicSpace?: boolean;
241
- }
242
- /**
243
- * Node.js implementation of IUserAuthorization.
244
- *
245
- * Supports multiple sign strategies for different use cases:
246
- * - auto-sign: Automatically approve all sign requests (trusted backends)
247
- * - auto-reject: Reject all sign requests (read-only mode)
248
- * - callback: Delegate to a custom callback function (CLI prompts)
249
- * - event-emitter: Emit sign requests as events (async workflows)
250
- *
251
- * @example
252
- * ```typescript
253
- * // Auto-sign for backend services
254
- * const auth = new NodeUserAuthorization({
255
- * signer: new PrivateKeySigner(process.env.PRIVATE_KEY),
256
- * signStrategy: { type: 'auto-sign' },
257
- * domain: 'api.myapp.com',
258
- * });
259
- *
260
- * // Callback for CLI prompts
261
- * const auth = new NodeUserAuthorization({
262
- * signer,
263
- * signStrategy: {
264
- * type: 'callback',
265
- * handler: async (req) => {
266
- * const approved = await promptUser(`Sign for ${req.address}?`);
267
- * return { approved };
268
- * }
269
- * },
270
- * domain: 'cli.myapp.com',
271
- * });
272
- * ```
273
- */
274
- declare class NodeUserAuthorization implements IUserAuthorization {
275
- /** Flag to ensure WASM panic hook is only initialized once */
276
- private static wasmInitialized;
277
- private readonly signer;
278
- private readonly signStrategy;
279
- private readonly sessionStorage;
280
- private readonly domain;
281
- private readonly uri;
282
- private readonly statement?;
283
- private readonly spacePrefix;
284
- private readonly defaultActions;
285
- private readonly sessionExpirationMs;
286
- private readonly autoCreateSpace;
287
- private readonly tinycloudHosts;
288
- private readonly enablePublicSpace;
289
- private sessionManager;
290
- private extensions;
291
- private _session?;
292
- private _tinyCloudSession?;
293
- private _address?;
294
- private _chainId?;
295
- private _nodeFeatures;
296
- constructor(config: NodeUserAuthorizationConfig);
297
- /**
298
- * The current active session (web-core compatible).
299
- */
300
- get session(): ClientSession | undefined;
301
- /**
302
- * The current TinyCloud session with full delegation data.
303
- * Includes spaceId, delegationHeader, and delegationCid.
304
- */
305
- get tinyCloudSession(): TinyCloudSession | undefined;
306
- get nodeFeatures(): string[];
307
- /**
308
- * Add an extension to the authorization flow.
309
- */
310
- extend(extension: Extension): void;
311
- /**
312
- * Get the space ID for the current session.
313
- */
314
- getSpaceId(): string | undefined;
315
- /**
316
- * Create the space on the TinyCloud server (host delegation).
317
- * This registers the user as the owner of the space.
318
- */
319
- private hostSpace;
320
- /**
321
- * Create a specific space on the server via host delegation.
322
- * Used for lazy creation of additional spaces (e.g., public).
323
- */
324
- hostPublicSpace(spaceId: string): Promise<boolean>;
325
- /**
326
- * Ensure the user's space exists on the TinyCloud server.
327
- * Creates the space if it doesn't exist and autoCreateSpace is enabled.
328
- * If autoCreateSpace is false and space doesn't exist, silently returns
329
- * (user may be using delegations to access other spaces).
330
- *
331
- * @throws Error if space creation fails
332
- */
333
- ensureSpaceExists(): Promise<void>;
334
- /**
335
- * Sign in and create a new session.
336
- *
337
- * This follows the correct SIWE-ReCap flow:
338
- * 1. Create session key and get JWK
339
- * 2. Call prepareSession() which generates the SIWE with ReCap capabilities
340
- * 3. Sign the SIWE string from prepareSession
341
- * 4. Call completeSessionSetup() with the prepared session + signature
342
- */
343
- signIn(): Promise<ClientSession>;
344
- /**
345
- * Sign out and clear the current session.
346
- */
347
- signOut(): Promise<void>;
348
- /**
349
- * Get the current wallet/signer address.
350
- */
351
- address(): string | undefined;
352
- /**
353
- * Get the current chain ID.
354
- */
355
- chainId(): number | undefined;
356
- /**
357
- * Sign a message with the connected signer.
358
- */
359
- signMessage(message: string): Promise<string>;
360
- /**
361
- * Prepare a session for external signing.
362
- *
363
- * Use this method when you need to sign the SIWE message externally (e.g., via
364
- * a hardware wallet, multi-sig, or external service). After obtaining the signature,
365
- * call `signInWithPreparedSession()` to complete the sign-in.
366
- *
367
- * @example
368
- * ```typescript
369
- * const { prepared, keyId, jwk } = await auth.prepareSessionForSigning();
370
- * const signature = await externalSigner.signMessage(prepared.siwe);
371
- * const session = await auth.signInWithPreparedSession(prepared, signature, keyId, jwk);
372
- * ```
373
- */
374
- prepareSessionForSigning(): Promise<{
375
- prepared: {
376
- siwe: string;
377
- jwk: Record<string, unknown>;
378
- spaceId: string;
379
- verificationMethod: string;
380
- };
381
- keyId: string;
382
- jwk: Record<string, unknown>;
383
- address: string;
384
- chainId: number;
385
- }>;
386
- /**
387
- * Complete sign-in with a prepared session and signature.
388
- *
389
- * Use this method after obtaining a signature for the SIWE message from
390
- * `prepareSessionForSigning()`. The signature MUST be over `prepared.siwe`.
391
- *
392
- * @param prepared - The prepared session from `prepareSessionForSigning()`
393
- * @param signature - The signature over `prepared.siwe`
394
- * @param keyId - The session key ID from `prepareSessionForSigning()`
395
- * @param jwk - The JWK from `prepareSessionForSigning()`
396
- */
397
- signInWithPreparedSession(prepared: {
398
- siwe: string;
399
- jwk: Record<string, unknown>;
400
- spaceId: string;
401
- verificationMethod: string;
402
- }, signature: string, keyId: string, jwk: Record<string, unknown>): Promise<ClientSession>;
403
- /**
404
- * Clear persisted session data.
405
- */
406
- clearPersistedSession(address?: string): Promise<void>;
407
- /**
408
- * Check if a session is persisted for an address.
409
- */
410
- isSessionPersisted(address: string): boolean;
411
- /**
412
- * Request a signature based on the configured strategy.
413
- */
414
- private requestSignature;
415
- /**
416
- * Request signature via event emitter with timeout.
417
- */
418
- private requestSignatureViaEmitter;
419
- }
420
-
421
- /**
422
- * A portable delegation that can be transported between users.
423
- * Extends the base Delegation type with fields required for transport.
424
- *
425
- * @remarks
426
- * PortableDelegation adds transport fields to Delegation:
427
- * - `delegationHeader`: Structured authorization header for API calls
428
- * - `ownerAddress`: Space owner's address for session creation
429
- * - `chainId`: Chain ID for session creation
430
- * - `host`: Optional server URL
431
- */
432
- interface PortableDelegation extends Omit<Delegation, "isRevoked"> {
433
- /** The authorization header for this delegation (structured format) */
434
- delegationHeader: {
435
- Authorization: string;
436
- };
437
- /** The address of the space owner */
438
- ownerAddress: string;
439
- /** The chain ID */
440
- chainId: number;
441
- /** TinyCloud server URL where this delegation was created */
442
- host?: string;
443
- /** Whether the recipient is prevented from creating sub-delegations */
444
- disableSubDelegation?: boolean;
445
- }
446
- /**
447
- * Serialize a PortableDelegation for transport (e.g., over network).
448
- */
449
- declare function serializeDelegation(delegation: PortableDelegation): string;
450
- /**
451
- * Deserialize a PortableDelegation from transport.
452
- */
453
- declare function deserializeDelegation(data: string): PortableDelegation;
454
-
455
- /**
456
- * Provides access to a space via a received delegation.
457
- *
458
- * This is returned by TinyCloudNode.useDelegation() and provides
459
- * KV operations on the delegated space.
460
- */
461
- declare class DelegatedAccess {
462
- private session;
463
- private _delegation;
464
- private host;
465
- private _serviceContext;
466
- private _kv;
467
- private _sql;
468
- private _duckdb;
469
- constructor(session: TinyCloudSession, delegation: PortableDelegation, host: string);
470
- /**
471
- * Get the delegation this access was created from.
472
- */
473
- get delegation(): PortableDelegation;
474
- /**
475
- * The space ID this access is for.
476
- */
477
- get spaceId(): string;
478
- /**
479
- * The path this access is scoped to.
480
- */
481
- get path(): string;
482
- /**
483
- * KV operations on the delegated space.
484
- */
485
- get kv(): IKVService;
486
- /**
487
- * SQL operations on the delegated space.
488
- */
489
- get sql(): ISQLService;
490
- /**
491
- * DuckDB operations on the delegated space.
492
- */
493
- get duckdb(): IDuckDbService;
64
+ * Node.js WASM bindings using @tinycloud/node-sdk-wasm.
65
+ *
66
+ * This is the default IWasmBindings implementation for Node.js environments.
67
+ * Browser environments provide their own BrowserWasmBindings via config.wasmBindings.
68
+ */
69
+ declare class NodeWasmBindings implements IWasmBindings {
70
+ private static panicHookInitialized;
71
+ constructor();
72
+ invoke: typeof invoke;
73
+ prepareSession: typeof prepareSession;
74
+ completeSessionSetup: typeof completeSessionSetup;
75
+ ensureEip55: typeof ensureEip55;
76
+ makeSpaceId: typeof makeSpaceId;
77
+ createDelegation: typeof createDelegation;
78
+ generateHostSIWEMessage: typeof generateHostSIWEMessage;
79
+ siweToDelegationHeaders: typeof siweToDelegationHeaders;
80
+ protocolVersion: typeof protocolVersion;
81
+ vault_encrypt: typeof vault_encrypt;
82
+ vault_decrypt: typeof vault_decrypt;
83
+ vault_derive_key: typeof vault_derive_key;
84
+ vault_x25519_from_seed: typeof vault_x25519_from_seed;
85
+ vault_x25519_dh: typeof vault_x25519_dh;
86
+ vault_random_bytes: typeof vault_random_bytes;
87
+ vault_sha256: typeof vault_sha256;
88
+ createSessionManager(): ISessionManager;
494
89
  }
495
90
 
496
- /**
497
- * TinyCloudNode - High-level API for Node.js users.
498
- *
499
- * Each user has their own TinyCloudNode instance with their own key.
500
- * This class provides a simplified interface for:
501
- * - Signing in and managing sessions
502
- * - Key-value storage operations on own space
503
- * - Creating and using delegations
504
- *
505
- * @example
506
- * ```typescript
507
- * const alice = new TinyCloudNode({
508
- * privateKey: process.env.ALICE_PRIVATE_KEY,
509
- * host: "https://node.tinycloud.xyz",
510
- * prefix: "myapp",
511
- * });
512
- *
513
- * await alice.signIn();
514
- * await alice.kv.put("greeting", "Hello, world!");
515
- *
516
- * // Delegate access to Bob
517
- * const delegation = await alice.createDelegation({
518
- * path: "shared/",
519
- * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
520
- * delegateDID: bob.did,
521
- * });
522
- *
523
- * // Bob uses the delegation
524
- * const access = await bob.useDelegation(delegation);
525
- * const data = await access.kv.get("shared/data");
526
- * ```
527
- */
528
-
529
- /**
530
- * Configuration for TinyCloudNode.
531
- * All fields are optional - TinyCloudNode can work with zero configuration.
532
- */
533
- interface TinyCloudNodeConfig {
534
- /** Hex-encoded private key (with or without 0x prefix). Optional - only needed for wallet mode and signIn() */
535
- privateKey?: string;
536
- /** TinyCloud server URL (default: "https://node.tinycloud.xyz") */
537
- host?: string;
538
- /** Space prefix for this user's space. Optional - only needed for signIn() */
539
- prefix?: string;
540
- /** Domain for SIWE messages (default: derived from host) */
541
- domain?: string;
542
- /** Session expiration time in milliseconds (default: 1 hour) */
543
- sessionExpirationMs?: number;
544
- /** Whether to automatically create space if it doesn't exist (default: false) */
545
- autoCreateSpace?: boolean;
546
- /** Custom session storage implementation (default: MemorySessionStorage) */
547
- sessionStorage?: ISessionStorage;
548
- /** Whether to include public space capabilities in the session (default: true).
549
- * When true, signIn() automatically includes capabilities for the user's public space,
550
- * accessible via spaces.get('public').kv */
551
- enablePublicSpace?: boolean;
552
- }
553
- /**
554
- * High-level TinyCloud API for Node.js environments.
555
- *
556
- * Each user creates their own TinyCloudNode instance with their private key.
557
- * The instance manages the user's session and provides access to their space.
558
- */
559
- declare class TinyCloudNode {
560
- /** Flag to ensure WASM panic hook is only initialized once */
561
- private static wasmInitialized;
562
- private config;
563
- private signer;
564
- private auth;
565
- private tc;
566
- private _address?;
567
- private _chainId;
568
- private sessionManager;
569
- private _serviceContext?;
570
- private _kv?;
571
- private _sql?;
572
- private _duckdb?;
573
- private _vault?;
574
- /** Cached public KV with proper delegation (set by ensurePublicSpace) */
575
- private _publicKV?;
576
- /** Session key ID - always available */
577
- private sessionKeyId;
578
- /** Session key JWK as object - always available */
579
- private sessionKeyJwk;
580
- private _capabilityRegistry;
581
- private _keyProvider;
582
- private _sharingService;
583
- private _delegationManager?;
584
- private _spaceService?;
585
- private get nodeFeatures();
586
- /**
587
- * Create a new TinyCloudNode instance.
588
- *
589
- * All configuration is optional. Without a privateKey, the instance operates
590
- * in "session-only" mode where it can receive delegations but cannot create
591
- * its own space via signIn().
592
- *
593
- * @param config - Configuration options (all optional)
594
- *
595
- * @example
596
- * ```typescript
597
- * // Session-only mode - can receive delegations
598
- * const bob = new TinyCloudNode();
599
- * console.log(bob.did); // did:key:z6Mk... - available immediately
600
- *
601
- * // Wallet mode - can create own space
602
- * const alice = new TinyCloudNode({
603
- * privateKey: process.env.ALICE_PRIVATE_KEY,
604
- * prefix: "myapp",
605
- * });
606
- * await alice.signIn();
607
- * ```
608
- */
609
- constructor(config?: TinyCloudNodeConfig);
610
- /**
611
- * Get the primary identity DID for this user.
612
- * - If wallet connected and signed in: returns PKH DID (did:pkh:eip155:{chainId}:{address})
613
- * - If session-only mode: returns session key DID (did:key:z6Mk...)
614
- *
615
- * Use this for delegations - it always returns the appropriate identity.
616
- */
617
- get did(): string;
618
- /**
619
- * Get the session key DID. Always available.
620
- * Format: did:key:z6Mk...#z6Mk...
621
- *
622
- * Use this when you specifically need the session key, not the user identity.
623
- */
624
- get sessionDid(): string;
625
- /**
626
- * Get the Ethereum address for this user.
627
- */
628
- get address(): string | undefined;
629
- /**
630
- * Check if this instance is in session-only mode (no wallet).
631
- * In session-only mode, the instance can receive delegations but cannot
632
- * create its own space via signIn().
633
- */
634
- get isSessionOnly(): boolean;
635
- /**
636
- * Get the space ID for this user.
637
- * Available after signIn().
638
- */
639
- get spaceId(): string | undefined;
640
- /**
641
- * Get the current TinyCloud session.
642
- * Available after signIn().
643
- */
644
- get session(): TinyCloudSession | undefined;
645
- /**
646
- * Sign in and create a new session.
647
- * This creates the user's space if it doesn't exist.
648
- * Requires wallet mode (privateKey in config).
649
- */
650
- signIn(): Promise<void>;
651
- /**
652
- * Restore a previously established session from stored delegation data.
653
- *
654
- * This is used by the CLI to restore a session that was created via the
655
- * browser-based delegation flow (OpenKey `/delegate` page). Instead of
656
- * signing in with a private key, it injects the delegation data directly.
657
- *
658
- * @param sessionData - The stored delegation data from the browser flow
659
- */
660
- restoreSession(sessionData: {
661
- delegationHeader: {
662
- Authorization: string;
663
- };
664
- delegationCid: string;
665
- spaceId: string;
666
- jwk: object;
667
- verificationMethod: string;
668
- address?: string;
669
- chainId?: number;
670
- }): Promise<void>;
671
- /**
672
- * Connect a wallet to upgrade from session-only mode to wallet mode.
673
- *
674
- * This allows a user who started in session-only mode to later connect
675
- * a wallet and gain the ability to create their own space.
676
- *
677
- * Note: This does NOT automatically sign in. Call signIn() after connecting
678
- * the wallet to create your space.
679
- *
680
- * @param privateKey - The Ethereum private key (hex string, no 0x prefix)
681
- * @param options - Optional configuration
682
- * @param options.prefix - Space name prefix (defaults to "default")
683
- *
684
- * @example
685
- * ```typescript
686
- * // Start in session-only mode
687
- * const node = new TinyCloudNode({ host: "https://node.tinycloud.xyz" });
688
- * console.log(node.did); // did:key:z6Mk... (session key)
689
- *
690
- * // Later, connect a wallet
691
- * node.connectWallet(privateKey);
692
- * await node.signIn();
693
- * console.log(node.did); // did:pkh:eip155:1:0x... (PKH)
694
- * ```
695
- */
696
- connectWallet(privateKey: string, options?: {
697
- prefix?: string;
698
- sessionStorage?: ISessionStorage;
699
- }): void;
700
- /**
701
- * Initialize the service context and KV service after sign-in.
702
- * @internal
703
- */
704
- private initializeServices;
705
- /**
706
- * Initialize the v2 delegation system services.
707
- * @internal
708
- */
709
- private initializeV2Services;
710
- /**
711
- * Get the session expiry time.
712
- * @internal
713
- */
714
- private getSessionExpiry;
715
- /**
716
- * Wrapper for the WASM createDelegation function.
717
- * Adapts the WASM interface to what SharingService expects.
718
- * @internal
719
- */
720
- private createDelegationWrapper;
721
- /**
722
- * Track a received delegation in the capability registry.
723
- * @internal
724
- */
725
- private trackReceivedDelegation;
726
- /**
727
- * Key-value storage operations on this user's space.
728
- */
729
- get kv(): IKVService;
730
- /**
731
- * SQL database operations on this user's space.
732
- */
733
- get sql(): ISQLService;
734
- /**
735
- * DuckDB database operations on this user's space.
736
- */
737
- get duckdb(): IDuckDbService;
738
- /**
739
- * Data Vault operations - client-side encrypted KV storage.
740
- * Call `vault.unlock(signer)` after signIn() to derive encryption keys.
741
- */
742
- get vault(): IDataVaultService;
743
- /**
744
- * Get the CapabilityKeyRegistry for managing keys and their capabilities.
745
- *
746
- * The registry tracks keys (session, main, ingested) and their associated
747
- * delegations, enabling automatic key selection for operations.
748
- *
749
- * @example
750
- * ```typescript
751
- * const registry = alice.capabilityRegistry;
752
- *
753
- * // Get the best key for an operation
754
- * const key = registry.getKeyForCapability(
755
- * "tinycloud://my-space/kv/data",
756
- * "tinycloud.kv/get"
757
- * );
758
- *
759
- * // List all capabilities
760
- * const capabilities = registry.getAllCapabilities();
761
- * ```
762
- */
763
- get capabilityRegistry(): ICapabilityKeyRegistry;
764
- /**
765
- * Access received delegations (recipient view).
766
- *
767
- * Use this to see what delegations have been received via useDelegation().
768
- *
769
- * @example
770
- * ```typescript
771
- * // List all received delegations
772
- * const received = bob.delegations.list();
773
- * console.log("I have access to:", received.length, "spaces");
774
- *
775
- * // Get a specific delegation by CID
776
- * const delegation = bob.delegations.get(cid);
777
- * ```
778
- */
779
- get delegations(): {
780
- /** List all received delegations */
781
- list: () => Delegation[];
782
- /** Get a delegation by CID */
783
- get: (cid: string) => Delegation | undefined;
784
- };
785
- /**
786
- * Get the DelegationManager for delegation CRUD operations.
787
- *
788
- * This is the v2 delegation service providing a cleaner API than
789
- * the legacy createDelegation/useDelegation methods.
790
- *
791
- * @example
792
- * ```typescript
793
- * const delegations = alice.delegationManager;
794
- *
795
- * // Create a delegation
796
- * const result = await delegations.create({
797
- * delegateDID: bob.did,
798
- * path: "shared/",
799
- * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
800
- * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
801
- * });
802
- *
803
- * // List delegations
804
- * const listResult = await delegations.list();
805
- *
806
- * // Revoke a delegation
807
- * await delegations.revoke(delegationCid);
808
- * ```
809
- */
810
- get delegationManager(): DelegationManager;
811
- /**
812
- * Get the SpaceService for managing spaces.
813
- *
814
- * The SpaceService provides access to owned and delegated spaces,
815
- * including space creation, listing, and scoped operations.
816
- *
817
- * @example
818
- * ```typescript
819
- * const spaces = alice.spaces;
820
- *
821
- * // List all accessible spaces
822
- * const result = await spaces.list();
823
- *
824
- * // Create a new space
825
- * const createResult = await spaces.create('photos');
826
- *
827
- * // Get a space object for operations
828
- * const mySpace = spaces.get('default');
829
- * await mySpace.kv.put('key', 'value');
830
- *
831
- * // Check if a space exists
832
- * const exists = await spaces.exists('photos');
833
- * ```
834
- */
835
- get spaces(): ISpaceService;
836
- /**
837
- * Alias for `spaces` - get the SpaceService.
838
- * @see spaces
839
- */
840
- get spaceService(): ISpaceService;
841
- /**
842
- * Get the SharingService for creating and receiving v2 sharing links.
843
- *
844
- * The SharingService creates sharing links with embedded private keys,
845
- * allowing recipients to exercise delegations without prior session setup.
846
- *
847
- * @example
848
- * ```typescript
849
- * const sharing = alice.sharing;
850
- *
851
- * // Generate a sharing link
852
- * const result = await sharing.generate({
853
- * path: "/kv/documents/report.pdf",
854
- * actions: ["tinycloud.kv/get"],
855
- * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
856
- * });
857
- *
858
- * if (result.ok) {
859
- * console.log("Share URL:", result.data.url);
860
- * // Send the URL to the recipient
861
- * }
862
- *
863
- * // Receive a sharing link
864
- * const receiveResult = await sharing.receive(shareUrl);
865
- * if (receiveResult.ok) {
866
- * // Use the pre-configured KV service
867
- * const data = await receiveResult.data.kv.get("report.pdf");
868
- * }
869
- * ```
870
- */
871
- get sharing(): ISharingService;
872
- /**
873
- * Alias for `sharing` - get the SharingService.
874
- * @see sharing
875
- */
876
- get sharingService(): ISharingService;
877
- /**
878
- * Ensure the user's public space exists and is accessible.
879
- * Creates the space and activates a session delegation for it.
880
- * This is the trigger for lazy public space creation — call it
881
- * before writing to spaces.get('public').kv.
882
- */
883
- ensurePublicSpace(): Promise<void>;
884
- /**
885
- * Get a KVService scoped to the user's own public space.
886
- * Writes require authentication (owner/delegate).
887
- */
888
- get publicKV(): IKVService;
889
- /**
890
- * Create a delegation using the v2 DelegationManager.
891
- *
892
- * This is a convenience method that wraps DelegationManager.create().
893
- * For more control, use `this.delegationManager` directly.
894
- *
895
- * @param params - Delegation parameters
896
- * @returns Result containing the created Delegation
897
- *
898
- * @example
899
- * ```typescript
900
- * const result = await alice.delegate({
901
- * delegateDID: bob.did,
902
- * path: "shared/",
903
- * actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
904
- * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
905
- * });
906
- *
907
- * if (result.ok) {
908
- * console.log("Delegation created:", result.data.cid);
909
- * }
910
- * ```
911
- */
912
- delegate(params: CreateDelegationParams): Promise<DelegationResult<Delegation>>;
913
- /**
914
- * Revoke a delegation using the v2 DelegationManager.
915
- *
916
- * @param cid - The CID of the delegation to revoke
917
- * @returns Result indicating success or failure
918
- */
919
- revokeDelegation(cid: string): Promise<DelegationResult<void>>;
920
- /**
921
- * List all delegations for the current session's space.
922
- *
923
- * @returns Result containing an array of Delegations
924
- */
925
- listDelegations(): Promise<DelegationResult<Delegation[]>>;
926
- /**
927
- * Check if the current session has permission for a path and action.
928
- *
929
- * @param path - The resource path to check
930
- * @param action - The action to check (e.g., "tinycloud.kv/get")
931
- * @returns Result containing boolean permission status
932
- */
933
- checkPermission(path: string, action: string): Promise<DelegationResult<boolean>>;
934
- /**
935
- * Create a delegation from this user to another user.
936
- *
937
- * The delegation grants the recipient access to a specific path and actions
938
- * within this user's space.
939
- *
940
- * @param params - Delegation parameters
941
- * @returns A portable delegation that can be sent to the recipient
942
- */
943
- createDelegation(params: {
944
- /** Path within the space to delegate access to */
945
- path: string;
946
- /** Actions to allow (e.g., ["tinycloud.kv/get", "tinycloud.kv/put"]) */
947
- actions: string[];
948
- /** DID of the recipient (from their TinyCloudNode.did) */
949
- delegateDID: string;
950
- /** Whether to prevent the recipient from creating sub-delegations (default: false) */
951
- disableSubDelegation?: boolean;
952
- /** Expiration time in milliseconds from now (default: 1 hour) */
953
- expiryMs?: number;
954
- /** Override space ID (for creating delegations to non-primary spaces like public) */
955
- spaceIdOverride?: string;
956
- }): Promise<PortableDelegation>;
957
- /**
958
- * Use a delegation received from another user.
959
- *
960
- * This creates a new session key for this user that chains from the
961
- * received delegation, allowing operations on the delegator's space.
962
- *
963
- * Works in both modes:
964
- * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key
965
- * - **Session-only mode**: Uses the delegation directly (must target session key DID)
966
- *
967
- * @param delegation - The PortableDelegation to use (from createDelegation or transport)
968
- * @returns A DelegatedAccess instance for performing operations
969
- */
970
- useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess>;
971
- /**
972
- * Create a sub-delegation from a received delegation.
973
- *
974
- * This allows further delegating access that was received from another user,
975
- * if the original delegation allows sub-delegation.
976
- *
977
- * @param parentDelegation - The delegation received from another user
978
- * @param params - Sub-delegation parameters (must be within parent's scope)
979
- * @returns A portable delegation for the sub-delegate
980
- */
981
- createSubDelegation(parentDelegation: PortableDelegation, params: {
982
- /** Path within the delegated path to sub-delegate */
983
- path: string;
984
- /** Actions to allow (must be subset of parent's actions) */
985
- actions: string[];
986
- /** DID of the recipient */
987
- delegateDID: string;
988
- /** Whether to prevent the recipient from creating further sub-delegations */
989
- disableSubDelegation?: boolean;
990
- /** Expiration time in milliseconds from now (must be before parent's expiry) */
991
- expiryMs?: number;
992
- }): Promise<PortableDelegation>;
993
- }
994
-
995
- /**
996
- * WasmKeyProvider - KeyProvider implementation using WASM session manager.
997
- *
998
- * This provider wraps the SessionManager from node-sdk-wasm to provide
999
- * cryptographic key operations required by the SharingService.
1000
- *
1001
- * @packageDocumentation
1002
- */
1003
-
1004
- /**
1005
- * Configuration for WasmKeyProvider.
1006
- */
1007
- interface WasmKeyProviderConfig {
1008
- /**
1009
- * The WASM session manager instance.
1010
- * Must be created before constructing the KeyProvider.
1011
- */
1012
- sessionManager: TCWSessionManager;
1013
- }
1014
- /**
1015
- * KeyProvider implementation that wraps the WASM session manager.
1016
- *
1017
- * This allows the SharingService to create new session keys for sharing links
1018
- * using the same cryptographic operations as the main session management.
1019
- *
1020
- * @example
1021
- * ```typescript
1022
- * import { SessionManager } from "@tinycloud/node-sdk-wasm";
1023
- * import { WasmKeyProvider } from "@tinycloud/node-sdk";
1024
- *
1025
- * const sessionManager = new SessionManager();
1026
- * const keyProvider = new WasmKeyProvider({ sessionManager });
1027
- *
1028
- * // Create a session key for a sharing link
1029
- * const keyId = await keyProvider.createSessionKey("share:abc123");
1030
- * const jwk = keyProvider.getJWK(keyId);
1031
- * const did = await keyProvider.getDID(keyId);
1032
- * ```
1033
- */
1034
- declare class WasmKeyProvider implements KeyProvider {
1035
- private sessionManager;
1036
- /**
1037
- * Create a new WasmKeyProvider.
1038
- *
1039
- * @param config - Configuration with the WASM session manager
1040
- */
1041
- constructor(config: WasmKeyProviderConfig);
1042
- /**
1043
- * Generate a new session key with the given name.
1044
- *
1045
- * This creates a new Ed25519 key pair in the WASM session manager.
1046
- * The key can then be used for signing delegations in sharing links.
1047
- *
1048
- * @param name - A unique name/ID for the key (e.g., "share:timestamp:random")
1049
- * @returns The key ID (same as the name provided)
1050
- */
1051
- createSessionKey(name: string): Promise<string>;
1052
- /**
1053
- * Get the JWK (JSON Web Key) for a key.
1054
- *
1055
- * Returns the full JWK including the private key (d parameter),
1056
- * which is required for signing and for embedding in sharing links.
1057
- *
1058
- * @param keyId - The key ID to retrieve
1059
- * @returns The JWK object with public and private key components
1060
- * @throws Error if the key is not found
1061
- */
1062
- getJWK(keyId: string): JWK;
1063
- /**
1064
- * Get the DID (Decentralized Identifier) for a key.
1065
- *
1066
- * Returns the did:key format DID derived from the key's public key.
1067
- * This DID can be used as the delegatee in delegations.
1068
- *
1069
- * @param keyId - The key ID to retrieve
1070
- * @returns The DID in did:key format (e.g., "did:key:z6Mk...")
1071
- */
1072
- getDID(keyId: string): Promise<string>;
1073
- /**
1074
- * List all session keys currently held by the provider.
1075
- *
1076
- * @returns Array of key IDs
1077
- */
1078
- listKeys(): string[];
1079
- /**
1080
- * Check if a key exists in the provider.
1081
- *
1082
- * @param keyId - The key ID to check
1083
- * @returns True if the key exists
1084
- */
1085
- hasKey(keyId: string): boolean;
1086
- }
1087
- /**
1088
- * Create a new WasmKeyProvider instance.
1089
- *
1090
- * @param sessionManager - The WASM session manager
1091
- * @returns A new WasmKeyProvider instance
1092
- */
1093
- declare function createWasmKeyProvider(sessionManager: TCWSessionManager): WasmKeyProvider;
1094
-
1095
- export { DelegatedAccess, FileSessionStorage, MemorySessionStorage, type NodeEventEmitterStrategy, NodeUserAuthorization, type NodeUserAuthorizationConfig, type PortableDelegation, PrivateKeySigner, type SignStrategy, TinyCloudNode, type TinyCloudNodeConfig, WasmKeyProvider, type WasmKeyProviderConfig, createWasmKeyProvider, defaultSignStrategy, deserializeDelegation, serializeDelegation };
91
+ export { NodeWasmBindings, PrivateKeySigner };