@tinycloud/cli 1.0.1-beta.5 → 1.1.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -14899,11 +14899,12 @@ function historyRecordForPublishedShare(result, now = /* @__PURE__ */ new Date()
14899
14899
  };
14900
14900
  }
14901
14901
  var ShareNotifyError = class extends Error {
14902
- code = "delivery-failed";
14903
- constructor(message = "share delivery did not complete") {
14902
+ constructor(message = "share delivery did not complete", reason) {
14904
14903
  super(message);
14904
+ this.reason = reason;
14905
14905
  this.name = "ShareNotifyError";
14906
14906
  }
14907
+ code = "delivery-failed";
14907
14908
  };
14908
14909
  function recipientMatchesShareRecord(record, recipient) {
14909
14910
  const matcher = record.recipientMatcher;
@@ -14913,6 +14914,11 @@ function recipientMatchesShareRecord(record, recipient) {
14913
14914
  if (matcher.kind === "emailDomain") return mailbox.domain === matcher.value;
14914
14915
  return false;
14915
14916
  }
14917
+ function shareDeliveryWindowExpiresAt(record) {
14918
+ const expiresAt = Math.min(Date.parse(record.expiresAt), Date.parse(record.registeredAt) + 5 * 60 * 1e3);
14919
+ if (!Number.isFinite(expiresAt)) throw new ShareNotifyError("share delivery history has invalid timestamps");
14920
+ return expiresAt;
14921
+ }
14916
14922
  async function notifyShare(input) {
14917
14923
  const mailbox = canonicalMailbox(input.recipient);
14918
14924
  if (!input.shareId || mailbox === void 0) throw new ShareNotifyError("recipient is invalid");
@@ -14923,6 +14929,19 @@ async function notifyShare(input) {
14923
14929
  const idempotencyKey = input.idempotencyKey ?? await defaultIdempotencyKey(input.shareId, recipient);
14924
14930
  const attemptsLimit = input.maxAttempts ?? 3;
14925
14931
  if (!Number.isSafeInteger(attemptsLimit) || attemptsLimit < 1 || attemptsLimit > 8) throw new ShareNotifyError("maxAttempts is invalid");
14932
+ if (input.signal?.aborted) throw new ShareNotifyError("share delivery was cancelled");
14933
+ if (input.checkDeliveryWindow && input.record !== void 0 && shareDeliveryWindowExpiresAt(input.record) <= Date.now()) {
14934
+ return {
14935
+ protocol: "tinycloud-share",
14936
+ version: 1,
14937
+ shareId: input.shareId,
14938
+ state: "partial-failure",
14939
+ idempotencyKey,
14940
+ attempts: 1,
14941
+ retryable: false,
14942
+ reason: "delivery-window-expired"
14943
+ };
14944
+ }
14926
14945
  let attempts = 0;
14927
14946
  let lastError;
14928
14947
  while (attempts < attemptsLimit) {
@@ -14930,8 +14949,27 @@ async function notifyShare(input) {
14930
14949
  attempts += 1;
14931
14950
  try {
14932
14951
  const state = await input.adapter.deliver({ shareId: input.shareId, recipient, idempotencyKey, ...input.record === void 0 ? {} : { record: input.record }, ...input.signal === void 0 ? {} : { signal: input.signal } });
14933
- return { protocol: "tinycloud-share", version: 1, shareId: input.shareId, state, idempotencyKey, attempts };
14952
+ return {
14953
+ protocol: "tinycloud-share",
14954
+ version: 1,
14955
+ shareId: input.shareId,
14956
+ state: state === "delivered" && input.record?.deliveredRecipients?.includes(recipient) ? "already-delivered" : state,
14957
+ idempotencyKey,
14958
+ attempts
14959
+ };
14934
14960
  } catch (error) {
14961
+ if (error instanceof ShareNotifyError && error.reason === "delivery-window-expired") {
14962
+ return {
14963
+ protocol: "tinycloud-share",
14964
+ version: 1,
14965
+ shareId: input.shareId,
14966
+ state: "partial-failure",
14967
+ idempotencyKey,
14968
+ attempts,
14969
+ retryable: false,
14970
+ reason: "delivery-window-expired"
14971
+ };
14972
+ }
14935
14973
  lastError = error;
14936
14974
  }
14937
14975
  }
@@ -15090,7 +15128,11 @@ async function revokeShare(input) {
15090
15128
  });
15091
15129
  }
15092
15130
  const revokedAt = (input.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
15093
- if (input.records !== void 0) await input.records.put({ ...input.record, revokedAt });
15131
+ if (input.records?.update !== void 0) {
15132
+ await input.records.update(input.record.shareId, (record) => ({ ...record, revokedAt }));
15133
+ } else if (input.records !== void 0) {
15134
+ await input.records.put({ ...input.record, revokedAt });
15135
+ }
15094
15136
  return { state: "revoked", target, delegationCid, revokedAt };
15095
15137
  }
15096
15138
  function redactRecord(record, revealLink, link2) {
@@ -15159,1550 +15201,1011 @@ function parseNativeShareUrl(value) {
15159
15201
  return token;
15160
15202
  }
15161
15203
 
15162
- // src/lib/duration.ts
15163
- function parseDuration(input) {
15164
- const match = input.match(/^(\d+)(m|h|d|w)$/);
15165
- if (match) {
15166
- const value = parseInt(match[1], 10);
15167
- const unit = match[2];
15168
- const multipliers = {
15169
- m: 60 * 1e3,
15170
- h: 60 * 60 * 1e3,
15171
- d: 24 * 60 * 60 * 1e3,
15172
- w: 7 * 24 * 60 * 60 * 1e3
15173
- };
15174
- return value * multipliers[unit];
15204
+ // ../share-envelope/dist/index.js
15205
+ init_zod();
15206
+ var empty3 = new Uint8Array(0);
15207
+ function equals5(aa, bb) {
15208
+ if (aa === bb) {
15209
+ return true;
15175
15210
  }
15176
- const date = new Date(input);
15177
- if (!isNaN(date.getTime())) {
15178
- const ms = date.getTime() - Date.now();
15179
- if (ms <= 0) {
15180
- throw new Error(`Expiry date "${input}" is in the past`);
15211
+ if (aa.byteLength !== bb.byteLength) {
15212
+ return false;
15213
+ }
15214
+ for (let ii = 0; ii < aa.byteLength; ii++) {
15215
+ if (aa[ii] !== bb[ii]) {
15216
+ return false;
15181
15217
  }
15182
- return ms;
15183
15218
  }
15184
- throw new Error(`Invalid duration: "${input}". Use format like "1h", "7d", or an ISO date.`);
15185
- }
15186
-
15187
- // src/commands/share.ts
15188
- init_formatter();
15189
- init_errors();
15190
-
15191
- // src/share/output.ts
15192
- function writeJson2(value) {
15193
- process.stdout.write(`${JSON.stringify(value, null, 2)}
15194
- `);
15195
- }
15196
- function authorizationRequiredJson(result) {
15197
- return {
15198
- state: "authorization-required",
15199
- method: result.method,
15200
- next: "complete authorization through the configured authority adapter, then retry with the required proof"
15201
- };
15202
- }
15203
- function publishHuman(result) {
15204
- process.stdout.write(`${result.url}
15205
- `);
15206
- }
15207
- function inspectHuman(result) {
15208
- const metadata = result.metadata;
15209
- process.stdout.write([
15210
- `Share ${metadata.shareId}`,
15211
- `File: ${metadata.display.filename ?? "unnamed"}`,
15212
- `Target: ${metadata.target.kind === "bearer" ? "bearer (anyone with the complete link can read)" : metadata.target.kind}`,
15213
- `Expires: ${metadata.expiresAt}`,
15214
- `Resource: ${metadata.resource.path}`,
15215
- `Link format: ${result.link.kind}`
15216
- ].join("\n") + "\n");
15217
- }
15218
- function receiveHuman(path) {
15219
- process.stdout.write(`${path}
15220
- `);
15221
- }
15222
- function receiveJson(result, path) {
15223
- writeJson2({ protocol: "tinycloud-share", version: 1, path, metadata: result.metadata });
15219
+ return true;
15224
15220
  }
15225
-
15226
- // src/share/io.ts
15227
- import { constants } from "fs";
15228
- import { lstat as lstat2, mkdir as mkdir2, mkdtemp, open as open2, readFile as readFile2, realpath, stat as stat2, link, rename as rename2, rm as rm3, unlink } from "fs/promises";
15229
- import { randomBytes as randomBytes2 } from "crypto";
15230
- import { basename as basename2, join as join4, resolve, sep } from "path";
15231
- init_errors();
15232
- var MAX_SHARE_STDIN_BYTES = 100 * 1024 * 1024;
15233
- var MAX_SHARE_URL_BYTES = 64 * 1024;
15234
- async function readBoundedStdin(limit = MAX_SHARE_STDIN_BYTES) {
15235
- if (!Number.isSafeInteger(limit) || limit <= 0) throw new Error("MAX_BYTES_EXCEEDED");
15236
- const chunks = [];
15237
- let total = 0;
15238
- for await (const chunk of process.stdin) {
15239
- const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
15240
- total += bytes.byteLength;
15241
- if (total > limit) throw new Error("MAX_BYTES_EXCEEDED");
15242
- chunks.push(bytes);
15221
+ function coerce5(o) {
15222
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
15223
+ return o;
15243
15224
  }
15244
- return new Uint8Array(Buffer.concat(chunks, total));
15245
- }
15246
- async function readBoundedUrlStdin() {
15247
- const bytes = await readBoundedStdin(MAX_SHARE_URL_BYTES);
15248
- const value = new TextDecoder("utf-8", { fatal: true }).decode(bytes).trim();
15249
- if (value.length === 0 || /\s/.test(value)) throw new Error("INVALID_ARGUMENT");
15250
- return value;
15251
- }
15252
- function safeFilename(value) {
15253
- return shareFilename(value);
15254
- }
15255
- function shareFilename(value) {
15256
- try {
15257
- return canonicalShareFilename(value);
15258
- } catch {
15259
- throw new CLIError(
15260
- "UNSAFE_FILENAME",
15261
- hasUnsafeFilenameCodePoint(value) ? "filename contains control or invisible characters" : "filename must be one safe path segment",
15262
- 8
15263
- );
15225
+ if (o instanceof ArrayBuffer) {
15226
+ return new Uint8Array(o);
15264
15227
  }
15228
+ if (ArrayBuffer.isView(o)) {
15229
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
15230
+ }
15231
+ throw new Error("Unknown type, must be binary type");
15265
15232
  }
15266
- function shareInputFilename(input, name) {
15267
- return shareFilename(name ?? (input === "-" ? "stdin.md" : basename2(resolve(input))));
15268
- }
15269
- async function readShareInput(input, name, limit = MAX_SHARE_STDIN_BYTES) {
15270
- const filename = shareInputFilename(input, name);
15271
- if (input === "-") return { bytes: await readBoundedStdin(limit), filename };
15272
- const path = resolve(input);
15273
- const info = await stat2(path);
15274
- if (!info.isFile() || info.size > limit) throw new Error("MAX_BYTES_EXCEEDED");
15275
- const bytes = new Uint8Array(await readFile2(path));
15276
- if (bytes.byteLength > limit) throw new Error("MAX_BYTES_EXCEEDED");
15277
- return { bytes, filename };
15278
- }
15279
- async function assertDirectory(path) {
15280
- const absolute = resolve(path);
15281
- const segments = absolute.split(sep).filter(Boolean);
15282
- let current = absolute.startsWith(sep) ? sep : "";
15283
- for (const segment of segments) {
15284
- current = current === sep ? join4(current, segment) : join4(current, segment);
15285
- try {
15286
- const info = await lstat2(current);
15287
- if (info.isSymbolicLink()) {
15288
- const canonical = await realpath(current);
15289
- if (current !== "/tmp" && current !== "/var") throw new Error("OUTPUT_EXISTS");
15290
- if (canonical !== `/private${current}`) throw new Error("OUTPUT_EXISTS");
15291
- } else if (!info.isDirectory()) throw new Error("OUTPUT_EXISTS");
15292
- } catch (error) {
15293
- if (error.code !== "ENOENT") throw error;
15294
- await mkdir2(current, { mode: 448 });
15295
- const created = await lstat2(current);
15296
- if (created.isSymbolicLink() || !created.isDirectory()) throw new Error("OUTPUT_EXISTS");
15233
+ function base3(ALPHABET, name) {
15234
+ if (ALPHABET.length >= 255) {
15235
+ throw new TypeError("Alphabet too long");
15236
+ }
15237
+ var BASE_MAP = new Uint8Array(256);
15238
+ for (var j = 0; j < BASE_MAP.length; j++) {
15239
+ BASE_MAP[j] = 255;
15240
+ }
15241
+ for (var i = 0; i < ALPHABET.length; i++) {
15242
+ var x = ALPHABET.charAt(i);
15243
+ var xc = x.charCodeAt(0);
15244
+ if (BASE_MAP[xc] !== 255) {
15245
+ throw new TypeError(x + " is ambiguous");
15297
15246
  }
15247
+ BASE_MAP[xc] = i;
15298
15248
  }
15299
- }
15300
- async function writeShareOutput(directory, filename, bytes, force) {
15301
- const outputDirectory = resolve(directory);
15302
- await assertDirectory(outputDirectory);
15303
- const safeName = safeFilename(filename);
15304
- const directoryHandle = await open2(outputDirectory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | (constants.O_NOFOLLOW ?? 0));
15305
- const stableDirectory = await realpath(outputDirectory);
15306
- const outputPath = join4(stableDirectory, safeName);
15307
- const directoryIdentity = await directoryHandle.stat();
15308
- const assertStableDirectory = async () => {
15309
- const current = await stat2(stableDirectory);
15310
- if (current.dev !== directoryIdentity.dev || current.ino !== directoryIdentity.ino) throw new Error("OUTPUT_EXISTS");
15311
- };
15312
- await assertStableDirectory();
15313
- const stagingDirectory = await mkdtemp(join4(stableDirectory, ".tinycloud-share-stage-"));
15314
- const stagingInfo = await lstat2(stagingDirectory);
15315
- if (!stagingInfo.isDirectory() || (stagingInfo.mode & 511) !== 448) throw new Error("OUTPUT_EXISTS");
15316
- const stagingPath = join4(stagingDirectory, `.tinycloud-share-${randomBytes2(16).toString("hex")}.tmp`);
15317
- let temporaryPath;
15318
- let handle;
15319
- try {
15320
- await assertStableDirectory();
15321
- try {
15322
- const existing = await lstat2(outputPath);
15323
- if (existing.isSymbolicLink()) throw new Error("UNSAFE_FILENAME");
15324
- } catch (error) {
15325
- if (error.code !== "ENOENT") throw error;
15249
+ var BASE = ALPHABET.length;
15250
+ var LEADER = ALPHABET.charAt(0);
15251
+ var FACTOR = Math.log(BASE) / Math.log(256);
15252
+ var iFACTOR = Math.log(256) / Math.log(BASE);
15253
+ function encode32(source) {
15254
+ if (source instanceof Uint8Array)
15255
+ ;
15256
+ else if (ArrayBuffer.isView(source)) {
15257
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
15258
+ } else if (Array.isArray(source)) {
15259
+ source = Uint8Array.from(source);
15326
15260
  }
15327
- temporaryPath = stagingPath;
15328
- handle = await open2(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 384);
15329
- await handle.writeFile(bytes);
15330
- await handle.close();
15331
- handle = void 0;
15332
- await assertStableDirectory();
15333
- if (force) {
15334
- await rename2(temporaryPath, outputPath);
15335
- } else {
15336
- await link(temporaryPath, outputPath);
15337
- await unlink(temporaryPath);
15261
+ if (!(source instanceof Uint8Array)) {
15262
+ throw new TypeError("Expected Uint8Array");
15338
15263
  }
15339
- await assertStableDirectory();
15340
- } catch (error) {
15341
- if (error.code === "EEXIST") throw new Error("OUTPUT_EXISTS");
15342
- if (error.code === "ELOOP") throw new Error("UNSAFE_FILENAME");
15343
- throw error;
15344
- } finally {
15345
- await handle?.close();
15346
- try {
15347
- if (temporaryPath !== void 0) await unlink(temporaryPath);
15348
- } catch {
15264
+ if (source.length === 0) {
15265
+ return "";
15349
15266
  }
15350
- await rm3(stagingDirectory, { recursive: true, force: true });
15351
- await directoryHandle.close();
15352
- }
15353
- return join4(outputDirectory, safeName);
15354
- }
15355
-
15356
- // src/share/errors.ts
15357
- var SharePublishAuthorityError = class extends Error {
15358
- constructor(failure) {
15359
- super(failure.kind);
15360
- this.failure = failure;
15361
- this.name = "SharePublishAuthorityError";
15362
- }
15363
- };
15364
-
15365
- // src/commands/share.ts
15366
- var SHARE_ORIGIN = "https://share.tinycloud.xyz";
15367
- var shareServices = {};
15368
- function configureShareCommandServices(services) {
15369
- shareServices = services;
15370
- }
15371
- function parseShareTarget(value) {
15372
- if (value === "anyone" || value === "bearer") return { kind: "bearer" };
15373
- if (value.startsWith("did:")) return { kind: "recipientDid", did: value };
15374
- if (value.startsWith("domain:")) return canonicalMailboxTarget({ kind: "emailDomain", domain: value.slice("domain:".length) });
15375
- if (value.startsWith("email:")) return canonicalMailboxTarget({ kind: "email", address: value.slice("email:".length) });
15376
- if (value.includes("@")) return canonicalMailboxTarget({ kind: "email", address: value });
15377
- throw new CLIError("INVALID_ARGUMENT", "--to must be anyone, a did:, an email address, or domain:example.com", 2);
15378
- }
15379
- function canonicalMailboxTarget(target) {
15380
- try {
15381
- return normalizeShareTarget(target);
15382
- } catch (error) {
15383
- throw new CLIError("INVALID_ARGUMENT", error instanceof TypeError ? error.message : "share recipient is invalid", 2);
15267
+ var zeroes = 0;
15268
+ var length22 = 0;
15269
+ var pbegin = 0;
15270
+ var pend = source.length;
15271
+ while (pbegin !== pend && source[pbegin] === 0) {
15272
+ pbegin++;
15273
+ zeroes++;
15274
+ }
15275
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
15276
+ var b58 = new Uint8Array(size);
15277
+ while (pbegin !== pend) {
15278
+ var carry = source[pbegin];
15279
+ var i2 = 0;
15280
+ for (var it1 = size - 1; (carry !== 0 || i2 < length22) && it1 !== -1; it1--, i2++) {
15281
+ carry += 256 * b58[it1] >>> 0;
15282
+ b58[it1] = carry % BASE >>> 0;
15283
+ carry = carry / BASE >>> 0;
15284
+ }
15285
+ if (carry !== 0) {
15286
+ throw new Error("Non-zero carry");
15287
+ }
15288
+ length22 = i2;
15289
+ pbegin++;
15290
+ }
15291
+ var it2 = size - length22;
15292
+ while (it2 !== size && b58[it2] === 0) {
15293
+ it2++;
15294
+ }
15295
+ var str = LEADER.repeat(zeroes);
15296
+ for (; it2 < size; ++it2) {
15297
+ str += ALPHABET.charAt(b58[it2]);
15298
+ }
15299
+ return str;
15384
15300
  }
15385
- }
15386
- function shareCliError(error) {
15387
- if (error instanceof CLIError) return error;
15388
- if (error instanceof SharePublishAuthorityError) {
15389
- const failure = error.failure;
15390
- const profileName = "profileName" in failure ? failure.profileName : void 0;
15391
- const localKey = "localKey" in failure && failure.localKey === true;
15392
- const profileHint = profileName === void 0 ? "" : `--profile ${profileName} `;
15393
- const loginHint = localKey ? `\`tc ${profileHint}auth login --method local\`` : `\`tc ${profileHint}auth login --device --manifest builtin:share-publishing\` (or \`tc ${profileHint}enable share\`)`;
15394
- if (failure.kind === "caveated-session") {
15395
- const holder = profileName === void 0 ? "this session" : `profile ${profileName}'s session`;
15396
- return new CLIError(
15397
- "PERMISSION_DENIED",
15398
- `${holder} carries signed restrictions (caveats) on the authority an anyone-with-link share needs, so it cannot create the share link; nothing was shared. Approve Share publishing without restrictions on a new, dedicated profile (any unused name): \`tc init --name publisher --key-only && tc --profile publisher enable share\``,
15399
- 5
15400
- );
15301
+ function decodeUnsafe(source) {
15302
+ if (typeof source !== "string") {
15303
+ throw new TypeError("Expected String");
15401
15304
  }
15402
- if (failure.kind === "owner-space-unresolved") {
15403
- return new CLIError("AUTH_REQUIRED", `a valid signed TinyCloud session is required; run ${loginHint}`, 3);
15305
+ if (source.length === 0) {
15306
+ return new Uint8Array();
15404
15307
  }
15405
- if (failure.kind === "scope-denied") {
15406
- const requiredAction = failure.requiredAction === void 0 ? "" : ` (${failure.requiredAction})`;
15407
- const renew = localKey ? `renew it with ${loginHint} using the required capability` : `verify the session includes the builtin:share-publishing scope; if it does not, request it with ${loginHint}`;
15408
- return new CLIError("PERMISSION_DENIED", `the session lacks ${failure.capability} authority${requiredAction}; ${renew}`, 5);
15308
+ var psz = 0;
15309
+ if (source[psz] === " ") {
15310
+ return;
15409
15311
  }
15410
- if (failure.kind === "lifetime-exceeds-session") {
15411
- const expiresAt = failure.sessionExpiresAt.toISOString();
15412
- if (failure.reason === "session-too-close") {
15413
- return new CLIError("AUTH_REQUIRED", `the signed session expires too soon (${expiresAt}); log in again with ${loginHint}`, 3);
15312
+ var zeroes = 0;
15313
+ var length22 = 0;
15314
+ while (source[psz] === LEADER) {
15315
+ zeroes++;
15316
+ psz++;
15317
+ }
15318
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
15319
+ var b256 = new Uint8Array(size);
15320
+ while (source[psz]) {
15321
+ var carry = BASE_MAP[source.charCodeAt(psz)];
15322
+ if (carry === 255) {
15323
+ return;
15414
15324
  }
15415
- if (failure.reason === "below-minimum") {
15416
- return new CLIError("SESSION_LIFETIME_EXCEEDED", "share expiry must be at least 60 seconds from now; use a longer --expires value", 2);
15325
+ var i2 = 0;
15326
+ for (var it3 = size - 1; (carry !== 0 || i2 < length22) && it3 !== -1; it3--, i2++) {
15327
+ carry += BASE * b256[it3] >>> 0;
15328
+ b256[it3] = carry % 256 >>> 0;
15329
+ carry = carry / 256 >>> 0;
15417
15330
  }
15418
- return new CLIError("SESSION_LIFETIME_EXCEEDED", `requested share lifetime exceeds session expiry ${expiresAt}; use a shorter --expires value or renew the session with ${loginHint}`, 2);
15331
+ if (carry !== 0) {
15332
+ throw new Error("Non-zero carry");
15333
+ }
15334
+ length22 = i2;
15335
+ psz++;
15419
15336
  }
15420
- if (failure.kind === "origin-mismatch") {
15421
- return new CLIError("ORIGIN_MISMATCH", "share origin does not match the configured service", 2);
15337
+ if (source[psz] === " ") {
15338
+ return;
15422
15339
  }
15423
- if (failure.kind === "invalid-request") {
15424
- return new CLIError("INVALID_ARGUMENT", failure.reason, 2);
15340
+ var it4 = size - length22;
15341
+ while (it4 !== size && b256[it4] === 0) {
15342
+ it4++;
15425
15343
  }
15426
- if (failure.kind === "registry-unavailable") {
15427
- return new CLIError("UNAVAILABLE", "the TinyCloud location registry could not be reached, so nothing was shared; try again shortly", 4);
15344
+ var vch = new Uint8Array(zeroes + (size - it4));
15345
+ var j2 = zeroes;
15346
+ while (it4 !== size) {
15347
+ vch[j2++] = b256[it4++];
15428
15348
  }
15429
- if (failure.kind === "registry-rejected") {
15430
- return new CLIError("REGISTRY_REJECTED", "the TinyCloud location registry rejected this session's location record, so nothing was shared; retrying will not help. Log in again, and report the problem if it persists", 6);
15349
+ return vch;
15350
+ }
15351
+ function decode52(string) {
15352
+ var buffer = decodeUnsafe(string);
15353
+ if (buffer) {
15354
+ return buffer;
15431
15355
  }
15432
- if (failure.kind === "storage-quota-exceeded") {
15433
- const sizes = failure.usedBytes === void 0 || failure.limitBytes === void 0 ? "" : ` (${formatBytes(failure.usedBytes)} used of ${formatBytes(failure.limitBytes)} limit)`;
15434
- return new CLIError("STORAGE_QUOTA_EXCEEDED", `storage quota exceeded${sizes}; nothing was shared`, 4);
15356
+ throw new Error(`Non-${name} character`);
15357
+ }
15358
+ return {
15359
+ encode: encode32,
15360
+ decodeUnsafe,
15361
+ decode: decode52
15362
+ };
15363
+ }
15364
+ var src3 = base3;
15365
+ var _brrp__multiformats_scope_baseX3 = src3;
15366
+ var base_x_default3 = _brrp__multiformats_scope_baseX3;
15367
+ var Encoder3 = class {
15368
+ name;
15369
+ prefix;
15370
+ baseEncode;
15371
+ constructor(name, prefix, baseEncode) {
15372
+ this.name = name;
15373
+ this.prefix = prefix;
15374
+ this.baseEncode = baseEncode;
15375
+ }
15376
+ encode(bytes) {
15377
+ if (bytes instanceof Uint8Array) {
15378
+ return `${this.prefix}${this.baseEncode(bytes)}`;
15379
+ } else {
15380
+ throw Error("Unknown type, must be binary type");
15435
15381
  }
15436
- if (failure.kind === "upload-failed") {
15437
- return new CLIError("UPLOAD_FAILED", "share source upload failed; nothing was shared", 4);
15382
+ }
15383
+ };
15384
+ var Decoder3 = class {
15385
+ name;
15386
+ prefix;
15387
+ baseDecode;
15388
+ prefixCodePoint;
15389
+ constructor(name, prefix, baseDecode) {
15390
+ this.name = name;
15391
+ this.prefix = prefix;
15392
+ const prefixCodePoint = prefix.codePointAt(0);
15393
+ if (prefixCodePoint === void 0) {
15394
+ throw new Error("Invalid prefix character");
15438
15395
  }
15396
+ this.prefixCodePoint = prefixCodePoint;
15397
+ this.baseDecode = baseDecode;
15439
15398
  }
15440
- if (error instanceof ShareNotifyError) {
15441
- return new CLIError("INVALID_ARGUMENT", error.message, 2);
15399
+ decode(text) {
15400
+ if (typeof text === "string") {
15401
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
15402
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
15403
+ }
15404
+ return this.baseDecode(text.slice(this.prefix.length));
15405
+ } else {
15406
+ throw Error("Can only multibase decode strings");
15407
+ }
15442
15408
  }
15443
- if (error instanceof SharePublishError) {
15444
- const exit = error.code === "authority-required" ? 3 : error.code === "max-bytes-exceeded" ? 7 : 2;
15445
- const code3 = error.code === "authority-required" ? "AUTH_REQUIRED" : error.code === "max-bytes-exceeded" ? "MAX_BYTES_EXCEEDED" : "INVALID_ARGUMENT";
15446
- return new CLIError(code3, error.message, exit);
15409
+ or(decoder) {
15410
+ return or3(this, decoder);
15447
15411
  }
15448
- if (error instanceof ShareReceiveError) {
15449
- const verification = /* @__PURE__ */ new Set(["cid-mismatch", "decrypt-failed", "envelope-invalid", "origin-mismatch", "signature-invalid", "capability-invalid", "content-integrity-failed"]);
15450
- const exit = error.code === "max-bytes-exceeded" ? 7 : verification.has(error.code) ? 5 : error.code === "expired" || error.code === "fetch-failed" ? 4 : error.code === "invalid-link" || error.code === "unsupported-target" ? 2 : 2;
15451
- const code3 = error.code === "fetch-failed" ? "NOT_FOUND" : error.code.replaceAll("-", "_").toUpperCase();
15452
- return new CLIError(code3, error.message, exit);
15412
+ };
15413
+ var ComposedDecoder3 = class {
15414
+ decoders;
15415
+ constructor(decoders) {
15416
+ this.decoders = decoders;
15453
15417
  }
15454
- const message = error instanceof Error ? error.message : String(error);
15455
- const nodeCode = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
15456
- const known = {
15457
- MAX_BYTES_EXCEEDED: { code: "MAX_BYTES_EXCEEDED", exit: 7 },
15458
- UNSAFE_FILENAME: { code: "UNSAFE_FILENAME", exit: 8 },
15459
- OUTPUT_EXISTS: { code: "OUTPUT_EXISTS", exit: 8 },
15460
- INVALID_ARGUMENT: { code: "INVALID_ARGUMENT", exit: 2 },
15461
- "share not found": { code: "NOT_FOUND", exit: 4 },
15462
- AUTH_REQUIRED: { code: "AUTH_REQUIRED", exit: 3 },
15463
- UNAVAILABLE: { code: "UNAVAILABLE", exit: 4 }
15464
- };
15465
- if (nodeCode === "ENOENT") return new CLIError("INVALID_ARGUMENT", "share input was not found", 2);
15466
- if (nodeCode === "EISDIR") return new CLIError("INVALID_ARGUMENT", "share input must be a Markdown file", 2);
15467
- if (error instanceof TypeError) return new CLIError("INVALID_ARGUMENT", "share input is invalid", 2);
15468
- const mapped = typeof nodeCode === "string" && known[nodeCode] !== void 0 ? known[nodeCode] : known[message];
15469
- return new CLIError(mapped?.code ?? "INVALID_ARGUMENT", mapped ? mapped.code : "share operation failed", mapped?.exit ?? 2);
15470
- }
15471
- function inputUrl(value, stdin) {
15472
- if (stdin || value === "-") return readBoundedUrlStdin();
15473
- if (value === void 0 || value.length === 0) throw new CLIError("INVALID_ARGUMENT", "a share URL or - is required", 2);
15474
- return Promise.resolve(value);
15475
- }
15476
- async function inspectShareInputOnce(value, stdin, expectedOrigin, dependencies = {}) {
15477
- const link2 = stdin || value === "-" ? await (dependencies.read ?? readBoundedUrlStdin)() : await inputUrl(value, false);
15478
- try {
15479
- parseNativeShareUrl(link2);
15480
- } catch {
15481
- return (dependencies.inspect ?? inspectShare)(link2, { expectedOrigin });
15418
+ or(decoder) {
15419
+ return or3(this, decoder);
15482
15420
  }
15483
- throw new CLIError("UNSUPPORTED_LINK", "native bearer links are opaque; receive the link to verify access", 2);
15484
- }
15485
- function jsonOutput(options, command) {
15486
- return options.json === true || command.optsWithGlobals().json === true;
15487
- }
15488
- function expires(value) {
15489
- try {
15490
- return new Date(Date.now() + parseDuration(value));
15491
- } catch {
15492
- throw new CLIError("INVALID_ARGUMENT", "invalid expiry duration", 2);
15421
+ decode(input) {
15422
+ const prefix = input[0];
15423
+ const decoder = this.decoders[prefix];
15424
+ if (decoder != null) {
15425
+ return decoder.decode(input);
15426
+ } else {
15427
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
15428
+ }
15493
15429
  }
15430
+ };
15431
+ function or3(left, right) {
15432
+ return new ComposedDecoder3({
15433
+ ...left.decoders ?? { [left.prefix]: left },
15434
+ ...right.decoders ?? { [right.prefix]: right }
15435
+ });
15494
15436
  }
15495
- async function rememberPublishedShare(result) {
15496
- const record = historyRecordForPublishedShare(result);
15497
- if (shareServices.records !== void 0) await shareServices.records.put(record);
15498
- return record;
15499
- }
15500
- function byteLimit(value) {
15501
- if (value === void 0) return void 0;
15502
- const parsed = Number(value);
15503
- if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed > MAX_SHARE_STDIN_BYTES) throw new CLIError("MAX_BYTES_EXCEEDED", "max-bytes must be between 1 and 100 MiB", 7);
15504
- return parsed;
15505
- }
15506
- function mediaTypeFor(filename) {
15507
- const extension = filename.toLowerCase().split(".").at(-1);
15508
- return extension === "md" || extension === "markdown" ? "text/markdown" : extension === "txt" ? "text/plain" : extension === "html" || extension === "htm" ? "text/html" : extension === "json" ? "application/json" : extension === "css" ? "text/css" : extension === "js" ? "text/javascript" : "application/octet-stream";
15437
+ var Codec3 = class {
15438
+ name;
15439
+ prefix;
15440
+ baseEncode;
15441
+ baseDecode;
15442
+ encoder;
15443
+ decoder;
15444
+ constructor(name, prefix, baseEncode, baseDecode) {
15445
+ this.name = name;
15446
+ this.prefix = prefix;
15447
+ this.baseEncode = baseEncode;
15448
+ this.baseDecode = baseDecode;
15449
+ this.encoder = new Encoder3(name, prefix, baseEncode);
15450
+ this.decoder = new Decoder3(name, prefix, baseDecode);
15451
+ }
15452
+ encode(input) {
15453
+ return this.encoder.encode(input);
15454
+ }
15455
+ decode(input) {
15456
+ return this.decoder.decode(input);
15457
+ }
15458
+ };
15459
+ function from3({ name, prefix, encode: encode32, decode: decode52 }) {
15460
+ return new Codec3(name, prefix, encode32, decode52);
15509
15461
  }
15510
- function requestedActions(values) {
15511
- const actions = values === void 0 || values.length === 0 ? ["read"] : values;
15512
- if (actions.some((value) => value !== "read" && value !== "list" && value !== "edit")) throw new CLIError("INVALID_ARGUMENT", "--action must be read, list, or edit", 2);
15513
- return [...new Set(actions)];
15462
+ function baseX3({ name, prefix, alphabet }) {
15463
+ const { encode: encode32, decode: decode52 } = base_x_default3(alphabet, name);
15464
+ return from3({
15465
+ prefix,
15466
+ name,
15467
+ encode: encode32,
15468
+ decode: (text) => coerce5(decode52(text))
15469
+ });
15514
15470
  }
15515
- function assertAggregateInputLimit(inputs, maxBytes) {
15516
- const limit = maxBytes ?? MAX_SHARE_STDIN_BYTES;
15517
- let total = 0;
15518
- for (const input of inputs) {
15519
- total += input.bytes.byteLength;
15520
- if (!Number.isSafeInteger(total) || total > limit) throw new CLIError("MAX_BYTES_EXCEEDED", "combined share input exceeds the configured byte limit", 7);
15471
+ function decode9(string, alphabetIdx, bitsPerChar, name) {
15472
+ let end = string.length;
15473
+ while (string[end - 1] === "=") {
15474
+ --end;
15521
15475
  }
15522
- }
15523
- function registerShareCommand(program2) {
15524
- const share = program2.command("share").description("Publish and consume TinyCloud Share links");
15525
- share.command("publish <files...>").description("Publish one or more bounded files as a Share").option("--name <filename>", "Filename for stdin input").option("--to <target>", "Share target", "anyone").option("--notify", "Request idempotent email delivery for addressed targets").option("--expires <duration>", "Share lifetime").option("--max-bytes <bytes>", "Bound input bytes").option("--media-type <type>", "Media type for a single input").option("--action <actions...>", "Addressed permission: read, list, or edit").option("--prefix", "Publish multiple inputs beneath one addressed prefix").option("--binary", "Allow non-UTF-8 bearer content").option("--json", "Print versioned redacted JSON").option("--viewer-origin <origin>", "Canonical HTTPS viewer origin", SHARE_ORIGIN).action(async (files, options, command) => {
15526
- try {
15527
- const json = jsonOutput(options, command);
15528
- const maxBytes = byteLimit(options.maxBytes);
15529
- if (files.length === 0 || files.includes("-") && files.length > 1) throw new CLIError("INVALID_ARGUMENT", "stdin must be the only publish input", 2);
15530
- const name = files.length === 1 ? options.name : void 0;
15531
- for (const file of files) shareInputFilename(file, name);
15532
- const inputs = await Promise.all(files.map((file) => readShareInput(file, name, maxBytes)));
15533
- assertAggregateInputLimit(inputs, maxBytes);
15534
- const target = parseShareTarget(options.to);
15535
- const actions = requestedActions(options.action);
15536
- if (options.prefix && target.kind === "bearer") throw new CLIError("INVALID_ARGUMENT", "--prefix requires an addressed target", 2);
15537
- if (inputs.length > 1 && target.kind === "bearer") throw new CLIError("UNSUPPORTED_LINK", "multiple files require an addressed target", 2);
15538
- if (inputs.length > 1 && !options.prefix) throw new CLIError("INVALID_ARGUMENT", "multiple files require --prefix", 2);
15539
- if (options.notify === true && target.kind !== "email") throw new CLIError("INVALID_ARGUMENT", "--notify requires an exact email target", 2);
15540
- const result = await publishTargetShare({
15541
- source: inputs[0].bytes,
15542
- filename: inputs[0].filename,
15543
- files: inputs.map((input) => ({ bytes: input.bytes, filename: input.filename, mediaType: mediaTypeFor(input.filename) })),
15544
- mediaType: options.mediaType ?? mediaTypeFor(inputs[0].filename),
15545
- allowBinary: options.binary === true,
15546
- target,
15547
- resourceKind: options.prefix || inputs.length > 1 ? "prefix" : "exact",
15548
- actions,
15549
- expiresAt: expires(options.expires ?? "7d"),
15550
- expiryWasExplicit: options.expires !== void 0,
15551
- origin: options.viewerOrigin,
15552
- ...maxBytes === void 0 ? {} : { maxBytes },
15553
- notify: options.notify === true,
15554
- targetAdapter: shareServices.targetAdapter
15555
- });
15556
- if ("state" in result) {
15557
- if (json) {
15558
- writeJson2({ protocol: "tinycloud-share", version: 1, authorization: authorizationRequiredJson(result) });
15559
- process.exitCode = 6;
15560
- return;
15561
- }
15562
- throw new CLIError(result.method === "openkey-device" ? "DEVICE_AUTH_REQUIRED" : "CLAIM_REQUIRED", "recipient authorization is required; continue through the configured authority adapter", 6);
15563
- }
15564
- const record = await rememberPublishedShare(result);
15565
- if (options.notify === true && target.kind === "email") {
15566
- if (shareServices.delivery === void 0) throw new CLIError("AUTH_REQUIRED", "delivery authority is not configured", 3);
15567
- const recipient = record.recipientMatcher.kind === "exactEmail" ? record.recipientMatcher.value : target.address;
15568
- const delivery = await notifyShare({ shareId: record.shareId, recipient, record, adapter: shareServices.delivery });
15569
- if (delivery.state === "partial-failure") process.exitCode = 9;
15570
- }
15571
- if (result.metadata.expiryClamped === true) process.stderr.write(`Share expiry clamped to session expiry (${result.metadata.expiresAt}).
15572
- `);
15573
- if (json) writeJson2({ ...redactPublishedShare(result), expiryClamped: result.metadata.expiryClamped === true });
15574
- else publishHuman(result);
15575
- } catch (error) {
15576
- handleError(shareCliError(error));
15476
+ const out = new Uint8Array(end * bitsPerChar / 8 | 0);
15477
+ let bits = 0;
15478
+ let buffer = 0;
15479
+ let written = 0;
15480
+ for (let i = 0; i < end; ++i) {
15481
+ const value = alphabetIdx[string[i]];
15482
+ if (value === void 0) {
15483
+ throw new SyntaxError(`Non-${name} character`);
15577
15484
  }
15578
- });
15579
- share.command("inspect [url]").description("Verify a share link and print safe metadata").option("--stdin", "Read the complete URL from stdin").option("--json", "Print versioned redacted JSON").option("--viewer-origin <origin>", "Require this canonical Share origin", SHARE_ORIGIN).action(async (url, options, command) => {
15580
- try {
15581
- const json = jsonOutput(options, command);
15582
- const result = await inspectShareInputOnce(url, options.stdin === true, options.viewerOrigin);
15583
- if (json) writeJson2(result);
15584
- else inspectHuman(result);
15585
- } catch (error) {
15586
- handleError(shareCliError(error));
15485
+ buffer = buffer << bitsPerChar | value;
15486
+ bits += bitsPerChar;
15487
+ if (bits >= 8) {
15488
+ bits -= 8;
15489
+ out[written++] = 255 & buffer >> bits;
15587
15490
  }
15588
- });
15589
- share.command("receive [url]").description("Verify and receive a share link").option("--stdin", "Read the complete URL from stdin").option("--output <directory>", "Create the file in this directory").option("--stdout", "Write verified plaintext bytes to stdout").option("--force", "Allow replacing an existing non-symlink output").option("--max-bytes <bytes>", "Bound received content bytes").option("--json", "Print versioned redacted JSON").option("--viewer-origin <origin>", "Require this canonical Share origin", SHARE_ORIGIN).action(async (url, options, command) => {
15590
- try {
15591
- const json = jsonOutput(options, command);
15592
- if (options.stdout && json) throw new CLIError("INVALID_ARGUMENT", "--stdout and --json are mutually exclusive", 2);
15593
- const maxBytes = byteLimit(options.maxBytes);
15594
- const link2 = await inputUrl(url, options.stdin === true);
15595
- let nativeLink = false;
15596
- try {
15597
- parseNativeShareUrl(link2);
15598
- nativeLink = true;
15599
- } catch {
15600
- }
15601
- if (nativeLink) {
15602
- if (shareServices.nativeReader === void 0) throw new CLIError("AUTH_REQUIRED", "native TinyCloud receive is not configured", 3);
15603
- const native = await shareServices.nativeReader(link2);
15604
- if (maxBytes !== void 0 && native.bytes.byteLength > maxBytes) throw new CLIError("MAX_BYTES_EXCEEDED", "shared content exceeds max-bytes", 7);
15605
- if (options.stdout) {
15606
- process.stdout.write(Buffer.from(native.bytes));
15607
- return;
15608
- }
15609
- const output2 = await writeShareOutput(options.output ?? ".", native.filename, native.bytes, options.force === true);
15610
- if (json) writeJson2({ protocol: "tinycloud-share", version: 1, path: output2, transport: "native" });
15611
- else receiveHuman(output2);
15612
- return;
15613
- }
15614
- const result = await receiveShare(link2, {
15615
- expectedOrigin: options.viewerOrigin,
15616
- ...maxBytes === void 0 ? {} : { maxContentBlobBytes: maxBytes }
15617
- });
15618
- if ("state" in result) {
15619
- if (json) {
15620
- writeJson2({ protocol: "tinycloud-share", version: 1, authorization: authorizationRequiredJson(result) });
15621
- process.exitCode = 6;
15622
- return;
15623
- }
15624
- throw new CLIError(result.method === "openkey-device" ? "DEVICE_AUTH_REQUIRED" : "CLAIM_REQUIRED", "recipient authorization is required; resume through the configured authority adapter", 6);
15625
- }
15626
- if (options.stdout) {
15627
- process.stdout.write(Buffer.from(result.bytes));
15628
- return;
15629
- }
15630
- const output = await writeShareOutput(options.output ?? ".", result.metadata.display.filename ?? "share.md", result.bytes, options.force === true);
15631
- if (json) receiveJson(result, output);
15632
- else receiveHuman(output);
15633
- } catch (error) {
15634
- handleError(shareCliError(error));
15491
+ }
15492
+ if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) {
15493
+ throw new SyntaxError("Unexpected end of data");
15494
+ }
15495
+ return out;
15496
+ }
15497
+ function encode5(data, alphabet, bitsPerChar) {
15498
+ const pad = alphabet[alphabet.length - 1] === "=";
15499
+ const mask = (1 << bitsPerChar) - 1;
15500
+ let out = "";
15501
+ let bits = 0;
15502
+ let buffer = 0;
15503
+ for (let i = 0; i < data.length; ++i) {
15504
+ buffer = buffer << 8 | data[i];
15505
+ bits += 8;
15506
+ while (bits > bitsPerChar) {
15507
+ bits -= bitsPerChar;
15508
+ out += alphabet[mask & buffer >> bits];
15635
15509
  }
15636
- });
15637
- share.command("list").description("List encrypted sender history without complete bearer URLs").option("--json", "Print versioned redacted JSON").action(async (options, command) => {
15638
- try {
15639
- const json = jsonOutput(options, command);
15640
- if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
15641
- const result = await listShares(shareServices.records);
15642
- if (json) writeJson2({ protocol: "tinycloud-share", version: 1, shares: result });
15643
- else process.stdout.write(result.map((item) => `${item.shareId} ${item.target} ${item.expiresAt}`).join("\n") + (result.length ? "\n" : ""));
15644
- } catch (error) {
15645
- handleError(shareCliError(error));
15510
+ }
15511
+ if (bits !== 0) {
15512
+ out += alphabet[mask & buffer << bitsPerChar - bits];
15513
+ }
15514
+ if (pad) {
15515
+ while ((out.length * bitsPerChar & 7) !== 0) {
15516
+ out += "=";
15646
15517
  }
15647
- });
15648
- share.command("show <id>").description("Show one redacted sender-history record").option("--reveal-link", "Explicitly include the complete link").option("--json", "Print versioned redacted JSON").action(async (id, options, command) => {
15649
- try {
15650
- const json = jsonOutput(options, command);
15651
- if (options.revealLink && json) throw new CLIError("INVALID_ARGUMENT", "--reveal-link cannot be combined with --json", 2);
15652
- if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
15653
- const result = await showShare({ storage: shareServices.records, shareId: id, revealLink: options.revealLink === true, link: options.revealLink ? await shareServices.linkFor?.(id) : void 0 });
15654
- if (json) writeJson2({ protocol: "tinycloud-share", version: 1, share: result });
15655
- else writeJson2(result);
15656
- } catch (error) {
15657
- handleError(shareCliError(error));
15658
- }
15659
- });
15660
- share.command("notify <id>").description("Retry idempotent delivery without recreating the share").requiredOption("--to <address>", "Recipient email").option("--json", "Print versioned JSON").action(async (id, options, command) => {
15661
- try {
15662
- const json = jsonOutput(options, command);
15663
- if (shareServices.delivery === void 0) throw new CLIError("AUTH_REQUIRED", "delivery authority is not configured", 3);
15664
- if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
15665
- const record = await shareServices.records.get(id);
15666
- if (record === void 0) throw new CLIError("NOT_FOUND", "share not found", 4);
15667
- const result = await notifyShare({ shareId: id, recipient: options.to, record, adapter: shareServices.delivery });
15668
- if (json) writeJson2(result);
15669
- else process.stdout.write(`${result.state}
15670
- `);
15671
- if (result.state === "partial-failure") process.exitCode = 9;
15672
- } catch (error) {
15673
- handleError(shareCliError(error));
15674
- }
15675
- });
15676
- share.command("revoke <id>").description("Revoke addressed shares; report bearer retention honestly").option("--ancestor", "Revoke the owner delegation ancestry").option("--json", "Print versioned JSON").action(async (id, options, command) => {
15677
- try {
15678
- const json = jsonOutput(options, command);
15679
- if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
15680
- const record = shareServices.getRecord ? await shareServices.getRecord(id) : await shareServices.records.get(id);
15681
- if (record === void 0) throw new CLIError("NOT_FOUND", "share not found", 4);
15682
- const result = await revokeShare({ record, records: shareServices.records, adapter: shareServices.revocation, scope: options.ancestor ? "ancestor" : "direct" });
15683
- if (result.state === "unsupported") {
15684
- throw new CLIError("UNSUPPORTED_TARGET", result.reason, 2);
15685
- }
15686
- if (json) writeJson2({ protocol: "tinycloud-share", version: 1, result });
15687
- else process.stdout.write(`${result.state}
15688
- `);
15689
- } catch (error) {
15690
- handleError(shareCliError(error));
15518
+ }
15519
+ return out;
15520
+ }
15521
+ function createAlphabetIdx3(alphabet) {
15522
+ const alphabetIdx = {};
15523
+ for (let i = 0; i < alphabet.length; ++i) {
15524
+ alphabetIdx[alphabet[i]] = i;
15525
+ }
15526
+ return alphabetIdx;
15527
+ }
15528
+ function rfc46483({ name, prefix, bitsPerChar, alphabet }) {
15529
+ const alphabetIdx = createAlphabetIdx3(alphabet);
15530
+ return from3({
15531
+ prefix,
15532
+ name,
15533
+ encode(input) {
15534
+ return encode5(input, alphabet, bitsPerChar);
15535
+ },
15536
+ decode(input) {
15537
+ return decode9(input, alphabetIdx, bitsPerChar, name);
15691
15538
  }
15692
15539
  });
15693
15540
  }
15694
-
15695
- // src/share/adapters.ts
15696
- init_profiles();
15697
- import { readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
15698
- import { join as join6 } from "path";
15699
- import { createHash } from "crypto";
15700
-
15701
- // ../share-envelope/dist/index.js
15702
- init_zod();
15703
- var empty3 = new Uint8Array(0);
15704
- function equals5(aa, bb) {
15705
- if (aa === bb) {
15706
- return true;
15541
+ var base323 = rfc46483({
15542
+ prefix: "b",
15543
+ name: "base32",
15544
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567",
15545
+ bitsPerChar: 5
15546
+ });
15547
+ var base32upper3 = rfc46483({
15548
+ prefix: "B",
15549
+ name: "base32upper",
15550
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
15551
+ bitsPerChar: 5
15552
+ });
15553
+ var base32pad3 = rfc46483({
15554
+ prefix: "c",
15555
+ name: "base32pad",
15556
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
15557
+ bitsPerChar: 5
15558
+ });
15559
+ var base32padupper3 = rfc46483({
15560
+ prefix: "C",
15561
+ name: "base32padupper",
15562
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
15563
+ bitsPerChar: 5
15564
+ });
15565
+ var base32hex3 = rfc46483({
15566
+ prefix: "v",
15567
+ name: "base32hex",
15568
+ alphabet: "0123456789abcdefghijklmnopqrstuv",
15569
+ bitsPerChar: 5
15570
+ });
15571
+ var base32hexupper3 = rfc46483({
15572
+ prefix: "V",
15573
+ name: "base32hexupper",
15574
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
15575
+ bitsPerChar: 5
15576
+ });
15577
+ var base32hexpad3 = rfc46483({
15578
+ prefix: "t",
15579
+ name: "base32hexpad",
15580
+ alphabet: "0123456789abcdefghijklmnopqrstuv=",
15581
+ bitsPerChar: 5
15582
+ });
15583
+ var base32hexpadupper3 = rfc46483({
15584
+ prefix: "T",
15585
+ name: "base32hexpadupper",
15586
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
15587
+ bitsPerChar: 5
15588
+ });
15589
+ var base32z3 = rfc46483({
15590
+ prefix: "h",
15591
+ name: "base32z",
15592
+ alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
15593
+ bitsPerChar: 5
15594
+ });
15595
+ var base363 = baseX3({
15596
+ prefix: "k",
15597
+ name: "base36",
15598
+ alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
15599
+ });
15600
+ var base36upper3 = baseX3({
15601
+ prefix: "K",
15602
+ name: "base36upper",
15603
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
15604
+ });
15605
+ var base58btc3 = baseX3({
15606
+ name: "base58btc",
15607
+ prefix: "z",
15608
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
15609
+ });
15610
+ var base58flickr3 = baseX3({
15611
+ name: "base58flickr",
15612
+ prefix: "Z",
15613
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
15614
+ });
15615
+ var encode_13 = encode22;
15616
+ var MSB3 = 128;
15617
+ var REST3 = 127;
15618
+ var MSBALL3 = ~REST3;
15619
+ var INT3 = Math.pow(2, 31);
15620
+ function encode22(num, out, offset) {
15621
+ out = out || [];
15622
+ offset = offset || 0;
15623
+ var oldOffset = offset;
15624
+ while (num >= INT3) {
15625
+ out[offset++] = num & 255 | MSB3;
15626
+ num /= 128;
15707
15627
  }
15708
- if (aa.byteLength !== bb.byteLength) {
15709
- return false;
15628
+ while (num & MSBALL3) {
15629
+ out[offset++] = num & 255 | MSB3;
15630
+ num >>>= 7;
15710
15631
  }
15711
- for (let ii = 0; ii < aa.byteLength; ii++) {
15712
- if (aa[ii] !== bb[ii]) {
15713
- return false;
15632
+ out[offset] = num | 0;
15633
+ encode22.bytes = offset - oldOffset + 1;
15634
+ return out;
15635
+ }
15636
+ var decode22 = read3;
15637
+ var MSB$13 = 128;
15638
+ var REST$13 = 127;
15639
+ function read3(buf, offset) {
15640
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
15641
+ do {
15642
+ if (counter >= l) {
15643
+ read3.bytes = 0;
15644
+ throw new RangeError("Could not decode varint");
15714
15645
  }
15715
- }
15716
- return true;
15646
+ b = buf[counter++];
15647
+ res += shift < 28 ? (b & REST$13) << shift : (b & REST$13) * Math.pow(2, shift);
15648
+ shift += 7;
15649
+ } while (b >= MSB$13);
15650
+ read3.bytes = counter - offset;
15651
+ return res;
15717
15652
  }
15718
- function coerce5(o) {
15719
- if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
15720
- return o;
15721
- }
15722
- if (o instanceof ArrayBuffer) {
15723
- return new Uint8Array(o);
15653
+ var N13 = Math.pow(2, 7);
15654
+ var N23 = Math.pow(2, 14);
15655
+ var N33 = Math.pow(2, 21);
15656
+ var N43 = Math.pow(2, 28);
15657
+ var N53 = Math.pow(2, 35);
15658
+ var N63 = Math.pow(2, 42);
15659
+ var N73 = Math.pow(2, 49);
15660
+ var N83 = Math.pow(2, 56);
15661
+ var N93 = Math.pow(2, 63);
15662
+ var length3 = function(value) {
15663
+ return value < N13 ? 1 : value < N23 ? 2 : value < N33 ? 3 : value < N43 ? 4 : value < N53 ? 5 : value < N63 ? 6 : value < N73 ? 7 : value < N83 ? 8 : value < N93 ? 9 : 10;
15664
+ };
15665
+ var varint3 = {
15666
+ encode: encode_13,
15667
+ decode: decode22,
15668
+ encodingLength: length3
15669
+ };
15670
+ var _brrp_varint3 = varint3;
15671
+ var varint_default3 = _brrp_varint3;
15672
+ function decode32(data, offset = 0) {
15673
+ const code22 = varint_default3.decode(data, offset);
15674
+ return [code22, varint_default3.decode.bytes];
15675
+ }
15676
+ function encodeTo3(int, target, offset = 0) {
15677
+ varint_default3.encode(int, target, offset);
15678
+ return target;
15679
+ }
15680
+ function encodingLength3(int) {
15681
+ return varint_default3.encodingLength(int);
15682
+ }
15683
+ function create3(code22, digest) {
15684
+ const size = digest.byteLength;
15685
+ const sizeOffset = encodingLength3(code22);
15686
+ const digestOffset = sizeOffset + encodingLength3(size);
15687
+ const bytes = new Uint8Array(digestOffset + size);
15688
+ encodeTo3(code22, bytes, 0);
15689
+ encodeTo3(size, bytes, sizeOffset);
15690
+ bytes.set(digest, digestOffset);
15691
+ return new Digest3(code22, size, digest, bytes);
15692
+ }
15693
+ function decode42(multihash) {
15694
+ const bytes = coerce5(multihash);
15695
+ const [code22, sizeOffset] = decode32(bytes);
15696
+ const [size, digestOffset] = decode32(bytes.subarray(sizeOffset));
15697
+ const digest = bytes.subarray(sizeOffset + digestOffset);
15698
+ if (digest.byteLength !== size) {
15699
+ throw new Error("Incorrect length");
15724
15700
  }
15725
- if (ArrayBuffer.isView(o)) {
15726
- return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
15701
+ return new Digest3(code22, size, digest, bytes);
15702
+ }
15703
+ function equals22(a, b) {
15704
+ if (a === b) {
15705
+ return true;
15706
+ } else {
15707
+ const data = b;
15708
+ return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals5(a.bytes, data.bytes);
15727
15709
  }
15728
- throw new Error("Unknown type, must be binary type");
15729
15710
  }
15730
- function base3(ALPHABET, name) {
15731
- if (ALPHABET.length >= 255) {
15732
- throw new TypeError("Alphabet too long");
15711
+ var Digest3 = class {
15712
+ code;
15713
+ size;
15714
+ digest;
15715
+ bytes;
15716
+ /**
15717
+ * Creates a multihash digest.
15718
+ */
15719
+ constructor(code22, size, digest, bytes) {
15720
+ this.code = code22;
15721
+ this.size = size;
15722
+ this.digest = digest;
15723
+ this.bytes = bytes;
15733
15724
  }
15734
- var BASE_MAP = new Uint8Array(256);
15735
- for (var j = 0; j < BASE_MAP.length; j++) {
15736
- BASE_MAP[j] = 255;
15725
+ };
15726
+ function format3(link2, base22) {
15727
+ const { bytes, version: version2 } = link2;
15728
+ switch (version2) {
15729
+ case 0:
15730
+ return toStringV03(bytes, baseCache3(link2), base22 ?? base58btc3.encoder);
15731
+ default:
15732
+ return toStringV13(bytes, baseCache3(link2), base22 ?? base323.encoder);
15737
15733
  }
15738
- for (var i = 0; i < ALPHABET.length; i++) {
15739
- var x = ALPHABET.charAt(i);
15740
- var xc = x.charCodeAt(0);
15741
- if (BASE_MAP[xc] !== 255) {
15742
- throw new TypeError(x + " is ambiguous");
15743
- }
15744
- BASE_MAP[xc] = i;
15734
+ }
15735
+ var cache3 = /* @__PURE__ */ new WeakMap();
15736
+ function baseCache3(cid) {
15737
+ const baseCache22 = cache3.get(cid);
15738
+ if (baseCache22 == null) {
15739
+ const baseCache32 = /* @__PURE__ */ new Map();
15740
+ cache3.set(cid, baseCache32);
15741
+ return baseCache32;
15745
15742
  }
15746
- var BASE = ALPHABET.length;
15747
- var LEADER = ALPHABET.charAt(0);
15748
- var FACTOR = Math.log(BASE) / Math.log(256);
15749
- var iFACTOR = Math.log(256) / Math.log(BASE);
15750
- function encode32(source) {
15751
- if (source instanceof Uint8Array)
15752
- ;
15753
- else if (ArrayBuffer.isView(source)) {
15754
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
15755
- } else if (Array.isArray(source)) {
15756
- source = Uint8Array.from(source);
15757
- }
15758
- if (!(source instanceof Uint8Array)) {
15759
- throw new TypeError("Expected Uint8Array");
15760
- }
15761
- if (source.length === 0) {
15762
- return "";
15763
- }
15764
- var zeroes = 0;
15765
- var length22 = 0;
15766
- var pbegin = 0;
15767
- var pend = source.length;
15768
- while (pbegin !== pend && source[pbegin] === 0) {
15769
- pbegin++;
15770
- zeroes++;
15771
- }
15772
- var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
15773
- var b58 = new Uint8Array(size);
15774
- while (pbegin !== pend) {
15775
- var carry = source[pbegin];
15776
- var i2 = 0;
15777
- for (var it1 = size - 1; (carry !== 0 || i2 < length22) && it1 !== -1; it1--, i2++) {
15778
- carry += 256 * b58[it1] >>> 0;
15779
- b58[it1] = carry % BASE >>> 0;
15780
- carry = carry / BASE >>> 0;
15743
+ return baseCache22;
15744
+ }
15745
+ var CID3 = class _CID3 {
15746
+ code;
15747
+ version;
15748
+ multihash;
15749
+ bytes;
15750
+ "/";
15751
+ /**
15752
+ * @param version - Version of the CID
15753
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
15754
+ * @param multihash - (Multi)hash of the of the content.
15755
+ */
15756
+ constructor(version2, code22, multihash, bytes) {
15757
+ this.code = code22;
15758
+ this.version = version2;
15759
+ this.multihash = multihash;
15760
+ this.bytes = bytes;
15761
+ this["/"] = bytes;
15762
+ }
15763
+ /**
15764
+ * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
15765
+ * please either use `CID.asCID(cid)` or switch to new signalling mechanism
15766
+ *
15767
+ * @deprecated
15768
+ */
15769
+ get asCID() {
15770
+ return this;
15771
+ }
15772
+ // ArrayBufferView
15773
+ get byteOffset() {
15774
+ return this.bytes.byteOffset;
15775
+ }
15776
+ // ArrayBufferView
15777
+ get byteLength() {
15778
+ return this.bytes.byteLength;
15779
+ }
15780
+ toV0() {
15781
+ switch (this.version) {
15782
+ case 0: {
15783
+ return this;
15781
15784
  }
15782
- if (carry !== 0) {
15783
- throw new Error("Non-zero carry");
15785
+ case 1: {
15786
+ const { code: code22, multihash } = this;
15787
+ if (code22 !== DAG_PB_CODE3) {
15788
+ throw new Error("Cannot convert a non dag-pb CID to CIDv0");
15789
+ }
15790
+ if (multihash.code !== SHA_256_CODE3) {
15791
+ throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
15792
+ }
15793
+ return _CID3.createV0(multihash);
15794
+ }
15795
+ default: {
15796
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
15784
15797
  }
15785
- length22 = i2;
15786
- pbegin++;
15787
- }
15788
- var it2 = size - length22;
15789
- while (it2 !== size && b58[it2] === 0) {
15790
- it2++;
15791
- }
15792
- var str = LEADER.repeat(zeroes);
15793
- for (; it2 < size; ++it2) {
15794
- str += ALPHABET.charAt(b58[it2]);
15795
15798
  }
15796
- return str;
15797
15799
  }
15798
- function decodeUnsafe(source) {
15799
- if (typeof source !== "string") {
15800
- throw new TypeError("Expected String");
15801
- }
15802
- if (source.length === 0) {
15803
- return new Uint8Array();
15804
- }
15805
- var psz = 0;
15806
- if (source[psz] === " ") {
15807
- return;
15808
- }
15809
- var zeroes = 0;
15810
- var length22 = 0;
15811
- while (source[psz] === LEADER) {
15812
- zeroes++;
15813
- psz++;
15814
- }
15815
- var size = (source.length - psz) * FACTOR + 1 >>> 0;
15816
- var b256 = new Uint8Array(size);
15817
- while (source[psz]) {
15818
- var carry = BASE_MAP[source.charCodeAt(psz)];
15819
- if (carry === 255) {
15820
- return;
15800
+ toV1() {
15801
+ switch (this.version) {
15802
+ case 0: {
15803
+ const { code: code22, digest } = this.multihash;
15804
+ const multihash = create3(code22, digest);
15805
+ return _CID3.createV1(this.code, multihash);
15821
15806
  }
15822
- var i2 = 0;
15823
- for (var it3 = size - 1; (carry !== 0 || i2 < length22) && it3 !== -1; it3--, i2++) {
15824
- carry += BASE * b256[it3] >>> 0;
15825
- b256[it3] = carry % 256 >>> 0;
15826
- carry = carry / 256 >>> 0;
15807
+ case 1: {
15808
+ return this;
15827
15809
  }
15828
- if (carry !== 0) {
15829
- throw new Error("Non-zero carry");
15810
+ default: {
15811
+ throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
15830
15812
  }
15831
- length22 = i2;
15832
- psz++;
15833
- }
15834
- if (source[psz] === " ") {
15835
- return;
15836
- }
15837
- var it4 = size - length22;
15838
- while (it4 !== size && b256[it4] === 0) {
15839
- it4++;
15840
- }
15841
- var vch = new Uint8Array(zeroes + (size - it4));
15842
- var j2 = zeroes;
15843
- while (it4 !== size) {
15844
- vch[j2++] = b256[it4++];
15845
- }
15846
- return vch;
15847
- }
15848
- function decode52(string) {
15849
- var buffer = decodeUnsafe(string);
15850
- if (buffer) {
15851
- return buffer;
15852
15813
  }
15853
- throw new Error(`Non-${name} character`);
15854
- }
15855
- return {
15856
- encode: encode32,
15857
- decodeUnsafe,
15858
- decode: decode52
15859
- };
15860
- }
15861
- var src3 = base3;
15862
- var _brrp__multiformats_scope_baseX3 = src3;
15863
- var base_x_default3 = _brrp__multiformats_scope_baseX3;
15864
- var Encoder3 = class {
15865
- name;
15866
- prefix;
15867
- baseEncode;
15868
- constructor(name, prefix, baseEncode) {
15869
- this.name = name;
15870
- this.prefix = prefix;
15871
- this.baseEncode = baseEncode;
15872
15814
  }
15873
- encode(bytes) {
15874
- if (bytes instanceof Uint8Array) {
15875
- return `${this.prefix}${this.baseEncode(bytes)}`;
15876
- } else {
15877
- throw Error("Unknown type, must be binary type");
15878
- }
15815
+ equals(other) {
15816
+ return _CID3.equals(this, other);
15879
15817
  }
15880
- };
15881
- var Decoder3 = class {
15882
- name;
15883
- prefix;
15884
- baseDecode;
15885
- prefixCodePoint;
15886
- constructor(name, prefix, baseDecode) {
15887
- this.name = name;
15888
- this.prefix = prefix;
15889
- const prefixCodePoint = prefix.codePointAt(0);
15890
- if (prefixCodePoint === void 0) {
15891
- throw new Error("Invalid prefix character");
15892
- }
15893
- this.prefixCodePoint = prefixCodePoint;
15894
- this.baseDecode = baseDecode;
15818
+ static equals(self, other) {
15819
+ const unknown = other;
15820
+ return unknown != null && self.code === unknown.code && self.version === unknown.version && equals22(self.multihash, unknown.multihash);
15895
15821
  }
15896
- decode(text) {
15897
- if (typeof text === "string") {
15898
- if (text.codePointAt(0) !== this.prefixCodePoint) {
15899
- throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
15900
- }
15901
- return this.baseDecode(text.slice(this.prefix.length));
15902
- } else {
15903
- throw Error("Can only multibase decode strings");
15904
- }
15822
+ toString(base22) {
15823
+ return format3(this, base22);
15905
15824
  }
15906
- or(decoder) {
15907
- return or3(this, decoder);
15825
+ toJSON() {
15826
+ return { "/": format3(this) };
15908
15827
  }
15909
- };
15910
- var ComposedDecoder3 = class {
15911
- decoders;
15912
- constructor(decoders) {
15913
- this.decoders = decoders;
15828
+ link() {
15829
+ return this;
15914
15830
  }
15915
- or(decoder) {
15916
- return or3(this, decoder);
15831
+ [Symbol.toStringTag] = "CID";
15832
+ // Legacy
15833
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
15834
+ return `CID(${this.toString()})`;
15917
15835
  }
15918
- decode(input) {
15919
- const prefix = input[0];
15920
- const decoder = this.decoders[prefix];
15921
- if (decoder != null) {
15922
- return decoder.decode(input);
15923
- } else {
15924
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
15836
+ /**
15837
+ * Takes any input `value` and returns a `CID` instance if it was
15838
+ * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
15839
+ * it will return value back. If `value` is not instance of this CID
15840
+ * class, but is compatible CID it will return new instance of this
15841
+ * `CID` class. Otherwise returns null.
15842
+ *
15843
+ * This allows two different incompatible versions of CID library to
15844
+ * co-exist and interop as long as binary interface is compatible.
15845
+ */
15846
+ static asCID(input) {
15847
+ if (input == null) {
15848
+ return null;
15849
+ }
15850
+ const value = input;
15851
+ if (value instanceof _CID3) {
15852
+ return value;
15853
+ } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
15854
+ const { version: version2, code: code22, multihash, bytes } = value;
15855
+ return new _CID3(version2, code22, multihash, bytes ?? encodeCID3(version2, code22, multihash.bytes));
15856
+ } else if (value[cidSymbol3] === true) {
15857
+ const { version: version2, multihash, code: code22 } = value;
15858
+ const digest = decode42(multihash);
15859
+ return _CID3.create(version2, code22, digest);
15860
+ } else {
15861
+ return null;
15925
15862
  }
15926
15863
  }
15927
- };
15928
- function or3(left, right) {
15929
- return new ComposedDecoder3({
15930
- ...left.decoders ?? { [left.prefix]: left },
15931
- ...right.decoders ?? { [right.prefix]: right }
15932
- });
15933
- }
15934
- var Codec3 = class {
15935
- name;
15936
- prefix;
15937
- baseEncode;
15938
- baseDecode;
15939
- encoder;
15940
- decoder;
15941
- constructor(name, prefix, baseEncode, baseDecode) {
15942
- this.name = name;
15943
- this.prefix = prefix;
15944
- this.baseEncode = baseEncode;
15945
- this.baseDecode = baseDecode;
15946
- this.encoder = new Encoder3(name, prefix, baseEncode);
15947
- this.decoder = new Decoder3(name, prefix, baseDecode);
15948
- }
15949
- encode(input) {
15950
- return this.encoder.encode(input);
15864
+ /**
15865
+ * @param version - Version of the CID
15866
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
15867
+ * @param digest - (Multi)hash of the of the content.
15868
+ */
15869
+ static create(version2, code22, digest) {
15870
+ if (typeof code22 !== "number") {
15871
+ throw new Error("String codecs are no longer supported");
15872
+ }
15873
+ if (!(digest.bytes instanceof Uint8Array)) {
15874
+ throw new Error("Invalid digest");
15875
+ }
15876
+ switch (version2) {
15877
+ case 0: {
15878
+ if (code22 !== DAG_PB_CODE3) {
15879
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE3}) block encoding`);
15880
+ } else {
15881
+ return new _CID3(version2, code22, digest, digest.bytes);
15882
+ }
15883
+ }
15884
+ case 1: {
15885
+ const bytes = encodeCID3(version2, code22, digest.bytes);
15886
+ return new _CID3(version2, code22, digest, bytes);
15887
+ }
15888
+ default: {
15889
+ throw new Error("Invalid version");
15890
+ }
15891
+ }
15951
15892
  }
15952
- decode(input) {
15953
- return this.decoder.decode(input);
15893
+ /**
15894
+ * Simplified version of `create` for CIDv0.
15895
+ */
15896
+ static createV0(digest) {
15897
+ return _CID3.create(0, DAG_PB_CODE3, digest);
15954
15898
  }
15955
- };
15956
- function from3({ name, prefix, encode: encode32, decode: decode52 }) {
15957
- return new Codec3(name, prefix, encode32, decode52);
15958
- }
15959
- function baseX3({ name, prefix, alphabet }) {
15960
- const { encode: encode32, decode: decode52 } = base_x_default3(alphabet, name);
15961
- return from3({
15962
- prefix,
15963
- name,
15964
- encode: encode32,
15965
- decode: (text) => coerce5(decode52(text))
15966
- });
15967
- }
15968
- function decode9(string, alphabetIdx, bitsPerChar, name) {
15969
- let end = string.length;
15970
- while (string[end - 1] === "=") {
15971
- --end;
15899
+ /**
15900
+ * Simplified version of `create` for CIDv1.
15901
+ *
15902
+ * @param code - Content encoding format code.
15903
+ * @param digest - Multihash of the content.
15904
+ */
15905
+ static createV1(code22, digest) {
15906
+ return _CID3.create(1, code22, digest);
15972
15907
  }
15973
- const out = new Uint8Array(end * bitsPerChar / 8 | 0);
15974
- let bits = 0;
15975
- let buffer = 0;
15976
- let written = 0;
15977
- for (let i = 0; i < end; ++i) {
15978
- const value = alphabetIdx[string[i]];
15979
- if (value === void 0) {
15980
- throw new SyntaxError(`Non-${name} character`);
15981
- }
15982
- buffer = buffer << bitsPerChar | value;
15983
- bits += bitsPerChar;
15984
- if (bits >= 8) {
15985
- bits -= 8;
15986
- out[written++] = 255 & buffer >> bits;
15908
+ /**
15909
+ * Decoded a CID from its binary representation. The byte array must contain
15910
+ * only the CID with no additional bytes.
15911
+ *
15912
+ * An error will be thrown if the bytes provided do not contain a valid
15913
+ * binary representation of a CID.
15914
+ */
15915
+ static decode(bytes) {
15916
+ const [cid, remainder] = _CID3.decodeFirst(bytes);
15917
+ if (remainder.length !== 0) {
15918
+ throw new Error("Incorrect length");
15987
15919
  }
15920
+ return cid;
15988
15921
  }
15989
- if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) {
15990
- throw new SyntaxError("Unexpected end of data");
15922
+ /**
15923
+ * Decoded a CID from its binary representation at the beginning of a byte
15924
+ * array.
15925
+ *
15926
+ * Returns an array with the first element containing the CID and the second
15927
+ * element containing the remainder of the original byte array. The remainder
15928
+ * will be a zero-length byte array if the provided bytes only contained a
15929
+ * binary CID representation.
15930
+ */
15931
+ static decodeFirst(bytes) {
15932
+ const specs = _CID3.inspectBytes(bytes);
15933
+ const prefixSize = specs.size - specs.multihashSize;
15934
+ const multihashBytes = coerce5(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
15935
+ if (multihashBytes.byteLength !== specs.multihashSize) {
15936
+ throw new Error("Incorrect length");
15937
+ }
15938
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
15939
+ const digest = new Digest3(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
15940
+ const cid = specs.version === 0 ? _CID3.createV0(digest) : _CID3.createV1(specs.codec, digest);
15941
+ return [cid, bytes.subarray(specs.size)];
15991
15942
  }
15992
- return out;
15993
- }
15994
- function encode5(data, alphabet, bitsPerChar) {
15995
- const pad = alphabet[alphabet.length - 1] === "=";
15996
- const mask = (1 << bitsPerChar) - 1;
15997
- let out = "";
15998
- let bits = 0;
15999
- let buffer = 0;
16000
- for (let i = 0; i < data.length; ++i) {
16001
- buffer = buffer << 8 | data[i];
16002
- bits += 8;
16003
- while (bits > bitsPerChar) {
16004
- bits -= bitsPerChar;
16005
- out += alphabet[mask & buffer >> bits];
15943
+ /**
15944
+ * Inspect the initial bytes of a CID to determine its properties.
15945
+ *
15946
+ * Involves decoding up to 4 varints. Typically this will require only 4 to 6
15947
+ * bytes but for larger multicodec code values and larger multihash digest
15948
+ * lengths these varints can be quite large. It is recommended that at least
15949
+ * 10 bytes be made available in the `initialBytes` argument for a complete
15950
+ * inspection.
15951
+ */
15952
+ static inspectBytes(initialBytes) {
15953
+ let offset = 0;
15954
+ const next = () => {
15955
+ const [i, length22] = decode32(initialBytes.subarray(offset));
15956
+ offset += length22;
15957
+ return i;
15958
+ };
15959
+ let version2 = next();
15960
+ let codec = DAG_PB_CODE3;
15961
+ if (version2 === 18) {
15962
+ version2 = 0;
15963
+ offset = 0;
15964
+ } else {
15965
+ codec = next();
15966
+ }
15967
+ if (version2 !== 0 && version2 !== 1) {
15968
+ throw new RangeError(`Invalid CID version ${version2}`);
16006
15969
  }
15970
+ const prefixSize = offset;
15971
+ const multihashCode = next();
15972
+ const digestSize = next();
15973
+ const size = offset + digestSize;
15974
+ const multihashSize = size - prefixSize;
15975
+ return { version: version2, codec, multihashCode, digestSize, multihashSize, size };
16007
15976
  }
16008
- if (bits !== 0) {
16009
- out += alphabet[mask & buffer << bitsPerChar - bits];
15977
+ /**
15978
+ * Takes cid in a string representation and creates an instance. If `base`
15979
+ * decoder is not provided will use a default from the configuration. It will
15980
+ * throw an error if encoding of the CID is not compatible with supplied (or
15981
+ * a default decoder).
15982
+ */
15983
+ static parse(source, base22) {
15984
+ const [prefix, bytes] = parseCIDtoBytes3(source, base22);
15985
+ const cid = _CID3.decode(bytes);
15986
+ if (cid.version === 0 && source[0] !== "Q") {
15987
+ throw Error("Version 0 CID string must not include multibase prefix");
15988
+ }
15989
+ baseCache3(cid).set(prefix, source);
15990
+ return cid;
16010
15991
  }
16011
- if (pad) {
16012
- while ((out.length * bitsPerChar & 7) !== 0) {
16013
- out += "=";
15992
+ };
15993
+ function parseCIDtoBytes3(source, base22) {
15994
+ switch (source[0]) {
15995
+ // CIDv0 is parsed differently
15996
+ case "Q": {
15997
+ const decoder = base22 ?? base58btc3;
15998
+ return [
15999
+ base58btc3.prefix,
16000
+ decoder.decode(`${base58btc3.prefix}${source}`)
16001
+ ];
16002
+ }
16003
+ case base58btc3.prefix: {
16004
+ const decoder = base22 ?? base58btc3;
16005
+ return [base58btc3.prefix, decoder.decode(source)];
16006
+ }
16007
+ case base323.prefix: {
16008
+ const decoder = base22 ?? base323;
16009
+ return [base323.prefix, decoder.decode(source)];
16010
+ }
16011
+ case base363.prefix: {
16012
+ const decoder = base22 ?? base363;
16013
+ return [base363.prefix, decoder.decode(source)];
16014
+ }
16015
+ default: {
16016
+ if (base22 == null) {
16017
+ throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");
16018
+ }
16019
+ return [source[0], base22.decode(source)];
16014
16020
  }
16015
16021
  }
16016
- return out;
16017
16022
  }
16018
- function createAlphabetIdx3(alphabet) {
16019
- const alphabetIdx = {};
16020
- for (let i = 0; i < alphabet.length; ++i) {
16021
- alphabetIdx[alphabet[i]] = i;
16023
+ function toStringV03(bytes, cache22, base22) {
16024
+ const { prefix } = base22;
16025
+ if (prefix !== base58btc3.prefix) {
16026
+ throw Error(`Cannot string encode V0 in ${base22.name} encoding`);
16027
+ }
16028
+ const cid = cache22.get(prefix);
16029
+ if (cid == null) {
16030
+ const cid2 = base22.encode(bytes).slice(1);
16031
+ cache22.set(prefix, cid2);
16032
+ return cid2;
16033
+ } else {
16034
+ return cid;
16022
16035
  }
16023
- return alphabetIdx;
16024
16036
  }
16025
- function rfc46483({ name, prefix, bitsPerChar, alphabet }) {
16026
- const alphabetIdx = createAlphabetIdx3(alphabet);
16027
- return from3({
16028
- prefix,
16029
- name,
16030
- encode(input) {
16031
- return encode5(input, alphabet, bitsPerChar);
16032
- },
16033
- decode(input) {
16034
- return decode9(input, alphabetIdx, bitsPerChar, name);
16035
- }
16036
- });
16037
+ function toStringV13(bytes, cache22, base22) {
16038
+ const { prefix } = base22;
16039
+ const cid = cache22.get(prefix);
16040
+ if (cid == null) {
16041
+ const cid2 = base22.encode(bytes);
16042
+ cache22.set(prefix, cid2);
16043
+ return cid2;
16044
+ } else {
16045
+ return cid;
16046
+ }
16037
16047
  }
16038
- var base323 = rfc46483({
16039
- prefix: "b",
16040
- name: "base32",
16041
- alphabet: "abcdefghijklmnopqrstuvwxyz234567",
16042
- bitsPerChar: 5
16043
- });
16044
- var base32upper3 = rfc46483({
16045
- prefix: "B",
16046
- name: "base32upper",
16047
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
16048
- bitsPerChar: 5
16049
- });
16050
- var base32pad3 = rfc46483({
16051
- prefix: "c",
16052
- name: "base32pad",
16053
- alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
16054
- bitsPerChar: 5
16055
- });
16056
- var base32padupper3 = rfc46483({
16057
- prefix: "C",
16058
- name: "base32padupper",
16059
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
16060
- bitsPerChar: 5
16061
- });
16062
- var base32hex3 = rfc46483({
16063
- prefix: "v",
16064
- name: "base32hex",
16065
- alphabet: "0123456789abcdefghijklmnopqrstuv",
16066
- bitsPerChar: 5
16067
- });
16068
- var base32hexupper3 = rfc46483({
16069
- prefix: "V",
16070
- name: "base32hexupper",
16071
- alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
16072
- bitsPerChar: 5
16073
- });
16074
- var base32hexpad3 = rfc46483({
16075
- prefix: "t",
16076
- name: "base32hexpad",
16077
- alphabet: "0123456789abcdefghijklmnopqrstuv=",
16078
- bitsPerChar: 5
16079
- });
16080
- var base32hexpadupper3 = rfc46483({
16081
- prefix: "T",
16082
- name: "base32hexpadupper",
16083
- alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
16084
- bitsPerChar: 5
16085
- });
16086
- var base32z3 = rfc46483({
16087
- prefix: "h",
16088
- name: "base32z",
16089
- alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
16090
- bitsPerChar: 5
16091
- });
16092
- var base363 = baseX3({
16093
- prefix: "k",
16094
- name: "base36",
16095
- alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
16048
+ var DAG_PB_CODE3 = 112;
16049
+ var SHA_256_CODE3 = 18;
16050
+ function encodeCID3(version2, code22, multihash) {
16051
+ const codeOffset = encodingLength3(version2);
16052
+ const hashOffset = codeOffset + encodingLength3(code22);
16053
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
16054
+ encodeTo3(version2, bytes, 0);
16055
+ encodeTo3(code22, bytes, codeOffset);
16056
+ bytes.set(multihash, hashOffset);
16057
+ return bytes;
16058
+ }
16059
+ var cidSymbol3 = /* @__PURE__ */ Symbol.for("@ipld/js-cid/CID");
16060
+ var code2 = 85;
16061
+ var SHA256_CODE2 = 18;
16062
+ function isCanonicalRawCid2(cidString) {
16063
+ let cid;
16064
+ try {
16065
+ cid = CID3.parse(cidString);
16066
+ } catch {
16067
+ return false;
16068
+ }
16069
+ return cid.version === 1 && cid.code === code2 && cid.multihash.code === SHA256_CODE2 && cid.toString() === cidString;
16070
+ }
16071
+ var base642 = rfc46483({
16072
+ prefix: "m",
16073
+ name: "base64",
16074
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
16075
+ bitsPerChar: 6
16096
16076
  });
16097
- var base36upper3 = baseX3({
16098
- prefix: "K",
16099
- name: "base36upper",
16100
- alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16077
+ var base64pad2 = rfc46483({
16078
+ prefix: "M",
16079
+ name: "base64pad",
16080
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
16081
+ bitsPerChar: 6
16101
16082
  });
16102
- var base58btc3 = baseX3({
16103
- name: "base58btc",
16104
- prefix: "z",
16105
- alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
16083
+ var base64url2 = rfc46483({
16084
+ prefix: "u",
16085
+ name: "base64url",
16086
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
16087
+ bitsPerChar: 6
16106
16088
  });
16107
- var base58flickr3 = baseX3({
16108
- name: "base58flickr",
16109
- prefix: "Z",
16110
- alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
16089
+ var base64urlpad2 = rfc46483({
16090
+ prefix: "U",
16091
+ name: "base64urlpad",
16092
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
16093
+ bitsPerChar: 6
16111
16094
  });
16112
- var encode_13 = encode22;
16113
- var MSB3 = 128;
16114
- var REST3 = 127;
16115
- var MSBALL3 = ~REST3;
16116
- var INT3 = Math.pow(2, 31);
16117
- function encode22(num, out, offset) {
16118
- out = out || [];
16119
- offset = offset || 0;
16120
- var oldOffset = offset;
16121
- while (num >= INT3) {
16122
- out[offset++] = num & 255 | MSB3;
16123
- num /= 128;
16124
- }
16125
- while (num & MSBALL3) {
16126
- out[offset++] = num & 255 | MSB3;
16127
- num >>>= 7;
16095
+ function fromBase64Url2(text) {
16096
+ const bytes = base64url2.baseDecode(text);
16097
+ if (base64url2.baseEncode(bytes) !== text) {
16098
+ throw new TypeError("non-canonical base64url input");
16128
16099
  }
16129
- out[offset] = num | 0;
16130
- encode22.bytes = offset - oldOffset + 1;
16131
- return out;
16132
- }
16133
- var decode22 = read3;
16134
- var MSB$13 = 128;
16135
- var REST$13 = 127;
16136
- function read3(buf, offset) {
16137
- var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
16138
- do {
16139
- if (counter >= l) {
16140
- read3.bytes = 0;
16141
- throw new RangeError("Could not decode varint");
16142
- }
16143
- b = buf[counter++];
16144
- res += shift < 28 ? (b & REST$13) << shift : (b & REST$13) * Math.pow(2, shift);
16145
- shift += 7;
16146
- } while (b >= MSB$13);
16147
- read3.bytes = counter - offset;
16148
- return res;
16149
- }
16150
- var N13 = Math.pow(2, 7);
16151
- var N23 = Math.pow(2, 14);
16152
- var N33 = Math.pow(2, 21);
16153
- var N43 = Math.pow(2, 28);
16154
- var N53 = Math.pow(2, 35);
16155
- var N63 = Math.pow(2, 42);
16156
- var N73 = Math.pow(2, 49);
16157
- var N83 = Math.pow(2, 56);
16158
- var N93 = Math.pow(2, 63);
16159
- var length3 = function(value) {
16160
- return value < N13 ? 1 : value < N23 ? 2 : value < N33 ? 3 : value < N43 ? 4 : value < N53 ? 5 : value < N63 ? 6 : value < N73 ? 7 : value < N83 ? 8 : value < N93 ? 9 : 10;
16161
- };
16162
- var varint3 = {
16163
- encode: encode_13,
16164
- decode: decode22,
16165
- encodingLength: length3
16166
- };
16167
- var _brrp_varint3 = varint3;
16168
- var varint_default3 = _brrp_varint3;
16169
- function decode32(data, offset = 0) {
16170
- const code22 = varint_default3.decode(data, offset);
16171
- return [code22, varint_default3.decode.bytes];
16172
- }
16173
- function encodeTo3(int, target, offset = 0) {
16174
- varint_default3.encode(int, target, offset);
16175
- return target;
16176
- }
16177
- function encodingLength3(int) {
16178
- return varint_default3.encodingLength(int);
16100
+ return bytes;
16179
16101
  }
16180
- function create3(code22, digest) {
16181
- const size = digest.byteLength;
16182
- const sizeOffset = encodingLength3(code22);
16183
- const digestOffset = sizeOffset + encodingLength3(size);
16184
- const bytes = new Uint8Array(digestOffset + size);
16185
- encodeTo3(code22, bytes, 0);
16186
- encodeTo3(size, bytes, sizeOffset);
16187
- bytes.set(digest, digestOffset);
16188
- return new Digest3(code22, size, digest, bytes);
16102
+ function utf8Bytes2(text) {
16103
+ return new TextEncoder().encode(text);
16189
16104
  }
16190
- function decode42(multihash) {
16191
- const bytes = coerce5(multihash);
16192
- const [code22, sizeOffset] = decode32(bytes);
16193
- const [size, digestOffset] = decode32(bytes.subarray(sizeOffset));
16194
- const digest = bytes.subarray(sizeOffset + digestOffset);
16195
- if (digest.byteLength !== size) {
16196
- throw new Error("Incorrect length");
16105
+ var ED25519_MULTICODEC_PREFIX2 = Uint8Array.of(237, 1);
16106
+ function decodeBase64UrlOrNull2(value) {
16107
+ try {
16108
+ return fromBase64Url2(value);
16109
+ } catch {
16110
+ return null;
16197
16111
  }
16198
- return new Digest3(code22, size, digest, bytes);
16199
16112
  }
16200
- function equals22(a, b) {
16201
- if (a === b) {
16202
- return true;
16203
- } else {
16204
- const data = b;
16205
- return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals5(a.bytes, data.bytes);
16113
+ var base64UrlString2 = () => external_exports2.string().refine((value) => decodeBase64UrlOrNull2(value) !== null, {
16114
+ message: "expected strictly-decodable unpadded base64url"
16115
+ });
16116
+ function isCanonicalHttpsOrigin2(value) {
16117
+ let url;
16118
+ try {
16119
+ url = new URL(value);
16120
+ } catch {
16121
+ return false;
16206
16122
  }
16123
+ return url.protocol === "https:" && url.origin === value;
16207
16124
  }
16208
- var Digest3 = class {
16209
- code;
16210
- size;
16211
- digest;
16212
- bytes;
16213
- /**
16214
- * Creates a multihash digest.
16215
- */
16216
- constructor(code22, size, digest, bytes) {
16217
- this.code = code22;
16218
- this.size = size;
16219
- this.digest = digest;
16220
- this.bytes = bytes;
16221
- }
16125
+ var sessionJwkCommonFields2 = {
16126
+ alg: external_exports2.string().min(1).optional(),
16127
+ use: external_exports2.string().min(1).optional(),
16128
+ key_ops: external_exports2.array(external_exports2.string().min(1)).optional(),
16129
+ kid: external_exports2.string().min(1).optional(),
16130
+ ext: external_exports2.boolean().optional()
16222
16131
  };
16223
- function format3(link2, base22) {
16224
- const { bytes, version: version2 } = link2;
16225
- switch (version2) {
16226
- case 0:
16227
- return toStringV03(bytes, baseCache3(link2), base22 ?? base58btc3.encoder);
16228
- default:
16229
- return toStringV13(bytes, baseCache3(link2), base22 ?? base323.encoder);
16230
- }
16132
+ var okpPrivateJwkSchema2 = external_exports2.object({
16133
+ kty: external_exports2.literal("OKP"),
16134
+ crv: external_exports2.string().min(1),
16135
+ x: base64UrlString2(),
16136
+ d: base64UrlString2(),
16137
+ ...sessionJwkCommonFields2
16138
+ }).strict();
16139
+ var ecPrivateJwkSchema2 = external_exports2.object({
16140
+ kty: external_exports2.literal("EC"),
16141
+ crv: external_exports2.string().min(1),
16142
+ x: base64UrlString2(),
16143
+ y: base64UrlString2(),
16144
+ d: base64UrlString2(),
16145
+ ...sessionJwkCommonFields2
16146
+ }).strict();
16147
+ var sessionJwkSchema2 = external_exports2.discriminatedUnion("kty", [
16148
+ okpPrivateJwkSchema2,
16149
+ ecPrivateJwkSchema2
16150
+ ]);
16151
+ var policyTargetSchema2 = external_exports2.object({
16152
+ kind: external_exports2.literal("policy"),
16153
+ policyCid: external_exports2.string().min(1),
16154
+ /** Canonical policy bytes, base64url-encoded (bytes are not JSON). */
16155
+ policyBytes: base64UrlString2()
16156
+ }).strict();
16157
+ var bearerKeyTargetSchema2 = external_exports2.object({
16158
+ kind: external_exports2.literal("bearerKey"),
16159
+ sessionJwk: sessionJwkSchema2
16160
+ }).strict();
16161
+ var recipientDidTargetSchema2 = external_exports2.object({
16162
+ kind: external_exports2.literal("recipientDid"),
16163
+ did: external_exports2.string().regex(/^did:[a-z0-9]+:.+$/, "expected a DID")
16164
+ }).strict();
16165
+ var authorizationTargetSchema2 = external_exports2.discriminatedUnion("kind", [
16166
+ policyTargetSchema2,
16167
+ bearerKeyTargetSchema2,
16168
+ recipientDidTargetSchema2
16169
+ ]);
16170
+ function isCanonicalResourcePath2(value) {
16171
+ if (value.length === 0) return false;
16172
+ if (/[\u0000-\u001f\u007f\\]/.test(value)) return false;
16173
+ if (/%2f|%5c|%2e/i.test(value)) return false;
16174
+ return value.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
16231
16175
  }
16232
- var cache3 = /* @__PURE__ */ new WeakMap();
16233
- function baseCache3(cid) {
16234
- const baseCache22 = cache3.get(cid);
16235
- if (baseCache22 == null) {
16236
- const baseCache32 = /* @__PURE__ */ new Map();
16237
- cache3.set(cid, baseCache32);
16238
- return baseCache32;
16239
- }
16240
- return baseCache22;
16176
+ function isCanonicalPathSegment2(value) {
16177
+ return isCanonicalResourcePath2(value) && !value.includes("/");
16241
16178
  }
16242
- var CID3 = class _CID3 {
16243
- code;
16244
- version;
16245
- multihash;
16246
- bytes;
16247
- "/";
16248
- /**
16249
- * @param version - Version of the CID
16250
- * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
16251
- * @param multihash - (Multi)hash of the of the content.
16252
- */
16253
- constructor(version2, code22, multihash, bytes) {
16254
- this.code = code22;
16255
- this.version = version2;
16256
- this.multihash = multihash;
16257
- this.bytes = bytes;
16258
- this["/"] = bytes;
16259
- }
16260
- /**
16261
- * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
16262
- * please either use `CID.asCID(cid)` or switch to new signalling mechanism
16263
- *
16264
- * @deprecated
16265
- */
16266
- get asCID() {
16267
- return this;
16268
- }
16269
- // ArrayBufferView
16270
- get byteOffset() {
16271
- return this.bytes.byteOffset;
16272
- }
16273
- // ArrayBufferView
16274
- get byteLength() {
16275
- return this.bytes.byteLength;
16276
- }
16277
- toV0() {
16278
- switch (this.version) {
16279
- case 0: {
16280
- return this;
16281
- }
16282
- case 1: {
16283
- const { code: code22, multihash } = this;
16284
- if (code22 !== DAG_PB_CODE3) {
16285
- throw new Error("Cannot convert a non dag-pb CID to CIDv0");
16286
- }
16287
- if (multihash.code !== SHA_256_CODE3) {
16288
- throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
16289
- }
16290
- return _CID3.createV0(multihash);
16291
- }
16292
- default: {
16293
- throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
16294
- }
16295
- }
16296
- }
16297
- toV1() {
16298
- switch (this.version) {
16299
- case 0: {
16300
- const { code: code22, digest } = this.multihash;
16301
- const multihash = create3(code22, digest);
16302
- return _CID3.createV1(this.code, multihash);
16303
- }
16304
- case 1: {
16305
- return this;
16306
- }
16307
- default: {
16308
- throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
16309
- }
16310
- }
16311
- }
16312
- equals(other) {
16313
- return _CID3.equals(this, other);
16314
- }
16315
- static equals(self, other) {
16316
- const unknown = other;
16317
- return unknown != null && self.code === unknown.code && self.version === unknown.version && equals22(self.multihash, unknown.multihash);
16318
- }
16319
- toString(base22) {
16320
- return format3(this, base22);
16321
- }
16322
- toJSON() {
16323
- return { "/": format3(this) };
16324
- }
16325
- link() {
16326
- return this;
16327
- }
16328
- [Symbol.toStringTag] = "CID";
16329
- // Legacy
16330
- [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
16331
- return `CID(${this.toString()})`;
16332
- }
16333
- /**
16334
- * Takes any input `value` and returns a `CID` instance if it was
16335
- * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
16336
- * it will return value back. If `value` is not instance of this CID
16337
- * class, but is compatible CID it will return new instance of this
16338
- * `CID` class. Otherwise returns null.
16339
- *
16340
- * This allows two different incompatible versions of CID library to
16341
- * co-exist and interop as long as binary interface is compatible.
16342
- */
16343
- static asCID(input) {
16344
- if (input == null) {
16345
- return null;
16346
- }
16347
- const value = input;
16348
- if (value instanceof _CID3) {
16349
- return value;
16350
- } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
16351
- const { version: version2, code: code22, multihash, bytes } = value;
16352
- return new _CID3(version2, code22, multihash, bytes ?? encodeCID3(version2, code22, multihash.bytes));
16353
- } else if (value[cidSymbol3] === true) {
16354
- const { version: version2, multihash, code: code22 } = value;
16355
- const digest = decode42(multihash);
16356
- return _CID3.create(version2, code22, digest);
16357
- } else {
16358
- return null;
16359
- }
16360
- }
16361
- /**
16362
- * @param version - Version of the CID
16363
- * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
16364
- * @param digest - (Multi)hash of the of the content.
16365
- */
16366
- static create(version2, code22, digest) {
16367
- if (typeof code22 !== "number") {
16368
- throw new Error("String codecs are no longer supported");
16369
- }
16370
- if (!(digest.bytes instanceof Uint8Array)) {
16371
- throw new Error("Invalid digest");
16372
- }
16373
- switch (version2) {
16374
- case 0: {
16375
- if (code22 !== DAG_PB_CODE3) {
16376
- throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE3}) block encoding`);
16377
- } else {
16378
- return new _CID3(version2, code22, digest, digest.bytes);
16379
- }
16380
- }
16381
- case 1: {
16382
- const bytes = encodeCID3(version2, code22, digest.bytes);
16383
- return new _CID3(version2, code22, digest, bytes);
16384
- }
16385
- default: {
16386
- throw new Error("Invalid version");
16387
- }
16388
- }
16389
- }
16390
- /**
16391
- * Simplified version of `create` for CIDv0.
16392
- */
16393
- static createV0(digest) {
16394
- return _CID3.create(0, DAG_PB_CODE3, digest);
16179
+ var resourceSelectorSchema2 = external_exports2.object({
16180
+ kind: external_exports2.union([external_exports2.literal("exact"), external_exports2.literal("prefix")]),
16181
+ path: external_exports2.string().min(1)
16182
+ }).strict().superRefine((selector, ctx) => {
16183
+ const body = selector.kind === "prefix" && selector.path.endsWith("/") ? selector.path.slice(0, -1) : selector.path;
16184
+ if (!isCanonicalResourcePath2(body)) {
16185
+ ctx.addIssue({
16186
+ code: external_exports2.ZodIssueCode.custom,
16187
+ path: ["path"],
16188
+ message: "expected a canonical resource path (non-empty segments, no . or .. segments, no //, no backslash, no %2f/%5c/%2e, no control chars)"
16189
+ });
16395
16190
  }
16191
+ });
16192
+ var targetSchema2 = external_exports2.object({
16193
+ origin: external_exports2.string().refine(isCanonicalHttpsOrigin2, {
16194
+ message: "expected a canonical https origin (https://host[:port], nothing else)"
16195
+ }),
16196
+ nodeAudience: external_exports2.string().min(1),
16197
+ spaceId: external_exports2.string().refine(isCanonicalPathSegment2, {
16198
+ message: "expected a single canonical path segment (spaceId joins the resource URI; separators/traversal would alias grants)"
16199
+ }),
16200
+ resource: resourceSelectorSchema2
16201
+ }).strict();
16202
+ var displaySchema2 = external_exports2.object({
16203
+ senderName: external_exports2.string().optional(),
16204
+ filename: external_exports2.string().optional(),
16205
+ recipientHint: external_exports2.string().optional(),
16396
16206
  /**
16397
- * Simplified version of `create` for CIDv1.
16398
- *
16399
- * @param code - Content encoding format code.
16400
- * @param digest - Multihash of the content.
16401
- */
16402
- static createV1(code22, digest) {
16403
- return _CID3.create(1, code22, digest);
16404
- }
16405
- /**
16406
- * Decoded a CID from its binary representation. The byte array must contain
16407
- * only the CID with no additional bytes.
16408
- *
16409
- * An error will be thrown if the bytes provided do not contain a valid
16410
- * binary representation of a CID.
16411
- */
16412
- static decode(bytes) {
16413
- const [cid, remainder] = _CID3.decodeFirst(bytes);
16414
- if (remainder.length !== 0) {
16415
- throw new Error("Incorrect length");
16416
- }
16417
- return cid;
16418
- }
16419
- /**
16420
- * Decoded a CID from its binary representation at the beginning of a byte
16421
- * array.
16422
- *
16423
- * Returns an array with the first element containing the CID and the second
16424
- * element containing the remainder of the original byte array. The remainder
16425
- * will be a zero-length byte array if the provided bytes only contained a
16426
- * binary CID representation.
16427
- */
16428
- static decodeFirst(bytes) {
16429
- const specs = _CID3.inspectBytes(bytes);
16430
- const prefixSize = specs.size - specs.multihashSize;
16431
- const multihashBytes = coerce5(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
16432
- if (multihashBytes.byteLength !== specs.multihashSize) {
16433
- throw new Error("Incorrect length");
16434
- }
16435
- const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
16436
- const digest = new Digest3(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
16437
- const cid = specs.version === 0 ? _CID3.createV0(digest) : _CID3.createV1(specs.codec, digest);
16438
- return [cid, bytes.subarray(specs.size)];
16439
- }
16440
- /**
16441
- * Inspect the initial bytes of a CID to determine its properties.
16442
- *
16443
- * Involves decoding up to 4 varints. Typically this will require only 4 to 6
16444
- * bytes but for larger multicodec code values and larger multihash digest
16445
- * lengths these varints can be quite large. It is recommended that at least
16446
- * 10 bytes be made available in the `initialBytes` argument for a complete
16447
- * inspection.
16448
- */
16449
- static inspectBytes(initialBytes) {
16450
- let offset = 0;
16451
- const next = () => {
16452
- const [i, length22] = decode32(initialBytes.subarray(offset));
16453
- offset += length22;
16454
- return i;
16455
- };
16456
- let version2 = next();
16457
- let codec = DAG_PB_CODE3;
16458
- if (version2 === 18) {
16459
- version2 = 0;
16460
- offset = 0;
16461
- } else {
16462
- codec = next();
16463
- }
16464
- if (version2 !== 0 && version2 !== 1) {
16465
- throw new RangeError(`Invalid CID version ${version2}`);
16466
- }
16467
- const prefixSize = offset;
16468
- const multihashCode = next();
16469
- const digestSize = next();
16470
- const size = offset + digestSize;
16471
- const multihashSize = size - prefixSize;
16472
- return { version: version2, codec, multihashCode, digestSize, multihashSize, size };
16473
- }
16474
- /**
16475
- * Takes cid in a string representation and creates an instance. If `base`
16476
- * decoder is not provided will use a default from the configuration. It will
16477
- * throw an error if encoding of the CID is not compatible with supplied (or
16478
- * a default decoder).
16479
- */
16480
- static parse(source, base22) {
16481
- const [prefix, bytes] = parseCIDtoBytes3(source, base22);
16482
- const cid = _CID3.decode(bytes);
16483
- if (cid.version === 0 && source[0] !== "Q") {
16484
- throw Error("Version 0 CID string must not include multibase prefix");
16485
- }
16486
- baseCache3(cid).set(prefix, source);
16487
- return cid;
16488
- }
16489
- };
16490
- function parseCIDtoBytes3(source, base22) {
16491
- switch (source[0]) {
16492
- // CIDv0 is parsed differently
16493
- case "Q": {
16494
- const decoder = base22 ?? base58btc3;
16495
- return [
16496
- base58btc3.prefix,
16497
- decoder.decode(`${base58btc3.prefix}${source}`)
16498
- ];
16499
- }
16500
- case base58btc3.prefix: {
16501
- const decoder = base22 ?? base58btc3;
16502
- return [base58btc3.prefix, decoder.decode(source)];
16503
- }
16504
- case base323.prefix: {
16505
- const decoder = base22 ?? base323;
16506
- return [base323.prefix, decoder.decode(source)];
16507
- }
16508
- case base363.prefix: {
16509
- const decoder = base22 ?? base363;
16510
- return [base363.prefix, decoder.decode(source)];
16511
- }
16512
- default: {
16513
- if (base22 == null) {
16514
- throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");
16515
- }
16516
- return [source[0], base22.decode(source)];
16517
- }
16518
- }
16519
- }
16520
- function toStringV03(bytes, cache22, base22) {
16521
- const { prefix } = base22;
16522
- if (prefix !== base58btc3.prefix) {
16523
- throw Error(`Cannot string encode V0 in ${base22.name} encoding`);
16524
- }
16525
- const cid = cache22.get(prefix);
16526
- if (cid == null) {
16527
- const cid2 = base22.encode(bytes).slice(1);
16528
- cache22.set(prefix, cid2);
16529
- return cid2;
16530
- } else {
16531
- return cid;
16532
- }
16533
- }
16534
- function toStringV13(bytes, cache22, base22) {
16535
- const { prefix } = base22;
16536
- const cid = cache22.get(prefix);
16537
- if (cid == null) {
16538
- const cid2 = base22.encode(bytes);
16539
- cache22.set(prefix, cid2);
16540
- return cid2;
16541
- } else {
16542
- return cid;
16543
- }
16544
- }
16545
- var DAG_PB_CODE3 = 112;
16546
- var SHA_256_CODE3 = 18;
16547
- function encodeCID3(version2, code22, multihash) {
16548
- const codeOffset = encodingLength3(version2);
16549
- const hashOffset = codeOffset + encodingLength3(code22);
16550
- const bytes = new Uint8Array(hashOffset + multihash.byteLength);
16551
- encodeTo3(version2, bytes, 0);
16552
- encodeTo3(code22, bytes, codeOffset);
16553
- bytes.set(multihash, hashOffset);
16554
- return bytes;
16555
- }
16556
- var cidSymbol3 = /* @__PURE__ */ Symbol.for("@ipld/js-cid/CID");
16557
- var code2 = 85;
16558
- var SHA256_CODE2 = 18;
16559
- function isCanonicalRawCid2(cidString) {
16560
- let cid;
16561
- try {
16562
- cid = CID3.parse(cidString);
16563
- } catch {
16564
- return false;
16565
- }
16566
- return cid.version === 1 && cid.code === code2 && cid.multihash.code === SHA256_CODE2 && cid.toString() === cidString;
16567
- }
16568
- var base642 = rfc46483({
16569
- prefix: "m",
16570
- name: "base64",
16571
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
16572
- bitsPerChar: 6
16573
- });
16574
- var base64pad2 = rfc46483({
16575
- prefix: "M",
16576
- name: "base64pad",
16577
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
16578
- bitsPerChar: 6
16579
- });
16580
- var base64url2 = rfc46483({
16581
- prefix: "u",
16582
- name: "base64url",
16583
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
16584
- bitsPerChar: 6
16585
- });
16586
- var base64urlpad2 = rfc46483({
16587
- prefix: "U",
16588
- name: "base64urlpad",
16589
- alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
16590
- bitsPerChar: 6
16591
- });
16592
- function fromBase64Url2(text) {
16593
- const bytes = base64url2.baseDecode(text);
16594
- if (base64url2.baseEncode(bytes) !== text) {
16595
- throw new TypeError("non-canonical base64url input");
16596
- }
16597
- return bytes;
16598
- }
16599
- function utf8Bytes2(text) {
16600
- return new TextEncoder().encode(text);
16601
- }
16602
- var ED25519_MULTICODEC_PREFIX2 = Uint8Array.of(237, 1);
16603
- function decodeBase64UrlOrNull2(value) {
16604
- try {
16605
- return fromBase64Url2(value);
16606
- } catch {
16607
- return null;
16608
- }
16609
- }
16610
- var base64UrlString2 = () => external_exports2.string().refine((value) => decodeBase64UrlOrNull2(value) !== null, {
16611
- message: "expected strictly-decodable unpadded base64url"
16612
- });
16613
- function isCanonicalHttpsOrigin2(value) {
16614
- let url;
16615
- try {
16616
- url = new URL(value);
16617
- } catch {
16618
- return false;
16619
- }
16620
- return url.protocol === "https:" && url.origin === value;
16621
- }
16622
- var sessionJwkCommonFields2 = {
16623
- alg: external_exports2.string().min(1).optional(),
16624
- use: external_exports2.string().min(1).optional(),
16625
- key_ops: external_exports2.array(external_exports2.string().min(1)).optional(),
16626
- kid: external_exports2.string().min(1).optional(),
16627
- ext: external_exports2.boolean().optional()
16628
- };
16629
- var okpPrivateJwkSchema2 = external_exports2.object({
16630
- kty: external_exports2.literal("OKP"),
16631
- crv: external_exports2.string().min(1),
16632
- x: base64UrlString2(),
16633
- d: base64UrlString2(),
16634
- ...sessionJwkCommonFields2
16635
- }).strict();
16636
- var ecPrivateJwkSchema2 = external_exports2.object({
16637
- kty: external_exports2.literal("EC"),
16638
- crv: external_exports2.string().min(1),
16639
- x: base64UrlString2(),
16640
- y: base64UrlString2(),
16641
- d: base64UrlString2(),
16642
- ...sessionJwkCommonFields2
16643
- }).strict();
16644
- var sessionJwkSchema2 = external_exports2.discriminatedUnion("kty", [
16645
- okpPrivateJwkSchema2,
16646
- ecPrivateJwkSchema2
16647
- ]);
16648
- var policyTargetSchema2 = external_exports2.object({
16649
- kind: external_exports2.literal("policy"),
16650
- policyCid: external_exports2.string().min(1),
16651
- /** Canonical policy bytes, base64url-encoded (bytes are not JSON). */
16652
- policyBytes: base64UrlString2()
16653
- }).strict();
16654
- var bearerKeyTargetSchema2 = external_exports2.object({
16655
- kind: external_exports2.literal("bearerKey"),
16656
- sessionJwk: sessionJwkSchema2
16657
- }).strict();
16658
- var recipientDidTargetSchema2 = external_exports2.object({
16659
- kind: external_exports2.literal("recipientDid"),
16660
- did: external_exports2.string().regex(/^did:[a-z0-9]+:.+$/, "expected a DID")
16661
- }).strict();
16662
- var authorizationTargetSchema2 = external_exports2.discriminatedUnion("kind", [
16663
- policyTargetSchema2,
16664
- bearerKeyTargetSchema2,
16665
- recipientDidTargetSchema2
16666
- ]);
16667
- function isCanonicalResourcePath2(value) {
16668
- if (value.length === 0) return false;
16669
- if (/[\u0000-\u001f\u007f\\]/.test(value)) return false;
16670
- if (/%2f|%5c|%2e/i.test(value)) return false;
16671
- return value.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
16672
- }
16673
- function isCanonicalPathSegment2(value) {
16674
- return isCanonicalResourcePath2(value) && !value.includes("/");
16675
- }
16676
- var resourceSelectorSchema2 = external_exports2.object({
16677
- kind: external_exports2.union([external_exports2.literal("exact"), external_exports2.literal("prefix")]),
16678
- path: external_exports2.string().min(1)
16679
- }).strict().superRefine((selector, ctx) => {
16680
- const body = selector.kind === "prefix" && selector.path.endsWith("/") ? selector.path.slice(0, -1) : selector.path;
16681
- if (!isCanonicalResourcePath2(body)) {
16682
- ctx.addIssue({
16683
- code: external_exports2.ZodIssueCode.custom,
16684
- path: ["path"],
16685
- message: "expected a canonical resource path (non-empty segments, no . or .. segments, no //, no backslash, no %2f/%5c/%2e, no control chars)"
16686
- });
16687
- }
16688
- });
16689
- var targetSchema2 = external_exports2.object({
16690
- origin: external_exports2.string().refine(isCanonicalHttpsOrigin2, {
16691
- message: "expected a canonical https origin (https://host[:port], nothing else)"
16692
- }),
16693
- nodeAudience: external_exports2.string().min(1),
16694
- spaceId: external_exports2.string().refine(isCanonicalPathSegment2, {
16695
- message: "expected a single canonical path segment (spaceId joins the resource URI; separators/traversal would alias grants)"
16696
- }),
16697
- resource: resourceSelectorSchema2
16698
- }).strict();
16699
- var displaySchema2 = external_exports2.object({
16700
- senderName: external_exports2.string().optional(),
16701
- filename: external_exports2.string().optional(),
16702
- recipientHint: external_exports2.string().optional(),
16703
- /**
16704
- * Presentation preference only (viewer spec §1): may narrow, never widen;
16705
- * capabilities always win.
16207
+ * Presentation preference only (viewer spec §1): may narrow, never widen;
16208
+ * capabilities always win.
16706
16209
  */
16707
16210
  mode: external_exports2.union([external_exports2.literal("document"), external_exports2.literal("source"), external_exports2.literal("folder")]).optional()
16708
16211
  }).strict();
@@ -16736,324 +16239,954 @@ var unsignedShareEnvelopeSchema2 = external_exports2.object({
16736
16239
  /** Bearer-slice sealed-content pointer (see contentPointerSchema). */
16737
16240
  content: contentPointerSchema2.optional()
16738
16241
  }).strict();
16739
- var shareEnvelopeSchema2 = unsignedShareEnvelopeSchema2.extend({ signature: signatureSchema2 }).strict();
16740
- var recipientMatcherSchema2 = external_exports2.discriminatedUnion("kind", [
16741
- external_exports2.object({ kind: external_exports2.literal("exactEmail"), value: external_exports2.string().min(3).regex(/^[^@\s]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/) }).strict(),
16742
- external_exports2.object({ kind: external_exports2.literal("emailDomain"), value: external_exports2.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/) }).strict(),
16743
- external_exports2.object({ kind: external_exports2.literal("recipientDid"), value: external_exports2.string().regex(/^did:[a-z0-9]+:.+$/) }).strict(),
16744
- external_exports2.object({ kind: external_exports2.literal("policyDigest"), value: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/) }).strict(),
16745
- external_exports2.object({ kind: external_exports2.literal("bearer") }).strict()
16242
+ var shareEnvelopeSchema2 = unsignedShareEnvelopeSchema2.extend({ signature: signatureSchema2 }).strict();
16243
+ var recipientMatcherSchema2 = external_exports2.discriminatedUnion("kind", [
16244
+ external_exports2.object({ kind: external_exports2.literal("exactEmail"), value: external_exports2.string().min(3).regex(/^[^@\s]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/) }).strict(),
16245
+ external_exports2.object({ kind: external_exports2.literal("emailDomain"), value: external_exports2.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/) }).strict(),
16246
+ external_exports2.object({ kind: external_exports2.literal("recipientDid"), value: external_exports2.string().regex(/^did:[a-z0-9]+:.+$/) }).strict(),
16247
+ external_exports2.object({ kind: external_exports2.literal("policyDigest"), value: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/) }).strict(),
16248
+ external_exports2.object({ kind: external_exports2.literal("bearer") }).strict()
16249
+ ]);
16250
+ var shareActionSchema2 = external_exports2.union([external_exports2.literal("read"), external_exports2.literal("list"), external_exports2.literal("edit")]);
16251
+ var kvContentSourceSchema2 = external_exports2.object({
16252
+ kind: external_exports2.literal("kv"),
16253
+ space: external_exports2.string().min(1),
16254
+ path: external_exports2.string().min(1),
16255
+ action: external_exports2.literal("tinycloud.kv/get")
16256
+ }).strict();
16257
+ var sqlContentSourceSchema2 = external_exports2.object({
16258
+ kind: external_exports2.literal("sql"),
16259
+ space: external_exports2.string().min(1),
16260
+ database: external_exports2.string().min(1),
16261
+ path: external_exports2.string().min(1),
16262
+ statement: external_exports2.string().min(1),
16263
+ arguments: external_exports2.record(external_exports2.string(), external_exports2.number().int()),
16264
+ argumentsDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16265
+ action: external_exports2.literal("tinycloud.sql/read")
16266
+ }).strict();
16267
+ var contentSourceSchema2 = external_exports2.discriminatedUnion("kind", [kvContentSourceSchema2, sqlContentSourceSchema2]);
16268
+ var v2TargetSchema2 = external_exports2.object({
16269
+ origin: external_exports2.string().refine(isCanonicalHttpsOrigin2, { message: "expected a canonical https origin" }),
16270
+ nodeAudience: external_exports2.string().min(1),
16271
+ spaceId: external_exports2.string().refine(isCanonicalPathSegment2, { message: "expected a canonical space id" })
16272
+ }).strict();
16273
+ var shareDecryptionSchema2 = external_exports2.object({
16274
+ networkId: external_exports2.string().min(1),
16275
+ action: external_exports2.literal("tinycloud.encryption/decrypt")
16276
+ }).strict();
16277
+ var ownerAuthoritySchema2 = external_exports2.object({
16278
+ registrationCid: external_exports2.string().min(1),
16279
+ shareCid: external_exports2.string().min(1),
16280
+ envelopeCid: external_exports2.string().min(1),
16281
+ enforcementDelegation: external_exports2.record(external_exports2.string(), external_exports2.unknown()),
16282
+ outerEnvelope: external_exports2.record(external_exports2.string(), external_exports2.unknown()),
16283
+ /** Node-signed registration evidence; required by trusted policy adapters. */
16284
+ registrationReceipt: external_exports2.object({
16285
+ registration: external_exports2.record(external_exports2.string(), external_exports2.unknown()),
16286
+ proof: external_exports2.record(external_exports2.string(), external_exports2.unknown())
16287
+ }).strict().optional()
16288
+ }).strict();
16289
+ var contentMetadataSchema2 = external_exports2.object({
16290
+ mediaType: external_exports2.string().min(1).max(128).optional(),
16291
+ byteLength: external_exports2.number().int().nonnegative().max(100 * 1024 * 1024).optional(),
16292
+ filename: external_exports2.string().min(1).max(255).optional(),
16293
+ encoding: external_exports2.literal("utf-8").optional(),
16294
+ /** Encrypted presentation discriminator. The fixed entry point is index.html. */
16295
+ artifact: external_exports2.literal("html").optional()
16296
+ }).strict();
16297
+ var deliveryEmailSchema2 = external_exports2.string().email();
16298
+ function isEnvelopeDeliveryEmail2(value) {
16299
+ return deliveryEmailSchema2.safeParse(value).success;
16300
+ }
16301
+ var unsignedShareEnvelopeV2BaseSchema2 = external_exports2.object({
16302
+ version: external_exports2.literal(2),
16303
+ shareId: external_exports2.string().min(1),
16304
+ recipientMatcher: recipientMatcherSchema2,
16305
+ deliveryEmail: deliveryEmailSchema2.optional(),
16306
+ actions: external_exports2.array(shareActionSchema2).min(1).max(3),
16307
+ resource: resourceSelectorSchema2,
16308
+ target: v2TargetSchema2,
16309
+ delegationCid: external_exports2.string().min(1),
16310
+ authorityMaterialHandle: external_exports2.string().min(1),
16311
+ authorityMaterialDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16312
+ decryption: shareDecryptionSchema2.optional(),
16313
+ contentSource: contentSourceSchema2,
16314
+ contentSourceDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16315
+ authorizationTarget: authorizationTargetSchema2,
16316
+ display: displaySchema2,
16317
+ expiry: external_exports2.string().datetime(),
16318
+ encrypted: external_exports2.boolean(),
16319
+ content: contentPointerSchema2.optional(),
16320
+ metadata: contentMetadataSchema2,
16321
+ ownerAuthority: ownerAuthoritySchema2.optional()
16322
+ }).strict();
16323
+ function validateV2Invariants2(value, ctx) {
16324
+ const actions = [...value.actions];
16325
+ if (new Set(actions).size !== actions.length) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["actions"], message: "actions must be unique" });
16326
+ if (actions.some((action, index) => action !== ["read", "list", "edit"].filter((candidate) => actions.includes(candidate))[index])) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["actions"], message: "actions must be canonically ordered" });
16327
+ if (!value.encrypted && value.recipientMatcher.kind !== "policyDigest") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["recipientMatcher"], message: "safe plaintext must carry only a matcher digest" });
16328
+ if (!value.encrypted && value.authorizationTarget.kind !== "policy") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["encrypted"], message: "unencrypted content requires a policy target" });
16329
+ if (!value.encrypted && value.content !== void 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["content"], message: "policy-only plaintext cannot carry content" });
16330
+ if (value.encrypted && (value.metadata.mediaType === void 0 || value.metadata.filename === void 0 || value.metadata.byteLength === void 0)) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata"], message: "encrypted shares must describe their content" });
16331
+ if (!value.encrypted && Object.keys(value.metadata).length !== 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata"], message: "policy-only plaintext cannot describe content" });
16332
+ if (!value.encrypted && value.metadata.encoding !== void 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata", "encoding"], message: "policy-only plaintext cannot carry content encoding" });
16333
+ if (value.metadata.artifact === "html" && (!value.encrypted || value.resource.kind !== "prefix" || !value.actions.includes("read") || !value.actions.includes("list"))) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata", "artifact"], message: "html artifacts require an encrypted readable prefix" });
16334
+ if (!value.encrypted && (value.display.senderName !== void 0 || value.display.filename !== void 0 || value.display.recipientHint !== void 0)) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["display"], message: "policy-only plaintext cannot carry display metadata" });
16335
+ if (!value.encrypted && value.deliveryEmail !== void 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["deliveryEmail"], message: "policy-only plaintext cannot carry delivery metadata" });
16336
+ if (value.recipientMatcher.kind === "exactEmail" && value.deliveryEmail !== void 0 && value.deliveryEmail !== value.recipientMatcher.value) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["deliveryEmail"], message: "delivery email must match the exact matcher" });
16337
+ if (value.recipientMatcher.kind === "emailDomain" && value.deliveryEmail !== void 0 && value.deliveryEmail.toLowerCase().endsWith(`@${value.recipientMatcher.value}`) === false) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["deliveryEmail"], message: "delivery email must belong to the matcher domain" });
16338
+ if (value.contentSource.kind === "kv" && value.contentSource.action !== "tinycloud.kv/get") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["contentSource"], message: "source action mismatch" });
16339
+ if (value.contentSource.kind === "sql" && value.contentSource.action !== "tinycloud.sql/read") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["contentSource"], message: "source action mismatch" });
16340
+ }
16341
+ var unsignedShareEnvelopeV2Schema2 = unsignedShareEnvelopeV2BaseSchema2.superRefine(validateV2Invariants2);
16342
+ var shareEnvelopeV2Schema2 = unsignedShareEnvelopeV2BaseSchema2.extend({ signature: signatureSchema2 }).strict().superRefine(validateV2Invariants2);
16343
+ var unifiedResourceSchema2 = external_exports2.string().refine((value) => {
16344
+ const marker = value.indexOf("/kv/");
16345
+ if (marker < 1) return false;
16346
+ const space = value.slice(0, marker);
16347
+ const legacy = space.startsWith("tinycloud://");
16348
+ if (legacy ? /[:/?#%]/.test(space.slice("tinycloud://".length)) : !space.startsWith("tinycloud:") || /[/?#%]/.test(space)) return false;
16349
+ const path = value.slice(marker + 4);
16350
+ return !path.startsWith("/") && !path.endsWith("/") && !path.includes("//") && path.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
16351
+ }, { message: "expected canonical TinyCloud KV resource" });
16352
+ var unifiedEncryptionNetworkSchema2 = external_exports2.string().refine((value) => {
16353
+ if (!value.startsWith("urn:tinycloud:encryption:")) return false;
16354
+ const rest = value.slice("urn:tinycloud:encryption:".length);
16355
+ const separator = rest.lastIndexOf(":");
16356
+ const owner = separator < 0 ? "" : rest.slice(0, separator);
16357
+ const network = separator < 0 ? "" : rest.slice(separator + 1);
16358
+ return owner.startsWith("did:") && owner.length > 4 && network.length > 0 && !/[:/%?#\s]/.test(network);
16359
+ }, { message: "expected canonical TinyCloud encryption network" });
16360
+ var unifiedKvCapabilitySchema2 = external_exports2.object({
16361
+ kind: external_exports2.literal("kv"),
16362
+ resource: unifiedResourceSchema2,
16363
+ selector: external_exports2.union([external_exports2.literal("exact"), external_exports2.literal("prefix")]),
16364
+ actions: external_exports2.array(external_exports2.union([
16365
+ external_exports2.literal("tinycloud.kv/get"),
16366
+ external_exports2.literal("tinycloud.kv/list"),
16367
+ external_exports2.literal("tinycloud.kv/metadata"),
16368
+ external_exports2.literal("tinycloud.kv/put")
16369
+ ])).min(1)
16370
+ }).strict();
16371
+ var unifiedEncryptionCapabilitySchema2 = external_exports2.object({
16372
+ kind: external_exports2.literal("encryption"),
16373
+ resource: unifiedEncryptionNetworkSchema2,
16374
+ action: external_exports2.literal("tinycloud.encryption/decrypt")
16375
+ }).strict();
16376
+ var unifiedCapabilitySchema2 = external_exports2.union([unifiedKvCapabilitySchema2, unifiedEncryptionCapabilitySchema2]);
16377
+ var unifiedContentSourceSchema2 = external_exports2.object({
16378
+ shareId: external_exports2.string().min(1),
16379
+ kvResource: unifiedResourceSchema2,
16380
+ selector: external_exports2.union([external_exports2.literal("exact"), external_exports2.literal("prefix")]),
16381
+ encryptionNetwork: unifiedEncryptionNetworkSchema2,
16382
+ encryptedSymmetricKeyDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/),
16383
+ keyVersion: external_exports2.number().int().positive(),
16384
+ mode: external_exports2.union([external_exports2.literal("mutable"), external_exports2.literal("immutable")]),
16385
+ initialCiphertextDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/).optional()
16386
+ }).strict();
16387
+ var unifiedPolicyV1Schema2 = external_exports2.object({
16388
+ schema: external_exports2.literal("xyz.tinycloud.policy/policy/v1"),
16389
+ policyId: external_exports2.string().regex(/^pol_[a-z2-7]+$/),
16390
+ ownerDid: external_exports2.string().min(1),
16391
+ createdAt: external_exports2.string().datetime({ offset: true }),
16392
+ expiresAt: external_exports2.string().datetime({ offset: true }).optional(),
16393
+ contentSource: unifiedContentSourceSchema2,
16394
+ capabilityCeiling: external_exports2.array(unifiedCapabilitySchema2).min(2),
16395
+ signature: external_exports2.object({ suite: external_exports2.string().min(1), signerDid: external_exports2.string().min(1), value: external_exports2.string().min(1) }).strict()
16396
+ }).strict();
16397
+ var policyCredentialRequirementV1Schema2 = external_exports2.object({
16398
+ type: external_exports2.literal("TinyCloudPolicyCredentialRequirement"),
16399
+ version: external_exports2.literal(1),
16400
+ requirementDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16401
+ descriptorDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16402
+ issuerDid: external_exports2.string().min(1),
16403
+ issuerKid: external_exports2.string().min(1),
16404
+ profile: external_exports2.object({ id: external_exports2.string().min(1), version: external_exports2.literal(1) }).strict(),
16405
+ credentialType: external_exports2.object({ id: external_exports2.string().min(1), version: external_exports2.literal(1) }).strict()
16406
+ }).strict();
16407
+ var unifiedPolicyV2Schema2 = external_exports2.object({
16408
+ schema: external_exports2.literal("xyz.tinycloud.policy/policy/v2"),
16409
+ policyId: external_exports2.string().regex(/^pol_[a-z2-7]+$/),
16410
+ ownerDid: external_exports2.string().min(1),
16411
+ createdAt: external_exports2.string().datetime({ offset: true }),
16412
+ expiresAt: external_exports2.string().datetime({ offset: true }).optional(),
16413
+ contentSource: unifiedContentSourceSchema2,
16414
+ capabilityCeiling: external_exports2.array(unifiedCapabilitySchema2).min(2),
16415
+ credentialRequirement: policyCredentialRequirementV1Schema2,
16416
+ signature: external_exports2.object({ suite: external_exports2.literal("Ed25519"), signerDid: external_exports2.string().min(1), value: external_exports2.string().min(1) }).strict()
16417
+ }).strict();
16418
+ var unifiedPolicySchema2 = external_exports2.discriminatedUnion("schema", [
16419
+ unifiedPolicyV1Schema2,
16420
+ unifiedPolicyV2Schema2
16746
16421
  ]);
16747
- var shareActionSchema2 = external_exports2.union([external_exports2.literal("read"), external_exports2.literal("list"), external_exports2.literal("edit")]);
16748
- var kvContentSourceSchema2 = external_exports2.object({
16749
- kind: external_exports2.literal("kv"),
16750
- space: external_exports2.string().min(1),
16751
- path: external_exports2.string().min(1),
16752
- action: external_exports2.literal("tinycloud.kv/get")
16422
+ var unifiedRootSchema2 = external_exports2.object({
16423
+ cid: external_exports2.string().min(1),
16424
+ authorization: external_exports2.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/),
16425
+ role: external_exports2.union([external_exports2.literal("policy-authority"), external_exports2.literal("policy-enforcement")])
16753
16426
  }).strict();
16754
- var sqlContentSourceSchema2 = external_exports2.object({
16755
- kind: external_exports2.literal("sql"),
16756
- space: external_exports2.string().min(1),
16757
- database: external_exports2.string().min(1),
16758
- path: external_exports2.string().min(1),
16759
- statement: external_exports2.string().min(1),
16760
- arguments: external_exports2.record(external_exports2.string(), external_exports2.number().int()),
16761
- argumentsDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16762
- action: external_exports2.literal("tinycloud.sql/read")
16427
+ var attestedEnforcerBindingV2Schema2 = external_exports2.object({
16428
+ schema: external_exports2.literal("xyz.tinycloud.policy/attested-enforcer/v2"),
16429
+ enforcerDid: external_exports2.string().regex(/^did:key:z[1-9A-HJ-NP-Za-km-z]+$/),
16430
+ nodeAudience: external_exports2.string().min(1),
16431
+ attestationBindingDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/),
16432
+ issuedAt: external_exports2.string().datetime({ offset: true }),
16433
+ expiresAt: external_exports2.string().datetime({ offset: true }),
16434
+ signature: external_exports2.object({ suite: external_exports2.literal("Ed25519"), signerDid: external_exports2.string().min(1), value: base64UrlString2() }).strict()
16763
16435
  }).strict();
16764
- var contentSourceSchema2 = external_exports2.discriminatedUnion("kind", [kvContentSourceSchema2, sqlContentSourceSchema2]);
16765
- var v2TargetSchema2 = external_exports2.object({
16436
+ var v3TargetSchema2 = external_exports2.object({
16766
16437
  origin: external_exports2.string().refine(isCanonicalHttpsOrigin2, { message: "expected a canonical https origin" }),
16767
16438
  nodeAudience: external_exports2.string().min(1),
16768
16439
  spaceId: external_exports2.string().refine(isCanonicalPathSegment2, { message: "expected a canonical space id" })
16769
16440
  }).strict();
16770
- var shareDecryptionSchema2 = external_exports2.object({
16771
- networkId: external_exports2.string().min(1),
16772
- action: external_exports2.literal("tinycloud.encryption/decrypt")
16773
- }).strict();
16774
- var ownerAuthoritySchema2 = external_exports2.object({
16775
- registrationCid: external_exports2.string().min(1),
16776
- shareCid: external_exports2.string().min(1),
16777
- envelopeCid: external_exports2.string().min(1),
16778
- enforcementDelegation: external_exports2.record(external_exports2.string(), external_exports2.unknown()),
16779
- outerEnvelope: external_exports2.record(external_exports2.string(), external_exports2.unknown()),
16780
- /** Node-signed registration evidence; required by trusted policy adapters. */
16781
- registrationReceipt: external_exports2.object({
16782
- registration: external_exports2.record(external_exports2.string(), external_exports2.unknown()),
16783
- proof: external_exports2.record(external_exports2.string(), external_exports2.unknown())
16784
- }).strict().optional()
16785
- }).strict();
16786
- var contentMetadataSchema2 = external_exports2.object({
16787
- mediaType: external_exports2.string().min(1).max(128).optional(),
16788
- byteLength: external_exports2.number().int().nonnegative().max(100 * 1024 * 1024).optional(),
16789
- filename: external_exports2.string().min(1).max(255).optional(),
16790
- encoding: external_exports2.literal("utf-8").optional(),
16791
- /** Encrypted presentation discriminator. The fixed entry point is index.html. */
16792
- artifact: external_exports2.literal("html").optional()
16441
+ var unsignedShareEnvelopeV3BaseSchema2 = external_exports2.object({
16442
+ version: external_exports2.literal(3),
16443
+ shareId: external_exports2.string().min(1),
16444
+ recipientMatcher: recipientMatcherSchema2,
16445
+ deliveryEmail: deliveryEmailSchema2.optional(),
16446
+ actions: external_exports2.array(shareActionSchema2).min(1).max(3),
16447
+ resource: resourceSelectorSchema2,
16448
+ target: v3TargetSchema2,
16449
+ policy: unifiedPolicySchema2,
16450
+ policyCid: external_exports2.string().min(1),
16451
+ policyRoot: unifiedRootSchema2,
16452
+ enforcementRoot: unifiedRootSchema2,
16453
+ attestedEnforcerBinding: attestedEnforcerBindingV2Schema2,
16454
+ contentSource: unifiedContentSourceSchema2,
16455
+ contentSourceDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/),
16456
+ encryptionNetwork: unifiedEncryptionNetworkSchema2,
16457
+ expiry: external_exports2.string().datetime({ offset: true }),
16458
+ display: displaySchema2,
16459
+ encrypted: external_exports2.literal(true),
16460
+ metadata: contentMetadataSchema2
16793
16461
  }).strict();
16794
- var deliveryEmailSchema2 = external_exports2.string().email();
16795
- function isEnvelopeDeliveryEmail2(value) {
16796
- return deliveryEmailSchema2.safeParse(value).success;
16462
+ function validateV3Invariants2(value, ctx) {
16463
+ const actions = [...value.actions];
16464
+ if (new Set(actions).size !== actions.length || actions.some((action, index) => action !== ["read", "list", "edit"].filter((candidate) => actions.includes(candidate))[index])) {
16465
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["actions"], message: "actions must be unique and canonically ordered" });
16466
+ }
16467
+ if (value.policyRoot.role !== "policy-authority" || value.enforcementRoot.role !== "policy-enforcement") {
16468
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policyRoot", "role"], message: "root roles are fixed" });
16469
+ }
16470
+ if (value.policyCid.length === 0 || value.policyCid === value.policyRoot.cid || value.policyCid === value.enforcementRoot.cid) {
16471
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policyCid"], message: "policy CID must be distinct from both roots" });
16472
+ }
16473
+ if (value.contentSource.encryptionNetwork !== value.encryptionNetwork) {
16474
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["encryptionNetwork"], message: "encryption network is not bound to the source" });
16475
+ }
16476
+ if (value.attestedEnforcerBinding.nodeAudience !== value.target.nodeAudience || value.attestedEnforcerBinding.signature.signerDid !== value.attestedEnforcerBinding.nodeAudience || Date.parse(value.attestedEnforcerBinding.expiresAt) < Date.parse(value.expiry)) {
16477
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["attestedEnforcerBinding"], message: "enforcer binding does not cover the target and share lifetime" });
16478
+ }
16479
+ if (value.policy.contentSource.shareId !== value.contentSource.shareId || value.policy.contentSource.kvResource !== value.contentSource.kvResource || value.policy.contentSource.selector !== value.contentSource.selector || value.policy.contentSource.encryptionNetwork !== value.encryptionNetwork || value.policy.contentSource.encryptedSymmetricKeyDigestHex !== value.contentSource.encryptedSymmetricKeyDigestHex || value.policy.contentSource.keyVersion !== value.contentSource.keyVersion || value.policy.contentSource.mode !== value.contentSource.mode || value.policy.contentSource.initialCiphertextDigestHex !== value.contentSource.initialCiphertextDigestHex) {
16480
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["contentSource"], message: "content source is not bound to policy" });
16481
+ }
16482
+ if (value.policy.signature.suite !== "Ed25519" || value.policy.signature.signerDid !== value.policy.ownerDid) {
16483
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policy", "signature"], message: "policy must be signed by its owner" });
16484
+ }
16485
+ const kvCapabilities = value.policy.capabilityCeiling.filter((capability) => capability.kind === "kv");
16486
+ const decryptCapabilities = value.policy.capabilityCeiling.filter((capability) => capability.kind === "encryption" && capability.resource === value.encryptionNetwork && capability.action === "tinycloud.encryption/decrypt");
16487
+ if (value.policy.capabilityCeiling.length !== 2 || kvCapabilities.length !== 1 || decryptCapabilities.length !== 1 || kvCapabilities[0]?.resource !== value.contentSource.kvResource || kvCapabilities[0]?.selector !== value.contentSource.selector) {
16488
+ ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policy", "capabilityCeiling"], message: "policy ceiling must contain exact decrypt network" });
16489
+ }
16490
+ }
16491
+ var unsignedShareEnvelopeV3Schema2 = unsignedShareEnvelopeV3BaseSchema2.superRefine(validateV3Invariants2);
16492
+ var shareEnvelopeV3Schema2 = unsignedShareEnvelopeV3BaseSchema2.extend({ signature: signatureSchema2 }).strict().superRefine(validateV3Invariants2);
16493
+ var ENVELOPE_AAD_LABEL2 = "tinycloud-share-envelope-v1";
16494
+ var AAD2 = utf8Bytes2(ENVELOPE_AAD_LABEL2);
16495
+ function isPlainRecord2(value) {
16496
+ const proto = Object.getPrototypeOf(value);
16497
+ return proto === Object.prototype || proto === null;
16498
+ }
16499
+ function assertNoLoneSurrogates2(text) {
16500
+ for (let i = 0; i < text.length; i++) {
16501
+ const unit = text.charCodeAt(i);
16502
+ if (unit >= 56320 && unit <= 57343) {
16503
+ throw new TypeError(
16504
+ `cannot canonicalize string with unpaired low surrogate at index ${i}`
16505
+ );
16506
+ }
16507
+ if (unit >= 55296 && unit <= 56319) {
16508
+ const next = text.charCodeAt(i + 1);
16509
+ if (!(next >= 56320 && next <= 57343)) {
16510
+ throw new TypeError(
16511
+ `cannot canonicalize string with unpaired high surrogate at index ${i}`
16512
+ );
16513
+ }
16514
+ i++;
16515
+ }
16516
+ }
16517
+ }
16518
+ function serializeString2(text) {
16519
+ assertNoLoneSurrogates2(text);
16520
+ return JSON.stringify(text);
16521
+ }
16522
+ function serialize2(value) {
16523
+ if (value === null) return "null";
16524
+ switch (typeof value) {
16525
+ case "boolean":
16526
+ return JSON.stringify(value);
16527
+ case "string":
16528
+ return serializeString2(value);
16529
+ case "number":
16530
+ if (!Number.isFinite(value)) {
16531
+ throw new TypeError(`cannot canonicalize non-finite number: ${value}`);
16532
+ }
16533
+ return JSON.stringify(value);
16534
+ case "object":
16535
+ break;
16536
+ default:
16537
+ throw new TypeError(`cannot canonicalize value of type ${typeof value}`);
16538
+ }
16539
+ if (Array.isArray(value)) {
16540
+ return `[${value.map((item) => serialize2(item)).join(",")}]`;
16541
+ }
16542
+ if (!isPlainRecord2(value)) {
16543
+ throw new TypeError("cannot canonicalize non-plain object");
16544
+ }
16545
+ const keys = Object.keys(value).sort();
16546
+ const members = [];
16547
+ for (const key of keys) {
16548
+ const member = value[key];
16549
+ if (member === void 0) continue;
16550
+ members.push(`${serializeString2(key)}:${serialize2(member)}`);
16551
+ }
16552
+ return `{${members.join(",")}}`;
16553
+ }
16554
+ function canonicalize2(value) {
16555
+ return serialize2(value);
16556
+ }
16557
+ var LABEL2 = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
16558
+ function isCanonicalEmailDomain2(value) {
16559
+ if (value.length === 0 || value.length > 253) return false;
16560
+ const labels = value.split(".");
16561
+ return labels.length >= 2 && labels.every((label) => LABEL2.test(label)) && !/^[0-9]+$/.test(labels.at(-1));
16562
+ }
16563
+ function canonicalMailbox2(value) {
16564
+ const email = value.trim().toLowerCase();
16565
+ const at = email.indexOf("@");
16566
+ if (at <= 0 || at !== email.lastIndexOf("@")) return void 0;
16567
+ const local = email.slice(0, at);
16568
+ const domain = email.slice(at + 1);
16569
+ if (local.length > 64 || !/^[a-z0-9#$&'*+/=?^_`{|}~-]+(?:\.[a-z0-9#$&'*+/=?^_`{|}~-]+)*$/.test(local) || !isCanonicalEmailDomain2(domain)) return void 0;
16570
+ return Object.freeze({ email, domain });
16571
+ }
16572
+ var MAX_INLINE_BYTES2 = 256 * 1024;
16573
+
16574
+ // src/commands/share.ts
16575
+ import { ProfileLockTimeoutError as ProfileLockTimeoutError2 } from "@tinycloud/operations/state";
16576
+
16577
+ // src/lib/duration.ts
16578
+ function parseDuration(input) {
16579
+ const match = input.match(/^(\d+)(m|h|d|w)$/);
16580
+ if (match) {
16581
+ const value = parseInt(match[1], 10);
16582
+ const unit = match[2];
16583
+ const multipliers = {
16584
+ m: 60 * 1e3,
16585
+ h: 60 * 60 * 1e3,
16586
+ d: 24 * 60 * 60 * 1e3,
16587
+ w: 7 * 24 * 60 * 60 * 1e3
16588
+ };
16589
+ return value * multipliers[unit];
16590
+ }
16591
+ const date = new Date(input);
16592
+ if (!isNaN(date.getTime())) {
16593
+ const ms = date.getTime() - Date.now();
16594
+ if (ms <= 0) {
16595
+ throw new Error(`Expiry date "${input}" is in the past`);
16596
+ }
16597
+ return ms;
16598
+ }
16599
+ throw new Error(`Invalid duration: "${input}". Use format like "1h", "7d", or an ISO date.`);
16600
+ }
16601
+
16602
+ // src/commands/share.ts
16603
+ init_formatter();
16604
+ init_errors();
16605
+
16606
+ // src/share/output.ts
16607
+ function writeJson2(value) {
16608
+ process.stdout.write(`${JSON.stringify(value, null, 2)}
16609
+ `);
16610
+ }
16611
+ function authorizationRequiredJson(result) {
16612
+ return {
16613
+ state: "authorization-required",
16614
+ method: result.method,
16615
+ next: "complete authorization through the configured authority adapter, then retry with the required proof"
16616
+ };
16617
+ }
16618
+ function publishHuman(result) {
16619
+ process.stdout.write(`${result.url}
16620
+ `);
16621
+ }
16622
+ function inspectHuman(result) {
16623
+ const metadata = result.metadata;
16624
+ process.stdout.write([
16625
+ `Share ${metadata.shareId}`,
16626
+ `File: ${metadata.display.filename ?? "unnamed"}`,
16627
+ `Target: ${metadata.target.kind === "bearer" ? "bearer (anyone with the complete link can read)" : metadata.target.kind}`,
16628
+ `Expires: ${metadata.expiresAt}`,
16629
+ `Resource: ${metadata.resource.path}`,
16630
+ `Link format: ${result.link.kind}`
16631
+ ].join("\n") + "\n");
16632
+ }
16633
+ function receiveHuman(path) {
16634
+ process.stdout.write(`${path}
16635
+ `);
16797
16636
  }
16798
- var unsignedShareEnvelopeV2BaseSchema2 = external_exports2.object({
16799
- version: external_exports2.literal(2),
16800
- shareId: external_exports2.string().min(1),
16801
- recipientMatcher: recipientMatcherSchema2,
16802
- deliveryEmail: deliveryEmailSchema2.optional(),
16803
- actions: external_exports2.array(shareActionSchema2).min(1).max(3),
16804
- resource: resourceSelectorSchema2,
16805
- target: v2TargetSchema2,
16806
- delegationCid: external_exports2.string().min(1),
16807
- authorityMaterialHandle: external_exports2.string().min(1),
16808
- authorityMaterialDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16809
- decryption: shareDecryptionSchema2.optional(),
16810
- contentSource: contentSourceSchema2,
16811
- contentSourceDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16812
- authorizationTarget: authorizationTargetSchema2,
16813
- display: displaySchema2,
16814
- expiry: external_exports2.string().datetime(),
16815
- encrypted: external_exports2.boolean(),
16816
- content: contentPointerSchema2.optional(),
16817
- metadata: contentMetadataSchema2,
16818
- ownerAuthority: ownerAuthoritySchema2.optional()
16819
- }).strict();
16820
- function validateV2Invariants2(value, ctx) {
16821
- const actions = [...value.actions];
16822
- if (new Set(actions).size !== actions.length) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["actions"], message: "actions must be unique" });
16823
- if (actions.some((action, index) => action !== ["read", "list", "edit"].filter((candidate) => actions.includes(candidate))[index])) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["actions"], message: "actions must be canonically ordered" });
16824
- if (!value.encrypted && value.recipientMatcher.kind !== "policyDigest") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["recipientMatcher"], message: "safe plaintext must carry only a matcher digest" });
16825
- if (!value.encrypted && value.authorizationTarget.kind !== "policy") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["encrypted"], message: "unencrypted content requires a policy target" });
16826
- if (!value.encrypted && value.content !== void 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["content"], message: "policy-only plaintext cannot carry content" });
16827
- if (value.encrypted && (value.metadata.mediaType === void 0 || value.metadata.filename === void 0 || value.metadata.byteLength === void 0)) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata"], message: "encrypted shares must describe their content" });
16828
- if (!value.encrypted && Object.keys(value.metadata).length !== 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata"], message: "policy-only plaintext cannot describe content" });
16829
- if (!value.encrypted && value.metadata.encoding !== void 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata", "encoding"], message: "policy-only plaintext cannot carry content encoding" });
16830
- if (value.metadata.artifact === "html" && (!value.encrypted || value.resource.kind !== "prefix" || !value.actions.includes("read") || !value.actions.includes("list"))) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["metadata", "artifact"], message: "html artifacts require an encrypted readable prefix" });
16831
- if (!value.encrypted && (value.display.senderName !== void 0 || value.display.filename !== void 0 || value.display.recipientHint !== void 0)) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["display"], message: "policy-only plaintext cannot carry display metadata" });
16832
- if (!value.encrypted && value.deliveryEmail !== void 0) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["deliveryEmail"], message: "policy-only plaintext cannot carry delivery metadata" });
16833
- if (value.recipientMatcher.kind === "exactEmail" && value.deliveryEmail !== void 0 && value.deliveryEmail !== value.recipientMatcher.value) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["deliveryEmail"], message: "delivery email must match the exact matcher" });
16834
- if (value.recipientMatcher.kind === "emailDomain" && value.deliveryEmail !== void 0 && value.deliveryEmail.toLowerCase().endsWith(`@${value.recipientMatcher.value}`) === false) ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["deliveryEmail"], message: "delivery email must belong to the matcher domain" });
16835
- if (value.contentSource.kind === "kv" && value.contentSource.action !== "tinycloud.kv/get") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["contentSource"], message: "source action mismatch" });
16836
- if (value.contentSource.kind === "sql" && value.contentSource.action !== "tinycloud.sql/read") ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["contentSource"], message: "source action mismatch" });
16637
+ function receiveJson(result, path) {
16638
+ writeJson2({ protocol: "tinycloud-share", version: 1, path, metadata: result.metadata });
16837
16639
  }
16838
- var unsignedShareEnvelopeV2Schema2 = unsignedShareEnvelopeV2BaseSchema2.superRefine(validateV2Invariants2);
16839
- var shareEnvelopeV2Schema2 = unsignedShareEnvelopeV2BaseSchema2.extend({ signature: signatureSchema2 }).strict().superRefine(validateV2Invariants2);
16840
- var unifiedResourceSchema2 = external_exports2.string().refine((value) => {
16841
- const marker = value.indexOf("/kv/");
16842
- if (marker < 1) return false;
16843
- const space = value.slice(0, marker);
16844
- const legacy = space.startsWith("tinycloud://");
16845
- if (legacy ? /[:/?#%]/.test(space.slice("tinycloud://".length)) : !space.startsWith("tinycloud:") || /[/?#%]/.test(space)) return false;
16846
- const path = value.slice(marker + 4);
16847
- return !path.startsWith("/") && !path.endsWith("/") && !path.includes("//") && path.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
16848
- }, { message: "expected canonical TinyCloud KV resource" });
16849
- var unifiedEncryptionNetworkSchema2 = external_exports2.string().refine((value) => {
16850
- if (!value.startsWith("urn:tinycloud:encryption:")) return false;
16851
- const rest = value.slice("urn:tinycloud:encryption:".length);
16852
- const separator = rest.lastIndexOf(":");
16853
- const owner = separator < 0 ? "" : rest.slice(0, separator);
16854
- const network = separator < 0 ? "" : rest.slice(separator + 1);
16855
- return owner.startsWith("did:") && owner.length > 4 && network.length > 0 && !/[:/%?#\s]/.test(network);
16856
- }, { message: "expected canonical TinyCloud encryption network" });
16857
- var unifiedKvCapabilitySchema2 = external_exports2.object({
16858
- kind: external_exports2.literal("kv"),
16859
- resource: unifiedResourceSchema2,
16860
- selector: external_exports2.union([external_exports2.literal("exact"), external_exports2.literal("prefix")]),
16861
- actions: external_exports2.array(external_exports2.union([
16862
- external_exports2.literal("tinycloud.kv/get"),
16863
- external_exports2.literal("tinycloud.kv/list"),
16864
- external_exports2.literal("tinycloud.kv/metadata"),
16865
- external_exports2.literal("tinycloud.kv/put")
16866
- ])).min(1)
16867
- }).strict();
16868
- var unifiedEncryptionCapabilitySchema2 = external_exports2.object({
16869
- kind: external_exports2.literal("encryption"),
16870
- resource: unifiedEncryptionNetworkSchema2,
16871
- action: external_exports2.literal("tinycloud.encryption/decrypt")
16872
- }).strict();
16873
- var unifiedCapabilitySchema2 = external_exports2.union([unifiedKvCapabilitySchema2, unifiedEncryptionCapabilitySchema2]);
16874
- var unifiedContentSourceSchema2 = external_exports2.object({
16875
- shareId: external_exports2.string().min(1),
16876
- kvResource: unifiedResourceSchema2,
16877
- selector: external_exports2.union([external_exports2.literal("exact"), external_exports2.literal("prefix")]),
16878
- encryptionNetwork: unifiedEncryptionNetworkSchema2,
16879
- encryptedSymmetricKeyDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/),
16880
- keyVersion: external_exports2.number().int().positive(),
16881
- mode: external_exports2.union([external_exports2.literal("mutable"), external_exports2.literal("immutable")]),
16882
- initialCiphertextDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/).optional()
16883
- }).strict();
16884
- var unifiedPolicyV1Schema2 = external_exports2.object({
16885
- schema: external_exports2.literal("xyz.tinycloud.policy/policy/v1"),
16886
- policyId: external_exports2.string().regex(/^pol_[a-z2-7]+$/),
16887
- ownerDid: external_exports2.string().min(1),
16888
- createdAt: external_exports2.string().datetime({ offset: true }),
16889
- expiresAt: external_exports2.string().datetime({ offset: true }).optional(),
16890
- contentSource: unifiedContentSourceSchema2,
16891
- capabilityCeiling: external_exports2.array(unifiedCapabilitySchema2).min(2),
16892
- signature: external_exports2.object({ suite: external_exports2.string().min(1), signerDid: external_exports2.string().min(1), value: external_exports2.string().min(1) }).strict()
16893
- }).strict();
16894
- var policyCredentialRequirementV1Schema2 = external_exports2.object({
16895
- type: external_exports2.literal("TinyCloudPolicyCredentialRequirement"),
16896
- version: external_exports2.literal(1),
16897
- requirementDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16898
- descriptorDigest: external_exports2.string().regex(/^[A-Za-z0-9_-]{43}$/),
16899
- issuerDid: external_exports2.string().min(1),
16900
- issuerKid: external_exports2.string().min(1),
16901
- profile: external_exports2.object({ id: external_exports2.string().min(1), version: external_exports2.literal(1) }).strict(),
16902
- credentialType: external_exports2.object({ id: external_exports2.string().min(1), version: external_exports2.literal(1) }).strict()
16903
- }).strict();
16904
- var unifiedPolicyV2Schema2 = external_exports2.object({
16905
- schema: external_exports2.literal("xyz.tinycloud.policy/policy/v2"),
16906
- policyId: external_exports2.string().regex(/^pol_[a-z2-7]+$/),
16907
- ownerDid: external_exports2.string().min(1),
16908
- createdAt: external_exports2.string().datetime({ offset: true }),
16909
- expiresAt: external_exports2.string().datetime({ offset: true }).optional(),
16910
- contentSource: unifiedContentSourceSchema2,
16911
- capabilityCeiling: external_exports2.array(unifiedCapabilitySchema2).min(2),
16912
- credentialRequirement: policyCredentialRequirementV1Schema2,
16913
- signature: external_exports2.object({ suite: external_exports2.literal("Ed25519"), signerDid: external_exports2.string().min(1), value: external_exports2.string().min(1) }).strict()
16914
- }).strict();
16915
- var unifiedPolicySchema2 = external_exports2.discriminatedUnion("schema", [
16916
- unifiedPolicyV1Schema2,
16917
- unifiedPolicyV2Schema2
16918
- ]);
16919
- var unifiedRootSchema2 = external_exports2.object({
16920
- cid: external_exports2.string().min(1),
16921
- authorization: external_exports2.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/),
16922
- role: external_exports2.union([external_exports2.literal("policy-authority"), external_exports2.literal("policy-enforcement")])
16923
- }).strict();
16924
- var attestedEnforcerBindingV2Schema2 = external_exports2.object({
16925
- schema: external_exports2.literal("xyz.tinycloud.policy/attested-enforcer/v2"),
16926
- enforcerDid: external_exports2.string().regex(/^did:key:z[1-9A-HJ-NP-Za-km-z]+$/),
16927
- nodeAudience: external_exports2.string().min(1),
16928
- attestationBindingDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/),
16929
- issuedAt: external_exports2.string().datetime({ offset: true }),
16930
- expiresAt: external_exports2.string().datetime({ offset: true }),
16931
- signature: external_exports2.object({ suite: external_exports2.literal("Ed25519"), signerDid: external_exports2.string().min(1), value: base64UrlString2() }).strict()
16932
- }).strict();
16933
- var v3TargetSchema2 = external_exports2.object({
16934
- origin: external_exports2.string().refine(isCanonicalHttpsOrigin2, { message: "expected a canonical https origin" }),
16935
- nodeAudience: external_exports2.string().min(1),
16936
- spaceId: external_exports2.string().refine(isCanonicalPathSegment2, { message: "expected a canonical space id" })
16937
- }).strict();
16938
- var unsignedShareEnvelopeV3BaseSchema2 = external_exports2.object({
16939
- version: external_exports2.literal(3),
16940
- shareId: external_exports2.string().min(1),
16941
- recipientMatcher: recipientMatcherSchema2,
16942
- deliveryEmail: deliveryEmailSchema2.optional(),
16943
- actions: external_exports2.array(shareActionSchema2).min(1).max(3),
16944
- resource: resourceSelectorSchema2,
16945
- target: v3TargetSchema2,
16946
- policy: unifiedPolicySchema2,
16947
- policyCid: external_exports2.string().min(1),
16948
- policyRoot: unifiedRootSchema2,
16949
- enforcementRoot: unifiedRootSchema2,
16950
- attestedEnforcerBinding: attestedEnforcerBindingV2Schema2,
16951
- contentSource: unifiedContentSourceSchema2,
16952
- contentSourceDigestHex: external_exports2.string().regex(/^[0-9a-f]{64}$/),
16953
- encryptionNetwork: unifiedEncryptionNetworkSchema2,
16954
- expiry: external_exports2.string().datetime({ offset: true }),
16955
- display: displaySchema2,
16956
- encrypted: external_exports2.literal(true),
16957
- metadata: contentMetadataSchema2
16958
- }).strict();
16959
- function validateV3Invariants2(value, ctx) {
16960
- const actions = [...value.actions];
16961
- if (new Set(actions).size !== actions.length || actions.some((action, index) => action !== ["read", "list", "edit"].filter((candidate) => actions.includes(candidate))[index])) {
16962
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["actions"], message: "actions must be unique and canonically ordered" });
16640
+
16641
+ // src/share/io.ts
16642
+ import { constants } from "fs";
16643
+ import { lstat as lstat2, mkdir as mkdir2, mkdtemp, open as open2, readFile as readFile2, realpath, stat as stat2, link, rename as rename2, rm as rm3, unlink } from "fs/promises";
16644
+ import { randomBytes as randomBytes2 } from "crypto";
16645
+ import { basename as basename2, join as join4, resolve, sep } from "path";
16646
+ init_errors();
16647
+ var MAX_SHARE_STDIN_BYTES = 100 * 1024 * 1024;
16648
+ var MAX_SHARE_URL_BYTES = 64 * 1024;
16649
+ async function readBoundedStdin(limit = MAX_SHARE_STDIN_BYTES) {
16650
+ if (!Number.isSafeInteger(limit) || limit <= 0) throw new Error("MAX_BYTES_EXCEEDED");
16651
+ const chunks = [];
16652
+ let total = 0;
16653
+ for await (const chunk of process.stdin) {
16654
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
16655
+ total += bytes.byteLength;
16656
+ if (total > limit) throw new Error("MAX_BYTES_EXCEEDED");
16657
+ chunks.push(bytes);
16658
+ }
16659
+ return new Uint8Array(Buffer.concat(chunks, total));
16660
+ }
16661
+ async function readBoundedUrlStdin() {
16662
+ const bytes = await readBoundedStdin(MAX_SHARE_URL_BYTES);
16663
+ const value = new TextDecoder("utf-8", { fatal: true }).decode(bytes).trim();
16664
+ if (value.length === 0 || /\s/.test(value)) throw new Error("INVALID_ARGUMENT");
16665
+ return value;
16666
+ }
16667
+ function safeFilename(value) {
16668
+ return shareFilename(value);
16669
+ }
16670
+ function shareFilename(value) {
16671
+ try {
16672
+ return canonicalShareFilename(value);
16673
+ } catch {
16674
+ throw new CLIError(
16675
+ "UNSAFE_FILENAME",
16676
+ hasUnsafeFilenameCodePoint(value) ? "filename contains control or invisible characters" : "filename must be one safe path segment",
16677
+ 8
16678
+ );
16679
+ }
16680
+ }
16681
+ function shareInputFilename(input, name) {
16682
+ return shareFilename(name ?? (input === "-" ? "stdin.md" : basename2(resolve(input))));
16683
+ }
16684
+ async function readShareInput(input, name, limit = MAX_SHARE_STDIN_BYTES) {
16685
+ const filename = shareInputFilename(input, name);
16686
+ if (input === "-") return { bytes: await readBoundedStdin(limit), filename };
16687
+ const path = resolve(input);
16688
+ const info = await stat2(path);
16689
+ if (!info.isFile() || info.size > limit) throw new Error("MAX_BYTES_EXCEEDED");
16690
+ const bytes = new Uint8Array(await readFile2(path));
16691
+ if (bytes.byteLength > limit) throw new Error("MAX_BYTES_EXCEEDED");
16692
+ return { bytes, filename };
16693
+ }
16694
+ async function assertDirectory(path) {
16695
+ const absolute = resolve(path);
16696
+ const segments = absolute.split(sep).filter(Boolean);
16697
+ let current = absolute.startsWith(sep) ? sep : "";
16698
+ for (const segment of segments) {
16699
+ current = current === sep ? join4(current, segment) : join4(current, segment);
16700
+ try {
16701
+ const info = await lstat2(current);
16702
+ if (info.isSymbolicLink()) {
16703
+ const canonical = await realpath(current);
16704
+ if (current !== "/tmp" && current !== "/var") throw new Error("OUTPUT_EXISTS");
16705
+ if (canonical !== `/private${current}`) throw new Error("OUTPUT_EXISTS");
16706
+ } else if (!info.isDirectory()) throw new Error("OUTPUT_EXISTS");
16707
+ } catch (error) {
16708
+ if (error.code !== "ENOENT") throw error;
16709
+ await mkdir2(current, { mode: 448 });
16710
+ const created = await lstat2(current);
16711
+ if (created.isSymbolicLink() || !created.isDirectory()) throw new Error("OUTPUT_EXISTS");
16712
+ }
16713
+ }
16714
+ }
16715
+ async function writeShareOutput(directory, filename, bytes, force) {
16716
+ const outputDirectory = resolve(directory);
16717
+ await assertDirectory(outputDirectory);
16718
+ const safeName = safeFilename(filename);
16719
+ const directoryHandle = await open2(outputDirectory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | (constants.O_NOFOLLOW ?? 0));
16720
+ const stableDirectory = await realpath(outputDirectory);
16721
+ const outputPath = join4(stableDirectory, safeName);
16722
+ const directoryIdentity = await directoryHandle.stat();
16723
+ const assertStableDirectory = async () => {
16724
+ const current = await stat2(stableDirectory);
16725
+ if (current.dev !== directoryIdentity.dev || current.ino !== directoryIdentity.ino) throw new Error("OUTPUT_EXISTS");
16726
+ };
16727
+ await assertStableDirectory();
16728
+ const stagingDirectory = await mkdtemp(join4(stableDirectory, ".tinycloud-share-stage-"));
16729
+ const stagingInfo = await lstat2(stagingDirectory);
16730
+ if (!stagingInfo.isDirectory() || (stagingInfo.mode & 511) !== 448) throw new Error("OUTPUT_EXISTS");
16731
+ const stagingPath = join4(stagingDirectory, `.tinycloud-share-${randomBytes2(16).toString("hex")}.tmp`);
16732
+ let temporaryPath;
16733
+ let handle;
16734
+ try {
16735
+ await assertStableDirectory();
16736
+ try {
16737
+ const existing = await lstat2(outputPath);
16738
+ if (existing.isSymbolicLink()) throw new Error("UNSAFE_FILENAME");
16739
+ } catch (error) {
16740
+ if (error.code !== "ENOENT") throw error;
16741
+ }
16742
+ temporaryPath = stagingPath;
16743
+ handle = await open2(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 384);
16744
+ await handle.writeFile(bytes);
16745
+ await handle.close();
16746
+ handle = void 0;
16747
+ await assertStableDirectory();
16748
+ if (force) {
16749
+ await rename2(temporaryPath, outputPath);
16750
+ } else {
16751
+ await link(temporaryPath, outputPath);
16752
+ await unlink(temporaryPath);
16753
+ }
16754
+ await assertStableDirectory();
16755
+ } catch (error) {
16756
+ if (error.code === "EEXIST") throw new Error("OUTPUT_EXISTS");
16757
+ if (error.code === "ELOOP") throw new Error("UNSAFE_FILENAME");
16758
+ throw error;
16759
+ } finally {
16760
+ await handle?.close();
16761
+ try {
16762
+ if (temporaryPath !== void 0) await unlink(temporaryPath);
16763
+ } catch {
16764
+ }
16765
+ await rm3(stagingDirectory, { recursive: true, force: true });
16766
+ await directoryHandle.close();
16963
16767
  }
16964
- if (value.policyRoot.role !== "policy-authority" || value.enforcementRoot.role !== "policy-enforcement") {
16965
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policyRoot", "role"], message: "root roles are fixed" });
16768
+ return join4(outputDirectory, safeName);
16769
+ }
16770
+
16771
+ // src/share/errors.ts
16772
+ var SharePublishAuthorityError = class extends Error {
16773
+ constructor(failure) {
16774
+ super(failure.kind);
16775
+ this.failure = failure;
16776
+ this.name = "SharePublishAuthorityError";
16966
16777
  }
16967
- if (value.policyCid.length === 0 || value.policyCid === value.policyRoot.cid || value.policyCid === value.enforcementRoot.cid) {
16968
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policyCid"], message: "policy CID must be distinct from both roots" });
16778
+ };
16779
+ var ShareHistoryRetryError = class extends Error {
16780
+ constructor(profile) {
16781
+ super("sender history changed during the operation");
16782
+ this.profile = profile;
16783
+ this.name = "ShareHistoryRetryError";
16969
16784
  }
16970
- if (value.contentSource.encryptionNetwork !== value.encryptionNetwork) {
16971
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["encryptionNetwork"], message: "encryption network is not bound to the source" });
16785
+ code = "SHARE_HISTORY_RETRY";
16786
+ };
16787
+
16788
+ // src/commands/share.ts
16789
+ var SHARE_ORIGIN = "https://share.tinycloud.xyz";
16790
+ var NOTIFY_WINDOW_MESSAGE = "Share notification authorization expired (at share expiry or 5 minutes after publication); publish a new share and invite the recipient then.\n";
16791
+ var shareServices = {};
16792
+ function configureShareCommandServices(services) {
16793
+ shareServices = services;
16794
+ }
16795
+ function parseShareTarget(value) {
16796
+ if (value === "anyone" || value === "bearer") return { kind: "bearer" };
16797
+ if (value.startsWith("did:")) return { kind: "recipientDid", did: value };
16798
+ if (value.startsWith("domain:")) return canonicalMailboxTarget({ kind: "emailDomain", domain: value.slice("domain:".length) });
16799
+ if (value.startsWith("email:")) return canonicalMailboxTarget({ kind: "email", address: value.slice("email:".length) });
16800
+ if (value.includes("@")) return canonicalMailboxTarget({ kind: "email", address: value });
16801
+ throw new CLIError("INVALID_ARGUMENT", "--to must be anyone, a did:, an email address, or domain:example.com", 2);
16802
+ }
16803
+ function canonicalMailboxTarget(target) {
16804
+ try {
16805
+ return normalizeShareTarget(target);
16806
+ } catch (error) {
16807
+ throw new CLIError("INVALID_ARGUMENT", error instanceof TypeError ? error.message : "share recipient is invalid", 2);
16972
16808
  }
16973
- if (value.attestedEnforcerBinding.nodeAudience !== value.target.nodeAudience || value.attestedEnforcerBinding.signature.signerDid !== value.attestedEnforcerBinding.nodeAudience || Date.parse(value.attestedEnforcerBinding.expiresAt) < Date.parse(value.expiry)) {
16974
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["attestedEnforcerBinding"], message: "enforcer binding does not cover the target and share lifetime" });
16809
+ }
16810
+ function shareCliError(error, operation = "publish") {
16811
+ if (error instanceof CLIError) return error;
16812
+ if (error instanceof ProfileLockTimeoutError2) return wrapError(error);
16813
+ if (error instanceof ShareHistoryRetryError) {
16814
+ return new CLIError(
16815
+ "SHARE_HISTORY_RETRY",
16816
+ `sender history for profile ${JSON.stringify(error.profile)} changed or disappeared during this command`,
16817
+ 1,
16818
+ { hint: `Retry this command with --profile ${JSON.stringify(error.profile)}. If this was a revoke, check its node state first: revocation may already have succeeded.` }
16819
+ );
16975
16820
  }
16976
- if (value.policy.contentSource.shareId !== value.contentSource.shareId || value.policy.contentSource.kvResource !== value.contentSource.kvResource || value.policy.contentSource.selector !== value.contentSource.selector || value.policy.contentSource.encryptionNetwork !== value.encryptionNetwork || value.policy.contentSource.encryptedSymmetricKeyDigestHex !== value.contentSource.encryptedSymmetricKeyDigestHex || value.policy.contentSource.keyVersion !== value.contentSource.keyVersion || value.policy.contentSource.mode !== value.contentSource.mode || value.policy.contentSource.initialCiphertextDigestHex !== value.contentSource.initialCiphertextDigestHex) {
16977
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["contentSource"], message: "content source is not bound to policy" });
16821
+ if (error instanceof SharePublishAuthorityError) {
16822
+ const failure = error.failure;
16823
+ const profileName = "profileName" in failure ? failure.profileName : void 0;
16824
+ const localKey = "localKey" in failure && failure.localKey === true;
16825
+ const profileHint = profileName === void 0 ? "" : `--profile ${profileName} `;
16826
+ const loginHint = localKey ? `\`tc ${profileHint}auth login --method local\`` : `\`tc ${profileHint}auth login --device --manifest builtin:share-publishing\` (or \`tc ${profileHint}enable share\`)`;
16827
+ if (failure.kind === "caveated-session") {
16828
+ const holder = profileName === void 0 ? "this session" : `profile ${profileName}'s session`;
16829
+ return new CLIError(
16830
+ "PERMISSION_DENIED",
16831
+ `${holder} carries signed restrictions (caveats) on the authority an anyone-with-link share needs, so it cannot create the share link; nothing was shared. Approve Share publishing without restrictions on a new, dedicated profile (any unused name): \`tc init --name publisher --key-only && tc --profile publisher enable share\``,
16832
+ 5
16833
+ );
16834
+ }
16835
+ if (failure.kind === "owner-space-unresolved") {
16836
+ return new CLIError("AUTH_REQUIRED", `a valid signed TinyCloud session is required; run ${loginHint}`, 3);
16837
+ }
16838
+ if (failure.kind === "scope-denied") {
16839
+ const requiredAction = failure.requiredAction === void 0 ? "" : ` (${failure.requiredAction})`;
16840
+ const renew = localKey ? `renew it with ${loginHint} using the required capability` : `verify the session includes the builtin:share-publishing scope; if it does not, request it with ${loginHint}`;
16841
+ return new CLIError("PERMISSION_DENIED", `the session lacks ${failure.capability} authority${requiredAction}; ${renew}`, 5);
16842
+ }
16843
+ if (failure.kind === "lifetime-exceeds-session") {
16844
+ const expiresAt = failure.sessionExpiresAt.toISOString();
16845
+ if (failure.reason === "session-too-close") {
16846
+ return new CLIError("AUTH_REQUIRED", `the signed session expires too soon (${expiresAt}); log in again with ${loginHint}`, 3);
16847
+ }
16848
+ if (failure.reason === "below-minimum") {
16849
+ return new CLIError("SESSION_LIFETIME_EXCEEDED", "share expiry must be at least 60 seconds from now; use a longer --expires value", 2);
16850
+ }
16851
+ return new CLIError("SESSION_LIFETIME_EXCEEDED", `requested share lifetime exceeds session expiry ${expiresAt}; use a shorter --expires value or renew the session with ${loginHint}`, 2);
16852
+ }
16853
+ if (failure.kind === "origin-mismatch") {
16854
+ return new CLIError("ORIGIN_MISMATCH", "share origin does not match the configured service", 2);
16855
+ }
16856
+ if (failure.kind === "invalid-request") {
16857
+ return new CLIError("INVALID_ARGUMENT", failure.reason, 2);
16858
+ }
16859
+ if (failure.kind === "registry-unavailable") {
16860
+ return new CLIError("UNAVAILABLE", "the TinyCloud location registry could not be reached, so nothing was shared; try again shortly", 4);
16861
+ }
16862
+ if (failure.kind === "node-info-unavailable") {
16863
+ const outcome = operation === "publish" ? "nothing was shared and no invitation was sent" : "no invitation was sent";
16864
+ return new CLIError("UNAVAILABLE", `could not verify TinyCloud node 1.17.3 domain delivery support; ${outcome}. Check the node and retry`, 4);
16865
+ }
16866
+ if (failure.kind === "registry-rejected") {
16867
+ return new CLIError("REGISTRY_REJECTED", "the TinyCloud location registry rejected this session's location record, so nothing was shared; retrying will not help. Log in again, and report the problem if it persists", 6);
16868
+ }
16869
+ if (failure.kind === "storage-quota-exceeded") {
16870
+ const sizes = failure.usedBytes === void 0 || failure.limitBytes === void 0 ? "" : ` (${formatBytes(failure.usedBytes)} used of ${formatBytes(failure.limitBytes)} limit)`;
16871
+ return new CLIError("STORAGE_QUOTA_EXCEEDED", `storage quota exceeded${sizes}; nothing was shared`, 4);
16872
+ }
16873
+ if (failure.kind === "upload-failed") {
16874
+ return new CLIError("UPLOAD_FAILED", "share source upload failed; nothing was shared", 4);
16875
+ }
16978
16876
  }
16979
- if (value.policy.signature.suite !== "Ed25519" || value.policy.signature.signerDid !== value.policy.ownerDid) {
16980
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policy", "signature"], message: "policy must be signed by its owner" });
16877
+ if (error instanceof ShareNotifyError) {
16878
+ return new CLIError("INVALID_ARGUMENT", error.message, 2);
16981
16879
  }
16982
- const kvCapabilities = value.policy.capabilityCeiling.filter((capability) => capability.kind === "kv");
16983
- const decryptCapabilities = value.policy.capabilityCeiling.filter((capability) => capability.kind === "encryption" && capability.resource === value.encryptionNetwork && capability.action === "tinycloud.encryption/decrypt");
16984
- if (value.policy.capabilityCeiling.length !== 2 || kvCapabilities.length !== 1 || decryptCapabilities.length !== 1 || kvCapabilities[0]?.resource !== value.contentSource.kvResource || kvCapabilities[0]?.selector !== value.contentSource.selector) {
16985
- ctx.addIssue({ code: external_exports2.ZodIssueCode.custom, path: ["policy", "capabilityCeiling"], message: "policy ceiling must contain exact decrypt network" });
16880
+ if (error instanceof SharePublishError) {
16881
+ const exit = error.code === "authority-required" ? 3 : error.code === "max-bytes-exceeded" ? 7 : 2;
16882
+ const code3 = error.code === "authority-required" ? "AUTH_REQUIRED" : error.code === "max-bytes-exceeded" ? "MAX_BYTES_EXCEEDED" : "INVALID_ARGUMENT";
16883
+ return new CLIError(code3, error.message, exit);
16884
+ }
16885
+ if (error instanceof ShareReceiveError) {
16886
+ const verification = /* @__PURE__ */ new Set(["cid-mismatch", "decrypt-failed", "envelope-invalid", "origin-mismatch", "signature-invalid", "capability-invalid", "content-integrity-failed"]);
16887
+ const exit = error.code === "max-bytes-exceeded" ? 7 : verification.has(error.code) ? 5 : error.code === "expired" || error.code === "fetch-failed" ? 4 : error.code === "invalid-link" || error.code === "unsupported-target" ? 2 : 2;
16888
+ const code3 = error.code === "fetch-failed" ? "NOT_FOUND" : error.code.replaceAll("-", "_").toUpperCase();
16889
+ return new CLIError(code3, error.message, exit);
16986
16890
  }
16891
+ const message = error instanceof Error ? error.message : String(error);
16892
+ const nodeCode = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
16893
+ const known = {
16894
+ MAX_BYTES_EXCEEDED: { code: "MAX_BYTES_EXCEEDED", exit: 7 },
16895
+ UNSAFE_FILENAME: { code: "UNSAFE_FILENAME", exit: 8 },
16896
+ OUTPUT_EXISTS: { code: "OUTPUT_EXISTS", exit: 8 },
16897
+ INVALID_ARGUMENT: { code: "INVALID_ARGUMENT", exit: 2 },
16898
+ "share not found": { code: "NOT_FOUND", exit: 4 },
16899
+ AUTH_REQUIRED: { code: "AUTH_REQUIRED", exit: 3 },
16900
+ UNAVAILABLE: { code: "UNAVAILABLE", exit: 4 }
16901
+ };
16902
+ if (nodeCode === "ENOENT") return new CLIError("INVALID_ARGUMENT", "share input was not found", 2);
16903
+ if (nodeCode === "EISDIR") return new CLIError("INVALID_ARGUMENT", "share input must be a Markdown file", 2);
16904
+ if (error instanceof TypeError) return new CLIError("INVALID_ARGUMENT", "share input is invalid", 2);
16905
+ const mapped = typeof nodeCode === "string" && known[nodeCode] !== void 0 ? known[nodeCode] : known[message];
16906
+ return new CLIError(mapped?.code ?? "INVALID_ARGUMENT", mapped ? mapped.code : "share operation failed", mapped?.exit ?? 2);
16987
16907
  }
16988
- var unsignedShareEnvelopeV3Schema2 = unsignedShareEnvelopeV3BaseSchema2.superRefine(validateV3Invariants2);
16989
- var shareEnvelopeV3Schema2 = unsignedShareEnvelopeV3BaseSchema2.extend({ signature: signatureSchema2 }).strict().superRefine(validateV3Invariants2);
16990
- var ENVELOPE_AAD_LABEL2 = "tinycloud-share-envelope-v1";
16991
- var AAD2 = utf8Bytes2(ENVELOPE_AAD_LABEL2);
16992
- function isPlainRecord2(value) {
16993
- const proto = Object.getPrototypeOf(value);
16994
- return proto === Object.prototype || proto === null;
16908
+ function inputUrl(value, stdin) {
16909
+ if (stdin || value === "-") return readBoundedUrlStdin();
16910
+ if (value === void 0 || value.length === 0) throw new CLIError("INVALID_ARGUMENT", "a share URL or - is required", 2);
16911
+ return Promise.resolve(value);
16995
16912
  }
16996
- function assertNoLoneSurrogates2(text) {
16997
- for (let i = 0; i < text.length; i++) {
16998
- const unit = text.charCodeAt(i);
16999
- if (unit >= 56320 && unit <= 57343) {
17000
- throw new TypeError(
17001
- `cannot canonicalize string with unpaired low surrogate at index ${i}`
17002
- );
16913
+ async function inspectShareInputOnce(value, stdin, expectedOrigin, dependencies = {}) {
16914
+ const link2 = stdin || value === "-" ? await (dependencies.read ?? readBoundedUrlStdin)() : await inputUrl(value, false);
16915
+ try {
16916
+ parseNativeShareUrl(link2);
16917
+ } catch {
16918
+ return (dependencies.inspect ?? inspectShare)(link2, { expectedOrigin });
16919
+ }
16920
+ throw new CLIError("UNSUPPORTED_LINK", "native bearer links are opaque; receive the link to verify access", 2);
16921
+ }
16922
+ function jsonOutput(options, command) {
16923
+ return options.json === true || command.optsWithGlobals().json === true;
16924
+ }
16925
+ function expires(value) {
16926
+ try {
16927
+ return new Date(Date.now() + parseDuration(value));
16928
+ } catch {
16929
+ throw new CLIError("INVALID_ARGUMENT", "invalid expiry duration", 2);
16930
+ }
16931
+ }
16932
+ async function rememberPublishedShare(result) {
16933
+ const record = historyRecordForPublishedShare(result);
16934
+ if (shareServices.records === void 0) return { record, recorded: false };
16935
+ try {
16936
+ await shareServices.records.put(record);
16937
+ return { record, recorded: true };
16938
+ } catch {
16939
+ process.stderr.write("Warning: share was published but not recorded in sender history; future share list, share notify, and share revoke by ID will not find it.\n");
16940
+ return { record, recorded: false };
16941
+ }
16942
+ }
16943
+ async function notifyRecordedShare(record, recipient, adapter, storage) {
16944
+ const result = await notifyShare({ shareId: record.shareId, recipient, record, adapter, checkDeliveryWindow: true });
16945
+ if (result.state !== "partial-failure" && storage !== void 0) {
16946
+ const mailbox = canonicalMailbox2(recipient).email;
16947
+ if (!record.deliveredRecipients?.includes(mailbox)) {
16948
+ try {
16949
+ if (storage.update === void 0) throw new Error("atomic sender history update is unavailable");
16950
+ const updated = await storage.update(record.shareId, (current) => ({
16951
+ ...current,
16952
+ deliveredRecipients: current.deliveredRecipients?.includes(mailbox) ? current.deliveredRecipients : [...current.deliveredRecipients ?? [], mailbox]
16953
+ }));
16954
+ if (updated === void 0) throw new Error("sender history record was removed");
16955
+ } catch {
16956
+ process.stderr.write("Warning: delivery succeeded, but could not record its confirmation in sender history.\n");
16957
+ }
16958
+ }
16959
+ }
16960
+ return result;
16961
+ }
16962
+ function byteLimit(value) {
16963
+ if (value === void 0) return void 0;
16964
+ const parsed = Number(value);
16965
+ if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed > MAX_SHARE_STDIN_BYTES) throw new CLIError("MAX_BYTES_EXCEEDED", "max-bytes must be between 1 and 100 MiB", 7);
16966
+ return parsed;
16967
+ }
16968
+ function mediaTypeFor(filename) {
16969
+ const extension = filename.toLowerCase().split(".").at(-1);
16970
+ return extension === "md" || extension === "markdown" ? "text/markdown" : extension === "txt" ? "text/plain" : extension === "html" || extension === "htm" ? "text/html" : extension === "json" ? "application/json" : extension === "css" ? "text/css" : extension === "js" ? "text/javascript" : "application/octet-stream";
16971
+ }
16972
+ function requestedActions(values) {
16973
+ const actions = values === void 0 || values.length === 0 ? ["read"] : values;
16974
+ if (actions.some((value) => value !== "read" && value !== "list" && value !== "edit")) throw new CLIError("INVALID_ARGUMENT", "--action must be read, list, or edit", 2);
16975
+ return [...new Set(actions)];
16976
+ }
16977
+ function assertAggregateInputLimit(inputs, maxBytes) {
16978
+ const limit = maxBytes ?? MAX_SHARE_STDIN_BYTES;
16979
+ let total = 0;
16980
+ for (const input of inputs) {
16981
+ total += input.bytes.byteLength;
16982
+ if (!Number.isSafeInteger(total) || total > limit) throw new CLIError("MAX_BYTES_EXCEEDED", "combined share input exceeds the configured byte limit", 7);
16983
+ }
16984
+ }
16985
+ function registerShareCommand(program2) {
16986
+ const share = program2.command("share").description("Publish and consume TinyCloud Share links");
16987
+ share.command("publish <files...>").description("Publish one or more bounded files as a Share").option("--name <filename>", "Filename for stdin input").option("--to <target>", "Share target", "anyone").option("--notify", "Email an exact-email recipient, or a domain mailbox on node 1.17.3+").option("--notify-to <address>", "Mailbox to invite for --to domain:<name> --notify (node 1.17.3+)").option("--expires <duration>", "Share lifetime").option("--max-bytes <bytes>", "Bound input bytes").option("--media-type <type>", "Media type for a single input").option("--action <actions...>", "Addressed permission: read, list, or edit").option("--prefix", "Publish multiple inputs beneath one addressed prefix").option("--binary", "Allow non-UTF-8 bearer content").option("--json", "Print versioned redacted JSON").option("--viewer-origin <origin>", "Canonical HTTPS viewer origin", SHARE_ORIGIN).action(async (files, options, command) => {
16988
+ try {
16989
+ const json = jsonOutput(options, command);
16990
+ const maxBytes = byteLimit(options.maxBytes);
16991
+ if (files.length === 0 || files.includes("-") && files.length > 1) throw new CLIError("INVALID_ARGUMENT", "stdin must be the only publish input", 2);
16992
+ const name = files.length === 1 ? options.name : void 0;
16993
+ for (const file of files) shareInputFilename(file, name);
16994
+ const inputs = await Promise.all(files.map((file) => readShareInput(file, name, maxBytes)));
16995
+ assertAggregateInputLimit(inputs, maxBytes);
16996
+ const target = parseShareTarget(options.to);
16997
+ const actions = requestedActions(options.action);
16998
+ if (options.prefix && target.kind === "bearer") throw new CLIError("INVALID_ARGUMENT", "--prefix requires an addressed target", 2);
16999
+ if (inputs.length > 1 && target.kind === "bearer") throw new CLIError("UNSUPPORTED_LINK", "multiple files require an addressed target", 2);
17000
+ if (inputs.length > 1 && !options.prefix) throw new CLIError("INVALID_ARGUMENT", "multiple files require --prefix", 2);
17001
+ if (options.notify === true && !actions.includes("read")) throw new CLIError("INVALID_ARGUMENT", "--notify requires the read action; nothing was shared", 2);
17002
+ if (options.notifyTo !== void 0 && (options.notify !== true || target.kind !== "emailDomain")) {
17003
+ throw new CLIError("INVALID_ARGUMENT", "--notify-to requires --to domain:<name> --notify", 2);
17004
+ }
17005
+ let notifyRecipient;
17006
+ if (options.notify === true && target.kind === "email") notifyRecipient = target.address;
17007
+ else if (options.notify === true && target.kind === "emailDomain") {
17008
+ const mailbox = options.notifyTo === void 0 ? void 0 : canonicalMailbox2(options.notifyTo);
17009
+ if (mailbox === void 0 || mailbox.domain !== target.domain) {
17010
+ throw new CLIError("INVALID_ARGUMENT", "--to domain:<name> --notify requires --notify-to <email> at that exact domain (node 1.17.3+)", 2);
17011
+ }
17012
+ notifyRecipient = mailbox.email;
17013
+ } else if (options.notify === true) {
17014
+ throw new CLIError("INVALID_ARGUMENT", "--notify requires an email target, or a domain target with --notify-to on node 1.17.3+", 2);
17015
+ }
17016
+ const result = await publishTargetShare({
17017
+ source: inputs[0].bytes,
17018
+ filename: inputs[0].filename,
17019
+ files: inputs.map((input) => ({ bytes: input.bytes, filename: input.filename, mediaType: mediaTypeFor(input.filename) })),
17020
+ mediaType: options.mediaType ?? mediaTypeFor(inputs[0].filename),
17021
+ allowBinary: options.binary === true,
17022
+ target,
17023
+ resourceKind: options.prefix || inputs.length > 1 ? "prefix" : "exact",
17024
+ actions,
17025
+ expiresAt: expires(options.expires ?? "7d"),
17026
+ expiryWasExplicit: options.expires !== void 0,
17027
+ origin: options.viewerOrigin,
17028
+ ...maxBytes === void 0 ? {} : { maxBytes },
17029
+ notify: options.notify === true,
17030
+ targetAdapter: shareServices.targetAdapter
17031
+ });
17032
+ if ("state" in result) {
17033
+ if (json) {
17034
+ writeJson2({ protocol: "tinycloud-share", version: 1, authorization: authorizationRequiredJson(result) });
17035
+ process.exitCode = 6;
17036
+ return;
17037
+ }
17038
+ throw new CLIError(result.method === "openkey-device" ? "DEVICE_AUTH_REQUIRED" : "CLAIM_REQUIRED", "recipient authorization is required; continue through the configured authority adapter", 6);
17039
+ }
17040
+ const { record, recorded } = await rememberPublishedShare(result);
17041
+ let notification;
17042
+ if (notifyRecipient !== void 0) {
17043
+ if (shareServices.delivery === void 0) throw new CLIError("AUTH_REQUIRED", "delivery authority is not configured", 3);
17044
+ notification = await notifyRecordedShare(record, notifyRecipient, shareServices.delivery, recorded ? shareServices.records : void 0);
17045
+ if (notification.state === "partial-failure") process.exitCode = 9;
17046
+ if (notification.reason === "delivery-window-expired") process.stderr.write(NOTIFY_WINDOW_MESSAGE);
17047
+ }
17048
+ if (result.metadata.expiryClamped === true) process.stderr.write(`Share expiry clamped to session expiry (${result.metadata.expiresAt}).
17049
+ `);
17050
+ if (json) writeJson2({ ...redactPublishedShare(result), expiryClamped: result.metadata.expiryClamped === true, ...notification === void 0 ? {} : { notification } });
17051
+ else publishHuman(result);
17052
+ } catch (error) {
17053
+ handleError(shareCliError(error));
17003
17054
  }
17004
- if (unit >= 55296 && unit <= 56319) {
17005
- const next = text.charCodeAt(i + 1);
17006
- if (!(next >= 56320 && next <= 57343)) {
17007
- throw new TypeError(
17008
- `cannot canonicalize string with unpaired high surrogate at index ${i}`
17009
- );
17055
+ });
17056
+ share.command("inspect [url]").description("Verify a share link and print safe metadata").option("--stdin", "Read the complete URL from stdin").option("--json", "Print versioned redacted JSON").option("--viewer-origin <origin>", "Require this canonical Share origin", SHARE_ORIGIN).action(async (url, options, command) => {
17057
+ try {
17058
+ const json = jsonOutput(options, command);
17059
+ const result = await inspectShareInputOnce(url, options.stdin === true, options.viewerOrigin);
17060
+ if (json) writeJson2(result);
17061
+ else inspectHuman(result);
17062
+ } catch (error) {
17063
+ handleError(shareCliError(error));
17064
+ }
17065
+ });
17066
+ share.command("receive [url]").description("Verify and receive a share link").option("--stdin", "Read the complete URL from stdin").option("--output <directory>", "Create the file in this directory").option("--stdout", "Write verified plaintext bytes to stdout").option("--force", "Allow replacing an existing non-symlink output").option("--max-bytes <bytes>", "Bound received content bytes").option("--json", "Print versioned redacted JSON").option("--viewer-origin <origin>", "Require this canonical Share origin", SHARE_ORIGIN).action(async (url, options, command) => {
17067
+ try {
17068
+ const json = jsonOutput(options, command);
17069
+ if (options.stdout && json) throw new CLIError("INVALID_ARGUMENT", "--stdout and --json are mutually exclusive", 2);
17070
+ const maxBytes = byteLimit(options.maxBytes);
17071
+ const link2 = await inputUrl(url, options.stdin === true);
17072
+ let nativeLink = false;
17073
+ try {
17074
+ parseNativeShareUrl(link2);
17075
+ nativeLink = true;
17076
+ } catch {
17010
17077
  }
17011
- i++;
17078
+ if (nativeLink) {
17079
+ if (shareServices.nativeReader === void 0) throw new CLIError("AUTH_REQUIRED", "native TinyCloud receive is not configured", 3);
17080
+ const native = await shareServices.nativeReader(link2);
17081
+ if (maxBytes !== void 0 && native.bytes.byteLength > maxBytes) throw new CLIError("MAX_BYTES_EXCEEDED", "shared content exceeds max-bytes", 7);
17082
+ if (options.stdout) {
17083
+ process.stdout.write(Buffer.from(native.bytes));
17084
+ return;
17085
+ }
17086
+ const output2 = await writeShareOutput(options.output ?? ".", native.filename, native.bytes, options.force === true);
17087
+ if (json) writeJson2({ protocol: "tinycloud-share", version: 1, path: output2, transport: "native" });
17088
+ else receiveHuman(output2);
17089
+ return;
17090
+ }
17091
+ const result = await receiveShare(link2, {
17092
+ expectedOrigin: options.viewerOrigin,
17093
+ ...maxBytes === void 0 ? {} : { maxContentBlobBytes: maxBytes }
17094
+ });
17095
+ if ("state" in result) {
17096
+ if (json) {
17097
+ writeJson2({ protocol: "tinycloud-share", version: 1, authorization: authorizationRequiredJson(result) });
17098
+ process.exitCode = 6;
17099
+ return;
17100
+ }
17101
+ throw new CLIError(result.method === "openkey-device" ? "DEVICE_AUTH_REQUIRED" : "CLAIM_REQUIRED", "recipient authorization is required; resume through the configured authority adapter", 6);
17102
+ }
17103
+ if (options.stdout) {
17104
+ process.stdout.write(Buffer.from(result.bytes));
17105
+ return;
17106
+ }
17107
+ const output = await writeShareOutput(options.output ?? ".", result.metadata.display.filename ?? "share.md", result.bytes, options.force === true);
17108
+ if (json) receiveJson(result, output);
17109
+ else receiveHuman(output);
17110
+ } catch (error) {
17111
+ handleError(shareCliError(error));
17012
17112
  }
17013
- }
17014
- }
17015
- function serializeString2(text) {
17016
- assertNoLoneSurrogates2(text);
17017
- return JSON.stringify(text);
17018
- }
17019
- function serialize2(value) {
17020
- if (value === null) return "null";
17021
- switch (typeof value) {
17022
- case "boolean":
17023
- return JSON.stringify(value);
17024
- case "string":
17025
- return serializeString2(value);
17026
- case "number":
17027
- if (!Number.isFinite(value)) {
17028
- throw new TypeError(`cannot canonicalize non-finite number: ${value}`);
17113
+ });
17114
+ share.command("list").description("List encrypted sender history without complete bearer URLs").option("--json", "Print versioned redacted JSON").action(async (options, command) => {
17115
+ try {
17116
+ const json = jsonOutput(options, command);
17117
+ if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
17118
+ const result = await listShares(shareServices.records);
17119
+ if (json) writeJson2({ protocol: "tinycloud-share", version: 1, shares: result });
17120
+ else process.stdout.write(result.map((item) => `${item.shareId} ${item.target} ${item.expiresAt}`).join("\n") + (result.length ? "\n" : ""));
17121
+ } catch (error) {
17122
+ handleError(shareCliError(error));
17123
+ }
17124
+ });
17125
+ share.command("show <id>").description("Show one redacted sender-history record").option("--reveal-link", "Explicitly include the complete link").option("--json", "Print versioned redacted JSON").action(async (id, options, command) => {
17126
+ try {
17127
+ const json = jsonOutput(options, command);
17128
+ if (options.revealLink && json) throw new CLIError("INVALID_ARGUMENT", "--reveal-link cannot be combined with --json", 2);
17129
+ if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
17130
+ const result = await showShare({ storage: shareServices.records, shareId: id, revealLink: options.revealLink === true, link: options.revealLink ? await shareServices.linkFor?.(id) : void 0 });
17131
+ if (json) writeJson2({ protocol: "tinycloud-share", version: 1, share: result });
17132
+ else writeJson2(result);
17133
+ } catch (error) {
17134
+ handleError(shareCliError(error));
17135
+ }
17136
+ });
17137
+ share.command("notify <id>").description("Retry idempotent delivery within 5 minutes of publication; after that publish a new share").requiredOption("--to <address>", "Recipient email").option("--json", "Print versioned JSON").action(async (id, options, command) => {
17138
+ try {
17139
+ const json = jsonOutput(options, command);
17140
+ if (shareServices.delivery === void 0) throw new CLIError("AUTH_REQUIRED", "delivery authority is not configured", 3);
17141
+ if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
17142
+ const record = await shareServices.records.get(id);
17143
+ if (record === void 0) throw new CLIError("NOT_FOUND", "share not found", 4);
17144
+ if (!record.actions.includes("tinycloud.kv/get")) {
17145
+ throw new CLIError("INVALID_ARGUMENT", "share notify requires a stored share with the read action; no invitation was sent", 2);
17029
17146
  }
17030
- return JSON.stringify(value);
17031
- case "object":
17032
- break;
17033
- default:
17034
- throw new TypeError(`cannot canonicalize value of type ${typeof value}`);
17035
- }
17036
- if (Array.isArray(value)) {
17037
- return `[${value.map((item) => serialize2(item)).join(",")}]`;
17038
- }
17039
- if (!isPlainRecord2(value)) {
17040
- throw new TypeError("cannot canonicalize non-plain object");
17041
- }
17042
- const keys = Object.keys(value).sort();
17043
- const members = [];
17044
- for (const key of keys) {
17045
- const member = value[key];
17046
- if (member === void 0) continue;
17047
- members.push(`${serializeString2(key)}:${serialize2(member)}`);
17048
- }
17049
- return `{${members.join(",")}}`;
17050
- }
17051
- function canonicalize2(value) {
17052
- return serialize2(value);
17147
+ const mailbox = canonicalMailbox2(options.to);
17148
+ if (mailbox === void 0) throw new ShareNotifyError("recipient is invalid");
17149
+ if (!recipientMatchesShareRecord(record, mailbox.email)) throw new ShareNotifyError("recipient does not match the stored share target");
17150
+ if (record.recipientMatcher.kind === "emailDomain" && shareDeliveryWindowExpiresAt(record) > Date.now()) {
17151
+ if (shareServices.assertDomainDelivery === void 0) throw new CLIError("UNAVAILABLE", "could not verify TinyCloud node 1.17.3 domain delivery support; no invitation was sent", 4);
17152
+ await shareServices.assertDomainDelivery();
17153
+ }
17154
+ const result = await notifyRecordedShare(record, options.to, shareServices.delivery, shareServices.records);
17155
+ if (json) writeJson2(result);
17156
+ else process.stdout.write(`${result.state}
17157
+ `);
17158
+ if (result.reason === "delivery-window-expired") process.stderr.write(NOTIFY_WINDOW_MESSAGE);
17159
+ if (result.state === "partial-failure") process.exitCode = 9;
17160
+ } catch (error) {
17161
+ handleError(shareCliError(error, "notify"));
17162
+ }
17163
+ });
17164
+ share.command("revoke <id>").description("Revoke addressed shares; report bearer retention honestly").option("--ancestor", "Revoke the owner delegation ancestry").option("--json", "Print versioned JSON").action(async (id, options, command) => {
17165
+ try {
17166
+ const json = jsonOutput(options, command);
17167
+ if (shareServices.records === void 0) throw new CLIError("AUTH_REQUIRED", "sender history storage is not configured", 3);
17168
+ const record = shareServices.getRecord ? await shareServices.getRecord(id) : await shareServices.records.get(id);
17169
+ if (record === void 0) throw new CLIError("NOT_FOUND", "share not found", 4);
17170
+ const result = await revokeShare({ record, records: shareServices.records, adapter: shareServices.revocation, scope: options.ancestor ? "ancestor" : "direct" });
17171
+ if (result.state === "unsupported") {
17172
+ throw new CLIError("UNSUPPORTED_TARGET", result.reason, 2);
17173
+ }
17174
+ if (json) writeJson2({ protocol: "tinycloud-share", version: 1, result });
17175
+ else process.stdout.write(`${result.state}
17176
+ `);
17177
+ } catch (error) {
17178
+ handleError(shareCliError(error));
17179
+ }
17180
+ });
17053
17181
  }
17054
- var MAX_INLINE_BYTES2 = 256 * 1024;
17055
17182
 
17056
17183
  // src/share/adapters.ts
17184
+ init_profiles();
17185
+ init_constants();
17186
+ import { readFile as readFile4 } from "fs/promises";
17187
+ import { join as join6 } from "path";
17188
+ import { createHash } from "crypto";
17189
+ import { writeJsonAtomic as writeJsonAtomic2 } from "@tinycloud/operations/state";
17057
17190
  import { LocationRecordValidationError, LocationRegistryHttpError, revokePolicyRootV3 } from "@tinycloud/sdk-core";
17058
17191
  import { extractSiweExpiration, InvalidRestoredSessionError } from "@tinycloud/node-sdk";
17059
17192
  function requiredKvAction(meta) {
@@ -17073,6 +17206,28 @@ function throwKvUploadFailure(error) {
17073
17206
  throw new SharePublishAuthorityError({ kind: "upload-failed" });
17074
17207
  }
17075
17208
  var DEFAULT_SHARE_ORIGIN = "https://share.tinycloud.xyz";
17209
+ var MIN_DOMAIN_DELIVERY_VERSION = "1.17.3";
17210
+ function supportsDomainDelivery(version2) {
17211
+ if (typeof version2 !== "string") return false;
17212
+ const normalized = version2.trim();
17213
+ if (normalized.length > 128) return false;
17214
+ const match = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(normalized);
17215
+ if (match === null) return false;
17216
+ if (match[4] !== void 0 && /(?:^|\.)0[0-9]+(?:\.|$)/.test(match[4])) return false;
17217
+ const major = Number(match[1]);
17218
+ const minor = Number(match[2]);
17219
+ const patch = Number(match[3]);
17220
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) return false;
17221
+ if (major !== 1) return major > 1;
17222
+ if (minor !== 17) return minor > 17;
17223
+ if (patch !== 3) return patch > 3;
17224
+ return match[4] === void 0;
17225
+ }
17226
+ function displayedNodeVersion(version2) {
17227
+ if (typeof version2 !== "string") return "(unrecognized)";
17228
+ const trimmed = version2.trim();
17229
+ return /^[A-Za-z0-9.+_-]{1,64}$/.test(trimmed) ? trimmed : "(unrecognized)";
17230
+ }
17076
17231
  var URI_SAFE_FILENAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
17077
17232
  function safeStorageFilename(filename) {
17078
17233
  if (URI_SAFE_FILENAME.test(filename) && !filename.includes("..")) return filename;
@@ -17083,6 +17238,12 @@ function safeStorageFilename(filename) {
17083
17238
  }
17084
17239
  function createEncryptedSessionHistory() {
17085
17240
  const records = /* @__PURE__ */ new Map();
17241
+ let operation = Promise.resolve();
17242
+ const serial = (action) => {
17243
+ const next = operation.then(action, action);
17244
+ operation = next.then(() => void 0, () => void 0);
17245
+ return next;
17246
+ };
17086
17247
  let keyPromise;
17087
17248
  const key = async () => keyPromise ??= crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
17088
17249
  const encode6 = async (record) => {
@@ -17097,35 +17258,45 @@ function createEncryptedSessionHistory() {
17097
17258
  const decode10 = async (value) => JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await crypto.subtle.decrypt({ name: "AES-GCM", iv: value.slice(0, 12) }, await key(), value.slice(12))));
17098
17259
  return {
17099
17260
  async put(record) {
17100
- records.set(record.shareId, await encode6(record));
17261
+ return serial(async () => {
17262
+ records.set(record.shareId, await encode6(record));
17263
+ });
17264
+ },
17265
+ async update(shareId, change) {
17266
+ return serial(async () => {
17267
+ const value = records.get(shareId);
17268
+ if (value === void 0) return void 0;
17269
+ const updated = await change(await decode10(value));
17270
+ records.set(shareId, await encode6(updated));
17271
+ return updated;
17272
+ });
17101
17273
  },
17102
17274
  async list() {
17103
- return Promise.all([...records.values()].map(decode10));
17275
+ return serial(() => Promise.all([...records.values()].map(decode10)));
17104
17276
  },
17105
17277
  async get(shareId) {
17106
- const value = records.get(shareId);
17107
- return value === void 0 ? void 0 : decode10(value);
17278
+ return serial(async () => {
17279
+ const value = records.get(shareId);
17280
+ return value === void 0 ? void 0 : decode10(value);
17281
+ });
17108
17282
  },
17109
17283
  async delete(shareId) {
17110
- records.delete(shareId);
17284
+ return serial(async () => {
17285
+ records.delete(shareId);
17286
+ });
17111
17287
  }
17112
17288
  };
17113
17289
  }
17114
17290
  function createEncryptedProfileHistory(profileName, sessionSigner) {
17115
17291
  const HISTORY_VERSION = 2;
17116
- let profileSecretPromise;
17292
+ const identityChanged = new Error("share history profile or key changed");
17293
+ const saltChanged = new Error("share history salt changed");
17117
17294
  let operation = Promise.resolve();
17118
- const profileSecret = async () => profileSecretPromise ??= (async () => {
17119
- const profile = await profileName();
17120
- const config = await ProfileManager.getProfile(profile);
17121
- if (typeof config.privateKey === "string" && config.privateKey.length > 0) return new TextEncoder().encode(config.privateKey);
17122
- if (sessionSigner === void 0) {
17123
- throw new Error("share history requires an initialized profile");
17124
- }
17125
- return sessionSigner(new TextEncoder().encode("xyz.tinycloud.share/history-key/v1"));
17126
- })();
17127
- const path = async () => join6(await ProfileManager.getCacheDir(await profileName()), "share-history-v2.json");
17128
- const legacyPath = async () => join6(await ProfileManager.getCacheDir(await profileName()), "share-history-v1.bin");
17295
+ const observedProfiles = /* @__PURE__ */ new Set();
17296
+ let preparedKeys;
17297
+ let preparedKey;
17298
+ const path = async (profile) => join6(await ProfileManager.getCacheDir(profile), "share-history-v2.json");
17299
+ const legacyPath = async (profile) => join6(await ProfileManager.getCacheDir(profile), "share-history-v1.bin");
17129
17300
  const b64 = (value) => Buffer.from(value).toString("base64url");
17130
17301
  const unb64 = (value) => {
17131
17302
  if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("share history is unavailable");
@@ -17133,81 +17304,165 @@ function createEncryptedProfileHistory(profileName, sessionSigner) {
17133
17304
  if (b64(bytes) !== value) throw new Error("share history is unavailable");
17134
17305
  return bytes;
17135
17306
  };
17136
- const derive = async (salt, legacy = false) => {
17137
- const secret = await profileSecret();
17138
- if (legacy) {
17139
- const digest = await crypto.subtle.digest("SHA-256", secret);
17140
- return crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
17307
+ const isStoredRecord = (value) => typeof value === "object" && value !== null && "shareId" in value && typeof value.shareId === "string";
17308
+ const identity = async (profile) => {
17309
+ const config = await ProfileManager.getProfile(profile);
17310
+ const localKey = typeof config.privateKey === "string" && config.privateKey.length > 0;
17311
+ const [key, session] = localKey ? [null, null] : await Promise.all([ProfileManager.getKey(profile), ProfileManager.getSession(profile)]);
17312
+ const sessionJwk = session !== null && "jwk" in session ? session.jwk : void 0;
17313
+ const signerJwk = sessionJwk !== null && typeof sessionJwk === "object" && "d" in sessionJwk && typeof sessionJwk.d === "string" && sessionJwk.d.length > 0 ? sessionJwk : key;
17314
+ const method = session !== null && "verificationMethod" in session ? session.verificationMethod ?? config.did : config.did;
17315
+ const fingerprint = createHash("sha256").update(JSON.stringify(localKey ? ["local", config.privateKey] : ["openkey", sessionJwk, signerJwk, method])).digest("hex");
17316
+ return { config, fingerprint };
17317
+ };
17318
+ const prepareKeys = async (profile, snapshot) => {
17319
+ if (preparedKeys?.profile === profile && preparedKeys.identity === snapshot.fingerprint) return preparedKeys;
17320
+ let secret;
17321
+ if (typeof snapshot.config.privateKey === "string" && snapshot.config.privateKey.length > 0) {
17322
+ secret = new TextEncoder().encode(snapshot.config.privateKey);
17323
+ } else {
17324
+ if (sessionSigner === void 0) throw new Error("share history requires an initialized profile");
17325
+ secret = await sessionSigner(new TextEncoder().encode("xyz.tinycloud.share/history-key/v1"), profile);
17141
17326
  }
17327
+ if ((await identity(profile)).fingerprint !== snapshot.fingerprint) throw identityChanged;
17142
17328
  const material = await crypto.subtle.importKey("raw", secret, "PBKDF2", false, ["deriveKey"]);
17143
- return crypto.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
17329
+ const digest = await crypto.subtle.digest("SHA-256", secret);
17330
+ const legacyKey = await crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, ["decrypt"]);
17331
+ return preparedKeys = { profile, identity: snapshot.fingerprint, material, legacyKey };
17144
17332
  };
17145
- const read4 = async () => {
17333
+ const preparedSalt = async (profile) => {
17146
17334
  try {
17147
- const encoded = new Uint8Array(await readFile4(await path()));
17148
- const envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(encoded));
17335
+ const envelope = JSON.parse(await readFile4(await path(profile), "utf8"));
17149
17336
  if (envelope.version !== HISTORY_VERSION) throw new Error("share history is unavailable");
17150
17337
  const salt = unb64(envelope.kdfSalt);
17338
+ if (salt.length < 16) throw new Error("share history is unavailable");
17339
+ return salt;
17340
+ } catch (error) {
17341
+ if (error.code === "ENOENT") return crypto.getRandomValues(new Uint8Array(16));
17342
+ throw new Error("share history is unavailable");
17343
+ }
17344
+ };
17345
+ const read4 = async (profile, ready) => {
17346
+ try {
17347
+ const envelope = JSON.parse(await readFile4(await path(profile), "utf8"));
17348
+ if (envelope.version !== HISTORY_VERSION) throw new Error("share history is unavailable");
17349
+ if (envelope.kdfSalt !== b64(ready.salt)) throw saltChanged;
17151
17350
  const iv = unb64(envelope.iv);
17152
17351
  const ciphertext = unb64(envelope.ciphertext);
17153
- if (salt.length < 16 || iv.length !== 12 || ciphertext.length <= 16) throw new Error("share history is unavailable");
17154
- const bytes = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, await derive(salt), ciphertext);
17352
+ if (iv.length !== 12 || ciphertext.length <= 16) throw new Error("share history is unavailable");
17353
+ const bytes = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, ready.key, ciphertext);
17155
17354
  const values = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
17156
- return { values: Array.isArray(values) ? values.filter((value) => typeof value === "object" && value !== null && typeof value.shareId === "string") : [], salt };
17355
+ return Array.isArray(values) ? values.filter(isStoredRecord) : [];
17157
17356
  } catch (error) {
17357
+ if (error === saltChanged) throw error;
17158
17358
  if (error.code !== "ENOENT") throw new Error("share history is unavailable");
17159
17359
  try {
17160
- const legacy = new Uint8Array(await readFile4(await legacyPath()));
17161
- if (legacy.length <= 12) return { values: [], salt: crypto.getRandomValues(new Uint8Array(16)) };
17162
- const bytes = await crypto.subtle.decrypt({ name: "AES-GCM", iv: legacy.slice(0, 12) }, await derive(new Uint8Array(0), true), legacy.slice(12));
17360
+ const legacy = new Uint8Array(await readFile4(await legacyPath(profile)));
17361
+ if (legacy.length <= 12) return [];
17362
+ const bytes = await crypto.subtle.decrypt({ name: "AES-GCM", iv: legacy.slice(0, 12) }, ready.legacyKey, legacy.slice(12));
17163
17363
  const values = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
17164
- return { values: Array.isArray(values) ? values.filter((value) => typeof value === "object" && value !== null && typeof value.shareId === "string") : [], salt: crypto.getRandomValues(new Uint8Array(16)) };
17364
+ return Array.isArray(values) ? values.filter(isStoredRecord) : [];
17165
17365
  } catch (legacyError) {
17166
- if (legacyError.code === "ENOENT") return { values: [], salt: crypto.getRandomValues(new Uint8Array(16)) };
17366
+ if (legacyError.code === "ENOENT") return [];
17167
17367
  throw new Error("share history is unavailable");
17168
17368
  }
17169
17369
  }
17170
17370
  };
17171
- const write = async (values, salt) => {
17371
+ const write = async (profile, values, ready) => {
17172
17372
  const iv = crypto.getRandomValues(new Uint8Array(12));
17173
17373
  const bytes = new TextEncoder().encode(JSON.stringify(values));
17174
- const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await derive(salt), bytes));
17175
- const output = new TextEncoder().encode(JSON.stringify({ version: HISTORY_VERSION, kdfSalt: b64(salt), iv: b64(iv), ciphertext: b64(encrypted) }));
17176
- await writeFile2(await path(), output, { mode: 384 });
17374
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, ready.key, bytes));
17375
+ await writeJsonAtomic2(await path(profile), { version: HISTORY_VERSION, kdfSalt: b64(ready.salt), iv: b64(iv), ciphertext: b64(encrypted) });
17177
17376
  };
17178
- const serial = (operationFn) => {
17179
- const next = operation.then(operationFn, operationFn);
17377
+ const serial = (action) => {
17378
+ const next = operation.then(action, action);
17180
17379
  operation = next.then(() => void 0, () => void 0);
17181
17380
  return next;
17182
17381
  };
17382
+ const locked = (action, writing = false) => serial(async () => {
17383
+ const profile = await profileName();
17384
+ let warned = false;
17385
+ for (let attempt = 0; attempt < 3; attempt++) {
17386
+ try {
17387
+ const snapshot = await identity(profile);
17388
+ observedProfiles.add(profile);
17389
+ const keys = await prepareKeys(profile, snapshot);
17390
+ const salt = await preparedSalt(profile);
17391
+ const saltId = b64(salt);
17392
+ const key = preparedKey?.profile === profile && preparedKey.identity === snapshot.fingerprint && preparedKey.salt === saltId ? preparedKey.key : await crypto.subtle.deriveKey(
17393
+ { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
17394
+ keys.material,
17395
+ { name: "AES-GCM", length: 256 },
17396
+ false,
17397
+ ["encrypt", "decrypt"]
17398
+ );
17399
+ preparedKey = { profile, identity: snapshot.fingerprint, salt: saltId, key };
17400
+ const warning = writing ? setTimeout(() => {
17401
+ if (!warned) {
17402
+ warned = true;
17403
+ process.stderr.write(`Waiting for profile lock for ${JSON.stringify(profile)} before updating sender history.
17404
+ `);
17405
+ }
17406
+ }, 2e3) : void 0;
17407
+ warning?.unref();
17408
+ try {
17409
+ return await ProfileManager.withLock(profile, async () => {
17410
+ clearTimeout(warning);
17411
+ if ((await identity(profile)).fingerprint !== snapshot.fingerprint) throw identityChanged;
17412
+ return action(profile, { salt, key, legacyKey: keys.legacyKey });
17413
+ }, writing ? { timeoutMs: PROFILE_COMMIT_LOCK_TIMEOUT_MS } : void 0);
17414
+ } finally {
17415
+ clearTimeout(warning);
17416
+ }
17417
+ } catch (error) {
17418
+ if (error === saltChanged || error === identityChanged) continue;
17419
+ if (observedProfiles.has(profile) && typeof error === "object" && error !== null && "code" in error && error.code === "PROFILE_NOT_FOUND") {
17420
+ throw new ShareHistoryRetryError(profile);
17421
+ }
17422
+ throw error;
17423
+ }
17424
+ }
17425
+ throw new ShareHistoryRetryError(profile);
17426
+ });
17183
17427
  return {
17184
17428
  async put(record) {
17185
- return serial(async () => {
17186
- const state = await read4();
17187
- const values = [...state.values];
17429
+ return locked(async (profile, ready) => {
17430
+ const values = await read4(profile, ready);
17188
17431
  const index = values.findIndex((value) => value.shareId === record.shareId);
17189
17432
  if (index >= 0) values[index] = record;
17190
17433
  else values.push(record);
17191
- await write(values, state.salt);
17192
- });
17434
+ await write(profile, values, ready);
17435
+ }, true);
17436
+ },
17437
+ async update(shareId, change) {
17438
+ return locked(async (profile, ready) => {
17439
+ const values = await read4(profile, ready);
17440
+ const index = values.findIndex((record) => record.shareId === shareId);
17441
+ if (index < 0) return void 0;
17442
+ const updated = await change(values[index]);
17443
+ values[index] = updated;
17444
+ await write(profile, values, ready);
17445
+ return updated;
17446
+ }, true);
17193
17447
  },
17194
17448
  async list() {
17195
- return serial(async () => (await read4()).values);
17449
+ return locked((profile, ready) => read4(profile, ready));
17196
17450
  },
17197
17451
  async get(shareId) {
17198
- return serial(async () => (await read4()).values.find((record) => record.shareId === shareId));
17452
+ return locked(async (profile, ready) => (await read4(profile, ready)).find((record) => record.shareId === shareId));
17199
17453
  },
17200
17454
  async delete(shareId) {
17201
- return serial(async () => {
17202
- const state = await read4();
17203
- await write(state.values.filter((record) => record.shareId !== shareId), state.salt);
17204
- });
17455
+ return locked(async (profile, ready) => {
17456
+ await write(profile, (await read4(profile, ready)).filter((record) => record.shareId !== shareId), ready);
17457
+ }, true);
17205
17458
  }
17206
17459
  };
17207
17460
  }
17208
17461
  function createShareAuthorityAdapters(input = {}) {
17209
17462
  const origin = input.origin ?? DEFAULT_SHARE_ORIGIN;
17210
17463
  const fetchFn = input.fetchFn ?? globalThis.fetch;
17464
+ let selectedProfile;
17465
+ const profileName = () => selectedProfile ??= input.profileName?.() ?? selectedProfileName();
17211
17466
  const canonicalOrigin2 = (value, label) => {
17212
17467
  if (typeof value !== "string") throw new Error(`share ${label} is unavailable`);
17213
17468
  const parsed = new URL(value);
@@ -17237,7 +17492,7 @@ function createShareAuthorityAdapters(input = {}) {
17237
17492
  let nodePromise;
17238
17493
  let activeProfileName2;
17239
17494
  const authenticatedNode = async () => nodePromise ??= (async () => {
17240
- const profile = await (input.profileName?.() ?? selectedProfileName());
17495
+ const profile = await profileName();
17241
17496
  activeProfileName2 = profile;
17242
17497
  const context = await ProfileManager.resolveContext({ profile, ...input.nodeOrigin === void 0 ? {} : { host: input.nodeOrigin } });
17243
17498
  const { ensureAuthenticated: ensureAuthenticated2 } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
@@ -17256,6 +17511,38 @@ function createShareAuthorityAdapters(input = {}) {
17256
17511
  throw error;
17257
17512
  }
17258
17513
  })();
17514
+ const assertDomainDeliveryForOrigin = async (nodeOrigin, operation) => {
17515
+ let response;
17516
+ try {
17517
+ response = await fetchFn(`${nodeOrigin}/info`, { signal: AbortSignal.timeout(5e3) });
17518
+ } catch {
17519
+ throw new SharePublishAuthorityError({ kind: "node-info-unavailable" });
17520
+ }
17521
+ if (!response.ok) throw new SharePublishAuthorityError({ kind: "node-info-unavailable" });
17522
+ let body;
17523
+ try {
17524
+ body = await response.text();
17525
+ } catch {
17526
+ throw new SharePublishAuthorityError({ kind: "node-info-unavailable" });
17527
+ }
17528
+ let info;
17529
+ try {
17530
+ info = JSON.parse(body);
17531
+ } catch {
17532
+ info = void 0;
17533
+ }
17534
+ const version2 = typeof info === "object" && info !== null && "version" in info ? info.version : void 0;
17535
+ if (!supportsDomainDelivery(version2)) {
17536
+ throw new SharePublishAuthorityError({
17537
+ kind: "invalid-request",
17538
+ reason: `domain notifications require tinycloud-node ${MIN_DOMAIN_DELIVERY_VERSION} or later; node reports version ${displayedNodeVersion(version2)}. Upgrade the node before inviting; ${operation === "publish" ? "nothing was shared and no invitation was sent" : "no invitation was sent"}`
17539
+ });
17540
+ }
17541
+ };
17542
+ const assertDomainDelivery = async () => {
17543
+ const node = await authenticatedNode();
17544
+ await assertDomainDeliveryForOrigin((await node.activeNodeIdentity()).origin, "notify");
17545
+ };
17259
17546
  const targetAdapter = { async publish(targetInput) {
17260
17547
  if (input.publishTarget !== void 0) return input.publishTarget(targetInput);
17261
17548
  const [config, node] = await Promise.all([publicConfig(), authenticatedNode()]);
@@ -17306,6 +17593,9 @@ function createShareAuthorityAdapters(input = {}) {
17306
17593
  });
17307
17594
  }
17308
17595
  const activeNode = await node.activeNodeIdentity();
17596
+ if (targetInput.notify === true && targetInput.target.kind === "emailDomain") {
17597
+ await assertDomainDeliveryForOrigin(activeNode.origin, "publish");
17598
+ }
17309
17599
  const shareId = crypto.randomUUID().replaceAll("-", "");
17310
17600
  const files = targetInput.files === void 0 || targetInput.files.length === 0 ? [{ bytes: targetInput.source, filename: targetInput.filename, mediaType: targetInput.mediaType }] : targetInput.files;
17311
17601
  const resourceKind = targetInput.resourceKind ?? "exact";
@@ -17470,12 +17760,10 @@ function createShareAuthorityAdapters(input = {}) {
17470
17760
  const delivery = { deliver: input.deliver ?? (async (request) => {
17471
17761
  const record = request.record;
17472
17762
  if (record === void 0 || record.link === void 0 || record.deliveryMaterial === void 0 || request.idempotencyKey === void 0) throw new Error("share delivery history is incomplete");
17763
+ const expiry = shareDeliveryWindowExpiresAt(record);
17764
+ if (expiry <= Date.now()) throw new ShareNotifyError("share delivery authorization window has expired", "delivery-window-expired");
17765
+ const authorizationExpiresAt = new Date(expiry).toISOString();
17473
17766
  const [config, node] = await Promise.all([publicConfig(), authenticatedNode()]);
17474
- const authorizationExpiresAt = new Date(Math.min(
17475
- Date.parse(record.expiresAt),
17476
- Date.parse(record.registeredAt) + 5 * 60 * 1e3
17477
- )).toISOString();
17478
- if (Date.parse(authorizationExpiresAt) <= Date.now()) throw new Error("share delivery authorization retry window has expired");
17479
17767
  const receipt = await node.authorizeShareDeliveryV3({
17480
17768
  envelope: record.deliveryMaterial.envelope,
17481
17769
  sealedEnvelope: record.deliveryMaterial.sealedEnvelope,
@@ -17536,14 +17824,16 @@ function createShareAuthorityAdapters(input = {}) {
17536
17824
  };
17537
17825
  return {
17538
17826
  targetAdapter,
17539
- records: input.profileName === void 0 ? createEncryptedSessionHistory() : createEncryptedProfileHistory(input.profileName, async (bytes) => {
17540
- const profileName = await input.profileName();
17541
- const context = await ProfileManager.resolveContext({ profile: profileName });
17827
+ records: input.profileName === void 0 ? createEncryptedSessionHistory() : createEncryptedProfileHistory(profileName, async (bytes, profile) => {
17828
+ const context = await ProfileManager.resolveContext({ profile });
17829
+ if (context.profile !== profile) throw new ShareHistoryRetryError(profile);
17542
17830
  const { ensureAuthenticated: ensureAuthenticated2 } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
17543
- return (await ensureAuthenticated2(context)).signSessionBytes(bytes);
17831
+ const signer = await ensureAuthenticated2(context);
17832
+ return signer.signSessionBytes(bytes);
17544
17833
  }),
17545
17834
  delivery,
17546
17835
  revocation,
17836
+ assertDomainDelivery,
17547
17837
  nativeReader
17548
17838
  };
17549
17839
  }
@@ -17602,6 +17892,7 @@ configureShareCommandServices({
17602
17892
  targetAdapter: shareAuthority.targetAdapter,
17603
17893
  records: shareAuthority.records,
17604
17894
  delivery: shareAuthority.delivery,
17895
+ assertDomainDelivery: shareAuthority.assertDomainDelivery,
17605
17896
  revocation: shareAuthority.revocation,
17606
17897
  nativeReader: shareAuthority.nativeReader
17607
17898
  });