@tinycloud/cli 0.9.1-beta.7 → 0.9.1-beta.8
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 +830 -1591
- package/dist/index.js.map +1 -1
- package/dist/legacy-entry.js +181 -179
- package/dist/legacy-entry.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
tinycloudConfigPath,
|
|
38
38
|
tinycloudHomePath
|
|
39
39
|
} from "@tinycloud/operations/state";
|
|
40
|
-
var CONFIG_DIR, PROFILES_DIR, CONFIG_FILE, DEFAULT_HOST,
|
|
40
|
+
var CONFIG_DIR, PROFILES_DIR, CONFIG_FILE, DEFAULT_HOST, DEFAULT_PROFILE, ExitCode;
|
|
41
41
|
var init_constants = __esm({
|
|
42
42
|
"src/config/constants.ts"() {
|
|
43
43
|
"use strict";
|
|
@@ -45,9 +45,7 @@ var init_constants = __esm({
|
|
|
45
45
|
PROFILES_DIR = profilesPath();
|
|
46
46
|
CONFIG_FILE = tinycloudConfigPath();
|
|
47
47
|
DEFAULT_HOST = "https://node.tinycloud.xyz";
|
|
48
|
-
DEFAULT_OPENKEY_DEVICE_API_HOST = "https://api.openkey.so";
|
|
49
48
|
DEFAULT_PROFILE = "default";
|
|
50
|
-
DEFAULT_CHAIN_ID = 1;
|
|
51
49
|
ExitCode = {
|
|
52
50
|
SUCCESS: 0,
|
|
53
51
|
ERROR: 1,
|
|
@@ -4497,15 +4495,15 @@ function byteSwap32(arr) {
|
|
|
4497
4495
|
}
|
|
4498
4496
|
return arr;
|
|
4499
4497
|
}
|
|
4500
|
-
function bytesToHex(
|
|
4501
|
-
abytes(
|
|
4498
|
+
function bytesToHex(bytes) {
|
|
4499
|
+
abytes(bytes);
|
|
4502
4500
|
if (hasHexBuiltin)
|
|
4503
|
-
return
|
|
4504
|
-
let
|
|
4505
|
-
for (let i = 0; i <
|
|
4506
|
-
|
|
4501
|
+
return bytes.toHex();
|
|
4502
|
+
let hex4 = "";
|
|
4503
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
4504
|
+
hex4 += hexes[bytes[i]];
|
|
4507
4505
|
}
|
|
4508
|
-
return
|
|
4506
|
+
return hex4;
|
|
4509
4507
|
}
|
|
4510
4508
|
function asciiToBase16(ch) {
|
|
4511
4509
|
if (ch >= asciis._0 && ch <= asciis._9)
|
|
@@ -4516,21 +4514,21 @@ function asciiToBase16(ch) {
|
|
|
4516
4514
|
return ch - (asciis.a - 10);
|
|
4517
4515
|
return;
|
|
4518
4516
|
}
|
|
4519
|
-
function hexToBytes(
|
|
4520
|
-
if (typeof
|
|
4521
|
-
throw new Error("hex string expected, got " + typeof
|
|
4517
|
+
function hexToBytes(hex4) {
|
|
4518
|
+
if (typeof hex4 !== "string")
|
|
4519
|
+
throw new Error("hex string expected, got " + typeof hex4);
|
|
4522
4520
|
if (hasHexBuiltin)
|
|
4523
|
-
return Uint8Array.fromHex(
|
|
4524
|
-
const hl =
|
|
4521
|
+
return Uint8Array.fromHex(hex4);
|
|
4522
|
+
const hl = hex4.length;
|
|
4525
4523
|
const al = hl / 2;
|
|
4526
4524
|
if (hl % 2)
|
|
4527
4525
|
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
4528
4526
|
const array = new Uint8Array(al);
|
|
4529
4527
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
4530
|
-
const n1 = asciiToBase16(
|
|
4531
|
-
const n2 = asciiToBase16(
|
|
4528
|
+
const n1 = asciiToBase16(hex4.charCodeAt(hi));
|
|
4529
|
+
const n2 = asciiToBase16(hex4.charCodeAt(hi + 1));
|
|
4532
4530
|
if (n1 === void 0 || n2 === void 0) {
|
|
4533
|
-
const char =
|
|
4531
|
+
const char = hex4[hi] + hex4[hi + 1];
|
|
4534
4532
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
4535
4533
|
}
|
|
4536
4534
|
array[ai] = n1 * 16 + n2;
|
|
@@ -5153,28 +5151,28 @@ function _abool2(value, title = "") {
|
|
|
5153
5151
|
return value;
|
|
5154
5152
|
}
|
|
5155
5153
|
function _abytes2(value, length5, title = "") {
|
|
5156
|
-
const
|
|
5154
|
+
const bytes = isBytes(value);
|
|
5157
5155
|
const len = value?.length;
|
|
5158
5156
|
const needsLen = length5 !== void 0;
|
|
5159
|
-
if (!
|
|
5157
|
+
if (!bytes || needsLen && len !== length5) {
|
|
5160
5158
|
const prefix = title && `"${title}" `;
|
|
5161
5159
|
const ofLen = needsLen ? ` of length ${length5}` : "";
|
|
5162
|
-
const got =
|
|
5160
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
5163
5161
|
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
5164
5162
|
}
|
|
5165
5163
|
return value;
|
|
5166
5164
|
}
|
|
5167
|
-
function hexToNumber(
|
|
5168
|
-
if (typeof
|
|
5169
|
-
throw new Error("hex string expected, got " + typeof
|
|
5170
|
-
return
|
|
5165
|
+
function hexToNumber(hex4) {
|
|
5166
|
+
if (typeof hex4 !== "string")
|
|
5167
|
+
throw new Error("hex string expected, got " + typeof hex4);
|
|
5168
|
+
return hex4 === "" ? _0n : BigInt("0x" + hex4);
|
|
5171
5169
|
}
|
|
5172
|
-
function bytesToNumberBE(
|
|
5173
|
-
return hexToNumber(bytesToHex(
|
|
5170
|
+
function bytesToNumberBE(bytes) {
|
|
5171
|
+
return hexToNumber(bytesToHex(bytes));
|
|
5174
5172
|
}
|
|
5175
|
-
function bytesToNumberLE(
|
|
5176
|
-
abytes(
|
|
5177
|
-
return hexToNumber(bytesToHex(Uint8Array.from(
|
|
5173
|
+
function bytesToNumberLE(bytes) {
|
|
5174
|
+
abytes(bytes);
|
|
5175
|
+
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
|
5178
5176
|
}
|
|
5179
5177
|
function numberToBytesBE(n, len) {
|
|
5180
5178
|
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
|
|
@@ -5182,16 +5180,16 @@ function numberToBytesBE(n, len) {
|
|
|
5182
5180
|
function numberToBytesLE(n, len) {
|
|
5183
5181
|
return numberToBytesBE(n, len).reverse();
|
|
5184
5182
|
}
|
|
5185
|
-
function ensureBytes(title,
|
|
5183
|
+
function ensureBytes(title, hex4, expectedLength) {
|
|
5186
5184
|
let res;
|
|
5187
|
-
if (typeof
|
|
5185
|
+
if (typeof hex4 === "string") {
|
|
5188
5186
|
try {
|
|
5189
|
-
res = hexToBytes(
|
|
5187
|
+
res = hexToBytes(hex4);
|
|
5190
5188
|
} catch (e) {
|
|
5191
5189
|
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
|
|
5192
5190
|
}
|
|
5193
|
-
} else if (isBytes(
|
|
5194
|
-
res = Uint8Array.from(
|
|
5191
|
+
} else if (isBytes(hex4)) {
|
|
5192
|
+
res = Uint8Array.from(hex4);
|
|
5195
5193
|
} else {
|
|
5196
5194
|
throw new Error(title + " must be hex string or Uint8Array");
|
|
5197
5195
|
}
|
|
@@ -5208,8 +5206,8 @@ function equalBytes(a, b) {
|
|
|
5208
5206
|
diff |= a[i] ^ b[i];
|
|
5209
5207
|
return diff === 0;
|
|
5210
5208
|
}
|
|
5211
|
-
function copyBytes(
|
|
5212
|
-
return Uint8Array.from(
|
|
5209
|
+
function copyBytes(bytes) {
|
|
5210
|
+
return Uint8Array.from(bytes);
|
|
5213
5211
|
}
|
|
5214
5212
|
function inRange(n, min, max) {
|
|
5215
5213
|
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
@@ -5532,18 +5530,18 @@ function Field(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) {
|
|
|
5532
5530
|
return sqrtP(f, n);
|
|
5533
5531
|
}),
|
|
5534
5532
|
toBytes: (num2) => isLE2 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES),
|
|
5535
|
-
fromBytes: (
|
|
5533
|
+
fromBytes: (bytes, skipValidation = true) => {
|
|
5536
5534
|
if (allowedLengths) {
|
|
5537
|
-
if (!allowedLengths.includes(
|
|
5538
|
-
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " +
|
|
5535
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
5536
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
5539
5537
|
}
|
|
5540
5538
|
const padded = new Uint8Array(BYTES);
|
|
5541
|
-
padded.set(
|
|
5542
|
-
|
|
5539
|
+
padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
|
|
5540
|
+
bytes = padded;
|
|
5543
5541
|
}
|
|
5544
|
-
if (
|
|
5545
|
-
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " +
|
|
5546
|
-
let scalar = isLE2 ? bytesToNumberLE(
|
|
5542
|
+
if (bytes.length !== BYTES)
|
|
5543
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
5544
|
+
let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
5547
5545
|
if (modFromBytes)
|
|
5548
5546
|
scalar = mod(scalar, ORDER);
|
|
5549
5547
|
if (!skipValidation) {
|
|
@@ -5957,13 +5955,13 @@ function edwards(params, extraOpts = {}) {
|
|
|
5957
5955
|
return new Point2(x, y, _1n4, modP2(x * y));
|
|
5958
5956
|
}
|
|
5959
5957
|
// Uses algo from RFC8032 5.1.3.
|
|
5960
|
-
static fromBytes(
|
|
5958
|
+
static fromBytes(bytes, zip215 = false) {
|
|
5961
5959
|
const len = Fp2.BYTES;
|
|
5962
5960
|
const { a, d } = CURVE;
|
|
5963
|
-
|
|
5961
|
+
bytes = copyBytes(_abytes2(bytes, len, "point"));
|
|
5964
5962
|
_abool2(zip215, "zip215");
|
|
5965
|
-
const normed = copyBytes(
|
|
5966
|
-
const lastByte =
|
|
5963
|
+
const normed = copyBytes(bytes);
|
|
5964
|
+
const lastByte = bytes[len - 1];
|
|
5967
5965
|
normed[len - 1] = lastByte & ~128;
|
|
5968
5966
|
const y = bytesToNumberLE(normed);
|
|
5969
5967
|
const max = zip215 ? MASK : Fp2.ORDER;
|
|
@@ -5982,8 +5980,8 @@ function edwards(params, extraOpts = {}) {
|
|
|
5982
5980
|
x = modP2(-x);
|
|
5983
5981
|
return Point2.fromAffine({ x, y });
|
|
5984
5982
|
}
|
|
5985
|
-
static fromHex(
|
|
5986
|
-
return Point2.fromBytes(ensureBytes("point",
|
|
5983
|
+
static fromHex(bytes, zip215 = false) {
|
|
5984
|
+
return Point2.fromBytes(ensureBytes("point", bytes), zip215);
|
|
5987
5985
|
}
|
|
5988
5986
|
get x() {
|
|
5989
5987
|
return this.toAffine().x;
|
|
@@ -6109,9 +6107,9 @@ function edwards(params, extraOpts = {}) {
|
|
|
6109
6107
|
}
|
|
6110
6108
|
toBytes() {
|
|
6111
6109
|
const { x, y } = this.toAffine();
|
|
6112
|
-
const
|
|
6113
|
-
|
|
6114
|
-
return
|
|
6110
|
+
const bytes = Fp2.toBytes(y);
|
|
6111
|
+
bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
|
|
6112
|
+
return bytes;
|
|
6115
6113
|
}
|
|
6116
6114
|
toHex() {
|
|
6117
6115
|
return bytesToHex(this.toBytes());
|
|
@@ -6165,8 +6163,8 @@ function eddsa(Point2, cHash, eddsaOpts = {}) {
|
|
|
6165
6163
|
});
|
|
6166
6164
|
const { prehash } = eddsaOpts;
|
|
6167
6165
|
const { BASE, Fp: Fp2, Fn: Fn2 } = Point2;
|
|
6168
|
-
const
|
|
6169
|
-
const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((
|
|
6166
|
+
const randomBytes3 = eddsaOpts.randomBytes || randomBytes;
|
|
6167
|
+
const adjustScalarBytes2 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
|
|
6170
6168
|
const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
|
|
6171
6169
|
_abool2(phflag, "phflag");
|
|
6172
6170
|
if (ctx.length || phflag)
|
|
@@ -6247,7 +6245,7 @@ function eddsa(Point2, cHash, eddsaOpts = {}) {
|
|
|
6247
6245
|
signature: 2 * _size,
|
|
6248
6246
|
seed: _size
|
|
6249
6247
|
};
|
|
6250
|
-
function randomSecretKey(seed =
|
|
6248
|
+
function randomSecretKey(seed = randomBytes3(lengths.seed)) {
|
|
6251
6249
|
return _abytes2(seed, lengths.seed, "seed");
|
|
6252
6250
|
}
|
|
6253
6251
|
function keygen(seed) {
|
|
@@ -6575,11 +6573,11 @@ function ed25519_pow_2_252_3(x) {
|
|
|
6575
6573
|
const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
|
|
6576
6574
|
return { pow_p_5_8, b2 };
|
|
6577
6575
|
}
|
|
6578
|
-
function adjustScalarBytes(
|
|
6579
|
-
|
|
6580
|
-
|
|
6581
|
-
|
|
6582
|
-
return
|
|
6576
|
+
function adjustScalarBytes(bytes) {
|
|
6577
|
+
bytes[0] &= 248;
|
|
6578
|
+
bytes[31] &= 127;
|
|
6579
|
+
bytes[31] |= 64;
|
|
6580
|
+
return bytes;
|
|
6583
6581
|
}
|
|
6584
6582
|
function uvRatio(u, v) {
|
|
6585
6583
|
const P = ed25519_CURVE_p;
|
|
@@ -6625,11 +6623,11 @@ function calcElligatorRistrettoMap(r0) {
|
|
|
6625
6623
|
const W3 = mod3(_1n6 + s2);
|
|
6626
6624
|
return new ed25519.Point(mod3(W0 * W3), mod3(W2 * W1), mod3(W1 * W3), mod3(W0 * W2));
|
|
6627
6625
|
}
|
|
6628
|
-
function ristretto255_map(
|
|
6629
|
-
abytes(
|
|
6630
|
-
const r1 = bytes255ToNumberLE(
|
|
6626
|
+
function ristretto255_map(bytes) {
|
|
6627
|
+
abytes(bytes, 64);
|
|
6628
|
+
const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
|
|
6631
6629
|
const R1 = calcElligatorRistrettoMap(r1);
|
|
6632
|
-
const r2 = bytes255ToNumberLE(
|
|
6630
|
+
const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
|
|
6633
6631
|
const R2 = calcElligatorRistrettoMap(r2);
|
|
6634
6632
|
return new _RistrettoPoint(R1.add(R2));
|
|
6635
6633
|
}
|
|
@@ -6693,7 +6691,7 @@ var init_ed25519 = __esm({
|
|
|
6693
6691
|
D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");
|
|
6694
6692
|
invertSqrt = (number) => uvRatio(_1n6, number);
|
|
6695
6693
|
MAX_255B = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
|
|
6696
|
-
bytes255ToNumberLE = (
|
|
6694
|
+
bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
|
|
6697
6695
|
_RistrettoPoint = class __RistrettoPoint extends PrimeEdwardsPoint {
|
|
6698
6696
|
constructor(ep) {
|
|
6699
6697
|
super(ep);
|
|
@@ -6709,16 +6707,16 @@ var init_ed25519 = __esm({
|
|
|
6709
6707
|
return new __RistrettoPoint(ep);
|
|
6710
6708
|
}
|
|
6711
6709
|
/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
|
|
6712
|
-
static hashToCurve(
|
|
6713
|
-
return ristretto255_map(ensureBytes("ristrettoHash",
|
|
6710
|
+
static hashToCurve(hex4) {
|
|
6711
|
+
return ristretto255_map(ensureBytes("ristrettoHash", hex4, 64));
|
|
6714
6712
|
}
|
|
6715
|
-
static fromBytes(
|
|
6716
|
-
abytes(
|
|
6713
|
+
static fromBytes(bytes) {
|
|
6714
|
+
abytes(bytes, 32);
|
|
6717
6715
|
const { a, d } = ed25519_CURVE;
|
|
6718
6716
|
const P = ed25519_CURVE_p;
|
|
6719
6717
|
const mod3 = (n) => Fp.create(n);
|
|
6720
|
-
const s = bytes255ToNumberLE(
|
|
6721
|
-
if (!equalBytes(Fp.toBytes(s),
|
|
6718
|
+
const s = bytes255ToNumberLE(bytes);
|
|
6719
|
+
if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
|
|
6722
6720
|
throw new Error("invalid ristretto255 encoding 1");
|
|
6723
6721
|
const s2 = mod3(s * s);
|
|
6724
6722
|
const u1 = mod3(_1n6 + a * s2);
|
|
@@ -6743,8 +6741,8 @@ var init_ed25519 = __esm({
|
|
|
6743
6741
|
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
|
|
6744
6742
|
* @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
|
|
6745
6743
|
*/
|
|
6746
|
-
static fromHex(
|
|
6747
|
-
return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex",
|
|
6744
|
+
static fromHex(hex4) {
|
|
6745
|
+
return __RistrettoPoint.fromBytes(ensureBytes("ristrettoHex", hex4, 32));
|
|
6748
6746
|
}
|
|
6749
6747
|
static msm(points, scalars) {
|
|
6750
6748
|
return pippenger(__RistrettoPoint, ed25519.Point.Fn, points, scalars);
|
|
@@ -6955,28 +6953,28 @@ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
|
|
|
6955
6953
|
function padHex(hex_, { dir, size: size2 = 32 } = {}) {
|
|
6956
6954
|
if (size2 === null)
|
|
6957
6955
|
return hex_;
|
|
6958
|
-
const
|
|
6959
|
-
if (
|
|
6956
|
+
const hex4 = hex_.replace("0x", "");
|
|
6957
|
+
if (hex4.length > size2 * 2)
|
|
6960
6958
|
throw new SizeExceedsPaddingSizeError({
|
|
6961
|
-
size: Math.ceil(
|
|
6959
|
+
size: Math.ceil(hex4.length / 2),
|
|
6962
6960
|
targetSize: size2,
|
|
6963
6961
|
type: "hex"
|
|
6964
6962
|
});
|
|
6965
|
-
return `0x${
|
|
6963
|
+
return `0x${hex4[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
|
|
6966
6964
|
}
|
|
6967
|
-
function padBytes(
|
|
6965
|
+
function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
|
|
6968
6966
|
if (size2 === null)
|
|
6969
|
-
return
|
|
6970
|
-
if (
|
|
6967
|
+
return bytes;
|
|
6968
|
+
if (bytes.length > size2)
|
|
6971
6969
|
throw new SizeExceedsPaddingSizeError({
|
|
6972
|
-
size:
|
|
6970
|
+
size: bytes.length,
|
|
6973
6971
|
targetSize: size2,
|
|
6974
6972
|
type: "bytes"
|
|
6975
6973
|
});
|
|
6976
6974
|
const paddedBytes = new Uint8Array(size2);
|
|
6977
6975
|
for (let i = 0; i < size2; i++) {
|
|
6978
6976
|
const padEnd = dir === "right";
|
|
6979
|
-
paddedBytes[padEnd ? i : size2 - i - 1] =
|
|
6977
|
+
paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
|
|
6980
6978
|
}
|
|
6981
6979
|
return paddedBytes;
|
|
6982
6980
|
}
|
|
@@ -7014,21 +7012,21 @@ function assertSize(hexOrBytes, { size: size2 }) {
|
|
|
7014
7012
|
maxSize: size2
|
|
7015
7013
|
});
|
|
7016
7014
|
}
|
|
7017
|
-
function hexToBigInt(
|
|
7015
|
+
function hexToBigInt(hex4, opts = {}) {
|
|
7018
7016
|
const { signed } = opts;
|
|
7019
7017
|
if (opts.size)
|
|
7020
|
-
assertSize(
|
|
7021
|
-
const value = BigInt(
|
|
7018
|
+
assertSize(hex4, { size: opts.size });
|
|
7019
|
+
const value = BigInt(hex4);
|
|
7022
7020
|
if (!signed)
|
|
7023
7021
|
return value;
|
|
7024
|
-
const size2 = (
|
|
7022
|
+
const size2 = (hex4.length - 2) / 2;
|
|
7025
7023
|
const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
|
|
7026
7024
|
if (value <= max)
|
|
7027
7025
|
return value;
|
|
7028
7026
|
return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
|
|
7029
7027
|
}
|
|
7030
|
-
function hexToNumber2(
|
|
7031
|
-
const value = hexToBigInt(
|
|
7028
|
+
function hexToNumber2(hex4, opts = {}) {
|
|
7029
|
+
const value = hexToBigInt(hex4, opts);
|
|
7032
7030
|
const number = Number(value);
|
|
7033
7031
|
if (!Number.isSafeInteger(number))
|
|
7034
7032
|
throw new IntegerOutOfRangeError({
|
|
@@ -7060,24 +7058,24 @@ function toHex(value, opts = {}) {
|
|
|
7060
7058
|
return bytesToHex2(value, opts);
|
|
7061
7059
|
}
|
|
7062
7060
|
function boolToHex(value, opts = {}) {
|
|
7063
|
-
const
|
|
7061
|
+
const hex4 = `0x${Number(value)}`;
|
|
7064
7062
|
if (typeof opts.size === "number") {
|
|
7065
|
-
assertSize(
|
|
7066
|
-
return pad(
|
|
7063
|
+
assertSize(hex4, { size: opts.size });
|
|
7064
|
+
return pad(hex4, { size: opts.size });
|
|
7067
7065
|
}
|
|
7068
|
-
return
|
|
7066
|
+
return hex4;
|
|
7069
7067
|
}
|
|
7070
7068
|
function bytesToHex2(value, opts = {}) {
|
|
7071
7069
|
let string2 = "";
|
|
7072
7070
|
for (let i = 0; i < value.length; i++) {
|
|
7073
7071
|
string2 += hexes2[value[i]];
|
|
7074
7072
|
}
|
|
7075
|
-
const
|
|
7073
|
+
const hex4 = `0x${string2}`;
|
|
7076
7074
|
if (typeof opts.size === "number") {
|
|
7077
|
-
assertSize(
|
|
7078
|
-
return pad(
|
|
7075
|
+
assertSize(hex4, { size: opts.size });
|
|
7076
|
+
return pad(hex4, { dir: "right", size: opts.size });
|
|
7079
7077
|
}
|
|
7080
|
-
return
|
|
7078
|
+
return hex4;
|
|
7081
7079
|
}
|
|
7082
7080
|
function numberToHex(value_, opts = {}) {
|
|
7083
7081
|
const { signed, size: size2 } = opts;
|
|
@@ -7102,10 +7100,10 @@ function numberToHex(value_, opts = {}) {
|
|
|
7102
7100
|
value: `${value_}${suffix}`
|
|
7103
7101
|
});
|
|
7104
7102
|
}
|
|
7105
|
-
const
|
|
7103
|
+
const hex4 = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
|
|
7106
7104
|
if (size2)
|
|
7107
|
-
return pad(
|
|
7108
|
-
return
|
|
7105
|
+
return pad(hex4, { size: size2 });
|
|
7106
|
+
return hex4;
|
|
7109
7107
|
}
|
|
7110
7108
|
function stringToHex(value_, opts = {}) {
|
|
7111
7109
|
const value = encoder.encode(value_);
|
|
@@ -7134,13 +7132,13 @@ function toBytes2(value, opts = {}) {
|
|
|
7134
7132
|
return stringToBytes(value, opts);
|
|
7135
7133
|
}
|
|
7136
7134
|
function boolToBytes(value, opts = {}) {
|
|
7137
|
-
const
|
|
7138
|
-
|
|
7135
|
+
const bytes = new Uint8Array(1);
|
|
7136
|
+
bytes[0] = Number(value);
|
|
7139
7137
|
if (typeof opts.size === "number") {
|
|
7140
|
-
assertSize(
|
|
7141
|
-
return pad(
|
|
7138
|
+
assertSize(bytes, { size: opts.size });
|
|
7139
|
+
return pad(bytes, { size: opts.size });
|
|
7142
7140
|
}
|
|
7143
|
-
return
|
|
7141
|
+
return bytes;
|
|
7144
7142
|
}
|
|
7145
7143
|
function charCodeToBase16(char) {
|
|
7146
7144
|
if (char >= charCodeMap.zero && char <= charCodeMap.nine)
|
|
@@ -7152,37 +7150,37 @@ function charCodeToBase16(char) {
|
|
|
7152
7150
|
return void 0;
|
|
7153
7151
|
}
|
|
7154
7152
|
function hexToBytes2(hex_, opts = {}) {
|
|
7155
|
-
let
|
|
7153
|
+
let hex4 = hex_;
|
|
7156
7154
|
if (opts.size) {
|
|
7157
|
-
assertSize(
|
|
7158
|
-
|
|
7155
|
+
assertSize(hex4, { size: opts.size });
|
|
7156
|
+
hex4 = pad(hex4, { dir: "right", size: opts.size });
|
|
7159
7157
|
}
|
|
7160
|
-
let hexString =
|
|
7158
|
+
let hexString = hex4.slice(2);
|
|
7161
7159
|
if (hexString.length % 2)
|
|
7162
7160
|
hexString = `0${hexString}`;
|
|
7163
7161
|
const length5 = hexString.length / 2;
|
|
7164
|
-
const
|
|
7162
|
+
const bytes = new Uint8Array(length5);
|
|
7165
7163
|
for (let index = 0, j = 0; index < length5; index++) {
|
|
7166
7164
|
const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
|
|
7167
7165
|
const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
|
|
7168
7166
|
if (nibbleLeft === void 0 || nibbleRight === void 0) {
|
|
7169
7167
|
throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
|
|
7170
7168
|
}
|
|
7171
|
-
|
|
7169
|
+
bytes[index] = nibbleLeft * 16 + nibbleRight;
|
|
7172
7170
|
}
|
|
7173
|
-
return
|
|
7171
|
+
return bytes;
|
|
7174
7172
|
}
|
|
7175
7173
|
function numberToBytes(value, opts) {
|
|
7176
|
-
const
|
|
7177
|
-
return hexToBytes2(
|
|
7174
|
+
const hex4 = numberToHex(value, opts);
|
|
7175
|
+
return hexToBytes2(hex4);
|
|
7178
7176
|
}
|
|
7179
7177
|
function stringToBytes(value, opts = {}) {
|
|
7180
|
-
const
|
|
7178
|
+
const bytes = encoder2.encode(value);
|
|
7181
7179
|
if (typeof opts.size === "number") {
|
|
7182
|
-
assertSize(
|
|
7183
|
-
return pad(
|
|
7180
|
+
assertSize(bytes, { size: opts.size });
|
|
7181
|
+
return pad(bytes, { dir: "right", size: opts.size });
|
|
7184
7182
|
}
|
|
7185
|
-
return
|
|
7183
|
+
return bytes;
|
|
7186
7184
|
}
|
|
7187
7185
|
var encoder2, charCodeMap;
|
|
7188
7186
|
var init_toBytes = __esm({
|
|
@@ -7355,9 +7353,9 @@ var init_sha3 = __esm({
|
|
|
7355
7353
|
throw new Error("XOF is not possible for this instance");
|
|
7356
7354
|
return this.writeInto(out);
|
|
7357
7355
|
}
|
|
7358
|
-
xof(
|
|
7359
|
-
anumber(
|
|
7360
|
-
return this.xofInto(new Uint8Array(
|
|
7356
|
+
xof(bytes) {
|
|
7357
|
+
anumber(bytes);
|
|
7358
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
7361
7359
|
}
|
|
7362
7360
|
digestInto(out) {
|
|
7363
7361
|
aoutput(out, this);
|
|
@@ -7397,10 +7395,10 @@ var init_sha3 = __esm({
|
|
|
7397
7395
|
// ../../node_modules/viem/_esm/utils/hash/keccak256.js
|
|
7398
7396
|
function keccak256(value, to_) {
|
|
7399
7397
|
const to = to_ || "hex";
|
|
7400
|
-
const
|
|
7398
|
+
const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes2(value) : value);
|
|
7401
7399
|
if (to === "bytes")
|
|
7402
|
-
return
|
|
7403
|
-
return toHex(
|
|
7400
|
+
return bytes;
|
|
7401
|
+
return toHex(bytes);
|
|
7404
7402
|
}
|
|
7405
7403
|
var init_keccak256 = __esm({
|
|
7406
7404
|
"../../node_modules/viem/_esm/utils/hash/keccak256.js"() {
|
|
@@ -7664,23 +7662,23 @@ function abool(title, value) {
|
|
|
7664
7662
|
throw new Error(title + " boolean expected, got " + value);
|
|
7665
7663
|
}
|
|
7666
7664
|
function numberToHexUnpadded(num2) {
|
|
7667
|
-
const
|
|
7668
|
-
return
|
|
7665
|
+
const hex4 = num2.toString(16);
|
|
7666
|
+
return hex4.length & 1 ? "0" + hex4 : hex4;
|
|
7669
7667
|
}
|
|
7670
|
-
function hexToNumber3(
|
|
7671
|
-
if (typeof
|
|
7672
|
-
throw new Error("hex string expected, got " + typeof
|
|
7673
|
-
return
|
|
7668
|
+
function hexToNumber3(hex4) {
|
|
7669
|
+
if (typeof hex4 !== "string")
|
|
7670
|
+
throw new Error("hex string expected, got " + typeof hex4);
|
|
7671
|
+
return hex4 === "" ? _0n8 : BigInt("0x" + hex4);
|
|
7674
7672
|
}
|
|
7675
|
-
function bytesToHex3(
|
|
7676
|
-
abytes2(
|
|
7673
|
+
function bytesToHex3(bytes) {
|
|
7674
|
+
abytes2(bytes);
|
|
7677
7675
|
if (hasHexBuiltin2)
|
|
7678
|
-
return
|
|
7679
|
-
let
|
|
7680
|
-
for (let i = 0; i <
|
|
7681
|
-
|
|
7676
|
+
return bytes.toHex();
|
|
7677
|
+
let hex4 = "";
|
|
7678
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
7679
|
+
hex4 += hexes3[bytes[i]];
|
|
7682
7680
|
}
|
|
7683
|
-
return
|
|
7681
|
+
return hex4;
|
|
7684
7682
|
}
|
|
7685
7683
|
function asciiToBase162(ch) {
|
|
7686
7684
|
if (ch >= asciis2._0 && ch <= asciis2._9)
|
|
@@ -7691,33 +7689,33 @@ function asciiToBase162(ch) {
|
|
|
7691
7689
|
return ch - (asciis2.a - 10);
|
|
7692
7690
|
return;
|
|
7693
7691
|
}
|
|
7694
|
-
function hexToBytes3(
|
|
7695
|
-
if (typeof
|
|
7696
|
-
throw new Error("hex string expected, got " + typeof
|
|
7692
|
+
function hexToBytes3(hex4) {
|
|
7693
|
+
if (typeof hex4 !== "string")
|
|
7694
|
+
throw new Error("hex string expected, got " + typeof hex4);
|
|
7697
7695
|
if (hasHexBuiltin2)
|
|
7698
|
-
return Uint8Array.fromHex(
|
|
7699
|
-
const hl =
|
|
7696
|
+
return Uint8Array.fromHex(hex4);
|
|
7697
|
+
const hl = hex4.length;
|
|
7700
7698
|
const al = hl / 2;
|
|
7701
7699
|
if (hl % 2)
|
|
7702
7700
|
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
7703
7701
|
const array = new Uint8Array(al);
|
|
7704
7702
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
7705
|
-
const n1 = asciiToBase162(
|
|
7706
|
-
const n2 = asciiToBase162(
|
|
7703
|
+
const n1 = asciiToBase162(hex4.charCodeAt(hi));
|
|
7704
|
+
const n2 = asciiToBase162(hex4.charCodeAt(hi + 1));
|
|
7707
7705
|
if (n1 === void 0 || n2 === void 0) {
|
|
7708
|
-
const char =
|
|
7706
|
+
const char = hex4[hi] + hex4[hi + 1];
|
|
7709
7707
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
7710
7708
|
}
|
|
7711
7709
|
array[ai] = n1 * 16 + n2;
|
|
7712
7710
|
}
|
|
7713
7711
|
return array;
|
|
7714
7712
|
}
|
|
7715
|
-
function bytesToNumberBE2(
|
|
7716
|
-
return hexToNumber3(bytesToHex3(
|
|
7713
|
+
function bytesToNumberBE2(bytes) {
|
|
7714
|
+
return hexToNumber3(bytesToHex3(bytes));
|
|
7717
7715
|
}
|
|
7718
|
-
function bytesToNumberLE2(
|
|
7719
|
-
abytes2(
|
|
7720
|
-
return hexToNumber3(bytesToHex3(Uint8Array.from(
|
|
7716
|
+
function bytesToNumberLE2(bytes) {
|
|
7717
|
+
abytes2(bytes);
|
|
7718
|
+
return hexToNumber3(bytesToHex3(Uint8Array.from(bytes).reverse()));
|
|
7721
7719
|
}
|
|
7722
7720
|
function numberToBytesBE2(n, len) {
|
|
7723
7721
|
return hexToBytes3(n.toString(16).padStart(len * 2, "0"));
|
|
@@ -7725,16 +7723,16 @@ function numberToBytesBE2(n, len) {
|
|
|
7725
7723
|
function numberToBytesLE2(n, len) {
|
|
7726
7724
|
return numberToBytesBE2(n, len).reverse();
|
|
7727
7725
|
}
|
|
7728
|
-
function ensureBytes2(title,
|
|
7726
|
+
function ensureBytes2(title, hex4, expectedLength) {
|
|
7729
7727
|
let res;
|
|
7730
|
-
if (typeof
|
|
7728
|
+
if (typeof hex4 === "string") {
|
|
7731
7729
|
try {
|
|
7732
|
-
res = hexToBytes3(
|
|
7730
|
+
res = hexToBytes3(hex4);
|
|
7733
7731
|
} catch (e) {
|
|
7734
7732
|
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
|
|
7735
7733
|
}
|
|
7736
|
-
} else if (isBytes2(
|
|
7737
|
-
res = Uint8Array.from(
|
|
7734
|
+
} else if (isBytes2(hex4)) {
|
|
7735
|
+
res = Uint8Array.from(hex4);
|
|
7738
7736
|
} else {
|
|
7739
7737
|
throw new Error(title + " must be hex string or Uint8Array");
|
|
7740
7738
|
}
|
|
@@ -8095,10 +8093,10 @@ function Field2(ORDER, bitLen3, isLE2 = false, redef = {}) {
|
|
|
8095
8093
|
return sqrtP(f, n);
|
|
8096
8094
|
}),
|
|
8097
8095
|
toBytes: (num2) => isLE2 ? numberToBytesLE2(num2, BYTES) : numberToBytesBE2(num2, BYTES),
|
|
8098
|
-
fromBytes: (
|
|
8099
|
-
if (
|
|
8100
|
-
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " +
|
|
8101
|
-
return isLE2 ? bytesToNumberLE2(
|
|
8096
|
+
fromBytes: (bytes) => {
|
|
8097
|
+
if (bytes.length !== BYTES)
|
|
8098
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
8099
|
+
return isLE2 ? bytesToNumberLE2(bytes) : bytesToNumberBE2(bytes);
|
|
8102
8100
|
},
|
|
8103
8101
|
// TODO: we don't need it here, move out to separate fn
|
|
8104
8102
|
invertBatch: (lst) => FpInvertBatch2(f, lst),
|
|
@@ -8448,8 +8446,8 @@ function weierstrassPoints(opts) {
|
|
|
8448
8446
|
const a = point.toAffine();
|
|
8449
8447
|
return concatBytes3(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y));
|
|
8450
8448
|
});
|
|
8451
|
-
const fromBytes2 = CURVE.fromBytes || ((
|
|
8452
|
-
const tail =
|
|
8449
|
+
const fromBytes2 = CURVE.fromBytes || ((bytes) => {
|
|
8450
|
+
const tail = bytes.subarray(1);
|
|
8453
8451
|
const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
|
|
8454
8452
|
const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
|
|
8455
8453
|
return { x, y };
|
|
@@ -8575,8 +8573,8 @@ function weierstrassPoints(opts) {
|
|
|
8575
8573
|
* Converts hash string or Uint8Array to Point.
|
|
8576
8574
|
* @param hex short/long ECDSA hex
|
|
8577
8575
|
*/
|
|
8578
|
-
static fromHex(
|
|
8579
|
-
const P = Point2.fromAffine(fromBytes2(ensureBytes2("pointHex",
|
|
8576
|
+
static fromHex(hex4) {
|
|
8577
|
+
const P = Point2.fromAffine(fromBytes2(ensureBytes2("pointHex", hex4)));
|
|
8580
8578
|
P.assertValidity();
|
|
8581
8579
|
return P;
|
|
8582
8580
|
}
|
|
@@ -8880,10 +8878,10 @@ function weierstrass(curveDef) {
|
|
|
8880
8878
|
return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y));
|
|
8881
8879
|
}
|
|
8882
8880
|
},
|
|
8883
|
-
fromBytes(
|
|
8884
|
-
const len =
|
|
8885
|
-
const head =
|
|
8886
|
-
const tail =
|
|
8881
|
+
fromBytes(bytes) {
|
|
8882
|
+
const len = bytes.length;
|
|
8883
|
+
const head = bytes[0];
|
|
8884
|
+
const tail = bytes.subarray(1);
|
|
8887
8885
|
if (len === compressedLen && (head === 2 || head === 3)) {
|
|
8888
8886
|
const x = bytesToNumberBE2(tail);
|
|
8889
8887
|
if (!inRange2(x, _1n11, Fp2.ORDER))
|
|
@@ -8931,15 +8929,15 @@ function weierstrass(curveDef) {
|
|
|
8931
8929
|
Object.freeze(this);
|
|
8932
8930
|
}
|
|
8933
8931
|
// pair (bytes of r, bytes of s)
|
|
8934
|
-
static fromCompact(
|
|
8932
|
+
static fromCompact(hex4) {
|
|
8935
8933
|
const l = nByteLength;
|
|
8936
|
-
|
|
8937
|
-
return new Signature(slcNum(
|
|
8934
|
+
hex4 = ensureBytes2("compactSignature", hex4, l * 2);
|
|
8935
|
+
return new Signature(slcNum(hex4, 0, l), slcNum(hex4, l, 2 * l));
|
|
8938
8936
|
}
|
|
8939
8937
|
// DER encoded ECDSA signature
|
|
8940
8938
|
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
|
|
8941
|
-
static fromDER(
|
|
8942
|
-
const { r, s } = DER.toSig(ensureBytes2("DER",
|
|
8939
|
+
static fromDER(hex4) {
|
|
8940
|
+
const { r, s } = DER.toSig(ensureBytes2("DER", hex4));
|
|
8943
8941
|
return new Signature(r, s);
|
|
8944
8942
|
}
|
|
8945
8943
|
/**
|
|
@@ -9052,15 +9050,15 @@ function weierstrass(curveDef) {
|
|
|
9052
9050
|
const b = Point2.fromHex(publicB);
|
|
9053
9051
|
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
|
|
9054
9052
|
}
|
|
9055
|
-
const bits2int = CURVE.bits2int || function(
|
|
9056
|
-
if (
|
|
9053
|
+
const bits2int = CURVE.bits2int || function(bytes) {
|
|
9054
|
+
if (bytes.length > 8192)
|
|
9057
9055
|
throw new Error("input is too large");
|
|
9058
|
-
const num2 = bytesToNumberBE2(
|
|
9059
|
-
const delta =
|
|
9056
|
+
const num2 = bytesToNumberBE2(bytes);
|
|
9057
|
+
const delta = bytes.length * 8 - nBitLength;
|
|
9060
9058
|
return delta > 0 ? num2 >> BigInt(delta) : num2;
|
|
9061
9059
|
};
|
|
9062
|
-
const bits2int_modN = CURVE.bits2int_modN || function(
|
|
9063
|
-
return modN2(bits2int(
|
|
9060
|
+
const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
|
|
9061
|
+
return modN2(bits2int(bytes));
|
|
9064
9062
|
};
|
|
9065
9063
|
const ORDER_MASK = bitMask2(nBitLength);
|
|
9066
9064
|
function int2octets(num2) {
|
|
@@ -9070,7 +9068,7 @@ function weierstrass(curveDef) {
|
|
|
9070
9068
|
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
|
|
9071
9069
|
if (["recovered", "canonical"].some((k) => k in opts))
|
|
9072
9070
|
throw new Error("sign() legacy options not supported");
|
|
9073
|
-
const { hash, randomBytes:
|
|
9071
|
+
const { hash, randomBytes: randomBytes3 } = CURVE;
|
|
9074
9072
|
let { lowS, prehash, extraEntropy: ent } = opts;
|
|
9075
9073
|
if (lowS == null)
|
|
9076
9074
|
lowS = true;
|
|
@@ -9082,7 +9080,7 @@ function weierstrass(curveDef) {
|
|
|
9082
9080
|
const d = normPrivateKeyToScalar(privateKey);
|
|
9083
9081
|
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
9084
9082
|
if (ent != null && ent !== false) {
|
|
9085
|
-
const e = ent === true ?
|
|
9083
|
+
const e = ent === true ? randomBytes3(Fp2.BYTES) : ent;
|
|
9086
9084
|
seedArgs.push(ensureBytes2("extraEntropy", e));
|
|
9087
9085
|
}
|
|
9088
9086
|
const seed = concatBytes3(...seedArgs);
|
|
@@ -9356,12 +9354,12 @@ var init_weierstrass = __esm({
|
|
|
9356
9354
|
const { Err: E } = DER;
|
|
9357
9355
|
if (num2 < _0n11)
|
|
9358
9356
|
throw new E("integer: negative integers are not allowed");
|
|
9359
|
-
let
|
|
9360
|
-
if (Number.parseInt(
|
|
9361
|
-
|
|
9362
|
-
if (
|
|
9357
|
+
let hex4 = numberToHexUnpadded(num2);
|
|
9358
|
+
if (Number.parseInt(hex4[0], 16) & 8)
|
|
9359
|
+
hex4 = "00" + hex4;
|
|
9360
|
+
if (hex4.length & 1)
|
|
9363
9361
|
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
9364
|
-
return
|
|
9362
|
+
return hex4;
|
|
9365
9363
|
},
|
|
9366
9364
|
decode(data) {
|
|
9367
9365
|
const { Err: E } = DER;
|
|
@@ -9372,9 +9370,9 @@ var init_weierstrass = __esm({
|
|
|
9372
9370
|
return bytesToNumberBE2(data);
|
|
9373
9371
|
}
|
|
9374
9372
|
},
|
|
9375
|
-
toSig(
|
|
9373
|
+
toSig(hex4) {
|
|
9376
9374
|
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
9377
|
-
const data = ensureBytes2("signature",
|
|
9375
|
+
const data = ensureBytes2("signature", hex4);
|
|
9378
9376
|
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
9379
9377
|
if (seqLeftBytes.length)
|
|
9380
9378
|
throw new E("invalid signature: left bytes after parsing");
|
|
@@ -10294,9 +10292,9 @@ var init_blake3 = __esm({
|
|
|
10294
10292
|
throw new Error("XOF is not possible after digest call");
|
|
10295
10293
|
return this.writeInto(out);
|
|
10296
10294
|
}
|
|
10297
|
-
xof(
|
|
10298
|
-
anumber(
|
|
10299
|
-
return this.xofInto(new Uint8Array(
|
|
10295
|
+
xof(bytes) {
|
|
10296
|
+
anumber(bytes);
|
|
10297
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
10300
10298
|
}
|
|
10301
10299
|
digestInto(out) {
|
|
10302
10300
|
aoutput(out, this);
|
|
@@ -11807,11 +11805,11 @@ function toError(error) {
|
|
|
11807
11805
|
function toBytes3(str) {
|
|
11808
11806
|
return new TextEncoder().encode(str);
|
|
11809
11807
|
}
|
|
11810
|
-
function fromBytes(
|
|
11811
|
-
return new TextDecoder().decode(
|
|
11808
|
+
function fromBytes(bytes) {
|
|
11809
|
+
return new TextDecoder().decode(bytes);
|
|
11812
11810
|
}
|
|
11813
|
-
function hexEncode(
|
|
11814
|
-
return Array.from(
|
|
11811
|
+
function hexEncode(bytes) {
|
|
11812
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
11815
11813
|
}
|
|
11816
11814
|
function concatBytes4(...arrays) {
|
|
11817
11815
|
const total = arrays.reduce((acc, arr) => acc + arr.length, 0);
|
|
@@ -11823,20 +11821,20 @@ function concatBytes4(...arrays) {
|
|
|
11823
11821
|
}
|
|
11824
11822
|
return result;
|
|
11825
11823
|
}
|
|
11826
|
-
function base64Encode(
|
|
11824
|
+
function base64Encode(bytes) {
|
|
11827
11825
|
let binary = "";
|
|
11828
|
-
for (let i = 0; i <
|
|
11829
|
-
binary += String.fromCharCode(
|
|
11826
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
11827
|
+
binary += String.fromCharCode(bytes[i]);
|
|
11830
11828
|
}
|
|
11831
11829
|
return btoa(binary);
|
|
11832
11830
|
}
|
|
11833
11831
|
function base64Decode(str) {
|
|
11834
11832
|
const binary = atob(str);
|
|
11835
|
-
const
|
|
11833
|
+
const bytes = new Uint8Array(binary.length);
|
|
11836
11834
|
for (let i = 0; i < binary.length; i++) {
|
|
11837
|
-
|
|
11835
|
+
bytes[i] = binary.charCodeAt(i);
|
|
11838
11836
|
}
|
|
11839
|
-
return
|
|
11837
|
+
return bytes;
|
|
11840
11838
|
}
|
|
11841
11839
|
function unwrapKVData(value) {
|
|
11842
11840
|
if (value !== null && typeof value === "object" && "data" in value) {
|
|
@@ -11909,25 +11907,25 @@ function stringify(value) {
|
|
|
11909
11907
|
);
|
|
11910
11908
|
}
|
|
11911
11909
|
}
|
|
11912
|
-
function hexEncode2(
|
|
11910
|
+
function hexEncode2(bytes) {
|
|
11913
11911
|
let out = "";
|
|
11914
|
-
for (let i = 0; i <
|
|
11915
|
-
const b =
|
|
11912
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
11913
|
+
const b = bytes[i];
|
|
11916
11914
|
out += HEX[b >> 4 & 15] + HEX[b & 15];
|
|
11917
11915
|
}
|
|
11918
11916
|
return out;
|
|
11919
11917
|
}
|
|
11920
|
-
function base64Encode2(
|
|
11918
|
+
function base64Encode2(bytes) {
|
|
11921
11919
|
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
11922
11920
|
let out = "";
|
|
11923
|
-
for (let i = 0; i <
|
|
11924
|
-
const b0 =
|
|
11925
|
-
const b1 = i + 1 <
|
|
11926
|
-
const b2 = i + 2 <
|
|
11921
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
11922
|
+
const b0 = bytes[i];
|
|
11923
|
+
const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
|
|
11924
|
+
const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
|
|
11927
11925
|
out += chars[b0 >> 2 & 63];
|
|
11928
11926
|
out += chars[(b0 << 4 | b1 >> 4) & 63];
|
|
11929
|
-
out += i + 1 <
|
|
11930
|
-
out += i + 2 <
|
|
11927
|
+
out += i + 1 < bytes.length ? chars[(b1 << 2 | b2 >> 6) & 63] : "=";
|
|
11928
|
+
out += i + 2 < bytes.length ? chars[b2 & 63] : "=";
|
|
11931
11929
|
}
|
|
11932
11930
|
return out;
|
|
11933
11931
|
}
|
|
@@ -13430,9 +13428,9 @@ var init_dist2 = __esm({
|
|
|
13430
13428
|
}
|
|
13431
13429
|
if (ArrayBuffer.isView(item.value)) {
|
|
13432
13430
|
const value = item.value;
|
|
13433
|
-
const
|
|
13434
|
-
|
|
13435
|
-
return new Blob([
|
|
13431
|
+
const bytes = new Uint8Array(value.byteLength);
|
|
13432
|
+
bytes.set(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
|
|
13433
|
+
return new Blob([bytes], {
|
|
13436
13434
|
type: contentType ?? "application/octet-stream"
|
|
13437
13435
|
});
|
|
13438
13436
|
}
|
|
@@ -13487,9 +13485,9 @@ var init_dist2 = __esm({
|
|
|
13487
13485
|
}
|
|
13488
13486
|
parseBatchValue(dataBase64, headers, raw = false, binary = false) {
|
|
13489
13487
|
const encoded = globalThis.atob(dataBase64);
|
|
13490
|
-
const
|
|
13491
|
-
if (binary) return
|
|
13492
|
-
const text = new TextDecoder().decode(
|
|
13488
|
+
const bytes = Uint8Array.from(encoded, (character) => character.charCodeAt(0));
|
|
13489
|
+
if (binary) return bytes;
|
|
13490
|
+
const text = new TextDecoder().decode(bytes);
|
|
13493
13491
|
if (raw) return text;
|
|
13494
13492
|
const contentType = Object.entries(headers).find(
|
|
13495
13493
|
([name2]) => name2.toLowerCase() === "content-type"
|
|
@@ -14707,7 +14705,7 @@ var init_dist2 = __esm({
|
|
|
14707
14705
|
async handleErrorResponse(response, operation) {
|
|
14708
14706
|
const errorText = await response.text();
|
|
14709
14707
|
const errorBody = parseServiceErrorBody(errorText);
|
|
14710
|
-
const
|
|
14708
|
+
const errorCode = this.mapHttpStatusToErrorCode(
|
|
14711
14709
|
response.status,
|
|
14712
14710
|
errorBody.error
|
|
14713
14711
|
);
|
|
@@ -14725,7 +14723,7 @@ var init_dist2 = __esm({
|
|
|
14725
14723
|
if (resource) meta.resource = resource;
|
|
14726
14724
|
}
|
|
14727
14725
|
return err(
|
|
14728
|
-
serviceError(
|
|
14726
|
+
serviceError(errorCode, message, "sql", { meta })
|
|
14729
14727
|
);
|
|
14730
14728
|
}
|
|
14731
14729
|
mapHttpStatusToErrorCode(status, serverError) {
|
|
@@ -15055,7 +15053,7 @@ var init_dist2 = __esm({
|
|
|
15055
15053
|
async handleErrorResponse(response, operation) {
|
|
15056
15054
|
const errorText = await response.text();
|
|
15057
15055
|
const errorBody = parseServiceErrorBody(errorText);
|
|
15058
|
-
const
|
|
15056
|
+
const errorCode = this.mapHttpStatusToErrorCode(
|
|
15059
15057
|
response.status,
|
|
15060
15058
|
errorBody.error
|
|
15061
15059
|
);
|
|
@@ -15073,7 +15071,7 @@ var init_dist2 = __esm({
|
|
|
15073
15071
|
if (resource) meta.resource = resource;
|
|
15074
15072
|
}
|
|
15075
15073
|
return err(
|
|
15076
|
-
serviceError(
|
|
15074
|
+
serviceError(errorCode, message, "duckdb", { meta })
|
|
15077
15075
|
);
|
|
15078
15076
|
}
|
|
15079
15077
|
mapHttpStatusToErrorCode(status, serverError) {
|
|
@@ -17503,25 +17501,25 @@ function encodeTo(int, target, offset = 0) {
|
|
|
17503
17501
|
function encodingLength(int) {
|
|
17504
17502
|
return varint_default.encodingLength(int);
|
|
17505
17503
|
}
|
|
17506
|
-
function create(code222,
|
|
17507
|
-
const size2 =
|
|
17504
|
+
function create(code222, digest3) {
|
|
17505
|
+
const size2 = digest3.byteLength;
|
|
17508
17506
|
const sizeOffset = encodingLength(code222);
|
|
17509
17507
|
const digestOffset = sizeOffset + encodingLength(size2);
|
|
17510
17508
|
const bytes3 = new Uint8Array(digestOffset + size2);
|
|
17511
17509
|
encodeTo(code222, bytes3, 0);
|
|
17512
17510
|
encodeTo(size2, bytes3, sizeOffset);
|
|
17513
|
-
bytes3.set(
|
|
17514
|
-
return new Digest(code222, size2,
|
|
17511
|
+
bytes3.set(digest3, digestOffset);
|
|
17512
|
+
return new Digest(code222, size2, digest3, bytes3);
|
|
17515
17513
|
}
|
|
17516
17514
|
function decode4(multihash) {
|
|
17517
17515
|
const bytes3 = coerce22(multihash);
|
|
17518
17516
|
const [code222, sizeOffset] = decode3(bytes3);
|
|
17519
17517
|
const [size2, digestOffset] = decode3(bytes3.subarray(sizeOffset));
|
|
17520
|
-
const
|
|
17521
|
-
if (
|
|
17518
|
+
const digest3 = bytes3.subarray(sizeOffset + digestOffset);
|
|
17519
|
+
if (digest3.byteLength !== size2) {
|
|
17522
17520
|
throw new Error("Incorrect length");
|
|
17523
17521
|
}
|
|
17524
|
-
return new Digest(code222, size2,
|
|
17522
|
+
return new Digest(code222, size2, digest3, bytes3);
|
|
17525
17523
|
}
|
|
17526
17524
|
function equals2(a, b) {
|
|
17527
17525
|
if (a === b) {
|
|
@@ -17614,8 +17612,8 @@ function encodeCID(version3, code222, multihash) {
|
|
|
17614
17612
|
return bytes3;
|
|
17615
17613
|
}
|
|
17616
17614
|
async function computeCid(bytes3) {
|
|
17617
|
-
const
|
|
17618
|
-
return CID.create(1, code,
|
|
17615
|
+
const digest3 = create(SHA256_CODE, sha256(new Uint8Array(bytes3)));
|
|
17616
|
+
return CID.create(1, code, digest3).toString();
|
|
17619
17617
|
}
|
|
17620
17618
|
function isCanonicalRawCid(cidString) {
|
|
17621
17619
|
let cid2;
|
|
@@ -18242,8 +18240,8 @@ async function verifyEnvelopeV3(envelope, options) {
|
|
|
18242
18240
|
if (hex(sourceDigest) !== parsed.contentSourceDigestHex) return false;
|
|
18243
18241
|
const sortedCapabilities = [...policy.capabilityCeiling].sort((left, right) => canonicalize2(left).localeCompare(canonicalize2(right)));
|
|
18244
18242
|
const capabilityCeilingHashHex = hex(sha2562(new TextEncoder().encode(`${POLICY_CAPABILITY_V1_DOMAIN}${canonicalize2(sortedCapabilities)}`)));
|
|
18245
|
-
const
|
|
18246
|
-
const nativeProjectionHashHex = hex(sha2562(new TextEncoder().encode(`${NATIVE_PROJECTION_V1_DOMAIN}${canonicalize2(
|
|
18243
|
+
const nativeProjection2 = 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)));
|
|
18244
|
+
const nativeProjectionHashHex = hex(sha2562(new TextEncoder().encode(`${NATIVE_PROJECTION_V1_DOMAIN}${canonicalize2(nativeProjection2)}`)));
|
|
18247
18245
|
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 }]]))]));
|
|
18248
18246
|
const kv = policy.capabilityCeiling.find((capability) => capability.kind === "kv");
|
|
18249
18247
|
const expectedKvActions = parsed.actions.flatMap((action) => action === "read" ? ["tinycloud.kv/get", "tinycloud.kv/metadata"] : action === "list" ? ["tinycloud.kv/list"] : ["tinycloud.kv/put"]);
|
|
@@ -18256,8 +18254,8 @@ async function verifyEnvelopeV3(envelope, options) {
|
|
|
18256
18254
|
const expectedBindingDigestHex = hex(sha2562(new TextEncoder().encode(canonicalize2({ enforcerDid: binding.enforcerDid, nodeAudience: binding.nodeAudience }))));
|
|
18257
18255
|
if (binding.enforcerDid !== parsed.target.nodeAudience || binding.attestationBindingDigestHex !== expectedBindingDigestHex || bindingSignature.signerDid !== binding.nodeAudience || 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;
|
|
18258
18256
|
try {
|
|
18259
|
-
const
|
|
18260
|
-
if (!ed25519.verify(fromBase64Url(bindingSignature.value),
|
|
18257
|
+
const digest3 = sha2562(new TextEncoder().encode(`${ATTESTED_ENFORCER_V2_DOMAIN}${canonicalize2(unsignedBinding)}`));
|
|
18258
|
+
if (!ed25519.verify(fromBase64Url(bindingSignature.value), digest3, ed25519PublicKeyFromDidKey(binding.nodeAudience), ED25519_VERIFY_OPTS2)) return false;
|
|
18261
18259
|
} catch {
|
|
18262
18260
|
return false;
|
|
18263
18261
|
}
|
|
@@ -18981,6 +18979,12 @@ async function publishShare(options) {
|
|
|
18981
18979
|
envelopeKey?.fill(0);
|
|
18982
18980
|
}
|
|
18983
18981
|
}
|
|
18982
|
+
function authorizationMethodForTarget(target) {
|
|
18983
|
+
if (target.kind === "recipientDid") return "openkey-device";
|
|
18984
|
+
if (target.kind === "email") return "email-claim";
|
|
18985
|
+
if (target.kind === "emailDomain") return "email-claim";
|
|
18986
|
+
return void 0;
|
|
18987
|
+
}
|
|
18984
18988
|
function equals3(aa, bb) {
|
|
18985
18989
|
if (aa === bb) {
|
|
18986
18990
|
return true;
|
|
@@ -19226,6 +19230,317 @@ function rfc46482({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) {
|
|
|
19226
19230
|
}
|
|
19227
19231
|
});
|
|
19228
19232
|
}
|
|
19233
|
+
function validEmail(value) {
|
|
19234
|
+
return /^[^@\s]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(value);
|
|
19235
|
+
}
|
|
19236
|
+
function validDomain(value) {
|
|
19237
|
+
return /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))+$/i.test(value);
|
|
19238
|
+
}
|
|
19239
|
+
function validRecipientDid(value) {
|
|
19240
|
+
if (value.length === 0 || value.length > 2048 || /[\u0000-\u0020\u007f]/.test(value)) return false;
|
|
19241
|
+
const parts = value.split(":");
|
|
19242
|
+
if (parts.length < 3 || parts[0] !== "did" || !/^[a-z0-9]+$/.test(parts[1] ?? "")) return false;
|
|
19243
|
+
const identifier = parts.slice(2);
|
|
19244
|
+
if (identifier.some((part) => part.length === 0)) return false;
|
|
19245
|
+
if (parts[1] === "web") {
|
|
19246
|
+
const host = identifier[0] ?? "";
|
|
19247
|
+
if (host.length > 253 || host.split(".").some((label) => !label || label.length > 63 || !/^[A-Za-z0-9-]+$/.test(label) || label.startsWith("-") || label.endsWith("-"))) return false;
|
|
19248
|
+
return identifier.slice(1).every((part) => /^[A-Za-z0-9._%-]+$/.test(part));
|
|
19249
|
+
}
|
|
19250
|
+
if (parts[1] === "pkh") return identifier.length >= 3 && identifier.every((part) => /^[A-Za-z0-9._%-]+$/.test(part));
|
|
19251
|
+
if (parts[1] === "key") {
|
|
19252
|
+
try {
|
|
19253
|
+
const bytes3 = base58btc2.decode(identifier.join(":"));
|
|
19254
|
+
return bytes3.length === 34 && bytes3[0] === 237 && bytes3[1] === 1;
|
|
19255
|
+
} catch {
|
|
19256
|
+
return false;
|
|
19257
|
+
}
|
|
19258
|
+
}
|
|
19259
|
+
return false;
|
|
19260
|
+
}
|
|
19261
|
+
function normalizeShareTarget(target) {
|
|
19262
|
+
if (target.kind === "bearer") return target;
|
|
19263
|
+
if (target.kind === "recipientDid") {
|
|
19264
|
+
if (!validRecipientDid(target.did)) throw new TypeError("recipient DID is invalid");
|
|
19265
|
+
return { kind: target.kind, did: target.did };
|
|
19266
|
+
}
|
|
19267
|
+
if (target.kind === "email") {
|
|
19268
|
+
if (!validEmail(target.address)) throw new TypeError("recipient email is invalid");
|
|
19269
|
+
const at = target.address.lastIndexOf("@");
|
|
19270
|
+
return { kind: target.kind, address: `${target.address.slice(0, at)}@${target.address.slice(at + 1).toLowerCase()}` };
|
|
19271
|
+
}
|
|
19272
|
+
if (!validDomain(target.domain)) throw new TypeError("recipient email domain is invalid");
|
|
19273
|
+
return { kind: target.kind, domain: target.domain.toLowerCase() };
|
|
19274
|
+
}
|
|
19275
|
+
function targetAuthorizationMethod(target) {
|
|
19276
|
+
return authorizationMethodForTarget(target);
|
|
19277
|
+
}
|
|
19278
|
+
async function publishTargetShare(input) {
|
|
19279
|
+
const target = normalizeShareTarget(input.target);
|
|
19280
|
+
if (target.kind === "bearer") return publishShare(input);
|
|
19281
|
+
if (input.targetAdapter === void 0) {
|
|
19282
|
+
return {
|
|
19283
|
+
state: "authorization-required",
|
|
19284
|
+
method: targetAuthorizationMethod(target)
|
|
19285
|
+
};
|
|
19286
|
+
}
|
|
19287
|
+
const source = input.source instanceof Uint8Array ? input.source.slice() : await (async () => {
|
|
19288
|
+
const chunks = [];
|
|
19289
|
+
let size2 = 0;
|
|
19290
|
+
for await (const chunk of input.source) {
|
|
19291
|
+
if (!(chunk instanceof Uint8Array)) throw new TypeError("addressed publication source yielded invalid bytes");
|
|
19292
|
+
size2 += chunk.byteLength;
|
|
19293
|
+
if (size2 > (input.maxBytes ?? 100 * 1024 * 1024)) throw new TypeError("addressed publication exceeds maxBytes");
|
|
19294
|
+
chunks.push(chunk.slice());
|
|
19295
|
+
}
|
|
19296
|
+
const bytes3 = new Uint8Array(size2);
|
|
19297
|
+
let offset = 0;
|
|
19298
|
+
for (const chunk of chunks) {
|
|
19299
|
+
bytes3.set(chunk, offset);
|
|
19300
|
+
offset += chunk.byteLength;
|
|
19301
|
+
}
|
|
19302
|
+
return bytes3;
|
|
19303
|
+
})();
|
|
19304
|
+
const files = input.files === void 0 || input.files.length === 0 ? [{ bytes: source }] : input.files;
|
|
19305
|
+
const limit = input.maxBytes ?? SHARE_CONTENT_LIMIT;
|
|
19306
|
+
let totalBytes = 0;
|
|
19307
|
+
for (const file of files) {
|
|
19308
|
+
totalBytes += file.bytes.byteLength;
|
|
19309
|
+
if (!Number.isSafeInteger(totalBytes) || totalBytes > limit) {
|
|
19310
|
+
throw new SharePublishError("max-bytes-exceeded", "addressed publication exceeds the combined byte limit");
|
|
19311
|
+
}
|
|
19312
|
+
}
|
|
19313
|
+
return input.targetAdapter.publish({
|
|
19314
|
+
source,
|
|
19315
|
+
filename: input.filename,
|
|
19316
|
+
...input.files === void 0 ? {} : { files: input.files },
|
|
19317
|
+
...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
|
|
19318
|
+
...input.resourceKind === void 0 ? {} : { resourceKind: input.resourceKind },
|
|
19319
|
+
...input.actions === void 0 ? {} : { actions: input.actions },
|
|
19320
|
+
target,
|
|
19321
|
+
expiresAt: input.expiresAt ?? new Date((input.now?.() ?? Date.now()) + 7 * 24 * 60 * 60 * 1e3),
|
|
19322
|
+
origin: input.origin,
|
|
19323
|
+
...input.inline === void 0 ? {} : { inline: input.inline },
|
|
19324
|
+
upload: {
|
|
19325
|
+
...input.registryBaseUrl === void 0 ? {} : { registryBaseUrl: input.registryBaseUrl },
|
|
19326
|
+
...input.fetchFn === void 0 ? {} : { fetchFn: input.fetchFn },
|
|
19327
|
+
...input.authorizeUpload === void 0 ? {} : { authorizeUpload: input.authorizeUpload },
|
|
19328
|
+
...input.authorizationOrigin === void 0 ? {} : { authorizationOrigin: input.authorizationOrigin },
|
|
19329
|
+
...input.credentials === void 0 ? {} : { credentials: input.credentials },
|
|
19330
|
+
...input.allowInsecureRegistry === void 0 ? {} : { allowInsecureRegistry: input.allowInsecureRegistry },
|
|
19331
|
+
...input.uploadBlob === void 0 ? {} : { uploadBlob: input.uploadBlob }
|
|
19332
|
+
},
|
|
19333
|
+
...input.notify === void 0 ? {} : { notify: input.notify }
|
|
19334
|
+
});
|
|
19335
|
+
}
|
|
19336
|
+
function targetMatcher(target) {
|
|
19337
|
+
if (target.kind === "recipientDid") return { kind: "recipientDid", value: target.did };
|
|
19338
|
+
if (target.kind === "email") return { kind: "exactEmail", value: target.address };
|
|
19339
|
+
return { kind: "emailDomain", value: target.domain };
|
|
19340
|
+
}
|
|
19341
|
+
function targetKind(target) {
|
|
19342
|
+
return target.kind;
|
|
19343
|
+
}
|
|
19344
|
+
function assertSafeInput(input) {
|
|
19345
|
+
if (!/^[A-Za-z0-9_-]{16,128}$/.test(input.shareId)) throw new TypeError("addressed share id is invalid");
|
|
19346
|
+
if (input.filename.length === 0 || input.filename === "." || input.filename === ".." || /[/\\\u0000-\u001f\u007f]/.test(input.filename)) throw new TypeError("addressed filename is invalid");
|
|
19347
|
+
if (!Number.isSafeInteger(input.byteLength) || input.byteLength < 0 || input.byteLength > SHARE_CONTENT_LIMIT) throw new TypeError("addressed content length is invalid");
|
|
19348
|
+
if (input.actions.length === 0 || input.policyActions.length === 0) throw new TypeError("addressed share actions are empty");
|
|
19349
|
+
if (!Number.isFinite(input.expiresAt.getTime()) || input.expiresAt.getTime() <= Date.now()) throw new TypeError("addressed share expiry must be in the future");
|
|
19350
|
+
if (input.artifact === "html" && (input.resource.kind !== "prefix" || !input.actions.includes("read") || !input.actions.includes("list"))) throw new TypeError("html artifacts require a readable prefix");
|
|
19351
|
+
if (input.contentSource.shareId !== input.shareId || input.contentSource.selector !== input.resource.kind) throw new TypeError("addressed content source is not bound to the share");
|
|
19352
|
+
}
|
|
19353
|
+
function hex2(bytes3) {
|
|
19354
|
+
return [...bytes3].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
19355
|
+
}
|
|
19356
|
+
function digestHex(value, domain) {
|
|
19357
|
+
return hex2(sha2562(textEncoder.encode(`${domain}${canonicalize2(value)}`)));
|
|
19358
|
+
}
|
|
19359
|
+
function sortCanonical(values) {
|
|
19360
|
+
return [...values].sort((left, right) => canonicalize2(left).localeCompare(canonicalize2(right)));
|
|
19361
|
+
}
|
|
19362
|
+
function base32Lower2(bytes3) {
|
|
19363
|
+
const alphabet2 = "abcdefghijklmnopqrstuvwxyz234567";
|
|
19364
|
+
let output = "";
|
|
19365
|
+
let buffer = 0;
|
|
19366
|
+
let bits = 0;
|
|
19367
|
+
for (const byte of bytes3) {
|
|
19368
|
+
buffer = buffer << 8 | byte;
|
|
19369
|
+
bits += 8;
|
|
19370
|
+
while (bits >= 5) {
|
|
19371
|
+
output += alphabet2[buffer >>> bits - 5 & 31];
|
|
19372
|
+
bits -= 5;
|
|
19373
|
+
}
|
|
19374
|
+
}
|
|
19375
|
+
if (bits > 0) output += alphabet2[buffer << 5 - bits & 31];
|
|
19376
|
+
return output;
|
|
19377
|
+
}
|
|
19378
|
+
function rfc3339Seconds(value) {
|
|
19379
|
+
return new Date(Math.floor(value.getTime() / 1e3) * 1e3).toISOString().replace(".000Z", "Z");
|
|
19380
|
+
}
|
|
19381
|
+
function nativeProjection(capabilities) {
|
|
19382
|
+
return sortCanonical(capabilities.map((capability) => capability.kind === "encryption" ? { service: "tinycloud.encryption", space: capability.resource, path: capability.resource, actions: [capability.action] } : {
|
|
19383
|
+
service: "tinycloud.kv",
|
|
19384
|
+
space: capability.resource.slice(0, capability.resource.indexOf("/kv/")),
|
|
19385
|
+
path: capability.resource.slice(capability.resource.indexOf("/kv/") + 4),
|
|
19386
|
+
actions: [...capability.actions],
|
|
19387
|
+
caveat: { type: "xyz.tinycloud.resource/selector", kind: capability.selector, value: capability.resource }
|
|
19388
|
+
}));
|
|
19389
|
+
}
|
|
19390
|
+
async function createPolicy(options, capabilities) {
|
|
19391
|
+
const fields = {
|
|
19392
|
+
ownerDid: options.authority.ownerDid,
|
|
19393
|
+
createdAt: rfc3339Seconds(/* @__PURE__ */ new Date()),
|
|
19394
|
+
expiresAt: rfc3339Seconds(options.expiresAt),
|
|
19395
|
+
contentSource: options.contentSource,
|
|
19396
|
+
capabilityCeiling: [...capabilities]
|
|
19397
|
+
};
|
|
19398
|
+
const unsigned = options.credentialRequirement === void 0 ? { schema: "xyz.tinycloud.policy/policy/v1", ...fields } : { schema: "xyz.tinycloud.policy/policy/v2", ...fields, credentialRequirement: options.credentialRequirement };
|
|
19399
|
+
const domain = options.credentialRequirement === void 0 ? POLICY_V1_DOMAIN : POLICY_V2_DOMAIN;
|
|
19400
|
+
const policyDigestHex = digestHex(unsigned, domain);
|
|
19401
|
+
const signature = await options.authority.sign(sha2562(textEncoder.encode(`${domain}${canonicalize2(unsigned)}`)));
|
|
19402
|
+
if (signature.byteLength !== 64) throw new TypeError("policy signature must be Ed25519");
|
|
19403
|
+
const policy = {
|
|
19404
|
+
...unsigned,
|
|
19405
|
+
policyId: `pol_${base32Lower2(Uint8Array.from(policyDigestHex.match(/../g), (byte) => Number.parseInt(byte, 16)))}`,
|
|
19406
|
+
signature: { suite: "Ed25519", signerDid: options.authority.ownerDid, value: toBase64Url(signature) }
|
|
19407
|
+
};
|
|
19408
|
+
return { policy, policyCid: await computeCid(textEncoder.encode(canonicalize2(policy))), policyDigestHex };
|
|
19409
|
+
}
|
|
19410
|
+
function publicationResult(input) {
|
|
19411
|
+
const result = {
|
|
19412
|
+
protocol: "tinycloud-share",
|
|
19413
|
+
version: SHARE_PUBLISH_RESULT_VERSION,
|
|
19414
|
+
url: input.url,
|
|
19415
|
+
link: { kind: input.options.inline === true ? "inline" : "compact", cid: input.envelopeCid },
|
|
19416
|
+
metadata: {
|
|
19417
|
+
protocol: "tinycloud-share",
|
|
19418
|
+
version: 1,
|
|
19419
|
+
shareId: input.options.shareId,
|
|
19420
|
+
origin: input.options.shareOrigin,
|
|
19421
|
+
target: { kind: targetKind(input.options.target), origin: input.options.nodeOrigin, nodeAudience: input.enforcerDid, spaceId: input.options.spaceId },
|
|
19422
|
+
resource: { ...input.options.resource },
|
|
19423
|
+
actions: [...input.options.actions],
|
|
19424
|
+
expiresAt: input.expiry,
|
|
19425
|
+
display: { filename: input.options.filename },
|
|
19426
|
+
recipientMatcher: { ...input.matcher },
|
|
19427
|
+
policyCid: input.policyCid,
|
|
19428
|
+
ownerDelegationCid: input.policyRootCid,
|
|
19429
|
+
enforcementDelegationCid: input.enforcementRootCid,
|
|
19430
|
+
ownerDid: input.options.authority.ownerDid,
|
|
19431
|
+
enforcerDid: input.enforcerDid,
|
|
19432
|
+
envelopeCid: input.envelopeCid,
|
|
19433
|
+
shareCid: input.envelopeCid
|
|
19434
|
+
},
|
|
19435
|
+
registryDeleteAfter: input.retention
|
|
19436
|
+
};
|
|
19437
|
+
Object.defineProperty(result, "toJSON", { enumerable: false, value: () => redactPublishedShare(result) });
|
|
19438
|
+
Object.defineProperty(result, "url", { enumerable: false, value: input.url });
|
|
19439
|
+
Object.defineProperty(result, "deliveryMaterial", { enumerable: false, value: input.deliveryMaterial });
|
|
19440
|
+
return result;
|
|
19441
|
+
}
|
|
19442
|
+
async function publishAddressedShare(options) {
|
|
19443
|
+
assertSafeInput(options);
|
|
19444
|
+
const target = normalizeShareTarget(options.target);
|
|
19445
|
+
if (target.kind === "bearer") throw new TypeError("addressed target is required");
|
|
19446
|
+
const expiry = rfc3339Seconds(options.expiresAt);
|
|
19447
|
+
const matcher = targetMatcher(target);
|
|
19448
|
+
const capabilities = sortCanonical([
|
|
19449
|
+
{ kind: "kv", resource: options.contentSource.kvResource, selector: options.resource.kind, actions: [...options.policyActions] },
|
|
19450
|
+
{ kind: "encryption", resource: options.contentSource.encryptionNetwork, action: "tinycloud.encryption/decrypt" }
|
|
19451
|
+
]);
|
|
19452
|
+
const created = await createPolicy(options, capabilities);
|
|
19453
|
+
const contentSourceDigestHex = digestHex(options.contentSource, CONTENT_SOURCE_V1_DOMAIN2);
|
|
19454
|
+
const capabilityCeilingHashHex = digestHex(capabilities, POLICY_CAPABILITY_V1_DOMAIN2);
|
|
19455
|
+
const nativeProjectionHashHex = digestHex(nativeProjection(capabilities), NATIVE_PROJECTION_V1_DOMAIN2);
|
|
19456
|
+
const commonRoot = {
|
|
19457
|
+
ownerDid: options.authority.ownerDid,
|
|
19458
|
+
policyId: created.policy.policyId,
|
|
19459
|
+
policyDigestHex: created.policyDigestHex,
|
|
19460
|
+
policyCid: created.policyCid,
|
|
19461
|
+
contentSourceDigestHex,
|
|
19462
|
+
capabilityCeilingHashHex,
|
|
19463
|
+
nativeProjectionHashHex,
|
|
19464
|
+
notBefore: new Date(created.policy.createdAt),
|
|
19465
|
+
expiresAt: new Date(expiry),
|
|
19466
|
+
nodeAudience: options.nodeAudience,
|
|
19467
|
+
capabilities
|
|
19468
|
+
};
|
|
19469
|
+
const policyRootReceipt = await options.authority.createOwnerRoot({ ...commonRoot, role: "policy-authority", audienceDid: `did:tinycloud:policy:${created.policyDigestHex}` });
|
|
19470
|
+
const enforcementRootReceipt = await options.authority.createOwnerRoot({ ...commonRoot, role: "policy-enforcement", audienceDid: options.enforcerDid });
|
|
19471
|
+
const policyRoot = { cid: policyRootReceipt.cid, authorization: policyRootReceipt.delegationHeader.Authorization.replace(/^Bearer\s+/i, ""), role: "policy-authority" };
|
|
19472
|
+
const enforcementRoot = { cid: enforcementRootReceipt.cid, authorization: enforcementRootReceipt.delegationHeader.Authorization.replace(/^Bearer\s+/i, ""), role: "policy-enforcement" };
|
|
19473
|
+
const registration = await options.authority.registerPolicy({
|
|
19474
|
+
policyCid: created.policyCid,
|
|
19475
|
+
policy: created.policy,
|
|
19476
|
+
policyRoot,
|
|
19477
|
+
enforcementRoot,
|
|
19478
|
+
contentSourceDigestHex,
|
|
19479
|
+
nativeProjectionHashHex,
|
|
19480
|
+
rootExpiresAt: expiry,
|
|
19481
|
+
enforcerDid: options.enforcerDid,
|
|
19482
|
+
expectedNodeAudience: options.nodeAudience
|
|
19483
|
+
});
|
|
19484
|
+
if (registration.policyCid !== created.policyCid || registration.policyRootCid !== policyRoot.cid || registration.enforcementRootCid !== enforcementRoot.cid) throw new Error("Policy/v3 registration receipt is not bound to the published roots");
|
|
19485
|
+
const unsigned = {
|
|
19486
|
+
version: 3,
|
|
19487
|
+
shareId: options.shareId,
|
|
19488
|
+
recipientMatcher: matcher,
|
|
19489
|
+
...options.deliveryEmail === void 0 ? {} : { deliveryEmail: options.deliveryEmail },
|
|
19490
|
+
actions: [...options.actions],
|
|
19491
|
+
resource: { ...options.resource },
|
|
19492
|
+
target: { origin: options.nodeOrigin, nodeAudience: registration.attestedEnforcerBinding.enforcerDid, spaceId: options.spaceId },
|
|
19493
|
+
policy: created.policy,
|
|
19494
|
+
policyCid: created.policyCid,
|
|
19495
|
+
policyRoot,
|
|
19496
|
+
enforcementRoot,
|
|
19497
|
+
attestedEnforcerBinding: registration.attestedEnforcerBinding,
|
|
19498
|
+
contentSource: options.contentSource,
|
|
19499
|
+
contentSourceDigestHex,
|
|
19500
|
+
encryptionNetwork: options.contentSource.encryptionNetwork,
|
|
19501
|
+
expiry,
|
|
19502
|
+
display: { filename: options.filename },
|
|
19503
|
+
encrypted: true,
|
|
19504
|
+
metadata: {
|
|
19505
|
+
mediaType: options.mediaType,
|
|
19506
|
+
byteLength: options.byteLength,
|
|
19507
|
+
filename: options.filename,
|
|
19508
|
+
...options.mediaType.startsWith("text/") ? { encoding: "utf-8" } : {},
|
|
19509
|
+
...options.artifact === void 0 ? {} : { artifact: options.artifact }
|
|
19510
|
+
}
|
|
19511
|
+
};
|
|
19512
|
+
unsignedShareEnvelopeV3Schema.parse(unsigned);
|
|
19513
|
+
const envelopeSignature = await options.authority.sign(sha2562(textEncoder.encode(`${ENVELOPE_V3_DOMAIN}${canonicalize2(unsigned)}`)));
|
|
19514
|
+
if (envelopeSignature.byteLength !== 64) throw new TypeError("v3 envelope signature must be Ed25519");
|
|
19515
|
+
const envelope = { ...unsigned, signature: { signerDid: options.authority.ownerDid, algorithm: "Ed25519", value: toBase64Url(envelopeSignature) } };
|
|
19516
|
+
shareEnvelopeV3Schema.parse(envelope);
|
|
19517
|
+
const envelopeKey = generateKey();
|
|
19518
|
+
try {
|
|
19519
|
+
const sealed = await seal(textEncoder.encode(canonicalize2(envelope)), envelopeKey);
|
|
19520
|
+
let url;
|
|
19521
|
+
let retention = options.expiresAt.toISOString();
|
|
19522
|
+
if (options.inline === true) url = await encodeInlineShareUrl({ origin: options.shareOrigin, ciphertext: sealed.blob, key32: envelopeKey });
|
|
19523
|
+
else {
|
|
19524
|
+
const uploaded = await uploadShareBlob({ source: new Uint8Array([1]), filename: options.filename, origin: options.shareOrigin, ...options.upload }, { blob: sealed.blob, cid: sealed.cid, deleteAfter: retention, contentLength: sealed.blob.byteLength });
|
|
19525
|
+
retention = uploaded.deleteAfter;
|
|
19526
|
+
url = encodeShareUrl({ origin: options.shareOrigin, ciphertextCid: uploaded.cid, key32: envelopeKey });
|
|
19527
|
+
}
|
|
19528
|
+
await options.publishBinding?.({
|
|
19529
|
+
version: 3,
|
|
19530
|
+
shareCid: sealed.cid,
|
|
19531
|
+
shareId: options.shareId,
|
|
19532
|
+
policyCid: created.policyCid,
|
|
19533
|
+
policyRootCid: policyRoot.cid,
|
|
19534
|
+
enforcementRootCid: enforcementRoot.cid,
|
|
19535
|
+
contentSourceDigestHex
|
|
19536
|
+
});
|
|
19537
|
+
const deliveryMaterial = { envelope, sealedEnvelope: toBase64Url(sealed.blob), envelopeKey: toBase64Url(envelopeKey), shareCid: sealed.cid };
|
|
19538
|
+
options.onDeliveryMaterial?.(deliveryMaterial);
|
|
19539
|
+
return publicationResult({ options, url, envelopeCid: sealed.cid, matcher, policyCid: created.policyCid, policyRootCid: policyRoot.cid, enforcementRootCid: enforcementRoot.cid, enforcerDid: registration.attestedEnforcerBinding.enforcerDid, expiry, retention, deliveryMaterial });
|
|
19540
|
+
} finally {
|
|
19541
|
+
envelopeKey.fill(0);
|
|
19542
|
+
}
|
|
19543
|
+
}
|
|
19229
19544
|
function encode4(num2, out, offset) {
|
|
19230
19545
|
out = out || [];
|
|
19231
19546
|
offset = offset || 0;
|
|
@@ -19267,25 +19582,25 @@ function encodeTo2(int, target, offset = 0) {
|
|
|
19267
19582
|
function encodingLength2(int) {
|
|
19268
19583
|
return varint_default2.encodingLength(int);
|
|
19269
19584
|
}
|
|
19270
|
-
function create2(code32,
|
|
19271
|
-
const size2 =
|
|
19585
|
+
function create2(code32, digest3) {
|
|
19586
|
+
const size2 = digest3.byteLength;
|
|
19272
19587
|
const sizeOffset = encodingLength2(code32);
|
|
19273
19588
|
const digestOffset = sizeOffset + encodingLength2(size2);
|
|
19274
19589
|
const bytes3 = new Uint8Array(digestOffset + size2);
|
|
19275
19590
|
encodeTo2(code32, bytes3, 0);
|
|
19276
19591
|
encodeTo2(size2, bytes3, sizeOffset);
|
|
19277
|
-
bytes3.set(
|
|
19278
|
-
return new Digest2(code32, size2,
|
|
19592
|
+
bytes3.set(digest3, digestOffset);
|
|
19593
|
+
return new Digest2(code32, size2, digest3, bytes3);
|
|
19279
19594
|
}
|
|
19280
19595
|
function decode8(multihash) {
|
|
19281
19596
|
const bytes3 = coerce3(multihash);
|
|
19282
19597
|
const [code32, sizeOffset] = decode7(bytes3);
|
|
19283
19598
|
const [size2, digestOffset] = decode7(bytes3.subarray(sizeOffset));
|
|
19284
|
-
const
|
|
19285
|
-
if (
|
|
19599
|
+
const digest3 = bytes3.subarray(sizeOffset + digestOffset);
|
|
19600
|
+
if (digest3.byteLength !== size2) {
|
|
19286
19601
|
throw new Error("Incorrect length");
|
|
19287
19602
|
}
|
|
19288
|
-
return new Digest2(code32, size2,
|
|
19603
|
+
return new Digest2(code32, size2, digest3, bytes3);
|
|
19289
19604
|
}
|
|
19290
19605
|
function equals4(a, b) {
|
|
19291
19606
|
if (a === b) {
|
|
@@ -19377,18 +19692,6 @@ function encodeCID2(version3, code32, multihash) {
|
|
|
19377
19692
|
bytes3.set(multihash, hashOffset);
|
|
19378
19693
|
return bytes3;
|
|
19379
19694
|
}
|
|
19380
|
-
function bytes(value) {
|
|
19381
|
-
return new Uint8Array(value);
|
|
19382
|
-
}
|
|
19383
|
-
function b64(value) {
|
|
19384
|
-
if (typeof btoa === "function") {
|
|
19385
|
-
let binary = "";
|
|
19386
|
-
for (const byte of value) binary += String.fromCharCode(byte);
|
|
19387
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
19388
|
-
}
|
|
19389
|
-
if (typeof Buffer !== "undefined") return Buffer.from(value).toString("base64url");
|
|
19390
|
-
throw new Error("base64url encoding is unavailable");
|
|
19391
|
-
}
|
|
19392
19695
|
function fromB64(value) {
|
|
19393
19696
|
if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("owner-share value is not canonical base64url");
|
|
19394
19697
|
if (typeof atob === "function") {
|
|
@@ -19401,16 +19704,6 @@ function fromB64(value) {
|
|
|
19401
19704
|
function cid(bytesValue) {
|
|
19402
19705
|
return CID2.createV1(code2, create2(SHA256_CODE2, sha2562(bytesValue))).toString(base322.encoder);
|
|
19403
19706
|
}
|
|
19404
|
-
function digest(bytesValue) {
|
|
19405
|
-
return b64(sha2562(bytesValue));
|
|
19406
|
-
}
|
|
19407
|
-
function didKeyFromEd25519PublicKey2(publicKey) {
|
|
19408
|
-
if (publicKey.length !== 32) throw new Error("share key public key must be 32 bytes");
|
|
19409
|
-
const prefixed = new Uint8Array(34);
|
|
19410
|
-
prefixed.set([237, 1]);
|
|
19411
|
-
prefixed.set(publicKey, 2);
|
|
19412
|
-
return `did:key:${base58btc2.encode(prefixed)}`;
|
|
19413
|
-
}
|
|
19414
19707
|
function dagCborEncode(value) {
|
|
19415
19708
|
const output = [];
|
|
19416
19709
|
const writeHeader = (major, length32) => {
|
|
@@ -19480,52 +19773,6 @@ function assertObject(value, keys, label) {
|
|
|
19480
19773
|
if (Object.keys(record2).length !== keys.length || keys.some((key) => !Object.prototype.hasOwnProperty.call(record2, key))) throw new Error(`${label} has unknown or missing fields`);
|
|
19481
19774
|
return record2;
|
|
19482
19775
|
}
|
|
19483
|
-
async function createDelegatedShareKey(options) {
|
|
19484
|
-
if (!globalThis.crypto?.subtle) throw new Error("WebCrypto Ed25519 is required for delegated share keys");
|
|
19485
|
-
const generated = await crypto.subtle.generateKey({ name: "Ed25519" }, options.extractable, ["sign", "verify"]);
|
|
19486
|
-
const privateKey = generated.privateKey;
|
|
19487
|
-
const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", generated.publicKey));
|
|
19488
|
-
let cleared = false;
|
|
19489
|
-
const key = {
|
|
19490
|
-
did: didKeyFromEd25519PublicKey2(publicKey),
|
|
19491
|
-
publicKey: bytes(publicKey),
|
|
19492
|
-
extractable: options.extractable,
|
|
19493
|
-
cryptoKey: privateKey,
|
|
19494
|
-
async sign(input) {
|
|
19495
|
-
if (cleared) throw new Error("share key has been cleared");
|
|
19496
|
-
return new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, input));
|
|
19497
|
-
},
|
|
19498
|
-
clear() {
|
|
19499
|
-
cleared = true;
|
|
19500
|
-
}
|
|
19501
|
-
};
|
|
19502
|
-
return key;
|
|
19503
|
-
}
|
|
19504
|
-
async function createPolicyEnforcementDelegation(input) {
|
|
19505
|
-
if (input.shareKey.did.length === 0 || input.ownerDelegation.delegationCid.length === 0) throw new Error("owner delegation and share key are required");
|
|
19506
|
-
const facts = {
|
|
19507
|
-
ownerDelegationCid: input.ownerDelegation.delegationCid,
|
|
19508
|
-
policyCid: input.policyCid,
|
|
19509
|
-
shareId: input.shareId,
|
|
19510
|
-
shareKeyDid: input.shareKey.did,
|
|
19511
|
-
enforcerDid: input.enforcerDid,
|
|
19512
|
-
nodeAudience: input.nodeAudience,
|
|
19513
|
-
spaceId: input.spaceId,
|
|
19514
|
-
path: input.path,
|
|
19515
|
-
actions: [...input.actions],
|
|
19516
|
-
contentSourceDigest: input.contentSourceDigest,
|
|
19517
|
-
expiresAt: input.expiresAt
|
|
19518
|
-
};
|
|
19519
|
-
const unsigned = { type: "TinyCloudSharePolicyEnforcement", version: 2, issuerDid: input.shareKey.did, audienceDid: input.enforcerDid, facts };
|
|
19520
|
-
const dagCborBytes = dagCborEncode({ domain: POLICY_ENFORCEMENT_DOMAIN, unsigned });
|
|
19521
|
-
const signature = b64(await input.shareKey.sign(dagCborBytes));
|
|
19522
|
-
return { cid: cid(dagCborBytes), dagCbor: b64(dagCborBytes), issuerDid: input.shareKey.did, audienceDid: input.enforcerDid, facts, signature };
|
|
19523
|
-
}
|
|
19524
|
-
async function canonicalOwnerSharePolicy(policy) {
|
|
19525
|
-
const text = canonicalize2({ domain: POLICY_DOMAIN, policy });
|
|
19526
|
-
const policyBytes = new TextEncoder().encode(text);
|
|
19527
|
-
return { bytes: policyBytes, cid: cid(policyBytes), digest: digest(policyBytes) };
|
|
19528
|
-
}
|
|
19529
19776
|
function computeOwnerShareRegistrationCid(registration) {
|
|
19530
19777
|
return cid(new TextEncoder().encode(canonicalize2(registration)));
|
|
19531
19778
|
}
|
|
@@ -19566,357 +19813,19 @@ function validateOwnerSharePolicyRegistration(value, expected) {
|
|
|
19566
19813
|
if (signatureBytes.length !== 64 || !ed25519.verify(signatureBytes, signedBytes, publicKey)) throw new Error("owner-share registration proof signature is invalid");
|
|
19567
19814
|
return { registration, proof };
|
|
19568
19815
|
}
|
|
19569
|
-
function
|
|
19570
|
-
if (
|
|
19571
|
-
|
|
19572
|
-
if (
|
|
19573
|
-
return
|
|
19816
|
+
function record(value, keys, label) {
|
|
19817
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} is invalid`);
|
|
19818
|
+
const output = value;
|
|
19819
|
+
if (Object.keys(output).length !== keys.length || keys.some((key) => !Object.hasOwn(output, key))) throw new Error(`${label} has unknown or missing fields`);
|
|
19820
|
+
return output;
|
|
19574
19821
|
}
|
|
19575
|
-
function
|
|
19576
|
-
|
|
19822
|
+
function requiredString(value, label) {
|
|
19823
|
+
if (typeof value !== "string" || value.length === 0) throw new Error(`${label} is invalid`);
|
|
19824
|
+
return value;
|
|
19577
19825
|
}
|
|
19578
|
-
function
|
|
19579
|
-
|
|
19580
|
-
|
|
19581
|
-
function validRecipientDid(value) {
|
|
19582
|
-
if (value.length === 0 || value.length > 2048 || /[\u0000-\u0020\u007f]/.test(value)) return false;
|
|
19583
|
-
const parts = value.split(":");
|
|
19584
|
-
if (parts.length < 3 || parts[0] !== "did" || !/^[a-z0-9]+$/.test(parts[1] ?? "")) return false;
|
|
19585
|
-
const identifier = parts.slice(2);
|
|
19586
|
-
if (identifier.some((part) => part.length === 0)) return false;
|
|
19587
|
-
if (parts[1] === "web") {
|
|
19588
|
-
const host = identifier[0] ?? "";
|
|
19589
|
-
if (host.length > 253 || host.split(".").some((label) => !label || label.length > 63 || !/^[A-Za-z0-9-]+$/.test(label) || label.startsWith("-") || label.endsWith("-"))) return false;
|
|
19590
|
-
return identifier.slice(1).every((part) => /^[A-Za-z0-9._%-]+$/.test(part));
|
|
19591
|
-
}
|
|
19592
|
-
if (parts[1] === "pkh") return identifier.length >= 3 && identifier.every((part) => /^[A-Za-z0-9._%-]+$/.test(part));
|
|
19593
|
-
if (parts[1] === "key") {
|
|
19594
|
-
try {
|
|
19595
|
-
const bytes3 = base58btc2.decode(identifier.join(":"));
|
|
19596
|
-
return bytes3.length === 34 && bytes3[0] === 237 && bytes3[1] === 1;
|
|
19597
|
-
} catch {
|
|
19598
|
-
return false;
|
|
19599
|
-
}
|
|
19600
|
-
}
|
|
19601
|
-
return false;
|
|
19602
|
-
}
|
|
19603
|
-
function normalizeShareTarget(target) {
|
|
19604
|
-
if (target.kind === "bearer") return target;
|
|
19605
|
-
if (target.kind === "recipientDid") {
|
|
19606
|
-
if (!validRecipientDid(target.did)) throw new TypeError("recipient DID is invalid");
|
|
19607
|
-
return { kind: target.kind, did: target.did };
|
|
19608
|
-
}
|
|
19609
|
-
if (target.kind === "email") {
|
|
19610
|
-
if (!validEmail(target.address)) throw new TypeError("recipient email is invalid");
|
|
19611
|
-
const at = target.address.lastIndexOf("@");
|
|
19612
|
-
return { kind: target.kind, address: `${target.address.slice(0, at)}@${target.address.slice(at + 1).toLowerCase()}` };
|
|
19613
|
-
}
|
|
19614
|
-
if (!validDomain(target.domain)) throw new TypeError("recipient email domain is invalid");
|
|
19615
|
-
return { kind: target.kind, domain: target.domain.toLowerCase() };
|
|
19616
|
-
}
|
|
19617
|
-
function targetAuthorizationMethod(target) {
|
|
19618
|
-
return authorizationMethodForTarget(target);
|
|
19619
|
-
}
|
|
19620
|
-
async function publishTargetShare(input) {
|
|
19621
|
-
const target = normalizeShareTarget(input.target);
|
|
19622
|
-
if (target.kind === "bearer") return publishShare(input);
|
|
19623
|
-
if (input.targetAdapter === void 0) {
|
|
19624
|
-
return {
|
|
19625
|
-
state: "authorization-required",
|
|
19626
|
-
method: targetAuthorizationMethod(target)
|
|
19627
|
-
};
|
|
19628
|
-
}
|
|
19629
|
-
const source = input.source instanceof Uint8Array ? input.source.slice() : await (async () => {
|
|
19630
|
-
const chunks = [];
|
|
19631
|
-
let size2 = 0;
|
|
19632
|
-
for await (const chunk of input.source) {
|
|
19633
|
-
if (!(chunk instanceof Uint8Array)) throw new TypeError("addressed publication source yielded invalid bytes");
|
|
19634
|
-
size2 += chunk.byteLength;
|
|
19635
|
-
if (size2 > (input.maxBytes ?? 100 * 1024 * 1024)) throw new TypeError("addressed publication exceeds maxBytes");
|
|
19636
|
-
chunks.push(chunk.slice());
|
|
19637
|
-
}
|
|
19638
|
-
const bytes3 = new Uint8Array(size2);
|
|
19639
|
-
let offset = 0;
|
|
19640
|
-
for (const chunk of chunks) {
|
|
19641
|
-
bytes3.set(chunk, offset);
|
|
19642
|
-
offset += chunk.byteLength;
|
|
19643
|
-
}
|
|
19644
|
-
return bytes3;
|
|
19645
|
-
})();
|
|
19646
|
-
const files = input.files === void 0 || input.files.length === 0 ? [{ bytes: source }] : input.files;
|
|
19647
|
-
const limit = input.maxBytes ?? SHARE_CONTENT_LIMIT;
|
|
19648
|
-
let totalBytes = 0;
|
|
19649
|
-
for (const file of files) {
|
|
19650
|
-
totalBytes += file.bytes.byteLength;
|
|
19651
|
-
if (!Number.isSafeInteger(totalBytes) || totalBytes > limit) {
|
|
19652
|
-
throw new SharePublishError("max-bytes-exceeded", "addressed publication exceeds the combined byte limit");
|
|
19653
|
-
}
|
|
19654
|
-
}
|
|
19655
|
-
return input.targetAdapter.publish({
|
|
19656
|
-
source,
|
|
19657
|
-
filename: input.filename,
|
|
19658
|
-
...input.files === void 0 ? {} : { files: input.files },
|
|
19659
|
-
...input.mediaType === void 0 ? {} : { mediaType: input.mediaType },
|
|
19660
|
-
...input.resourceKind === void 0 ? {} : { resourceKind: input.resourceKind },
|
|
19661
|
-
...input.actions === void 0 ? {} : { actions: input.actions },
|
|
19662
|
-
target,
|
|
19663
|
-
expiresAt: input.expiresAt ?? new Date((input.now?.() ?? Date.now()) + 7 * 24 * 60 * 60 * 1e3),
|
|
19664
|
-
origin: input.origin,
|
|
19665
|
-
...input.inline === void 0 ? {} : { inline: input.inline },
|
|
19666
|
-
upload: {
|
|
19667
|
-
...input.registryBaseUrl === void 0 ? {} : { registryBaseUrl: input.registryBaseUrl },
|
|
19668
|
-
...input.fetchFn === void 0 ? {} : { fetchFn: input.fetchFn },
|
|
19669
|
-
...input.authorizeUpload === void 0 ? {} : { authorizeUpload: input.authorizeUpload },
|
|
19670
|
-
...input.authorizationOrigin === void 0 ? {} : { authorizationOrigin: input.authorizationOrigin },
|
|
19671
|
-
...input.credentials === void 0 ? {} : { credentials: input.credentials },
|
|
19672
|
-
...input.allowInsecureRegistry === void 0 ? {} : { allowInsecureRegistry: input.allowInsecureRegistry },
|
|
19673
|
-
...input.uploadBlob === void 0 ? {} : { uploadBlob: input.uploadBlob }
|
|
19674
|
-
},
|
|
19675
|
-
...input.notify === void 0 ? {} : { notify: input.notify }
|
|
19676
|
-
});
|
|
19677
|
-
}
|
|
19678
|
-
function targetMatcher(target) {
|
|
19679
|
-
if (target.kind === "recipientDid") return { kind: "recipientDid", value: target.did };
|
|
19680
|
-
if (target.kind === "email") return { kind: "exactEmail", value: target.address };
|
|
19681
|
-
return { kind: "emailDomain", value: target.domain };
|
|
19682
|
-
}
|
|
19683
|
-
function targetKind(target) {
|
|
19684
|
-
return target.kind;
|
|
19685
|
-
}
|
|
19686
|
-
function assertSafeInput(input) {
|
|
19687
|
-
if (!/^[A-Za-z0-9_-]{16,128}$/.test(input.shareId)) throw new TypeError("addressed share id is invalid");
|
|
19688
|
-
if (input.filename.length === 0 || input.filename === "." || input.filename === ".." || /[/\\\u0000-\u001f\u007f]/.test(input.filename)) throw new TypeError("addressed filename is invalid");
|
|
19689
|
-
if (!Number.isSafeInteger(input.byteLength) || input.byteLength < 0 || input.byteLength > SHARE_CONTENT_LIMIT) throw new TypeError("addressed content length is invalid");
|
|
19690
|
-
if (input.actions.length === 0 || input.policyActions.length === 0) throw new TypeError("addressed share actions are empty");
|
|
19691
|
-
const expiry = input.expiresAt.getTime();
|
|
19692
|
-
if (!Number.isFinite(expiry) || expiry <= Date.now()) throw new TypeError("addressed share expiry must be in the future");
|
|
19693
|
-
if (input.artifact === "html" && (input.resource.kind !== "prefix" || !input.actions.includes("read") || !input.actions.includes("list"))) throw new TypeError("html artifacts require a readable prefix");
|
|
19694
|
-
if (input.contentSource.kind !== "kv") throw new TypeError("addressed policy publication requires a KV content source");
|
|
19695
|
-
}
|
|
19696
|
-
async function sha2564(value) {
|
|
19697
|
-
return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", value)));
|
|
19698
|
-
}
|
|
19699
|
-
function publicationResult(input) {
|
|
19700
|
-
const result = {
|
|
19701
|
-
protocol: "tinycloud-share",
|
|
19702
|
-
version: SHARE_PUBLISH_RESULT_VERSION,
|
|
19703
|
-
url: input.url,
|
|
19704
|
-
link: { kind: input.options.inline === true ? "inline" : "compact", cid: input.envelopeCid },
|
|
19705
|
-
metadata: {
|
|
19706
|
-
protocol: "tinycloud-share",
|
|
19707
|
-
version: 1,
|
|
19708
|
-
shareId: input.options.shareId,
|
|
19709
|
-
origin: input.options.shareOrigin,
|
|
19710
|
-
target: {
|
|
19711
|
-
kind: targetKind(input.options.target),
|
|
19712
|
-
origin: input.options.nodeOrigin,
|
|
19713
|
-
nodeAudience: input.options.nodeAudience,
|
|
19714
|
-
spaceId: input.options.spaceId
|
|
19715
|
-
},
|
|
19716
|
-
resource: { ...input.options.resource },
|
|
19717
|
-
actions: [...input.options.actions],
|
|
19718
|
-
expiresAt: input.options.expiresAt.toISOString(),
|
|
19719
|
-
display: { filename: input.options.filename },
|
|
19720
|
-
recipientMatcher: { ...input.matcher },
|
|
19721
|
-
registrationCid: input.registration.registrationCid,
|
|
19722
|
-
policyCid: input.policyCid,
|
|
19723
|
-
ownerDelegationCid: input.registration.ownerDelegationCid,
|
|
19724
|
-
enforcementDelegationCid: input.enforcementDelegationCid,
|
|
19725
|
-
ownerDid: input.registration.ownerDid,
|
|
19726
|
-
shareKeyDid: input.shareKeyDid,
|
|
19727
|
-
enforcerDid: input.registration.enforcerDid,
|
|
19728
|
-
envelopeCid: input.envelopeCid,
|
|
19729
|
-
shareCid: input.shareCid
|
|
19730
|
-
},
|
|
19731
|
-
registryDeleteAfter: input.retention
|
|
19732
|
-
};
|
|
19733
|
-
Object.defineProperty(result, "toJSON", { enumerable: false, value: () => redactPublishedShare(result) });
|
|
19734
|
-
Object.defineProperty(result, "url", { enumerable: false, value: input.url });
|
|
19735
|
-
return result;
|
|
19736
|
-
}
|
|
19737
|
-
async function publishAddressedShare(options) {
|
|
19738
|
-
assertSafeInput(options);
|
|
19739
|
-
const target = normalizeShareTarget(options.target);
|
|
19740
|
-
if (target.kind === "bearer") throw new TypeError("addressed target is required");
|
|
19741
|
-
if (options.contentSource.kind !== "kv") throw new TypeError("addressed policy publication requires a KV content source");
|
|
19742
|
-
const contentSource = options.contentSource;
|
|
19743
|
-
const matcher = targetMatcher(target);
|
|
19744
|
-
const expiresAt = options.expiresAt.toISOString();
|
|
19745
|
-
const contentSourceDigest = options.contentSourceDigest ?? await sha2564(new TextEncoder().encode(canonicalize2(contentSource)));
|
|
19746
|
-
const shareKey = await createDelegatedShareKey({ extractable: false });
|
|
19747
|
-
let envelopeKey;
|
|
19748
|
-
try {
|
|
19749
|
-
const permissions = [
|
|
19750
|
-
{
|
|
19751
|
-
service: "tinycloud.kv",
|
|
19752
|
-
path: options.resource.kind === "prefix" ? `${options.resource.path.replace(/\/+$/, "")}/` : options.resource.path,
|
|
19753
|
-
actions: [...options.policyActions]
|
|
19754
|
-
},
|
|
19755
|
-
...options.decryption === void 0 ? [] : [{
|
|
19756
|
-
service: "tinycloud.encryption",
|
|
19757
|
-
path: options.decryption.networkId,
|
|
19758
|
-
actions: [options.decryption.action]
|
|
19759
|
-
}]
|
|
19760
|
-
];
|
|
19761
|
-
const ownerDelegation = await options.authority.createOwnerDelegation({
|
|
19762
|
-
delegateDid: shareKey.did,
|
|
19763
|
-
spaceId: options.spaceId,
|
|
19764
|
-
permissions,
|
|
19765
|
-
expiresAt: options.expiresAt
|
|
19766
|
-
});
|
|
19767
|
-
const policy = {
|
|
19768
|
-
type: "TinyCloudSharePolicy",
|
|
19769
|
-
version: 2,
|
|
19770
|
-
shareId: options.shareId,
|
|
19771
|
-
ownerDid: options.authority.ownerDid,
|
|
19772
|
-
shareKeyDid: shareKey.did,
|
|
19773
|
-
recipientMatcher: matcher,
|
|
19774
|
-
target: {
|
|
19775
|
-
origin: options.nodeOrigin,
|
|
19776
|
-
nodeAudience: options.nodeAudience,
|
|
19777
|
-
enforcerDid: options.enforcerDid,
|
|
19778
|
-
spaceId: options.spaceId
|
|
19779
|
-
},
|
|
19780
|
-
resource: { ...options.resource },
|
|
19781
|
-
actions: [...options.policyActions],
|
|
19782
|
-
...options.decryption === void 0 ? {} : { decryption: options.decryption },
|
|
19783
|
-
contentSource,
|
|
19784
|
-
contentSourceDigest,
|
|
19785
|
-
ownerDelegationCid: ownerDelegation.delegationCid,
|
|
19786
|
-
expiresAt
|
|
19787
|
-
};
|
|
19788
|
-
const canonicalPolicy = await canonicalOwnerSharePolicy(policy);
|
|
19789
|
-
const policyProof = toBase64Url(await shareKey.sign(canonicalPolicy.bytes));
|
|
19790
|
-
const enforcementDelegation = await createPolicyEnforcementDelegation({
|
|
19791
|
-
ownerDelegation,
|
|
19792
|
-
shareKey,
|
|
19793
|
-
enforcerDid: options.enforcerDid,
|
|
19794
|
-
policyCid: canonicalPolicy.cid,
|
|
19795
|
-
shareId: options.shareId,
|
|
19796
|
-
spaceId: options.spaceId,
|
|
19797
|
-
nodeAudience: options.nodeAudience,
|
|
19798
|
-
path: options.resource.path,
|
|
19799
|
-
actions: options.policyActions,
|
|
19800
|
-
contentSourceDigest,
|
|
19801
|
-
expiresAt
|
|
19802
|
-
});
|
|
19803
|
-
const registration = await options.authority.registerOwnerSharePolicy({
|
|
19804
|
-
policy: { bytes: canonicalPolicy.bytes, cid: canonicalPolicy.cid, proof: policyProof },
|
|
19805
|
-
ownerDelegation,
|
|
19806
|
-
enforcementDelegation,
|
|
19807
|
-
contentSourceDigest
|
|
19808
|
-
});
|
|
19809
|
-
const authorityMaterialDigest = await sha2564(fromBase64Url(enforcementDelegation.dagCbor));
|
|
19810
|
-
const authorityTarget = {
|
|
19811
|
-
origin: options.nodeOrigin,
|
|
19812
|
-
nodeAudience: options.nodeAudience,
|
|
19813
|
-
enforcerDid: options.enforcerDid,
|
|
19814
|
-
spaceId: options.spaceId
|
|
19815
|
-
};
|
|
19816
|
-
const envelopeIdentity = {
|
|
19817
|
-
schema: "xyz.tinycloud.share/envelope/v2",
|
|
19818
|
-
version: 2,
|
|
19819
|
-
shareId: options.shareId,
|
|
19820
|
-
delegationCid: ownerDelegation.delegationCid,
|
|
19821
|
-
policyCid: canonicalPolicy.cid,
|
|
19822
|
-
target: authorityTarget,
|
|
19823
|
-
resource: options.resource,
|
|
19824
|
-
actions: options.policyActions,
|
|
19825
|
-
...options.decryption === void 0 ? {} : { decryption: options.decryption },
|
|
19826
|
-
contentSource,
|
|
19827
|
-
contentSourceDigest,
|
|
19828
|
-
expiresAt
|
|
19829
|
-
};
|
|
19830
|
-
const envelopeCid = await computeCid(new TextEncoder().encode(canonicalize2(envelopeIdentity)));
|
|
19831
|
-
const shareCid = await computeCid(new TextEncoder().encode(canonicalize2({ version: 2, shareId: options.shareId, policyCid: canonicalPolicy.cid, envelopeCid })));
|
|
19832
|
-
const outerUnsigned = { ...envelopeIdentity, envelopeCid, shareCid };
|
|
19833
|
-
const outerSignature = toBase64Url(await shareKey.sign(new TextEncoder().encode(`${ENVELOPE_DOMAIN}${canonicalize2(outerUnsigned)}`)));
|
|
19834
|
-
const unsigned = {
|
|
19835
|
-
version: 2,
|
|
19836
|
-
shareId: options.shareId,
|
|
19837
|
-
recipientMatcher: matcher,
|
|
19838
|
-
...options.deliveryEmail === void 0 ? {} : { deliveryEmail: options.deliveryEmail },
|
|
19839
|
-
actions: [...options.actions],
|
|
19840
|
-
resource: { ...options.resource },
|
|
19841
|
-
target: { origin: options.nodeOrigin, nodeAudience: options.nodeAudience, spaceId: options.spaceId },
|
|
19842
|
-
delegationCid: ownerDelegation.delegationCid,
|
|
19843
|
-
authorityMaterialHandle: registration.registration.registrationCid,
|
|
19844
|
-
authorityMaterialDigest,
|
|
19845
|
-
contentSource,
|
|
19846
|
-
contentSourceDigest,
|
|
19847
|
-
authorizationTarget: { kind: "policy", policyCid: canonicalPolicy.cid, policyBytes: toBase64Url(canonicalPolicy.bytes) },
|
|
19848
|
-
display: { filename: options.filename },
|
|
19849
|
-
expiry: expiresAt,
|
|
19850
|
-
encrypted: true,
|
|
19851
|
-
metadata: {
|
|
19852
|
-
mediaType: options.mediaType,
|
|
19853
|
-
byteLength: options.byteLength,
|
|
19854
|
-
filename: options.filename,
|
|
19855
|
-
...options.mediaType.startsWith("text/") ? { encoding: "utf-8" } : {},
|
|
19856
|
-
...options.artifact === void 0 ? {} : { artifact: options.artifact }
|
|
19857
|
-
},
|
|
19858
|
-
ownerAuthority: {
|
|
19859
|
-
registrationCid: registration.registration.registrationCid,
|
|
19860
|
-
shareCid,
|
|
19861
|
-
envelopeCid,
|
|
19862
|
-
enforcementDelegation,
|
|
19863
|
-
registrationReceipt: registration,
|
|
19864
|
-
outerEnvelope: {
|
|
19865
|
-
...outerUnsigned,
|
|
19866
|
-
signature: { signerDid: shareKey.did, algorithm: "Ed25519", value: outerSignature }
|
|
19867
|
-
}
|
|
19868
|
-
}
|
|
19869
|
-
};
|
|
19870
|
-
unsignedShareEnvelopeV2Schema.parse(unsigned);
|
|
19871
|
-
const envelopeSignature = toBase64Url(await shareKey.sign(new TextEncoder().encode(`${ENVELOPE_DOMAIN}${canonicalize2(unsigned)}`)));
|
|
19872
|
-
const envelope = { ...unsigned, signature: { signerDid: shareKey.did, algorithm: "Ed25519", value: envelopeSignature } };
|
|
19873
|
-
shareEnvelopeV2Schema.parse(envelope);
|
|
19874
|
-
envelopeKey = generateKey();
|
|
19875
|
-
const sealed = await seal(new TextEncoder().encode(canonicalize2(envelope)), envelopeKey);
|
|
19876
|
-
let url;
|
|
19877
|
-
let retention = expiresAt;
|
|
19878
|
-
if (options.inline === true) {
|
|
19879
|
-
url = await encodeInlineShareUrl({ origin: options.shareOrigin, ciphertext: sealed.blob, key32: envelopeKey });
|
|
19880
|
-
} else {
|
|
19881
|
-
const uploaded = await uploadShareBlob({
|
|
19882
|
-
source: new Uint8Array([1]),
|
|
19883
|
-
filename: options.filename,
|
|
19884
|
-
origin: options.shareOrigin,
|
|
19885
|
-
...options.upload
|
|
19886
|
-
}, { blob: sealed.blob, cid: sealed.cid, deleteAfter: expiresAt, contentLength: sealed.blob.byteLength });
|
|
19887
|
-
retention = uploaded.deleteAfter;
|
|
19888
|
-
url = encodeShareUrl({ origin: options.shareOrigin, ciphertextCid: uploaded.cid, key32: envelopeKey });
|
|
19889
|
-
}
|
|
19890
|
-
return publicationResult({
|
|
19891
|
-
options,
|
|
19892
|
-
url,
|
|
19893
|
-
envelopeCid: sealed.cid,
|
|
19894
|
-
shareCid,
|
|
19895
|
-
matcher,
|
|
19896
|
-
registration: registration.registration,
|
|
19897
|
-
policyCid: canonicalPolicy.cid,
|
|
19898
|
-
enforcementDelegationCid: enforcementDelegation.cid,
|
|
19899
|
-
shareKeyDid: shareKey.did,
|
|
19900
|
-
retention
|
|
19901
|
-
});
|
|
19902
|
-
} finally {
|
|
19903
|
-
shareKey.clear();
|
|
19904
|
-
envelopeKey?.fill(0);
|
|
19905
|
-
}
|
|
19906
|
-
}
|
|
19907
|
-
function record(value, keys, label) {
|
|
19908
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} is invalid`);
|
|
19909
|
-
const output = value;
|
|
19910
|
-
if (Object.keys(output).length !== keys.length || keys.some((key) => !Object.hasOwn(output, key))) throw new Error(`${label} has unknown or missing fields`);
|
|
19911
|
-
return output;
|
|
19912
|
-
}
|
|
19913
|
-
function requiredString(value, label) {
|
|
19914
|
-
if (typeof value !== "string" || value.length === 0) throw new Error(`${label} is invalid`);
|
|
19915
|
-
return value;
|
|
19916
|
-
}
|
|
19917
|
-
function stringArray(value, label) {
|
|
19918
|
-
if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string" && item.length > 0)) throw new Error(`${label} is invalid`);
|
|
19919
|
-
return value;
|
|
19826
|
+
function stringArray(value, label) {
|
|
19827
|
+
if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string" && item.length > 0)) throw new Error(`${label} is invalid`);
|
|
19828
|
+
return value;
|
|
19920
19829
|
}
|
|
19921
19830
|
function parseEnforcement(value) {
|
|
19922
19831
|
const delegation = record(value, ["cid", "dagCbor", "issuerDid", "audienceDid", "facts", "signature"], "policy enforcement delegation");
|
|
@@ -19984,7 +19893,7 @@ async function verifyOuterEnvelope(value, envelope, policyCid, expectedEnforcerD
|
|
|
19984
19893
|
const signatureBytes = fromBase64Url(requiredString(signature.value, "outer signature"));
|
|
19985
19894
|
if (signatureBytes.length !== 64 || !ed25519.verify(
|
|
19986
19895
|
signatureBytes,
|
|
19987
|
-
new TextEncoder().encode(`${
|
|
19896
|
+
new TextEncoder().encode(`${ENVELOPE_DOMAIN}${canonicalize2(unsigned)}`),
|
|
19988
19897
|
ed25519PublicKeyFromDidKey(envelope.signature.signerDid),
|
|
19989
19898
|
{ zip215: false }
|
|
19990
19899
|
)) return void 0;
|
|
@@ -20077,6 +19986,7 @@ function historyRecordForPublishedShare(result, now = /* @__PURE__ */ new Date()
|
|
|
20077
19986
|
registeredAt: now.toISOString(),
|
|
20078
19987
|
expiresAt: result.metadata.expiresAt,
|
|
20079
19988
|
link: result.url,
|
|
19989
|
+
...result.deliveryMaterial === void 0 ? {} : { deliveryMaterial: result.deliveryMaterial },
|
|
20080
19990
|
...result.metadata.display.filename === void 0 ? {} : { filename: result.metadata.display.filename }
|
|
20081
19991
|
};
|
|
20082
19992
|
}
|
|
@@ -20112,11 +20022,11 @@ async function notifyShare(input) {
|
|
|
20112
20022
|
}
|
|
20113
20023
|
async function defaultIdempotencyKey(shareId, recipient) {
|
|
20114
20024
|
const canonicalRecipient = canonicalize2(recipient.trim().toLowerCase());
|
|
20115
|
-
const
|
|
20025
|
+
const digest3 = new Uint8Array(await crypto.subtle.digest(
|
|
20116
20026
|
"SHA-256",
|
|
20117
20027
|
new TextEncoder().encode(canonicalRecipient)
|
|
20118
20028
|
));
|
|
20119
|
-
return `tinycloud-share:${shareId}:${toBase64Url(
|
|
20029
|
+
return `tinycloud-share:${shareId}:${toBase64Url(digest3)}`;
|
|
20120
20030
|
}
|
|
20121
20031
|
function targetKind2(record2) {
|
|
20122
20032
|
if (record2.targetKind !== void 0) return record2.targetKind;
|
|
@@ -20237,12 +20147,6 @@ function fromBase64(value, label) {
|
|
|
20237
20147
|
if (toBase64(out) !== value) throw new Error(`${label} is invalid`);
|
|
20238
20148
|
return out;
|
|
20239
20149
|
}
|
|
20240
|
-
async function digest3(value) {
|
|
20241
|
-
return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalize2(value)))));
|
|
20242
|
-
}
|
|
20243
|
-
async function digestText2(value) {
|
|
20244
|
-
return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))));
|
|
20245
|
-
}
|
|
20246
20150
|
async function digestBytes2(value) {
|
|
20247
20151
|
return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", value)));
|
|
20248
20152
|
}
|
|
@@ -20252,24 +20156,9 @@ function trustedPublicKey(value) {
|
|
|
20252
20156
|
}
|
|
20253
20157
|
return value.invitationPublicKey;
|
|
20254
20158
|
}
|
|
20255
|
-
async function verifyWrapped(value, key, domain, trust) {
|
|
20256
|
-
const wrapper = object2(value, `${key} response`);
|
|
20257
|
-
if (Object.keys(wrapper).length !== 2 || !Object.hasOwn(wrapper, key) || !Object.hasOwn(wrapper, "proof")) throw new Error(`${key} response is invalid`);
|
|
20258
|
-
const artifact = object2(wrapper[key], `${key} artifact`);
|
|
20259
|
-
const proof = object2(wrapper.proof, `${key} proof`);
|
|
20260
|
-
if (proof.alg !== "EdDSA" || proof.kid !== trust.invitationKid) throw new Error(`${key} proof is invalid`);
|
|
20261
|
-
if (!ed25519.verify(bytes2(proof.signature, `${key} signature`), new TextEncoder().encode(`${domain}${canonicalize2(artifact)}`), trustedPublicKey(trust))) throw new Error(`${key} proof is invalid`);
|
|
20262
|
-
return artifact;
|
|
20263
|
-
}
|
|
20264
20159
|
function nativeAction(action) {
|
|
20265
20160
|
return action === "list" ? "tinycloud.kv/list" : action === "edit" ? "tinycloud.kv/put" : "tinycloud.kv/get";
|
|
20266
20161
|
}
|
|
20267
|
-
function uiAction(action) {
|
|
20268
|
-
return action === "tinycloud.kv/list" ? "list" : action === "tinycloud.kv/put" ? "edit" : "read";
|
|
20269
|
-
}
|
|
20270
|
-
function selectedAction(envelope) {
|
|
20271
|
-
return envelope.actions.includes("list") ? "tinycloud.kv/list" : envelope.actions.includes("edit") ? "tinycloud.kv/put" : "tinycloud.kv/get";
|
|
20272
|
-
}
|
|
20273
20162
|
function policyAttenuationForV3(envelope) {
|
|
20274
20163
|
const policy = object2(envelope.policy, "v3 policy");
|
|
20275
20164
|
if (!Array.isArray(policy.capabilityCeiling)) throw new Error("v3 policy capability ceiling is invalid");
|
|
@@ -20303,11 +20192,11 @@ function verifyV3PolicyAuthorization(input) {
|
|
|
20303
20192
|
if (!legacyShape && !v4Shape || POLICY_SESSION_DIGEST_FACT_KEYS.some((key) => !LOWER_SHA256_HEX.test(fact[key])) || v4Shape && (!LOWER_SHA256_HEX.test(fact.credentialIdAuditDigestHex) || !LOWER_SHA256_HEX.test(fact.presentationJtiAuditDigestHex)) || compact.payload.aud !== input.holderDid || compact.payload.iss.split("#", 1)[0] !== fact.nodeAudience || fact.profile !== "policy-session-ucan/v1" || fact.ownerDid !== policy.ownerDid || fact.policyId !== policy.policyId || fact.policyCid !== input.envelope.policyCid || fact.contentSourceDigestHex !== input.envelope.contentSourceDigestHex || fact.enforcerDid !== binding.enforcerDid || fact.nodeAudience !== binding.nodeAudience || fact.recipientDid !== input.holderDid || fact.policyDelegationCid !== input.envelope.policyRoot.cid || fact.enforcementDelegationCid !== input.envelope.enforcementRoot.cid || typeof fact.remainingRedelegationDepth !== "number" || !Number.isInteger(fact.remainingRedelegationDepth) || fact.remainingRedelegationDepth < 0 || fact.remainingRedelegationDepth > 8 || compact.payload.prf.length !== 2 || compact.payload.prf[0] !== input.envelope.policyRoot.cid || compact.payload.prf[1] !== input.envelope.enforcementRoot.cid || compact.payload.nbf > now || compact.payload.exp <= now || compact.payload.exp - compact.payload.nbf > 60 || canonicalize2(compact.payload.att) !== canonicalize2(policyAttenuationForV3(input.envelope))) throw new Error("v3 policy delegation signed binding mismatch");
|
|
20304
20193
|
return compact;
|
|
20305
20194
|
}
|
|
20306
|
-
function
|
|
20195
|
+
function hex3(value) {
|
|
20307
20196
|
return [...value].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
20308
20197
|
}
|
|
20309
20198
|
function canonicalHashHex2(value) {
|
|
20310
|
-
return
|
|
20199
|
+
return hex3(sha2562(new TextEncoder().encode(canonicalize2(value))));
|
|
20311
20200
|
}
|
|
20312
20201
|
async function aesGcmDecrypt(key, blob) {
|
|
20313
20202
|
if (key.length !== 32 || blob.length < 28) throw new Error("encrypted content is malformed");
|
|
@@ -20339,25 +20228,6 @@ function parseV3InlineEncryptedEnvelope(bytes3, expected) {
|
|
|
20339
20228
|
}
|
|
20340
20229
|
return record2;
|
|
20341
20230
|
}
|
|
20342
|
-
async function verifyDetachedResponse(response, trust) {
|
|
20343
|
-
let value;
|
|
20344
|
-
try {
|
|
20345
|
-
value = await response.clone().json();
|
|
20346
|
-
} catch {
|
|
20347
|
-
throw new Error("share read response is invalid");
|
|
20348
|
-
}
|
|
20349
|
-
const record2 = object2(value, "share read response");
|
|
20350
|
-
const proof = object2(record2.proof, "share read detached proof");
|
|
20351
|
-
if (proof.alg !== "EdDSA" || proof.kid !== trust.invitationKid) throw new Error("share read detached proof is invalid");
|
|
20352
|
-
const unsigned = { ...record2 };
|
|
20353
|
-
delete unsigned.proof;
|
|
20354
|
-
if (!ed25519.verify(bytes2(proof.signature, "share read signature"), new TextEncoder().encode(`${SHARE_V2_PROTOCOL.readResponseDomain}${canonicalize2(unsigned)}`), trustedPublicKey(trust))) throw new Error("share read detached proof is invalid");
|
|
20355
|
-
}
|
|
20356
|
-
async function post(fetchFn, origin, path, body) {
|
|
20357
|
-
const response = await fetchFn(new URL(path, origin), { method: "POST", redirect: "error", headers: { accept: "application/json", "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
20358
|
-
if (!response.ok) throw new Error("share authority rejected the request");
|
|
20359
|
-
return response.json();
|
|
20360
|
-
}
|
|
20361
20231
|
function createAddressedAuthorization(input) {
|
|
20362
20232
|
const { buildPresentation, ...options } = input;
|
|
20363
20233
|
const client = (envelope) => new ShareRecipientClient({
|
|
@@ -20393,7 +20263,7 @@ function createAddressedAuthorization(input) {
|
|
|
20393
20263
|
}
|
|
20394
20264
|
};
|
|
20395
20265
|
}
|
|
20396
|
-
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,
|
|
20266
|
+
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, base58btc2, base58flickr2, POLICY_V1_DOMAIN, POLICY_V2_DOMAIN, POLICY_CAPABILITY_V1_DOMAIN2, CONTENT_SOURCE_V1_DOMAIN2, NATIVE_PROJECTION_V1_DOMAIN2, ENVELOPE_V3_DOMAIN, textEncoder, base322, base32upper2, base32pad2, base32padupper2, base32hex2, base32hexupper2, base32hexpad2, base32hexpadupper2, base32z2, base362, base36upper2, 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, OWNER_SHARE_REGISTRATION_DOMAIN, ENVELOPE_DOMAIN, ShareNotifyError, SHARE_V2_PROTOCOL, DOMAIN, PRESENTATION_DOMAIN, SESSION_DOMAIN, INVOCATION_DOMAIN, BASE64_ALPHABET, POLICY_SESSION_FACT_KEYS, POLICY_SESSION_V4_AUDIT_FACT_KEYS, POLICY_SESSION_DIGEST_FACT_KEYS, LOWER_SHA256_HEX, ShareRecipientClient;
|
|
20397
20267
|
var init_dist3 = __esm({
|
|
20398
20268
|
"../share-sdk/dist/index.js"() {
|
|
20399
20269
|
"use strict";
|
|
@@ -20404,11 +20274,12 @@ var init_dist3 = __esm({
|
|
|
20404
20274
|
init_ed25519();
|
|
20405
20275
|
init_sha256();
|
|
20406
20276
|
init_ed25519();
|
|
20407
|
-
init_ed25519();
|
|
20408
20277
|
init_sha256();
|
|
20409
20278
|
init_ed25519();
|
|
20410
20279
|
init_ed25519();
|
|
20411
20280
|
init_sha256();
|
|
20281
|
+
init_ed25519();
|
|
20282
|
+
init_sha256();
|
|
20412
20283
|
__defProp2 = Object.defineProperty;
|
|
20413
20284
|
__export2 = (target, all) => {
|
|
20414
20285
|
for (var name2 in all)
|
|
@@ -24417,10 +24288,10 @@ var init_dist3 = __esm({
|
|
|
24417
24288
|
/**
|
|
24418
24289
|
* Creates a multihash digest.
|
|
24419
24290
|
*/
|
|
24420
|
-
constructor(code222, size2,
|
|
24291
|
+
constructor(code222, size2, digest3, bytes3) {
|
|
24421
24292
|
this.code = code222;
|
|
24422
24293
|
this.size = size2;
|
|
24423
|
-
this.digest =
|
|
24294
|
+
this.digest = digest3;
|
|
24424
24295
|
this.bytes = bytes3;
|
|
24425
24296
|
}
|
|
24426
24297
|
};
|
|
@@ -24483,8 +24354,8 @@ var init_dist3 = __esm({
|
|
|
24483
24354
|
toV1() {
|
|
24484
24355
|
switch (this.version) {
|
|
24485
24356
|
case 0: {
|
|
24486
|
-
const { code: code222, digest:
|
|
24487
|
-
const multihash = create(code222,
|
|
24357
|
+
const { code: code222, digest: digest3 } = this.multihash;
|
|
24358
|
+
const multihash = create(code222, digest3);
|
|
24488
24359
|
return _CID.createV1(this.code, multihash);
|
|
24489
24360
|
}
|
|
24490
24361
|
case 1: {
|
|
@@ -24538,8 +24409,8 @@ var init_dist3 = __esm({
|
|
|
24538
24409
|
return new _CID(version3, code222, multihash, bytes3 ?? encodeCID(version3, code222, multihash.bytes));
|
|
24539
24410
|
} else if (value[cidSymbol] === true) {
|
|
24540
24411
|
const { version: version3, multihash, code: code222 } = value;
|
|
24541
|
-
const
|
|
24542
|
-
return _CID.create(version3, code222,
|
|
24412
|
+
const digest3 = decode4(multihash);
|
|
24413
|
+
return _CID.create(version3, code222, digest3);
|
|
24543
24414
|
} else {
|
|
24544
24415
|
return null;
|
|
24545
24416
|
}
|
|
@@ -24549,11 +24420,11 @@ var init_dist3 = __esm({
|
|
|
24549
24420
|
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
|
|
24550
24421
|
* @param digest - (Multi)hash of the of the content.
|
|
24551
24422
|
*/
|
|
24552
|
-
static create(version3, code222,
|
|
24423
|
+
static create(version3, code222, digest3) {
|
|
24553
24424
|
if (typeof code222 !== "number") {
|
|
24554
24425
|
throw new Error("String codecs are no longer supported");
|
|
24555
24426
|
}
|
|
24556
|
-
if (!(
|
|
24427
|
+
if (!(digest3.bytes instanceof Uint8Array)) {
|
|
24557
24428
|
throw new Error("Invalid digest");
|
|
24558
24429
|
}
|
|
24559
24430
|
switch (version3) {
|
|
@@ -24561,12 +24432,12 @@ var init_dist3 = __esm({
|
|
|
24561
24432
|
if (code222 !== DAG_PB_CODE) {
|
|
24562
24433
|
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
|
|
24563
24434
|
} else {
|
|
24564
|
-
return new _CID(version3, code222,
|
|
24435
|
+
return new _CID(version3, code222, digest3, digest3.bytes);
|
|
24565
24436
|
}
|
|
24566
24437
|
}
|
|
24567
24438
|
case 1: {
|
|
24568
|
-
const bytes3 = encodeCID(version3, code222,
|
|
24569
|
-
return new _CID(version3, code222,
|
|
24439
|
+
const bytes3 = encodeCID(version3, code222, digest3.bytes);
|
|
24440
|
+
return new _CID(version3, code222, digest3, bytes3);
|
|
24570
24441
|
}
|
|
24571
24442
|
default: {
|
|
24572
24443
|
throw new Error("Invalid version");
|
|
@@ -24576,8 +24447,8 @@ var init_dist3 = __esm({
|
|
|
24576
24447
|
/**
|
|
24577
24448
|
* Simplified version of `create` for CIDv0.
|
|
24578
24449
|
*/
|
|
24579
|
-
static createV0(
|
|
24580
|
-
return _CID.create(0, DAG_PB_CODE,
|
|
24450
|
+
static createV0(digest3) {
|
|
24451
|
+
return _CID.create(0, DAG_PB_CODE, digest3);
|
|
24581
24452
|
}
|
|
24582
24453
|
/**
|
|
24583
24454
|
* Simplified version of `create` for CIDv1.
|
|
@@ -24585,8 +24456,8 @@ var init_dist3 = __esm({
|
|
|
24585
24456
|
* @param code - Content encoding format code.
|
|
24586
24457
|
* @param digest - Multihash of the content.
|
|
24587
24458
|
*/
|
|
24588
|
-
static createV1(code222,
|
|
24589
|
-
return _CID.create(1, code222,
|
|
24459
|
+
static createV1(code222, digest3) {
|
|
24460
|
+
return _CID.create(1, code222, digest3);
|
|
24590
24461
|
}
|
|
24591
24462
|
/**
|
|
24592
24463
|
* Decoded a CID from its binary representation. The byte array must contain
|
|
@@ -24619,8 +24490,8 @@ var init_dist3 = __esm({
|
|
|
24619
24490
|
throw new Error("Incorrect length");
|
|
24620
24491
|
}
|
|
24621
24492
|
const digestBytes3 = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
|
|
24622
|
-
const
|
|
24623
|
-
const cid2 = specs.version === 0 ? _CID.createV0(
|
|
24493
|
+
const digest3 = new Digest(specs.multihashCode, specs.digestSize, digestBytes3, multihashBytes);
|
|
24494
|
+
const cid2 = specs.version === 0 ? _CID.createV0(digest3) : _CID.createV1(specs.codec, digest3);
|
|
24624
24495
|
return [cid2, bytes3.subarray(specs.size)];
|
|
24625
24496
|
}
|
|
24626
24497
|
/**
|
|
@@ -25158,6 +25029,23 @@ var init_dist3 = __esm({
|
|
|
25158
25029
|
return this.decoder.decode(input);
|
|
25159
25030
|
}
|
|
25160
25031
|
};
|
|
25032
|
+
base58btc2 = baseX2({
|
|
25033
|
+
name: "base58btc",
|
|
25034
|
+
prefix: "z",
|
|
25035
|
+
alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
25036
|
+
});
|
|
25037
|
+
base58flickr2 = baseX2({
|
|
25038
|
+
name: "base58flickr",
|
|
25039
|
+
prefix: "Z",
|
|
25040
|
+
alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
|
|
25041
|
+
});
|
|
25042
|
+
POLICY_V1_DOMAIN = "xyz.tinycloud.policy/policy/v1\0";
|
|
25043
|
+
POLICY_V2_DOMAIN = "xyz.tinycloud.policy/policy/v2\0";
|
|
25044
|
+
POLICY_CAPABILITY_V1_DOMAIN2 = "xyz.tinycloud.policy/PolicyCapability/v1\0";
|
|
25045
|
+
CONTENT_SOURCE_V1_DOMAIN2 = "xyz.tinycloud.policy/ContentSource/v1\0";
|
|
25046
|
+
NATIVE_PROJECTION_V1_DOMAIN2 = "xyz.tinycloud.policy/NativeProjection/v1\0";
|
|
25047
|
+
ENVELOPE_V3_DOMAIN = "xyz.tinycloud.share/envelope/v3\0";
|
|
25048
|
+
textEncoder = new TextEncoder();
|
|
25161
25049
|
base322 = rfc46482({
|
|
25162
25050
|
prefix: "b",
|
|
25163
25051
|
name: "base32",
|
|
@@ -25222,16 +25110,6 @@ var init_dist3 = __esm({
|
|
|
25222
25110
|
name: "base36upper",
|
|
25223
25111
|
alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
25224
25112
|
});
|
|
25225
|
-
base58btc2 = baseX2({
|
|
25226
|
-
name: "base58btc",
|
|
25227
|
-
prefix: "z",
|
|
25228
|
-
alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
25229
|
-
});
|
|
25230
|
-
base58flickr2 = baseX2({
|
|
25231
|
-
name: "base58flickr",
|
|
25232
|
-
prefix: "Z",
|
|
25233
|
-
alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
|
|
25234
|
-
});
|
|
25235
25113
|
encode_12 = encode4;
|
|
25236
25114
|
MSB2 = 128;
|
|
25237
25115
|
REST2 = 127;
|
|
@@ -25267,10 +25145,10 @@ var init_dist3 = __esm({
|
|
|
25267
25145
|
/**
|
|
25268
25146
|
* Creates a multihash digest.
|
|
25269
25147
|
*/
|
|
25270
|
-
constructor(code32, size2,
|
|
25148
|
+
constructor(code32, size2, digest3, bytes3) {
|
|
25271
25149
|
this.code = code32;
|
|
25272
25150
|
this.size = size2;
|
|
25273
|
-
this.digest =
|
|
25151
|
+
this.digest = digest3;
|
|
25274
25152
|
this.bytes = bytes3;
|
|
25275
25153
|
}
|
|
25276
25154
|
};
|
|
@@ -25333,8 +25211,8 @@ var init_dist3 = __esm({
|
|
|
25333
25211
|
toV1() {
|
|
25334
25212
|
switch (this.version) {
|
|
25335
25213
|
case 0: {
|
|
25336
|
-
const { code: code32, digest:
|
|
25337
|
-
const multihash = create2(code32,
|
|
25214
|
+
const { code: code32, digest: digest3 } = this.multihash;
|
|
25215
|
+
const multihash = create2(code32, digest3);
|
|
25338
25216
|
return _CID2.createV1(this.code, multihash);
|
|
25339
25217
|
}
|
|
25340
25218
|
case 1: {
|
|
@@ -25388,8 +25266,8 @@ var init_dist3 = __esm({
|
|
|
25388
25266
|
return new _CID2(version3, code32, multihash, bytes3 ?? encodeCID2(version3, code32, multihash.bytes));
|
|
25389
25267
|
} else if (value[cidSymbol2] === true) {
|
|
25390
25268
|
const { version: version3, multihash, code: code32 } = value;
|
|
25391
|
-
const
|
|
25392
|
-
return _CID2.create(version3, code32,
|
|
25269
|
+
const digest3 = decode8(multihash);
|
|
25270
|
+
return _CID2.create(version3, code32, digest3);
|
|
25393
25271
|
} else {
|
|
25394
25272
|
return null;
|
|
25395
25273
|
}
|
|
@@ -25399,11 +25277,11 @@ var init_dist3 = __esm({
|
|
|
25399
25277
|
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
|
|
25400
25278
|
* @param digest - (Multi)hash of the of the content.
|
|
25401
25279
|
*/
|
|
25402
|
-
static create(version3, code32,
|
|
25280
|
+
static create(version3, code32, digest3) {
|
|
25403
25281
|
if (typeof code32 !== "number") {
|
|
25404
25282
|
throw new Error("String codecs are no longer supported");
|
|
25405
25283
|
}
|
|
25406
|
-
if (!(
|
|
25284
|
+
if (!(digest3.bytes instanceof Uint8Array)) {
|
|
25407
25285
|
throw new Error("Invalid digest");
|
|
25408
25286
|
}
|
|
25409
25287
|
switch (version3) {
|
|
@@ -25411,12 +25289,12 @@ var init_dist3 = __esm({
|
|
|
25411
25289
|
if (code32 !== DAG_PB_CODE2) {
|
|
25412
25290
|
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE2}) block encoding`);
|
|
25413
25291
|
} else {
|
|
25414
|
-
return new _CID2(version3, code32,
|
|
25292
|
+
return new _CID2(version3, code32, digest3, digest3.bytes);
|
|
25415
25293
|
}
|
|
25416
25294
|
}
|
|
25417
25295
|
case 1: {
|
|
25418
|
-
const bytes3 = encodeCID2(version3, code32,
|
|
25419
|
-
return new _CID2(version3, code32,
|
|
25296
|
+
const bytes3 = encodeCID2(version3, code32, digest3.bytes);
|
|
25297
|
+
return new _CID2(version3, code32, digest3, bytes3);
|
|
25420
25298
|
}
|
|
25421
25299
|
default: {
|
|
25422
25300
|
throw new Error("Invalid version");
|
|
@@ -25426,8 +25304,8 @@ var init_dist3 = __esm({
|
|
|
25426
25304
|
/**
|
|
25427
25305
|
* Simplified version of `create` for CIDv0.
|
|
25428
25306
|
*/
|
|
25429
|
-
static createV0(
|
|
25430
|
-
return _CID2.create(0, DAG_PB_CODE2,
|
|
25307
|
+
static createV0(digest3) {
|
|
25308
|
+
return _CID2.create(0, DAG_PB_CODE2, digest3);
|
|
25431
25309
|
}
|
|
25432
25310
|
/**
|
|
25433
25311
|
* Simplified version of `create` for CIDv1.
|
|
@@ -25435,8 +25313,8 @@ var init_dist3 = __esm({
|
|
|
25435
25313
|
* @param code - Content encoding format code.
|
|
25436
25314
|
* @param digest - Multihash of the content.
|
|
25437
25315
|
*/
|
|
25438
|
-
static createV1(code32,
|
|
25439
|
-
return _CID2.create(1, code32,
|
|
25316
|
+
static createV1(code32, digest3) {
|
|
25317
|
+
return _CID2.create(1, code32, digest3);
|
|
25440
25318
|
}
|
|
25441
25319
|
/**
|
|
25442
25320
|
* Decoded a CID from its binary representation. The byte array must contain
|
|
@@ -25469,8 +25347,8 @@ var init_dist3 = __esm({
|
|
|
25469
25347
|
throw new Error("Incorrect length");
|
|
25470
25348
|
}
|
|
25471
25349
|
const digestBytes3 = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
|
|
25472
|
-
const
|
|
25473
|
-
const cid2 = specs.version === 0 ? _CID2.createV0(
|
|
25350
|
+
const digest3 = new Digest2(specs.multihashCode, specs.digestSize, digestBytes3, multihashBytes);
|
|
25351
|
+
const cid2 = specs.version === 0 ? _CID2.createV0(digest3) : _CID2.createV1(specs.codec, digest3);
|
|
25474
25352
|
return [cid2, bytes3.subarray(specs.size)];
|
|
25475
25353
|
}
|
|
25476
25354
|
/**
|
|
@@ -25530,10 +25408,8 @@ var init_dist3 = __esm({
|
|
|
25530
25408
|
SHA256_CODE2 = 18;
|
|
25531
25409
|
MAX_CONTENT_BYTES = 100 * 1024 * 1024;
|
|
25532
25410
|
POLICY_ENFORCEMENT_DOMAIN = "xyz.tinycloud.share/policy-enforcement/v2\0";
|
|
25533
|
-
POLICY_DOMAIN = "xyz.tinycloud.share/policy/v2\0";
|
|
25534
25411
|
OWNER_SHARE_REGISTRATION_DOMAIN = "xyz.tinycloud.share/policy-registration/v2\0";
|
|
25535
25412
|
ENVELOPE_DOMAIN = "xyz.tinycloud.share/envelope/v2\0";
|
|
25536
|
-
ENVELOPE_DOMAIN2 = "xyz.tinycloud.share/envelope/v2\0";
|
|
25537
25413
|
ShareNotifyError = class extends Error {
|
|
25538
25414
|
code = "delivery-failed";
|
|
25539
25415
|
constructor(message = "share delivery did not complete") {
|
|
@@ -25622,72 +25498,12 @@ var init_dist3 = __esm({
|
|
|
25622
25498
|
v3ContentKey;
|
|
25623
25499
|
v3ContentEnvelope;
|
|
25624
25500
|
async beginChallenge(envelope) {
|
|
25625
|
-
|
|
25626
|
-
|
|
25627
|
-
const outer = object2(authority.outerEnvelope, "owner authority outer envelope");
|
|
25628
|
-
const enforcement = object2(authority.enforcementDelegation, "owner authority enforcement delegation");
|
|
25629
|
-
const target = object2(outer.target, "owner authority target");
|
|
25630
|
-
const outerResource = object2(outer.resource, "owner authority resource");
|
|
25631
|
-
const source = object2(outer.contentSource, "owner authority content source");
|
|
25632
|
-
if (!Array.isArray(outer.actions) || outer.actions.length === 0 || outer.actions.some((value) => typeof value !== "string")) throw new Error("owner authority outer envelope actions are invalid");
|
|
25633
|
-
const actions = [...outer.actions];
|
|
25634
|
-
const action = selectedAction(envelope);
|
|
25635
|
-
const challengeBody = { envelopeCid: authority.envelopeCid, shareCid: authority.shareCid, shareId: envelope.shareId, registrationCid: authority.registrationCid, delegationCid: envelope.delegationCid, policyCid: envelope.authorizationTarget.kind === "policy" ? envelope.authorizationTarget.policyCid : "", enforcementDelegationCid: String(enforcement.cid), enforcementDelegation: enforcement, outerEnvelope: outer, contentSource: source, contentSourceDigest: String(outer.contentSourceDigest), holderDid: this.options.holderDid, targetOrigin: String(target.origin), nodeAudience: String(target.nodeAudience), action, actions, resource: String(outerResource.path) };
|
|
25636
|
-
const requestBodyDigest = await digest3(challengeBody);
|
|
25637
|
-
const challenge2 = await verifyWrapped(await post(this.fetchFn, this.options.nodeOrigin, "/share/v2/policy/challenges", { ...challengeBody, requestBodyDigest }), "challenge", DOMAIN, this.options.trustedNode);
|
|
25638
|
-
if (challenge2.type !== "TinyCloudSharePolicyChallenge" || challenge2.version !== 2 || challenge2.challengeId.length < 16 || challenge2.nonce.length < 16 || challenge2.shareCid !== authority.shareCid || challenge2.shareId !== envelope.shareId || challenge2.registrationCid !== authority.registrationCid || challenge2.envelopeCid !== authority.envelopeCid || challenge2.policyCid !== challengeBody.policyCid || challenge2.delegationCid !== envelope.delegationCid || challenge2.enforcementDelegationCid !== enforcement.cid || canonicalize2(challenge2.contentSource) !== canonicalize2(source) || challenge2.contentSourceDigest !== challengeBody.contentSourceDigest || challenge2.requestBodyDigest !== requestBodyDigest || challenge2.holderDid !== this.options.holderDid || challenge2.targetOrigin !== challengeBody.targetOrigin || challenge2.nodeAudience !== challengeBody.nodeAudience || challenge2.action !== action || canonicalize2(challenge2.actions) !== canonicalize2(actions) || challenge2.resource !== challengeBody.resource || !Number.isFinite(Date.parse(challenge2.expiresAt)) || Date.parse(challenge2.expiresAt) <= Date.now()) throw new Error("share authority returned an unbound challenge");
|
|
25639
|
-
return challenge2;
|
|
25501
|
+
void envelope;
|
|
25502
|
+
throw new Error("v2 Share recipient transport has been removed; use the embedded policy v3 envelope");
|
|
25640
25503
|
}
|
|
25641
25504
|
async establish(envelope) {
|
|
25642
|
-
|
|
25643
|
-
|
|
25644
|
-
const outer = object2(authority.outerEnvelope, "owner authority outer envelope");
|
|
25645
|
-
const enforcement = object2(authority.enforcementDelegation, "owner authority enforcement delegation");
|
|
25646
|
-
const target = object2(outer.target, "owner authority target");
|
|
25647
|
-
const outerResource = object2(outer.resource, "owner authority resource");
|
|
25648
|
-
const source = object2(outer.contentSource, "owner authority content source");
|
|
25649
|
-
if (!Array.isArray(outer.actions) || outer.actions.length === 0 || outer.actions.some((value) => typeof value !== "string")) throw new Error("owner authority outer envelope actions are invalid");
|
|
25650
|
-
const actions = [...outer.actions];
|
|
25651
|
-
const action = selectedAction(envelope);
|
|
25652
|
-
const challengeBody = { envelopeCid: authority.envelopeCid, shareCid: authority.shareCid, shareId: envelope.shareId, registrationCid: authority.registrationCid, delegationCid: envelope.delegationCid, policyCid: envelope.authorizationTarget.kind === "policy" ? envelope.authorizationTarget.policyCid : "", enforcementDelegationCid: String(enforcement.cid), enforcementDelegation: enforcement, outerEnvelope: outer, contentSource: source, contentSourceDigest: String(outer.contentSourceDigest), holderDid: this.options.holderDid, targetOrigin: String(target.origin), nodeAudience: String(target.nodeAudience), action, actions, resource: String(outerResource.path) };
|
|
25653
|
-
const requestBodyDigest = await digest3(challengeBody);
|
|
25654
|
-
const challenge2 = await verifyWrapped(await post(this.fetchFn, this.options.nodeOrigin, "/share/v2/policy/challenges", { ...challengeBody, requestBodyDigest }), "challenge", DOMAIN, this.options.trustedNode);
|
|
25655
|
-
if (challenge2.type !== "TinyCloudSharePolicyChallenge" || challenge2.version !== 2 || challenge2.challengeId === void 0 || challenge2.nonce === void 0 || challenge2.shareCid !== authority.shareCid || challenge2.shareId !== envelope.shareId || challenge2.registrationCid !== authority.registrationCid || challenge2.envelopeCid !== authority.envelopeCid || challenge2.policyCid !== challengeBody.policyCid || challenge2.delegationCid !== envelope.delegationCid || challenge2.enforcementDelegationCid !== enforcement.cid || challenge2.requestBodyDigest !== requestBodyDigest || canonicalize2(challenge2.contentSource) !== canonicalize2(source) || challenge2.contentSourceDigest !== challengeBody.contentSourceDigest || challenge2.holderDid !== this.options.holderDid || challenge2.targetOrigin !== challengeBody.targetOrigin || challenge2.nodeAudience !== challengeBody.nodeAudience || challenge2.action !== action || canonicalize2(challenge2.actions) !== canonicalize2(actions) || challenge2.resource !== challengeBody.resource || !Number.isFinite(Date.parse(challenge2.expiresAt)) || Date.parse(challenge2.expiresAt) <= Date.now()) throw new Error("share authority returned an unbound challenge");
|
|
25656
|
-
if (this.options.buildPresentation === void 0) throw new Error("share presentation builder is required");
|
|
25657
|
-
const material = await this.options.buildPresentation({ challenge: challenge2, envelope, policy: {} });
|
|
25658
|
-
this.holderProof = material.proof;
|
|
25659
|
-
this.signer = material.sign;
|
|
25660
|
-
this.nativeSigner = material.sign;
|
|
25661
|
-
if (this.signer === void 0) throw new Error("share holder signer is required");
|
|
25662
|
-
const presentation = {
|
|
25663
|
-
type: "TinyCloudSharePolicyPresentation",
|
|
25664
|
-
version: 2,
|
|
25665
|
-
challengeId: challenge2.challengeId,
|
|
25666
|
-
nonce: challenge2.nonce,
|
|
25667
|
-
shareCid: authority.shareCid,
|
|
25668
|
-
shareId: envelope.shareId,
|
|
25669
|
-
delegationCid: envelope.delegationCid,
|
|
25670
|
-
policyCid: challengeBody.policyCid,
|
|
25671
|
-
contentSource: source,
|
|
25672
|
-
contentSourceDigest: challengeBody.contentSourceDigest,
|
|
25673
|
-
holderDid: material.holderDid,
|
|
25674
|
-
targetOrigin: challengeBody.targetOrigin,
|
|
25675
|
-
nodeAudience: challengeBody.nodeAudience,
|
|
25676
|
-
...challenge2.enforcerDid === void 0 ? {} : { enforcerDid: challenge2.enforcerDid },
|
|
25677
|
-
credentialDigest: material.credentialDigest ?? await digestText2(material.credential),
|
|
25678
|
-
action,
|
|
25679
|
-
actions,
|
|
25680
|
-
resource: challengeBody.resource,
|
|
25681
|
-
requestBodyDigest,
|
|
25682
|
-
issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
25683
|
-
expiresAt: challenge2.expiresAt,
|
|
25684
|
-
jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
|
|
25685
|
-
};
|
|
25686
|
-
const presentationProof = { alg: "EdDSA", kid: `${material.holderDid}#${material.holderDid.slice("did:key:".length)}`, signature: toBase64Url(await this.signer(new TextEncoder().encode(`${PRESENTATION_DOMAIN}${canonicalize2(presentation)}`))) };
|
|
25687
|
-
const session = await verifyWrapped(await post(this.fetchFn, this.options.nodeOrigin, "/share/v2/policy/session", { challengeId: challenge2.challengeId, nonce: challenge2.nonce, presentation, credential: material.credential, proof: presentationProof, holderBinding: material.holderBinding, readSignerDid: material.holderDid }), "session", SESSION_DOMAIN, this.options.trustedNode);
|
|
25688
|
-
if (session.type !== "TinyCloudSharePolicySession" || session.version !== 2 || typeof session.sessionId !== "string" || session.shareCid !== authority.shareCid || session.shareId !== envelope.shareId || session.registrationCid !== authority.registrationCid || session.envelopeCid !== authority.envelopeCid || session.policyCid !== challengeBody.policyCid || session.delegationCid !== envelope.delegationCid || session.holderDid !== this.options.holderDid || session.targetOrigin !== challengeBody.targetOrigin || session.nodeAudience !== challengeBody.nodeAudience || session.action !== action || canonicalize2(session.actions) !== canonicalize2(actions) || canonicalize2(session.contentSource) !== canonicalize2(source) || session.contentSourceDigest !== challengeBody.contentSourceDigest || session.resource !== challengeBody.resource || typeof session.expiresAt !== "string" || !Number.isFinite(Date.parse(session.expiresAt)) || Date.parse(session.expiresAt) <= Date.now()) throw new Error("share authority returned an unbound session");
|
|
25689
|
-
this.session = { sessionId: session.sessionId, expiresAt: session.expiresAt, actions: actions.map(uiAction), resource: { kind: envelope.resource.kind, path: String(session.resource) } };
|
|
25690
|
-
return this.session;
|
|
25505
|
+
void envelope;
|
|
25506
|
+
throw new Error("v2 Share recipient transport has been removed; use the embedded policy v3 envelope");
|
|
25691
25507
|
}
|
|
25692
25508
|
async authorize(envelope) {
|
|
25693
25509
|
if (this.session === void 0) await this.establish(envelope);
|
|
@@ -25715,7 +25531,7 @@ var init_dist3 = __esm({
|
|
|
25715
25531
|
} catch {
|
|
25716
25532
|
throw new Error("v3 attested Node audience is invalid");
|
|
25717
25533
|
}
|
|
25718
|
-
const challengeResponse = await this.fetchFn(new URL("/
|
|
25534
|
+
const challengeResponse = await this.fetchFn(new URL("/policy/v3/challenges", this.options.nodeOrigin), {
|
|
25719
25535
|
method: "POST",
|
|
25720
25536
|
redirect: "error",
|
|
25721
25537
|
headers: { accept: "application/json", "content-type": "application/json" },
|
|
@@ -25736,7 +25552,7 @@ var init_dist3 = __esm({
|
|
|
25736
25552
|
throw new Error(accountless ? "v4 ceremony requires a verified credential and requirement" : "v3 ceremony requires a claim");
|
|
25737
25553
|
}
|
|
25738
25554
|
this.options.onStage?.("policy-admission");
|
|
25739
|
-
const delegationResponse = await this.fetchFn(new URL("/
|
|
25555
|
+
const delegationResponse = await this.fetchFn(new URL("/policy/v3/delegations", this.options.nodeOrigin), {
|
|
25740
25556
|
method: "POST",
|
|
25741
25557
|
redirect: "error",
|
|
25742
25558
|
headers: { accept: "application/json", "content-type": "application/json" },
|
|
@@ -25767,7 +25583,7 @@ var init_dist3 = __esm({
|
|
|
25767
25583
|
const receiverPublicKey = toBase64(x25519.getPublicKey(receiverPrivateKey));
|
|
25768
25584
|
const receiverPublicKeyHash = canonicalHashHex2(receiverPublicKey);
|
|
25769
25585
|
const body = { type: "tinycloud.encryption.decrypt/v1", targetNode: this.v3NodeAudience, networkId: encrypted.networkId, alg: encrypted.alg, keyVersion: encrypted.keyVersion, encryptedSymmetricKey: encrypted.encryptedSymmetricKey, encryptedSymmetricKeyHash: encrypted.encryptedSymmetricKeyHash, receiverPublicKey, receiverPublicKeyHash };
|
|
25770
|
-
const bodyHash =
|
|
25586
|
+
const bodyHash = hex3(sha2562(new TextEncoder().encode(canonicalize2(body))));
|
|
25771
25587
|
const session = verifyCompactUcanAuthorization(this.v3Authorization, this.session.sessionId);
|
|
25772
25588
|
const now = Math.floor(Date.now() / 1e3);
|
|
25773
25589
|
const invocation = await signCompactUcanAuthorization({
|
|
@@ -25787,7 +25603,7 @@ var init_dist3 = __esm({
|
|
|
25787
25603
|
if (!response.ok) throw new Error(`v3 decrypt invocation rejected (${response.status})`);
|
|
25788
25604
|
const value = object2(await response.json(), "v3 decrypt response");
|
|
25789
25605
|
const allowed = ["type", "targetNode", "networkId", "invocationCid", "encryptedSymmetricKeyHash", "receiverPublicKeyHash", "wrappedKey", "alg", "keyVersion", "requestHash", "nodeId", "nodeSignature"];
|
|
25790
|
-
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 !==
|
|
25606
|
+
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 !== hex3(sha2562(new TextEncoder().encode(`${invocation.cid}${bodyHash}`))) || typeof value.wrappedKey !== "string" || typeof value.nodeSignature !== "string") throw new Error("v3 decrypt response binding is invalid");
|
|
25791
25607
|
const unsigned = { ...value };
|
|
25792
25608
|
delete unsigned.nodeSignature;
|
|
25793
25609
|
const signature = fromBase64(value.nodeSignature, "v3 decrypt response signature");
|
|
@@ -25813,47 +25629,16 @@ var init_dist3 = __esm({
|
|
|
25813
25629
|
return new TextEncoder().encode(canonicalize2({ ...this.v3ContentEnvelope, ciphertext: toBase64Url(await aesGcmEncrypt(this.v3ContentKey, bytes3)), metadata: { ...this.v3ContentEnvelope.metadata ?? {}, contentType: mediaType } }));
|
|
25814
25630
|
}
|
|
25815
25631
|
async resumeWithProof(envelope, resumeToken, proof) {
|
|
25816
|
-
|
|
25817
|
-
|
|
25818
|
-
|
|
25819
|
-
|
|
25820
|
-
const credential = material.credential;
|
|
25821
|
-
const holderDid = material.holderDid;
|
|
25822
|
-
const holderBinding = material.holderBinding;
|
|
25823
|
-
if (typeof nonce !== "string" || typeof credential !== "string" || typeof holderDid !== "string" || holderDid !== this.options.holderDid || typeof holderBinding !== "object" || holderBinding === null || presentationProof.alg !== "EdDSA" || typeof presentationProof.signature !== "string") throw new Error("share authorization proof is incomplete");
|
|
25824
|
-
const value = object2(await post(this.fetchFn, this.options.nodeOrigin, "/share/v2/policy/session", { challengeId: resumeToken, nonce, presentation, credential, proof: presentationProof, holderBinding, readSignerDid: holderDid }), "share policy session");
|
|
25825
|
-
const session = await verifyWrapped(value, "session", SESSION_DOMAIN, this.options.trustedNode);
|
|
25826
|
-
const authority = envelope.ownerAuthority;
|
|
25827
|
-
if (authority === void 0 || session.type !== "TinyCloudSharePolicySession" || session.version !== 2 || typeof session.sessionId !== "string" || session.shareCid !== authority.shareCid || session.shareId !== envelope.shareId || session.registrationCid !== authority.registrationCid || session.envelopeCid !== authority.envelopeCid || session.delegationCid !== envelope.delegationCid || typeof session.resource !== "string" || typeof session.expiresAt !== "string") throw new Error("share authority returned an unbound session");
|
|
25828
|
-
const policyCid = envelope.authorizationTarget.kind === "policy" ? envelope.authorizationTarget.policyCid : "";
|
|
25829
|
-
const actions = [...new Set(envelope.actions.map(nativeAction))].sort();
|
|
25830
|
-
if (session.policyCid !== policyCid || session.holderDid !== this.options.holderDid || session.targetOrigin !== envelope.target.origin || session.nodeAudience !== envelope.target.nodeAudience || session.action !== selectedAction(envelope) || canonicalize2(session.actions) !== canonicalize2(actions) || canonicalize2(session.contentSource) !== canonicalize2(envelope.contentSource) || session.contentSourceDigest !== envelope.contentSourceDigest || !Number.isFinite(Date.parse(session.expiresAt)) || Date.parse(session.expiresAt) <= Date.now()) throw new Error("share authority returned an unbound session");
|
|
25831
|
-
this.session = { sessionId: session.sessionId, expiresAt: session.expiresAt, actions: actions.map(uiAction), resource: { kind: envelope.resource.kind, path: String(session.resource) } };
|
|
25832
|
-
this.holderProof = presentationProof;
|
|
25833
|
-
this.signer ??= this.options.sign;
|
|
25834
|
-
return this.authorize(envelope);
|
|
25632
|
+
void envelope;
|
|
25633
|
+
void resumeToken;
|
|
25634
|
+
void proof;
|
|
25635
|
+
throw new Error("v2 Share recipient transport has been removed; use the embedded policy v3 envelope");
|
|
25835
25636
|
}
|
|
25836
25637
|
async nativeInvoke(request) {
|
|
25837
25638
|
if (this.session === void 0) throw new Error("share policy session is required");
|
|
25838
25639
|
const envelope = this.options.envelope;
|
|
25839
25640
|
if (envelope.version === 3) return this.nativeInvokeV3(request, envelope);
|
|
25840
|
-
|
|
25841
|
-
const authority = envelope.ownerAuthority;
|
|
25842
|
-
const action = request.action === "list" ? "tinycloud.kv/list" : request.action === "put" ? "tinycloud.kv/put" : request.action === "metadata" ? "tinycloud.kv/metadata" : "tinycloud.kv/get";
|
|
25843
|
-
const resource = typeof request.resource?.path === "string" ? request.resource.path : this.session.resource.path;
|
|
25844
|
-
const actions = [...new Set(this.session.actions.map(nativeAction).concat(action === "tinycloud.kv/metadata" ? [action] : []))].sort();
|
|
25845
|
-
const bodyBytes = request.body === void 0 ? void 0 : Uint8Array.from(request.body);
|
|
25846
|
-
const bodyDigest = bodyBytes === void 0 ? void 0 : toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bodyBytes)));
|
|
25847
|
-
const outer = object2(authority.outerEnvelope, "owner authority outer envelope");
|
|
25848
|
-
const enforcement = object2(authority.enforcementDelegation, "owner authority enforcement delegation");
|
|
25849
|
-
const invocationBase = { type: "TinyCloudShareReadInvocation", version: 2, sessionId: this.session.sessionId, envelopeCid: authority.envelopeCid, shareCid: authority.shareCid, shareId: envelope.shareId, registrationCid: authority.registrationCid, delegationCid: envelope.delegationCid, policyCid: envelope.authorizationTarget.kind === "policy" ? envelope.authorizationTarget.policyCid : "", enforcementDelegationCid: String(enforcement.cid), contentSource: outer.contentSource, contentSourceDigest: String(outer.contentSourceDigest), holderDid: this.options.holderDid, targetOrigin: String(object2(outer.target, "owner authority target").origin), nodeAudience: String(object2(outer.target, "owner authority target").nodeAudience), action, actions, resource, ...action === "tinycloud.kv/list" ? { limit: 100 } : {}, ...bodyDigest === void 0 ? {} : { bodyDigest, ifMatch: request.ifMatch, contentType: request.contentType }, issuedAt: (/* @__PURE__ */ new Date()).toISOString(), expiresAt: new Date(Math.min(Date.now() + 6e4, Date.parse(this.session.expiresAt))).toISOString(), jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))) };
|
|
25850
|
-
const requestBodyDigest = await digest3(invocationBase);
|
|
25851
|
-
const invocation = { ...invocationBase, requestBodyDigest };
|
|
25852
|
-
const proof = { ...this.holderProof, signature: toBase64Url(await this.signer(new TextEncoder().encode(`${INVOCATION_DOMAIN}${canonicalize2(invocation)}`))) };
|
|
25853
|
-
const signedRequest = { sessionId: this.session.sessionId, envelopeCid: authority.envelopeCid, shareCid: authority.shareCid, shareId: envelope.shareId, registrationCid: authority.registrationCid, delegationCid: envelope.delegationCid, policyCid: envelope.authorizationTarget.kind === "policy" ? envelope.authorizationTarget.policyCid : "", enforcementDelegationCid: String(enforcement.cid), contentSource: outer.contentSource, contentSourceDigest: String(outer.contentSourceDigest), holderDid: this.options.holderDid, nodeAudience: String(object2(outer.target, "owner authority target").nodeAudience), action, actions, resource, requestBodyDigest, invocation, proof };
|
|
25854
|
-
const response = await this.fetchFn(new URL("/share/v2/invoke", this.options.nodeOrigin), { method: "POST", redirect: "error", headers: { accept: "application/vnd.tinycloud.share+json", "content-type": "application/vnd.tinycloud.share+json" }, body: JSON.stringify({ request: signedRequest, ...action === "tinycloud.kv/list" ? { limit: 100 } : {}, ...bodyBytes === void 0 ? {} : { body: toBase64Url(bodyBytes), bodyDigest, ifMatch: request.ifMatch, contentType: request.contentType } }) });
|
|
25855
|
-
if (response.ok) await verifyDetachedResponse(response, this.options.trustedNode);
|
|
25856
|
-
return response;
|
|
25641
|
+
throw new Error("v2 Share invocation transport has been removed; use the embedded policy v3 envelope");
|
|
25857
25642
|
}
|
|
25858
25643
|
async nativeInvokeV3(request, envelope) {
|
|
25859
25644
|
const signer = this.nativeSigner ?? this.signer;
|
|
@@ -26181,25 +25966,25 @@ function encodeTo3(int, target, offset = 0) {
|
|
|
26181
25966
|
function encodingLength3(int) {
|
|
26182
25967
|
return varint_default3.encodingLength(int);
|
|
26183
25968
|
}
|
|
26184
|
-
function create3(code32,
|
|
26185
|
-
const size2 =
|
|
25969
|
+
function create3(code32, digest4) {
|
|
25970
|
+
const size2 = digest4.byteLength;
|
|
26186
25971
|
const sizeOffset = encodingLength3(code32);
|
|
26187
25972
|
const digestOffset = sizeOffset + encodingLength3(size2);
|
|
26188
25973
|
const bytes22 = new Uint8Array(digestOffset + size2);
|
|
26189
25974
|
encodeTo3(code32, bytes22, 0);
|
|
26190
25975
|
encodeTo3(size2, bytes22, sizeOffset);
|
|
26191
|
-
bytes22.set(
|
|
26192
|
-
return new Digest3(code32, size2,
|
|
25976
|
+
bytes22.set(digest4, digestOffset);
|
|
25977
|
+
return new Digest3(code32, size2, digest4, bytes22);
|
|
26193
25978
|
}
|
|
26194
25979
|
function decode42(multihash) {
|
|
26195
25980
|
const bytes22 = coerce4(multihash);
|
|
26196
25981
|
const [code32, sizeOffset] = decode32(bytes22);
|
|
26197
25982
|
const [size2, digestOffset] = decode32(bytes22.subarray(sizeOffset));
|
|
26198
|
-
const
|
|
26199
|
-
if (
|
|
25983
|
+
const digest4 = bytes22.subarray(sizeOffset + digestOffset);
|
|
25984
|
+
if (digest4.byteLength !== size2) {
|
|
26200
25985
|
throw new Error("Incorrect length");
|
|
26201
25986
|
}
|
|
26202
|
-
return new Digest3(code32, size2,
|
|
25987
|
+
return new Digest3(code32, size2, digest4, bytes22);
|
|
26203
25988
|
}
|
|
26204
25989
|
function equals22(a, b) {
|
|
26205
25990
|
if (a === b) {
|
|
@@ -26312,7 +26097,7 @@ function decode52(str) {
|
|
|
26312
26097
|
}
|
|
26313
26098
|
return new Uint8Array(byts);
|
|
26314
26099
|
}
|
|
26315
|
-
function
|
|
26100
|
+
function digest(input, options2) {
|
|
26316
26101
|
if (options2?.truncate != null && options2.truncate !== input.byteLength) {
|
|
26317
26102
|
if (options2.truncate < 0 || options2.truncate > input.byteLength) {
|
|
26318
26103
|
throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`);
|
|
@@ -26324,14 +26109,14 @@ function digest2(input, options2) {
|
|
|
26324
26109
|
function from22({ name: name2, code: code32, encode: encode52, minDigestLength, maxDigestLength }) {
|
|
26325
26110
|
return new Hasher(name2, code32, encode52, minDigestLength, maxDigestLength);
|
|
26326
26111
|
}
|
|
26327
|
-
function createDigest(
|
|
26328
|
-
if (truncate != null && truncate !==
|
|
26329
|
-
if (truncate >
|
|
26330
|
-
throw new Error(`Invalid truncate option, must be less than or equal to ${
|
|
26112
|
+
function createDigest(digest4, code32, truncate) {
|
|
26113
|
+
if (truncate != null && truncate !== digest4.byteLength) {
|
|
26114
|
+
if (truncate > digest4.byteLength) {
|
|
26115
|
+
throw new Error(`Invalid truncate option, must be less than or equal to ${digest4.byteLength}`);
|
|
26331
26116
|
}
|
|
26332
|
-
|
|
26117
|
+
digest4 = digest4.subarray(0, truncate);
|
|
26333
26118
|
}
|
|
26334
|
-
return create3(code32,
|
|
26119
|
+
return create3(code32, digest4);
|
|
26335
26120
|
}
|
|
26336
26121
|
function sha(name2) {
|
|
26337
26122
|
return async (data) => new Uint8Array(await crypto.subtle.digest(name2, data));
|
|
@@ -26362,64 +26147,6 @@ function createShareLinkDataSchema(dataSchema) {
|
|
|
26362
26147
|
path: external_exports.string()
|
|
26363
26148
|
});
|
|
26364
26149
|
}
|
|
26365
|
-
function activationFlightKey(host, delegationHeader) {
|
|
26366
|
-
const entries = Object.entries(delegationHeader).sort(
|
|
26367
|
-
([a], [b]) => a < b ? -1 : a > b ? 1 : 0
|
|
26368
|
-
);
|
|
26369
|
-
return JSON.stringify([host, entries]);
|
|
26370
|
-
}
|
|
26371
|
-
async function activateSessionWithHost(host, delegationHeader) {
|
|
26372
|
-
const key = activationFlightKey(host, delegationHeader);
|
|
26373
|
-
const existing = inFlightActivations.get(key);
|
|
26374
|
-
if (!existing) return startActivationFlight(key, host, delegationHeader);
|
|
26375
|
-
try {
|
|
26376
|
-
return await existing;
|
|
26377
|
-
} catch {
|
|
26378
|
-
return joinOrStartActivationFlight(key, host, delegationHeader);
|
|
26379
|
-
}
|
|
26380
|
-
}
|
|
26381
|
-
function joinOrStartActivationFlight(key, host, delegationHeader) {
|
|
26382
|
-
return inFlightActivations.get(key) ?? startActivationFlight(key, host, delegationHeader);
|
|
26383
|
-
}
|
|
26384
|
-
function startActivationFlight(key, host, delegationHeader) {
|
|
26385
|
-
const flight = postSessionActivation(host, delegationHeader);
|
|
26386
|
-
inFlightActivations.set(key, flight);
|
|
26387
|
-
const evict = () => {
|
|
26388
|
-
if (inFlightActivations.get(key) === flight) inFlightActivations.delete(key);
|
|
26389
|
-
};
|
|
26390
|
-
flight.then(evict, evict);
|
|
26391
|
-
return flight;
|
|
26392
|
-
}
|
|
26393
|
-
async function postSessionActivation(host, delegationHeader) {
|
|
26394
|
-
const res = await fetch(`${host}/delegate`, {
|
|
26395
|
-
method: "POST",
|
|
26396
|
-
headers: delegationHeader
|
|
26397
|
-
});
|
|
26398
|
-
if (res.ok) {
|
|
26399
|
-
try {
|
|
26400
|
-
const body = await res.json();
|
|
26401
|
-
return {
|
|
26402
|
-
success: true,
|
|
26403
|
-
status: res.status,
|
|
26404
|
-
activated: body.activated ?? [],
|
|
26405
|
-
skipped: body.skipped ?? [],
|
|
26406
|
-
commitEventCid: body.cid
|
|
26407
|
-
};
|
|
26408
|
-
} catch {
|
|
26409
|
-
return {
|
|
26410
|
-
success: true,
|
|
26411
|
-
status: res.status,
|
|
26412
|
-
activated: [],
|
|
26413
|
-
skipped: []
|
|
26414
|
-
};
|
|
26415
|
-
}
|
|
26416
|
-
}
|
|
26417
|
-
return {
|
|
26418
|
-
success: false,
|
|
26419
|
-
status: res.status,
|
|
26420
|
-
error: await res.text().catch(() => res.statusText)
|
|
26421
|
-
};
|
|
26422
|
-
}
|
|
26423
26150
|
function equals32(a, b) {
|
|
26424
26151
|
if (a === b) {
|
|
26425
26152
|
return true;
|
|
@@ -27358,7 +27085,7 @@ function decodeBase64Url4(value) {
|
|
|
27358
27085
|
}
|
|
27359
27086
|
return Uint8Array.from(bytes22);
|
|
27360
27087
|
}
|
|
27361
|
-
var import_ms, __defProp3, __typeError, __defNormalProp, __export3, __publicField, __accessCheck, __privateGet, __privateAdd, __privateSet, EnsDataSchema, SiweConfigSchema, ClientSessionSchema, objectHasOwn, base32_exports, empty3, src3, _brrp__multiformats_scope_baseX3, base_x_default3, Encoder3, Decoder3, ComposedDecoder3, Codec3, base323, base32upper3, base32pad3, base32padupper3, base32hex3, base32hexupper3, base32hexpad3, base32hexpadupper3, base32z3, base36_exports, base363, base36upper3, base58_exports, base58btc3, base58flickr3, encode_13, MSB3, REST3, MSBALL3, INT3, decode22, MSB$13, REST$13, N13, N23, N33, N43, N53, N63, N73, N83, N93, length3, varint3, _brrp_varint3, varint_default3, Digest3, cache3, _a, CID3, DAG_PB_CODE3, SHA_256_CODE3, cidSymbol3,
|
|
27088
|
+
var import_ms, __defProp3, __typeError, __defNormalProp, __export3, __publicField, __accessCheck, __privateGet, __privateAdd, __privateSet, EnsDataSchema, SiweConfigSchema, ClientSessionSchema, objectHasOwn, base32_exports, empty3, src3, _brrp__multiformats_scope_baseX3, base_x_default3, Encoder3, Decoder3, ComposedDecoder3, Codec3, base323, base32upper3, base32pad3, base32padupper3, base32hex3, base32hexupper3, base32hexpad3, base32hexpadupper3, base32z3, base36_exports, base363, base36upper3, base58_exports, base58btc3, base58flickr3, encode_13, MSB3, REST3, MSBALL3, INT3, decode22, MSB$13, REST$13, N13, N23, N33, N43, N53, N63, N73, N83, N93, length3, varint3, _brrp_varint3, varint_default3, Digest3, cache3, _a, CID3, DAG_PB_CODE3, SHA_256_CODE3, cidSymbol3, textEncoder2, objectHasOwn2, CEILING_SERVICES, GRANTABLE_ACTIONS, base10_exports, base10, base16_exports, base16, base16upper, base2_exports, base22, base256emoji_exports, alphabet, alphabetBytesToChars, alphabetCharsToBytes, base256emoji, base64_exports, base642, base64pad2, base64url2, base64urlpad2, base8_exports, base8, identity_exports, identity, textEncoder22, textDecoder, identity_exports2, code22, name, encode42, identity2, sha2_browser_exports, DEFAULT_MIN_DIGEST_LENGTH, Hasher, sha25622, sha5122, bases, hashes, textEncoder3, objectHasOwn3, TRANSCRIPT_SHARE_BOOTSTRAP_SCHEMA, OWNER_NODE_ENDPOINT_SCHEMA, W3C_VC_CREDENTIAL_VERIFIER, objectHasOwn4, CompactHeaderSchema, CompactPayloadSchema, POLICY_ENGINE_CHALLENGE_RESPONSE_SCHEMA, POLICY_ENGINE_DENIAL_SCHEMA, POLICY_ENGINE_GRANT_PRESENTATION_DENIAL_CODES, JsonValueSchema, Rfc3339Schema, SignedRecordSchema, PolicyEngineSchema, OwnerNodeSchema, ResourceHintSchema, BootstrapSchema, SignatureSchema, ChallengeSchema, ChallengeResponseSchema, DenialSchema, ErrorEnvelopeDenialSchema, WireDelegationSchema, ResolveResponseSchema, DelegateReceiptSchema, SqlReadResponseSchema, KvReadResponseSchema, LISTEN_SQL_STATEMENT_CATALOG, LISTEN_SQL_STATEMENT_BY_NAME, JWKSchema, KeyTypeSchema, KeyInfoSchema, DelegationErrorSchema, DelegationSchema, DelegationStatusSchema, DelegationRevocationReceiptSchema, AccountDelegationResourceSchema, AccountDelegationDateSchema, AccountDelegationRecordSchema, AccountDelegationPageSchema, AccountDelegationQueryOptionsSchema, CapabilityEntrySchema, DelegationRecordSchema, CreateDelegationParamsSchema, DelegationChainSchema, DelegationChainV2Schema, DelegationDirectionSchema, DelegationFiltersSchema, SpaceOwnershipSchema, SpaceInfoSchema, ShareSchemaSchema, ShareLinkSchema, ShareLinkDataSchema, IngestOptionsSchema, GenerateShareParamsSchema, DelegationManagerConfigSchema, KeyProviderSchema, DelegationApiResponseSchema, DelegatedResourceSchema, CreateDelegationWasmParamsSchema, CreateDelegationWasmResultSchema, EPHEMERAL_MS, SIGNED_READ_URL_MS, SESSION_MS, SHARE_MS, APP_MS, MAX_MS, EXPIRY, DEFAULT_SIGNED_READ_URL_EXPIRY_MS2, EncodedShareDataSchema, ReceiveOptionsSchema, SharingServiceConfigSchema, SERVICE_SHORT_TO_LONG, SERVICE_LONG_TO_SHORT, DEFAULT_MAX_INLINE_BYTES, MAX_SHARE_CONTENT_BYTES, MAX_SEALED_SHARE_CONTENT_BYTES, MAX_SHARE_ARTIFACT_BYTES, PUBLISHED_AAD, ShareRecipientTargetSchema, ShareResourceSchema, ShareActionSchema, ShareRecipientPolicySchema, ShareRecipientClientOptionsSchema, ShareNativeActionSchema, ShareWireActionSchema, ShareContentSourceSchema, ShareAddressedRecipientSchema, ShareAddressedDelegationRequestV2Schema, ShareAddressedDelegationEnvelopeV2Schema, ShareAddressedDelegationResponseV2Schema, ShareNativeResponseEntrySchema, ShareNativeResponseBase, ShareNativeResponseSchema, ResourceSchema, PortableDelegationSchema, MAX_NATIVE_CURSOR_BYTES, DEFAULT_EXPIRY_MS2, MAX_CONTENT_BYTES2, ethereumAddressPattern, EnsDataSchema2, PersistedTinyCloudSessionSchema, PersistedSessionDataSchema, TinyCloudSessionSchema, SpaceConfigSchema, SpaceServiceConfigSchema, SpaceDelegationParamsSchema, ServerDelegationInfoSchema, ServerDelegationsResponseSchema, ServerOwnedSpaceSchema, ServerOwnedSpacesResponseSchema, ServerCreateSpaceResponseSchema, ServerSpaceInfoResponseSchema, AutoApproveSpaceCreationHandler, defaultSpaceCreationHandler, N122, N222, N322, N422, N522, N622, N722, MSB22, REST22, string, ascii, BASES, bases_default, InvalidMultiaddrError, ValidationError, InvalidParametersError, UnknownProtocolError, Parser, MAX_IPV6_LENGTH, MAX_IPV4_LENGTH, parser, CODE_IP4, CODE_TCP, CODE_UDP, CODE_DCCP, CODE_IP6, CODE_IP6ZONE, CODE_IPCIDR, CODE_DNS, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_SCTP, CODE_UDT, CODE_UTP, CODE_UNIX, CODE_P2P, CODE_ONION, CODE_ONION3, CODE_GARLIC64, CODE_GARLIC32, CODE_TLS, CODE_SNI, CODE_NOISE, CODE_QUIC, CODE_QUIC_V1, CODE_WEBTRANSPORT, CODE_CERTHASH, CODE_HTTP, CODE_HTTP_PATH, CODE_HTTPS, CODE_WS, CODE_WSS, CODE_P2P_WEBSOCKET_STAR, CODE_P2P_STARDUST, CODE_P2P_WEBRTC_STAR, CODE_P2P_WEBRTC_DIRECT, CODE_WEBRTC_DIRECT, CODE_WEBRTC, CODE_P2P_CIRCUIT, CODE_MEMORY, ip4ToBytes, ip6ToBytes, ip4ToString, ip6ToString, decoders, anybaseDecoder, validatePort, V, Registry, registry, codecs, inspect, symbol, _a2, _components, _string, _bytes, _Multiaddr, Multiaddr, ASSUME_HTTP_CODES, interpreters, word, boundry, v4, v6segment, v6, v46Exact, v4exact, v6exact, ipRegex, toString3, DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL, LOCAL_LOOPBACK_PROBE_TIMEOUT_MS, LOCAL_LINK_PROBE_TIMEOUT_MS, LOCAL_LINK_HOST_SUFFIX, LocationRecordValidationError, defaultLocalNodeIdentityStore, DNS_LABEL_REGEX;
|
|
27362
27089
|
var init_dist4 = __esm({
|
|
27363
27090
|
"../sdk-core/dist/index.js"() {
|
|
27364
27091
|
"use strict";
|
|
@@ -27641,14 +27368,14 @@ var init_dist4 = __esm({
|
|
|
27641
27368
|
/**
|
|
27642
27369
|
* Creates a multihash digest.
|
|
27643
27370
|
*/
|
|
27644
|
-
constructor(code32, size2,
|
|
27371
|
+
constructor(code32, size2, digest4, bytes22) {
|
|
27645
27372
|
__publicField(this, "code");
|
|
27646
27373
|
__publicField(this, "size");
|
|
27647
27374
|
__publicField(this, "digest");
|
|
27648
27375
|
__publicField(this, "bytes");
|
|
27649
27376
|
this.code = code32;
|
|
27650
27377
|
this.size = size2;
|
|
27651
|
-
this.digest =
|
|
27378
|
+
this.digest = digest4;
|
|
27652
27379
|
this.bytes = bytes22;
|
|
27653
27380
|
}
|
|
27654
27381
|
};
|
|
@@ -27712,8 +27439,8 @@ var init_dist4 = __esm({
|
|
|
27712
27439
|
toV1() {
|
|
27713
27440
|
switch (this.version) {
|
|
27714
27441
|
case 0: {
|
|
27715
|
-
const { code: code32, digest:
|
|
27716
|
-
const multihash = create3(code32,
|
|
27442
|
+
const { code: code32, digest: digest4 } = this.multihash;
|
|
27443
|
+
const multihash = create3(code32, digest4);
|
|
27717
27444
|
return _CID3.createV1(this.code, multihash);
|
|
27718
27445
|
}
|
|
27719
27446
|
case 1: {
|
|
@@ -27766,8 +27493,8 @@ var init_dist4 = __esm({
|
|
|
27766
27493
|
return new _CID3(version3, code32, multihash, bytes22 ?? encodeCID3(version3, code32, multihash.bytes));
|
|
27767
27494
|
} else if (value[cidSymbol3] === true) {
|
|
27768
27495
|
const { version: version3, multihash, code: code32 } = value;
|
|
27769
|
-
const
|
|
27770
|
-
return _CID3.create(version3, code32,
|
|
27496
|
+
const digest4 = decode42(multihash);
|
|
27497
|
+
return _CID3.create(version3, code32, digest4);
|
|
27771
27498
|
} else {
|
|
27772
27499
|
return null;
|
|
27773
27500
|
}
|
|
@@ -27777,11 +27504,11 @@ var init_dist4 = __esm({
|
|
|
27777
27504
|
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
|
|
27778
27505
|
* @param digest - (Multi)hash of the of the content.
|
|
27779
27506
|
*/
|
|
27780
|
-
static create(version3, code32,
|
|
27507
|
+
static create(version3, code32, digest4) {
|
|
27781
27508
|
if (typeof code32 !== "number") {
|
|
27782
27509
|
throw new Error("String codecs are no longer supported");
|
|
27783
27510
|
}
|
|
27784
|
-
if (!(
|
|
27511
|
+
if (!(digest4.bytes instanceof Uint8Array)) {
|
|
27785
27512
|
throw new Error("Invalid digest");
|
|
27786
27513
|
}
|
|
27787
27514
|
switch (version3) {
|
|
@@ -27789,12 +27516,12 @@ var init_dist4 = __esm({
|
|
|
27789
27516
|
if (code32 !== DAG_PB_CODE3) {
|
|
27790
27517
|
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE3}) block encoding`);
|
|
27791
27518
|
} else {
|
|
27792
|
-
return new _CID3(version3, code32,
|
|
27519
|
+
return new _CID3(version3, code32, digest4, digest4.bytes);
|
|
27793
27520
|
}
|
|
27794
27521
|
}
|
|
27795
27522
|
case 1: {
|
|
27796
|
-
const bytes22 = encodeCID3(version3, code32,
|
|
27797
|
-
return new _CID3(version3, code32,
|
|
27523
|
+
const bytes22 = encodeCID3(version3, code32, digest4.bytes);
|
|
27524
|
+
return new _CID3(version3, code32, digest4, bytes22);
|
|
27798
27525
|
}
|
|
27799
27526
|
default: {
|
|
27800
27527
|
throw new Error("Invalid version");
|
|
@@ -27804,8 +27531,8 @@ var init_dist4 = __esm({
|
|
|
27804
27531
|
/**
|
|
27805
27532
|
* Simplified version of `create` for CIDv0.
|
|
27806
27533
|
*/
|
|
27807
|
-
static createV0(
|
|
27808
|
-
return _CID3.create(0, DAG_PB_CODE3,
|
|
27534
|
+
static createV0(digest4) {
|
|
27535
|
+
return _CID3.create(0, DAG_PB_CODE3, digest4);
|
|
27809
27536
|
}
|
|
27810
27537
|
/**
|
|
27811
27538
|
* Simplified version of `create` for CIDv1.
|
|
@@ -27813,8 +27540,8 @@ var init_dist4 = __esm({
|
|
|
27813
27540
|
* @param code - Content encoding format code.
|
|
27814
27541
|
* @param digest - Multihash of the content.
|
|
27815
27542
|
*/
|
|
27816
|
-
static createV1(code32,
|
|
27817
|
-
return _CID3.create(1, code32,
|
|
27543
|
+
static createV1(code32, digest4) {
|
|
27544
|
+
return _CID3.create(1, code32, digest4);
|
|
27818
27545
|
}
|
|
27819
27546
|
/**
|
|
27820
27547
|
* Decoded a CID from its binary representation. The byte array must contain
|
|
@@ -27847,8 +27574,8 @@ var init_dist4 = __esm({
|
|
|
27847
27574
|
throw new Error("Incorrect length");
|
|
27848
27575
|
}
|
|
27849
27576
|
const digestBytes3 = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
|
|
27850
|
-
const
|
|
27851
|
-
const cid2 = specs.version === 0 ? _CID3.createV0(
|
|
27577
|
+
const digest4 = new Digest3(specs.multihashCode, specs.digestSize, digestBytes3, multihashBytes);
|
|
27578
|
+
const cid2 = specs.version === 0 ? _CID3.createV0(digest4) : _CID3.createV1(specs.codec, digest4);
|
|
27852
27579
|
return [cid2, bytes22.subarray(specs.size)];
|
|
27853
27580
|
}
|
|
27854
27581
|
/**
|
|
@@ -27904,7 +27631,7 @@ var init_dist4 = __esm({
|
|
|
27904
27631
|
DAG_PB_CODE3 = 112;
|
|
27905
27632
|
SHA_256_CODE3 = 18;
|
|
27906
27633
|
cidSymbol3 = /* @__PURE__ */ Symbol.for("@ipld/js-cid/CID");
|
|
27907
|
-
|
|
27634
|
+
textEncoder2 = new TextEncoder();
|
|
27908
27635
|
objectHasOwn2 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
|
|
27909
27636
|
Object.prototype.hasOwnProperty
|
|
27910
27637
|
);
|
|
@@ -28034,7 +27761,7 @@ var init_dist4 = __esm({
|
|
|
28034
27761
|
encode: (buf) => toString(buf),
|
|
28035
27762
|
decode: (str) => fromString(str)
|
|
28036
27763
|
});
|
|
28037
|
-
|
|
27764
|
+
textEncoder22 = new TextEncoder();
|
|
28038
27765
|
textDecoder = new TextDecoder();
|
|
28039
27766
|
identity_exports2 = {};
|
|
28040
27767
|
__export3(identity_exports2, {
|
|
@@ -28043,7 +27770,7 @@ var init_dist4 = __esm({
|
|
|
28043
27770
|
code22 = 0;
|
|
28044
27771
|
name = "identity";
|
|
28045
27772
|
encode42 = coerce4;
|
|
28046
|
-
identity2 = { code: code22, name, encode: encode42, digest
|
|
27773
|
+
identity2 = { code: code22, name, encode: encode42, digest };
|
|
28047
27774
|
sha2_browser_exports = {};
|
|
28048
27775
|
__export3(sha2_browser_exports, {
|
|
28049
27776
|
sha256: () => sha25622,
|
|
@@ -28077,7 +27804,7 @@ var init_dist4 = __esm({
|
|
|
28077
27804
|
if (result instanceof Uint8Array) {
|
|
28078
27805
|
return createDigest(result, this.code, options2?.truncate);
|
|
28079
27806
|
}
|
|
28080
|
-
return result.then((
|
|
27807
|
+
return result.then((digest4) => createDigest(digest4, this.code, options2?.truncate));
|
|
28081
27808
|
} else {
|
|
28082
27809
|
throw Error("Unknown type, must be binary type");
|
|
28083
27810
|
}
|
|
@@ -29165,7 +28892,6 @@ var init_dist4 = __esm({
|
|
|
29165
28892
|
/** Expiration for delegated access */
|
|
29166
28893
|
expiresAt: external_exports.string().optional()
|
|
29167
28894
|
});
|
|
29168
|
-
inFlightActivations = /* @__PURE__ */ new Map();
|
|
29169
28895
|
AutoApproveSpaceCreationHandler = class {
|
|
29170
28896
|
/**
|
|
29171
28897
|
* Always returns true to auto-approve space creation.
|
|
@@ -30658,385 +30384,6 @@ var init_sdk = __esm({
|
|
|
30658
30384
|
}
|
|
30659
30385
|
});
|
|
30660
30386
|
|
|
30661
|
-
// src/auth/local-key.ts
|
|
30662
|
-
import { TCWSessionManager, importKey, initPanicHook } from "@tinycloud/node-sdk-wasm";
|
|
30663
|
-
import { PrivateKeySigner } from "@tinycloud/node-sdk";
|
|
30664
|
-
import { randomBytes as randomBytes3 } from "crypto";
|
|
30665
|
-
function ensureWasm() {
|
|
30666
|
-
if (!wasmInitialized) {
|
|
30667
|
-
initPanicHook();
|
|
30668
|
-
wasmInitialized = true;
|
|
30669
|
-
}
|
|
30670
|
-
}
|
|
30671
|
-
function generateKey2() {
|
|
30672
|
-
ensureWasm();
|
|
30673
|
-
const mgr = new TCWSessionManager();
|
|
30674
|
-
const keyId = mgr.createSessionKey("cli");
|
|
30675
|
-
const jwkStr = mgr.jwk(keyId);
|
|
30676
|
-
if (!jwkStr) throw new Error("Failed to generate key");
|
|
30677
|
-
const jwk = JSON.parse(jwkStr);
|
|
30678
|
-
const did = mgr.getDID(keyId);
|
|
30679
|
-
return { jwk, did };
|
|
30680
|
-
}
|
|
30681
|
-
function keyToDID(jwk) {
|
|
30682
|
-
ensureWasm();
|
|
30683
|
-
const mgr = new TCWSessionManager();
|
|
30684
|
-
const keyId = importKey(mgr, JSON.stringify(jwk), "imported");
|
|
30685
|
-
return mgr.getDID(keyId);
|
|
30686
|
-
}
|
|
30687
|
-
var wasmInitialized;
|
|
30688
|
-
var init_local_key = __esm({
|
|
30689
|
-
"src/auth/local-key.ts"() {
|
|
30690
|
-
"use strict";
|
|
30691
|
-
wasmInitialized = false;
|
|
30692
|
-
}
|
|
30693
|
-
});
|
|
30694
|
-
|
|
30695
|
-
// src/auth/browser-auth.ts
|
|
30696
|
-
import { createServer } from "http";
|
|
30697
|
-
import { createInterface } from "readline";
|
|
30698
|
-
function publicJwkForDelegation(jwk) {
|
|
30699
|
-
const publicJwk = {};
|
|
30700
|
-
for (const [key, value] of Object.entries(jwk)) {
|
|
30701
|
-
if (!PRIVATE_JWK_FIELDS.has(key)) {
|
|
30702
|
-
publicJwk[key] = value;
|
|
30703
|
-
}
|
|
30704
|
-
}
|
|
30705
|
-
return publicJwk;
|
|
30706
|
-
}
|
|
30707
|
-
function validateDelegationCallbackPayload(value) {
|
|
30708
|
-
if (!value || typeof value !== "object") return "expected an object";
|
|
30709
|
-
const v = value;
|
|
30710
|
-
if (!v.delegationHeader || typeof v.delegationHeader !== "object") {
|
|
30711
|
-
return "delegationHeader must be an object";
|
|
30712
|
-
}
|
|
30713
|
-
const auth = v.delegationHeader.Authorization;
|
|
30714
|
-
if (typeof auth !== "string" || !auth) {
|
|
30715
|
-
return "delegationHeader.Authorization must be a non-empty string";
|
|
30716
|
-
}
|
|
30717
|
-
if (typeof v.delegationCid !== "string" || !v.delegationCid) {
|
|
30718
|
-
return "delegationCid must be a non-empty string";
|
|
30719
|
-
}
|
|
30720
|
-
if (typeof v.spaceId !== "string" || !v.spaceId) {
|
|
30721
|
-
return "spaceId must be a non-empty string";
|
|
30722
|
-
}
|
|
30723
|
-
if (v.permissions !== void 0) {
|
|
30724
|
-
if (!Array.isArray(v.permissions)) {
|
|
30725
|
-
return "permissions, when present, must be an array";
|
|
30726
|
-
}
|
|
30727
|
-
for (let i = 0; i < v.permissions.length; i++) {
|
|
30728
|
-
const entry = v.permissions[i];
|
|
30729
|
-
if (!entry || typeof entry !== "object") {
|
|
30730
|
-
return `permissions[${i}] must be an object`;
|
|
30731
|
-
}
|
|
30732
|
-
const e = entry;
|
|
30733
|
-
if (typeof e.service !== "string" || !e.service) {
|
|
30734
|
-
return `permissions[${i}].service must be a non-empty string`;
|
|
30735
|
-
}
|
|
30736
|
-
if (typeof e.space !== "string") {
|
|
30737
|
-
return `permissions[${i}].space must be a string`;
|
|
30738
|
-
}
|
|
30739
|
-
if (typeof e.path !== "string") {
|
|
30740
|
-
return `permissions[${i}].path must be a string`;
|
|
30741
|
-
}
|
|
30742
|
-
if (!Array.isArray(e.actions) || e.actions.some((a) => typeof a !== "string" || !a)) {
|
|
30743
|
-
return `permissions[${i}].actions must be a non-empty string[]`;
|
|
30744
|
-
}
|
|
30745
|
-
}
|
|
30746
|
-
}
|
|
30747
|
-
return null;
|
|
30748
|
-
}
|
|
30749
|
-
var PRIVATE_JWK_FIELDS;
|
|
30750
|
-
var init_browser_auth = __esm({
|
|
30751
|
-
"src/auth/browser-auth.ts"() {
|
|
30752
|
-
"use strict";
|
|
30753
|
-
init_formatter();
|
|
30754
|
-
init_constants();
|
|
30755
|
-
PRIVATE_JWK_FIELDS = /* @__PURE__ */ new Set([
|
|
30756
|
-
"d",
|
|
30757
|
-
"p",
|
|
30758
|
-
"q",
|
|
30759
|
-
"dp",
|
|
30760
|
-
"dq",
|
|
30761
|
-
"qi",
|
|
30762
|
-
"oth",
|
|
30763
|
-
"k"
|
|
30764
|
-
]);
|
|
30765
|
-
}
|
|
30766
|
-
});
|
|
30767
|
-
|
|
30768
|
-
// src/auth/device-auth.ts
|
|
30769
|
-
var device_auth_exports = {};
|
|
30770
|
-
__export(device_auth_exports, {
|
|
30771
|
-
SHARE_DEVICE_DELEGATION_SECONDS: () => SHARE_DEVICE_DELEGATION_SECONDS,
|
|
30772
|
-
SHARE_DEVICE_PERMISSIONS: () => SHARE_DEVICE_PERMISSIONS,
|
|
30773
|
-
acquireShareDeviceDelegation: () => acquireShareDeviceDelegation,
|
|
30774
|
-
ensureShareDeviceAuthorization: () => ensureShareDeviceAuthorization,
|
|
30775
|
-
mergePrivateJwkIntoSession: () => mergePrivateJwkIntoSession
|
|
30776
|
-
});
|
|
30777
|
-
import {
|
|
30778
|
-
createDecipheriv,
|
|
30779
|
-
createHash,
|
|
30780
|
-
createHmac,
|
|
30781
|
-
createPublicKey,
|
|
30782
|
-
diffieHellman,
|
|
30783
|
-
generateKeyPairSync,
|
|
30784
|
-
randomBytes as randomBytes4
|
|
30785
|
-
} from "crypto";
|
|
30786
|
-
function digest4(value) {
|
|
30787
|
-
return createHash("sha256").update(value).digest("base64url");
|
|
30788
|
-
}
|
|
30789
|
-
function canonicalOrigin(value, label) {
|
|
30790
|
-
const url = new URL(value);
|
|
30791
|
-
const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost";
|
|
30792
|
-
if (url.origin !== value || url.protocol !== "https:" && !(loopback && url.protocol === "http:")) {
|
|
30793
|
-
throw new Error(`${label} must be a canonical HTTPS origin`);
|
|
30794
|
-
}
|
|
30795
|
-
return value;
|
|
30796
|
-
}
|
|
30797
|
-
function jsonEqual(left, right) {
|
|
30798
|
-
const canonical = (value) => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, canonical(entry)])) : value;
|
|
30799
|
-
return JSON.stringify(canonical(left)) === JSON.stringify(canonical(right));
|
|
30800
|
-
}
|
|
30801
|
-
function validateStart(value) {
|
|
30802
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("OpenKey returned an invalid device authorization response");
|
|
30803
|
-
const result = value;
|
|
30804
|
-
if (typeof result.transactionId !== "string" || !/^[A-Za-z0-9_-]{20,}$/.test(result.transactionId) || typeof result.userCode !== "string" || !/^[A-Z2-9]{4}-[A-Z2-9]{4}$/.test(result.userCode) || typeof result.verificationUri !== "string" || typeof result.verificationUriComplete !== "string" || !Number.isSafeInteger(result.expiresIn) || Number(result.expiresIn) < 60 || !Number.isSafeInteger(result.interval) || Number(result.interval) < 1) throw new Error("OpenKey returned an invalid device authorization response");
|
|
30805
|
-
canonicalOrigin(new URL(result.verificationUri).origin, "verification URI");
|
|
30806
|
-
if (new URL(result.verificationUriComplete).origin !== new URL(result.verificationUri).origin) {
|
|
30807
|
-
throw new Error("OpenKey returned an invalid verification URI");
|
|
30808
|
-
}
|
|
30809
|
-
return result;
|
|
30810
|
-
}
|
|
30811
|
-
async function responseJson(response) {
|
|
30812
|
-
try {
|
|
30813
|
-
return await response.json();
|
|
30814
|
-
} catch {
|
|
30815
|
-
throw new Error(`OpenKey device authorization failed (HTTP ${response.status})`);
|
|
30816
|
-
}
|
|
30817
|
-
}
|
|
30818
|
-
function errorCode(value) {
|
|
30819
|
-
return value && typeof value === "object" && typeof value.error === "string" ? value.error : void 0;
|
|
30820
|
-
}
|
|
30821
|
-
function publicSessionJwk(value) {
|
|
30822
|
-
const publicJwk = publicJwkForDelegation(value);
|
|
30823
|
-
const record2 = publicJwk;
|
|
30824
|
-
if (record2.kty !== "OKP" || record2.crv !== "Ed25519" || typeof record2.x !== "string") {
|
|
30825
|
-
throw new Error("CLI session key is not a public Ed25519 JWK");
|
|
30826
|
-
}
|
|
30827
|
-
return publicJwk;
|
|
30828
|
-
}
|
|
30829
|
-
function publicRelayJwk(value) {
|
|
30830
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("OpenKey returned an invalid relay key");
|
|
30831
|
-
const jwk = value;
|
|
30832
|
-
if (jwk.kty !== "EC" || jwk.crv !== "P-256" || typeof jwk.x !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x) || typeof jwk.y !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(jwk.y) || "d" in jwk) throw new Error("OpenKey returned an invalid relay key");
|
|
30833
|
-
return { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y };
|
|
30834
|
-
}
|
|
30835
|
-
function decodeCanonicalBase64Url(value, label) {
|
|
30836
|
-
if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error(`OpenKey returned an invalid ${label}`);
|
|
30837
|
-
const decoded = Buffer.from(value, "base64url");
|
|
30838
|
-
if (decoded.toString("base64url") !== value) throw new Error(`OpenKey returned an invalid ${label}`);
|
|
30839
|
-
return decoded;
|
|
30840
|
-
}
|
|
30841
|
-
function deriveRelayKey(sharedSecret, transactionId) {
|
|
30842
|
-
const extracted = createHmac("sha256", Buffer.from(transactionId)).update(sharedSecret).digest();
|
|
30843
|
-
return createHmac("sha256", extracted).update(Buffer.from("openkey-device-relay-v1")).update(Buffer.from([1])).digest();
|
|
30844
|
-
}
|
|
30845
|
-
function decryptRelayResult(envelope, transactionId, privateKey) {
|
|
30846
|
-
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) throw new Error("OpenKey returned an invalid encrypted relay result");
|
|
30847
|
-
const relay = envelope;
|
|
30848
|
-
if (relay.version !== 1 || relay.algorithm !== "ECDH-P256-A256GCM") throw new Error("OpenKey returned an unsupported encrypted relay result");
|
|
30849
|
-
const peer = createPublicKey({ key: publicRelayJwk(relay.ephemeralPublicJwk), format: "jwk" });
|
|
30850
|
-
const nonce = decodeCanonicalBase64Url(relay.nonce, "relay nonce");
|
|
30851
|
-
const ciphertext = decodeCanonicalBase64Url(relay.ciphertext, "relay ciphertext");
|
|
30852
|
-
if (nonce.length !== 12 || ciphertext.length <= 16) throw new Error("OpenKey returned an invalid encrypted relay result");
|
|
30853
|
-
const sharedSecret = diffieHellman({ privateKey, publicKey: peer });
|
|
30854
|
-
const key = deriveRelayKey(sharedSecret, transactionId);
|
|
30855
|
-
const decipher = createDecipheriv("aes-256-gcm", key, nonce);
|
|
30856
|
-
decipher.setAAD(Buffer.from(transactionId));
|
|
30857
|
-
decipher.setAuthTag(ciphertext.subarray(ciphertext.length - 16));
|
|
30858
|
-
let value;
|
|
30859
|
-
try {
|
|
30860
|
-
value = JSON.parse(Buffer.concat([decipher.update(ciphertext.subarray(0, -16)), decipher.final()]).toString("utf8"));
|
|
30861
|
-
} catch {
|
|
30862
|
-
throw new Error("OpenKey returned an unreadable encrypted relay result");
|
|
30863
|
-
}
|
|
30864
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("OpenKey returned an invalid encrypted relay result");
|
|
30865
|
-
return value;
|
|
30866
|
-
}
|
|
30867
|
-
function assertShareDelegationPermissions(value) {
|
|
30868
|
-
if (!Array.isArray(value) || value.length !== 1) throw new Error("OpenKey returned a delegation outside the requested Share scope");
|
|
30869
|
-
const permission = value[0];
|
|
30870
|
-
if (!permission || permission.service !== "tinycloud.capabilities" && permission.service !== "capabilities" || permission.space !== "applications" && !(typeof permission.space === "string" && permission.space.endsWith(":applications")) || permission.path !== "" || !Array.isArray(permission.actions) || permission.actions.length !== 1 || permission.actions[0] !== "tinycloud.capabilities/read") throw new Error("OpenKey returned a delegation outside the requested Share scope");
|
|
30871
|
-
}
|
|
30872
|
-
function assertApprovedBinding(input) {
|
|
30873
|
-
if (input.binding.transactionId !== input.transactionId || input.binding.sessionDid !== input.sessionDid || input.binding.nodeOrigin !== input.nodeOrigin || input.binding.shareOrigin !== input.shareOrigin || !jsonEqual(input.binding.permissions, SHARE_DEVICE_PERMISSIONS)) throw new Error("OpenKey returned a delegation with the wrong device binding");
|
|
30874
|
-
const expiresAt = Date.parse(input.binding.delegationExpiresAt);
|
|
30875
|
-
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || expiresAt > Date.now() + SHARE_DEVICE_DELEGATION_SECONDS * 1e3 + 3e4) {
|
|
30876
|
-
throw new Error("OpenKey returned a delegation outside the requested expiry window");
|
|
30877
|
-
}
|
|
30878
|
-
if (input.delegation.verificationMethod !== input.sessionDid) {
|
|
30879
|
-
throw new Error("OpenKey returned a delegation for a different CLI session DID");
|
|
30880
|
-
}
|
|
30881
|
-
assertShareDelegationPermissions(input.delegation.permissions);
|
|
30882
|
-
const delegationExpiryValue = input.delegation.expiresAt ?? input.delegation.expirationTime ?? input.delegation.expiry;
|
|
30883
|
-
const delegationExpiresAt = typeof delegationExpiryValue === "string" ? Date.parse(delegationExpiryValue) : Number.NaN;
|
|
30884
|
-
if (!Number.isFinite(delegationExpiresAt) || delegationExpiresAt !== expiresAt) {
|
|
30885
|
-
throw new Error("OpenKey returned a delegation outside the approved expiry window");
|
|
30886
|
-
}
|
|
30887
|
-
if (!input.delegation.jwk || typeof input.delegation.jwk !== "object" || !jsonEqual(publicSessionJwk(input.delegation.jwk), input.publicJwk)) {
|
|
30888
|
-
throw new Error("OpenKey returned a delegation for a different CLI session key");
|
|
30889
|
-
}
|
|
30890
|
-
const invalid = validateDelegationCallbackPayload(input.delegation);
|
|
30891
|
-
if (invalid) throw new Error(`OpenKey returned an invalid delegation: ${invalid}`);
|
|
30892
|
-
}
|
|
30893
|
-
async function acquireShareDeviceDelegation(input) {
|
|
30894
|
-
const openkeyHost = canonicalOrigin(input.openkeyHost ?? DEFAULT_OPENKEY_DEVICE_API_HOST, "OpenKey host");
|
|
30895
|
-
const nodeOrigin = canonicalOrigin(input.nodeOrigin, "TinyCloud node origin");
|
|
30896
|
-
const shareOrigin = canonicalOrigin(input.shareOrigin, "Share origin");
|
|
30897
|
-
const fetchFn = input.fetchFn ?? globalThis.fetch;
|
|
30898
|
-
const deviceSecret = randomBytes4(32).toString("base64url");
|
|
30899
|
-
const codeVerifier = randomBytes4(32).toString("base64url");
|
|
30900
|
-
const relayKeys = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
|
|
30901
|
-
const relayPublicJwk = publicRelayJwk(relayKeys.publicKey.export({ format: "jwk" }));
|
|
30902
|
-
const publicJwk = publicSessionJwk(input.jwk);
|
|
30903
|
-
const startResponse = await fetchFn(`${openkeyHost}/api/device-authorizations`, {
|
|
30904
|
-
method: "POST",
|
|
30905
|
-
credentials: "omit",
|
|
30906
|
-
redirect: "error",
|
|
30907
|
-
referrerPolicy: "no-referrer",
|
|
30908
|
-
headers: { accept: "application/json", "content-type": "application/json" },
|
|
30909
|
-
body: JSON.stringify({
|
|
30910
|
-
deviceSecretHash: digest4(deviceSecret),
|
|
30911
|
-
codeChallenge: digest4(codeVerifier),
|
|
30912
|
-
relayPublicJwk,
|
|
30913
|
-
sessionDid: input.sessionDid,
|
|
30914
|
-
publicJwk,
|
|
30915
|
-
permissions: SHARE_DEVICE_PERMISSIONS,
|
|
30916
|
-
nodeOrigin,
|
|
30917
|
-
shareOrigin,
|
|
30918
|
-
delegationTtlSeconds: SHARE_DEVICE_DELEGATION_SECONDS
|
|
30919
|
-
})
|
|
30920
|
-
});
|
|
30921
|
-
const startValue = await responseJson(startResponse);
|
|
30922
|
-
if (!startResponse.ok) throw new Error(`OpenKey device authorization failed: ${errorCode(startValue) ?? startResponse.status}`);
|
|
30923
|
-
const started = validateStart(startValue);
|
|
30924
|
-
(input.emitInstructions ?? ((value) => {
|
|
30925
|
-
process.stderr.write(`OpenKey device authorization
|
|
30926
|
-
Visit: ${value.verificationUri}
|
|
30927
|
-
Code: ${value.userCode}
|
|
30928
|
-
|
|
30929
|
-
Waiting for approval\u2026
|
|
30930
|
-
`);
|
|
30931
|
-
}))({ verificationUri: started.verificationUri, verificationUriComplete: started.verificationUriComplete, userCode: started.userCode });
|
|
30932
|
-
const deadline = Date.now() + started.expiresIn * 1e3;
|
|
30933
|
-
let interval = started.interval;
|
|
30934
|
-
const wait = input.wait ?? ((milliseconds) => new Promise((resolve2) => setTimeout(resolve2, milliseconds)));
|
|
30935
|
-
while (Date.now() < deadline) {
|
|
30936
|
-
await wait(interval * 1e3);
|
|
30937
|
-
const response = await fetchFn(`${openkeyHost}/api/device-authorizations/token`, {
|
|
30938
|
-
method: "POST",
|
|
30939
|
-
credentials: "omit",
|
|
30940
|
-
redirect: "error",
|
|
30941
|
-
referrerPolicy: "no-referrer",
|
|
30942
|
-
headers: { accept: "application/json", "content-type": "application/json" },
|
|
30943
|
-
body: JSON.stringify({ transactionId: started.transactionId, deviceSecret, codeVerifier })
|
|
30944
|
-
});
|
|
30945
|
-
const value = await responseJson(response);
|
|
30946
|
-
const code4 = errorCode(value);
|
|
30947
|
-
if (response.status === 429 && code4 === "slow_down") {
|
|
30948
|
-
interval += 1;
|
|
30949
|
-
continue;
|
|
30950
|
-
}
|
|
30951
|
-
if (!response.ok) throw new Error(`OpenKey device authorization failed: ${code4 ?? response.status}`);
|
|
30952
|
-
const result = value;
|
|
30953
|
-
if (result.status === "pending") {
|
|
30954
|
-
interval = Math.max(interval, result.interval);
|
|
30955
|
-
continue;
|
|
30956
|
-
}
|
|
30957
|
-
if (result.status !== "approved" || !result.relay || !result.binding) {
|
|
30958
|
-
throw new Error("OpenKey returned an invalid device authorization result");
|
|
30959
|
-
}
|
|
30960
|
-
const delegation = decryptRelayResult(result.relay, started.transactionId, relayKeys.privateKey);
|
|
30961
|
-
assertApprovedBinding({ binding: result.binding, transactionId: started.transactionId, sessionDid: input.sessionDid, nodeOrigin, shareOrigin, publicJwk, delegation });
|
|
30962
|
-
return delegation;
|
|
30963
|
-
}
|
|
30964
|
-
throw new Error("OpenKey device authorization expired before approval");
|
|
30965
|
-
}
|
|
30966
|
-
function mergePrivateJwkIntoSession(session, key) {
|
|
30967
|
-
const sessionJwk = session.jwk;
|
|
30968
|
-
if (!sessionJwk || typeof sessionJwk !== "object") return session;
|
|
30969
|
-
const sessionJwkRecord = sessionJwk;
|
|
30970
|
-
if (typeof sessionJwkRecord.d === "string" && sessionJwkRecord.d.length > 0) return session;
|
|
30971
|
-
const privateParameter = key.d;
|
|
30972
|
-
if (typeof privateParameter !== "string" || privateParameter.length === 0) return session;
|
|
30973
|
-
return { ...session, jwk: { ...sessionJwkRecord, d: privateParameter } };
|
|
30974
|
-
}
|
|
30975
|
-
async function ensureShareDeviceAuthorization(input) {
|
|
30976
|
-
let profile = await ProfileManager.getProfile(input.profileName).catch(() => null);
|
|
30977
|
-
if (profile?.authMethod === "local" && input.allowReplaceLocal !== true) {
|
|
30978
|
-
throw new Error("This profile uses a local owner key. Run `tc auth login --device` explicitly to replace its authentication posture.");
|
|
30979
|
-
}
|
|
30980
|
-
let key = await ProfileManager.getKey(input.profileName);
|
|
30981
|
-
if (!key) {
|
|
30982
|
-
const generated = generateKey2();
|
|
30983
|
-
key = generated.jwk;
|
|
30984
|
-
await ProfileManager.setKey(input.profileName, key);
|
|
30985
|
-
}
|
|
30986
|
-
const sessionDid = keyToDID(key);
|
|
30987
|
-
profile = {
|
|
30988
|
-
...profile,
|
|
30989
|
-
name: input.profileName,
|
|
30990
|
-
host: input.nodeOrigin,
|
|
30991
|
-
chainId: profile?.chainId ?? DEFAULT_CHAIN_ID,
|
|
30992
|
-
spaceName: profile?.spaceName ?? "applications",
|
|
30993
|
-
did: sessionDid,
|
|
30994
|
-
sessionDid,
|
|
30995
|
-
createdAt: profile?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
30996
|
-
posture: "owner-openkey",
|
|
30997
|
-
operatorType: profile?.operatorType ?? "human",
|
|
30998
|
-
authMethod: "openkey",
|
|
30999
|
-
openkeyHost: input.openkeyHost ?? profile?.openkeyHost
|
|
31000
|
-
};
|
|
31001
|
-
await ProfileManager.setProfile(input.profileName, profile);
|
|
31002
|
-
const delegation = await acquireShareDeviceDelegation({
|
|
31003
|
-
sessionDid,
|
|
31004
|
-
jwk: key,
|
|
31005
|
-
nodeOrigin: input.nodeOrigin,
|
|
31006
|
-
shareOrigin: input.shareOrigin,
|
|
31007
|
-
openkeyHost: input.openkeyHost ?? profile.openkeyHost,
|
|
31008
|
-
fetchFn: input.fetchFn,
|
|
31009
|
-
emitInstructions: input.emitInstructions,
|
|
31010
|
-
wait: input.wait
|
|
31011
|
-
});
|
|
31012
|
-
const session = mergePrivateJwkIntoSession(delegation, key);
|
|
31013
|
-
await ProfileManager.setSession(input.profileName, session);
|
|
31014
|
-
const updatedProfile = {
|
|
31015
|
-
...profile,
|
|
31016
|
-
ownerDid: typeof session.ownerDid === "string" ? session.ownerDid : profile.ownerDid,
|
|
31017
|
-
spaceId: typeof session.spaceId === "string" ? session.spaceId : profile.spaceId
|
|
31018
|
-
};
|
|
31019
|
-
await ProfileManager.setProfile(input.profileName, updatedProfile);
|
|
31020
|
-
return { profile: updatedProfile, delegation: session };
|
|
31021
|
-
}
|
|
31022
|
-
var SHARE_DEVICE_DELEGATION_SECONDS, SHARE_DEVICE_PERMISSIONS;
|
|
31023
|
-
var init_device_auth = __esm({
|
|
31024
|
-
"src/auth/device-auth.ts"() {
|
|
31025
|
-
"use strict";
|
|
31026
|
-
init_constants();
|
|
31027
|
-
init_profiles();
|
|
31028
|
-
init_local_key();
|
|
31029
|
-
init_browser_auth();
|
|
31030
|
-
SHARE_DEVICE_DELEGATION_SECONDS = 30 * 24 * 60 * 60;
|
|
31031
|
-
SHARE_DEVICE_PERMISSIONS = [{
|
|
31032
|
-
service: "tinycloud.capabilities",
|
|
31033
|
-
space: "applications",
|
|
31034
|
-
path: "",
|
|
31035
|
-
actions: ["tinycloud.capabilities/read"]
|
|
31036
|
-
}];
|
|
31037
|
-
}
|
|
31038
|
-
});
|
|
31039
|
-
|
|
31040
30387
|
// src/index.ts
|
|
31041
30388
|
init_errors();
|
|
31042
30389
|
import { readFileSync as readFileSync2 } from "fs";
|
|
@@ -31221,16 +30568,16 @@ async function readBoundedStdin(limit = MAX_SHARE_STDIN_BYTES) {
|
|
|
31221
30568
|
const chunks = [];
|
|
31222
30569
|
let total = 0;
|
|
31223
30570
|
for await (const chunk of process.stdin) {
|
|
31224
|
-
const
|
|
31225
|
-
total +=
|
|
30571
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
30572
|
+
total += bytes.byteLength;
|
|
31226
30573
|
if (total > limit) throw new Error("MAX_BYTES_EXCEEDED");
|
|
31227
|
-
chunks.push(
|
|
30574
|
+
chunks.push(bytes);
|
|
31228
30575
|
}
|
|
31229
30576
|
return new Uint8Array(Buffer.concat(chunks, total));
|
|
31230
30577
|
}
|
|
31231
30578
|
async function readBoundedUrlStdin() {
|
|
31232
|
-
const
|
|
31233
|
-
const value = new TextDecoder("utf-8", { fatal: true }).decode(
|
|
30579
|
+
const bytes = await readBoundedStdin(MAX_SHARE_URL_BYTES);
|
|
30580
|
+
const value = new TextDecoder("utf-8", { fatal: true }).decode(bytes).trim();
|
|
31234
30581
|
if (value.length === 0 || /\s/.test(value)) throw new Error("INVALID_ARGUMENT");
|
|
31235
30582
|
return value;
|
|
31236
30583
|
}
|
|
@@ -31243,16 +30590,16 @@ function shareFilename(value) {
|
|
|
31243
30590
|
}
|
|
31244
30591
|
async function readShareInput(input, name2, limit = MAX_SHARE_STDIN_BYTES) {
|
|
31245
30592
|
if (input === "-") {
|
|
31246
|
-
const
|
|
31247
|
-
return { bytes:
|
|
30593
|
+
const bytes3 = await readBoundedStdin(limit);
|
|
30594
|
+
return { bytes: bytes3, filename: shareFilename(name2 ?? "stdin.md") };
|
|
31248
30595
|
}
|
|
31249
30596
|
const path = resolve(input);
|
|
31250
30597
|
const info = await stat2(path);
|
|
31251
30598
|
if (!info.isFile() || info.size > limit) throw new Error("MAX_BYTES_EXCEEDED");
|
|
31252
30599
|
const filename = shareFilename(name2 ?? basename2(path));
|
|
31253
|
-
const
|
|
31254
|
-
if (
|
|
31255
|
-
return { bytes
|
|
30600
|
+
const bytes = new Uint8Array(await readFile2(path));
|
|
30601
|
+
if (bytes.byteLength > limit) throw new Error("MAX_BYTES_EXCEEDED");
|
|
30602
|
+
return { bytes, filename };
|
|
31256
30603
|
}
|
|
31257
30604
|
async function assertDirectory(path) {
|
|
31258
30605
|
const absolute = resolve(path);
|
|
@@ -31275,7 +30622,7 @@ async function assertDirectory(path) {
|
|
|
31275
30622
|
}
|
|
31276
30623
|
}
|
|
31277
30624
|
}
|
|
31278
|
-
async function writeShareOutput(directory, filename,
|
|
30625
|
+
async function writeShareOutput(directory, filename, bytes, force) {
|
|
31279
30626
|
const outputDirectory = resolve(directory);
|
|
31280
30627
|
await assertDirectory(outputDirectory);
|
|
31281
30628
|
const safeName = safeFilename(filename);
|
|
@@ -31304,7 +30651,7 @@ async function writeShareOutput(directory, filename, bytes3, force) {
|
|
|
31304
30651
|
}
|
|
31305
30652
|
temporaryPath = stagingPath;
|
|
31306
30653
|
handle = await open2(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 384);
|
|
31307
|
-
await handle.writeFile(
|
|
30654
|
+
await handle.writeFile(bytes);
|
|
31308
30655
|
await handle.close();
|
|
31309
30656
|
handle = void 0;
|
|
31310
30657
|
await assertStableDirectory();
|
|
@@ -31523,12 +30870,12 @@ function registerShareCommand(program2) {
|
|
|
31523
30870
|
const proof = await authorizationProof(options);
|
|
31524
30871
|
if (options.legacy) {
|
|
31525
30872
|
if (!isLegacyShareLink(link2) || shareServices.legacyReader === void 0) throw new CLIError("UNSUPPORTED_LINK", "legacy receive requires an installed read-only tc1 adapter", 2);
|
|
31526
|
-
const
|
|
30873
|
+
const bytes = await receiveLegacyShare(link2, shareServices.legacyReader);
|
|
31527
30874
|
if (options.stdout) {
|
|
31528
|
-
process.stdout.write(Buffer.from(
|
|
30875
|
+
process.stdout.write(Buffer.from(bytes));
|
|
31529
30876
|
return;
|
|
31530
30877
|
}
|
|
31531
|
-
const output2 = await writeShareOutput(options.output ?? ".", "share.md",
|
|
30878
|
+
const output2 = await writeShareOutput(options.output ?? ".", "share.md", bytes, options.force === true);
|
|
31532
30879
|
if (json) writeJson2({ protocol: "tinycloud-share", version: 1, legacy: true, path: output2 });
|
|
31533
30880
|
else receiveHuman(output2);
|
|
31534
30881
|
return;
|
|
@@ -31571,10 +30918,10 @@ function registerShareCommand(program2) {
|
|
|
31571
30918
|
const migrated = await migrateShare({
|
|
31572
30919
|
link: link2,
|
|
31573
30920
|
reader: shareServices.legacyReader,
|
|
31574
|
-
publish: async (
|
|
31575
|
-
if (
|
|
30921
|
+
publish: async (bytes) => {
|
|
30922
|
+
if (bytes.byteLength > maxBytes) throw new SharePublishError("max-bytes-exceeded", "legacy content exceeds the configured byte limit");
|
|
31576
30923
|
const result = await publishTargetShare({
|
|
31577
|
-
source:
|
|
30924
|
+
source: bytes,
|
|
31578
30925
|
filename: options.name,
|
|
31579
30926
|
mediaType: "text/markdown",
|
|
31580
30927
|
target: parseShareTarget(options.to),
|
|
@@ -31668,7 +31015,7 @@ init_profiles();
|
|
|
31668
31015
|
init_dist3();
|
|
31669
31016
|
import { readFile as readFile5, writeFile as writeFile2 } from "fs/promises";
|
|
31670
31017
|
import { join as join6 } from "path";
|
|
31671
|
-
import { createHash
|
|
31018
|
+
import { createHash } from "crypto";
|
|
31672
31019
|
|
|
31673
31020
|
// ../share-envelope/dist/index.js
|
|
31674
31021
|
init_zod();
|
|
@@ -31842,9 +31189,9 @@ var Encoder4 = class {
|
|
|
31842
31189
|
this.prefix = prefix;
|
|
31843
31190
|
this.baseEncode = baseEncode;
|
|
31844
31191
|
}
|
|
31845
|
-
encode(
|
|
31846
|
-
if (
|
|
31847
|
-
return `${this.prefix}${this.baseEncode(
|
|
31192
|
+
encode(bytes) {
|
|
31193
|
+
if (bytes instanceof Uint8Array) {
|
|
31194
|
+
return `${this.prefix}${this.baseEncode(bytes)}`;
|
|
31848
31195
|
} else {
|
|
31849
31196
|
throw Error("Unknown type, must be binary type");
|
|
31850
31197
|
}
|
|
@@ -32149,25 +31496,25 @@ function encodeTo4(int, target, offset = 0) {
|
|
|
32149
31496
|
function encodingLength4(int) {
|
|
32150
31497
|
return varint_default4.encodingLength(int);
|
|
32151
31498
|
}
|
|
32152
|
-
function create4(code23,
|
|
32153
|
-
const size2 =
|
|
31499
|
+
function create4(code23, digest2) {
|
|
31500
|
+
const size2 = digest2.byteLength;
|
|
32154
31501
|
const sizeOffset = encodingLength4(code23);
|
|
32155
31502
|
const digestOffset = sizeOffset + encodingLength4(size2);
|
|
32156
|
-
const
|
|
32157
|
-
encodeTo4(code23,
|
|
32158
|
-
encodeTo4(size2,
|
|
32159
|
-
|
|
32160
|
-
return new Digest4(code23, size2,
|
|
31503
|
+
const bytes = new Uint8Array(digestOffset + size2);
|
|
31504
|
+
encodeTo4(code23, bytes, 0);
|
|
31505
|
+
encodeTo4(size2, bytes, sizeOffset);
|
|
31506
|
+
bytes.set(digest2, digestOffset);
|
|
31507
|
+
return new Digest4(code23, size2, digest2, bytes);
|
|
32161
31508
|
}
|
|
32162
31509
|
function decode43(multihash) {
|
|
32163
|
-
const
|
|
32164
|
-
const [code23, sizeOffset] = decode33(
|
|
32165
|
-
const [size2, digestOffset] = decode33(
|
|
32166
|
-
const
|
|
32167
|
-
if (
|
|
31510
|
+
const bytes = coerce5(multihash);
|
|
31511
|
+
const [code23, sizeOffset] = decode33(bytes);
|
|
31512
|
+
const [size2, digestOffset] = decode33(bytes.subarray(sizeOffset));
|
|
31513
|
+
const digest2 = bytes.subarray(sizeOffset + digestOffset);
|
|
31514
|
+
if (digest2.byteLength !== size2) {
|
|
32168
31515
|
throw new Error("Incorrect length");
|
|
32169
31516
|
}
|
|
32170
|
-
return new Digest4(code23, size2,
|
|
31517
|
+
return new Digest4(code23, size2, digest2, bytes);
|
|
32171
31518
|
}
|
|
32172
31519
|
function equals23(a, b) {
|
|
32173
31520
|
if (a === b) {
|
|
@@ -32185,20 +31532,20 @@ var Digest4 = class {
|
|
|
32185
31532
|
/**
|
|
32186
31533
|
* Creates a multihash digest.
|
|
32187
31534
|
*/
|
|
32188
|
-
constructor(code23, size2,
|
|
31535
|
+
constructor(code23, size2, digest2, bytes) {
|
|
32189
31536
|
this.code = code23;
|
|
32190
31537
|
this.size = size2;
|
|
32191
|
-
this.digest =
|
|
32192
|
-
this.bytes =
|
|
31538
|
+
this.digest = digest2;
|
|
31539
|
+
this.bytes = bytes;
|
|
32193
31540
|
}
|
|
32194
31541
|
};
|
|
32195
31542
|
function format4(link2, base23) {
|
|
32196
|
-
const { bytes
|
|
31543
|
+
const { bytes, version: version3 } = link2;
|
|
32197
31544
|
switch (version3) {
|
|
32198
31545
|
case 0:
|
|
32199
|
-
return toStringV04(
|
|
31546
|
+
return toStringV04(bytes, baseCache4(link2), base23 ?? base58btc4.encoder);
|
|
32200
31547
|
default:
|
|
32201
|
-
return toStringV14(
|
|
31548
|
+
return toStringV14(bytes, baseCache4(link2), base23 ?? base324.encoder);
|
|
32202
31549
|
}
|
|
32203
31550
|
}
|
|
32204
31551
|
var cache4 = /* @__PURE__ */ new WeakMap();
|
|
@@ -32222,12 +31569,12 @@ var CID4 = class _CID4 {
|
|
|
32222
31569
|
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
|
|
32223
31570
|
* @param multihash - (Multi)hash of the of the content.
|
|
32224
31571
|
*/
|
|
32225
|
-
constructor(version3, code23, multihash,
|
|
31572
|
+
constructor(version3, code23, multihash, bytes) {
|
|
32226
31573
|
this.code = code23;
|
|
32227
31574
|
this.version = version3;
|
|
32228
31575
|
this.multihash = multihash;
|
|
32229
|
-
this.bytes =
|
|
32230
|
-
this["/"] =
|
|
31576
|
+
this.bytes = bytes;
|
|
31577
|
+
this["/"] = bytes;
|
|
32231
31578
|
}
|
|
32232
31579
|
/**
|
|
32233
31580
|
* Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
|
|
@@ -32269,8 +31616,8 @@ var CID4 = class _CID4 {
|
|
|
32269
31616
|
toV1() {
|
|
32270
31617
|
switch (this.version) {
|
|
32271
31618
|
case 0: {
|
|
32272
|
-
const { code: code23, digest:
|
|
32273
|
-
const multihash = create4(code23,
|
|
31619
|
+
const { code: code23, digest: digest2 } = this.multihash;
|
|
31620
|
+
const multihash = create4(code23, digest2);
|
|
32274
31621
|
return _CID4.createV1(this.code, multihash);
|
|
32275
31622
|
}
|
|
32276
31623
|
case 1: {
|
|
@@ -32320,12 +31667,12 @@ var CID4 = class _CID4 {
|
|
|
32320
31667
|
if (value instanceof _CID4) {
|
|
32321
31668
|
return value;
|
|
32322
31669
|
} else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
|
|
32323
|
-
const { version: version3, code: code23, multihash, bytes
|
|
32324
|
-
return new _CID4(version3, code23, multihash,
|
|
31670
|
+
const { version: version3, code: code23, multihash, bytes } = value;
|
|
31671
|
+
return new _CID4(version3, code23, multihash, bytes ?? encodeCID4(version3, code23, multihash.bytes));
|
|
32325
31672
|
} else if (value[cidSymbol4] === true) {
|
|
32326
31673
|
const { version: version3, multihash, code: code23 } = value;
|
|
32327
|
-
const
|
|
32328
|
-
return _CID4.create(version3, code23,
|
|
31674
|
+
const digest2 = decode43(multihash);
|
|
31675
|
+
return _CID4.create(version3, code23, digest2);
|
|
32329
31676
|
} else {
|
|
32330
31677
|
return null;
|
|
32331
31678
|
}
|
|
@@ -32335,11 +31682,11 @@ var CID4 = class _CID4 {
|
|
|
32335
31682
|
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
|
|
32336
31683
|
* @param digest - (Multi)hash of the of the content.
|
|
32337
31684
|
*/
|
|
32338
|
-
static create(version3, code23,
|
|
31685
|
+
static create(version3, code23, digest2) {
|
|
32339
31686
|
if (typeof code23 !== "number") {
|
|
32340
31687
|
throw new Error("String codecs are no longer supported");
|
|
32341
31688
|
}
|
|
32342
|
-
if (!(
|
|
31689
|
+
if (!(digest2.bytes instanceof Uint8Array)) {
|
|
32343
31690
|
throw new Error("Invalid digest");
|
|
32344
31691
|
}
|
|
32345
31692
|
switch (version3) {
|
|
@@ -32347,12 +31694,12 @@ var CID4 = class _CID4 {
|
|
|
32347
31694
|
if (code23 !== DAG_PB_CODE4) {
|
|
32348
31695
|
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE4}) block encoding`);
|
|
32349
31696
|
} else {
|
|
32350
|
-
return new _CID4(version3, code23,
|
|
31697
|
+
return new _CID4(version3, code23, digest2, digest2.bytes);
|
|
32351
31698
|
}
|
|
32352
31699
|
}
|
|
32353
31700
|
case 1: {
|
|
32354
|
-
const
|
|
32355
|
-
return new _CID4(version3, code23,
|
|
31701
|
+
const bytes = encodeCID4(version3, code23, digest2.bytes);
|
|
31702
|
+
return new _CID4(version3, code23, digest2, bytes);
|
|
32356
31703
|
}
|
|
32357
31704
|
default: {
|
|
32358
31705
|
throw new Error("Invalid version");
|
|
@@ -32362,8 +31709,8 @@ var CID4 = class _CID4 {
|
|
|
32362
31709
|
/**
|
|
32363
31710
|
* Simplified version of `create` for CIDv0.
|
|
32364
31711
|
*/
|
|
32365
|
-
static createV0(
|
|
32366
|
-
return _CID4.create(0, DAG_PB_CODE4,
|
|
31712
|
+
static createV0(digest2) {
|
|
31713
|
+
return _CID4.create(0, DAG_PB_CODE4, digest2);
|
|
32367
31714
|
}
|
|
32368
31715
|
/**
|
|
32369
31716
|
* Simplified version of `create` for CIDv1.
|
|
@@ -32371,8 +31718,8 @@ var CID4 = class _CID4 {
|
|
|
32371
31718
|
* @param code - Content encoding format code.
|
|
32372
31719
|
* @param digest - Multihash of the content.
|
|
32373
31720
|
*/
|
|
32374
|
-
static createV1(code23,
|
|
32375
|
-
return _CID4.create(1, code23,
|
|
31721
|
+
static createV1(code23, digest2) {
|
|
31722
|
+
return _CID4.create(1, code23, digest2);
|
|
32376
31723
|
}
|
|
32377
31724
|
/**
|
|
32378
31725
|
* Decoded a CID from its binary representation. The byte array must contain
|
|
@@ -32381,8 +31728,8 @@ var CID4 = class _CID4 {
|
|
|
32381
31728
|
* An error will be thrown if the bytes provided do not contain a valid
|
|
32382
31729
|
* binary representation of a CID.
|
|
32383
31730
|
*/
|
|
32384
|
-
static decode(
|
|
32385
|
-
const [cid2, remainder] = _CID4.decodeFirst(
|
|
31731
|
+
static decode(bytes) {
|
|
31732
|
+
const [cid2, remainder] = _CID4.decodeFirst(bytes);
|
|
32386
31733
|
if (remainder.length !== 0) {
|
|
32387
31734
|
throw new Error("Incorrect length");
|
|
32388
31735
|
}
|
|
@@ -32397,17 +31744,17 @@ var CID4 = class _CID4 {
|
|
|
32397
31744
|
* will be a zero-length byte array if the provided bytes only contained a
|
|
32398
31745
|
* binary CID representation.
|
|
32399
31746
|
*/
|
|
32400
|
-
static decodeFirst(
|
|
32401
|
-
const specs = _CID4.inspectBytes(
|
|
31747
|
+
static decodeFirst(bytes) {
|
|
31748
|
+
const specs = _CID4.inspectBytes(bytes);
|
|
32402
31749
|
const prefixSize = specs.size - specs.multihashSize;
|
|
32403
|
-
const multihashBytes = coerce5(
|
|
31750
|
+
const multihashBytes = coerce5(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
|
|
32404
31751
|
if (multihashBytes.byteLength !== specs.multihashSize) {
|
|
32405
31752
|
throw new Error("Incorrect length");
|
|
32406
31753
|
}
|
|
32407
31754
|
const digestBytes3 = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
|
|
32408
|
-
const
|
|
32409
|
-
const cid2 = specs.version === 0 ? _CID4.createV0(
|
|
32410
|
-
return [cid2,
|
|
31755
|
+
const digest2 = new Digest4(specs.multihashCode, specs.digestSize, digestBytes3, multihashBytes);
|
|
31756
|
+
const cid2 = specs.version === 0 ? _CID4.createV0(digest2) : _CID4.createV1(specs.codec, digest2);
|
|
31757
|
+
return [cid2, bytes.subarray(specs.size)];
|
|
32411
31758
|
}
|
|
32412
31759
|
/**
|
|
32413
31760
|
* Inspect the initial bytes of a CID to determine its properties.
|
|
@@ -32450,8 +31797,8 @@ var CID4 = class _CID4 {
|
|
|
32450
31797
|
* a default decoder).
|
|
32451
31798
|
*/
|
|
32452
31799
|
static parse(source, base23) {
|
|
32453
|
-
const [prefix,
|
|
32454
|
-
const cid2 = _CID4.decode(
|
|
31800
|
+
const [prefix, bytes] = parseCIDtoBytes4(source, base23);
|
|
31801
|
+
const cid2 = _CID4.decode(bytes);
|
|
32455
31802
|
if (cid2.version === 0 && source[0] !== "Q") {
|
|
32456
31803
|
throw Error("Version 0 CID string must not include multibase prefix");
|
|
32457
31804
|
}
|
|
@@ -32489,25 +31836,25 @@ function parseCIDtoBytes4(source, base23) {
|
|
|
32489
31836
|
}
|
|
32490
31837
|
}
|
|
32491
31838
|
}
|
|
32492
|
-
function toStringV04(
|
|
31839
|
+
function toStringV04(bytes, cache22, base23) {
|
|
32493
31840
|
const { prefix } = base23;
|
|
32494
31841
|
if (prefix !== base58btc4.prefix) {
|
|
32495
31842
|
throw Error(`Cannot string encode V0 in ${base23.name} encoding`);
|
|
32496
31843
|
}
|
|
32497
31844
|
const cid2 = cache22.get(prefix);
|
|
32498
31845
|
if (cid2 == null) {
|
|
32499
|
-
const cid22 = base23.encode(
|
|
31846
|
+
const cid22 = base23.encode(bytes).slice(1);
|
|
32500
31847
|
cache22.set(prefix, cid22);
|
|
32501
31848
|
return cid22;
|
|
32502
31849
|
} else {
|
|
32503
31850
|
return cid2;
|
|
32504
31851
|
}
|
|
32505
31852
|
}
|
|
32506
|
-
function toStringV14(
|
|
31853
|
+
function toStringV14(bytes, cache22, base23) {
|
|
32507
31854
|
const { prefix } = base23;
|
|
32508
31855
|
const cid2 = cache22.get(prefix);
|
|
32509
31856
|
if (cid2 == null) {
|
|
32510
|
-
const cid22 = base23.encode(
|
|
31857
|
+
const cid22 = base23.encode(bytes);
|
|
32511
31858
|
cache22.set(prefix, cid22);
|
|
32512
31859
|
return cid22;
|
|
32513
31860
|
} else {
|
|
@@ -32519,11 +31866,11 @@ var SHA_256_CODE4 = 18;
|
|
|
32519
31866
|
function encodeCID4(version3, code23, multihash) {
|
|
32520
31867
|
const codeOffset = encodingLength4(version3);
|
|
32521
31868
|
const hashOffset = codeOffset + encodingLength4(code23);
|
|
32522
|
-
const
|
|
32523
|
-
encodeTo4(version3,
|
|
32524
|
-
encodeTo4(code23,
|
|
32525
|
-
|
|
32526
|
-
return
|
|
31869
|
+
const bytes = new Uint8Array(hashOffset + multihash.byteLength);
|
|
31870
|
+
encodeTo4(version3, bytes, 0);
|
|
31871
|
+
encodeTo4(code23, bytes, codeOffset);
|
|
31872
|
+
bytes.set(multihash, hashOffset);
|
|
31873
|
+
return bytes;
|
|
32527
31874
|
}
|
|
32528
31875
|
var cidSymbol4 = /* @__PURE__ */ Symbol.for("@ipld/js-cid/CID");
|
|
32529
31876
|
var code3 = 85;
|
|
@@ -32561,15 +31908,15 @@ var base64urlpad3 = rfc46484({
|
|
|
32561
31908
|
alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
|
|
32562
31909
|
bitsPerChar: 6
|
|
32563
31910
|
});
|
|
32564
|
-
function toBase64Url2(
|
|
32565
|
-
return base64url3.baseEncode(
|
|
31911
|
+
function toBase64Url2(bytes) {
|
|
31912
|
+
return base64url3.baseEncode(bytes);
|
|
32566
31913
|
}
|
|
32567
31914
|
function fromBase64Url2(text) {
|
|
32568
|
-
const
|
|
32569
|
-
if (base64url3.baseEncode(
|
|
31915
|
+
const bytes = base64url3.baseDecode(text);
|
|
31916
|
+
if (base64url3.baseEncode(bytes) !== text) {
|
|
32570
31917
|
throw new TypeError("non-canonical base64url input");
|
|
32571
31918
|
}
|
|
32572
|
-
return
|
|
31919
|
+
return bytes;
|
|
32573
31920
|
}
|
|
32574
31921
|
function utf8Bytes2(text) {
|
|
32575
31922
|
return new TextEncoder().encode(text);
|
|
@@ -33025,8 +32372,6 @@ function canonicalize3(value) {
|
|
|
33025
32372
|
var MAX_INLINE_BYTES2 = 256 * 1024;
|
|
33026
32373
|
|
|
33027
32374
|
// src/share/adapters.ts
|
|
33028
|
-
init_dist4();
|
|
33029
|
-
init_constants();
|
|
33030
32375
|
var DEFAULT_SHARE_ORIGIN = "https://share.tinycloud.xyz";
|
|
33031
32376
|
var ShareAuthorityError = class extends Error {
|
|
33032
32377
|
code;
|
|
@@ -33037,17 +32382,14 @@ var ShareAuthorityError = class extends Error {
|
|
|
33037
32382
|
}
|
|
33038
32383
|
};
|
|
33039
32384
|
async function postAddressedShareDelivery(input) {
|
|
33040
|
-
|
|
32385
|
+
if (input.receipt.request.returnLink !== input.shareUrl) throw new Error("credential invitation is not bound to the share link");
|
|
32386
|
+
return input.fetchFn(`${input.credentialsOrigin}/v1/credential-invitations`, {
|
|
33041
32387
|
method: "POST",
|
|
33042
32388
|
credentials: "omit",
|
|
33043
32389
|
redirect: "error",
|
|
33044
32390
|
referrerPolicy: "no-referrer",
|
|
33045
32391
|
headers: { accept: "application/json", "content-type": "application/json" },
|
|
33046
|
-
body: JSON.stringify(
|
|
33047
|
-
authorization: input.receipt.authorization,
|
|
33048
|
-
proof: input.receipt.proof,
|
|
33049
|
-
shareUrl: input.shareUrl
|
|
33050
|
-
}),
|
|
32392
|
+
body: JSON.stringify(input.receipt),
|
|
33051
32393
|
signal: input.signal
|
|
33052
32394
|
});
|
|
33053
32395
|
}
|
|
@@ -33096,18 +32438,18 @@ function createEncryptedProfileHistory(profileName, sessionSigner) {
|
|
|
33096
32438
|
})();
|
|
33097
32439
|
const path = async () => join6(await ProfileManager.getCacheDir(await profileName()), "share-history-v2.json");
|
|
33098
32440
|
const legacyPath = async () => join6(await ProfileManager.getCacheDir(await profileName()), "share-history-v1.bin");
|
|
33099
|
-
const
|
|
32441
|
+
const b64 = (value) => Buffer.from(value).toString("base64url");
|
|
33100
32442
|
const unb64 = (value) => {
|
|
33101
32443
|
if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("share history is unavailable");
|
|
33102
|
-
const
|
|
33103
|
-
if (
|
|
33104
|
-
return
|
|
32444
|
+
const bytes = new Uint8Array(Buffer.from(value, "base64url"));
|
|
32445
|
+
if (b64(bytes) !== value) throw new Error("share history is unavailable");
|
|
32446
|
+
return bytes;
|
|
33105
32447
|
};
|
|
33106
32448
|
const derive = async (salt, legacy = false) => {
|
|
33107
32449
|
const secret = await profileSecret();
|
|
33108
32450
|
if (legacy) {
|
|
33109
|
-
const
|
|
33110
|
-
return crypto.subtle.importKey("raw",
|
|
32451
|
+
const digest2 = await crypto.subtle.digest("SHA-256", secret);
|
|
32452
|
+
return crypto.subtle.importKey("raw", digest2, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
33111
32453
|
}
|
|
33112
32454
|
const material = await crypto.subtle.importKey("raw", secret, "PBKDF2", false, ["deriveKey"]);
|
|
33113
32455
|
return crypto.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
|
|
@@ -33121,16 +32463,16 @@ function createEncryptedProfileHistory(profileName, sessionSigner) {
|
|
|
33121
32463
|
const iv = unb64(envelope.iv);
|
|
33122
32464
|
const ciphertext = unb64(envelope.ciphertext);
|
|
33123
32465
|
if (salt.length < 16 || iv.length !== 12 || ciphertext.length <= 16) throw new Error("share history is unavailable");
|
|
33124
|
-
const
|
|
33125
|
-
const values = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(
|
|
32466
|
+
const bytes = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, await derive(salt), ciphertext);
|
|
32467
|
+
const values = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
33126
32468
|
return { values: Array.isArray(values) ? values.filter((value) => typeof value === "object" && value !== null && typeof value.shareId === "string") : [], salt };
|
|
33127
32469
|
} catch (error) {
|
|
33128
32470
|
if (error.code !== "ENOENT") throw new Error("share history is unavailable");
|
|
33129
32471
|
try {
|
|
33130
32472
|
const legacy = new Uint8Array(await readFile5(await legacyPath()));
|
|
33131
32473
|
if (legacy.length <= 12) return { values: [], salt: crypto.getRandomValues(new Uint8Array(16)) };
|
|
33132
|
-
const
|
|
33133
|
-
const values = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(
|
|
32474
|
+
const bytes = await crypto.subtle.decrypt({ name: "AES-GCM", iv: legacy.slice(0, 12) }, await derive(new Uint8Array(0), true), legacy.slice(12));
|
|
32475
|
+
const values = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
33134
32476
|
return { values: Array.isArray(values) ? values.filter((value) => typeof value === "object" && value !== null && typeof value.shareId === "string") : [], salt: crypto.getRandomValues(new Uint8Array(16)) };
|
|
33135
32477
|
} catch (legacyError) {
|
|
33136
32478
|
if (legacyError.code === "ENOENT") return { values: [], salt: crypto.getRandomValues(new Uint8Array(16)) };
|
|
@@ -33140,9 +32482,9 @@ function createEncryptedProfileHistory(profileName, sessionSigner) {
|
|
|
33140
32482
|
};
|
|
33141
32483
|
const write = async (values, salt) => {
|
|
33142
32484
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
33143
|
-
const
|
|
33144
|
-
const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await derive(salt),
|
|
33145
|
-
const output = new TextEncoder().encode(JSON.stringify({ version: HISTORY_VERSION, kdfSalt:
|
|
32485
|
+
const bytes = new TextEncoder().encode(JSON.stringify(values));
|
|
32486
|
+
const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await derive(salt), bytes));
|
|
32487
|
+
const output = new TextEncoder().encode(JSON.stringify({ version: HISTORY_VERSION, kdfSalt: b64(salt), iv: b64(iv), ciphertext: b64(encrypted) }));
|
|
33146
32488
|
await writeFile2(await path(), output, { mode: 384 });
|
|
33147
32489
|
};
|
|
33148
32490
|
const serial = (operationFn) => {
|
|
@@ -33178,7 +32520,7 @@ function createEncryptedProfileHistory(profileName, sessionSigner) {
|
|
|
33178
32520
|
function createShareAuthorityAdapters(input = {}) {
|
|
33179
32521
|
const origin = input.origin ?? DEFAULT_SHARE_ORIGIN;
|
|
33180
32522
|
const fetchFn = input.fetchFn ?? globalThis.fetch;
|
|
33181
|
-
const
|
|
32523
|
+
const canonicalOrigin = (value, label) => {
|
|
33182
32524
|
if (typeof value !== "string") throw new Error(`share ${label} is unavailable`);
|
|
33183
32525
|
const parsed = new URL(value);
|
|
33184
32526
|
const loopback = parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost";
|
|
@@ -33203,17 +32545,17 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33203
32545
|
if (decoded.length !== 32 || Buffer.from(decoded).toString("base64url") !== key) throw new Error("share node receipt key is invalid");
|
|
33204
32546
|
return decoded;
|
|
33205
32547
|
};
|
|
33206
|
-
const nodeOrigin =
|
|
32548
|
+
const nodeOrigin = canonicalOrigin(input.nodeOrigin ?? object3.nodeOrigin, "node origin");
|
|
33207
32549
|
const nodeAudience = typeof object3.nodeAudience === "string" ? object3.nodeAudience : "";
|
|
33208
32550
|
const enforcerDid = typeof object3.enforcerDid === "string" ? object3.enforcerDid : nodeAudience;
|
|
33209
32551
|
const nodeInvitationKid = typeof object3.nodeInvitationKid === "string" ? object3.nodeInvitationKid : "";
|
|
33210
32552
|
if (!nodeAudience.startsWith("did:web:") || !nodeInvitationKid.startsWith(`${nodeAudience}#`) || !enforcerDid.startsWith("did:key:") && enforcerDid !== nodeAudience) throw new Error("share node trust binding is invalid");
|
|
33211
32553
|
return {
|
|
33212
|
-
shareOrigin:
|
|
33213
|
-
registryOrigin:
|
|
32554
|
+
shareOrigin: canonicalOrigin(object3.shareOrigin, "origin"),
|
|
32555
|
+
registryOrigin: canonicalOrigin(object3.registryOrigin, "registry origin"),
|
|
33214
32556
|
nodeOrigin,
|
|
33215
|
-
emailOrigin:
|
|
33216
|
-
credentialsOrigin:
|
|
32557
|
+
emailOrigin: canonicalOrigin(input.emailOrigin ?? object3.emailOrigin, "email origin"),
|
|
32558
|
+
credentialsOrigin: canonicalOrigin(object3.credentialsOrigin, "credentials origin"),
|
|
33217
32559
|
nodeAudience,
|
|
33218
32560
|
enforcerDid,
|
|
33219
32561
|
nodeInvitationKid,
|
|
@@ -33234,16 +32576,29 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33234
32576
|
if (targetInput.origin !== config.shareOrigin || node.spaceId === void 0) throw new Error("addressed publication is not bound to the configured Share service");
|
|
33235
32577
|
const shareId = crypto.randomUUID().replaceAll("-", "");
|
|
33236
32578
|
const files = targetInput.files === void 0 || targetInput.files.length === 0 ? [{ bytes: targetInput.source, filename: targetInput.filename, mediaType: targetInput.mediaType }] : targetInput.files;
|
|
33237
|
-
const resourceKind = targetInput.resourceKind ??
|
|
33238
|
-
|
|
33239
|
-
const
|
|
33240
|
-
|
|
33241
|
-
const
|
|
33242
|
-
|
|
33243
|
-
|
|
33244
|
-
|
|
33245
|
-
|
|
33246
|
-
|
|
32579
|
+
const resourceKind = targetInput.resourceKind ?? "exact";
|
|
32580
|
+
if (resourceKind !== "exact" || files.length !== 1) throw new Error("addressed publication requires a single exact source file");
|
|
32581
|
+
const file = files[0];
|
|
32582
|
+
const resourcePath = `shares/${shareId}/${targetInput.filename}`;
|
|
32583
|
+
const byteLength = file.bytes.byteLength;
|
|
32584
|
+
if (!Number.isSafeInteger(byteLength) || byteLength > 100 * 1024 * 1024) throw new Error("addressed publication exceeds the combined byte limit");
|
|
32585
|
+
const mediaType = targetInput.mediaType ?? file.mediaType ?? "application/octet-stream";
|
|
32586
|
+
const encryptionNetwork = node.getEncryptionNetworkIdForSpace(node.spaceId);
|
|
32587
|
+
const encrypted = await node.encryption.encryptToNetwork(encryptionNetwork, file.bytes, { metadata: { contentType: mediaType } });
|
|
32588
|
+
if (!encrypted.ok) throw new Error("addressed source encryption was rejected");
|
|
32589
|
+
const storedBytes = new TextEncoder().encode(canonicalize3(encrypted.data));
|
|
32590
|
+
const stored = await node.kvForSpace(node.spaceId).put(resourcePath, storedBytes, { contentType: "application/vnd.tinycloud.encrypted-envelope+json" });
|
|
32591
|
+
if (!stored.ok) throw new Error("addressed source upload was rejected");
|
|
32592
|
+
const contentSource = {
|
|
32593
|
+
shareId,
|
|
32594
|
+
kvResource: `${node.spaceId}/kv/${resourcePath}`,
|
|
32595
|
+
selector: resourceKind,
|
|
32596
|
+
encryptionNetwork: encrypted.data.networkId,
|
|
32597
|
+
encryptedSymmetricKeyDigestHex: encrypted.data.encryptedSymmetricKeyHash,
|
|
32598
|
+
keyVersion: encrypted.data.keyVersion,
|
|
32599
|
+
mode: "immutable",
|
|
32600
|
+
initialCiphertextDigestHex: createHash("sha256").update(storedBytes).digest("hex")
|
|
32601
|
+
};
|
|
33247
32602
|
const actions = targetInput.actions === void 0 || targetInput.actions.length === 0 ? ["read"] : targetInput.actions;
|
|
33248
32603
|
const policyActions = [...new Set(actions.flatMap((action) => action === "read" ? ["tinycloud.kv/get", "tinycloud.kv/metadata"] : action === "list" ? ["tinycloud.kv/list"] : ["tinycloud.kv/put"]))];
|
|
33249
32604
|
return publishAddressedShare({
|
|
@@ -33257,19 +32612,19 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33257
32612
|
resource: { kind: resourceKind, path: resourcePath },
|
|
33258
32613
|
actions,
|
|
33259
32614
|
policyActions,
|
|
33260
|
-
contentSource
|
|
32615
|
+
contentSource,
|
|
33261
32616
|
filename: targetInput.filename,
|
|
33262
|
-
mediaType
|
|
33263
|
-
byteLength
|
|
32617
|
+
mediaType,
|
|
32618
|
+
byteLength,
|
|
33264
32619
|
expiresAt: targetInput.expiresAt,
|
|
33265
32620
|
inline: targetInput.inline,
|
|
32621
|
+
// App-neutral owner authority: the Node SDK owns every Policy/v3
|
|
32622
|
+
// transport hop, so the CLI supplies only owner signing material.
|
|
33266
32623
|
authority: {
|
|
33267
32624
|
ownerDid: node.did,
|
|
33268
|
-
|
|
33269
|
-
|
|
33270
|
-
|
|
33271
|
-
nodeProof: { kid: config.nodeInvitationKid, publicKey: config.nodeInvitationPublicKey }
|
|
33272
|
-
})
|
|
32625
|
+
createOwnerRoot: (request) => node.createUnifiedOwnerRoot(request),
|
|
32626
|
+
sign: (bytes) => node.signSessionBytes(bytes),
|
|
32627
|
+
registerPolicy: (request) => node.registerPolicy(request)
|
|
33273
32628
|
},
|
|
33274
32629
|
upload: targetInput.upload ?? {}
|
|
33275
32630
|
});
|
|
@@ -33295,8 +32650,8 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33295
32650
|
nodeOrigin: config.nodeOrigin,
|
|
33296
32651
|
trustedNode: { invitationKid: config.nodeInvitationKid, invitationPublicKey: config.nodeInvitationPublicKey },
|
|
33297
32652
|
holderDid,
|
|
33298
|
-
sign: async (
|
|
33299
|
-
return node.signSessionBytes(
|
|
32653
|
+
sign: async (bytes) => {
|
|
32654
|
+
return node.signSessionBytes(bytes);
|
|
33300
32655
|
},
|
|
33301
32656
|
buildPresentation: async ({ challenge: challenge2, envelope }) => {
|
|
33302
32657
|
const authority = envelope.ownerAuthority;
|
|
@@ -33339,7 +32694,7 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33339
32694
|
const proof = { alg: "EdDSA", kid: `${holderDid}#${holderDid.slice("did:key:".length)}`, signature };
|
|
33340
32695
|
const holderBinding = await createShareV2HolderBindingArtifact({
|
|
33341
32696
|
holderDid,
|
|
33342
|
-
sign: (
|
|
32697
|
+
sign: (bytes) => node.signSessionBytes(bytes),
|
|
33343
32698
|
message: {
|
|
33344
32699
|
type: SHARE_V2_PROTOCOL.holderBindingType,
|
|
33345
32700
|
version: SHARE_V2_PROTOCOL.holderBindingVersion,
|
|
@@ -33365,7 +32720,7 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33365
32720
|
presentationProof: proof,
|
|
33366
32721
|
proof,
|
|
33367
32722
|
holderBinding,
|
|
33368
|
-
sign: (
|
|
32723
|
+
sign: (bytes) => node.signSessionBytes(bytes)
|
|
33369
32724
|
};
|
|
33370
32725
|
}
|
|
33371
32726
|
});
|
|
@@ -33391,21 +32746,17 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33391
32746
|
};
|
|
33392
32747
|
const delivery = { deliver: input.deliver ?? (async (request) => {
|
|
33393
32748
|
const record2 = request.record;
|
|
33394
|
-
if (record2 === void 0 || record2.link === void 0 || record2.
|
|
32749
|
+
if (record2 === void 0 || record2.link === void 0 || record2.deliveryMaterial === void 0) throw new Error("share delivery history is incomplete");
|
|
33395
32750
|
const [config, node] = await Promise.all([publicConfig(), authenticatedNode()]);
|
|
33396
|
-
const receipt = await node.
|
|
33397
|
-
|
|
33398
|
-
|
|
33399
|
-
|
|
33400
|
-
|
|
33401
|
-
policyCid: record2.policyCid,
|
|
33402
|
-
delegationCid: record2.ownerDelegationCid,
|
|
33403
|
-
enforcementDelegationCid: record2.enforcementDelegationCid,
|
|
32751
|
+
const receipt = await node.authorizeShareDeliveryV3({
|
|
32752
|
+
envelope: record2.deliveryMaterial.envelope,
|
|
32753
|
+
sealedEnvelope: record2.deliveryMaterial.sealedEnvelope,
|
|
32754
|
+
envelopeKey: record2.deliveryMaterial.envelopeKey,
|
|
32755
|
+
shareCid: record2.deliveryMaterial.shareCid,
|
|
33404
32756
|
resourcePath: record2.resource.path,
|
|
33405
32757
|
recipientEmail: request.recipient,
|
|
33406
32758
|
shareUrl: record2.link,
|
|
33407
32759
|
documentName: record2.filename ?? "share.md",
|
|
33408
|
-
idempotencyKey: request.idempotencyKey ?? `tinycloud-share:${record2.shareId}`,
|
|
33409
32760
|
expiresAt: new Date(Math.min(Date.parse(record2.expiresAt), Date.now() + 5 * 60 * 1e3)).toISOString(),
|
|
33410
32761
|
nodeProof: { kid: config.nodeInvitationKid, publicKey: config.nodeInvitationPublicKey },
|
|
33411
32762
|
credentialsAudience: config.credentialsOrigin
|
|
@@ -33447,11 +32798,11 @@ function createShareAuthorityAdapters(input = {}) {
|
|
|
33447
32798
|
return {
|
|
33448
32799
|
targetAdapter,
|
|
33449
32800
|
authorization,
|
|
33450
|
-
records: input.profileName === void 0 ? createEncryptedSessionHistory() : createEncryptedProfileHistory(input.profileName, async (
|
|
32801
|
+
records: input.profileName === void 0 ? createEncryptedSessionHistory() : createEncryptedProfileHistory(input.profileName, async (bytes) => {
|
|
33451
32802
|
const profileName = await input.profileName();
|
|
33452
32803
|
const context = await ProfileManager.resolveContext({ profile: profileName });
|
|
33453
32804
|
const { ensureAuthenticated: ensureAuthenticated2 } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
|
|
33454
|
-
return (await ensureAuthenticated2(context)).signSessionBytes(
|
|
32805
|
+
return (await ensureAuthenticated2(context)).signSessionBytes(bytes);
|
|
33455
32806
|
}),
|
|
33456
32807
|
delivery,
|
|
33457
32808
|
revocation,
|
|
@@ -33463,132 +32814,21 @@ async function selectedProfileName() {
|
|
|
33463
32814
|
const config = await ProfileManager.getConfig();
|
|
33464
32815
|
return process.env.TC_PROFILE ?? config.defaultProfile;
|
|
33465
32816
|
}
|
|
33466
|
-
function canonicalNodeOrigin(value) {
|
|
33467
|
-
if (typeof value !== "string") throw new ShareAuthorityError("AUTH_REQUIRED", "share upload requires a configured Node host");
|
|
33468
|
-
let parsed;
|
|
33469
|
-
try {
|
|
33470
|
-
parsed = new URL(value);
|
|
33471
|
-
} catch {
|
|
33472
|
-
throw new ShareAuthorityError("UNAVAILABLE", "configured Node host is invalid");
|
|
33473
|
-
}
|
|
33474
|
-
const loopback = parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost";
|
|
33475
|
-
if (parsed.protocol !== "https:" && !(loopback && parsed.protocol === "http:") || parsed.origin !== value || parsed.username || parsed.password || parsed.search || parsed.hash) {
|
|
33476
|
-
throw new ShareAuthorityError("UNAVAILABLE", "configured Node host is invalid");
|
|
33477
|
-
}
|
|
33478
|
-
return parsed.origin;
|
|
33479
|
-
}
|
|
33480
|
-
function canonicalNodeAudience(origin) {
|
|
33481
|
-
return `did:web:${new URL(origin).hostname}`;
|
|
33482
|
-
}
|
|
33483
32817
|
function base64UrlSha256(value) {
|
|
33484
|
-
return
|
|
33485
|
-
}
|
|
33486
|
-
async function authenticatedNodeForProfile(profileName, host) {
|
|
33487
|
-
const context = await ProfileManager.resolveContext({ profile: profileName, host });
|
|
33488
|
-
const { ensureAuthenticated: ensureAuthenticated2 } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
|
|
33489
|
-
return ensureAuthenticated2(context);
|
|
33490
|
-
}
|
|
33491
|
-
function strictUploadAttestation(value, upload, origin, sessionDid) {
|
|
33492
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ShareAuthorityError("UNAVAILABLE", "Node returned an invalid upload attestation");
|
|
33493
|
-
const record2 = value;
|
|
33494
|
-
const expectedKeys = ["type", "version", "issuer", "kid", "ownerDid", "sessionDid", "shareOrigin", "encryptedBlobCid", "encryptedBlobSha256", "byteLength", "deleteAfter", "retention", "issuedAt", "authorityExpiresAt", "expiresAt", "jti", "signature"];
|
|
33495
|
-
if (Object.keys(record2).sort().join("\0") !== expectedKeys.sort().join("\0")) throw new ShareAuthorityError("UNAVAILABLE", "Node returned an invalid upload attestation");
|
|
33496
|
-
const sessionPrincipal = sessionDid.split("#", 1)[0];
|
|
33497
|
-
if (record2.type !== "TinyCloudShareUploadAttestation" || record2.version !== 1 || typeof record2.issuer !== "string" || !record2.issuer.startsWith("did:web:") || typeof record2.kid !== "string" || !record2.kid.startsWith(`${record2.issuer}#`) || typeof record2.ownerDid !== "string" || !record2.ownerDid.startsWith("did:") || record2.sessionDid !== sessionDid && record2.sessionDid !== sessionPrincipal || typeof record2.shareOrigin !== "string" || record2.shareOrigin !== origin || record2.encryptedBlobCid !== upload.cid || record2.encryptedBlobSha256 !== base64UrlSha256(upload.blob) || record2.byteLength !== upload.contentLength || record2.deleteAfter !== upload.deleteAfter || record2.retention === null || record2.retention === void 0 || typeof record2.issuedAt !== "string" || typeof record2.authorityExpiresAt !== "string" || typeof record2.expiresAt !== "string" || typeof record2.jti !== "string" || !/^[A-Za-z0-9_-]{16,}$/.test(record2.jti) || typeof record2.signature !== "string" || !/^[A-Za-z0-9_-]{86}$/.test(record2.signature)) throw new ShareAuthorityError("UNAVAILABLE", "Node returned an invalid upload attestation");
|
|
33498
|
-
const issuedAt = Date.parse(record2.issuedAt);
|
|
33499
|
-
const authorityExpiresAt = Date.parse(record2.authorityExpiresAt);
|
|
33500
|
-
const expiresAt = Date.parse(record2.expiresAt);
|
|
33501
|
-
const now = Date.now();
|
|
33502
|
-
if (!Number.isFinite(issuedAt) || !Number.isFinite(authorityExpiresAt) || !Number.isFinite(expiresAt) || new Date(issuedAt).toISOString() !== record2.issuedAt || new Date(authorityExpiresAt).toISOString() !== record2.authorityExpiresAt || new Date(expiresAt).toISOString() !== record2.expiresAt || authorityExpiresAt < expiresAt || expiresAt <= now || expiresAt - issuedAt > 12e4 || issuedAt > now + 3e4) throw new ShareAuthorityError("UNAVAILABLE", "Node returned an expired upload attestation");
|
|
33503
|
-
return record2;
|
|
33504
|
-
}
|
|
33505
|
-
async function openKeyUploadAuthorization(input) {
|
|
33506
|
-
const profile = await ProfileManager.getProfile(input.profileName).catch(() => {
|
|
33507
|
-
throw new ShareAuthorityError("AUTH_REQUIRED", "share upload requires an initialized profile");
|
|
33508
|
-
});
|
|
33509
|
-
if (profile.authMethod !== "openkey") throw new ShareAuthorityError("AUTH_REQUIRED", "share upload requires an OpenKey session");
|
|
33510
|
-
const session = await ProfileManager.getSession(input.profileName);
|
|
33511
|
-
const sessionDid = session?.verificationMethod;
|
|
33512
|
-
if (session === null || typeof sessionDid !== "string" || !sessionDid.startsWith("did:key:") || typeof session.delegationHeader !== "object" || session.delegationHeader === null || typeof session.delegationHeader.Authorization !== "string" || typeof session.delegationCid !== "string" || typeof session.spaceId !== "string") {
|
|
33513
|
-
throw new ShareAuthorityError("AUTH_REQUIRED", "share upload requires an active OpenKey session");
|
|
33514
|
-
}
|
|
33515
|
-
const requestWithoutDigest = {
|
|
33516
|
-
shareOrigin: input.origin,
|
|
33517
|
-
encryptedBlobCid: input.upload.cid,
|
|
33518
|
-
encryptedBlobSha256: base64UrlSha256(input.upload.blob),
|
|
33519
|
-
byteLength: input.upload.contentLength,
|
|
33520
|
-
deleteAfter: input.upload.deleteAfter,
|
|
33521
|
-
retention: "until-delete"
|
|
33522
|
-
};
|
|
33523
|
-
const requestBodyDigest = base64UrlSha256(new TextEncoder().encode(canonicalize3(requestWithoutDigest)));
|
|
33524
|
-
const body = canonicalize3({ ...requestWithoutDigest, requestBodyDigest });
|
|
33525
|
-
const entries = [{ spaceId: session.spaceId, service: "capabilities", action: "tinycloud.capabilities/read" }];
|
|
33526
|
-
const nodeOrigin = canonicalNodeOrigin(profile.host);
|
|
33527
|
-
const activation = await activateSessionWithHost(nodeOrigin, session.delegationHeader);
|
|
33528
|
-
if (!activation.success) throw new ShareAuthorityError("AUTH_REQUIRED", "Node upload authorization was rejected");
|
|
33529
|
-
const invocationHeaders = new Headers(input.node.invokeAny(entries, [{ requestBodyDigest }]));
|
|
33530
|
-
const invocation = invocationHeaders.get("authorization");
|
|
33531
|
-
if (invocation === null) throw new ShareAuthorityError("AUTH_REQUIRED", "Node upload authorization was rejected");
|
|
33532
|
-
const authorization = await input.node.bindInvocationAudience(invocation, canonicalNodeAudience(nodeOrigin));
|
|
33533
|
-
let response;
|
|
33534
|
-
try {
|
|
33535
|
-
const headers = new Headers({ authorization });
|
|
33536
|
-
headers.set("accept", "application/json");
|
|
33537
|
-
headers.set("content-type", "application/json");
|
|
33538
|
-
response = await input.fetchFn(new URL("/share/upload/attestation", nodeOrigin), { method: "POST", credentials: "omit", redirect: "error", referrerPolicy: "no-referrer", headers, body });
|
|
33539
|
-
} catch {
|
|
33540
|
-
throw new ShareAuthorityError("UNAVAILABLE", "Node upload authorization is unavailable");
|
|
33541
|
-
}
|
|
33542
|
-
if (response.status === 401 || response.status === 403) throw new ShareAuthorityError("AUTH_REQUIRED", "Node upload authorization was rejected");
|
|
33543
|
-
if (!response.ok) throw new ShareAuthorityError("UNAVAILABLE", "Node upload authorization is unavailable");
|
|
33544
|
-
let value;
|
|
33545
|
-
try {
|
|
33546
|
-
value = await response.json();
|
|
33547
|
-
} catch {
|
|
33548
|
-
throw new ShareAuthorityError("UNAVAILABLE", "Node returned an invalid upload attestation");
|
|
33549
|
-
}
|
|
33550
|
-
const attestation = strictUploadAttestation(value, input.upload, input.origin, sessionDid);
|
|
33551
|
-
return {
|
|
33552
|
-
"x-tinycloud-upload-attestation": JSON.stringify(attestation),
|
|
33553
|
-
"x-tinycloud-retention": canonicalize3(attestation.retention)
|
|
33554
|
-
};
|
|
32818
|
+
return createHash("sha256").update(value).digest("base64url");
|
|
33555
32819
|
}
|
|
33556
32820
|
function createProductionUploadAuthorizer(input = {}) {
|
|
33557
32821
|
const origin = input.origin ?? DEFAULT_SHARE_ORIGIN;
|
|
33558
32822
|
if (origin !== DEFAULT_SHARE_ORIGIN) throw new ShareAuthorityError("UNAVAILABLE", "share upload authorization is restricted to the canonical Share origin");
|
|
33559
|
-
const fetchFn = input.fetchFn ?? globalThis.fetch;
|
|
33560
32823
|
return async (upload) => {
|
|
33561
32824
|
const profileName = await (input.profileName?.() ?? selectedProfileName());
|
|
33562
32825
|
if (input.testOnly === true) {
|
|
33563
32826
|
const suppliedSession = input.sessionAuthorization === void 0 ? void 0 : await input.sessionAuthorization();
|
|
33564
32827
|
if (suppliedSession !== void 0) return suppliedSession;
|
|
33565
|
-
const
|
|
33566
|
-
if (
|
|
33567
|
-
}
|
|
33568
|
-
const existing = await ProfileManager.getProfile(profileName).catch(() => null);
|
|
33569
|
-
if (existing?.authMethod === "openkey") {
|
|
33570
|
-
try {
|
|
33571
|
-
return await openKeyUploadAuthorization({ fetchFn, origin, profileName, upload, node: await authenticatedNodeForProfile(profileName, existing.host) });
|
|
33572
|
-
} catch (error) {
|
|
33573
|
-
if (!(error instanceof ShareAuthorityError) || error.code !== "AUTH_REQUIRED") throw error;
|
|
33574
|
-
}
|
|
32828
|
+
const acquired = await input.acquireUploadAuthorization?.({ profileName, upload });
|
|
32829
|
+
if (acquired !== void 0) return acquired;
|
|
33575
32830
|
}
|
|
33576
|
-
|
|
33577
|
-
const nodeOrigin = await (input.nodeOrigin?.() ?? Promise.resolve(existing?.host ?? process.env.TC_HOST ?? DEFAULT_HOST));
|
|
33578
|
-
const acquired = await ensureShareDeviceAuthorization2({
|
|
33579
|
-
profileName,
|
|
33580
|
-
nodeOrigin,
|
|
33581
|
-
shareOrigin: origin,
|
|
33582
|
-
openkeyHost: process.env.TC_OPENKEY_HOST ?? existing?.openkeyHost,
|
|
33583
|
-
fetchFn
|
|
33584
|
-
});
|
|
33585
|
-
return openKeyUploadAuthorization({
|
|
33586
|
-
fetchFn,
|
|
33587
|
-
origin,
|
|
33588
|
-
profileName,
|
|
33589
|
-
upload,
|
|
33590
|
-
node: await authenticatedNodeForProfile(profileName, acquired.profile.host)
|
|
33591
|
-
});
|
|
32831
|
+
throw new ShareAuthorityError("UNAVAILABLE", "Node-specific registry upload authorization is retired; use an inline share");
|
|
33592
32832
|
};
|
|
33593
32833
|
}
|
|
33594
32834
|
|
|
@@ -33649,9 +32889,8 @@ program.hook("preAction", async (thisCommand) => {
|
|
|
33649
32889
|
});
|
|
33650
32890
|
configureShareCommandServices({
|
|
33651
32891
|
fetchFn: globalThis.fetch,
|
|
33652
|
-
//
|
|
33653
|
-
//
|
|
33654
|
-
// touches profile state, and no secret is serialized into a publish result.
|
|
32892
|
+
// Node-specific registry upload authorization is retired. The adapter keeps
|
|
32893
|
+
// the explicit contract seam while production callers use inline links.
|
|
33655
32894
|
authorizeUpload: createProductionUploadAuthorizer({
|
|
33656
32895
|
fetchFn: globalThis.fetch,
|
|
33657
32896
|
profileName: async () => selectedShareProfile() ?? (await ProfileManager.getConfig()).defaultProfile,
|