@terminal3/t3n-sdk 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.OIDC.md +216 -0
  3. package/README.md +639 -0
  4. package/dist/demo.d.ts +25 -0
  5. package/dist/index.d.ts +819 -0
  6. package/dist/index.esm.js +2 -0
  7. package/dist/index.js +2 -0
  8. package/dist/src/client/actions.d.ts +17 -0
  9. package/dist/src/client/config.d.ts +35 -0
  10. package/dist/src/client/encryption.d.ts +30 -0
  11. package/dist/src/client/handlers.d.ts +45 -0
  12. package/dist/src/client/index.d.ts +10 -0
  13. package/dist/src/client/request-parser.d.ts +48 -0
  14. package/dist/src/client/t3n-client.d.ts +70 -0
  15. package/dist/src/client/transport.d.ts +107 -0
  16. package/dist/src/config/index.d.ts +67 -0
  17. package/dist/src/config/loader.d.ts +11 -0
  18. package/dist/src/config/types.d.ts +25 -0
  19. package/dist/src/index.d.ts +23 -0
  20. package/dist/src/types/auth.d.ts +54 -0
  21. package/dist/src/types/index.d.ts +35 -0
  22. package/dist/src/types/session.d.ts +24 -0
  23. package/dist/src/utils/contract-version.d.ts +5 -0
  24. package/dist/src/utils/crypto.d.ts +52 -0
  25. package/dist/src/utils/errors.d.ts +61 -0
  26. package/dist/src/utils/index.d.ts +9 -0
  27. package/dist/src/utils/logger.d.ts +102 -0
  28. package/dist/src/utils/redaction.d.ts +13 -0
  29. package/dist/src/utils/session.d.ts +37 -0
  30. package/dist/src/wasm/index.d.ts +5 -0
  31. package/dist/src/wasm/interface.d.ts +105 -0
  32. package/dist/src/wasm/loader.d.ts +43 -0
  33. package/dist/wasm/generated/interfaces/component-session-client-auth.d.ts +12 -0
  34. package/dist/wasm/generated/interfaces/component-session-client-handshake.d.ts +12 -0
  35. package/dist/wasm/generated/interfaces/component-session-server-auth.d.ts +12 -0
  36. package/dist/wasm/generated/interfaces/component-session-server-handshake.d.ts +12 -0
  37. package/dist/wasm/generated/interfaces/component-session-session.d.ts +8 -0
  38. package/dist/wasm/generated/interfaces/wasi-cli-environment.d.ts +2 -0
  39. package/dist/wasm/generated/interfaces/wasi-cli-exit.d.ts +3 -0
  40. package/dist/wasm/generated/interfaces/wasi-cli-stderr.d.ts +3 -0
  41. package/dist/wasm/generated/interfaces/wasi-cli-stdin.d.ts +3 -0
  42. package/dist/wasm/generated/interfaces/wasi-cli-stdout.d.ts +3 -0
  43. package/dist/wasm/generated/interfaces/wasi-clocks-wall-clock.d.ts +5 -0
  44. package/dist/wasm/generated/interfaces/wasi-filesystem-preopens.d.ts +3 -0
  45. package/dist/wasm/generated/interfaces/wasi-filesystem-types.d.ts +124 -0
  46. package/dist/wasm/generated/interfaces/wasi-io-error.d.ts +8 -0
  47. package/dist/wasm/generated/interfaces/wasi-io-streams.d.ts +28 -0
  48. package/dist/wasm/generated/session.core.wasm +0 -0
  49. package/dist/wasm/generated/session.core2.wasm +0 -0
  50. package/dist/wasm/generated/session.d.ts +16 -0
  51. package/dist/wasm/generated/session.js +3437 -0
  52. package/package.json +104 -0
