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

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