@tinycloud/cli 0.9.0 → 0.9.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4499,11 +4499,11 @@ function bytesToHex(bytes3) {
4499
4499
  abytes(bytes3);
4500
4500
  if (hasHexBuiltin)
4501
4501
  return bytes3.toHex();
4502
- let hex2 = "";
4502
+ let hex3 = "";
4503
4503
  for (let i = 0; i < bytes3.length; i++) {
4504
- hex2 += hexes[bytes3[i]];
4504
+ hex3 += hexes[bytes3[i]];
4505
4505
  }
4506
- return hex2;
4506
+ return hex3;
4507
4507
  }
4508
4508
  function asciiToBase16(ch) {
4509
4509
  if (ch >= asciis._0 && ch <= asciis._9)
@@ -4514,21 +4514,21 @@ function asciiToBase16(ch) {
4514
4514
  return ch - (asciis.a - 10);
4515
4515
  return;
4516
4516
  }
4517
- function hexToBytes(hex2) {
4518
- if (typeof hex2 !== "string")
4519
- throw new Error("hex string expected, got " + typeof hex2);
4517
+ function hexToBytes(hex3) {
4518
+ if (typeof hex3 !== "string")
4519
+ throw new Error("hex string expected, got " + typeof hex3);
4520
4520
  if (hasHexBuiltin)
4521
- return Uint8Array.fromHex(hex2);
4522
- const hl = hex2.length;
4521
+ return Uint8Array.fromHex(hex3);
4522
+ const hl = hex3.length;
4523
4523
  const al = hl / 2;
4524
4524
  if (hl % 2)
4525
4525
  throw new Error("hex string expected, got unpadded hex of length " + hl);
4526
4526
  const array = new Uint8Array(al);
4527
4527
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
4528
- const n1 = asciiToBase16(hex2.charCodeAt(hi));
4529
- const n2 = asciiToBase16(hex2.charCodeAt(hi + 1));
4528
+ const n1 = asciiToBase16(hex3.charCodeAt(hi));
4529
+ const n2 = asciiToBase16(hex3.charCodeAt(hi + 1));
4530
4530
  if (n1 === void 0 || n2 === void 0) {
4531
- const char = hex2[hi] + hex2[hi + 1];
4531
+ const char = hex3[hi] + hex3[hi + 1];
4532
4532
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
4533
4533
  }
4534
4534
  array[ai] = n1 * 16 + n2;
@@ -5162,10 +5162,10 @@ function _abytes2(value, length5, title = "") {
5162
5162
  }
5163
5163
  return value;
5164
5164
  }
5165
- function hexToNumber(hex2) {
5166
- if (typeof hex2 !== "string")
5167
- throw new Error("hex string expected, got " + typeof hex2);
5168
- return hex2 === "" ? _0n : BigInt("0x" + hex2);
5165
+ function hexToNumber(hex3) {
5166
+ if (typeof hex3 !== "string")
5167
+ throw new Error("hex string expected, got " + typeof hex3);
5168
+ return hex3 === "" ? _0n : BigInt("0x" + hex3);
5169
5169
  }
5170
5170
  function bytesToNumberBE(bytes3) {
5171
5171
  return hexToNumber(bytesToHex(bytes3));
@@ -5180,16 +5180,16 @@ function numberToBytesBE(n, len) {
5180
5180
  function numberToBytesLE(n, len) {
5181
5181
  return numberToBytesBE(n, len).reverse();
5182
5182
  }
5183
- function ensureBytes(title, hex2, expectedLength) {
5183
+ function ensureBytes(title, hex3, expectedLength) {
5184
5184
  let res;
5185
- if (typeof hex2 === "string") {
5185
+ if (typeof hex3 === "string") {
5186
5186
  try {
5187
- res = hexToBytes(hex2);
5187
+ res = hexToBytes(hex3);
5188
5188
  } catch (e) {
5189
5189
  throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
5190
5190
  }
5191
- } else if (isBytes(hex2)) {
5192
- res = Uint8Array.from(hex2);
5191
+ } else if (isBytes(hex3)) {
5192
+ res = Uint8Array.from(hex3);
5193
5193
  } else {
5194
5194
  throw new Error(title + " must be hex string or Uint8Array");
5195
5195
  }
@@ -6707,8 +6707,8 @@ var init_ed25519 = __esm({
6707
6707
  return new __RistrettoPoint(ep);
6708
6708
  }
6709
6709
  /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
6710
- static hashToCurve(hex2) {
6711
- return ristretto255_map(ensureBytes("ristrettoHash", hex2, 64));
6710
+ static hashToCurve(hex3) {
6711
+ return ristretto255_map(ensureBytes("ristrettoHash", hex3, 64));
6712
6712
  }
6713
6713
  static fromBytes(bytes3) {
6714
6714
  abytes(bytes3, 32);
@@ -6741,8 +6741,8 @@ var init_ed25519 = __esm({
6741
6741
  * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
6742
6742
  * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
6743
6743
  */
6744
- static fromHex(hex2) {
6745
- return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex2, 32));
6744
+ static fromHex(hex3) {
6745
+ return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex3, 32));
6746
6746
  }
6747
6747
  static msm(points, scalars) {
6748
6748
  return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
@@ -6953,14 +6953,14 @@ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
6953
6953
  function padHex(hex_, { dir, size: size2 = 32 } = {}) {
6954
6954
  if (size2 === null)
6955
6955
  return hex_;
6956
- const hex2 = hex_.replace("0x", "");
6957
- if (hex2.length > size2 * 2)
6956
+ const hex3 = hex_.replace("0x", "");
6957
+ if (hex3.length > size2 * 2)
6958
6958
  throw new SizeExceedsPaddingSizeError({
6959
- size: Math.ceil(hex2.length / 2),
6959
+ size: Math.ceil(hex3.length / 2),
6960
6960
  targetSize: size2,
6961
6961
  type: "hex"
6962
6962
  });
6963
- return `0x${hex2[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
6963
+ return `0x${hex3[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
6964
6964
  }
6965
6965
  function padBytes(bytes3, { dir, size: size2 = 32 } = {}) {
6966
6966
  if (size2 === null)
@@ -7012,21 +7012,21 @@ function assertSize(hexOrBytes, { size: size2 }) {
7012
7012
  maxSize: size2
7013
7013
  });
7014
7014
  }
7015
- function hexToBigInt(hex2, opts = {}) {
7015
+ function hexToBigInt(hex3, opts = {}) {
7016
7016
  const { signed } = opts;
7017
7017
  if (opts.size)
7018
- assertSize(hex2, { size: opts.size });
7019
- const value = BigInt(hex2);
7018
+ assertSize(hex3, { size: opts.size });
7019
+ const value = BigInt(hex3);
7020
7020
  if (!signed)
7021
7021
  return value;
7022
- const size2 = (hex2.length - 2) / 2;
7022
+ const size2 = (hex3.length - 2) / 2;
7023
7023
  const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
7024
7024
  if (value <= max)
7025
7025
  return value;
7026
7026
  return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
7027
7027
  }
7028
- function hexToNumber2(hex2, opts = {}) {
7029
- const value = hexToBigInt(hex2, opts);
7028
+ function hexToNumber2(hex3, opts = {}) {
7029
+ const value = hexToBigInt(hex3, opts);
7030
7030
  const number = Number(value);
7031
7031
  if (!Number.isSafeInteger(number))
7032
7032
  throw new IntegerOutOfRangeError({
@@ -7058,24 +7058,24 @@ function toHex(value, opts = {}) {
7058
7058
  return bytesToHex2(value, opts);
7059
7059
  }
7060
7060
  function boolToHex(value, opts = {}) {
7061
- const hex2 = `0x${Number(value)}`;
7061
+ const hex3 = `0x${Number(value)}`;
7062
7062
  if (typeof opts.size === "number") {
7063
- assertSize(hex2, { size: opts.size });
7064
- return pad(hex2, { size: opts.size });
7063
+ assertSize(hex3, { size: opts.size });
7064
+ return pad(hex3, { size: opts.size });
7065
7065
  }
7066
- return hex2;
7066
+ return hex3;
7067
7067
  }
7068
7068
  function bytesToHex2(value, opts = {}) {
7069
7069
  let string2 = "";
7070
7070
  for (let i = 0; i < value.length; i++) {
7071
7071
  string2 += hexes2[value[i]];
7072
7072
  }
7073
- const hex2 = `0x${string2}`;
7073
+ const hex3 = `0x${string2}`;
7074
7074
  if (typeof opts.size === "number") {
7075
- assertSize(hex2, { size: opts.size });
7076
- return pad(hex2, { dir: "right", size: opts.size });
7075
+ assertSize(hex3, { size: opts.size });
7076
+ return pad(hex3, { dir: "right", size: opts.size });
7077
7077
  }
7078
- return hex2;
7078
+ return hex3;
7079
7079
  }
7080
7080
  function numberToHex(value_, opts = {}) {
7081
7081
  const { signed, size: size2 } = opts;
@@ -7100,10 +7100,10 @@ function numberToHex(value_, opts = {}) {
7100
7100
  value: `${value_}${suffix}`
7101
7101
  });
7102
7102
  }
7103
- const hex2 = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
7103
+ const hex3 = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
7104
7104
  if (size2)
7105
- return pad(hex2, { size: size2 });
7106
- return hex2;
7105
+ return pad(hex3, { size: size2 });
7106
+ return hex3;
7107
7107
  }
7108
7108
  function stringToHex(value_, opts = {}) {
7109
7109
  const value = encoder.encode(value_);
@@ -7150,12 +7150,12 @@ function charCodeToBase16(char) {
7150
7150
  return void 0;
7151
7151
  }
7152
7152
  function hexToBytes2(hex_, opts = {}) {
7153
- let hex2 = hex_;
7153
+ let hex3 = hex_;
7154
7154
  if (opts.size) {
7155
- assertSize(hex2, { size: opts.size });
7156
- hex2 = pad(hex2, { dir: "right", size: opts.size });
7155
+ assertSize(hex3, { size: opts.size });
7156
+ hex3 = pad(hex3, { dir: "right", size: opts.size });
7157
7157
  }
7158
- let hexString = hex2.slice(2);
7158
+ let hexString = hex3.slice(2);
7159
7159
  if (hexString.length % 2)
7160
7160
  hexString = `0${hexString}`;
7161
7161
  const length5 = hexString.length / 2;
@@ -7171,8 +7171,8 @@ function hexToBytes2(hex_, opts = {}) {
7171
7171
  return bytes3;
7172
7172
  }
7173
7173
  function numberToBytes(value, opts) {
7174
- const hex2 = numberToHex(value, opts);
7175
- return hexToBytes2(hex2);
7174
+ const hex3 = numberToHex(value, opts);
7175
+ return hexToBytes2(hex3);
7176
7176
  }
7177
7177
  function stringToBytes(value, opts = {}) {
7178
7178
  const bytes3 = encoder2.encode(value);
@@ -7662,23 +7662,23 @@ function abool(title, value) {
7662
7662
  throw new Error(title + " boolean expected, got " + value);
7663
7663
  }
7664
7664
  function numberToHexUnpadded(num2) {
7665
- const hex2 = num2.toString(16);
7666
- return hex2.length & 1 ? "0" + hex2 : hex2;
7665
+ const hex3 = num2.toString(16);
7666
+ return hex3.length & 1 ? "0" + hex3 : hex3;
7667
7667
  }
7668
- function hexToNumber3(hex2) {
7669
- if (typeof hex2 !== "string")
7670
- throw new Error("hex string expected, got " + typeof hex2);
7671
- return hex2 === "" ? _0n8 : BigInt("0x" + hex2);
7668
+ function hexToNumber3(hex3) {
7669
+ if (typeof hex3 !== "string")
7670
+ throw new Error("hex string expected, got " + typeof hex3);
7671
+ return hex3 === "" ? _0n8 : BigInt("0x" + hex3);
7672
7672
  }
7673
7673
  function bytesToHex3(bytes3) {
7674
7674
  abytes2(bytes3);
7675
7675
  if (hasHexBuiltin2)
7676
7676
  return bytes3.toHex();
7677
- let hex2 = "";
7677
+ let hex3 = "";
7678
7678
  for (let i = 0; i < bytes3.length; i++) {
7679
- hex2 += hexes3[bytes3[i]];
7679
+ hex3 += hexes3[bytes3[i]];
7680
7680
  }
7681
- return hex2;
7681
+ return hex3;
7682
7682
  }
7683
7683
  function asciiToBase162(ch) {
7684
7684
  if (ch >= asciis2._0 && ch <= asciis2._9)
@@ -7689,21 +7689,21 @@ function asciiToBase162(ch) {
7689
7689
  return ch - (asciis2.a - 10);
7690
7690
  return;
7691
7691
  }
7692
- function hexToBytes3(hex2) {
7693
- if (typeof hex2 !== "string")
7694
- throw new Error("hex string expected, got " + typeof hex2);
7692
+ function hexToBytes3(hex3) {
7693
+ if (typeof hex3 !== "string")
7694
+ throw new Error("hex string expected, got " + typeof hex3);
7695
7695
  if (hasHexBuiltin2)
7696
- return Uint8Array.fromHex(hex2);
7697
- const hl = hex2.length;
7696
+ return Uint8Array.fromHex(hex3);
7697
+ const hl = hex3.length;
7698
7698
  const al = hl / 2;
7699
7699
  if (hl % 2)
7700
7700
  throw new Error("hex string expected, got unpadded hex of length " + hl);
7701
7701
  const array = new Uint8Array(al);
7702
7702
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
7703
- const n1 = asciiToBase162(hex2.charCodeAt(hi));
7704
- const n2 = asciiToBase162(hex2.charCodeAt(hi + 1));
7703
+ const n1 = asciiToBase162(hex3.charCodeAt(hi));
7704
+ const n2 = asciiToBase162(hex3.charCodeAt(hi + 1));
7705
7705
  if (n1 === void 0 || n2 === void 0) {
7706
- const char = hex2[hi] + hex2[hi + 1];
7706
+ const char = hex3[hi] + hex3[hi + 1];
7707
7707
  throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
7708
7708
  }
7709
7709
  array[ai] = n1 * 16 + n2;
@@ -7723,16 +7723,16 @@ function numberToBytesBE2(n, len) {
7723
7723
  function numberToBytesLE2(n, len) {
7724
7724
  return numberToBytesBE2(n, len).reverse();
7725
7725
  }
7726
- function ensureBytes2(title, hex2, expectedLength) {
7726
+ function ensureBytes2(title, hex3, expectedLength) {
7727
7727
  let res;
7728
- if (typeof hex2 === "string") {
7728
+ if (typeof hex3 === "string") {
7729
7729
  try {
7730
- res = hexToBytes3(hex2);
7730
+ res = hexToBytes3(hex3);
7731
7731
  } catch (e) {
7732
7732
  throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
7733
7733
  }
7734
- } else if (isBytes2(hex2)) {
7735
- res = Uint8Array.from(hex2);
7734
+ } else if (isBytes2(hex3)) {
7735
+ res = Uint8Array.from(hex3);
7736
7736
  } else {
7737
7737
  throw new Error(title + " must be hex string or Uint8Array");
7738
7738
  }
@@ -8573,8 +8573,8 @@ function weierstrassPoints(opts) {
8573
8573
  * Converts hash string or Uint8Array to Point.
8574
8574
  * @param hex short/long ECDSA hex
8575
8575
  */
8576
- static fromHex(hex2) {
8577
- const P = Point2.fromAffine(fromBytes2(ensureBytes2("pointHex", hex2)));
8576
+ static fromHex(hex3) {
8577
+ const P = Point2.fromAffine(fromBytes2(ensureBytes2("pointHex", hex3)));
8578
8578
  P.assertValidity();
8579
8579
  return P;
8580
8580
  }
@@ -8929,15 +8929,15 @@ function weierstrass(curveDef) {
8929
8929
  Object.freeze(this);
8930
8930
  }
8931
8931
  // pair (bytes of r, bytes of s)
8932
- static fromCompact(hex2) {
8932
+ static fromCompact(hex3) {
8933
8933
  const l = nByteLength;
8934
- hex2 = ensureBytes2("compactSignature", hex2, l * 2);
8935
- return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l));
8934
+ hex3 = ensureBytes2("compactSignature", hex3, l * 2);
8935
+ return new Signature(slcNum(hex3, 0, l), slcNum(hex3, l, 2 * l));
8936
8936
  }
8937
8937
  // DER encoded ECDSA signature
8938
8938
  // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
8939
- static fromDER(hex2) {
8940
- const { r, s } = DER.toSig(ensureBytes2("DER", hex2));
8939
+ static fromDER(hex3) {
8940
+ const { r, s } = DER.toSig(ensureBytes2("DER", hex3));
8941
8941
  return new Signature(r, s);
8942
8942
  }
8943
8943
  /**
@@ -9354,12 +9354,12 @@ var init_weierstrass = __esm({
9354
9354
  const { Err: E } = DER;
9355
9355
  if (num2 < _0n11)
9356
9356
  throw new E("integer: negative integers are not allowed");
9357
- let hex2 = numberToHexUnpadded(num2);
9358
- if (Number.parseInt(hex2[0], 16) & 8)
9359
- hex2 = "00" + hex2;
9360
- if (hex2.length & 1)
9357
+ let hex3 = numberToHexUnpadded(num2);
9358
+ if (Number.parseInt(hex3[0], 16) & 8)
9359
+ hex3 = "00" + hex3;
9360
+ if (hex3.length & 1)
9361
9361
  throw new E("unexpected DER parsing assertion: unpadded hex");
9362
- return hex2;
9362
+ return hex3;
9363
9363
  },
9364
9364
  decode(data) {
9365
9365
  const { Err: E } = DER;
@@ -9370,9 +9370,9 @@ var init_weierstrass = __esm({
9370
9370
  return bytesToNumberBE2(data);
9371
9371
  }
9372
9372
  },
9373
- toSig(hex2) {
9373
+ toSig(hex3) {
9374
9374
  const { Err: E, _int: int, _tlv: tlv } = DER;
9375
- const data = ensureBytes2("signature", hex2);
9375
+ const data = ensureBytes2("signature", hex3);
9376
9376
  const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
9377
9377
  if (seqLeftBytes.length)
9378
9378
  throw new E("invalid signature: left bytes after parsing");
@@ -16833,7 +16833,10 @@ var init_dist2 = __esm({
16833
16833
  const descriptor = usable.data;
16834
16834
  const networkPublicKey = base64Decode2(descriptor.publicEncryptionKey);
16835
16835
  const result = encryptToNetwork(this.crypto, {
16836
- networkId,
16836
+ // Discovery returns the node's canonical network identifier. Persist
16837
+ // that spelling in the envelope so a later response can be compared
16838
+ // byte-for-byte (notably for checksummed did:pkh principals).
16839
+ networkId: descriptor.networkId,
16837
16840
  networkPublicKey,
16838
16841
  plaintext,
16839
16842
  ...options?.aad !== void 0 ? { aad: options.aad } : {},
@@ -18159,6 +18162,14 @@ function signingBytesV2(unsigned) {
18159
18162
  bytes3.set(body, domain.length);
18160
18163
  return bytes3;
18161
18164
  }
18165
+ function signingBytesV3(unsigned) {
18166
+ const domain = utf8Bytes(ENVELOPE_V3_SIGNATURE_DOMAIN);
18167
+ const body = utf8Bytes(canonicalize2(unsigned));
18168
+ const bytes3 = new Uint8Array(domain.length + body.length);
18169
+ bytes3.set(domain);
18170
+ bytes3.set(body, domain.length);
18171
+ return bytes3;
18172
+ }
18162
18173
  function signEnvelope(envelopeWithoutSig, ed25519PrivKey) {
18163
18174
  const unsigned = unsignedShareEnvelopeSchema.parse(envelopeWithoutSig);
18164
18175
  const publicKey = ed25519.getPublicKey(ed25519PrivKey);
@@ -18206,6 +18217,92 @@ async function verifyEnvelopeV2(envelope, options) {
18206
18217
  if (parsed.authorizationTarget.kind === "policy") return await computeCid(fromBase64Url(parsed.authorizationTarget.policyBytes)) === parsed.authorizationTarget.policyCid;
18207
18218
  return true;
18208
18219
  }
18220
+ function verifyEnvelopeV3SignatureOnly(envelope) {
18221
+ const parsed = shareEnvelopeV3Schema.parse(envelope);
18222
+ const { signature, ...unsigned } = parsed;
18223
+ return ed25519.verify(fromBase64Url(signature.value), sha2562(signingBytesV3(unsigned)), ed25519PublicKeyFromDidKey(signature.signerDid), ED25519_VERIFY_OPTS2);
18224
+ }
18225
+ async function verifyEnvelopeV3(envelope, options) {
18226
+ const parsed = shareEnvelopeV3Schema.parse(envelope);
18227
+ if (parsed.signature.signerDid !== options.expectedSignerDid || parsed.signature.signerDid !== parsed.policy.ownerDid || !verifyEnvelopeV3SignatureOnly(parsed)) return false;
18228
+ const { policy } = parsed;
18229
+ const unsignedPolicy = { ...policy };
18230
+ delete unsignedPolicy.policyId;
18231
+ delete unsignedPolicy.signature;
18232
+ const policySignatureDomain = policy.schema === "xyz.tinycloud.policy/policy/v2" ? POLICY_V2_SIGNATURE_DOMAIN : POLICY_V1_SIGNATURE_DOMAIN;
18233
+ const policyDigest = sha2562(new TextEncoder().encode(`${policySignatureDomain}${canonicalize2(unsignedPolicy)}`));
18234
+ const policySignature = policy.signature;
18235
+ if (policySignature.suite !== "Ed25519" || policySignature.signerDid !== policy.ownerDid) return false;
18236
+ let policyPublicKey;
18237
+ let policySignatureBytes;
18238
+ try {
18239
+ policyPublicKey = ed25519PublicKeyFromDidKey(policy.ownerDid);
18240
+ policySignatureBytes = fromBase64Url(policySignature.value);
18241
+ } catch {
18242
+ return false;
18243
+ }
18244
+ if (policySignatureBytes.length !== 64 || !ed25519.verify(policySignatureBytes, policyDigest, policyPublicKey, ED25519_VERIFY_OPTS2)) return false;
18245
+ const policyIdDigest = policyDigest;
18246
+ if (policy.policyId !== `pol_${base32Lower(policyIdDigest)}`) return false;
18247
+ const policyBytes = new TextEncoder().encode(canonicalize2(policy));
18248
+ if (await computeCid(policyBytes) !== parsed.policyCid) return false;
18249
+ const sourceDigest = sha2562(new TextEncoder().encode(`${CONTENT_SOURCE_V1_DOMAIN}${canonicalize2(policy.contentSource)}`));
18250
+ if (hex(sourceDigest) !== parsed.contentSourceDigestHex) return false;
18251
+ const sortedCapabilities = [...policy.capabilityCeiling].sort((left, right) => canonicalize2(left).localeCompare(canonicalize2(right)));
18252
+ const capabilityCeilingHashHex = hex(sha2562(new TextEncoder().encode(`${POLICY_CAPABILITY_V1_DOMAIN}${canonicalize2(sortedCapabilities)}`)));
18253
+ const nativeProjection = sortedCapabilities.map((capability) => capability.kind === "encryption" ? { service: "tinycloud.encryption", space: capability.resource, path: capability.resource, actions: [capability.action] } : { service: "tinycloud.kv", space: capability.resource.slice(0, capability.resource.indexOf("/kv/")), path: capability.resource.split("/kv/")[1], actions: [...capability.actions], caveat: { type: "xyz.tinycloud.resource/selector", kind: capability.selector, value: capability.resource } }).sort((left, right) => canonicalize2(left).localeCompare(canonicalize2(right)));
18254
+ const nativeProjectionHashHex = hex(sha2562(new TextEncoder().encode(`${NATIVE_PROJECTION_V1_DOMAIN}${canonicalize2(nativeProjection)}`)));
18255
+ const expectedAttenuation = Object.fromEntries(sortedCapabilities.map((capability) => capability.kind === "encryption" ? [capability.resource, { [capability.action]: [{}] }] : [capability.resource, Object.fromEntries(capability.actions.map((action) => [action, [{ kind: capability.selector, type: "xyz.tinycloud.resource/selector", value: capability.resource }]]))]));
18256
+ const kv = policy.capabilityCeiling.find((capability) => capability.kind === "kv");
18257
+ const expectedKvActions = parsed.actions.flatMap((action) => action === "read" ? ["tinycloud.kv/get", "tinycloud.kv/metadata"] : action === "list" ? ["tinycloud.kv/list"] : ["tinycloud.kv/put"]);
18258
+ const marker = parsed.contentSource.kvResource.indexOf("/kv/");
18259
+ const resourceSpace = marker < 1 ? "" : parsed.contentSource.kvResource.slice(0, marker);
18260
+ const resourcePath = marker < 1 ? "" : parsed.contentSource.kvResource.slice(marker + 4);
18261
+ if (parsed.shareId !== parsed.contentSource.shareId || resourceSpace !== parsed.target.spaceId || resourcePath !== parsed.resource.path.replace(/\/$/, "") || parsed.resource.kind !== parsed.contentSource.selector || kv?.kind !== "kv" || expectedKvActions.some((action) => !kv.actions.includes(action)) || parsed.encryptionNetwork !== parsed.contentSource.encryptionNetwork || parsed.contentSource.keyVersion <= 0 || policy.expiresAt !== void 0 && Date.parse(parsed.expiry) > Date.parse(policy.expiresAt)) return false;
18262
+ const binding = parsed.attestedEnforcerBinding;
18263
+ const { signature: bindingSignature, ...unsignedBinding } = binding;
18264
+ const expectedBindingDigestHex = hex(sha2562(new TextEncoder().encode(canonicalize2({ enforcerDid: binding.enforcerDid, nodeAudience: binding.nodeAudience }))));
18265
+ if (binding.enforcerDid !== parsed.target.nodeAudience || binding.nodeAudience !== parsed.target.nodeAudience || binding.attestationBindingDigestHex !== expectedBindingDigestHex || bindingSignature.signerDid !== binding.enforcerDid || bindingSignature.suite !== "Ed25519" || Date.parse(binding.issuedAt) > Date.now() || Date.parse(binding.expiresAt) <= Date.now() || Date.parse(binding.expiresAt) < Date.parse(parsed.expiry)) return false;
18266
+ try {
18267
+ const digest4 = sha2562(new TextEncoder().encode(`${ATTESTED_ENFORCER_V2_DOMAIN}${canonicalize2(unsignedBinding)}`));
18268
+ if (!ed25519.verify(fromBase64Url(bindingSignature.value), digest4, ed25519PublicKeyFromDidKey(binding.enforcerDid), ED25519_VERIFY_OPTS2)) return false;
18269
+ } catch {
18270
+ return false;
18271
+ }
18272
+ if (parsed.policyRoot.role !== "policy-authority" || parsed.enforcementRoot.role !== "policy-enforcement" || parsed.policyRoot.cid === parsed.enforcementRoot.cid) return false;
18273
+ try {
18274
+ const policyRoot = verifyCompactUcanAuthorization(parsed.policyRoot.authorization, parsed.policyRoot.cid);
18275
+ const enforcementRoot = verifyCompactUcanAuthorization(parsed.enforcementRoot.authorization, parsed.enforcementRoot.cid);
18276
+ const policyFact = policyRoot.payload.fct[0];
18277
+ const enforcementFact = enforcementRoot.payload.fct[0];
18278
+ const common = ["ownerDid", "policyId", "policyDigestHex", "policyCid", "contentSourceDigestHex", "capabilityCeilingHashHex", "nativeProjectionHashHex", "nodeAudience"];
18279
+ const policyKeys = [...common, "role", "mode"];
18280
+ const enforcementKeys = [...policyKeys, "enforcerDid"];
18281
+ if (Object.keys(policyFact).length !== policyKeys.length || policyKeys.some((key) => !(key in policyFact)) || Object.keys(enforcementFact).length !== enforcementKeys.length || enforcementKeys.some((key) => !(key in enforcementFact)) || policyRoot.payload.prf.length !== 0 || enforcementRoot.payload.prf.length !== 0 || policyRoot.payload.iss.split("#", 1)[0] !== policy.ownerDid || enforcementRoot.payload.iss.split("#", 1)[0] !== policy.ownerDid || policyRoot.payload.nbf !== enforcementRoot.payload.nbf || policyRoot.payload.exp !== enforcementRoot.payload.exp || canonicalize2(policyRoot.payload.att) !== canonicalize2(expectedAttenuation) || canonicalize2(enforcementRoot.payload.att) !== canonicalize2(expectedAttenuation) || policyFact.role !== "policy-authority" || policyFact.mode !== "policy-source" || "enforcerDid" in policyFact || enforcementFact.role !== "policy-enforcement" || enforcementFact.mode !== "conditional-mint" || policyRoot.payload.aud !== `did:tinycloud:policy:${hex(policyIdDigest)}` || enforcementRoot.payload.aud !== parsed.target.nodeAudience || enforcementFact.enforcerDid !== parsed.target.nodeAudience || common.some((key) => policyFact[key] !== enforcementFact[key]) || policyFact.ownerDid !== policy.ownerDid || policyFact.policyId !== policy.policyId || policyFact.policyDigestHex !== hex(policyIdDigest) || policyFact.policyCid !== parsed.policyCid || policyFact.contentSourceDigestHex !== parsed.contentSourceDigestHex || policyFact.capabilityCeilingHashHex !== capabilityCeilingHashHex || policyFact.nativeProjectionHashHex !== nativeProjectionHashHex || policyFact.nodeAudience !== parsed.target.nodeAudience || policyRoot.payload.exp * 1e3 < Date.parse(parsed.expiry)) return false;
18282
+ } catch {
18283
+ return false;
18284
+ }
18285
+ return true;
18286
+ }
18287
+ function hex(bytes3) {
18288
+ return [...bytes3].map((byte) => byte.toString(16).padStart(2, "0")).join("");
18289
+ }
18290
+ function base32Lower(bytes3) {
18291
+ const alphabet2 = "abcdefghijklmnopqrstuvwxyz234567";
18292
+ let output = "";
18293
+ let buffer = 0;
18294
+ let bits = 0;
18295
+ for (const byte of bytes3) {
18296
+ buffer = buffer << 8 | byte;
18297
+ bits += 8;
18298
+ while (bits >= 5) {
18299
+ output += alphabet2[buffer >>> bits - 5 & 31];
18300
+ bits -= 5;
18301
+ }
18302
+ }
18303
+ if (bits > 0) output += alphabet2[buffer << 5 - bits & 31];
18304
+ return output;
18305
+ }
18209
18306
  function assertCanonicalCid(cidString) {
18210
18307
  const cid2 = CID.parse(cidString);
18211
18308
  if (cid2.version !== 1 || cid2.code !== code || cid2.multihash.code !== 18 || // sha2-256 (0x12) only, at the link layer too
@@ -18384,7 +18481,7 @@ function registryFetcher(options, limit, tooLargeCode = "max-bytes-exceeded", st
18384
18481
  };
18385
18482
  }
18386
18483
  function metadataFor(envelope, origin) {
18387
- if (envelope.version === 2) {
18484
+ if (envelope.version === 2 || envelope.version === 3) {
18388
18485
  const targetKind3 = envelope.recipientMatcher.kind === "recipientDid" ? "recipientDid" : envelope.recipientMatcher.kind === "exactEmail" ? "email" : envelope.recipientMatcher.kind === "emailDomain" ? "emailDomain" : "bearer";
18389
18486
  return {
18390
18487
  protocol: "tinycloud-share",
@@ -18400,7 +18497,7 @@ function metadataFor(envelope, origin) {
18400
18497
  ...envelope.display.filename === void 0 ? {} : { filename: envelope.display.filename },
18401
18498
  ...envelope.display.mode === void 0 ? {} : { mode: envelope.display.mode }
18402
18499
  },
18403
- ...envelope.content === void 0 ? {} : { content: { cid: envelope.content.cid } }
18500
+ ...envelope.version === 2 && envelope.content !== void 0 ? { content: { cid: envelope.content.cid } } : {}
18404
18501
  };
18405
18502
  }
18406
18503
  return {
@@ -18425,8 +18522,10 @@ function parseEnvelope(bytes3) {
18425
18522
  const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes3);
18426
18523
  const value = JSON.parse(text);
18427
18524
  if (canonicalize2(value) !== text) throw new Error("share envelope is not canonical JSON");
18428
- if (typeof value === "object" && value !== null && !Array.isArray(value) && value.version === 2) {
18429
- return shareEnvelopeV2Schema.parse(value);
18525
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
18526
+ const version3 = value.version;
18527
+ if (version3 === 3) return shareEnvelopeV3Schema.parse(value);
18528
+ if (version3 === 2) return shareEnvelopeV2Schema.parse(value);
18430
18529
  }
18431
18530
  return shareEnvelopeSchema.parse(value);
18432
18531
  } catch {
@@ -18498,6 +18597,19 @@ async function verifyV2Envelope(envelope, linkOrigin, options) {
18498
18597
  if (options.trustedSignerDid === void 0 || envelope.signature.signerDid !== options.trustedSignerDid) throw new ShareReceiveError("signature-invalid", "an addressed signer trust root is required");
18499
18598
  }
18500
18599
  }
18600
+ async function verifyV3Envelope(envelope, linkOrigin, options) {
18601
+ if (options.expectedOrigin !== void 0 && linkOrigin !== options.expectedOrigin) {
18602
+ throw new ShareReceiveError("origin-mismatch", "share link origin does not match the trusted origin");
18603
+ }
18604
+ try {
18605
+ if (!await verifyEnvelopeV3(envelope, { expectedSignerDid: envelope.policy.ownerDid })) throw new Error("signature");
18606
+ } catch {
18607
+ throw new ShareReceiveError("signature-invalid", "share signature is invalid");
18608
+ }
18609
+ const expiry = Date.parse(envelope.expiry);
18610
+ if (!Number.isFinite(expiry)) throw new ShareReceiveError("envelope-invalid", "share expiry is invalid");
18611
+ if (expiry <= (options.now?.() ?? Date.now())) throw new ShareReceiveError("expired", "share has expired", { expiresAt: envelope.expiry });
18612
+ }
18501
18613
  async function verifyV1PolicyEnvelope(envelope, linkOrigin, options) {
18502
18614
  if (envelope.authorizationTarget.kind !== "policy") throw new ShareReceiveError("unsupported-target", "share target is not an addressed policy", { reason: "policy-target" });
18503
18615
  if (envelope.target.origin !== linkOrigin || options.expectedOrigin !== void 0 && (linkOrigin !== options.expectedOrigin || envelope.target.origin !== options.expectedOrigin)) {
@@ -18529,12 +18641,18 @@ async function inspectShare(link2, options = {}) {
18529
18641
  const resolved = await resolveShareEnvelope(link2, options);
18530
18642
  if (resolved.envelope.version === 1 && resolved.envelope.authorizationTarget.kind === "policy") await verifyV1PolicyEnvelope(resolved.envelope, resolved.origin, options);
18531
18643
  else if (resolved.envelope.version === 1) await verifyResolved(resolved.envelope, resolved.origin, options);
18532
- else await verifyV2Envelope(resolved.envelope, resolved.origin, options);
18533
- if (resolved.envelope.version === 2 || resolved.envelope.authorizationTarget.kind === "policy") options.onResolvedAddressedEnvelope?.(resolved.envelope, resolved.cid);
18644
+ else if (resolved.envelope.version === 2) await verifyV2Envelope(resolved.envelope, resolved.origin, options);
18645
+ else await verifyV3Envelope(resolved.envelope, resolved.origin, options);
18646
+ if (resolved.envelope.version === 2 || resolved.envelope.version === 3 || resolved.envelope.authorizationTarget.kind === "policy") options.onResolvedAddressedEnvelope?.(resolved.envelope, resolved.cid);
18534
18647
  return { metadata: metadataFor(resolved.envelope, resolved.origin), link: { origin: resolved.origin, cid: resolved.cid, kind: resolved.kind } };
18535
18648
  }
18536
18649
  async function receiveShare(link2, options = {}) {
18537
18650
  const resolved = await resolveShareEnvelope(link2, options);
18651
+ if (resolved.envelope.version === 3) {
18652
+ await verifyV3Envelope(resolved.envelope, resolved.origin, options);
18653
+ options.onResolvedAddressedEnvelope?.(resolved.envelope, resolved.cid);
18654
+ return { state: "authorization-required", method: resolved.envelope.recipientMatcher.kind === "recipientDid" ? "openkey-device" : "email-claim" };
18655
+ }
18538
18656
  if (resolved.envelope.version === 2) {
18539
18657
  await verifyV2Envelope(resolved.envelope, resolved.origin, options);
18540
18658
  options.onResolvedAddressedEnvelope?.(resolved.envelope, resolved.cid);
@@ -20147,11 +20265,11 @@ function uiAction(action) {
20147
20265
  function selectedAction(envelope) {
20148
20266
  return envelope.actions.includes("list") ? "tinycloud.kv/list" : envelope.actions.includes("edit") ? "tinycloud.kv/put" : "tinycloud.kv/get";
20149
20267
  }
20150
- function hex(value) {
20268
+ function hex2(value) {
20151
20269
  return [...value].map((byte) => byte.toString(16).padStart(2, "0")).join("");
20152
20270
  }
20153
20271
  function canonicalHashHex2(value) {
20154
- return hex(sha2562(new TextEncoder().encode(canonicalize2(value))));
20272
+ return hex2(sha2562(new TextEncoder().encode(canonicalize2(value))));
20155
20273
  }
20156
20274
  async function aesGcmDecrypt(key, blob) {
20157
20275
  if (key.length !== 32 || blob.length < 28) throw new Error("encrypted content is malformed");
@@ -20237,7 +20355,7 @@ function createAddressedAuthorization(input) {
20237
20355
  }
20238
20356
  };
20239
20357
  }
20240
- var __defProp2, __export2, external_exports2, util2, objectUtil2, ZodParsedType2, getParsedType2, ZodIssueCode2, quotelessJson2, ZodError2, errorMap2, en_default2, overrideErrorMap2, makeIssue2, EMPTY_PATH2, ParseStatus2, INVALID2, DIRTY2, OK2, isAborted2, isDirty2, isValid2, isAsync2, errorUtil2, ParseInputLazyPath2, handleResult2, ZodType2, cuidRegex2, cuid2Regex2, ulidRegex2, uuidRegex2, nanoidRegex2, jwtRegex2, durationRegex2, emailRegex2, _emojiRegex2, emojiRegex2, ipv4Regex2, ipv4CidrRegex2, ipv6Regex2, ipv6CidrRegex2, base64Regex2, base64urlRegex2, dateRegexSource2, dateRegex2, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator2, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum2, ZodPromise2, ZodEffects2, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND2, ZodBranded2, ZodPipeline2, ZodReadonly2, late2, ZodFirstPartyTypeKind2, instanceOfType2, stringType2, numberType2, nanType2, bigIntType2, booleanType2, dateType2, symbolType2, undefinedType2, nullType2, anyType2, unknownType2, neverType2, voidType2, arrayType2, objectType2, strictObjectType2, unionType2, discriminatedUnionType2, intersectionType2, tupleType2, recordType2, mapType2, setType2, functionType2, lazyType2, literalType2, enumType2, nativeEnumType2, promiseType2, effectsType2, optionalType2, nullableType2, preprocessType2, pipelineType2, ostring2, onumber2, oboolean2, coerce2, NEVER2, empty, src, _brrp__multiformats_scope_baseX, base_x_default, Encoder, Decoder, ComposedDecoder, Codec, base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z, base36, base36upper, base58btc, base58flickr, encode_1, MSB, REST, MSBALL, INT, decode2, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default, Digest, cache, CID, DAG_PB_CODE, SHA_256_CODE, cidSymbol, code, SHA256_CODE, base64, base64pad, base64url, base64urlpad, ED25519_MULTICODEC_PREFIX, PUBLIC_KEY_LENGTH, base64UrlString, sessionJwkCommonFields, okpPrivateJwkSchema, ecPrivateJwkSchema, sessionJwkSchema, policyTargetSchema, bearerKeyTargetSchema, recipientDidTargetSchema, authorizationTargetSchema, resourceSelectorSchema, targetSchema, displaySchema, contentPointerSchema, signatureSchema, unsignedShareEnvelopeSchema, shareEnvelopeSchema, recipientMatcherSchema, shareActionSchema, kvContentSourceSchema, sqlContentSourceSchema, contentSourceSchema, v2TargetSchema, shareDecryptionSchema, ownerAuthoritySchema, contentMetadataSchema, unsignedShareEnvelopeV2BaseSchema, unsignedShareEnvelopeV2Schema, shareEnvelopeV2Schema, unifiedResourceSchema, unifiedEncryptionNetworkSchema, unifiedKvCapabilitySchema, unifiedEncryptionCapabilitySchema, unifiedCapabilitySchema, unifiedContentSourceSchema, unifiedPolicySchema, unifiedRootSchema, attestedEnforcerBindingV2Schema, v3TargetSchema, unsignedShareEnvelopeV3BaseSchema, unsignedShareEnvelopeV3Schema, shareEnvelopeV3Schema, BEARER_READ_ABILITY, READ_ABILITIES, ED25519_VERIFY_OPTS, ENVELOPE_AAD_LABEL, SEALED_BLOB_VERSION, AAD, KEY_LENGTH, NONCE_LENGTH, TAG_LENGTH, HEADER_LENGTH, ED25519_VERIFY_OPTS2, ENVELOPE_SIGNATURE_DOMAIN, ENVELOPE_V2_SIGNATURE_DOMAIN, KEY_LENGTH2, INLINE_PREFIX, MAX_INLINE_BYTES, SHARE_RESULT_VERSION, DEFAULT_MAX_SEALED_BLOB_BYTES, DEFAULT_MAX_CONTENT_BLOB_BYTES, CONTENT_SEALED_OVERHEAD, ShareReceiveError, SHARE_CONTENT_LIMIT, SHARE_SEALED_OVERHEAD, SHARE_PUBLISH_RESULT_VERSION, DEFAULT_SHARE_LIFETIME_MS, SharePublishError, empty2, src2, _brrp__multiformats_scope_baseX2, base_x_default2, Encoder2, Decoder2, ComposedDecoder2, Codec2, base322, base32upper2, base32pad2, base32padupper2, base32hex2, base32hexupper2, base32hexpad2, base32hexpadupper2, base32z2, base362, base36upper2, base58btc2, base58flickr2, encode_12, MSB2, REST2, MSBALL2, INT2, decode6, MSB$12, REST$12, N12, N22, N32, N42, N52, N62, N72, N82, N92, length2, varint2, _brrp_varint2, varint_default2, Digest2, cache2, CID2, DAG_PB_CODE2, SHA_256_CODE2, cidSymbol2, code2, SHA256_CODE2, MAX_CONTENT_BYTES, POLICY_ENFORCEMENT_DOMAIN, POLICY_DOMAIN, OWNER_SHARE_REGISTRATION_DOMAIN, ENVELOPE_DOMAIN, ENVELOPE_DOMAIN2, ShareNotifyError, SHARE_V2_PROTOCOL, DOMAIN, PRESENTATION_DOMAIN, SESSION_DOMAIN, INVOCATION_DOMAIN, BASE64_ALPHABET, ShareRecipientClient;
20358
+ var __defProp2, __export2, external_exports2, util2, objectUtil2, ZodParsedType2, getParsedType2, ZodIssueCode2, quotelessJson2, ZodError2, errorMap2, en_default2, overrideErrorMap2, makeIssue2, EMPTY_PATH2, ParseStatus2, INVALID2, DIRTY2, OK2, isAborted2, isDirty2, isValid2, isAsync2, errorUtil2, ParseInputLazyPath2, handleResult2, ZodType2, cuidRegex2, cuid2Regex2, ulidRegex2, uuidRegex2, nanoidRegex2, jwtRegex2, durationRegex2, emailRegex2, _emojiRegex2, emojiRegex2, ipv4Regex2, ipv4CidrRegex2, ipv6Regex2, ipv6CidrRegex2, base64Regex2, base64urlRegex2, dateRegexSource2, dateRegex2, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator2, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum2, ZodPromise2, ZodEffects2, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND2, ZodBranded2, ZodPipeline2, ZodReadonly2, late2, ZodFirstPartyTypeKind2, instanceOfType2, stringType2, numberType2, nanType2, bigIntType2, booleanType2, dateType2, symbolType2, undefinedType2, nullType2, anyType2, unknownType2, neverType2, voidType2, arrayType2, objectType2, strictObjectType2, unionType2, discriminatedUnionType2, intersectionType2, tupleType2, recordType2, mapType2, setType2, functionType2, lazyType2, literalType2, enumType2, nativeEnumType2, promiseType2, effectsType2, optionalType2, nullableType2, preprocessType2, pipelineType2, ostring2, onumber2, oboolean2, coerce2, NEVER2, empty, src, _brrp__multiformats_scope_baseX, base_x_default, Encoder, Decoder, ComposedDecoder, Codec, base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z, base36, base36upper, base58btc, base58flickr, encode_1, MSB, REST, MSBALL, INT, decode2, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default, Digest, cache, CID, DAG_PB_CODE, SHA_256_CODE, cidSymbol, code, SHA256_CODE, base64, base64pad, base64url, base64urlpad, ED25519_MULTICODEC_PREFIX, PUBLIC_KEY_LENGTH, base64UrlString, sessionJwkCommonFields, okpPrivateJwkSchema, ecPrivateJwkSchema, sessionJwkSchema, policyTargetSchema, bearerKeyTargetSchema, recipientDidTargetSchema, authorizationTargetSchema, resourceSelectorSchema, targetSchema, displaySchema, contentPointerSchema, signatureSchema, unsignedShareEnvelopeSchema, shareEnvelopeSchema, recipientMatcherSchema, shareActionSchema, kvContentSourceSchema, sqlContentSourceSchema, contentSourceSchema, v2TargetSchema, shareDecryptionSchema, ownerAuthoritySchema, contentMetadataSchema, unsignedShareEnvelopeV2BaseSchema, unsignedShareEnvelopeV2Schema, shareEnvelopeV2Schema, unifiedResourceSchema, unifiedEncryptionNetworkSchema, unifiedKvCapabilitySchema, unifiedEncryptionCapabilitySchema, unifiedCapabilitySchema, unifiedContentSourceSchema, unifiedPolicyV1Schema, policyCredentialRequirementV1Schema, unifiedPolicyV2Schema, unifiedPolicySchema, unifiedRootSchema, attestedEnforcerBindingV2Schema, v3TargetSchema, unsignedShareEnvelopeV3BaseSchema, unsignedShareEnvelopeV3Schema, shareEnvelopeV3Schema, BEARER_READ_ABILITY, READ_ABILITIES, ED25519_VERIFY_OPTS, ENVELOPE_AAD_LABEL, SEALED_BLOB_VERSION, AAD, KEY_LENGTH, NONCE_LENGTH, TAG_LENGTH, HEADER_LENGTH, ED25519_VERIFY_OPTS2, ENVELOPE_SIGNATURE_DOMAIN, ENVELOPE_V2_SIGNATURE_DOMAIN, ENVELOPE_V3_SIGNATURE_DOMAIN, POLICY_V1_SIGNATURE_DOMAIN, POLICY_V2_SIGNATURE_DOMAIN, CONTENT_SOURCE_V1_DOMAIN, POLICY_CAPABILITY_V1_DOMAIN, NATIVE_PROJECTION_V1_DOMAIN, ATTESTED_ENFORCER_V2_DOMAIN, KEY_LENGTH2, INLINE_PREFIX, MAX_INLINE_BYTES, SHARE_RESULT_VERSION, DEFAULT_MAX_SEALED_BLOB_BYTES, DEFAULT_MAX_CONTENT_BLOB_BYTES, CONTENT_SEALED_OVERHEAD, ShareReceiveError, SHARE_CONTENT_LIMIT, SHARE_SEALED_OVERHEAD, SHARE_PUBLISH_RESULT_VERSION, DEFAULT_SHARE_LIFETIME_MS, SharePublishError, empty2, src2, _brrp__multiformats_scope_baseX2, base_x_default2, Encoder2, Decoder2, ComposedDecoder2, Codec2, base322, base32upper2, base32pad2, base32padupper2, base32hex2, base32hexupper2, base32hexpad2, base32hexpadupper2, base32z2, base362, base36upper2, base58btc2, base58flickr2, encode_12, MSB2, REST2, MSBALL2, INT2, decode6, MSB$12, REST$12, N12, N22, N32, N42, N52, N62, N72, N82, N92, length2, varint2, _brrp_varint2, varint_default2, Digest2, cache2, CID2, DAG_PB_CODE2, SHA_256_CODE2, cidSymbol2, code2, SHA256_CODE2, MAX_CONTENT_BYTES, POLICY_ENFORCEMENT_DOMAIN, POLICY_DOMAIN, OWNER_SHARE_REGISTRATION_DOMAIN, ENVELOPE_DOMAIN, ENVELOPE_DOMAIN2, ShareNotifyError, SHARE_V2_PROTOCOL, DOMAIN, PRESENTATION_DOMAIN, SESSION_DOMAIN, INVOCATION_DOMAIN, BASE64_ALPHABET, ShareRecipientClient;
20241
20359
  var init_dist3 = __esm({
20242
20360
  "../share-sdk/dist/index.js"() {
20243
20361
  "use strict";
@@ -20246,6 +20364,7 @@ var init_dist3 = __esm({
20246
20364
  init_ed25519();
20247
20365
  init_blake3();
20248
20366
  init_ed25519();
20367
+ init_sha256();
20249
20368
  init_ed25519();
20250
20369
  init_ed25519();
20251
20370
  init_sha256();
@@ -24738,9 +24857,12 @@ var init_dist3 = __esm({
24738
24857
  unsignedShareEnvelopeV2Schema = unsignedShareEnvelopeV2BaseSchema.superRefine(validateV2Invariants);
24739
24858
  shareEnvelopeV2Schema = unsignedShareEnvelopeV2BaseSchema.extend({ signature: signatureSchema }).strict().superRefine(validateV2Invariants);
24740
24859
  unifiedResourceSchema = external_exports2.string().refine((value) => {
24741
- const match = /^tinycloud:\/\/([^/]+)\/kv\/(.+)$/.exec(value);
24742
- if (match === null || /[:?#%]/.test(match[1])) return false;
24743
- const path = match[2];
24860
+ const marker = value.indexOf("/kv/");
24861
+ if (marker < 1) return false;
24862
+ const space = value.slice(0, marker);
24863
+ const legacy = space.startsWith("tinycloud://");
24864
+ if (legacy ? /[:/?#%]/.test(space.slice("tinycloud://".length)) : !space.startsWith("tinycloud:") || /[/?#%]/.test(space)) return false;
24865
+ const path = value.slice(marker + 4);
24744
24866
  return !path.startsWith("/") && !path.endsWith("/") && !path.includes("//") && path.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
24745
24867
  }, { message: "expected canonical TinyCloud KV resource" });
24746
24868
  unifiedEncryptionNetworkSchema = external_exports2.string().refine((value) => {
@@ -24778,7 +24900,7 @@ var init_dist3 = __esm({
24778
24900
  mode: external_exports2.union([external_exports2.literal("mutable"), external_exports2.literal("immutable")]),
24779
24901
  initialCiphertextDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/).optional()
24780
24902
  }).strict();
24781
- unifiedPolicySchema = external_exports2.object({
24903
+ unifiedPolicyV1Schema = external_exports2.object({
24782
24904
  schema: external_exports2.literal("xyz.tinycloud.policy/policy/v1"),
24783
24905
  policyId: external_exports2.string().regex(/^pol_[a-z2-7]+$/),
24784
24906
  ownerDid: external_exports2.string().min(1),
@@ -24788,6 +24910,31 @@ var init_dist3 = __esm({
24788
24910
  capabilityCeiling: external_exports2.array(unifiedCapabilitySchema).min(2),
24789
24911
  signature: external_exports2.object({ suite: external_exports2.string().min(1), signerDid: external_exports2.string().min(1), value: external_exports2.string().min(1) }).strict()
24790
24912
  }).strict();
24913
+ policyCredentialRequirementV1Schema = external_exports2.object({
24914
+ type: external_exports2.literal("TinyCloudPolicyCredentialRequirement"),
24915
+ version: external_exports2.literal(1),
24916
+ requirementDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
24917
+ descriptorDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
24918
+ issuerDid: external_exports2.string().min(1),
24919
+ issuerKid: external_exports2.string().min(1),
24920
+ profile: external_exports2.object({ id: external_exports2.string().min(1), version: external_exports2.literal(1) }).strict(),
24921
+ credentialType: external_exports2.object({ id: external_exports2.string().min(1), version: external_exports2.literal(1) }).strict()
24922
+ }).strict();
24923
+ unifiedPolicyV2Schema = external_exports2.object({
24924
+ schema: external_exports2.literal("xyz.tinycloud.policy/policy/v2"),
24925
+ policyId: external_exports2.string().regex(/^pol_[a-z2-7]+$/),
24926
+ ownerDid: external_exports2.string().min(1),
24927
+ createdAt: external_exports2.string().datetime({ offset: true }),
24928
+ expiresAt: external_exports2.string().datetime({ offset: true }).optional(),
24929
+ contentSource: unifiedContentSourceSchema,
24930
+ capabilityCeiling: external_exports2.array(unifiedCapabilitySchema).min(2),
24931
+ credentialRequirement: policyCredentialRequirementV1Schema,
24932
+ signature: external_exports2.object({ suite: external_exports2.literal("Ed25519"), signerDid: external_exports2.string().min(1), value: external_exports2.string().min(1) }).strict()
24933
+ }).strict();
24934
+ unifiedPolicySchema = external_exports2.discriminatedUnion("schema", [
24935
+ unifiedPolicyV1Schema,
24936
+ unifiedPolicyV2Schema
24937
+ ]);
24791
24938
  unifiedRootSchema = external_exports2.object({
24792
24939
  cid: external_exports2.string().min(1),
24793
24940
  authorization: external_exports2.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/),
@@ -24843,6 +24990,13 @@ var init_dist3 = __esm({
24843
24990
  ED25519_VERIFY_OPTS2 = { zip215: false };
24844
24991
  ENVELOPE_SIGNATURE_DOMAIN = "xyz.tinycloud.share/envelope/v1\0";
24845
24992
  ENVELOPE_V2_SIGNATURE_DOMAIN = "xyz.tinycloud.share/envelope/v2\0";
24993
+ ENVELOPE_V3_SIGNATURE_DOMAIN = "xyz.tinycloud.share/envelope/v3\0";
24994
+ POLICY_V1_SIGNATURE_DOMAIN = "xyz.tinycloud.policy/policy/v1\0";
24995
+ POLICY_V2_SIGNATURE_DOMAIN = "xyz.tinycloud.policy/policy/v2\0";
24996
+ CONTENT_SOURCE_V1_DOMAIN = "xyz.tinycloud.policy/ContentSource/v1\0";
24997
+ POLICY_CAPABILITY_V1_DOMAIN = "xyz.tinycloud.policy/PolicyCapability/v1\0";
24998
+ NATIVE_PROJECTION_V1_DOMAIN = "xyz.tinycloud.policy/NativeProjection/v1\0";
24999
+ ATTESTED_ENFORCER_V2_DOMAIN = "xyz.tinycloud.policy/AttestedEnforcerBinding/v2\0";
24846
25000
  KEY_LENGTH2 = 32;
24847
25001
  INLINE_PREFIX = "#v=2&p=";
24848
25002
  MAX_INLINE_BYTES = 256 * 1024;
@@ -25509,7 +25663,7 @@ var init_dist3 = __esm({
25509
25663
  const receiverPublicKey = toBase64Url(x25519.getPublicKey(receiverPrivateKey));
25510
25664
  const receiverPublicKeyHash = canonicalHashHex2(receiverPublicKey);
25511
25665
  const body = { type: "tinycloud.encryption.decrypt/v1", targetNode: envelope.target.nodeAudience, networkId: encrypted.networkId, alg: encrypted.alg, keyVersion: encrypted.keyVersion, encryptedSymmetricKey: encrypted.encryptedSymmetricKey, encryptedSymmetricKeyHash: encrypted.encryptedSymmetricKeyHash, receiverPublicKey, receiverPublicKeyHash };
25512
- const bodyHash = hex(sha2562(new TextEncoder().encode(canonicalize2(body))));
25666
+ const bodyHash = hex2(sha2562(new TextEncoder().encode(canonicalize2(body))));
25513
25667
  const session = verifyCompactUcanAuthorization(this.v3Authorization, this.session.sessionId);
25514
25668
  const now = Math.floor(Date.now() / 1e3);
25515
25669
  const invocation = await signCompactUcanAuthorization({
@@ -25528,7 +25682,7 @@ var init_dist3 = __esm({
25528
25682
  if (!response.ok) throw new Error(`v3 decrypt invocation rejected (${response.status})`);
25529
25683
  const value = object2(await response.json(), "v3 decrypt response");
25530
25684
  const allowed = ["type", "targetNode", "networkId", "invocationCid", "encryptedSymmetricKeyHash", "receiverPublicKeyHash", "wrappedKey", "alg", "keyVersion", "requestHash", "nodeId", "nodeSignature"];
25531
- if (Object.keys(value).length !== allowed.length || Object.keys(value).some((key) => !allowed.includes(key)) || value.type !== "tinycloud.encryption.decrypt-result/v1" || value.targetNode !== body.targetNode || value.nodeId !== body.targetNode || value.networkId !== body.networkId || value.invocationCid !== invocation.cid || value.encryptedSymmetricKeyHash !== body.encryptedSymmetricKeyHash || value.receiverPublicKeyHash !== receiverPublicKeyHash || value.alg !== body.alg || value.keyVersion !== body.keyVersion || value.requestHash !== hex(sha2562(new TextEncoder().encode(`${invocation.cid}${bodyHash}`))) || typeof value.wrappedKey !== "string" || typeof value.nodeSignature !== "string") throw new Error("v3 decrypt response binding is invalid");
25685
+ if (Object.keys(value).length !== allowed.length || Object.keys(value).some((key) => !allowed.includes(key)) || value.type !== "tinycloud.encryption.decrypt-result/v1" || value.targetNode !== body.targetNode || value.nodeId !== body.targetNode || value.networkId !== body.networkId || value.invocationCid !== invocation.cid || value.encryptedSymmetricKeyHash !== body.encryptedSymmetricKeyHash || value.receiverPublicKeyHash !== receiverPublicKeyHash || value.alg !== body.alg || value.keyVersion !== body.keyVersion || value.requestHash !== hex2(sha2562(new TextEncoder().encode(`${invocation.cid}${bodyHash}`))) || typeof value.wrappedKey !== "string" || typeof value.nodeSignature !== "string") throw new Error("v3 decrypt response binding is invalid");
25532
25686
  const unsigned = { ...value };
25533
25687
  delete unsigned.nodeSignature;
25534
25688
  const signature = fromBase64(value.nodeSignature, "v3 decrypt response signature");
@@ -32159,9 +32313,12 @@ function validateV2Invariants2(value, ctx) {
32159
32313
  var unsignedShareEnvelopeV2Schema2 = unsignedShareEnvelopeV2BaseSchema2.superRefine(validateV2Invariants2);
32160
32314
  var shareEnvelopeV2Schema2 = unsignedShareEnvelopeV2BaseSchema2.extend({ signature: signatureSchema2 }).strict().superRefine(validateV2Invariants2);
32161
32315
  var unifiedResourceSchema2 = external_exports.string().refine((value) => {
32162
- const match = /^tinycloud:\/\/([^/]+)\/kv\/(.+)$/.exec(value);
32163
- if (match === null || /[:?#%]/.test(match[1])) return false;
32164
- const path = match[2];
32316
+ const marker = value.indexOf("/kv/");
32317
+ if (marker < 1) return false;
32318
+ const space = value.slice(0, marker);
32319
+ const legacy = space.startsWith("tinycloud://");
32320
+ if (legacy ? /[:/?#%]/.test(space.slice("tinycloud://".length)) : !space.startsWith("tinycloud:") || /[/?#%]/.test(space)) return false;
32321
+ const path = value.slice(marker + 4);
32165
32322
  return !path.startsWith("/") && !path.endsWith("/") && !path.includes("//") && path.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
32166
32323
  }, { message: "expected canonical TinyCloud KV resource" });
32167
32324
  var unifiedEncryptionNetworkSchema2 = external_exports.string().refine((value) => {
@@ -32199,7 +32356,7 @@ var unifiedContentSourceSchema2 = external_exports.object({
32199
32356
  mode: external_exports.union([external_exports.literal("mutable"), external_exports.literal("immutable")]),
32200
32357
  initialCiphertextDigestHex: external_exports.string().regex(/^[0-9a-f]{64}$/).optional()
32201
32358
  }).strict();
32202
- var unifiedPolicySchema2 = external_exports.object({
32359
+ var unifiedPolicyV1Schema2 = external_exports.object({
32203
32360
  schema: external_exports.literal("xyz.tinycloud.policy/policy/v1"),
32204
32361
  policyId: external_exports.string().regex(/^pol_[a-z2-7]+$/),
32205
32362
  ownerDid: external_exports.string().min(1),
@@ -32209,6 +32366,31 @@ var unifiedPolicySchema2 = external_exports.object({
32209
32366
  capabilityCeiling: external_exports.array(unifiedCapabilitySchema2).min(2),
32210
32367
  signature: external_exports.object({ suite: external_exports.string().min(1), signerDid: external_exports.string().min(1), value: external_exports.string().min(1) }).strict()
32211
32368
  }).strict();
32369
+ var policyCredentialRequirementV1Schema2 = external_exports.object({
32370
+ type: external_exports.literal("TinyCloudPolicyCredentialRequirement"),
32371
+ version: external_exports.literal(1),
32372
+ requirementDigest: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/),
32373
+ descriptorDigest: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/),
32374
+ issuerDid: external_exports.string().min(1),
32375
+ issuerKid: external_exports.string().min(1),
32376
+ profile: external_exports.object({ id: external_exports.string().min(1), version: external_exports.literal(1) }).strict(),
32377
+ credentialType: external_exports.object({ id: external_exports.string().min(1), version: external_exports.literal(1) }).strict()
32378
+ }).strict();
32379
+ var unifiedPolicyV2Schema2 = external_exports.object({
32380
+ schema: external_exports.literal("xyz.tinycloud.policy/policy/v2"),
32381
+ policyId: external_exports.string().regex(/^pol_[a-z2-7]+$/),
32382
+ ownerDid: external_exports.string().min(1),
32383
+ createdAt: external_exports.string().datetime({ offset: true }),
32384
+ expiresAt: external_exports.string().datetime({ offset: true }).optional(),
32385
+ contentSource: unifiedContentSourceSchema2,
32386
+ capabilityCeiling: external_exports.array(unifiedCapabilitySchema2).min(2),
32387
+ credentialRequirement: policyCredentialRequirementV1Schema2,
32388
+ signature: external_exports.object({ suite: external_exports.literal("Ed25519"), signerDid: external_exports.string().min(1), value: external_exports.string().min(1) }).strict()
32389
+ }).strict();
32390
+ var unifiedPolicySchema2 = external_exports.discriminatedUnion("schema", [
32391
+ unifiedPolicyV1Schema2,
32392
+ unifiedPolicyV2Schema2
32393
+ ]);
32212
32394
  var unifiedRootSchema2 = external_exports.object({
32213
32395
  cid: external_exports.string().min(1),
32214
32396
  authorization: external_exports.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/),