@@ -0,0 +1,819 @@
1
+ /**
2
+ * WASM Component Interface - Mirrors the WIT specification exactly
3
+ *
4
+ * This interface works with completely opaque byte arrays, just like the WIT interface.
5
+ * The TypeScript SDK doesn't know about internal state machine phases or details.
6
+ */
7
+ /**
8
+ * Result type for WASM next() operations
9
+ */
10
+ interface WasmNextResult {
11
+ state: Uint8Array;
12
+ request: Uint8Array;
13
+ }
14
+ /**
15
+ * Client handshake operations - completely opaque byte arrays only
16
+ */
17
+ interface ClientHandshake {
18
+ /**
19
+ * Process next step in handshake
20
+ * @param state - Current handshake state (null for initial call)
21
+ * @param action - Action to process (opaque bytes)
22
+ * @returns Promise with new state and request to send
23
+ */
24
+ next(state: Uint8Array | null, action: Uint8Array): Promise<WasmNextResult>;
25
+ /**
26
+ * Attempt to finalize handshake
27
+ * @param state - Current handshake state
28
+ * @returns Promise with session bytes if successful
29
+ * @throws Error if handshake not ready to finalize
30
+ */
31
+ finish(state: Uint8Array): Promise<Uint8Array>;
32
+ }
33
+ /**
34
+ * Client authentication operations - completely opaque byte arrays only
35
+ */
36
+ interface ClientAuth {
37
+ /**
38
+ * Process next step in authentication
39
+ * @param state - Current auth state (null for initial call)
40
+ * @param action - Action to process (opaque bytes)
41
+ * @returns Promise with new state and request to send
42
+ */
43
+ next(state: Uint8Array | null, action: Uint8Array): Promise<WasmNextResult>;
44
+ /**
45
+ * Attempt to finalize authentication
46
+ * @param state - Current auth state
47
+ * @returns Promise with DID bytes if successful
48
+ * @throws Error if authentication not ready to finalize
49
+ */
50
+ finish(state: Uint8Array): Promise<Uint8Array>;
51
+ }
52
+ /**
53
+ * Client authentication operations - completely opaque byte arrays only
54
+ */
55
+ interface ClientExecute {
56
+ /**
57
+ * Process next step in authentication
58
+ * @param state - Current auth state (null for initial call)
59
+ * @param action - Action to process (opaque bytes)
60
+ * @returns Promise with new state and request to send
61
+ */
62
+ next(state: Uint8Array | null, action: Uint8Array): Promise<WasmNextResult>;
63
+ /**
64
+ * Attempt to finalize authentication
65
+ * @param state - Current auth state
66
+ * @returns Promise with DID bytes if successful
67
+ * @throws Error if authentication not ready to finalize
68
+ */
69
+ finish(state: Uint8Array): Promise<Uint8Array>;
70
+ }
71
+ /**
72
+ * Session encryption/decryption operations - completely opaque byte arrays only
73
+ */
74
+ interface SessionCrypto {
75
+ /**
76
+ * Encrypt plaintext using session
77
+ * @param session - Session state (opaque bytes)
78
+ * @param nonce - Nonce to use for encryption
79
+ * @param plaintext - Data to encrypt
80
+ * @returns Promise with encrypted bytes
81
+ */
82
+ encrypt(session: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array): Promise<Uint8Array>;
83
+ /**
84
+ * Decrypt ciphertext using session
85
+ * @param session - Session state (opaque bytes)
86
+ * @param ciphertext - Data to decrypt
87
+ * @returns Promise with decrypted bytes
88
+ */
89
+ decrypt(session: Uint8Array, ciphertext: Uint8Array): Promise<Uint8Array>;
90
+ }
91
+ /**
92
+ * Main WASM Component interface - mirrors the WIT interface exactly
93
+ *
94
+ * This is completely opaque to the TypeScript layer. All state machine logic,
95
+ * authentication flows, and cryptographic operations are handled in WASM.
96
+ */
97
+ interface WasmComponent {
98
+ /** Client handshake operations */
99
+ flow: {
100
+ handshake: ClientHandshake;
101
+ auth: ClientAuth;
102
+ execute: ClientExecute;
103
+ };
104
+ session: SessionCrypto;
105
+ }
106
+
107
+ /**
108
+ * Logger interface and implementations for T3n SDK
109
+ *
110
+ * Provides hierarchical log level control (DEBUG, INFO, WARN, ERROR) with
111
+ * global defaults and per-component override capabilities.
112
+ *
113
+ * ## Usage
114
+ *
115
+ * ```typescript
116
+ * import { getLogger, setGlobalLogLevel, LogLevel } from '@t3n-sdk/logger';
117
+ *
118
+ * // Use the global logger (defaults to ERROR level)
119
+ * const logger = getLogger();
120
+ * logger.error("This will be logged");
121
+ * logger.debug("This will NOT be logged by default");
122
+ *
123
+ * // Enable debug logging globally
124
+ * setGlobalLogLevel(LogLevel.DEBUG);
125
+ * const debugLogger = getLogger();
126
+ * debugLogger.debug("This will now be logged");
127
+ *
128
+ * // Create a logger with a specific level (overrides global)
129
+ * const infoLogger = createLogger(LogLevel.INFO);
130
+ * infoLogger.info("This will be logged");
131
+ * infoLogger.debug("This will NOT be logged");
132
+ * ```
133
+ *
134
+ * ## Log Levels
135
+ *
136
+ * - `DEBUG` (0): Most verbose, logs everything
137
+ * - `INFO` (1): Logs info, warnings, and errors
138
+ * - `WARN` (2): Logs warnings and errors only
139
+ * - `ERROR` (3): Logs errors only (default)
140
+ */
141
+ /**
142
+ * Log levels in hierarchical order (lower values = more verbose)
143
+ */
144
+ declare enum LogLevel {
145
+ DEBUG = 0,
146
+ INFO = 1,
147
+ WARN = 2,
148
+ ERROR = 3
149
+ }
150
+ /**
151
+ * Logger interface for SDK debugging and monitoring
152
+ */
153
+ interface Logger {
154
+ /**
155
+ * Log a debug message (most verbose)
156
+ * @param args - Arguments to log
157
+ */
158
+ debug(...args: any[]): void;
159
+ /**
160
+ * Log an info message
161
+ * @param args - Arguments to log
162
+ */
163
+ info(...args: any[]): void;
164
+ /**
165
+ * Log a warning message
166
+ * @param args - Arguments to log
167
+ */
168
+ warn(...args: any[]): void;
169
+ /**
170
+ * Log an error message (least verbose)
171
+ * @param args - Arguments to log
172
+ */
173
+ error(...args: any[]): void;
174
+ }
175
+ /**
176
+ * Set the global default log level for all components
177
+ *
178
+ * This affects all loggers created without an explicit log level.
179
+ * The default global log level is LogLevel.ERROR (only errors are logged).
180
+ *
181
+ * @param level - The log level to set as default for all components
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * // Enable debug logging globally
186
+ * setGlobalLogLevel(LogLevel.DEBUG);
187
+ *
188
+ * // Only log errors (default)
189
+ * setGlobalLogLevel(LogLevel.ERROR);
190
+ * ```
191
+ */
192
+ declare function setGlobalLogLevel(level: LogLevel): void;
193
+ /**
194
+ * Get the current global log level
195
+ * @returns The current global log level (default: LogLevel.ERROR)
196
+ */
197
+ declare function getGlobalLogLevel(): LogLevel;
198
+ /**
199
+ * Create a logger instance with the specified log level
200
+ * @param level - The log level for this logger. If not provided, defaults to the global log level (LogLevel.ERROR).
201
+ * @returns Logger instance configured with the specified or default log level
202
+ */
203
+ declare function createLogger(level?: LogLevel): Logger;
204
+ /**
205
+ * Get a logger instance using the global log level
206
+ * @returns Logger instance with global log level (default: LogLevel.ERROR)
207
+ */
208
+ declare function getLogger(): Logger;
209
+
210
+ /**
211
+ * WASM Component Loader
212
+ *
213
+ * This module provides utilities for loading and initializing the WASM component.
214
+ * The actual WASM loading implementation will depend on the build system and
215
+ * deployment environment.
216
+ */
217
+
218
+ /**
219
+ * Configuration for WASM component loading
220
+ */
221
+ interface WasmLoadConfig {
222
+ /** Path or URL to the WASM module */
223
+ wasmPath?: string;
224
+ /** Custom fetch function for loading WASM */
225
+ fetchFn?: typeof fetch;
226
+ /** Additional initialization options */
227
+ initOptions?: Record<string, any>;
228
+ /** Optional logger instance - if not provided, uses global default */
229
+ logger?: Logger;
230
+ }
231
+ /**
232
+ * Load and initialize the T3n WASM component
233
+ *
234
+ * @param config - Optional configuration for loading the WASM component
235
+ * @returns Promise that resolves to the initialized WASM component
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * const wasmComponent = await loadWasmComponent({
240
+ * wasmPath: '/path/to/t3n.wasm'
241
+ * });
242
+ * ```
243
+ */
244
+ declare function loadWasmComponent(config?: WasmLoadConfig): Promise<WasmComponent>;
245
+
246
+ /**
247
+ * Session-related types for T3n SDK
248
+ */
249
+ interface SessionId {
250
+ readonly value: string;
251
+ }
252
+ interface Did {
253
+ readonly value: string;
254
+ toString(): string;
255
+ }
256
+ interface HandshakeResult {
257
+ readonly sessionId: SessionId;
258
+ readonly expiry: number;
259
+ readonly authenticated: boolean;
260
+ readonly did?: Did;
261
+ }
262
+ /**
263
+ * Simple status enum - mirrors server SessionStatus only
264
+ */
265
+ declare enum SessionStatus {
266
+ Init = 0,
267
+ Encrypted = 1,
268
+ Authenticated = 2
269
+ }
270
+
271
+ /**
272
+ * Authentication-related types for T3n SDK
273
+ */
274
+ /**
275
+ * Authentication method enum
276
+ */
277
+ declare enum AuthMethod {
278
+ Ethereum = "eth",
279
+ OIDC = "oidc"
280
+ }
281
+ /**
282
+ * OIDC credentials interface
283
+ */
284
+ interface OidcCredentials {
285
+ provider: string;
286
+ idToken: string;
287
+ }
288
+ /**
289
+ * Base authentication input with method discriminator
290
+ */
291
+ interface BaseAuthInput {
292
+ method: AuthMethod;
293
+ }
294
+ /**
295
+ * Ethereum authentication input
296
+ */
297
+ interface EthAuthInput extends BaseAuthInput {
298
+ method: AuthMethod.Ethereum;
299
+ address: string;
300
+ }
301
+ /**
302
+ * OIDC authentication input
303
+ */
304
+ interface OidcAuthInput extends BaseAuthInput {
305
+ method: AuthMethod.OIDC;
306
+ credentials: OidcCredentials;
307
+ }
308
+ /**
309
+ * Union type for all supported authentication inputs
310
+ */
311
+ type AuthInput = EthAuthInput | OidcAuthInput;
312
+ /**
313
+ * Helper functions to create auth inputs
314
+ */
315
+ declare function createEthAuthInput(address: string): EthAuthInput;
316
+ declare function createOidcAuthInput(credentials: OidcCredentials): OidcAuthInput;
317
+
318
+ /**
319
+ * Public types export for T3n SDK
320
+ */
321
+ /**
322
+ * Guest-to-Host request handler function type
323
+ * Handles requests from WASM guest that need host (SDK) to perform side effects
324
+ */
325
+ type GuestToHostHandler = (requestData: any) => Promise<Uint8Array>;
326
+ /**
327
+ * Map of guest-to-host request handlers
328
+ * Keys match the guest_to_host tag values from the WASM
329
+ */
330
+ interface GuestToHostHandlers {
331
+ /**
332
+ * Handle Ethereum signature requests
333
+ * requestData: { guest_to_host: "EthSign", challenge: string (base64) }
334
+ * Returns: JSON bytes of { host_to_guest: "EthSign", challenge: string, signature: string }
335
+ */
336
+ EthSign?: GuestToHostHandler;
337
+ /**
338
+ * Handle MlKem public key requests
339
+ * requestData: { guest_to_host: "MlKemPublicKey" }
340
+ * Returns: JSON bytes of { host_to_guest: "MlKemPublicKey", key: string }
341
+ */
342
+ MlKemPublicKey?: GuestToHostHandler;
343
+ /**
344
+ * Handle random bytes requests
345
+ * requestData: { guest_to_host: "Random", len?: number }
346
+ * Returns: JSON bytes of { host_to_guest: "Random", bytes: string (base64) }
347
+ */
348
+ Random?: GuestToHostHandler;
349
+ [key: string]: GuestToHostHandler | undefined;
350
+ }
351
+
352
+ /**
353
+ * Transport layer for T3n SDK
354
+ *
355
+ * Abstracts the communication with T3n nodes, allowing for different
356
+ * implementations (HTTP, WebSocket, Mock) and easy testing.
357
+ */
358
+ /**
359
+ * JSON-RPC request structure
360
+ */
361
+ interface JsonRpcRequest {
362
+ jsonrpc: "2.0";
363
+ method: string;
364
+ params: any;
365
+ id: string | number;
366
+ }
367
+ /**
368
+ * JSON-RPC response structure
369
+ */
370
+ interface JsonRpcResponse {
371
+ jsonrpc: "2.0";
372
+ result?: any;
373
+ error?: {
374
+ code: number;
375
+ message: string;
376
+ data?: any;
377
+ };
378
+ id: string | number;
379
+ }
380
+ /**
381
+ * Transport interface for sending requests to T3n nodes
382
+ */
383
+ interface Transport {
384
+ /**
385
+ * Send a JSON-RPC request to the T3n node
386
+ * @param request - The JSON-RPC request to send
387
+ * @param headers - Additional headers to include
388
+ * @returns Promise that resolves to the JSON-RPC response
389
+ */
390
+ send(request: JsonRpcRequest, headers: Record<string, string>): Promise<JsonRpcResponse>;
391
+ /**
392
+ * Optional accessor for the latest Set-Cookie header value.
393
+ * (Useful in Node.js demos/tests; browsers block HttpOnly cookies.)
394
+ */
395
+ getLastSetCookie?(): string | null;
396
+ /**
397
+ * Optional accessor for the last response headers (debugging).
398
+ */
399
+ getLastResponseHeaders?(): Record<string, string>;
400
+ }
401
+ /**
402
+ * HTTP transport implementation using fetch
403
+ */
404
+ declare class HttpTransport implements Transport {
405
+ private baseUrl;
406
+ private timeout;
407
+ private lastSetCookie;
408
+ private lastResponseHeaders;
409
+ constructor(baseUrl: string, timeout?: number);
410
+ getLastSetCookie(): string | null;
411
+ getLastResponseHeaders(): Record<string, string>;
412
+ send(request: JsonRpcRequest, headers: Record<string, string>): Promise<JsonRpcResponse>;
413
+ }
414
+ /**
415
+ * Mock transport for testing
416
+ *
417
+ * @example
418
+ * ```typescript
419
+ * const mockTransport = new MockTransport();
420
+ * mockTransport.mockResponse("auth.handshake", { result: "..." });
421
+ *
422
+ * const client = new T3nClient({
423
+ * transport: mockTransport,
424
+ * wasmComponent: mockWasm,
425
+ * });
426
+ * ```
427
+ */
428
+ declare class MockTransport implements Transport {
429
+ private responses;
430
+ private requests;
431
+ /**
432
+ * Mock a response for a specific method
433
+ */
434
+ mockResponse(method: string, response: Partial<JsonRpcResponse>): void;
435
+ /**
436
+ * Mock an error response for a specific method
437
+ */
438
+ mockError(method: string, code: number, message: string, data?: any): void;
439
+ /**
440
+ * Get all requests that were sent
441
+ */
442
+ getRequests(): Array<{
443
+ request: JsonRpcRequest;
444
+ headers: Record<string, string>;
445
+ }>;
446
+ /**
447
+ * Get requests for a specific method
448
+ */
449
+ getRequestsForMethod(method: string): Array<{
450
+ request: JsonRpcRequest;
451
+ headers: Record<string, string>;
452
+ }>;
453
+ /**
454
+ * Clear all recorded requests
455
+ */
456
+ clearRequests(): void;
457
+ send(request: JsonRpcRequest, headers: Record<string, string>): Promise<JsonRpcResponse>;
458
+ }
459
+
460
+ /**
461
+ * Configuration types for T3n Client
462
+ */
463
+
464
+ /**
465
+ * Configuration interface for T3n Client
466
+ */
467
+ interface T3nClientConfig {
468
+ /** Base URL of the T3n node (used if transport not provided) */
469
+ baseUrl?: string;
470
+ /** WASM component instance for cryptographic operations */
471
+ wasmComponent: WasmComponent;
472
+ /** Optional transport layer - if not provided, uses HttpTransport with baseUrl */
473
+ transport?: Transport;
474
+ /** Optional session ID - will be generated if not provided */
475
+ sessionId?: SessionId;
476
+ /** Optional request timeout in milliseconds (default: 30000) - used for HttpTransport */
477
+ timeout?: number;
478
+ /** Optional custom headers to include in requests */
479
+ headers?: Record<string, string>;
480
+ /**
481
+ * Log level for this client instance.
482
+ * Defaults to global log level (LogLevel.ERROR) if not specified.
483
+ * Use LogLevel.DEBUG for verbose logging, LogLevel.INFO for informational messages,
484
+ * LogLevel.WARN for warnings, or LogLevel.ERROR for errors only.
485
+ */
486
+ logLevel?: LogLevel;
487
+ /** Optional custom logger - if provided, overrides logLevel */
488
+ logger?: Logger;
489
+ /** Optional guest-to-host request handlers - provides custom behavior for WASM requests */
490
+ handlers?: GuestToHostHandlers;
491
+ }
492
+
493
+ /**
494
+ * T3n Client - Main SDK class
495
+ *
496
+ * Provides a simple interface for establishing secure sessions with T3n nodes.
497
+ * All cryptographic complexity is handled in WASM components.
498
+ */
499
+
500
+ /**
501
+ * Main T3n SDK Client
502
+ */
503
+ declare class T3nClient {
504
+ private readonly config;
505
+ private readonly transport;
506
+ private readonly sessionId;
507
+ private readonly logger;
508
+ private readonly encryption;
509
+ private status;
510
+ private wasmState;
511
+ private did;
512
+ private handshakeResult;
513
+ constructor(config: T3nClientConfig);
514
+ /**
515
+ * Start the handshake process with the T3n node
516
+ */
517
+ handshake(): Promise<HandshakeResult>;
518
+ /**
519
+ * Authenticate with the T3n node
520
+ */
521
+ authenticate(authInput: AuthInput): Promise<Did>;
522
+ /**
523
+ * Execute an action on the T3n node
524
+ */
525
+ execute(payload: unknown): Promise<string>;
526
+ getSessionId(): SessionId;
527
+ getStatus(): SessionStatus;
528
+ getDid(): Did | null;
529
+ getLastSetCookie(): string | null;
530
+ getLastResponseHeaders(): Record<string, string>;
531
+ isAuthenticated(): boolean;
532
+ /**
533
+ * Run a WASM state machine flow to completion
534
+ */
535
+ private runFlow;
536
+ /**
537
+ * Try to finalize the current flow
538
+ */
539
+ private tryFinalize;
540
+ /**
541
+ * Handle a WASM request based on its type
542
+ */
543
+ private handleWasmRequest;
544
+ /**
545
+ * Handle a send-remote request by calling the RPC endpoint
546
+ */
547
+ private handleSendRemote;
548
+ private captureHandshakeResult;
549
+ /**
550
+ * Handle a guest-to-host request using configured handlers
551
+ */
552
+ private handleGuestToHost;
553
+ /**
554
+ * Send an RPC request with automatic encryption/decryption
555
+ */
556
+ private sendRpcRequest;
557
+ /**
558
+ * Get the current session state for encryption
559
+ */
560
+ private getSessionState;
561
+ }
562
+
563
+ /**
564
+ * Guest-to-Host Request Handlers
565
+ *
566
+ * These handle requests from WASM that need the host environment to perform side effects.
567
+ * Examples: signing challenges, providing public keys, generating random bytes.
568
+ */
569
+
570
+ /**
571
+ * Create an EthSign handler using MetaMask (window.ethereum)
572
+ * @param account - MetaMask account (string address or object with address property)
573
+ * @param logger - Optional logger instance. Defaults to a logger using the global log level (LogLevel.ERROR).
574
+ * Pass a custom logger to override logging behavior for this handler.
575
+ * @param privateKey - Optional private key for signing (if provided, MetaMask is not used)
576
+ */
577
+ declare function metamask_sign(account: any, logger?: Logger, privateKey?: string | undefined): GuestToHostHandler;
578
+ /**
579
+ * Get the current MetaMask address
580
+ * @returns Ethereum address (lowercase, 0x prefixed)
581
+ */
582
+ declare function metamask_get_address(): Promise<string>;
583
+ /**
584
+ * Get the address for a given private key
585
+ * @param privateKey - Ethereum private key (0x prefixed hex string)
586
+ * @returns Ethereum address (lowercase, 0x prefixed)
587
+ */
588
+ declare function eth_get_address(privateKey: string): string;
589
+ /**
590
+ * Create MlKemPublicKey handler that returns the environment-specific root public key
591
+ * Note: The Rust PkWithRho type serializes as an array of bytes, not a base64 string
592
+ */
593
+ declare function createMlKemPublicKeyHandler(): GuestToHostHandler;
594
+ /**
595
+ * Create Random handler backed by crypto.getRandomValues
596
+ * Note: The Rust Vec<u8> type serializes as an array of bytes, not a base64 string
597
+ */
598
+ declare function createRandomHandler(): GuestToHostHandler;
599
+ /**
600
+ * Create the default handler set required by the T3n handshake
601
+ */
602
+ declare function createDefaultHandlers(): GuestToHostHandlers;
603
+
604
+ /**
605
+ * Cryptographic utilities for T3n SDK
606
+ *
607
+ * Cross-platform crypto support:
608
+ * - Browsers: Uses Web Crypto API (global crypto)
609
+ * - Node.js 19+: Uses global crypto
610
+ * - Node.js 16-18: Imports crypto module
611
+ */
612
+ /**
613
+ * Generate a cryptographically secure random string
614
+ * @param length - Length of the random string in bytes
615
+ * @returns Base64-encoded random string
616
+ */
617
+ declare function generateRandomString(length?: number): string;
618
+ /**
619
+ * Generate a UUID v4
620
+ * @returns UUID string
621
+ */
622
+ declare function generateUUID(): string;
623
+ /**
624
+ * Convert a string to Uint8Array
625
+ * @param str - String to convert
626
+ * @returns Uint8Array representation
627
+ */
628
+ declare function stringToBytes(str: string): Uint8Array;
629
+ /**
630
+ * Convert Uint8Array to string
631
+ * @param bytes - Bytes to convert
632
+ * @returns String representation
633
+ */
634
+ declare function bytesToString(bytes: Uint8Array): string;
635
+
636
+ declare function getScriptVersion(rpcUrl: string, scriptName: string): Promise<string>;
637
+
638
+ /**
639
+ * Error classes for T3n SDK
640
+ */
641
+ /**
642
+ * Base error class for T3n SDK errors
643
+ */
644
+ declare class T3nError extends Error {
645
+ readonly code?: string | undefined;
646
+ constructor(message: string, code?: string | undefined);
647
+ }
648
+ /**
649
+ * Error thrown when session is in invalid state for operation
650
+ */
651
+ declare class SessionStateError extends T3nError {
652
+ readonly currentState: string;
653
+ constructor(message: string, currentState: string);
654
+ }
655
+ /**
656
+ * Error thrown during authentication process
657
+ */
658
+ declare class AuthenticationError extends T3nError {
659
+ readonly authMethod?: string | undefined;
660
+ constructor(message: string, authMethod?: string | undefined);
661
+ }
662
+ /**
663
+ * Error thrown during handshake process
664
+ */
665
+ declare class HandshakeError extends T3nError {
666
+ constructor(message: string);
667
+ }
668
+ /**
669
+ * Error thrown during RPC communication
670
+ */
671
+ declare class RpcError extends T3nError {
672
+ readonly rpcMethod?: string | undefined;
673
+ readonly httpStatus?: number | undefined;
674
+ constructor(message: string, rpcMethod?: string | undefined, httpStatus?: number | undefined);
675
+ }
676
+ /**
677
+ * Error thrown when WASM operations fail
678
+ */
679
+ declare class WasmError extends T3nError {
680
+ readonly operation?: string | undefined;
681
+ readonly payload?: unknown | undefined;
682
+ constructor(message: string, operation?: string | undefined, payload?: unknown | undefined);
683
+ }
684
+ /**
685
+ * Decode WASM error message from comma-separated byte array format
686
+ * WASM errors often come as "83,101,114,100,101..." which represents ASCII bytes
687
+ *
688
+ * @param errorMessage - The error message string that may contain comma-separated bytes
689
+ * @returns Decoded error message if it was encoded, otherwise original message
690
+ */
691
+ declare function decodeWasmErrorMessage(errorMessage: string): string;
692
+ /**
693
+ * Extract and decode error from WASM ComponentError
694
+ *
695
+ * @param error - The error object from WASM
696
+ * @returns Decoded error message
697
+ */
698
+ declare function extractWasmError(error: unknown): string;
699
+
700
+ /**
701
+ * Secret redaction utilities for T3n SDK
702
+ *
703
+ * Provides functions to redact sensitive information before logging
704
+ */
705
+ /**
706
+ * Redact secrets from values before logging
707
+ */
708
+ declare function redactSecrets(value: any): any;
709
+ /**
710
+ * Redact secrets from a JSON string
711
+ */
712
+ declare function redactSecretsFromJson(jsonString: string): string;
713
+
714
+ /**
715
+ * Configuration types for T3n SDK
716
+ */
717
+ /**
718
+ * Environment type for SDK configuration
719
+ */
720
+ type Environment = "local" | "staging" | "production" | "test";
721
+ /**
722
+ * SDK configuration structure
723
+ */
724
+ interface SdkConfig {
725
+ /** Environment identifier */
726
+ environment: Environment;
727
+ /** Base64-encoded ML-KEM root public key */
728
+ mlKemPublicKey: string;
729
+ /** Configuration version */
730
+ version: string;
731
+ }
732
+ /**
733
+ * Configuration validation result
734
+ */
735
+ interface ConfigValidationResult {
736
+ valid: boolean;
737
+ errors: string[];
738
+ }
739
+
740
+ /**
741
+ * Configuration loader for T3n SDK
742
+ *
743
+ * This module provides configuration validation utilities.
744
+ * All environment keys are included in the bundle, and runtime selection is done via setEnvironment().
745
+ */
746
+
747
+ /**
748
+ * Validate SDK configuration
749
+ */
750
+ declare function validateConfig(config: unknown): ConfigValidationResult;
751
+
752
+ /**
753
+ * Configuration entry point for T3n SDK
754
+ *
755
+ * This module imports all environment keys as base64 strings. All keys are included
756
+ * in the bundle, and the active key is selected at runtime via setEnvironment().
757
+ *
758
+ * Runtime key selection:
759
+ * - All keys (local, staging, production, test) are included in the bundle
760
+ * - Default environment is "production"
761
+ * - Use setEnvironment(env) to change the active key at runtime
762
+ *
763
+ * Binary files are converted to base64 strings at build time by the rollup binary plugin.
764
+ * In development mode (when running with tsx), files are read from the filesystem.
765
+ */
766
+
767
+ /**
768
+ * Set the active environment for key selection
769
+ *
770
+ * This function allows engineers to configure which ML-KEM public key
771
+ * should be used at runtime. All keys are included in the bundle, so
772
+ * switching environments doesn't require rebuilding.
773
+ *
774
+ * @param env - The environment identifier (local, staging, production, or test)
775
+ * @throws Error if the environment is invalid
776
+ *
777
+ * @example
778
+ * ```typescript
779
+ * import { setEnvironment } from '@terminal3/t3n-sdk';
780
+ *
781
+ * // Use staging environment
782
+ * setEnvironment('staging');
783
+ * ```
784
+ */
785
+ declare function setEnvironment(env: Environment): void;
786
+ /**
787
+ * Get the current environment identifier
788
+ *
789
+ * Returns the currently active environment, which defaults to "production".
790
+ * Use setEnvironment() to change the active environment.
791
+ *
792
+ * @returns The current environment identifier
793
+ */
794
+ declare function getEnvironment(): Environment;
795
+ /**
796
+ * Load configuration for the current environment
797
+ *
798
+ * Returns the SDK configuration with the ML-KEM public key for the
799
+ * currently active environment (set via setEnvironment()).
800
+ *
801
+ * @returns A minimal SdkConfig object with the ML-KEM public key
802
+ */
803
+ declare function loadConfig(): SdkConfig;
804
+ /**
805
+ * Get the ML-KEM public key from the current configuration
806
+ * This is the main entry point used by handlers
807
+ *
808
+ * @returns The base64-encoded ML-KEM public key for the current environment
809
+ */
810
+ declare function getMlKemPublicKey(): string;
811
+ /**
812
+ * Get the current environment identifier
813
+ *
814
+ * @returns The current environment name
815
+ */
816
+ declare function getEnvironmentName(): string;
817
+
818
+ export { AuthMethod, AuthenticationError, HandshakeError, HttpTransport, LogLevel, MockTransport, RpcError, SessionStateError, SessionStatus, T3nClient, T3nError, WasmError, bytesToString, createDefaultHandlers, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createRandomHandler, decodeWasmErrorMessage, eth_get_address, extractWasmError, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getMlKemPublicKey, getScriptVersion, loadConfig, loadWasmComponent, metamask_get_address, metamask_sign, redactSecrets, redactSecretsFromJson, setEnvironment, setGlobalLogLevel, stringToBytes, validateConfig };
819
+ export type { AuthInput, ClientAuth, ClientHandshake, ConfigValidationResult, Did, Environment, EthAuthInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, Logger, OidcAuthInput, OidcCredentials, SdkConfig, SessionCrypto, SessionId, T3nClientConfig, Transport, WasmComponent, WasmNextResult };