sealnet 2.0.3 → 3.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.cjs CHANGED
@@ -37,7 +37,7 @@ __export(index_exports, {
37
37
  module.exports = __toCommonJS(index_exports);
38
38
 
39
39
  // <define:__SEAL_WASM__>
40
- var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v2.0.3/seal_crypto.wasm", integrity: "sha384-Ns+tIeOoczLFd8Cu9QLYM0jfXhqXKtwZ4DUGXDbpx4rvgBmPdduFWqlvTIZQz1Q7" };
40
+ var define_SEAL_WASM_default = { url: "https://seal.net/sdk/v3.0.0/seal_crypto.wasm", integrity: "sha384-1YRbwC1HEXYdDK3uZhUll78kTSwBJsxo0u34UsveDvpdd5We2JKnqAWOsru5GK3R" };
41
41
 
42
42
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
43
43
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
@@ -49,19 +49,122 @@ var __export2 = (target, all) => {
49
49
  };
50
50
  var glue_module_generated_exports = {};
51
51
  __export2(glue_module_generated_exports, {
52
+ ContractTermsBuilder: () => ContractTermsBuilder,
52
53
  WasmIdentity: () => WasmIdentity,
53
54
  default: () => __wbg_init,
54
55
  init: () => init,
55
56
  initSync: () => initSync,
57
+ wasm_approval_message: () => wasm_approval_message,
56
58
  wasm_bundle_address: () => wasm_bundle_address,
57
59
  wasm_bundle_verify_for_address: () => wasm_bundle_verify_for_address,
58
60
  wasm_contract_message: () => wasm_contract_message,
61
+ wasm_contract_message_v2: () => wasm_contract_message_v2,
59
62
  wasm_ed25519_verify: () => wasm_ed25519_verify,
60
63
  wasm_sealbox_unwrap: () => wasm_sealbox_unwrap,
61
64
  wasm_sealbox_wrap: () => wasm_sealbox_wrap,
65
+ wasm_summary_message: () => wasm_summary_message,
62
66
  wasm_unwrap_file_key: () => wasm_unwrap_file_key,
63
67
  wasm_wrap_file_key: () => wasm_wrap_file_key
64
68
  });
69
+ var ContractTermsBuilder = class {
70
+ __destroy_into_raw() {
71
+ const ptr = this.__wbg_ptr;
72
+ this.__wbg_ptr = 0;
73
+ ContractTermsBuilderFinalization.unregister(this);
74
+ return ptr;
75
+ }
76
+ free() {
77
+ const ptr = this.__destroy_into_raw();
78
+ wasm.__wbg_contracttermsbuilder_free(ptr, 0);
79
+ }
80
+ /**
81
+ * The digest in hex; the builder is spent.
82
+ * @returns {string}
83
+ */
84
+ digest() {
85
+ let deferred1_0;
86
+ let deferred1_1;
87
+ try {
88
+ const ptr = this.__destroy_into_raw();
89
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
90
+ wasm.contracttermsbuilder_digest(retptr, ptr);
91
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
92
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
93
+ deferred1_0 = r0;
94
+ deferred1_1 = r1;
95
+ return getStringFromWasm0(r0, r1);
96
+ } finally {
97
+ wasm.__wbindgen_add_to_stack_pointer(16);
98
+ wasm.__wbindgen_export2(deferred1_0, deferred1_1, 1);
99
+ }
100
+ }
101
+ /**
102
+ * @param {string} id
103
+ * @param {string} field_type
104
+ * @param {number} page
105
+ * @param {number} x
106
+ * @param {number} y
107
+ * @param {number} w
108
+ * @param {number} h
109
+ * @param {string} assignee_type
110
+ * @param {string} assignee
111
+ * @param {boolean} required
112
+ */
113
+ field(id, field_type, page, x, y, w, h, assignee_type, assignee, required) {
114
+ try {
115
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
116
+ const ptr0 = passStringToWasm0(id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
117
+ const len0 = WASM_VECTOR_LEN;
118
+ const ptr1 = passStringToWasm0(field_type, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
119
+ const len1 = WASM_VECTOR_LEN;
120
+ const ptr2 = passStringToWasm0(assignee_type, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
121
+ const len2 = WASM_VECTOR_LEN;
122
+ const ptr3 = passStringToWasm0(assignee, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
123
+ const len3 = WASM_VECTOR_LEN;
124
+ wasm.contracttermsbuilder_field(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, page, x, y, w, h, ptr2, len2, ptr3, len3, required);
125
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
126
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
127
+ if (r1) {
128
+ throw takeObject(r0);
129
+ }
130
+ } finally {
131
+ wasm.__wbindgen_add_to_stack_pointer(16);
132
+ }
133
+ }
134
+ /**
135
+ * @param {string} field_id
136
+ * @param {string} sha256_hex
137
+ */
138
+ filled(field_id, sha256_hex) {
139
+ try {
140
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
141
+ const ptr0 = passStringToWasm0(field_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
142
+ const len0 = WASM_VECTOR_LEN;
143
+ const ptr1 = passStringToWasm0(sha256_hex, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
144
+ const len1 = WASM_VECTOR_LEN;
145
+ wasm.contracttermsbuilder_filled(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);
146
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
147
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
148
+ if (r1) {
149
+ throw takeObject(r0);
150
+ }
151
+ } finally {
152
+ wasm.__wbindgen_add_to_stack_pointer(16);
153
+ }
154
+ }
155
+ /**
156
+ * @param {string | null} [meta_encrypted]
157
+ */
158
+ constructor(meta_encrypted) {
159
+ var ptr0 = isLikeNone(meta_encrypted) ? 0 : passStringToWasm0(meta_encrypted, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
160
+ var len0 = WASM_VECTOR_LEN;
161
+ const ret = wasm.contracttermsbuilder_new(ptr0, len0);
162
+ this.__wbg_ptr = ret;
163
+ ContractTermsBuilderFinalization.register(this, this.__wbg_ptr, this);
164
+ return this;
165
+ }
166
+ };
167
+ if (Symbol.dispose) ContractTermsBuilder.prototype[Symbol.dispose] = ContractTermsBuilder.prototype.free;
65
168
  var WasmIdentity = class _WasmIdentity {
66
169
  static __wrap(ptr) {
67
170
  const obj = Object.create(_WasmIdentity.prototype);
@@ -224,6 +327,34 @@ var WasmIdentity = class _WasmIdentity {
224
327
  wasm.__wbindgen_add_to_stack_pointer(16);
225
328
  }
226
329
  }
330
+ /**
331
+ * An owner's answer to a guard's question (SPEC agent egress §7.3): `allow` or `deny` of `ask` at `at`.
332
+ * @param {string} ask
333
+ * @param {string} decision
334
+ * @param {string} at
335
+ * @returns {Uint8Array}
336
+ */
337
+ signApproval(ask, decision, at) {
338
+ try {
339
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
340
+ const ptr0 = passStringToWasm0(ask, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
341
+ const len0 = WASM_VECTOR_LEN;
342
+ const ptr1 = passStringToWasm0(decision, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
343
+ const len1 = WASM_VECTOR_LEN;
344
+ const ptr2 = passStringToWasm0(at, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
345
+ const len2 = WASM_VECTOR_LEN;
346
+ wasm.wasmidentity_signApproval(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);
347
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
348
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
349
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
350
+ if (r2) {
351
+ throw takeObject(r1);
352
+ }
353
+ return takeObject(r0);
354
+ } finally {
355
+ wasm.__wbindgen_add_to_stack_pointer(16);
356
+ }
357
+ }
227
358
  /**
228
359
  * The signature of a contract (Р31, Р37).
229
360
  * @param {string} org_id
@@ -253,7 +384,93 @@ var WasmIdentity = class _WasmIdentity {
253
384
  }
254
385
  }
255
386
  /**
256
- * The three words of the address.
387
+ * The signature of a contract and of what its signer saw (AUDIT K204): `terms` is `ContractTermsBuilder`'s digest.
388
+ * @param {string} org_id
389
+ * @param {string} request_id
390
+ * @param {string} doc_hash
391
+ * @param {string} terms
392
+ * @returns {Uint8Array}
393
+ */
394
+ signContractV2(org_id, request_id, doc_hash, terms) {
395
+ try {
396
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
397
+ const ptr0 = passStringToWasm0(org_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
398
+ const len0 = WASM_VECTOR_LEN;
399
+ const ptr1 = passStringToWasm0(request_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
400
+ const len1 = WASM_VECTOR_LEN;
401
+ const ptr2 = passStringToWasm0(doc_hash, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
402
+ const len2 = WASM_VECTOR_LEN;
403
+ const ptr3 = passStringToWasm0(terms, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
404
+ const len3 = WASM_VECTOR_LEN;
405
+ wasm.wasmidentity_signContractV2(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3);
406
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
407
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
408
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
409
+ if (r2) {
410
+ throw takeObject(r1);
411
+ }
412
+ return takeObject(r0);
413
+ } finally {
414
+ wasm.__wbindgen_add_to_stack_pointer(16);
415
+ }
416
+ }
417
+ /**
418
+ * A guard's daily summary of a lent key (SPEC agent egress §7.4): the chain's root and length for `day`.
419
+ * @param {string} secret_id
420
+ * @param {string} day
421
+ * @param {string} root_hex
422
+ * @param {bigint} n
423
+ * @returns {Uint8Array}
424
+ */
425
+ signSummary(secret_id, day, root_hex, n) {
426
+ try {
427
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
428
+ const ptr0 = passStringToWasm0(secret_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
429
+ const len0 = WASM_VECTOR_LEN;
430
+ const ptr1 = passStringToWasm0(day, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
431
+ const len1 = WASM_VECTOR_LEN;
432
+ const ptr2 = passStringToWasm0(root_hex, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
433
+ const len2 = WASM_VECTOR_LEN;
434
+ wasm.wasmidentity_signSummary(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, n);
435
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
436
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
437
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
438
+ if (r2) {
439
+ throw takeObject(r1);
440
+ }
441
+ return takeObject(r0);
442
+ } finally {
443
+ wasm.__wbindgen_add_to_stack_pointer(16);
444
+ }
445
+ }
446
+ /**
447
+ * A person's sign-in from a device (Д5 §3.2): the user proof for a 16-byte user id and the server's challenge, as
448
+ * sealfs signs it — the SEAL Pro CLI's key session (AUDIT K227).
449
+ * @param {Uint8Array} user_id
450
+ * @param {Uint8Array} nonce
451
+ * @returns {Uint8Array}
452
+ */
453
+ userProof(user_id, nonce) {
454
+ try {
455
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
456
+ const ptr0 = passArray8ToWasm0(user_id, wasm.__wbindgen_export3);
457
+ const len0 = WASM_VECTOR_LEN;
458
+ const ptr1 = passArray8ToWasm0(nonce, wasm.__wbindgen_export3);
459
+ const len1 = WASM_VECTOR_LEN;
460
+ wasm.wasmidentity_userProof(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);
461
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
462
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
463
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
464
+ if (r2) {
465
+ throw takeObject(r1);
466
+ }
467
+ return takeObject(r0);
468
+ } finally {
469
+ wasm.__wbindgen_add_to_stack_pointer(16);
470
+ }
471
+ }
472
+ /**
473
+ * The eight words of the address.
257
474
  * @returns {string}
258
475
  */
259
476
  words() {
@@ -302,6 +519,37 @@ if (Symbol.dispose) WasmIdentity.prototype[Symbol.dispose] = WasmIdentity.protot
302
519
  function init() {
303
520
  wasm.init();
304
521
  }
522
+ function wasm_approval_message(ask, decision, at) {
523
+ let deferred5_0;
524
+ let deferred5_1;
525
+ try {
526
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
527
+ const ptr0 = passStringToWasm0(ask, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
528
+ const len0 = WASM_VECTOR_LEN;
529
+ const ptr1 = passStringToWasm0(decision, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
530
+ const len1 = WASM_VECTOR_LEN;
531
+ const ptr2 = passStringToWasm0(at, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
532
+ const len2 = WASM_VECTOR_LEN;
533
+ wasm.wasm_approval_message(retptr, ptr0, len0, ptr1, len1, ptr2, len2);
534
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
535
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
536
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
537
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
538
+ var ptr4 = r0;
539
+ var len4 = r1;
540
+ if (r3) {
541
+ ptr4 = 0;
542
+ len4 = 0;
543
+ throw takeObject(r2);
544
+ }
545
+ deferred5_0 = ptr4;
546
+ deferred5_1 = len4;
547
+ return getStringFromWasm0(ptr4, len4);
548
+ } finally {
549
+ wasm.__wbindgen_add_to_stack_pointer(16);
550
+ wasm.__wbindgen_export2(deferred5_0, deferred5_1, 1);
551
+ }
552
+ }
305
553
  function wasm_bundle_address(packed) {
306
554
  try {
307
555
  const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
@@ -358,6 +606,39 @@ function wasm_contract_message(org_id, request_id, doc_hash) {
358
606
  wasm.__wbindgen_export2(deferred5_0, deferred5_1, 1);
359
607
  }
360
608
  }
609
+ function wasm_contract_message_v2(org_id, request_id, doc_hash, terms) {
610
+ let deferred6_0;
611
+ let deferred6_1;
612
+ try {
613
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
614
+ const ptr0 = passStringToWasm0(org_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
615
+ const len0 = WASM_VECTOR_LEN;
616
+ const ptr1 = passStringToWasm0(request_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
617
+ const len1 = WASM_VECTOR_LEN;
618
+ const ptr2 = passStringToWasm0(doc_hash, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
619
+ const len2 = WASM_VECTOR_LEN;
620
+ const ptr3 = passStringToWasm0(terms, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
621
+ const len3 = WASM_VECTOR_LEN;
622
+ wasm.wasm_contract_message_v2(retptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3);
623
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
624
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
625
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
626
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
627
+ var ptr5 = r0;
628
+ var len5 = r1;
629
+ if (r3) {
630
+ ptr5 = 0;
631
+ len5 = 0;
632
+ throw takeObject(r2);
633
+ }
634
+ deferred6_0 = ptr5;
635
+ deferred6_1 = len5;
636
+ return getStringFromWasm0(ptr5, len5);
637
+ } finally {
638
+ wasm.__wbindgen_add_to_stack_pointer(16);
639
+ wasm.__wbindgen_export2(deferred6_0, deferred6_1, 1);
640
+ }
641
+ }
361
642
  function wasm_ed25519_verify(public_key, message, signature) {
362
643
  const ptr0 = passArray8ToWasm0(public_key, wasm.__wbindgen_export3);
363
644
  const len0 = WASM_VECTOR_LEN;
@@ -414,6 +695,37 @@ function wasm_sealbox_wrap(key_to_wrap, packed_bundle, scope_type, scope_id) {
414
695
  wasm.__wbindgen_add_to_stack_pointer(16);
415
696
  }
416
697
  }
698
+ function wasm_summary_message(secret_id, day, root_hex, n) {
699
+ let deferred5_0;
700
+ let deferred5_1;
701
+ try {
702
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
703
+ const ptr0 = passStringToWasm0(secret_id, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
704
+ const len0 = WASM_VECTOR_LEN;
705
+ const ptr1 = passStringToWasm0(day, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
706
+ const len1 = WASM_VECTOR_LEN;
707
+ const ptr2 = passStringToWasm0(root_hex, wasm.__wbindgen_export3, wasm.__wbindgen_export4);
708
+ const len2 = WASM_VECTOR_LEN;
709
+ wasm.wasm_summary_message(retptr, ptr0, len0, ptr1, len1, ptr2, len2, n);
710
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
711
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
712
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
713
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
714
+ var ptr4 = r0;
715
+ var len4 = r1;
716
+ if (r3) {
717
+ ptr4 = 0;
718
+ len4 = 0;
719
+ throw takeObject(r2);
720
+ }
721
+ deferred5_0 = ptr4;
722
+ deferred5_1 = len4;
723
+ return getStringFromWasm0(ptr4, len4);
724
+ } finally {
725
+ wasm.__wbindgen_add_to_stack_pointer(16);
726
+ wasm.__wbindgen_export2(deferred5_0, deferred5_1, 1);
727
+ }
728
+ }
417
729
  function wasm_unwrap_file_key(packed_envelope, seal_key, seal_id, file_id) {
418
730
  try {
419
731
  const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
@@ -613,6 +925,9 @@ function __wbg_get_imports() {
613
925
  "./seal_crypto_bg.js": import0
614
926
  };
615
927
  }
928
+ var ContractTermsBuilderFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
929
+ }, unregister: () => {
930
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_contracttermsbuilder_free(ptr, 1));
616
931
  var WasmIdentityFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
617
932
  }, unregister: () => {
618
933
  } } : new FinalizationRegistry((ptr) => wasm.__wbg_wasmidentity_free(ptr, 1));
@@ -821,9 +1136,12 @@ function configureWasm(next) {
821
1136
  }
822
1137
  source = next;
823
1138
  }
1139
+ function isWorker() {
1140
+ return globalThis.navigator?.userAgent === "Cloudflare-Workers";
1141
+ }
824
1142
  function isNode() {
825
1143
  const p = globalThis.process;
826
- return typeof p?.versions?.node === "string";
1144
+ return typeof p?.versions?.node === "string" && !isWorker();
827
1145
  }
828
1146
  async function readNodeFile(path) {
829
1147
  const fsModule = "node:fs/promises";
@@ -835,6 +1153,9 @@ async function readNodeFile(path) {
835
1153
  return readFile(path);
836
1154
  }
837
1155
  async function wasmInput() {
1156
+ if (source && "module" in source) {
1157
+ return source.module;
1158
+ }
838
1159
  if (source && "url" in source) {
839
1160
  return fetch(source.url, source.integrity ? { integrity: source.integrity } : {});
840
1161
  }
@@ -845,7 +1166,7 @@ async function wasmInput() {
845
1166
  return readNodeFile(new URL(WASM_FILE, importMetaUrl));
846
1167
  }
847
1168
  throw new Error(
848
- "sealnet: no WASM source in this browser (a broken build — reinstall sealnet)"
1169
+ isWorker() ? "seal crypto core: a Worker compiles no WASM from bytes \u2014 call configureWasm({ module }) with the imported .wasm" : "sealnet: no WASM source in this browser (a broken build — reinstall sealnet)"
849
1170
  );
850
1171
  }
851
1172
  async function ensureWasm() {
@@ -867,18 +1188,6 @@ async function ensureWasm() {
867
1188
  throw error;
868
1189
  }
869
1190
  }
870
- async function sha256(data) {
871
- const buffer = data.buffer.slice(
872
- data.byteOffset,
873
- data.byteOffset + data.byteLength
874
- );
875
- const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
876
- return new Uint8Array(hashBuffer);
877
- }
878
- async function sha256Hex(data) {
879
- const hashBytes = await sha256(data);
880
- return Array.from(hashBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
881
- }
882
1191
  var BASE64_CHUNK_SIZE = 32768;
883
1192
  var Base64DecodeError = class extends Error {
884
1193
  constructor(message, input) {
@@ -903,7 +1212,7 @@ function binaryStringToBytes(binary) {
903
1212
  return bytes;
904
1213
  }
905
1214
  function safeAtob(base64) {
906
- const preview = base64.substring(0, 20) + (base64.length > 20 ? "..." : "");
1215
+ const preview = `${base64.length} characters`;
907
1216
  if (typeof atob !== "undefined") {
908
1217
  try {
909
1218
  return atob(base64);
@@ -944,6 +1253,18 @@ function base64ToBytes(base64) {
944
1253
  function base64urlToBytes(base64url) {
945
1254
  return base64ToBytes(base64urlToBase64(base64url));
946
1255
  }
1256
+ async function sha256(data) {
1257
+ const buffer = data.buffer.slice(
1258
+ data.byteOffset,
1259
+ data.byteOffset + data.byteLength
1260
+ );
1261
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
1262
+ return new Uint8Array(hashBuffer);
1263
+ }
1264
+ async function sha256Hex(data) {
1265
+ const hashBytes = await sha256(data);
1266
+ return Array.from(hashBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1267
+ }
947
1268
 
948
1269
  var import_sha2 = require("@noble/hashes/sha2");
949
1270
  var import_fflate = require("fflate");
@@ -991,8 +1312,8 @@ var FILE_ID = aeon_format_default.header_layout.find((field) => field.name === "
991
1312
  var AAD_LENGTH = aeon_format_default.aad_layout.reduce((sum, field) => sum + field.length, 0);
992
1313
  var V3_MAGIC = new Uint8Array(aeon_format_default.v3_reader.magic_bytes);
993
1314
  var V3_HEADER_LENGTH = aeon_format_default.v3_reader.header_length;
994
- function encryptedSegmentSize(plaintextSize) {
995
- return NONCE_LENGTH + plaintextSize + TAG_LENGTH;
1315
+ function encryptedSegmentSize(plaintextSize2) {
1316
+ return NONCE_LENGTH + plaintextSize2 + TAG_LENGTH;
996
1317
  }
997
1318
  function ciphertextSize(plaintextLen) {
998
1319
  const segments = Math.max(1, Math.ceil(plaintextLen / SEGMENT_SIZE));
@@ -1045,7 +1366,12 @@ function toArrayBuffer(bytes) {
1045
1366
  return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1046
1367
  }
1047
1368
  function importSegmentKey(key2) {
1048
- return crypto.subtle.importKey("raw", toArrayBuffer(key2), { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
1369
+ const copy = toArrayBuffer(key2);
1370
+ try {
1371
+ return crypto.subtle.importKey("raw", copy, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
1372
+ } finally {
1373
+ new Uint8Array(copy).fill(0);
1374
+ }
1049
1375
  }
1050
1376
  async function encryptSegment(key2, plaintext, aad) {
1051
1377
  const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
@@ -1135,7 +1461,7 @@ var limits_default = {
1135
1461
  description: "One-time payment for 500 GB storage and 12 months TTL"
1136
1462
  }
1137
1463
  },
1138
- PRO_REGIONS: ["eu-west", "us-east", "us-west", "apac-southeast", "apac-northeast"],
1464
+ PRO_REGIONS: ["eu-west", "eu-central", "us-east", "us-west", "apac-southeast", "apac-northeast"],
1139
1465
  ttl_options: ["5m", "30m", "1h", "1d", "7d"],
1140
1466
  OTP_LENGTH: { min: 6, max: 10 },
1141
1467
  USER_PASSWORD_MIN_LENGTH: 8,
@@ -1145,6 +1471,13 @@ var limits_default = {
1145
1471
  PAYMENT_WAIT_MAX_SECONDS: 82800,
1146
1472
  ADDRESS_PROOF_TTL_SECONDS: 300,
1147
1473
  INBOX_MAX_ITEMS: 200,
1474
+ LEASE_DEFAULT_DAYS: 7,
1475
+ LEASE_MAX_DAYS: 90,
1476
+ LEASE_STATUS_BATCH_MAX: 500,
1477
+ LEASE_POLL_SECONDS: 600,
1478
+ LEASE_KEEP_DAYS: 30,
1479
+ APPROVE_WAIT_SECONDS: 120,
1480
+ APPROVE_BODY_SHOWN_BYTES: 2048,
1148
1481
  DRIVE_OPEN_TTL_SECONDS: 300,
1149
1482
  DRIVE_PRESIGN_WINDOW_DEFAULT_BYTES: 67108864,
1150
1483
  DRIVE_PRESIGN_WINDOW_MIN_BYTES: 8388608,
@@ -1163,26 +1496,217 @@ var limits_default = {
1163
1496
  SENSOR_GROWTH_BYTES_PER_DAY_DEFAULT: 107374182400
1164
1497
  }
1165
1498
  };
1166
- var seal_address_default = {
1167
- version: 2,
1168
- $comment: "Address of a bundle: who a seal is for, without a URL (SPEC-AEON-V4 \xA75). Numbers live in limits.json, error codes in error_codes.json, the bundle and the wrap in crypto.json (keybundle, sealed_box_v2).",
1169
- address: {
1170
- of: "SHA-256 of the identity key (Ed25519) of the bundle v2, 32 bytes",
1171
- text: "base64url without padding, 43 characters",
1172
- words: "fingerprint_words.json over the first three bytes of the address: the words of SHA-256(identity key), named without hashing again",
1173
- inbox: "the 32 bytes of the address are the key the server finds an inbox by"
1174
- },
1175
- box_origin: "https://box.seal.net",
1176
- seed: {
1177
- env: "SEAL_SEED",
1178
- text: "base64url without padding of the 32-byte seed of an agent, a device or an inbox, 43 characters",
1179
- derives: "the agreement key (X25519) is the seed itself; the identity key (Ed25519) and the ML-KEM-768 key are HKDF of the seed (crypto.json hkdf.identity_key_salt, info_prefixes workload_identity and kem_mlkem768) \u2014 together the bundle v2 the address names",
1180
- same_as: [
1181
- "sealnet-mcp state.identity.x25519_secret_b64",
1182
- "seal identity.v1.json x25519_secret_b64url",
1183
- "sealnet (npm) KeyPair.secretKey",
1499
+ var crypto_default = {
1500
+ version: 1,
1501
+ default_aead: "aes_256_gcm",
1502
+ aes_gcm: {
1503
+ key_length_bytes: 32,
1504
+ nonce_length_bytes: 12,
1505
+ tag_length_bytes: 16
1506
+ },
1507
+ sha256: {
1508
+ output_length_bytes: 32,
1509
+ hex_string_length: 64
1510
+ },
1511
+ owner_token_bytes: 32,
1512
+ link_key_bytes: 32,
1513
+ metadata_aad_prefix: "field:",
1514
+ keybundle: {
1515
+ signature_prefix: "seal:keybundle:",
1516
+ signed_bundle_version: 2,
1517
+ v2_fields: ["identity_ed25519_pub", "agreement_x25519_pub", "kem_mlkem768_pub"],
1518
+ packed_length: 1316,
1519
+ address: {
1520
+ of: "sha256(identity_ed25519_pub), 32 bytes",
1521
+ text: "base64url without padding, 43 characters",
1522
+ words: "fingerprint_words.json over its first eight bytes"
1523
+ }
1524
+ },
1525
+ hkdf: {
1526
+ wrap_key_salt: "seal:wrapkey:v1",
1527
+ wrap_key_salt_v2: "seal:wrapkey:v2",
1528
+ identity_key_salt: "seal:key-derivation:v1",
1529
+ file_envelope_salt: "seal:file-envelope:v1",
1530
+ info_prefixes: {
1531
+ wrap: "WRAP",
1532
+ agreement: "AGRE",
1533
+ identity: "IDEN",
1534
+ workload_identity: "seal:workload-identity:v1",
1535
+ share_proof: "seal:share-proof:v1",
1536
+ kem_mlkem768: "seal:kem-mlkem768:v1"
1537
+ }
1538
+ },
1539
+ share_link: {
1540
+ proof_of: "the proof of a share link's key (AUDIT K237): HKDF-SHA256(ikm = the link's 32-byte key, salt = hkdf.identity_key_salt, info = hkdf.info_prefixes.share_proof, 32 bytes), base64url; its maker gives the server proof_hash = SHA-256 hex of those bytes, an opener sends the proof in proof_header",
1541
+ proof_header: "X-Share-Proof",
1542
+ proof_vector: { link_key: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8", proof: "xYwpyfG6o6iW43T5O7W9Av5bVZJc5MpUhcmPa6SxQy8", proof_hash: "75d668b6b3295aad0b8e3f83eb9d03181a9c81f92836105077023bf3bea0aa4a" }
1543
+ },
1544
+ xwing: { label_hex: "5c2e2f2f5e5c" },
1545
+ sealed_box_v2: {
1546
+ version_byte: 2,
1547
+ packed_layout: [
1548
+ { name: "version", offset: 0, length: 1 },
1549
+ { name: "eph_pub", offset: 1, length: 32 },
1550
+ { name: "kem_ct", offset: 33, length: 1088 },
1551
+ { name: "nonce", offset: 1121, length: 12 },
1552
+ { name: "ct", offset: 1133, length: 48 }
1553
+ ],
1554
+ packed_length: 1181,
1555
+ packed_b64_length: 1575
1556
+ },
1557
+ secret_scope_aad: "secret:{secret_id}",
1558
+ scope_metadata_aad: {
1559
+ is: "What a sealed text of a scope's metadata is bound to: the AAD of its AES-256-GCM (SEAL Pro, AUDIT K140, SPEC-NAMES-BOUND). A room's name and description are bound to the room. A text under the organization's key and the name of a seal's folder are bound to their own object: its id stands in the AAD, so two of them cannot be swapped unnoticed. The binding before that named the kind and the organization (the seal) only; a row says which one its text has by `encryption_version`, a seal's folder has no such mark and is read bound first, then as before.",
1560
+ room: "room:{room_id}:{field}",
1561
+ org_object: {
1562
+ bound: "{kind}:{org_id}:{object_id}:{field}",
1563
+ before: "{kind}:{org_id}:{field}",
1564
+ kinds: [
1565
+ "secret",
1566
+ "sign-policy",
1567
+ "sign-template",
1568
+ "sign-template-body",
1569
+ "sign-template-meta",
1570
+ "sign-folder",
1571
+ "sign-request-meta",
1572
+ "sign-field-value"
1573
+ ],
1574
+ field: "name",
1575
+ object: "the row the text belongs to: the secret, the policy, the template (its name, text and terms alike), the contract folder, the sign request, the signature field of a drawing"
1576
+ },
1577
+ folder: {
1578
+ bound: "seal:{seal_id}:{folder_id}:name",
1579
+ before: "seal:{seal_id}:name"
1580
+ },
1581
+ versions: {
1582
+ before: 3,
1583
+ bound: 5,
1584
+ note: "4 is a file's format version (seal_files) and names no metadata"
1585
+ },
1586
+ vectors: {
1587
+ key_hex: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
1588
+ nonce_b64: "ZGVmZ2hpamtsbW5v",
1589
+ org_object: {
1590
+ kind: "secret",
1591
+ org_id: "0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e",
1592
+ object_id: "7a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
1593
+ other_object_id: "11111111-2222-4333-8444-555555555555",
1594
+ text: "prod-db",
1595
+ bound_aad: "secret:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:7a1d2c3b-4e5f-4a6b-8c7d-9e0f1a2b3c4d:name",
1596
+ bound_b64: "OGmxAlSNNC/EcAW6hlU6eU73XrC7Vaw=",
1597
+ before_aad: "secret:0b9f4c1e-6f0a-4c56-9d0e-2f1c3a4b5d6e:name",
1598
+ before_b64: "OGmxAlSNNBiKlnxW4fkbPMjFoZGJJDY="
1599
+ },
1600
+ folder: {
1601
+ seal_id: "AbCd1234",
1602
+ folder_id: "c0ffee00-1234-4abc-8def-0123456789ab",
1603
+ other_folder_id: "11111111-2222-4333-8444-555555555555",
1604
+ text: "\u0414\u043E\u0433\u043E\u0432\u043E\u0440\u044B 2026",
1605
+ bound_aad: "seal:AbCd1234:c0ffee00-1234-4abc-8def-0123456789ab:name",
1606
+ bound_b64: "mI8O2KlahiDu0I9WC+W7dmLwNji94CvUmMxJnLVFN5EChD6uMg==",
1607
+ before_aad: "seal:AbCd1234:name",
1608
+ before_b64: "mI8O2KlahiDu0I9WC+W7dmLwNji9ni0vIvgReyNDk0uY98XR7Q=="
1609
+ }
1610
+ }
1611
+ },
1612
+ sign: {
1613
+ message_prefix: "aeon:sign:v1",
1614
+ message_format: "aeon:sign:v1|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}",
1615
+ message_prefix_v2: "aeon:sign:v2",
1616
+ message_format_v2: "aeon:sign:v2|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}|terms:{terms_hex}",
1617
+ terms_label: "aeon:terms:v1",
1618
+ terms_of: "what the signer was shown (AUDIT K204): SHA-256 hex of the lines the core builds (shared/core/src/contract_terms.rs) \u2014 for a member of the organization or its agent from the metadata ciphertext and the whole field layout, for an outside signer from their own fields alone and no metadata \u2014 and the signer's own filled fields",
1619
+ terms_vector: {
1620
+ org_id: "0d0f2a1e-5b7c-4c1d-9e3a-2f6b8c4d1a70",
1621
+ request_id: "7a1c3e5b-9d2f-4b6a-8c0e-1f3a5b7d9c2e",
1622
+ doc_hash: "cb99e3fc33b873e56252762ef641f21153fb14f66fb1d8bbf82d2033dcb31d33",
1623
+ meta: "bWV0YS1jaXBoZXJ0ZXh0",
1624
+ fields: [
1625
+ {
1626
+ id: "b2f1c3d4-0000-4000-8000-000000000002",
1627
+ type: "signature",
1628
+ page: 2,
1629
+ x: 0.615,
1630
+ y: 0.8125,
1631
+ w: 0.3,
1632
+ h: 0.075,
1633
+ assignee_type: "email",
1634
+ assignee: "ann|example@example.com",
1635
+ required: true
1636
+ },
1637
+ {
1638
+ id: "a1e0b2c3-0000-4000-8000-000000000001",
1639
+ type: "signature",
1640
+ page: 1,
1641
+ x: 0.1,
1642
+ y: 0.7,
1643
+ w: 0.3,
1644
+ h: 0.075,
1645
+ assignee_type: "user",
1646
+ assignee: "5c9e7a3b-1d2f-4a6b-8c0d-2e4f6a8b0c1d",
1647
+ required: true
1648
+ }
1649
+ ],
1650
+ filled: [
1651
+ {
1652
+ field_id: "a1e0b2c3-0000-4000-8000-000000000001",
1653
+ sha256: "bde5c9647a96e96c78ea116eaa7a653b2347cd83855d223b30984f235151f813"
1654
+ }
1655
+ ],
1656
+ terms: "a38d4d567232eb54cb8c2276988b1a4d0b31dc763b6dadcc6b33909d1b844f30",
1657
+ message: "aeon:sign:v2|org:0d0f2a1e-5b7c-4c1d-9e3a-2f6b8c4d1a70|req:7a1c3e5b-9d2f-4b6a-8c0e-1f3a5b7d9c2e|doc_hash:cb99e3fc33b873e56252762ef641f21153fb14f66fb1d8bbf82d2033dcb31d33|terms:a38d4d567232eb54cb8c2276988b1a4d0b31dc763b6dadcc6b33909d1b844f30"
1658
+ }
1659
+ },
1660
+ sign_doc_hash_of: "sha256(plaintext) of the exact seal_files row in doc_ref",
1661
+ recovery_phrase: {
1662
+ seed: `BIP39: PBKDF2-HMAC-SHA512 of the phrase after trim, lower case and NFKD, salt "mnemonic", 2048 iterations, 64 bytes; the web's recoveryPhrase.ts phraseToMasterSeed and the core's hkdf::master_seed_from_phrase (\u04145 \xA73.2)`,
1663
+ vector: {
1664
+ phrase: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
1665
+ typed: " Abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon ART\n",
1666
+ seed_hex: "408b285c123836004f4b8842c89324c1f01382450c0d439af345ba7fc49acf705489c6fc77dbd4e3dc1dd8cc6bc9f043db8ada1e243c4a0eafb290d399480840"
1667
+ }
1668
+ },
1669
+ device_link: {
1670
+ record: "a person's seed64, base64url, sealed by the browser to the one-time bundle of sealfs login: sealReply(seed64, bundle, scope, code) of the protocol's identity module \u2014 box (sealed_box_v2) \u2016 nonce(12) \u2016 AES-256-GCM of the record under the box's key; the daemon opens it with its one-time identity (\u04145 \xA73.2 \u043F. 2, D119)",
1671
+ scope: "device",
1672
+ vector: {
1673
+ daemon_seed64_hex: "01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3ba",
1674
+ code: "K7M2Q9XA",
1675
+ seed64_hex: "030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bc",
1676
+ record: "AlbSFUYf2V9yux_9DyViIEw_gXJcdITRt0kFjJC9XAJTOCRSKh3_hDCGxBSS5idHldzc_qQOtd43_GYaZQm9_VH90eY2JDP_A2T4I8W_qPPfS4MlLGtBp0kkShY_PnspF6bELAbft3XNkEuwQpfynXH2OFFvAPwJFKceua18YAywNbq84plsv8n3C5lRmeITyeFwKlxDW3-6q-2NHlAgkSrScie1B63CQu3D0U3SRWcOHMvwnl9Topwe1J2iu4EpOUlJRZQsgfBR4LhyywAWam0R3VHa_pXjCtN4Of-JRyO3Jub-6MgDXpoGsQuD9V1XszngRZkwz0R_4xqSlabtA-GMiCJyhff7HBp3t0XHeaS04cNdtATfwce_FUL3IL-z0YAQh-JSzKz_VeVq8iFSZcbHnx2Eab3ND4YuwvJxfJJ8jGquahnhndiI6qxZtK7OmQsy8ZBQ_p4Gi8v1ziN74OMdQG9UtqR9igeJohiMos5tHpveIXQ9luWiQ9gk22p53yGzP8hH_mv508tb4KsveNjssXS0hVmLl4c7fqQbrBjKvNauuEbzNd1gimV4I_f-N0FN2c7Pe7sTZevR5dnIGrAF_31cxFTOWVjZdKsyEWUiwSHrG2dQBccO2AB6TurTsqr4hBP64c3WkUW1vJVXKEOCKxBIwMa7XyyLw4La5tZue0Ls2cHzfy2Kd5jKCo3UIQrjvNWOvXFDRlkTx10UMFpZNvmnITHVh6rHkr5_tGFVMwqU2arRmwQBWCBYsDhN1NVJ8cEwEb0lNHfuotqf54IZUP25JwqpqSkSadjHdVHZdJ50MQUiNiumm0e-kbLDfWHds9dkGhwVgqha3s-svngKweowybgYAnRIDYeHHkSN-9Bm2jNmidilQhTiY6eLmnxg81sdESUNrjk1nhNJdiTaDAeX-CL5DJxPVirKFWYgrBpvJ7ocpxg9Idqsdm8fIzZi-MAQyq_I1y2RcsUqZEwFFeHqwPZdUce1PxVBjFn27cfKzyifotbTBumodLXMRnrrhfQ2i6cHAt9utI2X_WJuGxDRfYICuKdQHt3NPswIwLxSxgNUvpani5DzhYA5FnC-zfh_LWXyJnyfJx1Yr-07_ICpIP85fwzO7FAVZxpdpsL8wk19HhW63LAOVcQxANLcIue7hp1vU6QU1Co0H4yGJgmehDEBYWFJCpaDk8_srkw42Y9eZn6SNoIekuz-BNgjnnB0WB2mh-k3vux92C-_2o8GsSeENNvOOTRwLOLAB4PCi-Uf__oonrLR0kBdE2gbrVjb6sttEx8Df_S7YuTCytpw13ABaXCcJRsPfR6os2KuM1Rv53CH5SZ2NpKgdFlBmva9gIsMSJxAh08UtLGNhKrli3uUW1KER7Ng92RDDV-HHUqNyOhkPPD4KteeZHX0m9h8POVCjXr0TNHSisQK_CPFMMOhUc2DmEHDOZO9piI5uMAznMdzrR-qFbhPNN9ugUUSIdDnVS9Mc2INiUIKjnLWB37_wYTSpXRCS5bSfohMPyNu0dTuAJuHLNfK1hA9XOGhvZLFW9rgXN8bYdAmUL0TrJJ4DYBWrpzXuzaiXEf2peRi0z6LYiXWyjvmIaQfvttTgWSymbREbJmanBDfTUPR5XPFQHZ-n_876ODCoJAXnqOkSSWEHKf885bOre3IkJIS_2jH9_MJzG0Fsmnvj8VYHECIrZlRFdsqzMQ9MIIIIWg0bfHvAn5R06o"
1677
+ }
1678
+ }
1679
+ };
1680
+ var seal_address_default = {
1681
+ version: 2,
1682
+ $comment: "Address of a bundle: who a seal is for, without a URL (SPEC-AEON-V4 \xA75). Numbers live in limits.json, error codes in error_codes.json, the bundle and the wrap in crypto.json (keybundle, sealed_box_v2).",
1683
+ address: {
1684
+ of: "SHA-256 of the identity key (Ed25519) of the bundle v2, 32 bytes",
1685
+ text: "base64url without padding, 43 characters",
1686
+ words: "fingerprint_words.json over the first eight bytes of the address: the words of SHA-256(identity key), named without hashing again",
1687
+ inbox: "the 32 bytes of the address are the key the server finds an inbox by"
1688
+ },
1689
+ box_origin: "https://box.seal.net",
1690
+ seed: {
1691
+ env: "SEAL_SEED",
1692
+ text: "base64url without padding of the 64-byte seed of an agent, a device or an inbox, 86 characters",
1693
+ derives: "all three keys of the bundle v2 the address names are HKDF-SHA256 of the seed under crypto.json hkdf.identity_key_salt, each under its own info: hkdf.info_prefixes identity (Ed25519), agreement (X25519) and kem_mlkem768 (d \u2016 z of ML-KEM-768), followed by key_version as four bytes, little-endian \u2014 the core's Identity::from_seed. No public key of the bundle is the seed",
1694
+ key_version: 1,
1695
+ same_as: [
1696
+ "sealnet-mcp state.identity.seed_b64",
1697
+ "seal identity.v1.json seed_b64url",
1698
+ "sealnet (npm) KeyPair.secretKey",
1184
1699
  "sealnet (PyPI) keygen().secret_key"
1185
- ]
1700
+ ],
1701
+ root: "SPEC-SEED-ROOT: the one kind of seed. A seed of 32 bytes (43 characters) is a key of the kind before: a holder that keeps its seed itself reads it as its previous key (below) until that expires, and nothing makes it or takes it as a seed \u2014 SEAL_SEED, an inbox key file, a device transfer and an SDK key of that length are refused in words that say how to make a new one.",
1702
+ vector: {
1703
+ comment: "the seed of the vector `sealed-box-v2-person` of xwing_test_vectors.json (seed64_hex; its bundle, address and words are there) signs the challenge of ts into this proof \u2014 Identity::from_seed, Identity::inbox_proof; Ed25519 is deterministic, every client reproduces it",
1704
+ of: "sealed-box-v2-person",
1705
+ ts: 179e7,
1706
+ challenge: "wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8",
1707
+ proof: "1790000000.wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t8.1VKxaNHrNu5Is9gYxMur7mAABL8Pn0Lcz6vpw5JDmUI65epcxGCMUOGcJK-lneqALDx0EHlBHbhmUIHWPCCDCQ"
1708
+ },
1709
+ previous: "the seed a holder had before it replaced its key, 32 or 64 bytes, kept beside the current one where the holder keeps its seed itself (an inbox, a device's identity file, the MCP server's state): it opens what the server still holds at the old address and is erased when the last of that has expired \u2014 seven days from the replacement (limits.json ttl_options, the longest free seal), longer while the inbox shows a live row at the old address"
1186
1710
  },
1187
1711
  bundles: {
1188
1712
  put: "PUT /intake/bundles {bundle}: bundle is base64url of the packed bundle (crypto.json keybundle.packed_length). The server verifies it with the core and files it under the address it computes; no authorization \u2014 the bundle proves itself \u2014 and a limit per IP",
@@ -1217,14 +1741,20 @@ var seal_address_default = {
1217
1741
  listing: "GET /intake?to= lists deliveries only, as before owner copies and cards existed; `all=1` adds owner and request items (a person's inbox). Agent clients never send it: those rows are a person's."
1218
1742
  },
1219
1743
  request: {
1220
- recipient_bundle: "POST /intake carries recipient_bundle, base64url of the requester's packed bundle; the page verifies it and shows the three words of its address, the answer's key is wrapped to it (scope share_link) and comes back as the request's fragment, with share_path without a fragment"
1744
+ recipient_bundle: "POST /intake carries recipient_bundle, base64url of the requester's packed bundle; the page verifies it and shows the eight words of its address, the answer's key is wrapped to it (scope share_link) and comes back as the request's fragment, with share_path without a fragment"
1221
1745
  },
1222
1746
  owner_copy: {
1223
1747
  web_label: "seal.net",
1224
1748
  is: "The seal names the inbox that manages it: its row carries the owner-blob key wrapped to that address's bundle, one per seal, written with the owner blob (PATCH /seal/{id}/blob with to, fragment, label) before the first byte of the files. Best effort: an address without a bundle is the same PATCH without the address part, and the seal is made anyway."
1225
1749
  },
1226
- request_kinds: ["secret", "file", "any", "pair", "device"],
1750
+ request_kinds: ["secret", "file", "any", "pair", "device", "guard"],
1227
1751
  pair_what: "inbox",
1752
+ guard: {
1753
+ kind: "guard",
1754
+ is: "a pair request whose requester is this machine's guard (SPEC agent egress \xA73.1): the same answer as `pair` (the pairing file), and the inbox marks the agent as a guard. A request for a secret whose recipient_bundle is a guard's is shown by the inbox as sealed to that guard; one whose bundle is no known guard's is answered only after the person types its eight words (\xA76.1, T2\u0430).",
1755
+ gateway: "SPEC agent egress \xA77.2, level \u0412: `seal guard expose --listen <address:port> [--as <host:port>]` makes a guard the owner's gateway \u2014 `POST https://<host:port>/v1/forward` over mTLS, both certificates made from the guards' Ed25519 identity keys and checked against the published bundles of their addresses (the client names its address in `x-seal-address`, the server is the `gateway.guard` of the binding). `seal guard lend <key> --to <address>` lends a key as use: the borrower's guard receives a handle under a binding with `gateway: {at, guard}` (owner_blob_payload.v1.json bindings) and sends the request with `x-seal-method` and `x-seal-url` (the host's URL) to the gateway, which puts the value in and answers with the host's answer. The gateway not reachable: 502 `{error: seal_guard.gateway, reason: gateway_offline}`.",
1756
+ bind: "POST /intake may carry `bind`: what the agent proposes the key be bound to \u2014 {hosts: [<host>], place?: <place>, class?: outbound|inprocess} (secrets.json guard_note). `bind` is sent only when the recipient_bundle is a guard's, hosts proposed or not: its presence is what lets the page bind the key and lend it under a lease; without it the page says the value goes to the agent as it is. The page shows the proposal as the binding when no entry of secrets.json knows the key's form; the person confirms, narrows or removes it. At most 16 hosts of 253 characters, each a name of two labels or more (`*.` with two labels under it, three under secrets.json wildcard_public_second_level); the server checks the shape and keeps it as given."
1757
+ },
1228
1758
  payloads: {
1229
1759
  name_max: 80,
1230
1760
  pair: {
@@ -1233,19 +1763,43 @@ var seal_address_default = {
1233
1763
  },
1234
1764
  device: {
1235
1765
  mime: "application/vnd.seal.device+json",
1236
- json: '{"v":2,"seed":"<inbox seed, 43>","name":"<inbox name>","agents":[{"address":"<43>","name":"<name>","paired_at":"<ISO 8601>"}]}'
1766
+ json: '{"v":2,"seed":"<inbox seed, 86>","name":"<inbox name>","agents":[{"address":"<43>","name":"<name>","paired_at":"<ISO 8601>","kind":"guard"?}]}',
1767
+ kind: "`guard` for an agent that is a machine's guard (request kind `guard`): it stays a guard on every device of the inbox and through a rename; a reader drops a kind it does not know (SPEC-APP r5 \u041425)"
1768
+ },
1769
+ approve: {
1770
+ mime: "application/vnd.seal.approve+json",
1771
+ json: '{"v":2,"ask":"<16 random bytes, base64url>","secret_id":"<k_\u2026>","secret":"<STRIPE_KEY>","guard":"<eight words of the guard>","host":"api.stripe.com","method":"POST","path":"/v1/refunds?expand=charge","at":"<ISO 8601>","until":"<ISO 8601>","body_bytes":24,"body":"charge=ch_1&amount=50000"?,"body_sha256":"<SHA-256 hex of the whole body>"?,"body_more":true?}',
1772
+ body: "What the call carries (AUDIT K152): `path` is the path with its query; `body_bytes` the bytes of the body the guard read; `body` its first `limits.json::APPROVE_BODY_SHOWN_BYTES` bytes when they are text, cut where a character ends, absent for an empty or a binary body; `body_sha256` the digest of the whole body, absent for an empty one and for one that streams on past what the guard reads whole, which `body_more` says. An agent's request holds surrogates, never a value. A reader takes a question without these fields (a guard before them) and shows what it has.",
1773
+ is: "A guard's question to a key's owner (SPEC agent egress \xA77.3, \u04214): a call the binding marks `approve: owner` waits for this answer. Sent as a seal addressed to the owner (30 minutes, one open), its share blob marked `payload: approve`; the inbox shows it as a card with Allow and Deny and pushes. Unanswered within `limits.json::APPROVE_WAIT_SECONDS` the call is refused (403 `approve`)."
1774
+ },
1775
+ approve_answer: {
1776
+ mime: "application/vnd.seal.approve-answer+json",
1777
+ json: `{"v":2,"ask":"<the ask>","decision":"allow"|"deny","at":"<ISO 8601>","signature":"<Ed25519 by the inbox's identity key over the core's approval message, base64url, 86>"}`,
1778
+ is: "The owner's answer (\xA77.3): a seal from the inbox to the guard's address (30 minutes, one open), blob `payload: approve_answer`; the guard checks the signature against the owner's bundle (the `owner` of the binding). `allow` is for the one call the question was about (AUDIT K152): the same call again is another question."
1779
+ },
1780
+ summary: {
1781
+ mime: "application/vnd.seal.summary+json",
1782
+ json: `{"v":2,"secret_id":"<k_\u2026>","secret":"<STRIPE_KEY>","day":"<YYYY-MM-DD, UTC>","counts":[{"method":"GET","path":"/v1/charges/*","status":200,"n":40}],"approved":2,"refused":1,"root":"<SHA-256 hex, the chain's last link>","n":43,"signature":"<Ed25519 by the guard's identity key over the core's summary message, base64url, 86>"}`,
1783
+ is: "A guard's daily summary of one lent key to its owner (\xA77.4, \u04213): once a day by UTC and on a revoke, a seal addressed to the owner (7 days, one open), blob `payload: summary`. The inbox checks the signature against the guard's bundle (the item's sender), keeps the summary in its own storage (the carrier expires) and shows the journal under the lease. Attested by the guard that wrote the receipts: honest of an honest guard."
1784
+ },
1785
+ blob_payload: "A seal a machine makes for another machine or for an inbox carries the kind of its file in the share blob's `payload` (`approve`, `approve_answer`, `summary`, `delivery`), under the link key: the inbox reads the blob of every delivery and downloads only the files of these kinds; the server sees one more addressed seal. Readers tolerate a blob without the field.",
1786
+ delivery: {
1787
+ mime: "application/vnd.seal.delivery+json",
1788
+ json: `{"v":2,"name":"<the binding's name, STRIPE_KEY>","level":"A"|"B"|"0","at":"<ISO 8601>"}`,
1789
+ is: "The receipt of a lent key's arrival (SPEC agent egress \xA76.2, T17): whoever opens a secret whose binding names an `owner` sends this file, as a seal addressed to that owner (7d, one open), the moment the secret is opened. `A` or `B`: the opener's guard holds the key and the agent got a surrogate \u2014 the level is the one that guard names in its `status` (SPEC-APP r4 \u042038: `A` its key in a file of the user, `B` in the protected keychain of the SEAL app); `0`: the opener holds the value itself, the second level. The level travels inside the ciphertext; the server sees one more addressed seal. No receipt when the binding has no owner, or the owner is the opener itself."
1237
1790
  }
1238
1791
  },
1239
1792
  device_link: {
1240
- code: "8 Crockford base32 characters from 5 random bytes",
1793
+ code: "16 Crockford base32 characters from 10 random bytes (80 bits): the server sees the what beside the device's address, so the code must not be searchable from them (SPEC-r4 \u041A-4, AUDIT wpkg03.3)",
1241
1794
  what: "base64url(HMAC-SHA256(key = the code in ASCII, message = the 32-byte address of the new device)), 43 characters: the what of the device request",
1242
1795
  link: "https://box.seal.net/#link=<address>.<code>"
1243
1796
  },
1244
1797
  bridge: {
1245
1798
  path: "/bridge",
1246
- is: "A hidden iframe of box_origin on seal.net; postMessage only between the two origins. It never gives out the address or the name: it answers any script of seal.net.",
1799
+ is: "A hidden iframe of box_origin on seal.net; postMessage only between the two origins. It never gives out the address or the name for the asking: it answers any script of seal.net. The address goes back only with a lease the inbox kept (box.lease), to be sealed into the key's binding as its owner.",
1247
1800
  hello: "box.hello {sealId?} -> {box: boolean, has: boolean}; box: this device has an inbox; has: this seal is already in Yours",
1248
- owner_copy: "box.ownerCopy {sealId, ownerToken, linkKey} -> {ok: boolean}"
1801
+ owner_copy: "box.ownerCopy {sealId, ownerToken, linkKey} -> {ok: boolean}",
1802
+ lease: "box.lease {lease: {id, token, name, hosts, words, expires_at}} -> {ok: boolean, address?: string}; ok: the lease and its revoke token are in Sent; address: the inbox's address, the owner of the lent key (SPEC agent egress \xA77.3\u20137.5: the guard asks it for its word and sends it the daily summary)"
1249
1803
  },
1250
1804
  migrate: {
1251
1805
  until: "C1 + 7 days (C1 \xA76)",
@@ -1274,7 +1828,7 @@ var seal_address_default = {
1274
1828
  seed: "Aw4ZJC86RVBbZnF8h5KdqLO-ydTf6vUACxYhLDdCTVg",
1275
1829
  signature: "74s5T1rE2xRNbameeTbYUHVMN-ZzFu1JBPZJNtH8eYC1vV7-h2HE_hxgo4vUB0_sHFfdYRUf0bve4_KGe32ICg",
1276
1830
  ts: 179e7,
1277
- words: "album wren hedge"
1831
+ words: "album wren hedge kite tulip peach llama echo"
1278
1832
  }
1279
1833
  ]
1280
1834
  };
@@ -1316,129 +1870,454 @@ var upload_default = {
1316
1870
  PROGRESS_SPEED_WINDOW_MS: 2e4
1317
1871
  }
1318
1872
  };
1319
- var clientIdentity;
1320
- function setClientIdentity(name2, version) {
1321
- clientIdentity = `${name2}/${version}`;
1873
+ var hostFetch;
1874
+ function transportFetch(input, init2) {
1875
+ return (hostFetch ?? globalThis.fetch).call(globalThis, input, init2);
1322
1876
  }
1323
- function clientHeaders() {
1324
- return clientIdentity === void 0 ? {} : { [header]: clientIdentity };
1877
+ function hostNamedTransport() {
1878
+ return hostFetch !== void 0;
1325
1879
  }
1326
- var BackendError = class extends Error {
1327
- constructor(message, code, status, extra = {}) {
1328
- super(message);
1329
- this.name = "BackendError";
1330
- this.code = code;
1331
- this.status = status;
1332
- this.body = extra.body;
1333
- this.detail = extra.detail;
1334
- this.appCode = extra.appCode;
1335
- this.retryAfter = extra.retryAfter;
1336
- this.update = extra.update;
1337
- this.minVersion = extra.minVersion;
1880
+ var MAX_BODY_BYTES = 2 * 1024 * 1024;
1881
+ var API_ANSWER_TIMEOUT_MS = (limits_default.limits.INTAKE_WAIT_MAX_SECONDS + 15) * 1e3;
1882
+ var ADDRESS_HEADER = seal_address_default.proof.header_address;
1883
+ var PROOF_HEADER = seal_address_default.proof.header_proof;
1884
+ function isProduction() {
1885
+ try {
1886
+ return typeof process !== "undefined" && process.env?.NODE_ENV === "production";
1887
+ } catch {
1888
+ return false;
1338
1889
  }
1339
- };
1340
- function classifyStatus(status) {
1341
- if (status === 404) return "not_found";
1342
- if (status === 410) return "revoked";
1343
- if (status === 429) return "rate_limited";
1344
- if (status === 401 || status === 403) return "auth";
1345
- if (status >= 500 && status < 600) return "transient";
1346
- return "unknown";
1347
1890
  }
1348
- async function errorFromResponse(resp, fallback) {
1349
- const body = await resp.text().catch(() => "");
1350
- let detail;
1351
- let appCode;
1352
- let retryAfter;
1353
- let update;
1354
- let minVersion;
1355
- if (body) {
1356
- try {
1357
- const parsed = JSON.parse(body);
1358
- if (typeof parsed?.detail === "string") detail = parsed.detail;
1359
- if (typeof parsed?.code === "string") appCode = parsed.code;
1360
- if (typeof parsed?.retry_after === "number") retryAfter = parsed.retry_after;
1361
- if (typeof parsed?.update === "string") update = parsed.update;
1362
- if (typeof parsed?.min_version === "string") minVersion = parsed.min_version;
1363
- } catch {
1364
- }
1891
+ var defaultLogHandler = (level2, module2, message, ...args) => {
1892
+ const formatted = `[${module2}] ${message}`;
1893
+ switch (level2) {
1894
+ case "debug":
1895
+ if (!isProduction()) {
1896
+ console.debug(formatted, ...args);
1897
+ }
1898
+ break;
1899
+ case "info":
1900
+ console.info(formatted, ...args);
1901
+ break;
1902
+ case "warn":
1903
+ console.warn(formatted, ...args);
1904
+ break;
1905
+ case "error":
1906
+ console.error(formatted, ...args);
1907
+ break;
1365
1908
  }
1366
- return new BackendError(detail ?? fallback, classifyStatus(resp.status), resp.status, {
1367
- body: body || void 0,
1368
- detail,
1369
- appCode,
1370
- retryAfter,
1371
- update,
1372
- minVersion
1373
- });
1374
- }
1375
- function toSealMetadata(wire) {
1909
+ };
1910
+ var currentHandler = defaultLogHandler;
1911
+ function createLogger(module2) {
1376
1912
  return {
1377
- id: wire.id,
1378
- expiresAt: wire.expires_at,
1379
- revokedAt: wire.revoked_at,
1380
- ndaRequired: wire.nda_required,
1381
- otpRequired: wire.otp_required,
1382
- singleUse: wire.single_use,
1383
- maxOpens: wire.max_opens ?? null,
1384
- files: (wire.files ?? []).map((f) => ({
1385
- id: f.id,
1386
- size: f.size,
1387
- sha256_hex: f.sha256_hex,
1388
- name_encrypted: f.name_encrypted,
1389
- name_nonce: f.name_nonce,
1390
- mime_encrypted: f.mime_encrypted,
1391
- mime_nonce: f.mime_nonce
1392
- }))
1913
+ debug: (message, ...args) => currentHandler("debug", module2, message, ...args),
1914
+ info: (message, ...args) => currentHandler("info", module2, message, ...args),
1915
+ warn: (message, ...args) => currentHandler("warn", module2, message, ...args),
1916
+ error: (message, ...args) => currentHandler("error", module2, message, ...args)
1393
1917
  };
1394
1918
  }
1395
- function encode(segment) {
1396
- return encodeURIComponent(segment);
1919
+ var UploadError = class extends Error {
1920
+ constructor(message, code, httpStatus, partNumber, retryable = false) {
1921
+ super(message);
1922
+ this.code = code;
1923
+ this.httpStatus = httpStatus;
1924
+ this.partNumber = partNumber;
1925
+ this.retryable = retryable;
1926
+ this.name = "UploadError";
1927
+ }
1928
+ };
1929
+ function attachSession(err, session) {
1930
+ Object.defineProperty(err, "session", { value: session, enumerable: false, configurable: true, writable: true });
1931
+ return err;
1397
1932
  }
1398
- var SealApi = class _SealApi {
1399
- constructor(options) {
1400
- this.baseUrl = options.baseUrl.replace(/\/+$/, "");
1401
- if (typeof (options.fetch ?? globalThis.fetch) !== "function") {
1402
- throw new Error(
1403
- "SealApi: no global fetch in this runtime \u2014 pass options.fetch or use Node >= 18"
1404
- );
1405
- }
1406
- this.injectedFetch = options.fetch;
1407
- this.credentials = options.credentials;
1933
+ function toUploadError(err, fallbackMessage) {
1934
+ if (err instanceof UploadError) return err;
1935
+ if (err instanceof DOMException && err.name === "AbortError") {
1936
+ return new UploadError("Upload aborted", "ABORTED");
1408
1937
  }
1409
- /**
1410
- * The transport for one request.
1411
- *
1412
- * Called with `globalThis` as receiver, ALWAYS. Storing `globalThis.fetch`
1413
- * on an instance and calling it as `this.fetchImpl(...)` hands the browser a
1414
- * receiver that is not `window`, and it answers "Failed to execute 'fetch'
1415
- * on 'Window': Illegal invocation". Node does not care, which is exactly why
1416
- * the previous copies of this client — all of them Node-only — could carry
1417
- * the same line for a year without anyone noticing.
1418
- *
1419
- * Resolved per call rather than captured in the constructor: a browser host
1420
- * may replace `window.fetch` after this module is evaluated (SEAL Pro does,
1421
- * to re-anchor root-absolute paths onto its `/pro` base path), and clients
1422
- * built as module-level singletons are constructed before that happens.
1423
- */
1424
- fetchImpl(input, init2) {
1425
- const impl = this.injectedFetch ?? globalThis.fetch;
1426
- return impl.call(globalThis, input, init2);
1938
+ return new UploadError(err instanceof Error ? err.message : fallbackMessage, "UNKNOWN");
1939
+ }
1940
+ async function uploadErrorFromResponse(resp, what, code, partNumber) {
1941
+ const refusal = await errorFromResponse(resp, String(resp.status));
1942
+ return new UploadError(
1943
+ `${what}: ${refusal.message}`,
1944
+ resp.status === 426 ? "CLIENT_OUTDATED" : code,
1945
+ resp.status,
1946
+ partNumber
1947
+ );
1948
+ }
1949
+ var log = createLogger("upload");
1950
+ var REAL_CLOCK = {
1951
+ now: () => performance.now(),
1952
+ after: (ms, run) => {
1953
+ const timer = setTimeout(run, ms);
1954
+ return () => clearTimeout(timer);
1955
+ },
1956
+ every: (ms, run) => {
1957
+ const timer = setInterval(run, ms);
1958
+ return () => clearInterval(timer);
1427
1959
  }
1428
- /** Absolute (or origin-relative) URL for a path that must start with `/`. */
1429
- url(path) {
1430
- if (!path.startsWith("/")) {
1431
- throw new Error(`SealApi: path must start with '/', got: ${path}`);
1432
- }
1960
+ };
1961
+ var DEFAULT_TRANSPORT_POLICY = {
1962
+ retryBackoffMs: upload_default.upload.RETRY_BACKOFF_MS,
1963
+ retryJitterRatio: upload_default.upload.RETRY_JITTER_RATIO,
1964
+ stallNoticeMs: upload_default.upload.STALL_NOTICE_MS,
1965
+ maxStallMs: upload_default.upload.MAX_STALL_MS,
1966
+ putFloorBytesPerSecond: upload_default.upload.PUT_FLOOR_BYTES_PER_SECOND,
1967
+ putMinDeadlineMs: upload_default.upload.PUT_MIN_DEADLINE_MS,
1968
+ controlTimeoutMs: upload_default.upload.CONTROL_TIMEOUT_MS,
1969
+ completeTimeoutMs: upload_default.upload.COMPLETE_TIMEOUT_MS,
1970
+ poolStart: upload_default.upload.PART_POOL_START,
1971
+ poolMax: upload_default.upload.PART_POOL_MAX,
1972
+ poolMin: upload_default.upload.PART_POOL_MIN,
1973
+ poolGrowRatio: upload_default.upload.PART_POOL_GROW_RATIO,
1974
+ poolShrinkRatio: upload_default.upload.PART_POOL_SHRINK_RATIO,
1975
+ partQueueLimit: upload_default.upload.PART_QUEUE_LIMIT,
1976
+ hedgeMinInflightMs: upload_default.upload.HEDGE_MIN_INFLIGHT_MS,
1977
+ hedgeLagFactor: upload_default.upload.HEDGE_LAG_FACTOR,
1978
+ hedgePollMs: upload_default.upload.HEDGE_POLL_MS,
1979
+ livenessSilenceMs: upload_default.upload.LIVENESS_SILENCE_MS,
1980
+ verifyPollBackoffMs: upload_default.upload.VERIFY_POLL_BACKOFF_MS,
1981
+ verifyFallbackWaitMs: upload_default.upload.VERIFY_FALLBACK_WAIT_MS,
1982
+ speedWindowMs: upload_default.upload.PROGRESS_SPEED_WINDOW_MS,
1983
+ clock: REAL_CLOCK
1984
+ };
1985
+ function resolveTransportPolicy(overrides) {
1986
+ return { ...DEFAULT_TRANSPORT_POLICY, ...overrides };
1987
+ }
1988
+ function putDeadlineMs(bytes, policy) {
1989
+ return Math.max(policy.putMinDeadlineMs, Math.ceil(bytes / policy.putFloorBytesPerSecond * 1e3));
1990
+ }
1991
+ var signalStatics = () => globalThis.AbortSignal;
1992
+ function anySignal(signals) {
1993
+ const native = signalStatics()?.any;
1994
+ if (typeof native === "function") return native.call(AbortSignal, signals);
1995
+ const controller = new AbortController();
1996
+ const done = signals.find((signal) => signal.aborted);
1997
+ if (done) {
1998
+ controller.abort(done.reason);
1999
+ return controller.signal;
2000
+ }
2001
+ for (const signal of signals) {
2002
+ signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true, signal: controller.signal });
2003
+ }
2004
+ return controller.signal;
2005
+ }
2006
+ function timeoutSignal(ms) {
2007
+ const native = signalStatics()?.timeout;
2008
+ if (typeof native === "function") return native.call(AbortSignal, ms);
2009
+ const controller = new AbortController();
2010
+ setTimeout(() => controller.abort(new DOMException("The operation timed out.", "TimeoutError")), ms);
2011
+ return controller.signal;
2012
+ }
2013
+ function withDeadline(base, ms) {
2014
+ const deadline = timeoutSignal(ms);
2015
+ return base ? anySignal([base, deadline]) : deadline;
2016
+ }
2017
+ async function policyFetch(url, init2, timeoutMs, signal) {
2018
+ try {
2019
+ return await transportFetch(url, { ...init2, signal: withDeadline(signal, timeoutMs) });
2020
+ } catch (err) {
2021
+ if (signal?.aborted) throw new UploadError("Upload aborted", "ABORTED");
2022
+ throw new UploadError(
2023
+ `Request failed: ${err instanceof Error ? err.message : String(err)}`,
2024
+ "NETWORK",
2025
+ void 0,
2026
+ void 0,
2027
+ true
2028
+ );
2029
+ }
2030
+ }
2031
+ function classifyStatus(status) {
2032
+ if (status === 408 || status === 429 || status >= 500) return "retryable";
2033
+ return "terminal";
2034
+ }
2035
+ function classifyStorageFailure(failure) {
2036
+ if (failure.code === "ABORTED") return "terminal";
2037
+ if (failure.code === "BAD_DIGEST") return "retryable";
2038
+ if (failure.httpStatus === void 0) return "retryable";
2039
+ if (failure.httpStatus === 403) return "refresh_url";
2040
+ return classifyStatus(failure.httpStatus);
2041
+ }
2042
+ function classifyControlFailure(failure) {
2043
+ if (failure.code === "ABORTED") return "terminal";
2044
+ if (failure.httpStatus === void 0) return "retryable";
2045
+ return classifyStatus(failure.httpStatus);
2046
+ }
2047
+ var StallClock = class {
2048
+ constructor(policy, onState, now = () => performance.now()) {
2049
+ this.policy = policy;
2050
+ this.onState = onState;
2051
+ this.now = now;
2052
+ this.failingSince = null;
2053
+ this.current = "running";
2054
+ this.noticeTimer = null;
2055
+ this.retriesSinceDelivery = 0;
2056
+ }
2057
+ get state() {
2058
+ return this.current;
2059
+ }
2060
+ /**
2061
+ * The connections are known to be dead (the browser went offline, or every
2062
+ * socket of the upload has been silent): say so now. Nothing failed, so the
2063
+ * give-up clock does not start; the next delivery clears it.
2064
+ */
2065
+ connectionLost() {
2066
+ this.setState("stalled");
2067
+ }
2068
+ /** Storage (or the API) confirmed bytes: the upload is alive. */
2069
+ delivered() {
2070
+ this.failingSince = null;
2071
+ this.retriesSinceDelivery = 0;
2072
+ this.clearNotice();
2073
+ this.setState("running");
2074
+ }
2075
+ /** True when the upload has failed, delivering nothing, for `maxStallMs`. */
2076
+ exhausted() {
2077
+ return this.failingSince !== null && this.now() - this.failingSince >= this.policy.maxStallMs;
2078
+ }
2079
+ /**
2080
+ * A retryable failure happened. Flips to `stalled` once the failing has
2081
+ * lasted long enough — now, or later via a timer, so the notice is on
2082
+ * time even when the next attempt sits out a 30 s backoff.
2083
+ */
2084
+ failed() {
2085
+ this.retriesSinceDelivery += 1;
2086
+ this.failingSince ?? (this.failingSince = this.now());
2087
+ const remaining = this.policy.stallNoticeMs - (this.now() - this.failingSince);
2088
+ if (remaining <= 0) {
2089
+ this.setState("stalled");
2090
+ } else if (this.noticeTimer === null && this.current === "running") {
2091
+ this.noticeTimer = setTimeout(() => {
2092
+ this.noticeTimer = null;
2093
+ this.setState("stalled");
2094
+ }, remaining);
2095
+ }
2096
+ }
2097
+ /** Stop the pending notice; call when the upload ends either way. */
2098
+ dispose() {
2099
+ this.clearNotice();
2100
+ }
2101
+ clearNotice() {
2102
+ if (this.noticeTimer !== null) {
2103
+ clearTimeout(this.noticeTimer);
2104
+ this.noticeTimer = null;
2105
+ }
2106
+ }
2107
+ setState(next) {
2108
+ if (next === this.current) return;
2109
+ this.current = next;
2110
+ this.onState?.(next);
2111
+ }
2112
+ };
2113
+ function abortableDelay(ms, signal) {
2114
+ return new Promise((resolve2, reject) => {
2115
+ if (signal?.aborted) {
2116
+ reject(new UploadError("Upload aborted", "ABORTED"));
2117
+ return;
2118
+ }
2119
+ const onAbort = () => {
2120
+ clearTimeout(timer);
2121
+ reject(new UploadError("Upload aborted", "ABORTED"));
2122
+ };
2123
+ const timer = setTimeout(() => {
2124
+ signal?.removeEventListener("abort", onAbort);
2125
+ resolve2();
2126
+ }, ms);
2127
+ signal?.addEventListener("abort", onAbort, { once: true });
2128
+ });
2129
+ }
2130
+ async function retrying(step, options) {
2131
+ const { clock, policy, signal, classify, what } = options;
2132
+ let after;
2133
+ let refreshedInARow = 0;
2134
+ for (let attempt = 0; ; attempt++) {
2135
+ if (signal?.aborted) throw new UploadError("Upload aborted", "ABORTED");
2136
+ try {
2137
+ return await step({ attempt, after });
2138
+ } catch (err) {
2139
+ const failure = toUploadError(err, `${what} failed`);
2140
+ if (failure.code === "ABORTED") throw failure;
2141
+ const failureClass = classify(failure);
2142
+ if (failureClass === "terminal") throw failure;
2143
+ if (clock.exhausted()) {
2144
+ throw new UploadError(
2145
+ `${what}: no progress for ${Math.round(policy.maxStallMs / 1e3)} s \u2014 ${failure.message}`,
2146
+ failure.code,
2147
+ failure.httpStatus,
2148
+ failure.partNumber,
2149
+ false
2150
+ );
2151
+ }
2152
+ clock.failed();
2153
+ refreshedInARow = failureClass === "refresh_url" ? refreshedInARow + 1 : 0;
2154
+ const immediate = failureClass === "refresh_url" && refreshedInARow === 1;
2155
+ const base = policy.retryBackoffMs[Math.min(attempt, policy.retryBackoffMs.length - 1)] ?? 0;
2156
+ const jitter = 1 + (Math.random() * 2 - 1) * policy.retryJitterRatio;
2157
+ const delay = immediate ? 0 : Math.round(base * jitter);
2158
+ log.debug(
2159
+ `retry ${what} attempt=${attempt + 2} in ${delay}ms after ${failure.code}${failure.httpStatus ? " " + failure.httpStatus : ""} (${failureClass})`
2160
+ );
2161
+ after = failureClass;
2162
+ await abortableDelay(delay, signal);
2163
+ }
2164
+ }
2165
+ }
2166
+ var clientIdentity;
2167
+ function setClientIdentity(name2, version) {
2168
+ clientIdentity = `${name2}/${version}`;
2169
+ }
2170
+ function clientHeaders() {
2171
+ return clientIdentity === void 0 ? {} : { [header]: clientIdentity };
2172
+ }
2173
+ var BackendError = class extends Error {
2174
+ constructor(message, code, status, extra = {}) {
2175
+ super(message);
2176
+ this.name = "BackendError";
2177
+ this.code = code;
2178
+ this.status = status;
2179
+ this.body = extra.body;
2180
+ this.detail = extra.detail;
2181
+ this.appCode = extra.appCode;
2182
+ this.retryAfter = extra.retryAfter;
2183
+ this.update = extra.update;
2184
+ this.minVersion = extra.minVersion;
2185
+ }
2186
+ };
2187
+ function classifyStatus2(status) {
2188
+ if (status === 404) return "not_found";
2189
+ if (status === 410) return "revoked";
2190
+ if (status === 451) return "blocked";
2191
+ if (status === 429) return "rate_limited";
2192
+ if (status === 401 || status === 403) return "auth";
2193
+ if (status >= 500 && status < 600) return "transient";
2194
+ return "unknown";
2195
+ }
2196
+ async function errorFromResponse(resp, fallback) {
2197
+ const body = await resp.text().catch(() => "");
2198
+ let detail;
2199
+ let appCode;
2200
+ let retryAfter;
2201
+ let update;
2202
+ let minVersion;
2203
+ if (body) {
2204
+ try {
2205
+ const parsed = JSON.parse(body);
2206
+ if (typeof parsed?.detail === "string") detail = parsed.detail;
2207
+ if (typeof parsed?.code === "string") appCode = parsed.code;
2208
+ if (typeof parsed?.retry_after === "number") retryAfter = parsed.retry_after;
2209
+ if (typeof parsed?.update === "string") update = parsed.update;
2210
+ if (typeof parsed?.min_version === "string") minVersion = parsed.min_version;
2211
+ } catch {
2212
+ }
2213
+ }
2214
+ return new BackendError(detail ?? fallback, classifyStatus2(resp.status), resp.status, {
2215
+ body: body || void 0,
2216
+ detail,
2217
+ appCode,
2218
+ retryAfter,
2219
+ update,
2220
+ minVersion
2221
+ });
2222
+ }
2223
+ function toSealMetadata(wire) {
2224
+ return {
2225
+ id: wire.id,
2226
+ expiresAt: wire.expires_at,
2227
+ revokedAt: wire.revoked_at,
2228
+ ndaRequired: wire.nda_required,
2229
+ otpRequired: wire.otp_required,
2230
+ singleUse: wire.single_use,
2231
+ maxOpens: wire.max_opens ?? null,
2232
+ files: (wire.files ?? []).map((f) => ({
2233
+ id: f.id,
2234
+ size: f.size,
2235
+ sha256_hex: f.sha256_hex,
2236
+ name_encrypted: f.name_encrypted,
2237
+ name_nonce: f.name_nonce,
2238
+ mime_encrypted: f.mime_encrypted,
2239
+ mime_nonce: f.mime_nonce
2240
+ }))
2241
+ };
2242
+ }
2243
+ function encode(segment) {
2244
+ return encodeURIComponent(segment);
2245
+ }
2246
+ var SHARE_PROOF_HEADER = crypto_default.share_link.proof_header;
2247
+ var heldProofs = /* @__PURE__ */ new Map();
2248
+ async function shareProof(linkKey) {
2249
+ const text2 = new TextEncoder();
2250
+ const ikm = await crypto.subtle.importKey("raw", linkKey, "HKDF", false, ["deriveBits"]);
2251
+ const derived = await crypto.subtle.deriveBits(
2252
+ { name: "HKDF", hash: "SHA-256", salt: text2.encode(crypto_default.hkdf.identity_key_salt), info: text2.encode(crypto_default.hkdf.info_prefixes.share_proof) },
2253
+ ikm,
2254
+ 256
2255
+ );
2256
+ const proof = new Uint8Array(derived);
2257
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", proof));
2258
+ return { proof: bytesToBase64url(proof), hash: Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("") };
2259
+ }
2260
+ async function holdShareProof(sealId, linkKey) {
2261
+ heldProofs.set(sealId, (await shareProof(linkKey)).proof);
2262
+ }
2263
+ function shareProofHeader(path) {
2264
+ const seal = /^\/seal\/([^/?]+)/.exec(path)?.[1];
2265
+ const proof = seal ? heldProofs.get(decodeURIComponent(seal)) : void 0;
2266
+ return proof ? { [SHARE_PROOF_HEADER]: proof } : {};
2267
+ }
2268
+ var SealApi = class _SealApi {
2269
+ constructor(options) {
2270
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
2271
+ if (typeof (options.fetch ?? globalThis.fetch) !== "function") {
2272
+ throw new Error(
2273
+ "SealApi: no global fetch in this runtime \u2014 pass options.fetch or use Node >= 18"
2274
+ );
2275
+ }
2276
+ this.injectedFetch = options.fetch;
2277
+ this.credentials = options.credentials;
2278
+ this.answerTimeoutMs = options.answerTimeoutMs ?? API_ANSWER_TIMEOUT_MS;
2279
+ }
2280
+ /**
2281
+ * The transport for one request.
2282
+ *
2283
+ * Called with `globalThis` as receiver, ALWAYS. Storing `globalThis.fetch`
2284
+ * on an instance and calling it as `this.fetchImpl(...)` hands the browser a
2285
+ * receiver that is not `window`, and it answers "Failed to execute 'fetch'
2286
+ * on 'Window': Illegal invocation". Node does not care, which is exactly why
2287
+ * the previous copies of this client — all of them Node-only — could carry
2288
+ * the same line for a year without anyone noticing.
2289
+ *
2290
+ * Resolved per call rather than captured in the constructor: a browser host
2291
+ * may replace `window.fetch` after this module is evaluated (SEAL Pro does,
2292
+ * to re-anchor root-absolute paths onto its `/pro` base path), and clients
2293
+ * built as module-level singletons are constructed before that happens.
2294
+ * Without an injected one, the host's network (`setTransport`) carries it.
2295
+ */
2296
+ fetchImpl(input, init2) {
2297
+ return this.injectedFetch ? this.injectedFetch.call(globalThis, input, init2) : transportFetch(input, init2);
2298
+ }
2299
+ /** Absolute (or origin-relative) URL for a path that must start with `/`. */
2300
+ url(path) {
2301
+ if (!path.startsWith("/")) {
2302
+ throw new Error(`SealApi: path must start with '/', got: ${path}`);
2303
+ }
1433
2304
  return `${this.baseUrl}${path}`;
1434
2305
  }
1435
2306
  async request(path, init2) {
1436
2307
  const { what, ...rest } = init2;
1437
- const resp = await this.fetchImpl(this.url(path), {
1438
- ...rest,
1439
- headers: { ...clientHeaders(), ...rest.headers },
1440
- credentials: rest.credentials ?? this.credentials
1441
- });
2308
+ const deadline = new AbortController();
2309
+ const timer = setTimeout(() => deadline.abort(new DOMException(`${what}: no answer in time`, "TimeoutError")), this.answerTimeoutMs);
2310
+ let resp;
2311
+ try {
2312
+ resp = await this.fetchImpl(this.url(path), {
2313
+ ...rest,
2314
+ headers: { ...clientHeaders(), ...shareProofHeader(path), ...rest.headers },
2315
+ credentials: rest.credentials ?? this.credentials,
2316
+ signal: rest.signal ? anySignal([rest.signal, deadline.signal]) : deadline.signal
2317
+ });
2318
+ } finally {
2319
+ clearTimeout(timer);
2320
+ }
1442
2321
  if (!resp.ok) {
1443
2322
  throw await errorFromResponse(resp, `${what} failed: ${resp.status}`);
1444
2323
  }
@@ -1452,9 +2331,13 @@ var SealApi = class _SealApi {
1452
2331
  // ---------------------------------------------------------------------------
1453
2332
  // Public surface (recipient side)
1454
2333
  // ---------------------------------------------------------------------------
1455
- /** `GET /seal/{id}` — public metadata. Ticks no counters. */
2334
+ /**
2335
+ * `GET /seal/{id}` — public metadata. Ticks no counters. An organization's seal lists its files only to the
2336
+ * link `shareCode` names, the files of its scope (SPEC-r4 api11.1).
2337
+ */
1456
2338
  async getMetadata(sealId, opts = {}) {
1457
- const resp = await this.request(`/seal/${encode(sealId)}`, {
2339
+ const query = opts.shareCode ? `?share_code=${encode(opts.shareCode)}` : "";
2340
+ const resp = await this.request(`/seal/${encode(sealId)}${query}`, {
1458
2341
  what: `GET /seal/${sealId}`,
1459
2342
  signal: opts.signal
1460
2343
  });
@@ -1576,6 +2459,28 @@ var SealApi = class _SealApi {
1576
2459
  }
1577
2460
  }
1578
2461
  }
2462
+ /**
2463
+ * The ciphertext itself, for a runtime that decrypts: `openDownload`, and
2464
+ * where the answer is a BFF's `{url}` (`X-Download-Mode: presigned` — a
2465
+ * page served from seal.net reaches the API through `/api`, and script
2466
+ * cannot read `Location`), the bytes from storage behind it, opened as the
2467
+ * URL was signed: no client header, cookie or credentials. A page that
2468
+ * streams from the URL itself keeps calling `openDownload`.
2469
+ *
2470
+ * Found 30.10: an SDK on a seal.net page piped the `{url}` answer into the
2471
+ * decryptor; the one open of a single-use seal went on an integrity failure.
2472
+ */
2473
+ async downloadCiphertext(sealId, target, opts = {}) {
2474
+ const answer = await this.openDownload(sealId, target, opts);
2475
+ if (answer.headers.get("X-Download-Mode") !== "presigned") return answer;
2476
+ const { url } = await answer.json();
2477
+ if (typeof url !== "string" || !url) {
2478
+ throw new BackendError(`GET /seal/${sealId}/download answered no storage URL`, "transient", 502);
2479
+ }
2480
+ const storage = await this.fetchImpl(url, { signal: opts.signal });
2481
+ if (!storage.ok) throw await errorFromResponse(storage, `storage download failed: ${storage.status}`);
2482
+ return storage;
2483
+ }
1579
2484
  // ---------------------------------------------------------------------------
1580
2485
  // Owner surface (X-Owner-Token)
1581
2486
  // ---------------------------------------------------------------------------
@@ -1634,10 +2539,13 @@ var SealApi = class _SealApi {
1634
2539
  * `fileIds` scopes the link to those files of the seal (all of them when
1635
2540
  * absent). `ownerToken` is null when the host's BFF authorises the call
1636
2541
  * itself: an organisation's seal, minted under a member's session.
2542
+ * `linkKey` is the key the blob was encrypted with: the server gets the hash
2543
+ * of its proof, and opens the link to that proof whatever the seal's count
2544
+ * of wrong codes (AUDIT K237).
1637
2545
  */
1638
- async createShareLink(sealId, ownerToken, encryptedBlobB64, opts = {}) {
2546
+ async createShareLink(sealId, ownerToken, encryptedBlobB64, linkKey, opts = {}) {
1639
2547
  const headers = ownerToken === null ? { "Content-Type": "application/json" } : _SealApi.ownerHeaders(ownerToken, true);
1640
- const body = { encrypted_blob: encryptedBlobB64 };
2548
+ const body = { encrypted_blob: encryptedBlobB64, proof_hash: (await shareProof(linkKey)).hash };
1641
2549
  if (opts.fileIds) body.file_ids = opts.fileIds;
1642
2550
  addAddress(opts, body, headers);
1643
2551
  const resp = await this.request(`/seal/${encode(sealId)}/share`, {
@@ -1673,9 +2581,11 @@ var SealApi = class _SealApi {
1673
2581
  /**
1674
2582
  * `POST /seal/{id}/revoke` — revoke the whole seal.
1675
2583
  *
1676
- * Idempotent, including at the extremes: a seal that is already gone (404)
1677
- * or already revoked (410) satisfies the caller's intent, so both count as
1678
- * success. `revokedAt` is null when the server had nothing left to report.
2584
+ * Idempotent, including at the extremes: a seal that is already gone
2585
+ * (404 `seal.not_found`) or already revoked (410) satisfies the caller's
2586
+ * intent, so both count as success. Any other 404 — a proxy's, a route this
2587
+ * host does not serve — is a failure (AUDIT wpkg03.19): the seal may live on.
2588
+ * `revokedAt` is null when the server had nothing left to report.
1679
2589
  */
1680
2590
  async revoke(sealId, ownerToken, opts = {}) {
1681
2591
  let resp;
@@ -1687,7 +2597,7 @@ var SealApi = class _SealApi {
1687
2597
  signal: opts.signal
1688
2598
  });
1689
2599
  } catch (err) {
1690
- if (err instanceof BackendError && (err.status === 404 || err.status === 410)) {
2600
+ if (err instanceof BackendError && (err.status === 404 && err.appCode === "seal.not_found" || err.status === 410)) {
1691
2601
  return { status: "revoked", revokedAt: null };
1692
2602
  }
1693
2603
  throw err;
@@ -1786,6 +2696,7 @@ var SealApi = class _SealApi {
1786
2696
  if (input.whereUrl) body.where_url = input.whereUrl;
1787
2697
  if (input.ttlSeconds !== void 0) body.ttl_seconds = input.ttlSeconds;
1788
2698
  if (input.to) body.to = input.to;
2699
+ if (input.bind) body.bind = input.bind;
1789
2700
  const resp = await this.request("/intake", {
1790
2701
  what: "POST /intake",
1791
2702
  method: "POST",
@@ -1880,16 +2791,6 @@ var SealApi = class _SealApi {
1880
2791
  signal: opts.signal
1881
2792
  });
1882
2793
  }
1883
- async migrateInbox(proof, body, opts = {}) {
1884
- const resp = await this.request("/intake/migrate", {
1885
- what: "POST /intake/migrate",
1886
- method: "POST",
1887
- headers: { "Content-Type": "application/json", ...proofHeaders(proof) },
1888
- body: JSON.stringify(body),
1889
- signal: opts.signal
1890
- });
1891
- return await resp.json();
1892
- }
1893
2794
  /** `GET /intake/push-key` — the VAPID key a browser subscribes an inbox's push with (F3 §8). */
1894
2795
  async pushKey(opts = {}) {
1895
2796
  const resp = await this.request("/intake/push-key", { what: "GET /intake/push-key", signal: opts.signal });
@@ -1906,6 +2807,53 @@ var SealApi = class _SealApi {
1906
2807
  signal: opts.signal
1907
2808
  });
1908
2809
  }
2810
+ // ---------------------------------------------------------------------------
2811
+ // Leases of lent keys (SPEC agent egress §5.8)
2812
+ // ---------------------------------------------------------------------------
2813
+ /**
2814
+ * `POST /lease` — the one record of a lent key the server keeps: under the SHA-256 hex of a token the
2815
+ * lender made (`newLease` makes both), until `expiresAt` or, with null, until revoked. Which key, host
2816
+ * or address it is about stays inside the sealed binding.
2817
+ */
2818
+ async createLease(ownerTokenHash, expiresAt, opts = {}) {
2819
+ const resp = await this.request("/lease", {
2820
+ what: "POST /lease",
2821
+ method: "POST",
2822
+ headers: { "Content-Type": "application/json" },
2823
+ body: JSON.stringify({ owner_token_hash: ownerTokenHash, expires_at: expiresAt }),
2824
+ signal: opts.signal
2825
+ });
2826
+ return await resp.json();
2827
+ }
2828
+ /** `POST /lease/{id}/revoke` — the owner takes the key back; a repeat answers the first `revoked_at`. */
2829
+ async revokeLease(leaseId, token, opts = {}) {
2830
+ const resp = await this.request(`/lease/${encode(leaseId)}/revoke`, {
2831
+ what: `POST /lease/${leaseId}/revoke`,
2832
+ method: "POST",
2833
+ headers: _SealApi.ownerHeaders(token),
2834
+ signal: opts.signal
2835
+ });
2836
+ return await resp.json();
2837
+ }
2838
+ /**
2839
+ * `POST /lease/status` — the state of up to `LEASE_STATUS_BATCH_MAX` leases in one ask; an id the server
2840
+ * does not hold is `expired`. With `etag` from the last answer the server says 304 when nothing changed,
2841
+ * and this answers null.
2842
+ */
2843
+ async leaseStatus(ids, opts = {}) {
2844
+ const headers = { "Content-Type": "application/json" };
2845
+ if (opts.etag) headers["If-None-Match"] = opts.etag;
2846
+ const resp = await this.fetchImpl(this.url("/lease/status"), {
2847
+ method: "POST",
2848
+ headers: { ...clientHeaders(), ...headers },
2849
+ body: JSON.stringify({ ids }),
2850
+ credentials: this.credentials,
2851
+ signal: opts.signal
2852
+ });
2853
+ if (resp.status === 304) return null;
2854
+ if (!resp.ok) throw await errorFromResponse(resp, `POST /lease/status failed: ${resp.status}`);
2855
+ return { statuses: await resp.json(), etag: resp.headers.get("ETag") };
2856
+ }
1909
2857
  };
1910
2858
  var NOT_READY_DEFAULT_RETRY_AFTER_S = 3;
1911
2859
  function proofHeaders(proof) {
@@ -1965,6 +2913,10 @@ function extractSessionCookie(resp, wantedName) {
1965
2913
  var OWNER_TOKEN_BYTES = 32;
1966
2914
  var LINK_KEY_BYTES = 32;
1967
2915
  var MAX_BLOB_SIZE = limits_default.limits.MAX_BLOB_SIZE;
2916
+ var MAX_FILE_KEYS = limits_default.limits.MAX_FILE_KEYS;
2917
+ function assertFileKeyCount(count2) {
2918
+ if (count2 > MAX_FILE_KEYS) throw new Error(`Too many file keys: ${count2} exceeds maximum of ${MAX_FILE_KEYS}`);
2919
+ }
1968
2920
  var BlobDecryptionError = class extends Error {
1969
2921
  constructor() {
1970
2922
  super("Invalid encryption key");
@@ -1981,30 +2933,36 @@ async function hashOwnerToken(token) {
1981
2933
  function generateLinkKey() {
1982
2934
  return crypto.getRandomValues(new Uint8Array(LINK_KEY_BYTES));
1983
2935
  }
1984
- async function encryptOwnerBlob(ownerToken, fileKeys, linkKey, message, ndaFile) {
2936
+ async function encryptOwnerBlob(ownerToken, fileKeys, linkKey, message, ndaFile, bindings, payload) {
2937
+ assertFileKeyCount(fileKeys.size);
1985
2938
  const data = {
1986
2939
  owner_token: ownerToken,
1987
2940
  file_keys: Object.fromEntries(fileKeys),
1988
2941
  ...message ? { message } : {},
1989
- ...ndaFile ? { nda_file: ndaFile } : {}
2942
+ ...ndaFile ? { nda_file: ndaFile } : {},
2943
+ ...bindings && Object.keys(bindings).length > 0 ? { bindings } : {},
2944
+ ...payload ? { payload } : {}
1990
2945
  };
1991
2946
  return encryptBlob(data, linkKey);
1992
2947
  }
1993
- async function encryptShareBlob(fileKeys, linkKey, message, ndaFile, replyTo) {
2948
+ async function encryptShareBlob(fileKeys, linkKey, message, ndaFile, replyTo, bindings, payload) {
2949
+ assertFileKeyCount(fileKeys.size);
1994
2950
  const data = {
1995
2951
  file_keys: Object.fromEntries(fileKeys),
1996
2952
  ...message ? { message } : {},
1997
2953
  ...ndaFile ? { nda_file: ndaFile } : {},
1998
- ...replyTo ? { reply_to: bytesToBase64url(replyTo) } : {}
2954
+ ...replyTo ? { reply_to: bytesToBase64url(replyTo) } : {},
2955
+ ...bindings && Object.keys(bindings).length > 0 ? { bindings } : {},
2956
+ ...payload ? { payload } : {}
1999
2957
  };
2000
2958
  return encryptBlob(data, linkKey);
2001
2959
  }
2002
2960
  async function encryptBlob(data, linkKey) {
2003
- const json = JSON.stringify(data);
2004
- if (json.length > MAX_BLOB_SIZE) {
2005
- throw new Error(`Blob data size ${json.length} exceeds maximum of ${MAX_BLOB_SIZE}`);
2961
+ const plaintext = new TextEncoder().encode(JSON.stringify(data));
2962
+ const blobSize = 12 + plaintext.length + 16;
2963
+ if (blobSize > MAX_BLOB_SIZE) {
2964
+ throw new Error(`Blob size ${blobSize} exceeds maximum of ${MAX_BLOB_SIZE}`);
2006
2965
  }
2007
- const plaintext = new TextEncoder().encode(json);
2008
2966
  const nonce = crypto.getRandomValues(new Uint8Array(12));
2009
2967
  const cryptoKey = await crypto.subtle.importKey(
2010
2968
  "raw",
@@ -2023,6 +2981,15 @@ async function encryptBlob(data, linkKey) {
2023
2981
  result.set(new Uint8Array(ciphertext), 12);
2024
2982
  return result;
2025
2983
  }
2984
+ function isBinding(value) {
2985
+ if (typeof value !== "object" || value === null) return false;
2986
+ const obj = value;
2987
+ return obj.v === 1 && typeof obj.name === "string" && (obj.class === "outbound" || obj.class === "inprocess") && Array.isArray(obj.hosts) && obj.hosts.every((h) => typeof h === "string");
2988
+ }
2989
+ function bindingsOf(data) {
2990
+ if (typeof data.bindings !== "object" || data.bindings === null) return {};
2991
+ return Object.fromEntries(Object.entries(data.bindings).filter(([, b]) => isBinding(b)));
2992
+ }
2026
2993
  function isShareBlobData(data) {
2027
2994
  if (typeof data !== "object" || data === null) return false;
2028
2995
  const obj = data;
@@ -2032,6 +2999,7 @@ function isShareBlobData(data) {
2032
2999
  }
2033
3000
  if (obj.message !== void 0 && typeof obj.message !== "string") return false;
2034
3001
  if (obj.reply_to !== void 0 && typeof obj.reply_to !== "string") return false;
3002
+ if (obj.payload !== void 0 && typeof obj.payload !== "string") return false;
2035
3003
  return true;
2036
3004
  }
2037
3005
  async function decryptShareBlob(encrypted, linkKey) {
@@ -2073,42 +3041,7 @@ async function decryptBlob(encrypted, linkKey) {
2073
3041
  throw new Error("Invalid JSON in decrypted blob");
2074
3042
  }
2075
3043
  }
2076
- function isProduction() {
2077
- try {
2078
- return typeof process !== "undefined" && process.env?.NODE_ENV === "production";
2079
- } catch {
2080
- return false;
2081
- }
2082
- }
2083
- var defaultLogHandler = (level, module2, message, ...args) => {
2084
- const formatted = `[${module2}] ${message}`;
2085
- switch (level) {
2086
- case "debug":
2087
- if (!isProduction()) {
2088
- console.debug(formatted, ...args);
2089
- }
2090
- break;
2091
- case "info":
2092
- console.info(formatted, ...args);
2093
- break;
2094
- case "warn":
2095
- console.warn(formatted, ...args);
2096
- break;
2097
- case "error":
2098
- console.error(formatted, ...args);
2099
- break;
2100
- }
2101
- };
2102
- var currentHandler = defaultLogHandler;
2103
- function createLogger(module2) {
2104
- return {
2105
- debug: (message, ...args) => currentHandler("debug", module2, message, ...args),
2106
- info: (message, ...args) => currentHandler("info", module2, message, ...args),
2107
- warn: (message, ...args) => currentHandler("warn", module2, message, ...args),
2108
- error: (message, ...args) => currentHandler("error", module2, message, ...args)
2109
- };
2110
- }
2111
- var MAX_FILE_KEYS = limits_default.limits.MAX_FILE_KEYS;
3044
+ var MAX_FILE_KEYS2 = limits_default.limits.MAX_FILE_KEYS;
2112
3045
  var BLOCK_BYTES = 64;
2113
3046
  var SHIFTS = [
2114
3047
  7,
@@ -2466,22 +3399,255 @@ function createDecryptStream(key2, options) {
2466
3399
  );
2467
3400
  }
2468
3401
  var swLogger = createLogger("SwDownload");
3402
+ var SW_QUIET_MS = 10 * 6e4;
3403
+ var mime_default = {
3404
+ version: 1,
3405
+ default: "application/octet-stream",
3406
+ extensions: {
3407
+ json: "application/json",
3408
+ txt: "text/plain",
3409
+ log: "text/plain",
3410
+ md: "text/plain",
3411
+ csv: "text/csv",
3412
+ html: "text/html",
3413
+ htm: "text/html",
3414
+ xml: "application/xml",
3415
+ pdf: "application/pdf",
3416
+ zip: "application/zip",
3417
+ png: "image/png",
3418
+ jpg: "image/jpeg",
3419
+ jpeg: "image/jpeg",
3420
+ gif: "image/gif",
3421
+ webp: "image/webp",
3422
+ svg: "image/svg+xml",
3423
+ mp4: "video/mp4",
3424
+ webm: "video/webm",
3425
+ mp3: "audio/mpeg",
3426
+ wav: "audio/wav",
3427
+ ogg: "audio/ogg",
3428
+ doc: "application/msword",
3429
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
3430
+ xls: "application/vnd.ms-excel",
3431
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
3432
+ }
3433
+ };
3434
+ var REPLACEMENT_CHAR = "_";
3435
+ var MAX_FILENAME_BYTES = 200;
3436
+ var encoder = new TextEncoder();
3437
+ function utf8Length(text2) {
3438
+ return encoder.encode(text2).length;
3439
+ }
3440
+ function headWithin(text2, bytes) {
3441
+ let head = "";
3442
+ let used = 0;
3443
+ for (const char of text2) {
3444
+ used += utf8Length(char);
3445
+ if (used > bytes) break;
3446
+ head += char;
3447
+ }
3448
+ return head;
3449
+ }
3450
+ var WINDOWS_RESERVED_NAMES = /* @__PURE__ */ new Set([
3451
+ "CON",
3452
+ "PRN",
3453
+ "AUX",
3454
+ "NUL",
3455
+ "COM1",
3456
+ "COM2",
3457
+ "COM3",
3458
+ "COM4",
3459
+ "COM5",
3460
+ "COM6",
3461
+ "COM7",
3462
+ "COM8",
3463
+ "COM9",
3464
+ "LPT1",
3465
+ "LPT2",
3466
+ "LPT3",
3467
+ "LPT4",
3468
+ "LPT5",
3469
+ "LPT6",
3470
+ "LPT7",
3471
+ "LPT8",
3472
+ "LPT9"
3473
+ ]);
3474
+ function detectPlatform() {
3475
+ if (typeof process !== "undefined" && process.platform) {
3476
+ switch (process.platform) {
3477
+ case "win32":
3478
+ return "windows";
3479
+ case "darwin":
3480
+ return "macos";
3481
+ case "linux":
3482
+ return "linux";
3483
+ case "android":
3484
+ return "android";
3485
+ default:
3486
+ return "unknown";
3487
+ }
3488
+ }
3489
+ if (typeof navigator !== "undefined" && navigator.userAgent) {
3490
+ const ua = navigator.userAgent.toLowerCase();
3491
+ if (ua.includes("win")) return "windows";
3492
+ if (ua.includes("android")) return "android";
3493
+ if (ua.includes("iphone") || ua.includes("ipad") || ua.includes("ipod")) return "ios";
3494
+ if (ua.includes("mac")) return "macos";
3495
+ if (ua.includes("linux")) return "linux";
3496
+ }
3497
+ return "unknown";
3498
+ }
3499
+ function isValidChar(char, platform) {
3500
+ const code = char.charCodeAt(0);
3501
+ if (code < 32 || code === 127) return false;
3502
+ if (/[\u202A-\u202E\u2066-\u2069\u200E\u200F\u061C]/.test(char)) return false;
3503
+ switch (platform) {
3504
+ case "windows":
3505
+ return !/[<>:"/\\|?*]/.test(char);
3506
+ case "macos":
3507
+ case "ios":
3508
+ return !/[/:]/.test(char);
3509
+ case "linux":
3510
+ case "android":
3511
+ return char !== "/";
3512
+ default:
3513
+ return !/[<>:"/\\|?*]/.test(char);
3514
+ }
3515
+ }
3516
+ function isWindowsReservedName(name2) {
3517
+ const baseName = name2.split(".")[0].toUpperCase();
3518
+ return WINDOWS_RESERVED_NAMES.has(baseName);
3519
+ }
3520
+ function sanitizeFilename(filename, options = {}) {
3521
+ const {
3522
+ platform = detectPlatform(),
3523
+ replacement = REPLACEMENT_CHAR,
3524
+ maxLength = MAX_FILENAME_BYTES,
3525
+ fallback = "file"
3526
+ } = options;
3527
+ if (!filename || !filename.trim()) {
3528
+ return fallback;
3529
+ }
3530
+ let result = filename.normalize("NFC");
3531
+ result = result.trim();
3532
+ result = result.replace(/^\.+|\.+$/g, "");
3533
+ const chars = [...result];
3534
+ result = chars.map((char) => isValidChar(char, platform) ? char : replacement).join("");
3535
+ const escapedReplacement = replacement.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3536
+ result = result.replace(new RegExp(`${escapedReplacement}+`, "g"), replacement);
3537
+ result = result.replace(new RegExp(`^(?:\\.|${escapedReplacement})+|${escapedReplacement}+$`, "g"), "");
3538
+ if (platform === "windows" || platform === "unknown") {
3539
+ if (isWindowsReservedName(result)) {
3540
+ result = `${replacement}${result}`;
3541
+ }
3542
+ }
3543
+ if (utf8Length(result) > maxLength) {
3544
+ const lastDot = result.lastIndexOf(".");
3545
+ if (lastDot > 0 && lastDot > result.length - 10) {
3546
+ const ext = result.slice(lastDot);
3547
+ result = headWithin(result.slice(0, lastDot), maxLength - utf8Length(ext)) + ext;
3548
+ } else {
3549
+ result = headWithin(result, maxLength);
3550
+ }
3551
+ }
3552
+ if (!result || result === replacement) {
3553
+ return fallback;
3554
+ }
3555
+ return result;
3556
+ }
3557
+ var MIME_BY_EXTENSION = new Map(Object.entries(mime_default.extensions));
3558
+ function guessMimeFromName(name2) {
3559
+ const idx = name2.lastIndexOf(".");
3560
+ const ext = idx >= 0 && idx < name2.length - 1 ? name2.slice(idx + 1).toLowerCase() : "";
3561
+ return MIME_BY_EXTENSION.get(ext) ?? mime_default.default;
3562
+ }
2469
3563
  var DEFAULT_BLOB_LIMIT = upload_default.upload.MULTIPART_THRESHOLD_BYTES;
2470
3564
  var STREAMING_THRESHOLD = upload_default.upload.MULTIPART_THRESHOLD_BYTES;
3565
+ var encoder2 = new TextEncoder();
2471
3566
  var zipLogger = createLogger("FolderZip");
2472
3567
  var BLOB_LIMIT = 100 * 1024 * 1024;
2473
3568
  var HIGH_WATER_BYTES = 4 * 1024 * 1024;
2474
- var log = createLogger("upload");
3569
+ var ENCRYPTED_FILE_FALLBACK = "Encrypted file";
3570
+ var ENCRYPTED_MIME_FALLBACK = "application/octet-stream";
3571
+ function metadataFieldAAD(field) {
3572
+ return new TextEncoder().encode(`field:${field}`);
3573
+ }
3574
+ async function encryptMetadataField(plaintext, key2, field) {
3575
+ const nonce = crypto.getRandomValues(new Uint8Array(12));
3576
+ const cryptoKey = await crypto.subtle.importKey(
3577
+ "raw",
3578
+ key2.buffer.slice(key2.byteOffset, key2.byteOffset + key2.byteLength),
3579
+ { name: "AES-GCM" },
3580
+ false,
3581
+ ["encrypt"]
3582
+ );
3583
+ const params = { name: "AES-GCM", iv: nonce, tagLength: 128 };
3584
+ if (field) {
3585
+ const aad = metadataFieldAAD(field);
3586
+ params.additionalData = aad.buffer.slice(aad.byteOffset, aad.byteOffset + aad.byteLength);
3587
+ }
3588
+ const ciphertext = await crypto.subtle.encrypt(params, cryptoKey, new TextEncoder().encode(plaintext));
3589
+ return { ciphertext: bytesToBase64(new Uint8Array(ciphertext)), nonce: bytesToBase64(nonce) };
3590
+ }
3591
+ async function decryptMetadataField(encrypted, nonce, key2, field) {
3592
+ const ciphertext = base64ToBytes(encrypted);
3593
+ const iv = base64ToBytes(nonce);
3594
+ const run = async (aad) => {
3595
+ const params = { name: "AES-GCM", iv };
3596
+ if (aad) params.additionalData = aad;
3597
+ const plaintext = await crypto.subtle.decrypt(params, key2, ciphertext);
3598
+ return new TextDecoder().decode(plaintext);
3599
+ };
3600
+ return run(field ? metadataFieldAAD(field) : void 0);
3601
+ }
3602
+ async function decryptFileMetadata(file, key2) {
3603
+ let name2 = ENCRYPTED_FILE_FALLBACK;
3604
+ let mime = ENCRYPTED_MIME_FALLBACK;
3605
+ if (file.name_encrypted && file.name_nonce && file.name_nonce.length > 0) {
3606
+ try {
3607
+ name2 = await decryptMetadataField(file.name_encrypted, file.name_nonce, key2, "name");
3608
+ } catch {
3609
+ name2 = ENCRYPTED_FILE_FALLBACK;
3610
+ }
3611
+ }
3612
+ if (file.mime_encrypted && file.mime_nonce && file.mime_nonce.length > 0) {
3613
+ try {
3614
+ mime = await decryptMetadataField(file.mime_encrypted, file.mime_nonce, key2, "mime");
3615
+ } catch {
3616
+ mime = ENCRYPTED_MIME_FALLBACK;
3617
+ }
3618
+ }
3619
+ return { name: name2, mime };
3620
+ }
3621
+ async function importKeyForMetadata(keyBytes) {
3622
+ return crypto.subtle.importKey(
3623
+ "raw",
3624
+ keyBytes,
3625
+ { name: "AES-GCM" },
3626
+ false,
3627
+ ["decrypt"]
3628
+ );
3629
+ }
3630
+ async function decryptFileMetadataWithBytes(file, keyBytes) {
3631
+ try {
3632
+ const key2 = await importKeyForMetadata(keyBytes);
3633
+ return decryptFileMetadata(file, key2);
3634
+ } catch {
3635
+ return { name: ENCRYPTED_FILE_FALLBACK, mime: ENCRYPTED_MIME_FALLBACK };
3636
+ }
3637
+ }
3638
+ var log2 = createLogger("upload");
2475
3639
  var RENDER_SLICE_BYTES = 4 * 1024 * 1024;
2476
3640
  function abortError() {
2477
3641
  return new DOMException("Upload aborted", "AbortError");
2478
3642
  }
2479
3643
  async function runCryptoPipeline(options) {
2480
3644
  const { stream, totalBytes, key: key2, header: header2, partSize, signal, yieldToRenderer, onSegment } = options;
2481
- const segmentSize = SEGMENT_SIZE;
2482
- const segments = Math.max(1, Math.ceil(totalBytes / segmentSize));
2483
3645
  const encryptor = new Encryptor({ key: key2, header: header2 });
2484
3646
  await encryptor.init();
3647
+ const segmentSize = encryptor.segmentSize;
3648
+ const segments = Math.max(1, Math.ceil(totalBytes / segmentSize));
3649
+ let readBytes = 0;
3650
+ const changed = (what) => new UploadError(`The file changed while it was being sent: ${what} ${readBytes} of ${totalBytes} bytes`, "FILE_CHANGED");
2485
3651
  let headerPending = true;
2486
3652
  let segmentNumber = 0;
2487
3653
  let partNumber = 0;
@@ -2570,7 +3736,7 @@ async function runCryptoPipeline(options) {
2570
3736
  await emitFullParts();
2571
3737
  const encrypted = await encrypting;
2572
3738
  await wipe(plaintext);
2573
- log.debug(`encrypt segment=${segmentNumber} bytes=${plaintext.length} time=${Math.round(performance.now() - tEncStart)}ms`);
3739
+ log2.debug(`encrypt segment=${segmentNumber} bytes=${plaintext.length} time=${Math.round(performance.now() - tEncStart)}ms`);
2574
3740
  let partData;
2575
3741
  if (headerPending) {
2576
3742
  partData = new Uint8Array(header2.length + encrypted.length);
@@ -2587,337 +3753,131 @@ async function runCryptoPipeline(options) {
2587
3753
  const reader = stream.getReader();
2588
3754
  try {
2589
3755
  for (; ; ) {
2590
- if (signal?.aborted) throw abortError();
2591
- const { done, value } = await reader.read();
2592
- if (done) break;
2593
- if (value && value.length > 0) {
2594
- pending.push(value);
2595
- pendingBytes += value.length;
2596
- }
2597
- while (pendingBytes >= segmentSize) {
2598
- await encryptOneSegment(drainSegment(segmentSize), segmentNumber === segments - 1);
2599
- }
2600
- }
2601
- if (pendingBytes > 0 || segmentNumber === 0) {
2602
- await encryptOneSegment(drainSegment(pendingBytes), true);
2603
- }
2604
- await emitFullParts();
2605
- if (ciphertextPendingBytes > 0) {
2606
- await emitPart(await drainCiphertextPart(ciphertextPendingBytes));
2607
- }
2608
- } finally {
2609
- reader.releaseLock();
2610
- }
2611
- }
2612
- function blobToSegmentStream(blob, segmentSize) {
2613
- let offset = 0;
2614
- return new ReadableStream({
2615
- async pull(controller) {
2616
- if (offset >= blob.size) {
2617
- controller.close();
2618
- return;
2619
- }
2620
- const end = Math.min(offset + segmentSize, blob.size);
2621
- try {
2622
- const buf = await blob.slice(offset, end).arrayBuffer();
2623
- controller.enqueue(new Uint8Array(buf));
2624
- offset = end;
2625
- } catch (e) {
2626
- controller.error(e);
2627
- }
2628
- }
2629
- });
2630
- }
2631
- function runCryptoPipelineInWorker(worker, hasher, options) {
2632
- const { file, key: key2, header: header2, partSize, totalBytes, signal, initialCredits, onSegment, onPart } = options;
2633
- return new Promise((resolve2, reject) => {
2634
- let settled = false;
2635
- let workerDone = false;
2636
- let hashing = 0;
2637
- let partChain = Promise.resolve();
2638
- const fail = (err) => {
2639
- if (settled) return;
2640
- settled = true;
2641
- reject(err);
2642
- };
2643
- const maybeFinish = () => {
2644
- if (!workerDone || hashing > 0) return;
2645
- void partChain.then(() => {
2646
- if (settled) return;
2647
- settled = true;
2648
- resolve2();
2649
- });
2650
- };
2651
- if (signal) {
2652
- if (signal.aborted) {
2653
- fail(abortError());
2654
- return;
2655
- }
2656
- signal.addEventListener("abort", () => fail(abortError()), { once: true });
2657
- }
2658
- worker.onerror = hasher.onerror = (event) => {
2659
- fail(new Error(`crypto worker crashed: ${String(event?.message ?? event)}`));
2660
- };
2661
- worker.onmessage = (event) => {
2662
- const msg = event.data;
2663
- if (msg.type === "segment") {
2664
- onSegment?.(msg.segmentNumber);
2665
- return;
2666
- }
2667
- if (msg.type === "part") {
2668
- hashing += 1;
2669
- hasher.postMessage(
2670
- { type: "md5", partNumber: msg.partNumber, buffer: msg.buffer },
2671
- [msg.buffer]
2672
- );
2673
- return;
2674
- }
2675
- if (msg.type === "done") {
2676
- workerDone = true;
2677
- maybeFinish();
2678
- return;
2679
- }
2680
- if (msg.type === "error") fail(new Error(msg.message));
2681
- };
2682
- hasher.onmessage = (event) => {
2683
- const msg = event.data;
2684
- if (msg.type !== "md5") return;
2685
- hashing -= 1;
2686
- const ciphertext = new Uint8Array(msg.buffer);
2687
- partChain = partChain.then(async () => {
2688
- if (settled) return;
2689
- await onPart(msg.partNumber, ciphertext, msg.md5);
2690
- worker.postMessage({ type: "credit" });
2691
- }).catch(fail);
2692
- maybeFinish();
2693
- };
2694
- const keyBuf = new ArrayBuffer(key2.length);
2695
- new Uint8Array(keyBuf).set(key2);
2696
- const headerBuf = header2.slice().buffer;
2697
- worker.postMessage(
2698
- { type: "start", file, key: keyBuf, header: headerBuf, partSize, totalBytes, credits: initialCredits },
2699
- [keyBuf, headerBuf]
2700
- );
2701
- });
2702
- }
2703
- var cryptoWorkerFactory = null;
2704
- function getCryptoWorkerFactory() {
2705
- return cryptoWorkerFactory;
2706
- }
2707
- var UploadError = class extends Error {
2708
- constructor(message, code, httpStatus, partNumber, retryable = false) {
2709
- super(message);
2710
- this.code = code;
2711
- this.httpStatus = httpStatus;
2712
- this.partNumber = partNumber;
2713
- this.retryable = retryable;
2714
- this.name = "UploadError";
2715
- }
2716
- };
2717
- function toUploadError(err, fallbackMessage) {
2718
- if (err instanceof UploadError) return err;
2719
- if (err instanceof DOMException && err.name === "AbortError") {
2720
- return new UploadError("Upload aborted", "ABORTED");
2721
- }
2722
- return new UploadError(err instanceof Error ? err.message : fallbackMessage, "UNKNOWN");
2723
- }
2724
- async function uploadErrorFromResponse(resp, what, code, partNumber) {
2725
- const refusal = await errorFromResponse(resp, String(resp.status));
2726
- return new UploadError(
2727
- `${what}: ${refusal.message}`,
2728
- resp.status === 426 ? "CLIENT_OUTDATED" : code,
2729
- resp.status,
2730
- partNumber
2731
- );
2732
- }
2733
- var log2 = createLogger("upload");
2734
- var DEFAULT_TRANSPORT_POLICY = {
2735
- retryBackoffMs: upload_default.upload.RETRY_BACKOFF_MS,
2736
- retryJitterRatio: upload_default.upload.RETRY_JITTER_RATIO,
2737
- stallNoticeMs: upload_default.upload.STALL_NOTICE_MS,
2738
- maxStallMs: upload_default.upload.MAX_STALL_MS,
2739
- putFloorBytesPerSecond: upload_default.upload.PUT_FLOOR_BYTES_PER_SECOND,
2740
- putMinDeadlineMs: upload_default.upload.PUT_MIN_DEADLINE_MS,
2741
- controlTimeoutMs: upload_default.upload.CONTROL_TIMEOUT_MS,
2742
- completeTimeoutMs: upload_default.upload.COMPLETE_TIMEOUT_MS,
2743
- poolStart: upload_default.upload.PART_POOL_START,
2744
- poolMax: upload_default.upload.PART_POOL_MAX,
2745
- poolMin: upload_default.upload.PART_POOL_MIN,
2746
- poolGrowRatio: upload_default.upload.PART_POOL_GROW_RATIO,
2747
- poolShrinkRatio: upload_default.upload.PART_POOL_SHRINK_RATIO,
2748
- partQueueLimit: upload_default.upload.PART_QUEUE_LIMIT,
2749
- hedgeMinInflightMs: upload_default.upload.HEDGE_MIN_INFLIGHT_MS,
2750
- hedgeLagFactor: upload_default.upload.HEDGE_LAG_FACTOR,
2751
- hedgePollMs: upload_default.upload.HEDGE_POLL_MS,
2752
- livenessSilenceMs: upload_default.upload.LIVENESS_SILENCE_MS,
2753
- verifyPollBackoffMs: upload_default.upload.VERIFY_POLL_BACKOFF_MS,
2754
- verifyFallbackWaitMs: upload_default.upload.VERIFY_FALLBACK_WAIT_MS,
2755
- speedWindowMs: upload_default.upload.PROGRESS_SPEED_WINDOW_MS
2756
- };
2757
- function resolveTransportPolicy(overrides) {
2758
- return { ...DEFAULT_TRANSPORT_POLICY, ...overrides };
2759
- }
2760
- function putDeadlineMs(bytes, policy) {
2761
- return Math.max(policy.putMinDeadlineMs, Math.ceil(bytes / policy.putFloorBytesPerSecond * 1e3));
2762
- }
2763
- function withDeadline(base, ms) {
2764
- const statics = globalThis.AbortSignal;
2765
- if (typeof statics?.timeout !== "function") return base;
2766
- const deadline = statics.timeout(ms);
2767
- if (!base) return deadline;
2768
- if (typeof statics.any !== "function") return base;
2769
- return statics.any([base, deadline]);
2770
- }
2771
- async function policyFetch(url, init2, timeoutMs, signal) {
2772
- try {
2773
- return await fetch(url, { ...init2, signal: withDeadline(signal, timeoutMs) });
2774
- } catch (err) {
2775
- if (signal?.aborted) throw new UploadError("Upload aborted", "ABORTED");
2776
- throw new UploadError(
2777
- `Request failed: ${err instanceof Error ? err.message : String(err)}`,
2778
- "NETWORK",
2779
- void 0,
2780
- void 0,
2781
- true
2782
- );
2783
- }
2784
- }
2785
- function classifyStatus2(status) {
2786
- if (status === 408 || status === 429 || status >= 500) return "retryable";
2787
- return "terminal";
2788
- }
2789
- function classifyStorageFailure(failure) {
2790
- if (failure.code === "ABORTED") return "terminal";
2791
- if (failure.code === "BAD_DIGEST") return "retryable";
2792
- if (failure.httpStatus === void 0) return "retryable";
2793
- if (failure.httpStatus === 403) return "refresh_url";
2794
- return classifyStatus2(failure.httpStatus);
2795
- }
2796
- function classifyControlFailure(failure) {
2797
- if (failure.code === "ABORTED") return "terminal";
2798
- if (failure.httpStatus === void 0) return "retryable";
2799
- return classifyStatus2(failure.httpStatus);
2800
- }
2801
- var StallClock = class {
2802
- constructor(policy, onState, now = () => performance.now()) {
2803
- this.policy = policy;
2804
- this.onState = onState;
2805
- this.now = now;
2806
- this.failingSince = null;
2807
- this.current = "running";
2808
- this.noticeTimer = null;
2809
- this.retriesSinceDelivery = 0;
2810
- }
2811
- get state() {
2812
- return this.current;
2813
- }
2814
- /**
2815
- * The connections are known to be dead (the browser went offline, or every
2816
- * socket of the upload has been silent): say so now. Nothing failed, so the
2817
- * give-up clock does not start; the next delivery clears it.
2818
- */
2819
- connectionLost() {
2820
- this.setState("stalled");
2821
- }
2822
- /** Storage (or the API) confirmed bytes: the upload is alive. */
2823
- delivered() {
2824
- this.failingSince = null;
2825
- this.retriesSinceDelivery = 0;
2826
- this.clearNotice();
2827
- this.setState("running");
2828
- }
2829
- /** True when the upload has failed, delivering nothing, for `maxStallMs`. */
2830
- exhausted() {
2831
- return this.failingSince !== null && this.now() - this.failingSince >= this.policy.maxStallMs;
2832
- }
2833
- /**
2834
- * A retryable failure happened. Flips to `stalled` once the failing has
2835
- * lasted long enough — now, or later via a timer, so the notice is on
2836
- * time even when the next attempt sits out a 30 s backoff.
2837
- */
2838
- failed() {
2839
- this.retriesSinceDelivery += 1;
2840
- this.failingSince ?? (this.failingSince = this.now());
2841
- const remaining = this.policy.stallNoticeMs - (this.now() - this.failingSince);
2842
- if (remaining <= 0) {
2843
- this.setState("stalled");
2844
- } else if (this.noticeTimer === null && this.current === "running") {
2845
- this.noticeTimer = setTimeout(() => {
2846
- this.noticeTimer = null;
2847
- this.setState("stalled");
2848
- }, remaining);
3756
+ if (signal?.aborted) throw abortError();
3757
+ const { done, value } = await reader.read();
3758
+ if (done) break;
3759
+ if (value && value.length > 0) {
3760
+ readBytes += value.length;
3761
+ if (readBytes > totalBytes) throw changed("it gave more than");
3762
+ pending.push(value);
3763
+ pendingBytes += value.length;
3764
+ }
3765
+ while (pendingBytes >= segmentSize) {
3766
+ await encryptOneSegment(drainSegment(segmentSize), segmentNumber === segments - 1);
3767
+ }
2849
3768
  }
2850
- }
2851
- /** Stop the pending notice; call when the upload ends either way. */
2852
- dispose() {
2853
- this.clearNotice();
2854
- }
2855
- clearNotice() {
2856
- if (this.noticeTimer !== null) {
2857
- clearTimeout(this.noticeTimer);
2858
- this.noticeTimer = null;
3769
+ if (readBytes < totalBytes) throw changed("it ended at");
3770
+ if (pendingBytes > 0 || segmentNumber === 0) {
3771
+ await encryptOneSegment(drainSegment(pendingBytes), true);
2859
3772
  }
3773
+ await emitFullParts();
3774
+ if (ciphertextPendingBytes > 0) {
3775
+ await emitPart(await drainCiphertextPart(ciphertextPendingBytes));
3776
+ }
3777
+ } finally {
3778
+ reader.releaseLock();
2860
3779
  }
2861
- setState(next) {
2862
- if (next === this.current) return;
2863
- this.current = next;
2864
- this.onState?.(next);
2865
- }
2866
- };
2867
- function abortableDelay(ms, signal) {
2868
- return new Promise((resolve2, reject) => {
2869
- if (signal?.aborted) {
2870
- reject(new UploadError("Upload aborted", "ABORTED"));
2871
- return;
3780
+ }
3781
+ function blobToSegmentStream(blob, segmentSize) {
3782
+ let offset = 0;
3783
+ return new ReadableStream({
3784
+ async pull(controller) {
3785
+ if (offset >= blob.size) {
3786
+ controller.close();
3787
+ return;
3788
+ }
3789
+ const end = Math.min(offset + segmentSize, blob.size);
3790
+ try {
3791
+ const buf = await blob.slice(offset, end).arrayBuffer();
3792
+ controller.enqueue(new Uint8Array(buf));
3793
+ offset = end;
3794
+ } catch (e) {
3795
+ controller.error(e);
3796
+ }
2872
3797
  }
2873
- const onAbort = () => {
2874
- clearTimeout(timer);
2875
- reject(new UploadError("Upload aborted", "ABORTED"));
2876
- };
2877
- const timer = setTimeout(() => {
2878
- signal?.removeEventListener("abort", onAbort);
2879
- resolve2();
2880
- }, ms);
2881
- signal?.addEventListener("abort", onAbort, { once: true });
2882
3798
  });
2883
3799
  }
2884
- async function retrying(step, options) {
2885
- const { clock, policy, signal, classify, what } = options;
2886
- let after;
2887
- let refreshedInARow = 0;
2888
- for (let attempt = 0; ; attempt++) {
2889
- if (signal?.aborted) throw new UploadError("Upload aborted", "ABORTED");
2890
- try {
2891
- return await step({ attempt, after });
2892
- } catch (err) {
2893
- const failure = toUploadError(err, `${what} failed`);
2894
- if (failure.code === "ABORTED") throw failure;
2895
- const failureClass = classify(failure);
2896
- if (failureClass === "terminal") throw failure;
2897
- if (clock.exhausted()) {
2898
- throw new UploadError(
2899
- `${what}: no progress for ${Math.round(policy.maxStallMs / 1e3)} s \u2014 ${failure.message}`,
2900
- failure.code,
2901
- failure.httpStatus,
2902
- failure.partNumber,
2903
- false
2904
- );
3800
+ function runCryptoPipelineInWorker(worker, hasher, options) {
3801
+ const { file, key: key2, header: header2, partSize, totalBytes, signal, initialCredits, onSegment, onPart } = options;
3802
+ return new Promise((resolve2, reject) => {
3803
+ let settled = false;
3804
+ let workerDone = false;
3805
+ let hashing = 0;
3806
+ let partChain = Promise.resolve();
3807
+ const fail = (err) => {
3808
+ if (settled) return;
3809
+ settled = true;
3810
+ reject(err);
3811
+ };
3812
+ const maybeFinish = () => {
3813
+ if (!workerDone || hashing > 0) return;
3814
+ void partChain.then(() => {
3815
+ if (settled) return;
3816
+ settled = true;
3817
+ resolve2();
3818
+ });
3819
+ };
3820
+ if (signal) {
3821
+ if (signal.aborted) {
3822
+ fail(abortError());
3823
+ return;
2905
3824
  }
2906
- clock.failed();
2907
- refreshedInARow = failureClass === "refresh_url" ? refreshedInARow + 1 : 0;
2908
- const immediate = failureClass === "refresh_url" && refreshedInARow === 1;
2909
- const base = policy.retryBackoffMs[Math.min(attempt, policy.retryBackoffMs.length - 1)] ?? 0;
2910
- const jitter = 1 + (Math.random() * 2 - 1) * policy.retryJitterRatio;
2911
- const delay = immediate ? 0 : Math.round(base * jitter);
2912
- log2.debug(
2913
- `retry ${what} attempt=${attempt + 2} in ${delay}ms after ${failure.code}${failure.httpStatus ? " " + failure.httpStatus : ""} (${failureClass})`
2914
- );
2915
- after = failureClass;
2916
- await abortableDelay(delay, signal);
3825
+ signal.addEventListener("abort", () => fail(abortError()), { once: true });
2917
3826
  }
2918
- }
3827
+ worker.onerror = hasher.onerror = (event) => {
3828
+ fail(new Error(`crypto worker crashed: ${String(event?.message ?? event)}`));
3829
+ };
3830
+ worker.onmessage = (event) => {
3831
+ const msg = event.data;
3832
+ if (msg.type === "segment") {
3833
+ onSegment?.(msg.segmentNumber);
3834
+ return;
3835
+ }
3836
+ if (msg.type === "part") {
3837
+ hashing += 1;
3838
+ hasher.postMessage(
3839
+ { type: "md5", partNumber: msg.partNumber, buffer: msg.buffer },
3840
+ [msg.buffer]
3841
+ );
3842
+ return;
3843
+ }
3844
+ if (msg.type === "done") {
3845
+ workerDone = true;
3846
+ maybeFinish();
3847
+ return;
3848
+ }
3849
+ if (msg.type === "error") fail(new Error(msg.message));
3850
+ };
3851
+ hasher.onmessage = (event) => {
3852
+ const msg = event.data;
3853
+ if (msg.type !== "md5") return;
3854
+ hashing -= 1;
3855
+ const ciphertext = new Uint8Array(msg.buffer);
3856
+ partChain = partChain.then(async () => {
3857
+ if (settled) return;
3858
+ await onPart(msg.partNumber, ciphertext, msg.md5);
3859
+ worker.postMessage({ type: "credit" });
3860
+ }).catch(fail);
3861
+ maybeFinish();
3862
+ };
3863
+ const keyBuf = new ArrayBuffer(key2.length);
3864
+ new Uint8Array(keyBuf).set(key2);
3865
+ const headerBuf = header2.slice().buffer;
3866
+ worker.postMessage(
3867
+ { type: "start", file, key: keyBuf, header: headerBuf, partSize, totalBytes, credits: initialCredits },
3868
+ [keyBuf, headerBuf]
3869
+ );
3870
+ });
3871
+ }
3872
+ var cryptoWorkerFactory = null;
3873
+ function getCryptoWorkerFactory() {
3874
+ return cryptoWorkerFactory;
2919
3875
  }
2920
3876
  var log3 = createLogger("upload");
3877
+ function silenceHeard(look) {
3878
+ if (look.now - look.lastLookAt > 2 * look.every) return false;
3879
+ return look.now - look.lastActivityAt >= look.silenceMs;
3880
+ }
2921
3881
  var BAD_DIGEST_MARKER = "<Code>BadDigest</Code>";
2922
3882
  var HEDGE_MAX_PER_PART = 2;
2923
3883
  function createAuthHeaders(auth) {
@@ -2951,7 +3911,7 @@ async function multipartUpload(options) {
2951
3911
  async function multipartUploadFromFile(options) {
2952
3912
  const { file, partSize } = options;
2953
3913
  return multipartUploadStream({
2954
- stream: blobToSegmentStream(file, SEGMENT_SIZE),
3914
+ stream: blobToSegmentStream(file, parseHeader(options.header).segmentSize),
2955
3915
  totalBytes: file.size,
2956
3916
  sealId: options.sealId,
2957
3917
  fileId: options.fileId,
@@ -2987,6 +3947,7 @@ async function multipartUploadStream(options) {
2987
3947
  onConflict
2988
3948
  } = options;
2989
3949
  const policy = resolveTransportPolicy(options.transport);
3950
+ const time = policy.clock;
2990
3951
  if (key2.length !== 32) {
2991
3952
  throw new UploadError("Key must be 32 bytes", "ENCRYPTION_FAILED");
2992
3953
  }
@@ -3009,7 +3970,7 @@ async function multipartUploadStream(options) {
3009
3970
  let firstPutStartedAt = null;
3010
3971
  let speedBps;
3011
3972
  const noteDelivered = (bytes) => {
3012
- const now = performance.now();
3973
+ const now = time.now();
3013
3974
  speedSamples.push({ at: now, bytes });
3014
3975
  const windowStart = Math.max(firstPutStartedAt ?? now, now - policy.speedWindowMs);
3015
3976
  while (speedSamples.length > 0 && speedSamples[0].at < windowStart) speedSamples.shift();
@@ -3034,10 +3995,9 @@ async function multipartUploadStream(options) {
3034
3995
  attempt: clock.retriesSinceDelivery + 1
3035
3996
  });
3036
3997
  };
3037
- const clock = new StallClock(policy, () => report(lastPhase));
3998
+ const clock = new StallClock(policy, () => report(lastPhase), time.now);
3038
3999
  const teardown = new AbortController();
3039
- const combine = globalThis.AbortSignal?.any;
3040
- const runSignal = signal && typeof combine === "function" ? combine([signal, teardown.signal]) : signal ?? teardown.signal;
4000
+ const runSignal = signal ? anySignal([signal, teardown.signal]) : teardown.signal;
3041
4001
  const controlStep = (what, step) => retrying(step, { clock, policy, signal: runSignal, classify: classifyControlFailure, what });
3042
4002
  const abortUpload = async (_deliberate) => {
3043
4003
  keyCopy.fill(0);
@@ -3046,7 +4006,7 @@ async function multipartUploadStream(options) {
3046
4006
  const abortSessionBestEffort = (discardFile) => {
3047
4007
  if (!uploadId) return;
3048
4008
  try {
3049
- void fetch(`${baseUrl}/upload/multipart/abort`, {
4009
+ void transportFetch(`${baseUrl}/upload/multipart/abort`, {
3050
4010
  method: "POST",
3051
4011
  headers: { "Content-Type": "application/json", ...authHeaders },
3052
4012
  // `discard_file`: the caller cancelled, so the row this upload was
@@ -3059,6 +4019,7 @@ async function multipartUploadStream(options) {
3059
4019
  } catch {
3060
4020
  }
3061
4021
  };
4022
+ let streamed = false;
3062
4023
  const presignedUrlCache = /* @__PURE__ */ new Map();
3063
4024
  let presignPrefetchInFlight = null;
3064
4025
  let uploadError = null;
@@ -3074,10 +4035,10 @@ async function multipartUploadStream(options) {
3074
4035
  let roomWaiters = [];
3075
4036
  const fullPartPace = [];
3076
4037
  const partsInFlight = /* @__PURE__ */ new Set();
3077
- let lastSocketActivityAt = performance.now();
4038
+ let lastSocketActivityAt = time.now();
3078
4039
  let socketActivityObservable = false;
3079
4040
  const reconnectAllParts = (why) => {
3080
- lastSocketActivityAt = performance.now();
4041
+ lastSocketActivityAt = time.now();
3081
4042
  for (const part of [...partsInFlight]) part.reconnect(why);
3082
4043
  };
3083
4044
  function recordDelivery(item, elapsedMs) {
@@ -3091,7 +4052,7 @@ async function multipartUploadStream(options) {
3091
4052
  poolCeiling = poolSize;
3092
4053
  lastRoundRate = null;
3093
4054
  round += 1;
3094
- roundStartedAt = performance.now();
4055
+ roundStartedAt = time.now();
3095
4056
  roundBytes = 0;
3096
4057
  roundDeliveries = 0;
3097
4058
  return;
@@ -3101,7 +4062,7 @@ async function multipartUploadStream(options) {
3101
4062
  roundBytes += bytes;
3102
4063
  roundDeliveries += 1;
3103
4064
  if (roundDeliveries < poolSize || roundStartedAt === null) return;
3104
- const roundMs = performance.now() - roundStartedAt;
4065
+ const roundMs = time.now() - roundStartedAt;
3105
4066
  if (roundMs <= 0) return;
3106
4067
  const roundRate = roundBytes / roundMs;
3107
4068
  if (lastRoundRate === null) {
@@ -3113,12 +4074,12 @@ async function multipartUploadStream(options) {
3113
4074
  }
3114
4075
  lastRoundRate = roundRate;
3115
4076
  round += 1;
3116
- roundStartedAt = performance.now();
4077
+ roundStartedAt = time.now();
3117
4078
  roundBytes = 0;
3118
4079
  roundDeliveries = 0;
3119
4080
  }
3120
4081
  function hedgeDue(item, lastLaunchAt) {
3121
- const inFlightMs = performance.now() - lastLaunchAt;
4082
+ const inFlightMs = time.now() - lastLaunchAt;
3122
4083
  if (inFlightMs < policy.hedgeMinInflightMs) return false;
3123
4084
  const flowsNow = runningParts.size;
3124
4085
  const peers = fullPartPace.filter((p) => p.flows >= flowsNow).map((p) => p.rate);
@@ -3128,22 +4089,22 @@ async function multipartUploadStream(options) {
3128
4089
  return item.ciphertext.length / inFlightMs * policy.hedgeLagFactor < medianRate;
3129
4090
  }
3130
4091
  async function transportPut(ciphertext, contentMd52, partNumber, presignedUrl, copySignal, liveness) {
3131
- if (typeof XMLHttpRequest !== "undefined" && typeof document !== "undefined") {
4092
+ if (!hostNamedTransport() && typeof XMLHttpRequest !== "undefined" && typeof document !== "undefined") {
3132
4093
  return await new Promise((resolve2, reject) => {
3133
4094
  const xhr = new XMLHttpRequest();
3134
4095
  let settled = false;
3135
4096
  socketActivityObservable = true;
3136
4097
  xhr.upload.onprogress = (event) => {
3137
4098
  liveness.onSocketActivity(event.loaded, event.lengthComputable ? event.total : ciphertext.length);
3138
- clearTimeout(deadline);
3139
- deadline = armDeadline();
4099
+ cancelDeadline();
4100
+ cancelDeadline = armDeadline();
3140
4101
  };
3141
- const armDeadline = () => setTimeout(() => {
4102
+ const armDeadline = () => time.after(putDeadlineMs(ciphertext.length, policy), () => {
3142
4103
  if (!settled) liveness.onDeadline();
3143
- }, putDeadlineMs(ciphertext.length, policy));
3144
- let deadline = armDeadline();
4104
+ });
4105
+ let cancelDeadline = armDeadline();
3145
4106
  const cleanup = () => {
3146
- clearTimeout(deadline);
4107
+ cancelDeadline();
3147
4108
  copySignal.removeEventListener("abort", abortFromSignal);
3148
4109
  };
3149
4110
  const abortFromSignal = () => {
@@ -3189,7 +4150,7 @@ async function multipartUploadStream(options) {
3189
4150
  }
3190
4151
  let putResponse;
3191
4152
  try {
3192
- putResponse = await fetch(presignedUrl, {
4153
+ putResponse = await transportFetch(presignedUrl, {
3193
4154
  method: "PUT",
3194
4155
  headers: { "Content-MD5": contentMd52 },
3195
4156
  body: ciphertext,
@@ -3241,9 +4202,11 @@ async function multipartUploadStream(options) {
3241
4202
  return outcome.etag;
3242
4203
  }
3243
4204
  async function hedgedPut(item, presignedUrl) {
3244
- const t0 = performance.now();
3245
- let hedgeTicker = null;
4205
+ const t0 = time.now();
4206
+ let stopHedgeTicker = () => {
4207
+ };
3246
4208
  let hedgeCount = 0;
4209
+ let deadlines = 0;
3247
4210
  let lastLaunchAt = t0;
3248
4211
  let current = null;
3249
4212
  let replace = () => {
@@ -3268,14 +4231,24 @@ async function multipartUploadStream(options) {
3268
4231
  else runSignal?.addEventListener("abort", onUploadEnd, { once: true });
3269
4232
  const copy = { ctl, unsent: true, ended: Promise.resolve() };
3270
4233
  current = copy;
3271
- lastLaunchAt = performance.now();
4234
+ lastLaunchAt = time.now();
3272
4235
  lastSocketActivityAt = lastLaunchAt;
3273
4236
  copy.ended = transportPut(item.ciphertext, item.contentMd5, item.partNumber, presignedUrl, ctl.signal, {
3274
4237
  onSocketActivity: (loaded, total) => {
3275
- lastSocketActivityAt = performance.now();
4238
+ lastSocketActivityAt = time.now();
3276
4239
  copy.unsent = loaded < total;
3277
4240
  },
3278
- onDeadline: () => replace("copy deadline", false)
4241
+ onDeadline: () => {
4242
+ if (++deadlines < 2) return replace("copy deadline", false, false);
4243
+ if (current !== copy) return;
4244
+ settle(() => reject(new UploadError(
4245
+ `Part ${item.partNumber}: no answer from storage after a reconnect`,
4246
+ "NETWORK",
4247
+ void 0,
4248
+ item.partNumber,
4249
+ true
4250
+ )));
4251
+ }
3279
4252
  }).then(
3280
4253
  (outcome) => {
3281
4254
  if (current !== copy) return;
@@ -3294,11 +4267,11 @@ async function multipartUploadStream(options) {
3294
4267
  runSignal?.removeEventListener("abort", onUploadEnd);
3295
4268
  });
3296
4269
  };
3297
- replace = (why, spendsTicket) => {
4270
+ replace = (why, spendsTicket, handsBack = true) => {
3298
4271
  const old = current;
3299
4272
  if (settled || old === null || signal?.aborted) return;
3300
4273
  current = null;
3301
- hedgeCount = spendsTicket ? hedgeCount + 1 : 0;
4274
+ hedgeCount = spendsTicket ? hedgeCount + 1 : handsBack ? 0 : hedgeCount;
3302
4275
  log3.debug(`${spendsTicket ? "replace" : "reconnect"} part=${item.partNumber} (${why})`);
3303
4276
  old.ctl.abort();
3304
4277
  void old.ended.then(() => {
@@ -3311,14 +4284,14 @@ async function multipartUploadStream(options) {
3311
4284
  });
3312
4285
  };
3313
4286
  launch();
3314
- hedgeTicker = setInterval(() => {
4287
+ stopHedgeTicker = time.every(policy.hedgePollMs, () => {
3315
4288
  if (settled || signal?.aborted || current === null) return;
3316
4289
  if (hedgeCount >= HEDGE_MAX_PER_PART) return;
3317
4290
  if (!hedgeDue(item, lastLaunchAt)) return;
3318
- replace(`slower than its peers after ${Math.round(performance.now() - t0)}ms`, true);
3319
- }, policy.hedgePollMs);
4291
+ replace(`slower than its peers after ${Math.round(time.now() - t0)}ms`, true);
4292
+ });
3320
4293
  });
3321
- const tPut = performance.now();
4294
+ const tPut = time.now();
3322
4295
  uploadedParts.push({ part_number: item.partNumber, etag });
3323
4296
  processedBytes += item.ciphertext.length;
3324
4297
  noteDelivered(item.ciphertext.length);
@@ -3333,7 +4306,7 @@ async function multipartUploadStream(options) {
3333
4306
  partsInFlight.delete(inFlight);
3334
4307
  replace = () => {
3335
4308
  };
3336
- if (hedgeTicker !== null) clearInterval(hedgeTicker);
4309
+ stopHedgeTicker();
3337
4310
  current?.ctl.abort();
3338
4311
  }
3339
4312
  }
@@ -3399,7 +4372,7 @@ async function multipartUploadStream(options) {
3399
4372
  }
3400
4373
  async function runPart(item) {
3401
4374
  await yieldToMain();
3402
- roundStartedAt ?? (roundStartedAt = performance.now());
4375
+ roundStartedAt ?? (roundStartedAt = time.now());
3403
4376
  firstPutStartedAt ?? (firstPutStartedAt = roundStartedAt);
3404
4377
  item.round = round;
3405
4378
  item.flowsAtStart = runningParts.size;
@@ -3468,15 +4441,19 @@ async function multipartUploadStream(options) {
3468
4441
  scope.addEventListener?.("online", onOnline);
3469
4442
  scope.addEventListener?.("offline", onOffline);
3470
4443
  connection?.addEventListener?.("change", onConnectionChange);
3471
- const silenceCheck = setInterval(() => {
3472
- if (!socketActivityObservable || partsInFlight.size === 0) return;
3473
- if (performance.now() - lastSocketActivityAt < policy.livenessSilenceMs) return;
4444
+ const every = Math.max(10, policy.livenessSilenceMs / 4);
4445
+ let lastLookAt = time.now();
4446
+ const stopSilenceCheck = time.every(every, () => {
4447
+ const now = time.now();
4448
+ const silent = silenceHeard({ now, lastLookAt, every, lastActivityAt: lastSocketActivityAt, silenceMs: policy.livenessSilenceMs });
4449
+ lastLookAt = now;
4450
+ if (!socketActivityObservable || partsInFlight.size === 0 || !silent) return;
3474
4451
  if (![...partsInFlight].some((part) => part.hasUnsentBytes())) return;
3475
4452
  clock.connectionLost();
3476
4453
  reconnectAllParts("every socket silent");
3477
- }, Math.max(10, policy.livenessSilenceMs / 4));
4454
+ });
3478
4455
  return () => {
3479
- clearInterval(silenceCheck);
4456
+ stopSilenceCheck();
3480
4457
  scope.removeEventListener?.("online", onOnline);
3481
4458
  scope.removeEventListener?.("offline", onOffline);
3482
4459
  connection?.removeEventListener?.("change", onConnectionChange);
@@ -3597,6 +4574,7 @@ async function multipartUploadStream(options) {
3597
4574
  if (signal?.aborted) {
3598
4575
  await abortUpload(signal?.aborted === true);
3599
4576
  }
4577
+ streamed = true;
3600
4578
  onStreamed?.();
3601
4579
  let completeAttempted = false;
3602
4580
  let conflictWith;
@@ -3637,7 +4615,8 @@ async function multipartUploadStream(options) {
3637
4615
  } catch (error) {
3638
4616
  keyCopy.fill(0);
3639
4617
  const failure = toUploadError(error, "Unknown upload error");
3640
- abortSessionBestEffort(failure.code === "ABORTED");
4618
+ const askLater = streamed && failure.code !== "ABORTED" && (failure.httpStatus === void 0 || failure.httpStatus >= 500);
4619
+ if (!askLater) abortSessionBestEffort(failure.code === "ABORTED");
3641
4620
  throw failure;
3642
4621
  } finally {
3643
4622
  stopWatchingLiveness();
@@ -3645,88 +4624,6 @@ async function multipartUploadStream(options) {
3645
4624
  teardown.abort();
3646
4625
  }
3647
4626
  }
3648
- var ENCRYPTED_FILE_FALLBACK = "Encrypted file";
3649
- var ENCRYPTED_MIME_FALLBACK = "application/octet-stream";
3650
- function metadataFieldAAD(field) {
3651
- return new TextEncoder().encode(`field:${field}`);
3652
- }
3653
- async function encryptMetadataField(plaintext, key2, field) {
3654
- const nonce = crypto.getRandomValues(new Uint8Array(12));
3655
- const cryptoKey = await crypto.subtle.importKey(
3656
- "raw",
3657
- key2.buffer.slice(key2.byteOffset, key2.byteOffset + key2.byteLength),
3658
- { name: "AES-GCM" },
3659
- false,
3660
- ["encrypt"]
3661
- );
3662
- const params = { name: "AES-GCM", iv: nonce, tagLength: 128 };
3663
- if (field) {
3664
- const aad = metadataFieldAAD(field);
3665
- params.additionalData = aad.buffer.slice(aad.byteOffset, aad.byteOffset + aad.byteLength);
3666
- }
3667
- const ciphertext = await crypto.subtle.encrypt(params, cryptoKey, new TextEncoder().encode(plaintext));
3668
- return { ciphertext: bytesToBase64(new Uint8Array(ciphertext)), nonce: bytesToBase64(nonce) };
3669
- }
3670
- function isAeadTagFailure(error) {
3671
- const name2 = error?.name;
3672
- return name2 === "OperationError";
3673
- }
3674
- async function decryptMetadataField(encrypted, nonce, key2, field) {
3675
- const ciphertext = base64ToBytes(encrypted);
3676
- const iv = base64ToBytes(nonce);
3677
- const run = async (aad) => {
3678
- const params = { name: "AES-GCM", iv };
3679
- if (aad) params.additionalData = aad;
3680
- const plaintext = await crypto.subtle.decrypt(params, key2, ciphertext);
3681
- return new TextDecoder().decode(plaintext);
3682
- };
3683
- if (!field) return run(void 0);
3684
- try {
3685
- return await run(metadataFieldAAD(field));
3686
- } catch (boundError) {
3687
- if (!isAeadTagFailure(boundError)) throw boundError;
3688
- return run(void 0);
3689
- }
3690
- }
3691
- async function decryptFileMetadata(file, key2) {
3692
- let name2 = file.name || ENCRYPTED_FILE_FALLBACK;
3693
- let mime = file.mime || ENCRYPTED_MIME_FALLBACK;
3694
- if (file.name_encrypted && file.name_nonce && file.name_nonce.length > 0) {
3695
- try {
3696
- name2 = await decryptMetadataField(file.name_encrypted, file.name_nonce, key2, "name");
3697
- } catch {
3698
- name2 = ENCRYPTED_FILE_FALLBACK;
3699
- }
3700
- }
3701
- if (file.mime_encrypted && file.mime_nonce && file.mime_nonce.length > 0) {
3702
- try {
3703
- mime = await decryptMetadataField(file.mime_encrypted, file.mime_nonce, key2, "mime");
3704
- } catch {
3705
- mime = ENCRYPTED_MIME_FALLBACK;
3706
- }
3707
- }
3708
- return { name: name2, mime };
3709
- }
3710
- async function importKeyForMetadata(keyBytes) {
3711
- return crypto.subtle.importKey(
3712
- "raw",
3713
- keyBytes,
3714
- { name: "AES-GCM" },
3715
- false,
3716
- ["decrypt"]
3717
- );
3718
- }
3719
- async function decryptFileMetadataWithBytes(file, keyBytes) {
3720
- try {
3721
- const key2 = await importKeyForMetadata(keyBytes);
3722
- return decryptFileMetadata(file, key2);
3723
- } catch {
3724
- return {
3725
- name: file.name || ENCRYPTED_FILE_FALLBACK,
3726
- mime: file.mime || ENCRYPTED_MIME_FALLBACK
3727
- };
3728
- }
3729
- }
3730
4627
  var DEFAULT_POLICY = {
3731
4628
  multipartThresholdBytes: upload_default.upload.MULTIPART_THRESHOLD_BYTES,
3732
4629
  partSizeBytes: upload_default.upload.DEFAULT_PART_SIZE_BYTES,
@@ -3802,6 +4699,7 @@ var UploadSession = class {
3802
4699
  constructor(init2, run) {
3803
4700
  this.run = run;
3804
4701
  this.cancelled = false;
4702
+ this.running = null;
3805
4703
  this.ctx = init2.ctx;
3806
4704
  this.policy = init2.policy;
3807
4705
  this.sealId = init2.sealId;
@@ -3831,13 +4729,12 @@ var UploadSession = class {
3831
4729
  if (this.cancelled) {
3832
4730
  throw new UploadError("Upload session was cancelled", "ABORTED");
3833
4731
  }
3834
- try {
3835
- return await this.run(this, callbacks);
3836
- } catch (err) {
3837
- const failure = toUploadError(err, "Upload failed");
3838
- failure.session = this;
3839
- throw failure;
3840
- }
4732
+ this.running ?? (this.running = this.run(this, callbacks).catch((err) => {
4733
+ throw attachSession(toUploadError(err, "Upload failed"), this);
4734
+ }).finally(() => {
4735
+ this.running = null;
4736
+ }));
4737
+ return this.running;
3841
4738
  }
3842
4739
  /**
3843
4740
  * Give the registration back. A seal this upload created is revoked
@@ -3845,15 +4742,29 @@ var UploadSession = class {
3845
4742
  * which returns their bytes to the quota (the backend charges at
3846
4743
  * registration, not at delivery).
3847
4744
  *
4745
+ * A host without an owner token (an organisation's seal under a member's
4746
+ * session) gives its rows back by its own route, `ctx.revokeFilePath`.
4747
+ *
3848
4748
  * Best effort: the caller is cancelling, not asking for a second failure
3849
- * to handle. What this misses — a bearer-authenticated host with no owner
3850
- * token, a request that does not get through — the server's sweep of
3851
- * stale `pending` rows collects.
4749
+ * to handle. What this misses — a request that does not get through — the
4750
+ * server's sweep of stale `pending` rows collects.
3852
4751
  */
3853
4752
  async cancel() {
3854
4753
  this.cancelled = true;
3855
4754
  const ownerToken = ownerTokenOf(this.ctx);
3856
- if (!ownerToken) return;
4755
+ if (!ownerToken) {
4756
+ const template = this.ctx.revokeFilePath;
4757
+ if (!template || this.createdSeal) return;
4758
+ for (const entry of this.pending) {
4759
+ const path = template.replace("{sealId}", encodeURIComponent(this.sealId)).replace("{fileId}", encodeURIComponent(entry.fileId));
4760
+ await transportFetch(`${this.ctx.baseUrl}${path}`, {
4761
+ method: "DELETE",
4762
+ headers: createAuthHeaders(uploadAuthFor(this.ctx)),
4763
+ credentials: this.ctx.credentials ?? "include"
4764
+ }).catch(() => void 0);
4765
+ }
4766
+ return;
4767
+ }
3857
4768
  const api = new SealApi({ baseUrl: this.ctx.baseUrl, credentials: this.ctx.credentials ?? "include" });
3858
4769
  try {
3859
4770
  if (this.createdSeal) {
@@ -3880,8 +4791,7 @@ function pairRegisteredRows(rows, sentDigests, what) {
3880
4791
  throw new Error(`${what}: file record ${i} has no id \u2014 cannot upload ciphertext`);
3881
4792
  }
3882
4793
  if (row.sha256_hex === void 0) {
3883
- if (n === 1) return;
3884
- throw new Error(`${what}: file record ${i} carries no sha256_hex \u2014 refusing to pair ${n} files by position alone`);
4794
+ throw new Error(`${what}: file record ${i} carries no sha256_hex \u2014 refusing to pair it by position`);
3885
4795
  }
3886
4796
  if (row.sha256_hex !== sentDigests[i]) {
3887
4797
  throw new Error(
@@ -3959,6 +4869,7 @@ async function uploadPresignedSmallFile(opts) {
3959
4869
  ...ctx.onConflict ? { on_conflict: ctx.onConflict } : {}
3960
4870
  })
3961
4871
  }, transport.controlTimeoutMs, signal);
4872
+ if (response.status === 409) return false;
3962
4873
  if (!response.ok) throw await uploadErrorFromResponse(response, `Upload confirm failed${suffix}`, "NETWORK");
3963
4874
  const body = await response.json().catch(() => null);
3964
4875
  if (typeof body?.conflict_with === "string") opts.onConflictWith(body.conflict_with);
@@ -3984,15 +4895,16 @@ async function readUploadStatus(ctx, sealId, digest, authHeaders, transport, sig
3984
4895
  }
3985
4896
  }
3986
4897
  var REJECTED_STATUSES = /* @__PURE__ */ new Set(["failed", "size_mismatch", "verification_error"]);
4898
+ var DELIVERED_STATUSES = /* @__PURE__ */ new Set(["verified", "pending_verification"]);
3987
4899
  async function awaitVerification(opts) {
3988
4900
  const { ctx, sealId, digest, authHeaders, transport, signal, label } = opts;
3989
4901
  const ceilingMs = transport.verifyFallbackWaitMs;
3990
4902
  const startedAt = performance.now();
3991
4903
  const pauses = transport.verifyPollBackoffMs;
3992
4904
  for (let poll = 0; ; poll++) {
3993
- const pause = pauses[Math.min(poll, pauses.length - 1)] ?? 0;
3994
- if (performance.now() - startedAt + pause > ceilingMs) return "pending";
3995
- if (pause > 0) await abortableDelay(pause, signal);
4905
+ const pause2 = pauses[Math.min(poll, pauses.length - 1)] ?? 0;
4906
+ if (performance.now() - startedAt + pause2 > ceilingMs) return "pending";
4907
+ if (pause2 > 0) await abortableDelay(pause2, signal);
3996
4908
  const status = await readUploadStatus(ctx, sealId, digest, authHeaders, transport, signal);
3997
4909
  if (status === "verified") return "verified";
3998
4910
  if (status !== null && REJECTED_STATUSES.has(status)) {
@@ -4039,7 +4951,7 @@ async function uploadRegisteredFile(session, entry, callbacks = {}) {
4039
4951
  if (usesMultipart(file.size, policy)) {
4040
4952
  if (entry.streamed) {
4041
4953
  const held = await readUploadStatus(ctx, sealId, entry.sha256_hex, authHeaders, transport, signal);
4042
- if (held !== null && held !== "pending") {
4954
+ if (held !== null && DELIVERED_STATUSES.has(held)) {
4043
4955
  await settle(held === "verified");
4044
4956
  return;
4045
4957
  }
@@ -4095,6 +5007,7 @@ async function uploadRegisteredFile(session, entry, callbacks = {}) {
4095
5007
  const track = createFileProgress("single-put", (p) => onProgress?.(p));
4096
5008
  const totalBytes = entry.encryptedSize;
4097
5009
  let last = { phase: "encrypting", fraction: 0, delivered: false };
5010
+ let clock = null;
4098
5011
  const report = (phase, fraction, delivered = last.delivered) => {
4099
5012
  last = { phase, fraction, delivered };
4100
5013
  track({
@@ -4103,11 +5016,10 @@ async function uploadRegisteredFile(session, entry, callbacks = {}) {
4103
5016
  // A single request is all or nothing: 0 until storage confirms it.
4104
5017
  deliveredBytes: delivered ? totalBytes : 0,
4105
5018
  totalBytes,
4106
- state: clock.state,
4107
- attempt: clock.retriesSinceDelivery + 1
5019
+ state: clock?.state ?? "running",
5020
+ attempt: (clock?.retriesSinceDelivery ?? 0) + 1
4108
5021
  });
4109
5022
  };
4110
- const clock = new StallClock(transport, () => report(last.phase, last.fraction));
4111
5023
  if (!entry.prepared) {
4112
5024
  report("encrypting", 0);
4113
5025
  entry.prepared = await encryptBlob2(
@@ -4118,6 +5030,8 @@ async function uploadRegisteredFile(session, entry, callbacks = {}) {
4118
5030
  );
4119
5031
  }
4120
5032
  const ciphertext = entry.prepared;
5033
+ const transferClock = new StallClock(transport, () => report(last.phase, last.fraction));
5034
+ clock = transferClock;
4121
5035
  report("uploading", 0);
4122
5036
  let verified;
4123
5037
  try {
@@ -4130,14 +5044,14 @@ async function uploadRegisteredFile(session, entry, callbacks = {}) {
4130
5044
  onVerifying: () => report("verifying", 0, true),
4131
5045
  label: file.name,
4132
5046
  signal,
4133
- clock,
5047
+ clock: transferClock,
4134
5048
  transport,
4135
5049
  onConflictWith: (head) => {
4136
5050
  entry.conflictWith = head;
4137
5051
  }
4138
5052
  });
4139
5053
  } finally {
4140
- clock.dispose();
5054
+ transferClock.dispose();
4141
5055
  }
4142
5056
  report("verifying", 0.5, true);
4143
5057
  await settle(verified);
@@ -4165,8 +5079,8 @@ function applyAccessControl(sealPayload, ctx) {
4165
5079
  if (ctx.tier) sealPayload.tier = ctx.tier;
4166
5080
  }
4167
5081
  async function buildFileMeta(file, fileKey, size, sha256_hex, opts = {}) {
4168
- const nameEncrypted = await encryptMetadataField(file.name, fileKey, "name");
4169
- const mimeEncrypted = await encryptMetadataField(file.type || "application/octet-stream", fileKey, "mime");
5082
+ const nameEncrypted = await encryptMetadataField(opts.relativePath ?? file.name, fileKey, "name");
5083
+ const mimeEncrypted = await encryptMetadataField(file.type || guessMimeFromName(file.name), fileKey, "mime");
4170
5084
  const meta = {
4171
5085
  size,
4172
5086
  sha256_hex,
@@ -4176,11 +5090,6 @@ async function buildFileMeta(file, fileKey, size, sha256_hex, opts = {}) {
4176
5090
  mime_nonce: mimeEncrypted.nonce,
4177
5091
  encryption_version: aeon_format_default.current_format_version
4178
5092
  };
4179
- if (opts.relativePath !== void 0) {
4180
- const pathEncrypted = await encryptMetadataField(opts.relativePath, fileKey, "path");
4181
- meta.path_encrypted = pathEncrypted.ciphertext;
4182
- meta.path_nonce = pathEncrypted.nonce;
4183
- }
4184
5093
  if (opts.parentFolderId) {
4185
5094
  meta.parent_folder_id = opts.parentFolderId;
4186
5095
  }
@@ -4190,16 +5099,63 @@ async function buildFileMeta(file, fileKey, size, sha256_hex, opts = {}) {
4190
5099
  }
4191
5100
  return meta;
4192
5101
  }
4193
- async function registrationFetch(url, init2, signal) {
5102
+ async function registrationFetch(url, init2, signal, giveBack, deadlineMs) {
4194
5103
  if (signal?.aborted) throw new UploadError("Upload aborted", "ABORTED");
5104
+ const request = transportFetch(url, init2);
5105
+ return new Promise((resolve2, reject) => {
5106
+ let settled = false;
5107
+ const giveUp = (failure) => {
5108
+ if (settled) return;
5109
+ settled = true;
5110
+ cleanup();
5111
+ reject(failure);
5112
+ void request.then(async (answer) => answer.ok ? giveBack(await answer.json()) : void 0).catch(() => {
5113
+ });
5114
+ };
5115
+ const onAbort = () => giveUp(new UploadError("Upload aborted", "ABORTED"));
5116
+ const timer = setTimeout(
5117
+ () => giveUp(new UploadError(`The registration got no answer in ${Math.round(deadlineMs / 1e3)} s`, "NETWORK", void 0, void 0, true)),
5118
+ deadlineMs
5119
+ );
5120
+ const cleanup = () => {
5121
+ clearTimeout(timer);
5122
+ signal?.removeEventListener("abort", onAbort);
5123
+ };
5124
+ signal?.addEventListener("abort", onAbort, { once: true });
5125
+ request.then(
5126
+ (answer) => {
5127
+ if (settled) return;
5128
+ settled = true;
5129
+ cleanup();
5130
+ resolve2(answer);
5131
+ },
5132
+ (err) => {
5133
+ if (settled) return;
5134
+ settled = true;
5135
+ cleanup();
5136
+ reject(err);
5137
+ }
5138
+ );
5139
+ });
5140
+ }
5141
+ function registrationDeadlineMs(policy) {
5142
+ return resolveTransportPolicy(policy.transport).completeTimeoutMs;
5143
+ }
5144
+ async function pairOrGiveBack(rows, digests, what, giveBack) {
4195
5145
  try {
4196
- return await fetch(url, { ...init2, signal });
5146
+ return pairRegisteredRows(rows, digests, what);
4197
5147
  } catch (err) {
4198
- if (signal?.aborted) throw new UploadError("Upload aborted", "ABORTED");
5148
+ await giveBack((rows ?? []).filter((row) => row.sha256_hex !== void 0 && digests.includes(row.sha256_hex))).catch(() => {
5149
+ });
4199
5150
  throw err;
4200
5151
  }
4201
5152
  }
4202
- async function createSeal(ctx, filesMeta, signal) {
5153
+ async function stopIfCancelled(session, signal) {
5154
+ if (!signal?.aborted) return;
5155
+ await session.cancel();
5156
+ throw new UploadError("Upload aborted", "ABORTED");
5157
+ }
5158
+ async function createSeal(ctx, filesMeta, signal, giveBack, deadlineMs) {
4203
5159
  const sealPayload = { files_meta: filesMeta };
4204
5160
  if (ctx.ownerTokenHash) sealPayload.owner_token_hash = ctx.ownerTokenHash;
4205
5161
  applyAccessControl(sealPayload, ctx);
@@ -4208,7 +5164,7 @@ async function createSeal(ctx, filesMeta, signal) {
4208
5164
  headers: { "Content-Type": "application/json", ...createAuthHeaders(uploadAuthFor(ctx)) },
4209
5165
  credentials: ctx.credentials ?? "include",
4210
5166
  body: JSON.stringify(sealPayload)
4211
- }, signal);
5167
+ }, signal, giveBack, deadlineMs);
4212
5168
  if (!sealResponse.ok) throw await uploadErrorFromResponse(sealResponse, "Create seal failed", "UNKNOWN");
4213
5169
  return await sealResponse.json();
4214
5170
  }
@@ -4237,21 +5193,14 @@ function toSessionFiles(planned, rows) {
4237
5193
  async function uploadSingleFile(ctx, file, policy = DEFAULT_POLICY, callbacks = {}) {
4238
5194
  validateSealContext(ctx);
4239
5195
  const planned = await planFile(file, generateKey());
4240
- const seal = await createSeal(
4241
- ctx,
4242
- [await buildFileMeta(file, planned.key, ciphertextSize(file.size), planned.sha256_hex)],
4243
- callbacks.signal
4244
- );
4245
- const rows = pairRegisteredRows(seal.files, [planned.sha256_hex], `Create seal ${seal.id}`);
4246
- await announceRegistered(callbacks, seal.id, [planned], rows);
4247
- const session = new UploadSession(
5196
+ const sessionOf = (registration, files) => new UploadSession(
4248
5197
  {
4249
5198
  ctx,
4250
5199
  policy,
4251
- sealId: seal.id,
5200
+ sealId: registration.id,
4252
5201
  createdSeal: true,
4253
- expiresAt: seal.expires_at,
4254
- files: toSessionFiles([planned], rows)
5202
+ expiresAt: registration.expires_at,
5203
+ files
4255
5204
  },
4256
5205
  async (s, cb) => {
4257
5206
  const entry = s.files[0];
@@ -4269,6 +5218,18 @@ async function uploadSingleFile(ctx, file, policy = DEFAULT_POLICY, callbacks =
4269
5218
  };
4270
5219
  }
4271
5220
  );
5221
+ const seal = await createSeal(
5222
+ ctx,
5223
+ [await buildFileMeta(file, planned.key, ciphertextSize(file.size), planned.sha256_hex)],
5224
+ callbacks.signal,
5225
+ // A seal this upload created is given back whole.
5226
+ (late) => sessionOf(late, []).cancel(),
5227
+ registrationDeadlineMs(policy)
5228
+ );
5229
+ const rows = await pairOrGiveBack(seal.files, [planned.sha256_hex], `Create seal ${seal.id}`, () => sessionOf(seal, []).cancel());
5230
+ const session = sessionOf(seal, toSessionFiles([planned], rows));
5231
+ await stopIfCancelled(session, callbacks.signal);
5232
+ await announceRegistered(callbacks, seal.id, [planned], rows);
4272
5233
  return session.resume(callbacks);
4273
5234
  }
4274
5235
  var PAYMENT_POLL_MS = [2e3, 4e3, 8e3, 15e3];
@@ -4291,75 +5252,12 @@ async function waitForPayment(api, sealId, ownerToken, opts) {
4291
5252
  if (opts.signal?.aborted) throw err;
4292
5253
  if (err instanceof BackendError && err.code !== "transient" && err.code !== "rate_limited") throw err;
4293
5254
  }
4294
- const pause = PAYMENT_POLL_MS[Math.min(poll, PAYMENT_POLL_MS.length - 1)];
4295
- if (Date.now() + pause > opts.deadline) return null;
4296
- await abortableDelay(pause, opts.signal);
5255
+ const pause2 = PAYMENT_POLL_MS[Math.min(poll, PAYMENT_POLL_MS.length - 1)];
5256
+ if (Date.now() + pause2 > opts.deadline) return null;
5257
+ await abortableDelay(pause2, opts.signal);
4297
5258
  }
4298
5259
  }
4299
5260
  var TTL_OPTIONS = limits_default.limits.ttl_options;
4300
- var seal_share_url_default = {
4301
- version: 2,
4302
- name: "SEAL_SHARE_URL",
4303
- description: "URL fragment scheme for SEAL share links (SPEC-AEON-V4 \xA76, law \u041B2): the fragment of any link carries one symmetric key or nothing. A link addressed to someone carries no fragment: its key, wrapped to the recipient's bundle (sealed box v2, crypto.json sealed_box_v2), lives in the share link's row on the server and comes back as `fragment` of GET /seal/{id}/share/{code}. Backends never see fragments (URL fragments are not sent over HTTP per RFC 3986 \xA73.5). Consumers: the web, the CLI, the MCP server, the SDK, sealnet and the bots. The wrap and its opening live in shared/core (targeted.rs over sealed_box.rs, Identity::open).",
4304
- url_template: "https://<host>/s/<seal_id>/<share_code>[#<link_key>]",
4305
- fragment_variants: {
4306
- key: {
4307
- format: "<link_key_urlsafe_b64_no_pad>",
4308
- detection: "exactly 43 urlsafe-b64-no-pad characters, 32 bytes: the AES-256-GCM key of the share blob (seal_blob.v1.json)",
4309
- field_layout: [
4310
- { name: "link_key", offset: 0, length: 32, encoding: "urlsafe-b64-no-pad in URL" }
4311
- ]
4312
- },
4313
- none: {
4314
- format: "",
4315
- detection: "no fragment: an addressed link. The key, wrapped to the recipient's bundle with scope ('seal_share', seal_id from the path), is the `fragment` field of the share blob response (1575 base64url characters, first byte 0x02); only the recipient's seed opens it."
4316
- },
4317
- targeted_x25519_v1: {
4318
- status: "read only until the removal (C1 \xA76): links made before C1 with the sealed box v1 in the fragment",
4319
- format: "x25519:<packed_b64>",
4320
- prefix: "x25519:",
4321
- packed_binary_length_bytes: 92,
4322
- packed_layout: [
4323
- { name: "ephemeral_public", offset: 0, length: 32, encoding: "raw bytes; X25519 ephemeral pubkey from sender" },
4324
- { name: "nonce", offset: 32, length: 12, encoding: "raw bytes; AES-256-GCM nonce" },
4325
- { name: "wrapped_link_key", offset: 44, length: 48, encoding: "raw bytes; 32 B ciphertext of the link key || 16 B GCM tag" }
4326
- ],
4327
- implicit_fields_not_in_packed: {
4328
- recipient_public: "the X25519 key of the recipient's seed (the seed itself is the X25519 secret)",
4329
- scope_type: "'seal_share'",
4330
- scope_id: "seal_id from the URL path /s/<seal_id>/<code>",
4331
- grant_version: "1"
4332
- },
4333
- kdf_info_layout: 'seal_crypto::hkdf::derive_wrap_key: b"WRAP" || 0x01 || len(scope_type) || scope_type || len(scope_id) || scope_id, salt crypto.json hkdf.wrap_key_salt',
4334
- aad_layout: "recipient_public (32 B) || 0x01"
4335
- }
4336
- },
4337
- version_detection_rule: "(1) no fragment \u2192 none: the wrap comes from the server; (2) starts with 'x25519:' \u2192 targeted_x25519_v1, read only until the removal; (3) exactly 43 urlsafe-b64-no-pad characters \u2192 key; (4) anything else \u2192 'update the client' (SPEC-AEON-V4 \xA77.4), never decoded as a key.",
4338
- current_format_version: 2,
4339
- supported_format_versions: [2],
4340
- implementations: {
4341
- rust: "shared/core/src/targeted.rs (wrap_link_key / open_wrap; the x25519: opening until the removal); the CLI calls it as seal_crypto::targeted",
4342
- ts: "shared/packages/protocol/src/identity.ts (wrapTo / openWrap) over the core's WASM; the whole link is parsed by protocol/src/url.ts::parseShareUrl",
4343
- python: "sealnet calls the Rust core in its wheel (sealnet.seal_crypto); no Python implementation"
4344
- },
4345
- test_vectors: {
4346
- description: "Frozen outputs of the read-only v1 variant, until the removal: every reader MUST recover link_key from fragment with recipient_secret (the seed) and seal_id, and MUST fail with any other seal_id.",
4347
- targeted_x25519_v1: [
4348
- {
4349
- recipient_secret_b64url: "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",
4350
- recipient_public_b64url: "E75P6uryBMf9M1j8nAByGIHRdCeBKCJ-xnTzf3_pe20",
4351
- seal_id: "AbCd1234",
4352
- fragment: "x25519:GkbbXddA43eoSgY1ZAAnPTCDmJIoGM3ZrY2_wctdKX2ivODHag_TCSjQql3PMu22xzsxJsYKHnIhHjXhvuJfe468pvsvvzuEZiaVzoPu2PTqlRin8xiDsopyrGQ",
4353
- link_key_b64url: "q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s"
4354
- }
4355
- ]
4356
- },
4357
- security_properties: {
4358
- key: "Anyone with the URL can open. link_key is the entire capability \u2014 treat the URL itself as a bearer credential.",
4359
- none: "The URL alone opens nothing: the key is sealed to the recipient's bundle (X25519 + ML-KEM-768) and only the seed on the recipient's device opens it. Each wrap has a fresh ephemeral key and encapsulation."
4360
- }
4361
- };
4362
- var LEGACY_PREFIX = seal_share_url_default.fragment_variants.targeted_x25519_v1.prefix;
4363
5261
  var SEAL_ID_LENGTH = 8;
4364
5262
  var LINK_KEY_LENGTH = 43;
4365
5263
  var SHARE_CODE_LENGTH = 4;
@@ -4416,7 +5314,7 @@ function parseShareUrl(input) {
4416
5314
  try {
4417
5315
  url = new URL(input);
4418
5316
  } catch {
4419
- throw new ShareUrlError("url_invalid", `not a valid URL: ${input}`);
5317
+ throw new ShareUrlError("url_invalid", `not a valid URL (${input.length} characters)`);
4420
5318
  }
4421
5319
  let parsed;
4422
5320
  try {
@@ -4427,9 +5325,6 @@ function parseShareUrl(input) {
4427
5325
  const fragment = url.hash.replace(/^#/, "").trim();
4428
5326
  const shareCode = parsed.shareCode ?? null;
4429
5327
  if (!fragment) return { sealId: parsed.sealId, shareCode, fragmentVariant: "none", fragment };
4430
- if (fragment.startsWith(LEGACY_PREFIX)) {
4431
- return { sealId: parsed.sealId, shareCode, fragmentVariant: "targeted_x25519_v1", fragment };
4432
- }
4433
5328
  if (!isValidLinkKey(fragment)) {
4434
5329
  throw new ShareUrlError(
4435
5330
  "url_invalid",
@@ -4451,90 +5346,30 @@ function parseUrlType(pathname) {
4451
5346
  }
4452
5347
  return { sealId, shareCode };
4453
5348
  }
4454
- var crypto_default = {
4455
- version: 1,
4456
- default_aead: "aes_256_gcm",
4457
- aes_gcm: {
4458
- key_length_bytes: 32,
4459
- nonce_length_bytes: 12,
4460
- tag_length_bytes: 16
4461
- },
4462
- sha256: {
4463
- output_length_bytes: 32,
4464
- hex_string_length: 64
4465
- },
4466
- owner_token_bytes: 32,
4467
- link_key_bytes: 32,
4468
- metadata_aad_prefix: "field:",
4469
- keybundle: {
4470
- signature_prefix: "seal:keybundle:",
4471
- signed_bundle_version: 2,
4472
- v2_fields: ["identity_ed25519_pub", "agreement_x25519_pub", "kem_mlkem768_pub"],
4473
- packed_length: 1316,
4474
- address: {
4475
- of: "sha256(identity_ed25519_pub), 32 bytes",
4476
- text: "base64url without padding, 43 characters",
4477
- words: "fingerprint_words.json over its first three bytes"
4478
- }
4479
- },
4480
- hkdf: {
4481
- wrap_key_salt: "seal:wrapkey:v1",
4482
- wrap_key_salt_v2: "seal:wrapkey:v2",
4483
- identity_key_salt: "seal:key-derivation:v1",
4484
- file_envelope_salt: "seal:file-envelope:v1",
4485
- info_prefixes: {
4486
- wrap: "WRAP",
4487
- agreement: "AGRE",
4488
- identity: "IDEN",
4489
- workload_identity: "seal:workload-identity:v1",
4490
- kem_mlkem768: "seal:kem-mlkem768:v1"
4491
- }
4492
- },
4493
- xwing: { label_hex: "5c2e2f2f5e5c" },
4494
- sealed_box_v2: {
4495
- version_byte: 2,
4496
- packed_layout: [
4497
- { name: "version", offset: 0, length: 1 },
4498
- { name: "eph_pub", offset: 1, length: 32 },
4499
- { name: "kem_ct", offset: 33, length: 1088 },
4500
- { name: "nonce", offset: 1121, length: 12 },
4501
- { name: "ct", offset: 1133, length: 48 }
4502
- ],
4503
- packed_length: 1181,
4504
- packed_b64_length: 1575
4505
- },
4506
- secret_scope_aad: "secret:{secret_id}",
4507
- sign: {
4508
- message_prefix: "aeon:sign:v1",
4509
- message_format: "aeon:sign:v1|org:{org_id}|req:{request_id}|doc_hash:{doc_hash_hex}"
4510
- }
4511
- };
4512
5349
  var SHARE_SCOPE = seal_address_default.scopes.share_link;
4513
5350
  var OWNER_SCOPE = seal_address_default.scopes.owner_copy;
4514
5351
  var WRAP_VERSION = crypto_default.sealed_box_v2.version_byte;
4515
5352
  var WRAP_BYTES = crypto_default.sealed_box_v2.packed_length;
4516
- var LEGACY = seal_share_url_default.fragment_variants.targeted_x25519_v1;
4517
- var ADDRESS_PROOF_SCOPE = seal_address_default.migrate.scope_address_proof;
4518
- var SEED_BYTES = 32;
5353
+ var SEED_BYTES = 64;
5354
+ var SEED_BYTES_BEFORE = 32;
4519
5355
  var KEY_BYTES = 32;
4520
5356
  var B64URL = /^[A-Za-z0-9_-]+$/;
4521
5357
  function newSeed() {
4522
5358
  return crypto.getRandomValues(new Uint8Array(SEED_BYTES));
4523
5359
  }
4524
- async function openIdentity(seed, keyVersion = 1) {
5360
+ async function openIdentity(seed2, keyVersion = 1) {
4525
5361
  const wasm2 = await ensureWasm();
4526
- if (seed.length === SEED_BYTES) return wasm2.WasmIdentity.fromSeed32(seed);
4527
- if (seed.length === 2 * SEED_BYTES) return wasm2.WasmIdentity.fromSeed64(seed, keyVersion);
4528
- throw new Error(`a seed is ${SEED_BYTES} or ${2 * SEED_BYTES} bytes, got ${seed.length}`);
5362
+ if (seed2.length === SEED_BYTES) return wasm2.WasmIdentity.fromSeed64(seed2, keyVersion);
5363
+ if (seed2.length === SEED_BYTES_BEFORE) return wasm2.WasmIdentity.fromSeed32(seed2);
5364
+ throw new Error(`a seed is ${SEED_BYTES} bytes, or the ${SEED_BYTES_BEFORE} of a key made before, got ${seed2.length}`);
4529
5365
  }
4530
- async function identityOf(seed, keyVersion = 1) {
4531
- const identity = await openIdentity(seed, keyVersion);
5366
+ async function identityOf(seed2, keyVersion = 1) {
5367
+ const identity = await openIdentity(seed2, keyVersion);
4532
5368
  try {
4533
5369
  return {
4534
5370
  bundle: identity.bundle(),
4535
5371
  address: identity.address(),
4536
- words: identity.words(),
4537
- legacyAddress: identity.legacyAddress()
5372
+ words: identity.words()
4538
5373
  };
4539
5374
  } finally {
4540
5375
  identity.free();
@@ -4571,9 +5406,8 @@ var WrapError = class extends Error {
4571
5406
  this.cause = cause;
4572
5407
  }
4573
5408
  };
4574
- async function openWrap(wrap, seed, scope, id, keyVersion = 1) {
5409
+ async function openWrap(wrap, seed2, scope, id, keyVersion = 1) {
4575
5410
  if (id.length === 0) throw new WrapError("parse", "the scope id must not be empty: the wrap binds to it");
4576
- if (wrap.startsWith(LEGACY.prefix)) return openLegacy(wrap.slice(LEGACY.prefix.length), seed, scope, id);
4577
5411
  if (!B64URL.test(wrap)) throw new WrapError("parse", "the wrap is not urlsafe-base64-no-pad");
4578
5412
  const packed = base64urlToBytes(wrap);
4579
5413
  if (packed[0] !== WRAP_VERSION) {
@@ -4582,10 +5416,10 @@ async function openWrap(wrap, seed, scope, id, keyVersion = 1) {
4582
5416
  if (packed.length !== WRAP_BYTES) {
4583
5417
  throw new WrapError("parse", `the wrap is ${packed.length} bytes, expected ${WRAP_BYTES}`);
4584
5418
  }
4585
- if (seed.length !== SEED_BYTES && seed.length !== 2 * SEED_BYTES) {
4586
- throw new WrapError("parse", `a seed is ${SEED_BYTES} or ${2 * SEED_BYTES} bytes, got ${seed.length}`);
5419
+ if (seed2.length !== SEED_BYTES && seed2.length !== SEED_BYTES_BEFORE) {
5420
+ throw new WrapError("parse", `a seed is ${SEED_BYTES} bytes, or the ${SEED_BYTES_BEFORE} of a key made before, got ${seed2.length}`);
4587
5421
  }
4588
- const identity = await openIdentity(seed, keyVersion);
5422
+ const identity = await openIdentity(seed2, keyVersion);
4589
5423
  try {
4590
5424
  return identity.open(packed, scope, id);
4591
5425
  } catch (err) {
@@ -4594,22 +5428,8 @@ async function openWrap(wrap, seed, scope, id, keyVersion = 1) {
4594
5428
  identity.free();
4595
5429
  }
4596
5430
  }
4597
- async function openLegacy(packedB64, seed, scope, id) {
4598
- if (!B64URL.test(packedB64)) throw new WrapError("parse", `the ${LEGACY.prefix} wrap is not urlsafe-base64-no-pad`);
4599
- const packed = base64urlToBytes(packedB64);
4600
- if (packed.length !== LEGACY.packed_binary_length_bytes) {
4601
- throw new WrapError("parse", `the ${LEGACY.prefix} wrap is ${packed.length} bytes, expected ${LEGACY.packed_binary_length_bytes}`);
4602
- }
4603
- if (seed.length !== SEED_BYTES) throw new WrapError("parse", `an ${LEGACY.prefix} wrap opens with a ${SEED_BYTES}-byte seed`);
4604
- const wasm2 = await ensureWasm();
4605
- try {
4606
- return wasm2.wasm_sealbox_unwrap(packed, seed, scope, id);
4607
- } catch (err) {
4608
- throw new WrapError("aead", "the wrap does not open: it is not for this seed, or its scope, id or bytes were changed", err);
4609
- }
4610
- }
4611
- async function proveInbox(seed, challenge) {
4612
- const identity = await openIdentity(seed);
5431
+ async function proveInbox(seed2, challenge) {
5432
+ const identity = await openIdentity(seed2);
4613
5433
  try {
4614
5434
  const signature = identity.inboxProof(BigInt(challenge.ts), base64urlToBytes(challenge.challenge));
4615
5435
  return `${challenge.ts}.${challenge.challenge}.${bytesToBase64url(signature)}`;
@@ -4617,17 +5437,12 @@ async function proveInbox(seed, challenge) {
4617
5437
  identity.free();
4618
5438
  }
4619
5439
  }
4620
- async function proveLegacyAddress(seed, challenge, ts) {
4621
- const wasm2 = await ensureWasm();
4622
- const token = wasm2.wasm_sealbox_unwrap(base64urlToBytes(challenge), seed, ADDRESS_PROOF_SCOPE, String(ts));
4623
- return `${ts}.${bytesToBase64url(token)}`;
4624
- }
4625
5440
  var fingerprint_words_default = {
4626
- version: 1,
5441
+ version: 2,
4627
5442
  name: "FINGERPRINT_WORDS",
4628
- description: "Three words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3): word i (i = 0, 1, 2) is words[byte i of SHA-256(identity public key)] \u2014 the first three bytes of the same SHA-256 that is the address, so a client names an address by its own first bytes without hashing again \u2014 24 bits in all, written in lower case with one space between them. The agent shows them in its chat, box.seal.net and seal.net/i/{id} show them on the page, so a person sees at a glance whether both sides hold the same key. One list for every language and client: 256 English nouns of 3 to 7 letters, no two sharing their first three letters, in alphabetical order.",
5443
+ description: "Eight words that name the identity key of a bundle to a person (SPEC-AEON-V4 \xA75.3; eight since AUDIT K251, owner 11.11: eight words, 24 bits, were ground in 207 s on one Mac): word i (i = 0 \u2026 7) is words[byte i of SHA-256(identity public key)] \u2014 the first eight bytes of the same SHA-256 that is the address, so a client names an address by its own first bytes without hashing again \u2014 64 bits in all, written in lower case with one space between them; the first three are the three of before. The agent shows them in its chat, box.seal.net and seal.net/i/{id} show them on the page, so a person sees at a glance whether both sides hold the same key. One list for every language and client: 256 English nouns of 3 to 7 letters, no two sharing their first three letters, in alphabetical order.",
4629
5444
  digest: "sha256",
4630
- count: 3,
5445
+ count: 8,
4631
5446
  separator: " ",
4632
5447
  words: [
4633
5448
  "acorn",
@@ -4889,8 +5704,8 @@ var fingerprint_words_default = {
4889
5704
  ],
4890
5705
  vector: {
4891
5706
  public_key_b64url: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
4892
- sha256_prefix_hex: "66687a",
4893
- words: "iron ivory lava"
5707
+ sha256_prefix_hex: "66687aadf862bd77",
5708
+ words: "iron ivory lava plum yacht horse river lagoon"
4894
5709
  }
4895
5710
  };
4896
5711
  var WORDS = fingerprint_words_default.words;
@@ -4902,8 +5717,13 @@ function addressWords(address) {
4902
5717
  }
4903
5718
  var PAIRING_MIME = seal_address_default.payloads.pair.mime;
4904
5719
  var DEVICE_MIME = seal_address_default.payloads.device.mime;
5720
+ var DELIVERY_MIME = seal_address_default.payloads.delivery.mime;
5721
+ var APPROVE_MIME = seal_address_default.payloads.approve.mime;
5722
+ var APPROVE_ANSWER_MIME = seal_address_default.payloads.approve_answer.mime;
5723
+ var SUMMARY_MIME = seal_address_default.payloads.summary.mime;
4905
5724
  var PAIR_WHAT = seal_address_default.pair_what;
4906
5725
  var NAME_MAX = seal_address_default.payloads.name_max;
5726
+ var BODY_SHOWN_BYTES = limits_default.limits.APPROVE_BODY_SHOWN_BYTES;
4907
5727
  var BUNDLE_BYTES = crypto_default.keybundle.packed_length;
4908
5728
  var VERSION = 2;
4909
5729
  var B64URL2 = /^[A-Za-z0-9_-]+$/;
@@ -4963,8 +5783,23 @@ var secrets_default = {
4963
5783
  Twilio: "console.twilio.com",
4964
5784
  Vercel: "vercel.com"
4965
5785
  },
4966
- patterns_note: "What a key looks like, for every reader: `seal doctor --transcripts`, the scanner of the Pro web page and the `sealfs` detector (C1 \u042039). `pattern` is an expression in the subset all three run alike \u2014 JS, Python `re`, Rust `regex`: no lookaround, no backreference, no inline flag; a boundary is `\\b` inside the expression. The flags are shared: case-insensitive and multiline. A match that contains a string of the entry's `allowlist` (case-insensitive) is no finding. A finding is shown masked: its first four characters, `\u2026`, its last two. `vectors.hit` holds a finding of the entry, `vectors.clean` none; every reader passes them. The scanner page does not take a file larger than `max_file_bytes`; `seal doctor` reads agent transcripts of any size, a line at a time \u2014 skipping a long transcript would hide its leak. Data, not code: a service is added with one entry.",
5786
+ patterns_note: "What a key looks like, for every reader: `seal doctor --transcripts`, the scanner of the Pro web page and the `sealfs` detector (C1 \u042039). `pattern` is an expression in the subset all three run alike \u2014 JS, Python `re`, Rust `regex`: no lookaround, no backreference, no inline flag; a boundary is `\\b` inside the expression. The flags are shared: case-insensitive and multiline. A match that contains a string of the entry's `allowlist` (case-insensitive) is no finding. A match of an entry with `checksum` is a finding only when it passes that sum: `luhn` \u2014 the Luhn sum of its digits is 0 modulo 10; `iban` \u2014 its characters but spaces, upper-cased, the first four moved to the end, each letter read as a number (A = 10 \u2026 Z = 35), are 1 modulo 97. A finding is shown masked: its first four characters, `\u2026`, its last two. `vectors.hit` holds a finding of the entry, `vectors.clean` none; every reader passes them. The scanner page does not take a file larger than `max_file_bytes`; `seal doctor` reads agent transcripts of any size, a line at a time \u2014 skipping a long transcript would hide its leak. Data, not code: a service is added with one entry.",
4967
5787
  max_file_bytes: 10485760,
5788
+ wildcard_public_second_level: ["ac", "co", "com", "edu", "gov", "go", "ne", "net", "or", "org", "mil", "int", "gob", "ltd", "plc", "me", "nom"],
5789
+ shared_host_suffixes: ["s3.amazonaws.com", "cloudfront.net", "azurewebsites.net", "appspot.com", "firebaseapp.com", "web.app", "github.io", "githubusercontent.com", "gitlab.io", "herokuapp.com", "pages.dev", "workers.dev", "vercel.app", "netlify.app", "onrender.com", "fly.dev", "blogspot.com", "ngrok.io", "ngrok-free.app", "glitch.me", "surge.sh"],
5790
+ shared_host_note: "Names under which each customer has a name of its own (the private part of the public suffix list): a host there is one service with the label before it, as `x.co.uk` is \u2014 AUDIT K162: by its last two labels every github.io page was one service.",
5791
+ wildcard_note: "A proposed `*.<name>` binds a key unless <name> is a public suffix: one label (`*.com`), or two where the second is a two-letter country top level and the first is one of wildcard_public_second_level (`*.co.uk` would be a root for every .co.uk host; `*.me.com` is a name of its own); a bare name needs two labels (SPEC agent egress \xA74.2, review of phase 1).",
5792
+ guard_note: "What the guard does with a key of an entry (SPEC agent egress \xA74.1, read by `seal-client-core::guard`). `hosts`: where the key is a way in, the default binding a person confirms or narrows; `*.` is one label. `place`: where the guard puts the value \u2014 `bearer` (Authorization: Bearer), `header:<name>`, `query:<param>`, `basic_user`, `basic_pass`, `userinfo`, `url` (the secret is the request address itself, a webhook). `class`: `outbound` \u2014 a key a program enters a service with, the proxy puts it in; `inprocess` \u2014 a key a program works with itself (a webhook signing secret, a database password of a driver that uses no proxy, a private key, an assignment the pattern matches with its name): the program gets the value, by the person's word on the page. `surrogate`: the form of the stand-in the agent sees \u2014 `keep_prefix` (kept as it is), `alphabet` (`base62`, `base64url`, `hex`, `digits`, `base32`, `classes` \u2014 each character keeps its class and punctuation stays), `length` (a number, else the value's), `checksum` (`github_crc32`: the last six characters are the CRC32 of the body, base62), `parts` (`password`: of a connection URI only the password changes). An entry without `surrogate` is treated by classes. `provision_commands`: commands that write a key as data into a service's own store; a surrogate in their arguments or stdin is refused unless the binding's `provision` names the host (\xA75.4, \xA76.4). Data, not code: a service is added with one entry.",
5793
+ provision_commands: [
5794
+ { command: "wrangler secret put", host: "api.cloudflare.com" },
5795
+ { command: "gh secret set", host: "api.github.com" },
5796
+ { command: "vercel env add", host: "api.vercel.com" },
5797
+ { command: "fly secrets set", host: "api.machines.dev" },
5798
+ { command: "kubectl create secret", host: null },
5799
+ { command: "aws secretsmanager put-secret-value", host: "*.amazonaws.com" },
5800
+ { command: "heroku config:set", host: "api.heroku.com" },
5801
+ { command: "doppler secrets set", host: "api.doppler.com" }
5802
+ ],
4968
5803
  patterns: [
4969
5804
  {
4970
5805
  name: "openai_api_key",
@@ -4972,6 +5807,10 @@ var secrets_default = {
4972
5807
  severity: "critical",
4973
5808
  description: "OpenAI API Key",
4974
5809
  keywords: ["openai", "sk-proj-"],
5810
+ hosts: ["api.openai.com"],
5811
+ place: "bearer",
5812
+ class: "outbound",
5813
+ surrogate: { keep_prefix: "^sk-proj-", alphabet: "base64url" },
4975
5814
  vectors: { hit: "OPENAI_API_KEY=sk-proj-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEf", clean: "OPENAI_API_KEY=sk-proj-AbCdEfGhIj" }
4976
5815
  },
4977
5816
  {
@@ -4980,6 +5819,10 @@ var secrets_default = {
4980
5819
  severity: "critical",
4981
5820
  description: "Anthropic API Key",
4982
5821
  keywords: ["anthropic", "sk-ant-"],
5822
+ hosts: ["api.anthropic.com"],
5823
+ place: "header:x-api-key",
5824
+ class: "outbound",
5825
+ surrogate: { keep_prefix: "^sk-ant-(?:api[0-9]{2}-)?", alphabet: "base64url" },
4983
5826
  vectors: { hit: "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCd", clean: "sk-ant-api03-short" }
4984
5827
  },
4985
5828
  {
@@ -4988,6 +5831,10 @@ var secrets_default = {
4988
5831
  severity: "critical",
4989
5832
  description: "GitHub Token",
4990
5833
  keywords: ["github", "token", "ghp_", "github_pat_"],
5834
+ hosts: ["api.github.com", "github.com", "uploads.github.com", "codeload.github.com"],
5835
+ place: "bearer",
5836
+ class: "outbound",
5837
+ surrogate: { keep_prefix: "^(?:gh[pousr]|github_pat)_", alphabet: "classes", checksum: "github_crc32" },
4991
5838
  vectors: { hit: "token: ghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789", clean: "token: xghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789" }
4992
5839
  },
4993
5840
  {
@@ -4996,6 +5843,10 @@ var secrets_default = {
4996
5843
  severity: "critical",
4997
5844
  description: "GitLab Personal Access Token",
4998
5845
  keywords: ["gitlab", "token"],
5846
+ hosts: ["gitlab.com"],
5847
+ place: "header:PRIVATE-TOKEN",
5848
+ class: "outbound",
5849
+ surrogate: { keep_prefix: "^glpat-", alphabet: "classes" },
4999
5850
  vectors: { hit: "glpat-AbCdEfGhIjKlMnOpQrSt", clean: "glpat-short" }
5000
5851
  },
5001
5852
  {
@@ -5004,6 +5855,8 @@ var secrets_default = {
5004
5855
  severity: "critical",
5005
5856
  description: "AWS Access Key ID",
5006
5857
  keywords: ["aws", "amazon", "access_key", "accesskey"],
5858
+ class: "inprocess",
5859
+ surrogate: { keep_prefix: "^(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)", alphabet: "classes" },
5007
5860
  vectors: { hit: "AKIAIOSFODNN7EXAMPLE", clean: "AKIAIOSFODNN7EXAMPLEX" }
5008
5861
  },
5009
5862
  {
@@ -5012,6 +5865,8 @@ var secrets_default = {
5012
5865
  severity: "critical",
5013
5866
  description: "AWS Secret Access Key",
5014
5867
  keywords: ["aws", "secret", "access_key"],
5868
+ class: "inprocess",
5869
+ surrogate: { keep_prefix: `^.*[:=]\\s*['\\"]?`, alphabet: "classes" },
5015
5870
  vectors: { hit: 'aws_secret_access_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"', clean: 'aws_secret_access_key = "short"' }
5016
5871
  },
5017
5872
  {
@@ -5020,6 +5875,10 @@ var secrets_default = {
5020
5875
  severity: "critical",
5021
5876
  description: "Stripe Live Secret Key",
5022
5877
  keywords: ["stripe", "live", "secret"],
5878
+ hosts: ["api.stripe.com", "files.stripe.com"],
5879
+ place: "bearer",
5880
+ class: "outbound",
5881
+ surrogate: { keep_prefix: "^[sr]k_live_", alphabet: "base62" },
5023
5882
  vectors: { hit: "sk_live_AbCdEfGhIjKlMnOpQrStUvWx", clean: "sk_live_AbCd" }
5024
5883
  },
5025
5884
  {
@@ -5028,6 +5887,10 @@ var secrets_default = {
5028
5887
  severity: "medium",
5029
5888
  description: "Stripe Test Secret Key",
5030
5889
  keywords: ["stripe", "test"],
5890
+ hosts: ["api.stripe.com", "files.stripe.com"],
5891
+ place: "bearer",
5892
+ class: "outbound",
5893
+ surrogate: { keep_prefix: "^[sr]k_test_", alphabet: "base62" },
5031
5894
  vectors: { hit: "rk_test_AbCdEfGhIjKlMnOpQrStUvWx", clean: "rk_test_AbCd" }
5032
5895
  },
5033
5896
  {
@@ -5038,12 +5901,26 @@ var secrets_default = {
5038
5901
  keywords: ["stripe", "publishable"],
5039
5902
  vectors: { hit: "pk_live_AbCdEfGhIjKlMnOpQrStUvWx", clean: "pk_live_AbCd" }
5040
5903
  },
5904
+ {
5905
+ name: "stripe_webhook_secret",
5906
+ pattern: "\\bwhsec_[A-Za-z0-9]{32,}",
5907
+ severity: "critical",
5908
+ description: "Stripe Webhook Signing Secret",
5909
+ keywords: ["stripe", "webhook", "whsec_"],
5910
+ class: "inprocess",
5911
+ surrogate: { keep_prefix: "^whsec_", alphabet: "base62" },
5912
+ vectors: { hit: "STRIPE_WEBHOOK_SECRET=whsec_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789", clean: "STRIPE_WEBHOOK_SECRET=whsec_short" }
5913
+ },
5041
5914
  {
5042
5915
  name: "slack_token",
5043
5916
  pattern: "\\bxox[abprs]-[A-Za-z0-9-]{20,}",
5044
5917
  severity: "critical",
5045
5918
  description: "Slack Token",
5046
5919
  keywords: ["slack", "token", "xox"],
5920
+ hosts: ["slack.com"],
5921
+ place: "bearer",
5922
+ class: "outbound",
5923
+ surrogate: { keep_prefix: "^xox[abprs]-", alphabet: "classes" },
5047
5924
  vectors: { hit: "xoxb-1234567890-1234567890123-AbCdEfGhIjKl", clean: "xoxb-12345" }
5048
5925
  },
5049
5926
  {
@@ -5052,6 +5929,10 @@ var secrets_default = {
5052
5929
  severity: "high",
5053
5930
  description: "Slack Webhook URL",
5054
5931
  keywords: ["slack", "webhook", "hooks.slack.com"],
5932
+ hosts: ["hooks.slack.com"],
5933
+ place: "url",
5934
+ class: "outbound",
5935
+ surrogate: { keep_prefix: "^https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B", alphabet: "classes" },
5055
5936
  vectors: { hit: "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX", clean: "https://hooks.slack.com/services/" }
5056
5937
  },
5057
5938
  {
@@ -5060,6 +5941,10 @@ var secrets_default = {
5060
5941
  severity: "high",
5061
5942
  description: "Google API Key",
5062
5943
  keywords: ["google", "api", "AIza"],
5944
+ hosts: ["*.googleapis.com"],
5945
+ place: "query:key",
5946
+ class: "outbound",
5947
+ surrogate: { keep_prefix: "^AIza", alphabet: "base64url" },
5063
5948
  vectors: { hit: "AIzaSyAbCdEfGhIjKlMnOpQrStUvWxYz0123456", clean: "AIzaSyShort" }
5064
5949
  },
5065
5950
  {
@@ -5068,6 +5953,8 @@ var secrets_default = {
5068
5953
  severity: "high",
5069
5954
  description: "Google OAuth Client Secret",
5070
5955
  keywords: ["google", "oauth", "client_secret"],
5956
+ class: "inprocess",
5957
+ surrogate: { keep_prefix: `^.*[:=]\\s*['\\"]?`, alphabet: "classes" },
5071
5958
  vectors: { hit: 'client_secret: "AbCdEfGhIjKlMnOpQrStUvWx"', clean: 'client_secret: "short"' }
5072
5959
  },
5073
5960
  {
@@ -5108,6 +5995,8 @@ var secrets_default = {
5108
5995
  severity: "critical",
5109
5996
  description: "PostgreSQL Connection String",
5110
5997
  keywords: ["postgres", "postgresql", "database"],
5998
+ class: "inprocess",
5999
+ surrogate: { parts: "password" },
5111
6000
  vectors: { hit: "postgresql://app:hunter2secret@db.internal:5432/app", clean: "postgresql://db.internal/app" }
5112
6001
  },
5113
6002
  {
@@ -5116,6 +6005,8 @@ var secrets_default = {
5116
6005
  severity: "critical",
5117
6006
  description: "MySQL Connection String",
5118
6007
  keywords: ["mysql", "database"],
6008
+ class: "inprocess",
6009
+ surrogate: { parts: "password" },
5119
6010
  vectors: { hit: "mysql://app:hunter2secret@db.internal/app", clean: "mysql://db.internal/app" }
5120
6011
  },
5121
6012
  {
@@ -5124,6 +6015,8 @@ var secrets_default = {
5124
6015
  severity: "critical",
5125
6016
  description: "MongoDB Connection String",
5126
6017
  keywords: ["mongodb", "mongo", "database"],
6018
+ class: "inprocess",
6019
+ surrogate: { parts: "password" },
5127
6020
  vectors: { hit: "mongodb+srv://app:hunter2secret@cluster0.example.net", clean: "mongodb://localhost" }
5128
6021
  },
5129
6022
  {
@@ -5132,6 +6025,8 @@ var secrets_default = {
5132
6025
  severity: "high",
5133
6026
  description: "Redis Connection String",
5134
6027
  keywords: ["redis", "cache"],
6028
+ class: "inprocess",
6029
+ surrogate: { parts: "password" },
5135
6030
  vectors: { hit: "redis://:hunter2secret@cache.internal:6379", clean: "redis://cache.internal:6379" }
5136
6031
  },
5137
6032
  {
@@ -5156,6 +6051,10 @@ var secrets_default = {
5156
6051
  severity: "high",
5157
6052
  description: "SendGrid API Key",
5158
6053
  keywords: ["sendgrid", "email", "SG."],
6054
+ hosts: ["api.sendgrid.com"],
6055
+ place: "bearer",
6056
+ class: "outbound",
6057
+ surrogate: { keep_prefix: "^SG\\.", alphabet: "classes" },
5159
6058
  vectors: { hit: "SG.AbCdEfGhIjKlMnOpQrStUv.AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdE", clean: "SG.short.key" }
5160
6059
  },
5161
6060
  {
@@ -5164,6 +6063,10 @@ var secrets_default = {
5164
6063
  severity: "high",
5165
6064
  description: "Twilio API Key",
5166
6065
  keywords: ["twilio", "sms"],
6066
+ hosts: ["api.twilio.com"],
6067
+ place: "basic_user",
6068
+ class: "outbound",
6069
+ surrogate: { keep_prefix: "^SK", alphabet: "hex" },
5167
6070
  vectors: { hit: "SK0123456789abcdef0123456789abcdef", clean: "SK0123456789abcdef" }
5168
6071
  },
5169
6072
  {
@@ -5172,6 +6075,10 @@ var secrets_default = {
5172
6075
  severity: "high",
5173
6076
  description: "NPM Access Token",
5174
6077
  keywords: ["npm", "token"],
6078
+ hosts: ["registry.npmjs.org"],
6079
+ place: "bearer",
6080
+ class: "outbound",
6081
+ surrogate: { keep_prefix: "^npm_", alphabet: "base62" },
5175
6082
  vectors: { hit: "npm_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789", clean: "npm_short" }
5176
6083
  },
5177
6084
  {
@@ -5180,6 +6087,10 @@ var secrets_default = {
5180
6087
  severity: "high",
5181
6088
  description: "PyPI API Token",
5182
6089
  keywords: ["pypi", "token", "python"],
6090
+ hosts: ["upload.pypi.org"],
6091
+ place: "basic_pass",
6092
+ class: "outbound",
6093
+ surrogate: { keep_prefix: "^pypi-", alphabet: "base64url" },
5183
6094
  vectors: { hit: "pypi-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWx", clean: "pypi-short" }
5184
6095
  },
5185
6096
  {
@@ -5189,6 +6100,8 @@ var secrets_default = {
5189
6100
  description: "Generic Password Assignment",
5190
6101
  keywords: ["password", "passwd", "secret"],
5191
6102
  allowlist: ["password123", "changeme", "example", "placeholder", "xxxxxxxx"],
6103
+ class: "inprocess",
6104
+ surrogate: { keep_prefix: `^.*[:=]\\s*['\\"]`, alphabet: "classes" },
5192
6105
  vectors: { hit: 'password = "s3cr3t-Value!"', clean: 'password = "changeme-now"' }
5193
6106
  },
5194
6107
  {
@@ -5197,6 +6110,8 @@ var secrets_default = {
5197
6110
  severity: "medium",
5198
6111
  description: "Generic API Key Assignment",
5199
6112
  keywords: ["api_key", "apikey"],
6113
+ class: "inprocess",
6114
+ surrogate: { keep_prefix: `^.*[:=]\\s*['\\"]`, alphabet: "classes" },
5200
6115
  vectors: { hit: 'api_key = "AbCdEfGhIjKlMnOpQrStUvWx"', clean: 'api_key = "short"' }
5201
6116
  },
5202
6117
  {
@@ -5206,6 +6121,32 @@ var secrets_default = {
5206
6121
  description: "SEAL link (it opens its seal)",
5207
6122
  keywords: ["seal", "seal.net/s/"],
5208
6123
  vectors: { hit: "https://seal.net/s/AbCd1234/Xy7Q#AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCde", clean: "https://seal.net/s/AbCd1234/Xy7Q" }
6124
+ },
6125
+ {
6126
+ name: "payment_card",
6127
+ pattern: "\\b(?:\\d[ -]?){12,18}\\d\\b",
6128
+ checksum: "luhn",
6129
+ severity: "high",
6130
+ description: "Payment Card Number",
6131
+ keywords: ["card", "visa", "mastercard"],
6132
+ vectors: { hit: "card: 4111 1111 1111 1111", clean: "card: 4111 1111 1111 1112" }
6133
+ },
6134
+ {
6135
+ name: "iban",
6136
+ pattern: "\\b[A-Z]{2}\\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\\b",
6137
+ checksum: "iban",
6138
+ severity: "high",
6139
+ description: "IBAN",
6140
+ keywords: ["iban", "bank", "account"],
6141
+ vectors: { hit: "IBAN DE89 3704 0044 0532 0130 00, please", clean: "IBAN DE89 3704 0044 0532 0130 01, please" }
6142
+ },
6143
+ {
6144
+ name: "passport_number",
6145
+ pattern: "\\bpassport(?:\\s*(?:no|number|#))?\\.?\\s*[:=#]?\\s*[A-Z]{0,2}[0-9]{6,9}\\b",
6146
+ severity: "high",
6147
+ description: "Passport Number",
6148
+ keywords: ["passport"],
6149
+ vectors: { hit: "Passport No: X1234567", clean: "Passport photos: 2 copies" }
5209
6150
  }
5210
6151
  ]
5211
6152
  };
@@ -5231,16 +6172,14 @@ async function openShareLink(api, url, opts = {}) {
5231
6172
  throw new OpenError("url_invalid", "share code missing from the URL path (/s/<seal_id>/<share_code>#<key>)");
5232
6173
  }
5233
6174
  const { sealId, shareCode } = parsed;
5234
- if (parsed.fragmentVariant !== "key" && !opts.seed) {
5235
- throw new OpenError("targeted_fragment_invalid", "this link is addressed to someone: pass their seed to open it");
5236
- }
5237
- const seed = opts.seed;
5238
- const wrapped = parsed.fragmentVariant === "targeted_x25519_v1" ? parsed.fragment : opts.wrap ?? null;
5239
- let shareKey = parsed.fragmentVariant === "key" ? base64urlToBytes(parsed.fragment) : wrapped !== null && seed ? await openLinkWrap(wrapped, seed, sealId) : null;
6175
+ const seed2 = opts.seed;
6176
+ const wrapped = opts.wrap ?? null;
6177
+ let shareKey = parsed.fragmentVariant === "key" ? base64urlToBytes(parsed.fragment) : wrapped !== null && seed2 ? await openLinkWrap(wrapped, seed2, sealId) : null;
6178
+ if (shareKey !== null) await holdShareProof(sealId, shareKey);
5240
6179
  const request = opts.signal ? { signal: opts.signal } : {};
5241
6180
  let meta;
5242
6181
  try {
5243
- meta = toSealMetadata(await api.getMetadata(parsed.sealId, request));
6182
+ meta = toSealMetadata(await api.getMetadata(parsed.sealId, { ...request, shareCode }));
5244
6183
  } catch (err) {
5245
6184
  if (err instanceof BackendError && (err.code === "not_found" || err.code === "revoked")) {
5246
6185
  throw new OpenError(
@@ -5263,10 +6202,12 @@ async function openShareLink(api, url, opts = {}) {
5263
6202
  const share = await api.getShareBlob(sealId, shareCode, request);
5264
6203
  blobBytes = share.blob;
5265
6204
  if (shareKey === null) {
5266
- if (share.wrap === null || !seed) {
5267
- throw new OpenError("url_no_fragment", "the link carries no key and the server holds no wrap of it for this link");
6205
+ if (share.wrap === null) {
6206
+ throw new OpenError("url_no_fragment", "the link carries no key after #: copy it whole");
5268
6207
  }
5269
- shareKey = await openLinkWrap(share.wrap, seed, sealId);
6208
+ if (!seed2) throw new OpenError("targeted_fragment_invalid", "this link is addressed to someone: pass their seed to open it");
6209
+ shareKey = await openLinkWrap(share.wrap, seed2, sealId);
6210
+ await holdShareProof(sealId, shareKey);
5270
6211
  }
5271
6212
  } catch (err) {
5272
6213
  if (err instanceof OpenError) throw err;
@@ -5280,8 +6221,11 @@ async function openShareLink(api, url, opts = {}) {
5280
6221
  throw new OpenError("share_blob_fetch_failed", `share blob fetch failed: ${messageOf(err)}`, err);
5281
6222
  }
5282
6223
  let fileKeys;
6224
+ let bindings;
5283
6225
  try {
5284
- fileKeys = (await decryptShareBlob(blobBytes, shareKey)).file_keys;
6226
+ const blob = await decryptShareBlob(blobBytes, shareKey);
6227
+ fileKeys = blob.file_keys;
6228
+ bindings = bindingsOf(blob);
5285
6229
  } catch (err) {
5286
6230
  throw new OpenError(
5287
6231
  "share_blob_decrypt_failed",
@@ -5289,7 +6233,7 @@ async function openShareLink(api, url, opts = {}) {
5289
6233
  err
5290
6234
  );
5291
6235
  }
5292
- const files = await Promise.all(meta.files.map((f) => describeFile(f, fileKeys)));
6236
+ const files = await Promise.all(meta.files.map((f) => describeFile(f, fileKeys, bindings)));
5293
6237
  return {
5294
6238
  sealId,
5295
6239
  expiresAt: meta.expiresAt,
@@ -5300,9 +6244,9 @@ async function openShareLink(api, url, opts = {}) {
5300
6244
  files
5301
6245
  };
5302
6246
  }
5303
- async function openLinkWrap(wrap, seed, sealId) {
6247
+ async function openLinkWrap(wrap, seed2, sealId) {
5304
6248
  try {
5305
- return await openWrap(wrap, seed, SHARE_SCOPE, sealId);
6249
+ return await openWrap(wrap, seed2, SHARE_SCOPE, sealId);
5306
6250
  } catch (err) {
5307
6251
  const aead = err instanceof WrapError && err.kind === "aead";
5308
6252
  throw new OpenError(aead ? "targeted_decrypt_failed" : "targeted_fragment_invalid", messageOf(err), err);
@@ -5310,6 +6254,8 @@ async function openLinkWrap(wrap, seed, sealId) {
5310
6254
  }
5311
6255
  async function waitForIntake(api, intakeId, opts = {}) {
5312
6256
  for (; ; ) {
6257
+ opts.signal?.throwIfAborted();
6258
+ const askedAt = Date.now();
5313
6259
  let view;
5314
6260
  try {
5315
6261
  view = await api.getIntake(intakeId, { ...opts, waitSeconds: limits_default.limits.INTAKE_WAIT_MAX_SECONDS });
@@ -5320,11 +6266,29 @@ async function waitForIntake(api, intakeId, opts = {}) {
5320
6266
  throw err;
5321
6267
  }
5322
6268
  if (view.status === "expired") throw new OpenError("request_expired", "nobody answered before the request expired");
5323
- if (view.status === "fulfilled" && view.share_path && view.fragment) {
5324
- return { sharePath: view.share_path, wrap: view.fragment };
6269
+ if (view.status === "fulfilled") {
6270
+ if (view.share_path && view.fragment) return { sharePath: view.share_path, wrap: view.fragment };
6271
+ throw new OpenError("share_blob_corrupt", "the request was answered without its link");
5325
6272
  }
6273
+ if (view.status !== "pending") throw new OpenError("client_outdated", `the request is ${String(view.status)}, a state this client does not know`);
6274
+ const left = INTAKE_POLL_FLOOR_MS - (Date.now() - askedAt);
6275
+ if (left > 0) await pause(left, opts.signal);
5326
6276
  }
5327
6277
  }
6278
+ var INTAKE_POLL_FLOOR_MS = 2e3;
6279
+ function pause(ms, signal) {
6280
+ return new Promise((resolve2, reject) => {
6281
+ const onAbort = () => {
6282
+ clearTimeout(timer);
6283
+ reject(signal?.reason);
6284
+ };
6285
+ const timer = setTimeout(() => {
6286
+ signal?.removeEventListener("abort", onAbort);
6287
+ resolve2();
6288
+ }, ms);
6289
+ signal?.addEventListener("abort", onAbort, { once: true });
6290
+ });
6291
+ }
5328
6292
  var ANSWER_MAX_BYTES = 64 * 1024;
5329
6293
  async function readAnswerFile(api, url, mime, opts) {
5330
6294
  const seal = await openShareLink(api, url, opts);
@@ -5332,7 +6296,7 @@ async function readAnswerFile(api, url, mime, opts) {
5332
6296
  if (!file?.key || !file.sha256Hex || more.length > 0 || bareMime(file.mime) !== mime || file.size > ANSWER_MAX_BYTES) {
5333
6297
  throw new OpenError("share_blob_corrupt", `the answer is not one ${mime} file`);
5334
6298
  }
5335
- const resp = await api.openDownload(seal.sealId, { fileId: file.id }, opts.signal ? { signal: opts.signal } : {});
6299
+ const resp = await api.downloadCiphertext(seal.sealId, { fileId: file.id }, opts.signal ? { signal: opts.signal } : {});
5336
6300
  if (!resp.body) throw new OpenError("share_blob_corrupt", "the answer came without a body");
5337
6301
  const reader = decryptVerified(resp.body, file.key, file.sha256Hex).stream.getReader();
5338
6302
  const chunks = [];
@@ -5352,46 +6316,38 @@ async function publishOwn(api, identity, opts) {
5352
6316
  if (held !== null && equalBytes(held, identity.bundle)) return;
5353
6317
  await api.putBundle(identity.bundle, opts);
5354
6318
  }
5355
- async function addressProof(api, seed, opts = {}) {
5356
- const identity = await identityOf(seed);
6319
+ async function addressProof(api, seed2, opts = {}) {
6320
+ const identity = await identityOf(seed2);
5357
6321
  const key2 = `${api.baseUrl} ${identity.address}`;
5358
6322
  const kept = proofs.get(key2);
5359
6323
  if (!opts.fresh && kept && kept.until > Date.now()) return kept.proof;
5360
6324
  await publishOwn(api, identity, opts);
5361
6325
  const challenge = await api.requestAddressProof(identity.address, opts);
5362
- const proof = { address: identity.address, proof: await proveInbox(seed, challenge) };
6326
+ const proof = { address: identity.address, proof: await proveInbox(seed2, challenge) };
5363
6327
  proofs.set(key2, { proof, until: Date.parse(challenge.expires_at) - PROOF_MARGIN_MS });
5364
6328
  return proof;
5365
6329
  }
5366
- async function withAddressProof(api, seed, signal, call) {
6330
+ async function withAddressProof(api, seed2, signal, call) {
5367
6331
  const request = signal ? { signal } : {};
5368
6332
  try {
5369
- return await call(await addressProof(api, seed, request));
6333
+ return await call(await addressProof(api, seed2, request));
5370
6334
  } catch (err) {
5371
6335
  if (!(err instanceof BackendError && err.appCode === "intake.proof_required")) throw err;
5372
- return call(await addressProof(api, seed, { ...request, fresh: true }));
6336
+ return call(await addressProof(api, seed2, { ...request, fresh: true }));
5373
6337
  }
5374
6338
  }
5375
- async function migrateInbox(api, seed, opts = {}) {
5376
- const { legacyAddress } = await identityOf(seed);
5377
- return withAddressProof(api, seed, opts.signal, async (proof) => {
5378
- const challenge = await api.migrateInbox(proof, { old_address: legacyAddress }, opts);
5379
- const oldProof = await proveLegacyAddress(seed, challenge.challenge, challenge.ts);
5380
- return (await api.migrateInbox(proof, { old_address: legacyAddress, old_proof: oldProof }, opts)).moved;
5381
- });
5382
- }
5383
- async function readInbox(api, seed, opts = {}) {
6339
+ async function readInbox(api, seed2, opts = {}) {
5384
6340
  const list = opts;
5385
- return withAddressProof(api, seed, opts.signal, (proof) => api.listInbox(proof, list));
6341
+ return withAddressProof(api, seed2, opts.signal, (proof) => api.listInbox(proof, list));
5386
6342
  }
5387
- async function removeFromInbox(api, seed, itemId, opts = {}) {
5388
- return withAddressProof(api, seed, opts.signal, (proof) => api.dismissInboxItem(itemId, proof, opts));
6343
+ async function removeFromInbox(api, seed2, itemId, opts = {}) {
6344
+ return withAddressProof(api, seed2, opts.signal, (proof) => api.dismissInboxItem(itemId, proof, opts));
5389
6345
  }
5390
- async function describeFile(file, fileKeys) {
6346
+ async function describeFile(file, fileKeys, bindings) {
5391
6347
  const keyB64 = file.sha256_hex ? fileKeys[file.sha256_hex] : void 0;
5392
6348
  const base = { id: file.id, size: file.size, sha256Hex: file.sha256_hex };
5393
6349
  if (keyB64 === void 0) {
5394
- return { ...base, name: ENCRYPTED_FILE_FALLBACK, mime: ENCRYPTED_MIME_FALLBACK, secret: false, key: null };
6350
+ return { ...base, name: ENCRYPTED_FILE_FALLBACK, mime: ENCRYPTED_MIME_FALLBACK, secret: false, key: null, binding: null };
5395
6351
  }
5396
6352
  let key2;
5397
6353
  try {
@@ -5403,7 +6359,9 @@ async function describeFile(file, fileKeys) {
5403
6359
  throw new OpenError("share_blob_corrupt", `share blob key for ${file.sha256_hex} is ${key2.length} bytes`);
5404
6360
  }
5405
6361
  const { name: name2, mime } = await decryptFileMetadataWithBytes(file, key2);
5406
- return { ...base, name: name2, mime, secret: bareMime(mime) === SECRET_MIME, key: key2 };
6362
+ const secret = bareMime(mime) === SECRET_MIME;
6363
+ const binding = secret && file.sha256_hex ? bindings[file.sha256_hex] ?? null : null;
6364
+ return { ...base, name: name2, mime, secret, key: key2, binding };
5407
6365
  }
5408
6366
  function bareMime(mime) {
5409
6367
  return (mime.split(";")[0] ?? mime).trim().toLowerCase();
@@ -5423,7 +6381,7 @@ function decryptVerified(body, key2, expectedSha256, onCiphertext = () => void 0
5423
6381
  controller.enqueue(chunk);
5424
6382
  }
5425
6383
  });
5426
- const count = new TransformStream({
6384
+ const count2 = new TransformStream({
5427
6385
  transform(plaintext, controller) {
5428
6386
  plainHash.update(plaintext);
5429
6387
  sizeBytes += plaintext.length;
@@ -5434,7 +6392,7 @@ function decryptVerified(body, key2, expectedSha256, onCiphertext = () => void 0
5434
6392
  settle.resolve({ sizeBytes, sha256: bytesToHex(plainHash.digest()) });
5435
6393
  }
5436
6394
  });
5437
- const stream = body.pipeThrough(tap).pipeThrough(createDecryptStream(keyCopy, { expectedSha256Hex: expectedSha256 })).pipeThrough(count);
6395
+ const stream = body.pipeThrough(tap).pipeThrough(createDecryptStream(keyCopy, { expectedSha256Hex: expectedSha256 })).pipeThrough(count2);
5438
6396
  return { stream: rejectDoneOnError(stream, settle.reject, keyCopy), done };
5439
6397
  }
5440
6398
  function openErrorOf(err) {
@@ -5472,115 +6430,10 @@ function rejectDoneOnError(stream, reject, keyCopy) {
5472
6430
  function messageOf(err) {
5473
6431
  return err instanceof Error ? err.message : String(err);
5474
6432
  }
5475
- var REPLACEMENT_CHAR = "_";
5476
- var MAX_FILENAME_LENGTH = 200;
5477
- var WINDOWS_RESERVED_NAMES = /* @__PURE__ */ new Set([
5478
- "CON",
5479
- "PRN",
5480
- "AUX",
5481
- "NUL",
5482
- "COM1",
5483
- "COM2",
5484
- "COM3",
5485
- "COM4",
5486
- "COM5",
5487
- "COM6",
5488
- "COM7",
5489
- "COM8",
5490
- "COM9",
5491
- "LPT1",
5492
- "LPT2",
5493
- "LPT3",
5494
- "LPT4",
5495
- "LPT5",
5496
- "LPT6",
5497
- "LPT7",
5498
- "LPT8",
5499
- "LPT9"
5500
- ]);
5501
- function detectPlatform() {
5502
- if (typeof process !== "undefined" && process.platform) {
5503
- switch (process.platform) {
5504
- case "win32":
5505
- return "windows";
5506
- case "darwin":
5507
- return "macos";
5508
- case "linux":
5509
- return "linux";
5510
- case "android":
5511
- return "android";
5512
- default:
5513
- return "unknown";
5514
- }
5515
- }
5516
- if (typeof navigator !== "undefined" && navigator.userAgent) {
5517
- const ua = navigator.userAgent.toLowerCase();
5518
- if (ua.includes("win")) return "windows";
5519
- if (ua.includes("android")) return "android";
5520
- if (ua.includes("iphone") || ua.includes("ipad") || ua.includes("ipod")) return "ios";
5521
- if (ua.includes("mac")) return "macos";
5522
- if (ua.includes("linux")) return "linux";
5523
- }
5524
- return "unknown";
5525
- }
5526
- function isValidChar(char, platform) {
5527
- const code = char.charCodeAt(0);
5528
- if (code < 32 || code === 127) return false;
5529
- switch (platform) {
5530
- case "windows":
5531
- return !/[<>:"/\\|?*]/.test(char);
5532
- case "macos":
5533
- case "ios":
5534
- return !/[/:]/.test(char);
5535
- case "linux":
5536
- case "android":
5537
- return char !== "/";
5538
- default:
5539
- return !/[<>:"/\\|?*]/.test(char);
5540
- }
5541
- }
5542
- function isWindowsReservedName(name2) {
5543
- const baseName = name2.split(".")[0].toUpperCase();
5544
- return WINDOWS_RESERVED_NAMES.has(baseName);
5545
- }
5546
- function sanitizeFilename(filename, options = {}) {
5547
- const {
5548
- platform = detectPlatform(),
5549
- replacement = REPLACEMENT_CHAR,
5550
- maxLength = MAX_FILENAME_LENGTH,
5551
- fallback = "file"
5552
- } = options;
5553
- if (!filename || !filename.trim()) {
5554
- return fallback;
5555
- }
5556
- let result = filename.normalize("NFC");
5557
- result = result.trim();
5558
- result = result.replace(/^\.+|\.+$/g, "");
5559
- const chars = [...result];
5560
- result = chars.map((char) => isValidChar(char, platform) ? char : replacement).join("");
5561
- const escapedReplacement = replacement.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5562
- result = result.replace(new RegExp(`${escapedReplacement}+`, "g"), replacement);
5563
- result = result.replace(new RegExp(`^(?:\\.|${escapedReplacement})+|${escapedReplacement}+$`, "g"), "");
5564
- if (platform === "windows" || platform === "unknown") {
5565
- if (isWindowsReservedName(result)) {
5566
- result = `${replacement}${result}`;
5567
- }
5568
- }
5569
- if (result.length > maxLength) {
5570
- const lastDot = result.lastIndexOf(".");
5571
- if (lastDot > 0 && lastDot > result.length - 10) {
5572
- const ext = result.slice(lastDot);
5573
- const base = result.slice(0, maxLength - ext.length);
5574
- result = base + ext;
5575
- } else {
5576
- result = result.slice(0, maxLength);
5577
- }
5578
- }
5579
- if (!result || result === replacement) {
5580
- return fallback;
5581
- }
5582
- return result;
5583
- }
6433
+ var LEASE_DEFAULT_DAYS = limits_default.limits.LEASE_DEFAULT_DAYS;
6434
+ var LEASE_MAX_DAYS = limits_default.limits.LEASE_MAX_DAYS;
6435
+ var LEASE_POLL_SECONDS = limits_default.limits.LEASE_POLL_SECONDS;
6436
+ var LEASE_STATUS_BATCH_MAX = limits_default.limits.LEASE_STATUS_BATCH_MAX;
5584
6437
 
5585
6438
  var limits_default2 = {
5586
6439
  version: 1,
@@ -5625,7 +6478,7 @@ var limits_default2 = {
5625
6478
  description: "One-time payment for 500 GB storage and 12 months TTL"
5626
6479
  }
5627
6480
  },
5628
- PRO_REGIONS: ["eu-west", "us-east", "us-west", "apac-southeast", "apac-northeast"],
6481
+ PRO_REGIONS: ["eu-west", "eu-central", "us-east", "us-west", "apac-southeast", "apac-northeast"],
5629
6482
  ttl_options: ["5m", "30m", "1h", "1d", "7d"],
5630
6483
  OTP_LENGTH: { min: 6, max: 10 },
5631
6484
  USER_PASSWORD_MIN_LENGTH: 8,
@@ -5635,6 +6488,13 @@ var limits_default2 = {
5635
6488
  PAYMENT_WAIT_MAX_SECONDS: 82800,
5636
6489
  ADDRESS_PROOF_TTL_SECONDS: 300,
5637
6490
  INBOX_MAX_ITEMS: 200,
6491
+ LEASE_DEFAULT_DAYS: 7,
6492
+ LEASE_MAX_DAYS: 90,
6493
+ LEASE_STATUS_BATCH_MAX: 500,
6494
+ LEASE_POLL_SECONDS: 600,
6495
+ LEASE_KEEP_DAYS: 30,
6496
+ APPROVE_WAIT_SECONDS: 120,
6497
+ APPROVE_BODY_SHOWN_BYTES: 2048,
5638
6498
  DRIVE_OPEN_TTL_SECONDS: 300,
5639
6499
  DRIVE_PRESIGN_WINDOW_DEFAULT_BYTES: 67108864,
5640
6500
  DRIVE_PRESIGN_WINDOW_MIN_BYTES: 8388608,
@@ -5665,7 +6525,7 @@ var SealError = class _SealError extends Error {
5665
6525
  this.name = "SealError";
5666
6526
  this.code = code;
5667
6527
  this.status = status;
5668
- this.details = details;
6528
+ this.details = details && withHiddenSecrets(details);
5669
6529
  if (Error.captureStackTrace) Error.captureStackTrace(this, _SealError);
5670
6530
  }
5671
6531
  toJSON() {
@@ -5678,6 +6538,17 @@ var SealError = class _SealError extends Error {
5678
6538
  };
5679
6539
  }
5680
6540
  };
6541
+ var SECRET_DETAILS = ["ownerToken", "ownerLinkKey"];
6542
+ function withHiddenSecrets(details) {
6543
+ const shown = { ...details };
6544
+ for (const name2 of SECRET_DETAILS) {
6545
+ if (!(name2 in shown)) continue;
6546
+ const value = shown[name2];
6547
+ delete shown[name2];
6548
+ Object.defineProperty(shown, name2, { value, enumerable: false, writable: false, configurable: false });
6549
+ }
6550
+ return shown;
6551
+ }
5681
6552
  var OPEN_CODES = {
5682
6553
  url_invalid: "VALIDATION_ERROR",
5683
6554
  url_no_fragment: "VALIDATION_ERROR",
@@ -5931,14 +6802,14 @@ var AnonymousSealsSendResource = class {
5931
6802
  try {
5932
6803
  const shareBlobB64 = bytesToBase64url(shareBlob);
5933
6804
  shareCode = recipient && fragment ? await proven(
5934
- (sender) => this.api.createShareLink(result.sealId, ownerTokenB64, shareBlobB64, {
6805
+ (sender) => this.api.createShareLink(result.sealId, ownerTokenB64, shareBlobB64, shareLinkKey, {
5935
6806
  ...signalOpt,
5936
6807
  to: recipient,
5937
6808
  fragment,
5938
6809
  label: "sealnet",
5939
6810
  ...sender ? { sender } : {}
5940
6811
  })
5941
- ) : await this.api.createShareLink(result.sealId, ownerTokenB64, shareBlobB64, signalOpt);
6812
+ ) : await this.api.createShareLink(result.sealId, ownerTokenB64, shareBlobB64, shareLinkKey, signalOpt);
5942
6813
  } catch (err) {
5943
6814
  throw sealErrorFrom(
5944
6815
  err,
@@ -6026,11 +6897,16 @@ async function receiveToDisk(opened, dir, name2) {
6026
6897
  try {
6027
6898
  await fs.link(tmp, candidate);
6028
6899
  } catch (err) {
6029
- if (err.code === "EEXIST") continue;
6030
- throw err;
6900
+ const code = err.code;
6901
+ if (code === "EEXIST") continue;
6902
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EOPNOTSUPP" && code !== "ENOSYS") throw err;
6903
+ if (await fs.access(candidate).then(() => true, () => false)) continue;
6904
+ await fs.rename(tmp, candidate);
6905
+ placed = true;
6906
+ return { path: candidate, sizeBytes, sha256: sha2563 };
6031
6907
  }
6032
- await fs.unlink(tmp);
6033
6908
  placed = true;
6909
+ await fs.unlink(tmp).catch(() => void 0);
6034
6910
  return { path: candidate, sizeBytes, sha256: sha2563 };
6035
6911
  }
6036
6912
  throw new Error(`no free name for ${name2} in ${dir}`);
@@ -6043,10 +6919,16 @@ async function receiveToDisk(opened, dir, name2) {
6043
6919
  }
6044
6920
 
6045
6921
  // src/receive.ts
6922
+ var SECRET_KEY = /^[A-Za-z0-9_-]{86}$/;
6923
+ function seedOf(keyPair) {
6924
+ if (SECRET_KEY.test(keyPair.secretKey)) return base64urlToBytes(keyPair.secretKey);
6925
+ const said = keyPair.secretKey.length === 43 ? "This key is of the kind before: make a new one with keygen() and give its address to whoever sends to you. What was sent to the old address does not open." : "secretKey is not a SEAL key: expected the 86 base64url characters keygen() gives";
6926
+ throw new SealError(said, "INVALID_KEY", 400);
6927
+ }
6046
6928
  async function resolve(api, url, opts, wrap) {
6047
6929
  const request = opts.signal ? { signal: opts.signal } : {};
6048
6930
  const seal = await openShareLink(api, url, {
6049
- ...opts.keyPair ? { seed: base64urlToBytes(opts.keyPair.secretKey) } : {},
6931
+ ...opts.keyPair ? { seed: seedOf(opts.keyPair) } : {},
6050
6932
  ...wrap ? { wrap } : {},
6051
6933
  ...request
6052
6934
  });
@@ -6062,7 +6944,7 @@ async function resolve(api, url, opts, wrap) {
6062
6944
  const total = covered.reduce((sum, f) => sum + f.size, 0);
6063
6945
  let done = 0;
6064
6946
  const read = async (file) => {
6065
- const resp = await api.openDownload(
6947
+ const resp = await api.downloadCiphertext(
6066
6948
  seal.sealId,
6067
6949
  { fileId: file.id, ...sessionCookie ? { sessionCookie } : {} },
6068
6950
  request
@@ -6151,7 +7033,7 @@ async function pairWith(api, siteOrigin, opts) {
6151
7033
  const { sharePath, wrap } = await waitIntake(api, intake.id, opts.signal);
6152
7034
  try {
6153
7035
  const file = await readAnswerFile(api, `${siteOrigin}${sharePath}`, PAIRING_MIME, {
6154
- seed: base64urlToBytes(opts.keyPair.secretKey),
7036
+ seed: seedOf(opts.keyPair),
6155
7037
  wrap,
6156
7038
  ...opts.signal ? { signal: opts.signal } : {}
6157
7039
  });
@@ -6174,10 +7056,9 @@ async function keygen() {
6174
7056
  return { secretKey: bytesToBase64url(seed), address, bundle: bytesToBase64url(bundle2), words };
6175
7057
  }
6176
7058
  async function inboxOf(api, opts) {
6177
- const seed = base64urlToBytes(opts.keyPair.secretKey);
7059
+ const seed = seedOf(opts.keyPair);
6178
7060
  const deadline = Date.now() + (opts.wait ?? 0) * 1e3;
6179
7061
  try {
6180
- await migrateInbox(api, seed, opts.signal ? { signal: opts.signal } : {}).catch(() => 0);
6181
7062
  for (; ; ) {
6182
7063
  const left = Math.ceil((deadline - Date.now()) / 1e3);
6183
7064
  const wire = await readInbox(api, seed, {
@@ -6206,7 +7087,7 @@ async function inboxOf(api, opts) {
6206
7087
  async function inboxRow(api, site, item, opts) {
6207
7088
  let items;
6208
7089
  try {
6209
- items = (await readInbox(api, base64urlToBytes(opts.keyPair.secretKey), opts.signal ? { signal: opts.signal } : {})).items;
7090
+ items = (await readInbox(api, seedOf(opts.keyPair), opts.signal ? { signal: opts.signal } : {})).items;
6210
7091
  } catch (err) {
6211
7092
  throw sealErrorFrom(err, "Failed to read the inbox");
6212
7093
  }
@@ -6218,14 +7099,14 @@ async function inboxRow(api, site, item, opts) {
6218
7099
  }
6219
7100
  async function dismissItem(api, item, opts) {
6220
7101
  try {
6221
- await removeFromInbox(api, base64urlToBytes(opts.keyPair.secretKey), item.id, opts.signal ? { signal: opts.signal } : {});
7102
+ await removeFromInbox(api, seedOf(opts.keyPair), item.id, opts.signal ? { signal: opts.signal } : {});
6222
7103
  } catch (err) {
6223
7104
  throw sealErrorFrom(err, "Failed to remove the item");
6224
7105
  }
6225
7106
  }
6226
7107
 
6227
7108
  // src/index.ts
6228
- var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/2.0.3".split("/");
7109
+ var [CLIENT_NAME = "", CLIENT_VERSION = ""] = "sealnet-js/3.0.0".split("/");
6229
7110
  if (typeof globalThis.process?.versions?.node !== "string") {
6230
7111
  configureWasm(define_SEAL_WASM_default);
6231
7112
  }