@tinycloud/sdk-services 2.2.0-beta.13 → 2.2.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.
@@ -0,0 +1,1340 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/encryption/index.ts
21
+ var encryption_exports = {};
22
+ __export(encryption_exports, {
23
+ DECRYPT_ACTION: () => DECRYPT_ACTION,
24
+ DECRYPT_FACT_TYPE: () => DECRYPT_FACT_TYPE,
25
+ DECRYPT_RESULT_TYPE: () => DECRYPT_RESULT_TYPE,
26
+ DEFAULT_ENCRYPTION_ALG: () => DEFAULT_ENCRYPTION_ALG,
27
+ DEFAULT_KEY_VERSION: () => DEFAULT_KEY_VERSION,
28
+ ENCRYPTION_NETWORK_URN_PREFIX: () => ENCRYPTION_NETWORK_URN_PREFIX,
29
+ ENCRYPTION_SERVICE: () => ENCRYPTION_SERVICE,
30
+ ENCRYPTION_SERVICE_SHORT: () => ENCRYPTION_SERVICE_SHORT,
31
+ ENVELOPE_VERSION: () => ENVELOPE_VERSION,
32
+ EncryptionService: () => EncryptionService,
33
+ NETWORK_NAME_PATTERN: () => NETWORK_NAME_PATTERN,
34
+ NetworkIdError: () => NetworkIdError,
35
+ base64Decode: () => base64Decode,
36
+ base64Encode: () => base64Encode,
37
+ buildCanonicalDecryptRequest: () => buildCanonicalDecryptRequest,
38
+ buildDecryptAttenuation: () => buildDecryptAttenuation,
39
+ buildDecryptFacts: () => buildDecryptFacts,
40
+ buildDecryptInvocation: () => buildDecryptInvocation,
41
+ buildNetworkId: () => buildNetworkId,
42
+ canonicalHashHex: () => canonicalHashHex,
43
+ canonicalSignedResponse: () => canonicalSignedResponse,
44
+ canonicalize: () => canonicalize,
45
+ checkDecryptInvocationInput: () => checkDecryptInvocationInput,
46
+ decryptEnvelopeWithKey: () => decryptEnvelopeWithKey,
47
+ deriveSignedReceiverKey: () => deriveSignedReceiverKey,
48
+ discoverNetwork: () => discoverNetwork,
49
+ encryptToNetwork: () => encryptToNetwork,
50
+ encryptionError: () => encryptionError,
51
+ ensureNetworkUsableForDecrypt: () => ensureNetworkUsableForDecrypt,
52
+ generateRandomReceiverKey: () => generateRandomReceiverKey,
53
+ hexDecode: () => hexDecode,
54
+ hexEncode: () => hexEncode,
55
+ isNetworkId: () => isNetworkId,
56
+ networkDiscoveryKey: () => networkDiscoveryKey,
57
+ openWrappedKey: () => openWrappedKey,
58
+ parseNetworkId: () => parseNetworkId,
59
+ utf8Decode: () => utf8Decode,
60
+ utf8Encode: () => utf8Encode,
61
+ validateEnvelope: () => validateEnvelope,
62
+ verifyDecryptResponse: () => verifyDecryptResponse
63
+ });
64
+ module.exports = __toCommonJS(encryption_exports);
65
+
66
+ // src/types.ts
67
+ var ErrorCodes = {
68
+ // Common errors
69
+ NOT_FOUND: "NOT_FOUND",
70
+ AUTH_EXPIRED: "AUTH_EXPIRED",
71
+ AUTH_REQUIRED: "AUTH_REQUIRED",
72
+ AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
73
+ NETWORK_ERROR: "NETWORK_ERROR",
74
+ TIMEOUT: "TIMEOUT",
75
+ ABORTED: "ABORTED",
76
+ INVALID_INPUT: "INVALID_INPUT",
77
+ PERMISSION_DENIED: "PERMISSION_DENIED",
78
+ // KV-specific errors
79
+ KV_NOT_FOUND: "KV_NOT_FOUND",
80
+ KV_WRITE_FAILED: "KV_WRITE_FAILED",
81
+ // SQL-specific errors
82
+ SQL_ERROR: "SQL_ERROR",
83
+ SQL_PERMISSION_DENIED: "SQL_PERMISSION_DENIED",
84
+ SQL_DATABASE_NOT_FOUND: "SQL_DATABASE_NOT_FOUND",
85
+ SQL_RESPONSE_TOO_LARGE: "SQL_RESPONSE_TOO_LARGE",
86
+ SQL_QUOTA_EXCEEDED: "SQL_QUOTA_EXCEEDED",
87
+ SQL_INVALID_STATEMENT: "SQL_INVALID_STATEMENT",
88
+ SQL_SCHEMA_ERROR: "SQL_SCHEMA_ERROR",
89
+ SQL_READONLY_VIOLATION: "SQL_READONLY_VIOLATION",
90
+ // Storage quota errors
91
+ STORAGE_QUOTA_EXCEEDED: "STORAGE_QUOTA_EXCEEDED",
92
+ STORAGE_LIMIT_REACHED: "STORAGE_LIMIT_REACHED",
93
+ // DuckDB-specific errors
94
+ DUCKDB_ERROR: "DUCKDB_ERROR",
95
+ DUCKDB_PERMISSION_DENIED: "DUCKDB_PERMISSION_DENIED",
96
+ DUCKDB_DATABASE_NOT_FOUND: "DUCKDB_DATABASE_NOT_FOUND",
97
+ DUCKDB_RESPONSE_TOO_LARGE: "DUCKDB_RESPONSE_TOO_LARGE",
98
+ DUCKDB_QUOTA_EXCEEDED: "DUCKDB_QUOTA_EXCEEDED",
99
+ DUCKDB_INVALID_STATEMENT: "DUCKDB_INVALID_STATEMENT",
100
+ DUCKDB_SCHEMA_ERROR: "DUCKDB_SCHEMA_ERROR",
101
+ DUCKDB_READONLY_VIOLATION: "DUCKDB_READONLY_VIOLATION"
102
+ };
103
+ var defaultRetryPolicy = {
104
+ maxAttempts: 3,
105
+ backoff: "exponential",
106
+ baseDelayMs: 1e3,
107
+ maxDelayMs: 1e4,
108
+ retryableErrors: [ErrorCodes.NETWORK_ERROR, ErrorCodes.TIMEOUT]
109
+ };
110
+ var TelemetryEvents = {
111
+ SERVICE_REQUEST: "service.request",
112
+ SERVICE_RESPONSE: "service.response",
113
+ SERVICE_ERROR: "service.error",
114
+ SERVICE_RETRY: "service.retry",
115
+ SESSION_CHANGED: "session.changed",
116
+ SESSION_EXPIRED: "session.expired"
117
+ };
118
+ function err(error) {
119
+ return { ok: false, error };
120
+ }
121
+
122
+ // src/errors.ts
123
+ function timeoutError(service) {
124
+ return {
125
+ code: ErrorCodes.TIMEOUT,
126
+ message: "Request timed out.",
127
+ service
128
+ };
129
+ }
130
+ function abortedError(service) {
131
+ return {
132
+ code: ErrorCodes.ABORTED,
133
+ message: "Request was aborted.",
134
+ service
135
+ };
136
+ }
137
+ function wrapError(service, error, defaultCode = ErrorCodes.NETWORK_ERROR) {
138
+ if (error instanceof Error) {
139
+ if (error.name === "AbortError") {
140
+ return abortedError(service);
141
+ }
142
+ if (error.name === "TimeoutError" || error.message.toLowerCase().includes("timeout")) {
143
+ return timeoutError(service);
144
+ }
145
+ return {
146
+ code: defaultCode,
147
+ message: error.message,
148
+ service,
149
+ cause: error
150
+ };
151
+ }
152
+ return {
153
+ code: defaultCode,
154
+ message: String(error),
155
+ service
156
+ };
157
+ }
158
+
159
+ // src/base/BaseService.ts
160
+ var BaseService = class {
161
+ constructor() {
162
+ /**
163
+ * Abort controller for this service's operations.
164
+ * Reset on sign-out.
165
+ */
166
+ this.abortController = new AbortController();
167
+ /**
168
+ * Service-specific configuration.
169
+ */
170
+ this._config = {};
171
+ }
172
+ /**
173
+ * Get the service configuration.
174
+ */
175
+ get config() {
176
+ return this._config;
177
+ }
178
+ /**
179
+ * Initialize the service with context.
180
+ * Called by the SDK after instantiation.
181
+ *
182
+ * @param context - The service context
183
+ */
184
+ initialize(context) {
185
+ this.context = context;
186
+ }
187
+ /**
188
+ * Called when session changes (sign-in, sign-out, refresh).
189
+ * Override in subclasses to handle session changes.
190
+ *
191
+ * @param session - The new session, or null if signed out
192
+ */
193
+ onSessionChange(session) {
194
+ }
195
+ /**
196
+ * Called when SDK signs out.
197
+ * Aborts all pending operations.
198
+ */
199
+ onSignOut() {
200
+ this.abortController.abort();
201
+ this.abortController = new AbortController();
202
+ }
203
+ /**
204
+ * Get the abort signal for this service.
205
+ * Combines the service-level abort with context-level abort.
206
+ */
207
+ get abortSignal() {
208
+ return this.abortController.signal;
209
+ }
210
+ /**
211
+ * Check if the service is authenticated.
212
+ */
213
+ get isAuthenticated() {
214
+ return this.context?.isAuthenticated ?? false;
215
+ }
216
+ /**
217
+ * Get the current session.
218
+ * Throws if not authenticated.
219
+ */
220
+ get session() {
221
+ if (!this.context?.session) {
222
+ throw new Error("Not authenticated");
223
+ }
224
+ return this.context.session;
225
+ }
226
+ /**
227
+ * Check authentication and return error result if not authenticated.
228
+ * Use this at the start of methods that require authentication.
229
+ *
230
+ * @returns true if authenticated, false otherwise
231
+ */
232
+ requireAuth() {
233
+ return this.isAuthenticated;
234
+ }
235
+ /**
236
+ * Emit a telemetry event.
237
+ *
238
+ * @param event - Event name
239
+ * @param data - Event data
240
+ */
241
+ emit(event, data) {
242
+ this.context?.emit(event, data);
243
+ }
244
+ /**
245
+ * Emit a service request event.
246
+ *
247
+ * @param action - The action being performed
248
+ * @param key - Optional key/path being accessed
249
+ */
250
+ emitRequest(action, key) {
251
+ this.emit(TelemetryEvents.SERVICE_REQUEST, {
252
+ service: this.getServiceName(),
253
+ action,
254
+ key,
255
+ timestamp: Date.now()
256
+ });
257
+ }
258
+ /**
259
+ * Emit a service response event.
260
+ *
261
+ * @param action - The action that was performed
262
+ * @param ok - Whether the request was successful
263
+ * @param startTime - Start time for duration calculation
264
+ * @param status - Optional HTTP status code
265
+ */
266
+ emitResponse(action, ok, startTime, status) {
267
+ this.emit(TelemetryEvents.SERVICE_RESPONSE, {
268
+ service: this.getServiceName(),
269
+ action,
270
+ ok,
271
+ duration: Date.now() - startTime,
272
+ status
273
+ });
274
+ }
275
+ /**
276
+ * Emit a service error event.
277
+ *
278
+ * @param error - The service error
279
+ */
280
+ emitError(error) {
281
+ this.emit(TelemetryEvents.SERVICE_ERROR, {
282
+ service: this.getServiceName(),
283
+ error
284
+ });
285
+ }
286
+ /**
287
+ * Get the service name from the static property.
288
+ * Subclasses must define static serviceName.
289
+ */
290
+ getServiceName() {
291
+ return this.constructor.serviceName;
292
+ }
293
+ /**
294
+ * Create a combined abort signal from multiple sources.
295
+ *
296
+ * @param signals - Additional abort signals to combine
297
+ * @returns A combined abort signal
298
+ */
299
+ combineSignals(...signals) {
300
+ const controller = new AbortController();
301
+ const allSignals = [this.abortSignal, ...signals.filter(Boolean)];
302
+ for (const signal of allSignals) {
303
+ if (signal.aborted) {
304
+ controller.abort(signal.reason);
305
+ return controller.signal;
306
+ }
307
+ signal.addEventListener("abort", () => controller.abort(signal.reason), {
308
+ once: true
309
+ });
310
+ }
311
+ return controller.signal;
312
+ }
313
+ /**
314
+ * Wrap an operation with error handling and telemetry.
315
+ *
316
+ * @param action - The action name for telemetry
317
+ * @param key - Optional key for telemetry
318
+ * @param operation - The operation to execute
319
+ * @returns Result of the operation
320
+ */
321
+ async withTelemetry(action, key, operation) {
322
+ const startTime = Date.now();
323
+ this.emitRequest(action, key);
324
+ try {
325
+ const result = await operation();
326
+ if (result.ok) {
327
+ this.emitResponse(action, true, startTime);
328
+ } else {
329
+ this.emitResponse(action, false, startTime);
330
+ this.emitError(result.error);
331
+ }
332
+ return result;
333
+ } catch (error) {
334
+ const serviceError2 = wrapError(this.getServiceName(), error);
335
+ this.emitResponse(action, false, startTime);
336
+ this.emitError(serviceError2);
337
+ return err(serviceError2);
338
+ }
339
+ }
340
+ };
341
+
342
+ // src/encryption/canonical.ts
343
+ function canonicalize(value) {
344
+ if (value === void 0) {
345
+ return "";
346
+ }
347
+ return stringify(value);
348
+ }
349
+ function stringify(value) {
350
+ if (value === null) return "null";
351
+ switch (typeof value) {
352
+ case "boolean":
353
+ case "number":
354
+ return JSON.stringify(value);
355
+ case "string":
356
+ return JSON.stringify(value);
357
+ case "object": {
358
+ if (Array.isArray(value)) {
359
+ return `[${value.map(stringify).join(",")}]`;
360
+ }
361
+ const keys = Object.keys(value).sort();
362
+ const parts = [];
363
+ for (const k of keys) {
364
+ const v = value[k];
365
+ if (v === void 0) continue;
366
+ parts.push(`${JSON.stringify(k)}:${stringify(v)}`);
367
+ }
368
+ return `{${parts.join(",")}}`;
369
+ }
370
+ default:
371
+ throw new TypeError(
372
+ `canonicalize: unsupported value type ${typeof value}`
373
+ );
374
+ }
375
+ }
376
+ var HEX = "0123456789abcdef";
377
+ function hexEncode(bytes) {
378
+ let out = "";
379
+ for (let i = 0; i < bytes.length; i++) {
380
+ const b = bytes[i];
381
+ out += HEX[b >> 4 & 15] + HEX[b & 15];
382
+ }
383
+ return out;
384
+ }
385
+ function hexDecode(hex) {
386
+ if (hex.length % 2 !== 0) {
387
+ throw new Error("hex string must have even length");
388
+ }
389
+ const out = new Uint8Array(hex.length / 2);
390
+ for (let i = 0; i < out.length; i++) {
391
+ const hi = parseInt(hex[i * 2], 16);
392
+ const lo = parseInt(hex[i * 2 + 1], 16);
393
+ if (Number.isNaN(hi) || Number.isNaN(lo)) {
394
+ throw new Error("invalid hex character");
395
+ }
396
+ out[i] = hi << 4 | lo;
397
+ }
398
+ return out;
399
+ }
400
+ function base64Encode(bytes) {
401
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
402
+ let out = "";
403
+ for (let i = 0; i < bytes.length; i += 3) {
404
+ const b0 = bytes[i];
405
+ const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
406
+ const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
407
+ out += chars[b0 >> 2 & 63];
408
+ out += chars[(b0 << 4 | b1 >> 4) & 63];
409
+ out += i + 1 < bytes.length ? chars[(b1 << 2 | b2 >> 6) & 63] : "=";
410
+ out += i + 2 < bytes.length ? chars[b2 & 63] : "=";
411
+ }
412
+ return out;
413
+ }
414
+ function base64Decode(s) {
415
+ const clean = s.replace(/[^A-Za-z0-9+/=]/g, "");
416
+ const len = clean.length;
417
+ if (len % 4 !== 0) {
418
+ throw new Error("invalid base64 input");
419
+ }
420
+ const padding = clean.endsWith("==") ? 2 : clean.endsWith("=") ? 1 : 0;
421
+ const outLen = len / 4 * 3 - padding;
422
+ const out = new Uint8Array(outLen);
423
+ const lookup = {};
424
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
425
+ for (let i = 0; i < chars.length; i++) lookup[chars[i]] = i;
426
+ let outIdx = 0;
427
+ for (let i = 0; i < len; i += 4) {
428
+ const v0 = lookup[clean[i]] ?? 0;
429
+ const v1 = lookup[clean[i + 1]] ?? 0;
430
+ const v2 = clean[i + 2] === "=" ? 0 : lookup[clean[i + 2]] ?? 0;
431
+ const v3 = clean[i + 3] === "=" ? 0 : lookup[clean[i + 3]] ?? 0;
432
+ const b0 = v0 << 2 | v1 >> 4;
433
+ const b1 = (v1 & 15) << 4 | v2 >> 2;
434
+ const b2 = (v2 & 3) << 6 | v3;
435
+ if (outIdx < outLen) out[outIdx++] = b0;
436
+ if (outIdx < outLen) out[outIdx++] = b1;
437
+ if (outIdx < outLen) out[outIdx++] = b2;
438
+ }
439
+ return out;
440
+ }
441
+ function utf8Encode(s) {
442
+ return new TextEncoder().encode(s);
443
+ }
444
+ function utf8Decode(b) {
445
+ return new TextDecoder().decode(b);
446
+ }
447
+ function canonicalHashHex(sha256, value) {
448
+ const canonical = canonicalize(value);
449
+ return hexEncode(sha256(utf8Encode(canonical)));
450
+ }
451
+
452
+ // src/encryption/networkId.ts
453
+ var URN_PREFIX = "urn:tinycloud:encryption:";
454
+ var NETWORK_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
455
+ var NetworkIdError = class extends Error {
456
+ constructor(message) {
457
+ super(message);
458
+ this.name = "NetworkIdError";
459
+ }
460
+ };
461
+ function parseNetworkId(networkId) {
462
+ if (typeof networkId !== "string" || networkId.length === 0) {
463
+ throw new NetworkIdError("networkId must be a non-empty string");
464
+ }
465
+ if (!networkId.startsWith(URN_PREFIX)) {
466
+ throw new NetworkIdError(
467
+ `networkId must start with ${URN_PREFIX} (got ${JSON.stringify(networkId)})`
468
+ );
469
+ }
470
+ const body = networkId.slice(URN_PREFIX.length);
471
+ const lastColon = body.lastIndexOf(":");
472
+ if (lastColon <= 0 || lastColon === body.length - 1) {
473
+ throw new NetworkIdError(
474
+ `networkId missing principal or name segment (got ${JSON.stringify(networkId)})`
475
+ );
476
+ }
477
+ const principal = body.slice(0, lastColon);
478
+ const name = body.slice(lastColon + 1);
479
+ if (!principal.startsWith("did:")) {
480
+ throw new NetworkIdError(
481
+ `networkId principal must be a DID (got ${JSON.stringify(principal)})`
482
+ );
483
+ }
484
+ const didParts = principal.split(":");
485
+ if (didParts.length < 3 || didParts.some((p) => p.length === 0)) {
486
+ throw new NetworkIdError(
487
+ `networkId principal is not a well-formed DID (got ${JSON.stringify(principal)})`
488
+ );
489
+ }
490
+ if (!NETWORK_NAME_RE.test(name)) {
491
+ throw new NetworkIdError(
492
+ `networkId name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
493
+ );
494
+ }
495
+ return { networkId, principal, name };
496
+ }
497
+ function buildNetworkId(principal, name) {
498
+ if (typeof principal !== "string" || !principal.startsWith("did:")) {
499
+ throw new NetworkIdError("principal must be a DID");
500
+ }
501
+ if (typeof name !== "string" || !NETWORK_NAME_RE.test(name)) {
502
+ throw new NetworkIdError(
503
+ `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
504
+ );
505
+ }
506
+ const networkId = `${URN_PREFIX}${principal}:${name}`;
507
+ parseNetworkId(networkId);
508
+ return networkId;
509
+ }
510
+ function isNetworkId(networkId) {
511
+ if (typeof networkId !== "string") {
512
+ return false;
513
+ }
514
+ try {
515
+ parseNetworkId(networkId);
516
+ return true;
517
+ } catch {
518
+ return false;
519
+ }
520
+ }
521
+ function networkDiscoveryKey(name) {
522
+ if (!NETWORK_NAME_RE.test(name)) {
523
+ throw new NetworkIdError(
524
+ `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
525
+ );
526
+ }
527
+ return `.well-known/encryption/network/${name}`;
528
+ }
529
+ var ENCRYPTION_NETWORK_URN_PREFIX = URN_PREFIX;
530
+ var NETWORK_NAME_PATTERN = NETWORK_NAME_RE;
531
+
532
+ // src/encryption/types.ts
533
+ var DEFAULT_ENCRYPTION_ALG = "x25519-aes256gcm/v1";
534
+ var ENVELOPE_VERSION = 1;
535
+ var DEFAULT_KEY_VERSION = 1;
536
+ var DECRYPT_FACT_TYPE = "tinycloud.encryption.decrypt/v1";
537
+ var DECRYPT_RESULT_TYPE = "tinycloud.encryption.decrypt-result/v1";
538
+ var ENCRYPTION_SERVICE = "tinycloud.encryption";
539
+ var ENCRYPTION_SERVICE_SHORT = "encryption";
540
+ var DECRYPT_ACTION = "tinycloud.encryption/decrypt";
541
+ function defaultEncryptionMessage(input) {
542
+ switch (input.code) {
543
+ case "NETWORK_NOT_FOUND":
544
+ return input.message ?? `Network not found: ${input.networkId ?? input.name ?? "<unknown>"}`;
545
+ case "NETWORK_NOT_ACTIVE":
546
+ return input.message ?? `Network not active (state=${input.state})`;
547
+ case "INVALID_NETWORK_ID":
548
+ return input.message;
549
+ case "INVALID_ENVELOPE":
550
+ return input.message;
551
+ case "DECRYPT_DENIED":
552
+ return input.message;
553
+ case "INVALID_RESPONSE":
554
+ return input.message;
555
+ case "RESPONSE_SIGNATURE_INVALID":
556
+ return input.message ?? "Node response signature failed to verify";
557
+ case "RESPONSE_BINDING_MISMATCH":
558
+ return input.message ?? `Node response binding mismatch on field ${JSON.stringify(input.field)}`;
559
+ case "TRANSPORT_ERROR":
560
+ return input.message ?? input.cause.message;
561
+ case "INVALID_INPUT":
562
+ return input.message;
563
+ }
564
+ }
565
+ function encryptionError(input) {
566
+ return {
567
+ ...input,
568
+ service: "encryption",
569
+ message: defaultEncryptionMessage(input)
570
+ };
571
+ }
572
+ function toError(error) {
573
+ if (error instanceof Error) return error;
574
+ if (typeof error === "object" && error !== null) {
575
+ return new Error(JSON.stringify(error));
576
+ }
577
+ return new Error(String(error));
578
+ }
579
+
580
+ // src/encryption/discovery.ts
581
+ async function discoverNetwork(input) {
582
+ let networkId;
583
+ let principal;
584
+ let name;
585
+ try {
586
+ if (input.identifier.startsWith("urn:tinycloud:encryption:")) {
587
+ const parsed = parseNetworkId(input.identifier);
588
+ networkId = parsed.networkId;
589
+ principal = parsed.principal;
590
+ name = parsed.name;
591
+ } else {
592
+ if (input.principal === void 0) {
593
+ return {
594
+ ok: false,
595
+ error: encryptionError({
596
+ code: "INVALID_INPUT",
597
+ message: "discoverNetwork requires `principal` when identifier is a bare network name"
598
+ })
599
+ };
600
+ }
601
+ networkId = `urn:tinycloud:encryption:${input.principal}:${input.identifier}`;
602
+ const parsed = parseNetworkId(networkId);
603
+ principal = parsed.principal;
604
+ name = parsed.name;
605
+ }
606
+ } catch (err2) {
607
+ if (err2 instanceof NetworkIdError) {
608
+ return {
609
+ ok: false,
610
+ error: encryptionError({
611
+ code: "INVALID_NETWORK_ID",
612
+ message: err2.message
613
+ })
614
+ };
615
+ }
616
+ throw err2;
617
+ }
618
+ if (input.node !== void 0) {
619
+ try {
620
+ const descriptor = await input.node.fetchByNetworkId(networkId);
621
+ if (descriptor !== null) {
622
+ const validated = validateDescriptor(descriptor, networkId, principal, name);
623
+ if (!validated.ok) return validated;
624
+ return { ok: true, data: { descriptor: validated.data, source: "node" } };
625
+ }
626
+ } catch (err2) {
627
+ }
628
+ }
629
+ if (input.wellKnown !== void 0) {
630
+ try {
631
+ const descriptor = await input.wellKnown.fetchWellKnown(
632
+ principal,
633
+ networkDiscoveryKey(name)
634
+ );
635
+ if (descriptor !== null) {
636
+ const validated = validateDescriptor(descriptor, networkId, principal, name);
637
+ if (!validated.ok) return validated;
638
+ return {
639
+ ok: true,
640
+ data: { descriptor: validated.data, source: "well-known" }
641
+ };
642
+ }
643
+ } catch (err2) {
644
+ }
645
+ }
646
+ return {
647
+ ok: false,
648
+ error: encryptionError({
649
+ code: "NETWORK_NOT_FOUND",
650
+ networkId,
651
+ name
652
+ })
653
+ };
654
+ }
655
+ function validateDescriptor(descriptor, networkId, principal, name) {
656
+ if (descriptor.networkId !== networkId) {
657
+ return {
658
+ ok: false,
659
+ error: encryptionError({
660
+ code: "INVALID_NETWORK_ID",
661
+ message: `descriptor networkId ${JSON.stringify(descriptor.networkId)} does not match expected ${JSON.stringify(networkId)}`
662
+ })
663
+ };
664
+ }
665
+ if (descriptor.principal !== principal) {
666
+ return {
667
+ ok: false,
668
+ error: encryptionError({
669
+ code: "INVALID_NETWORK_ID",
670
+ message: "descriptor principal does not match networkId principal"
671
+ })
672
+ };
673
+ }
674
+ if (descriptor.name !== name) {
675
+ return {
676
+ ok: false,
677
+ error: encryptionError({
678
+ code: "INVALID_NETWORK_ID",
679
+ message: "descriptor name does not match networkId name"
680
+ })
681
+ };
682
+ }
683
+ if (typeof descriptor.publicEncryptionKey !== "string" || descriptor.publicEncryptionKey.length === 0) {
684
+ return {
685
+ ok: false,
686
+ error: encryptionError({
687
+ code: "INVALID_NETWORK_ID",
688
+ message: "descriptor publicEncryptionKey must be a non-empty string"
689
+ })
690
+ };
691
+ }
692
+ return { ok: true, data: descriptor };
693
+ }
694
+ function ensureNetworkUsableForDecrypt(descriptor) {
695
+ if (descriptor.state === "active" || descriptor.state === "rotating") {
696
+ return { ok: true, data: descriptor };
697
+ }
698
+ return {
699
+ ok: false,
700
+ error: encryptionError({
701
+ code: "NETWORK_NOT_ACTIVE",
702
+ state: descriptor.state
703
+ })
704
+ };
705
+ }
706
+
707
+ // src/encryption/envelope.ts
708
+ function encryptToNetwork(crypto, input) {
709
+ parseNetworkId(input.networkId);
710
+ const alg = input.alg ?? DEFAULT_ENCRYPTION_ALG;
711
+ const keyVersion = input.keyVersion ?? DEFAULT_KEY_VERSION;
712
+ const symmetricKey = crypto.randomBytes(32);
713
+ const ciphertext = crypto.authEncrypt(symmetricKey, input.plaintext, input.aad);
714
+ const wrapped = crypto.sealToNetworkKey(input.networkPublicKey, symmetricKey);
715
+ const encryptedSymmetricKey = base64Encode(wrapped);
716
+ const encryptedSymmetricKeyHash = canonicalHashHex(
717
+ crypto.sha256,
718
+ encryptedSymmetricKey
719
+ );
720
+ const envelope = {
721
+ v: ENVELOPE_VERSION,
722
+ networkId: input.networkId,
723
+ alg,
724
+ keyVersion,
725
+ encryptedSymmetricKey,
726
+ encryptedSymmetricKeyHash,
727
+ ciphertext: base64Encode(ciphertext),
728
+ ...input.aad !== void 0 ? { aad: base64Encode(input.aad) } : {},
729
+ ...input.metadata !== void 0 ? { metadata: input.metadata } : {}
730
+ };
731
+ return { envelope, symmetricKey };
732
+ }
733
+ function validateEnvelope(crypto, envelope) {
734
+ if (envelope === null || typeof envelope !== "object") {
735
+ return {
736
+ ok: false,
737
+ error: encryptionError({
738
+ code: "INVALID_ENVELOPE",
739
+ message: "envelope must be an object"
740
+ })
741
+ };
742
+ }
743
+ const e = envelope;
744
+ if (e.v !== ENVELOPE_VERSION) {
745
+ return {
746
+ ok: false,
747
+ error: encryptionError({
748
+ code: "INVALID_ENVELOPE",
749
+ message: `envelope.v must be ${ENVELOPE_VERSION} (got ${e.v})`
750
+ })
751
+ };
752
+ }
753
+ try {
754
+ parseNetworkId(e.networkId);
755
+ } catch (err2) {
756
+ return {
757
+ ok: false,
758
+ error: encryptionError({
759
+ code: "INVALID_ENVELOPE",
760
+ message: `envelope.networkId is malformed: ${err2 instanceof Error ? err2.message : String(err2)}`
761
+ })
762
+ };
763
+ }
764
+ for (const field of [
765
+ "alg",
766
+ "encryptedSymmetricKey",
767
+ "encryptedSymmetricKeyHash",
768
+ "ciphertext"
769
+ ]) {
770
+ if (typeof e[field] !== "string" || e[field].length === 0) {
771
+ return {
772
+ ok: false,
773
+ error: encryptionError({
774
+ code: "INVALID_ENVELOPE",
775
+ message: `envelope.${field} must be a non-empty string`
776
+ })
777
+ };
778
+ }
779
+ }
780
+ if (typeof e.keyVersion !== "number" || !Number.isInteger(e.keyVersion)) {
781
+ return {
782
+ ok: false,
783
+ error: encryptionError({
784
+ code: "INVALID_ENVELOPE",
785
+ message: "envelope.keyVersion must be an integer"
786
+ })
787
+ };
788
+ }
789
+ const expectedHash = canonicalHashHex(crypto.sha256, e.encryptedSymmetricKey);
790
+ if (expectedHash !== e.encryptedSymmetricKeyHash) {
791
+ return {
792
+ ok: false,
793
+ error: encryptionError({
794
+ code: "INVALID_ENVELOPE",
795
+ message: "envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"
796
+ })
797
+ };
798
+ }
799
+ return { ok: true, data: e };
800
+ }
801
+ function decryptEnvelopeWithKey(crypto, envelope, symmetricKey) {
802
+ const ciphertext = base64Decode(envelope.ciphertext);
803
+ const aad = envelope.aad !== void 0 ? base64Decode(envelope.aad) : void 0;
804
+ return crypto.authDecrypt(symmetricKey, ciphertext, aad);
805
+ }
806
+
807
+ // src/encryption/invocation.ts
808
+ function buildCanonicalDecryptRequest(input) {
809
+ const canonicalBody = canonicalize(input.body);
810
+ const bodyHash = canonicalHashHex(
811
+ input.crypto.sha256,
812
+ input.body
813
+ );
814
+ const receiverPublicKeyHash = canonicalHashHex(
815
+ input.crypto.sha256,
816
+ input.body.receiverPublicKey
817
+ );
818
+ return { canonicalBody, bodyHash, receiverPublicKeyHash };
819
+ }
820
+ function buildDecryptFacts(input) {
821
+ const bodyHash = input.canonicalBody !== void 0 ? hexEncode(input.crypto.sha256(utf8Encode(input.canonicalBody))) : canonicalHashHex(
822
+ input.crypto.sha256,
823
+ input.body
824
+ );
825
+ const receiverPublicKeyHash = canonicalHashHex(
826
+ input.crypto.sha256,
827
+ input.body.receiverPublicKey
828
+ );
829
+ return {
830
+ type: DECRYPT_FACT_TYPE,
831
+ targetNode: input.body.targetNode,
832
+ networkId: input.body.networkId,
833
+ bodyHash,
834
+ encryptedSymmetricKeyHash: input.encryptedSymmetricKeyHash,
835
+ receiverPublicKeyHash,
836
+ alg: input.body.alg,
837
+ keyVersion: input.body.keyVersion
838
+ };
839
+ }
840
+ function buildDecryptAttenuation(networkId) {
841
+ parseNetworkId(networkId);
842
+ return {
843
+ [networkId]: {
844
+ [DECRYPT_ACTION]: {}
845
+ }
846
+ };
847
+ }
848
+ function checkDecryptInvocationInput(crypto, input) {
849
+ if (input.body.type !== DECRYPT_FACT_TYPE) {
850
+ return {
851
+ ok: false,
852
+ error: encryptionError({
853
+ code: "INVALID_INPUT",
854
+ message: `body.type must be ${DECRYPT_FACT_TYPE}`
855
+ })
856
+ };
857
+ }
858
+ if (input.facts.type !== DECRYPT_FACT_TYPE) {
859
+ return {
860
+ ok: false,
861
+ error: encryptionError({
862
+ code: "INVALID_INPUT",
863
+ message: `facts.type must be ${DECRYPT_FACT_TYPE}`
864
+ })
865
+ };
866
+ }
867
+ if (input.facts.targetNode !== input.targetNode) {
868
+ return {
869
+ ok: false,
870
+ error: encryptionError({
871
+ code: "INVALID_INPUT",
872
+ message: "facts.targetNode must equal targetNode \u2014 the UCAN audience binds the request to a single node"
873
+ })
874
+ };
875
+ }
876
+ if (input.body.targetNode !== input.targetNode) {
877
+ return {
878
+ ok: false,
879
+ error: encryptionError({
880
+ code: "INVALID_INPUT",
881
+ message: "body.targetNode must equal targetNode"
882
+ })
883
+ };
884
+ }
885
+ if (input.facts.networkId !== input.networkId) {
886
+ return {
887
+ ok: false,
888
+ error: encryptionError({
889
+ code: "INVALID_INPUT",
890
+ message: "facts.networkId must equal networkId"
891
+ })
892
+ };
893
+ }
894
+ if (input.body.networkId !== input.networkId) {
895
+ return {
896
+ ok: false,
897
+ error: encryptionError({
898
+ code: "INVALID_INPUT",
899
+ message: "body.networkId must equal networkId"
900
+ })
901
+ };
902
+ }
903
+ if (input.facts.alg !== input.body.alg) {
904
+ return {
905
+ ok: false,
906
+ error: encryptionError({
907
+ code: "INVALID_INPUT",
908
+ message: "facts.alg must equal body.alg"
909
+ })
910
+ };
911
+ }
912
+ if (input.facts.keyVersion !== input.body.keyVersion) {
913
+ return {
914
+ ok: false,
915
+ error: encryptionError({
916
+ code: "INVALID_INPUT",
917
+ message: "facts.keyVersion must equal body.keyVersion"
918
+ })
919
+ };
920
+ }
921
+ if (input.facts.encryptedSymmetricKeyHash !== input.body.encryptedSymmetricKeyHash) {
922
+ return {
923
+ ok: false,
924
+ error: encryptionError({
925
+ code: "INVALID_INPUT",
926
+ message: "facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"
927
+ })
928
+ };
929
+ }
930
+ if (input.facts.receiverPublicKeyHash !== input.body.receiverPublicKeyHash) {
931
+ return {
932
+ ok: false,
933
+ error: encryptionError({
934
+ code: "INVALID_INPUT",
935
+ message: "facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"
936
+ })
937
+ };
938
+ }
939
+ try {
940
+ parseNetworkId(input.networkId);
941
+ } catch (err2) {
942
+ return {
943
+ ok: false,
944
+ error: encryptionError({
945
+ code: "INVALID_NETWORK_ID",
946
+ message: err2 instanceof Error ? err2.message : String(err2)
947
+ })
948
+ };
949
+ }
950
+ const canonicalBody = canonicalize(
951
+ input.body
952
+ );
953
+ const expectedBodyHash = canonicalHashHex(crypto.sha256, input.body);
954
+ if (expectedBodyHash !== input.facts.bodyHash) {
955
+ return {
956
+ ok: false,
957
+ error: encryptionError({
958
+ code: "INVALID_INPUT",
959
+ message: "facts.bodyHash does not match the canonical body hash"
960
+ })
961
+ };
962
+ }
963
+ return { ok: true, data: input, canonicalBody };
964
+ }
965
+ async function buildDecryptInvocation(crypto, signer, input) {
966
+ const checked = checkDecryptInvocationInput(crypto, input);
967
+ if (!checked.ok) {
968
+ return checked;
969
+ }
970
+ try {
971
+ const built = await signer.signDecryptInvocation(checked.data);
972
+ if (!built.authorization || !built.invocationCid) {
973
+ return {
974
+ ok: false,
975
+ error: encryptionError({
976
+ code: "INVALID_INPUT",
977
+ message: "decrypt-invocation signer returned an empty authorization or invocationCid"
978
+ })
979
+ };
980
+ }
981
+ if (built.canonicalBody !== checked.canonicalBody) {
982
+ return {
983
+ ok: false,
984
+ error: encryptionError({
985
+ code: "INVALID_INPUT",
986
+ message: "decrypt-invocation signer returned a canonicalBody that does not match the SDK's canonicalization \u2014 signer must use the SDK-provided body"
987
+ })
988
+ };
989
+ }
990
+ return { ok: true, data: built };
991
+ } catch (err2) {
992
+ return {
993
+ ok: false,
994
+ error: encryptionError({
995
+ code: "TRANSPORT_ERROR",
996
+ cause: err2 instanceof Error ? err2 : new Error(String(err2)),
997
+ message: `failed to sign decrypt invocation: ${err2 instanceof Error ? err2.message : String(err2)}`
998
+ })
999
+ };
1000
+ }
1001
+ }
1002
+
1003
+ // src/encryption/receiverKey.ts
1004
+ function generateRandomReceiverKey(input) {
1005
+ const seed = input.crypto.randomBytes(32);
1006
+ return input.crypto.x25519FromSeed(seed);
1007
+ }
1008
+ async function deriveSignedReceiverKey(input) {
1009
+ const message = `tinycloud.encryption.receiver-key/v1:${input.networkId}:${input.context ?? ""}`;
1010
+ const sig = await input.signer.signMessage(message);
1011
+ const sigBytes = utf8Encode(sig);
1012
+ const seed = input.crypto.sha256(sigBytes);
1013
+ return input.crypto.x25519FromSeed(seed);
1014
+ }
1015
+
1016
+ // src/encryption/response.ts
1017
+ function canonicalSignedResponse(response) {
1018
+ const { nodeSignature: _drop, ...rest } = response;
1019
+ return canonicalize(rest);
1020
+ }
1021
+ function verifyDecryptResponse(input) {
1022
+ const { crypto, request, facts, invocationCid, requestBodyHash, response } = input;
1023
+ if (response.type !== DECRYPT_RESULT_TYPE) {
1024
+ return {
1025
+ ok: false,
1026
+ error: encryptionError({
1027
+ code: "INVALID_RESPONSE",
1028
+ message: `response.type must be ${DECRYPT_RESULT_TYPE}`
1029
+ })
1030
+ };
1031
+ }
1032
+ if (response.targetNode !== request.targetNode) {
1033
+ return {
1034
+ ok: false,
1035
+ error: encryptionError({
1036
+ code: "RESPONSE_BINDING_MISMATCH",
1037
+ field: "targetNode"
1038
+ })
1039
+ };
1040
+ }
1041
+ if (response.networkId !== request.networkId) {
1042
+ return {
1043
+ ok: false,
1044
+ error: encryptionError({
1045
+ code: "RESPONSE_BINDING_MISMATCH",
1046
+ field: "networkId"
1047
+ })
1048
+ };
1049
+ }
1050
+ if (response.alg !== request.alg) {
1051
+ return {
1052
+ ok: false,
1053
+ error: encryptionError({
1054
+ code: "RESPONSE_BINDING_MISMATCH",
1055
+ field: "alg"
1056
+ })
1057
+ };
1058
+ }
1059
+ if (response.keyVersion !== request.keyVersion) {
1060
+ return {
1061
+ ok: false,
1062
+ error: encryptionError({
1063
+ code: "RESPONSE_BINDING_MISMATCH",
1064
+ field: "keyVersion"
1065
+ })
1066
+ };
1067
+ }
1068
+ if (response.encryptedSymmetricKeyHash !== request.encryptedSymmetricKeyHash) {
1069
+ return {
1070
+ ok: false,
1071
+ error: encryptionError({
1072
+ code: "RESPONSE_BINDING_MISMATCH",
1073
+ field: "encryptedSymmetricKeyHash"
1074
+ })
1075
+ };
1076
+ }
1077
+ if (response.receiverPublicKeyHash !== request.receiverPublicKeyHash) {
1078
+ return {
1079
+ ok: false,
1080
+ error: encryptionError({
1081
+ code: "RESPONSE_BINDING_MISMATCH",
1082
+ field: "receiverPublicKeyHash"
1083
+ })
1084
+ };
1085
+ }
1086
+ if (response.invocationCid !== invocationCid) {
1087
+ return {
1088
+ ok: false,
1089
+ error: encryptionError({
1090
+ code: "RESPONSE_BINDING_MISMATCH",
1091
+ field: "invocationCid"
1092
+ })
1093
+ };
1094
+ }
1095
+ const expectedRequestHash = hexEncode(
1096
+ crypto.sha256(utf8Encode(`${invocationCid}${requestBodyHash}`))
1097
+ );
1098
+ if (response.requestHash !== expectedRequestHash) {
1099
+ return {
1100
+ ok: false,
1101
+ error: encryptionError({
1102
+ code: "RESPONSE_BINDING_MISMATCH",
1103
+ field: "requestHash"
1104
+ })
1105
+ };
1106
+ }
1107
+ if (facts.encryptedSymmetricKeyHash !== response.encryptedSymmetricKeyHash || facts.receiverPublicKeyHash !== response.receiverPublicKeyHash || facts.networkId !== response.networkId || facts.targetNode !== response.targetNode || facts.alg !== response.alg || facts.keyVersion !== response.keyVersion) {
1108
+ return {
1109
+ ok: false,
1110
+ error: encryptionError({
1111
+ code: "RESPONSE_BINDING_MISMATCH",
1112
+ field: "facts"
1113
+ })
1114
+ };
1115
+ }
1116
+ const signedBytes = new TextEncoder().encode(
1117
+ canonicalSignedResponse(response)
1118
+ );
1119
+ const signatureBytes = base64Decode(response.nodeSignature);
1120
+ if (!crypto.verifyNodeSignature(response.nodeId, signedBytes, signatureBytes)) {
1121
+ return {
1122
+ ok: false,
1123
+ error: encryptionError({
1124
+ code: "RESPONSE_SIGNATURE_INVALID"
1125
+ })
1126
+ };
1127
+ }
1128
+ return { ok: true, data: response };
1129
+ }
1130
+ function openWrappedKey(crypto, receiverPrivateKey, response) {
1131
+ const wrapped = base64Decode(response.wrappedKey);
1132
+ return crypto.openWithReceiverKey(receiverPrivateKey, wrapped);
1133
+ }
1134
+
1135
+ // src/encryption/EncryptionService.ts
1136
+ function encOk(data) {
1137
+ return { ok: true, data };
1138
+ }
1139
+ function encErr(error) {
1140
+ return { ok: false, error };
1141
+ }
1142
+ var EncryptionService = class extends BaseService {
1143
+ constructor(config) {
1144
+ super();
1145
+ this._config = config;
1146
+ }
1147
+ get config() {
1148
+ return this._config;
1149
+ }
1150
+ get crypto() {
1151
+ return this._config.crypto;
1152
+ }
1153
+ async discoverNetwork(identifier, principal) {
1154
+ const result = await discoverNetwork({
1155
+ identifier,
1156
+ ...principal !== void 0 ? { principal } : {},
1157
+ ...this._config.node !== void 0 ? { node: this._config.node } : {},
1158
+ ...this._config.wellKnown !== void 0 ? { wellKnown: this._config.wellKnown } : {}
1159
+ });
1160
+ if (!result.ok) return result;
1161
+ return encOk(result.data.descriptor);
1162
+ }
1163
+ async encryptToNetwork(networkId, plaintext, options) {
1164
+ try {
1165
+ const discovered = await this.discoverNetwork(networkId);
1166
+ if (!discovered.ok) return discovered;
1167
+ const usable = ensureNetworkUsableForDecrypt(discovered.data);
1168
+ if (!usable.ok) return usable;
1169
+ const descriptor = usable.data;
1170
+ const networkPublicKey = base64Decode(descriptor.publicEncryptionKey);
1171
+ const result = encryptToNetwork(this.crypto, {
1172
+ networkId,
1173
+ networkPublicKey,
1174
+ plaintext,
1175
+ ...options?.aad !== void 0 ? { aad: options.aad } : {},
1176
+ alg: options?.alg ?? descriptor.alg,
1177
+ keyVersion: options?.keyVersion ?? descriptor.keyVersion,
1178
+ ...options?.metadata !== void 0 ? { metadata: options.metadata } : {}
1179
+ });
1180
+ return encOk(result.envelope);
1181
+ } catch (error) {
1182
+ return encErr(
1183
+ encryptionError({
1184
+ code: "TRANSPORT_ERROR",
1185
+ cause: toError(error)
1186
+ })
1187
+ );
1188
+ }
1189
+ }
1190
+ async decryptEnvelope(envelope, capabilityProof, options) {
1191
+ try {
1192
+ const validated = validateEnvelope(this.crypto, envelope);
1193
+ if (!validated.ok) return validated;
1194
+ let descriptor;
1195
+ if (options?.descriptor !== void 0) {
1196
+ descriptor = options.descriptor;
1197
+ } else {
1198
+ const discovered = await this.discoverNetwork(envelope.networkId);
1199
+ if (!discovered.ok) return discovered;
1200
+ descriptor = discovered.data;
1201
+ }
1202
+ const usable = ensureNetworkUsableForDecrypt(descriptor);
1203
+ if (!usable.ok) return usable;
1204
+ const targetNode = options?.targetNode ?? descriptor.members[0]?.nodeId;
1205
+ if (targetNode === void 0) {
1206
+ return encErr(
1207
+ encryptionError({
1208
+ code: "INVALID_INPUT",
1209
+ message: "no target node available from descriptor"
1210
+ })
1211
+ );
1212
+ }
1213
+ const receiverKey = generateRandomReceiverKey({ crypto: this.crypto });
1214
+ const receiverPublicKey = base64Encode(receiverKey.publicKey);
1215
+ const receiverPublicKeyHash = canonicalHashHex(
1216
+ this.crypto.sha256,
1217
+ receiverPublicKey
1218
+ );
1219
+ const body = {
1220
+ type: DECRYPT_FACT_TYPE,
1221
+ targetNode,
1222
+ networkId: envelope.networkId,
1223
+ alg: envelope.alg,
1224
+ keyVersion: envelope.keyVersion,
1225
+ encryptedSymmetricKey: envelope.encryptedSymmetricKey,
1226
+ encryptedSymmetricKeyHash: envelope.encryptedSymmetricKeyHash,
1227
+ receiverPublicKey,
1228
+ receiverPublicKeyHash
1229
+ };
1230
+ const canonicalRequest = buildCanonicalDecryptRequest({
1231
+ crypto: this.crypto,
1232
+ body,
1233
+ receiverPublicKey: receiverKey.publicKey
1234
+ });
1235
+ const facts = buildDecryptFacts({
1236
+ crypto: this.crypto,
1237
+ body,
1238
+ encryptedSymmetricKeyHash: envelope.encryptedSymmetricKeyHash,
1239
+ receiverPublicKey: receiverKey.publicKey,
1240
+ canonicalBody: canonicalRequest.canonicalBody
1241
+ });
1242
+ const built = await buildDecryptInvocation(this.crypto, this._config.signer, {
1243
+ targetNode,
1244
+ networkId: envelope.networkId,
1245
+ body,
1246
+ facts,
1247
+ proof: capabilityProof
1248
+ });
1249
+ if (!built.ok) return built;
1250
+ let response;
1251
+ try {
1252
+ response = await this._config.transport.postDecrypt({
1253
+ targetNode,
1254
+ networkId: envelope.networkId,
1255
+ authorization: built.data.authorization,
1256
+ canonicalBody: built.data.canonicalBody
1257
+ });
1258
+ } catch (error) {
1259
+ return encErr(
1260
+ encryptionError({
1261
+ code: "TRANSPORT_ERROR",
1262
+ cause: toError(error)
1263
+ })
1264
+ );
1265
+ }
1266
+ const verified = verifyDecryptResponse({
1267
+ crypto: this.crypto,
1268
+ request: body,
1269
+ facts,
1270
+ invocationCid: built.data.invocationCid,
1271
+ requestBodyHash: facts.bodyHash,
1272
+ response
1273
+ });
1274
+ if (!verified.ok) return verified;
1275
+ const symmetricKey = openWrappedKey(
1276
+ this.crypto,
1277
+ receiverKey.privateKey,
1278
+ verified.data
1279
+ );
1280
+ const plaintext = decryptEnvelopeWithKey(
1281
+ this.crypto,
1282
+ envelope,
1283
+ symmetricKey
1284
+ );
1285
+ return encOk(plaintext);
1286
+ } catch (error) {
1287
+ return encErr(
1288
+ encryptionError({
1289
+ code: "TRANSPORT_ERROR",
1290
+ cause: toError(error)
1291
+ })
1292
+ );
1293
+ }
1294
+ }
1295
+ };
1296
+ EncryptionService.serviceName = "encryption";
1297
+ // Annotate the CommonJS export names for ESM import in node:
1298
+ 0 && (module.exports = {
1299
+ DECRYPT_ACTION,
1300
+ DECRYPT_FACT_TYPE,
1301
+ DECRYPT_RESULT_TYPE,
1302
+ DEFAULT_ENCRYPTION_ALG,
1303
+ DEFAULT_KEY_VERSION,
1304
+ ENCRYPTION_NETWORK_URN_PREFIX,
1305
+ ENCRYPTION_SERVICE,
1306
+ ENCRYPTION_SERVICE_SHORT,
1307
+ ENVELOPE_VERSION,
1308
+ EncryptionService,
1309
+ NETWORK_NAME_PATTERN,
1310
+ NetworkIdError,
1311
+ base64Decode,
1312
+ base64Encode,
1313
+ buildCanonicalDecryptRequest,
1314
+ buildDecryptAttenuation,
1315
+ buildDecryptFacts,
1316
+ buildDecryptInvocation,
1317
+ buildNetworkId,
1318
+ canonicalHashHex,
1319
+ canonicalSignedResponse,
1320
+ canonicalize,
1321
+ checkDecryptInvocationInput,
1322
+ decryptEnvelopeWithKey,
1323
+ deriveSignedReceiverKey,
1324
+ discoverNetwork,
1325
+ encryptToNetwork,
1326
+ encryptionError,
1327
+ ensureNetworkUsableForDecrypt,
1328
+ generateRandomReceiverKey,
1329
+ hexDecode,
1330
+ hexEncode,
1331
+ isNetworkId,
1332
+ networkDiscoveryKey,
1333
+ openWrappedKey,
1334
+ parseNetworkId,
1335
+ utf8Decode,
1336
+ utf8Encode,
1337
+ validateEnvelope,
1338
+ verifyDecryptResponse
1339
+ });
1340
+ //# sourceMappingURL=index.cjs.map