@mp-lb/forum-cli 0.1.55 → 0.1.57

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
@@ -1879,12 +1879,12 @@ var KNOWN_JUNK_RULES = [
1879
1879
  ];
1880
1880
  var detectJunk = (paths, rules = KNOWN_JUNK_RULES) => {
1881
1881
  const grouped = /* @__PURE__ */ new Map();
1882
- for (const path28 of paths) {
1883
- const rule = rules.find((candidate) => candidate.matches(path28));
1882
+ for (const path36 of paths) {
1883
+ const rule = rules.find((candidate) => candidate.matches(path36));
1884
1884
  if (!rule) continue;
1885
1885
  const existing = grouped.get(rule);
1886
- if (existing) existing.push(path28);
1887
- else grouped.set(rule, [path28]);
1886
+ if (existing) existing.push(path36);
1887
+ else grouped.set(rule, [path36]);
1888
1888
  }
1889
1889
  return rules.filter((rule) => grouped.has(rule)).map((rule) => ({
1890
1890
  rule,
@@ -2102,8 +2102,8 @@ var prepareCheckoutIgnore = async ({
2102
2102
 
2103
2103
  // src/index.ts
2104
2104
  import { realpathSync, watch as watch2 } from "fs";
2105
- import path27 from "path";
2106
- import { lstat as lstat6, mkdir as mkdir7, readFile as readFile11, rm as rm8, writeFile as writeFile6 } from "fs/promises";
2105
+ import path35 from "path";
2106
+ import { lstat as lstat6, mkdir as mkdir7, readFile as readFile12, rm as rm8, writeFile as writeFile7 } from "fs/promises";
2107
2107
  import { createInterface as createInterface2 } from "readline/promises";
2108
2108
  import { pathToFileURL } from "url";
2109
2109
 
@@ -2873,10 +2873,10 @@ function mergeDefs(...defs) {
2873
2873
  function cloneDef(schema) {
2874
2874
  return mergeDefs(schema._zod.def);
2875
2875
  }
2876
- function getElementAtPath(obj, path28) {
2877
- if (!path28)
2876
+ function getElementAtPath(obj, path36) {
2877
+ if (!path36)
2878
2878
  return obj;
2879
- return path28.reduce((acc, key) => acc?.[key], obj);
2879
+ return path36.reduce((acc, key) => acc?.[key], obj);
2880
2880
  }
2881
2881
  function promiseAllObject(promisesObj) {
2882
2882
  const keys = Object.keys(promisesObj);
@@ -3285,11 +3285,11 @@ function explicitlyAborted(x, startIndex = 0) {
3285
3285
  }
3286
3286
  return false;
3287
3287
  }
3288
- function prefixIssues(path28, issues) {
3288
+ function prefixIssues(path36, issues) {
3289
3289
  return issues.map((iss) => {
3290
3290
  var _a4;
3291
3291
  (_a4 = iss).path ?? (_a4.path = []);
3292
- iss.path.unshift(path28);
3292
+ iss.path.unshift(path36);
3293
3293
  return iss;
3294
3294
  });
3295
3295
  }
@@ -3360,8 +3360,8 @@ function cleanEnum(obj) {
3360
3360
  return Number.isNaN(Number.parseInt(k, 10));
3361
3361
  }).map((el) => el[1]);
3362
3362
  }
3363
- function base64ToUint8Array(base643) {
3364
- const binaryString = atob(base643);
3363
+ function base64ToUint8Array(base644) {
3364
+ const binaryString = atob(base644);
3365
3365
  const bytes = new Uint8Array(binaryString.length);
3366
3366
  for (let i = 0; i < binaryString.length; i++) {
3367
3367
  bytes[i] = binaryString.charCodeAt(i);
@@ -3376,9 +3376,9 @@ function uint8ArrayToBase64(bytes) {
3376
3376
  return btoa(binaryString);
3377
3377
  }
3378
3378
  function base64urlToUint8Array(base64url3) {
3379
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
3380
- const padding = "=".repeat((4 - base643.length % 4) % 4);
3381
- return base64ToUint8Array(base643 + padding);
3379
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
3380
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
3381
+ return base64ToUint8Array(base644 + padding);
3382
3382
  }
3383
3383
  function uint8ArrayToBase64url(bytes) {
3384
3384
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -3436,16 +3436,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
3436
3436
  }
3437
3437
  function formatError(error51, mapper = (issue2) => issue2.message) {
3438
3438
  const fieldErrors = { _errors: [] };
3439
- const processError = (error52, path28 = []) => {
3439
+ const processError = (error52, path36 = []) => {
3440
3440
  for (const issue2 of error52.issues) {
3441
3441
  if (issue2.code === "invalid_union" && issue2.errors.length) {
3442
- issue2.errors.map((issues) => processError({ issues }, [...path28, ...issue2.path]));
3442
+ issue2.errors.map((issues) => processError({ issues }, [...path36, ...issue2.path]));
3443
3443
  } else if (issue2.code === "invalid_key") {
3444
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3444
+ processError({ issues: issue2.issues }, [...path36, ...issue2.path]);
3445
3445
  } else if (issue2.code === "invalid_element") {
3446
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3446
+ processError({ issues: issue2.issues }, [...path36, ...issue2.path]);
3447
3447
  } else {
3448
- const fullpath = [...path28, ...issue2.path];
3448
+ const fullpath = [...path36, ...issue2.path];
3449
3449
  if (fullpath.length === 0) {
3450
3450
  fieldErrors._errors.push(mapper(issue2));
3451
3451
  } else {
@@ -3472,17 +3472,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
3472
3472
  }
3473
3473
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
3474
3474
  const result = { errors: [] };
3475
- const processError = (error52, path28 = []) => {
3475
+ const processError = (error52, path36 = []) => {
3476
3476
  var _a4, _b;
3477
3477
  for (const issue2 of error52.issues) {
3478
3478
  if (issue2.code === "invalid_union" && issue2.errors.length) {
3479
- issue2.errors.map((issues) => processError({ issues }, [...path28, ...issue2.path]));
3479
+ issue2.errors.map((issues) => processError({ issues }, [...path36, ...issue2.path]));
3480
3480
  } else if (issue2.code === "invalid_key") {
3481
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3481
+ processError({ issues: issue2.issues }, [...path36, ...issue2.path]);
3482
3482
  } else if (issue2.code === "invalid_element") {
3483
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3483
+ processError({ issues: issue2.issues }, [...path36, ...issue2.path]);
3484
3484
  } else {
3485
- const fullpath = [...path28, ...issue2.path];
3485
+ const fullpath = [...path36, ...issue2.path];
3486
3486
  if (fullpath.length === 0) {
3487
3487
  result.errors.push(mapper(issue2));
3488
3488
  continue;
@@ -3514,8 +3514,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
3514
3514
  }
3515
3515
  function toDotPath(_path) {
3516
3516
  const segs = [];
3517
- const path28 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3518
- for (const seg of path28) {
3517
+ const path36 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3518
+ for (const seg of path36) {
3519
3519
  if (typeof seg === "number")
3520
3520
  segs.push(`[${seg}]`);
3521
3521
  else if (typeof seg === "symbol")
@@ -4744,8 +4744,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
4744
4744
  function isValidBase64URL(data) {
4745
4745
  if (!base64url.test(data))
4746
4746
  return false;
4747
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
4748
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
4747
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
4748
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
4749
4749
  return isValidBase64(padded);
4750
4750
  }
4751
4751
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -16207,13 +16207,13 @@ function resolveRef(ref, ctx) {
16207
16207
  if (!ref.startsWith("#")) {
16208
16208
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
16209
16209
  }
16210
- const path28 = ref.slice(1).split("/").filter(Boolean);
16211
- if (path28.length === 0) {
16210
+ const path36 = ref.slice(1).split("/").filter(Boolean);
16211
+ if (path36.length === 0) {
16212
16212
  return ctx.rootSchema;
16213
16213
  }
16214
16214
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
16215
- if (path28[0] === defsKey) {
16216
- const key = path28[1];
16215
+ if (path36[0] === defsKey) {
16216
+ const key = path36[1];
16217
16217
  if (!key || !ctx.defs[key]) {
16218
16218
  throw new Error(`Reference not found: ${ref}`);
16219
16219
  }
@@ -16622,8 +16622,8 @@ function date4(params) {
16622
16622
  config(en_default());
16623
16623
 
16624
16624
  // ../../packages/encryption/src/bytes/base64ToBytes.ts
16625
- var base64ToBytes = (base643) => {
16626
- const binary = atob(base643);
16625
+ var base64ToBytes = (base644) => {
16626
+ const binary = atob(base644);
16627
16627
  const bytes = new Uint8Array(binary.length);
16628
16628
  for (let index = 0; index < binary.length; index += 1) {
16629
16629
  bytes[index] = binary.charCodeAt(index);
@@ -16646,6 +16646,224 @@ var toBufferSource = (bytes) => bytes.buffer.slice(
16646
16646
  bytes.byteOffset + bytes.byteLength
16647
16647
  );
16648
16648
 
16649
+ // ../../packages/encryption/src/cipherNames.ts
16650
+ var encryptedFileCipher = "AES-GCM";
16651
+ var publicKeyCipher = "RSA-OAEP-SHA-256";
16652
+
16653
+ // ../../packages/encryption/src/envelope/EncryptedEnvelopeMismatchError.ts
16654
+ var messages = {
16655
+ different_object: "This encrypted content belongs to a different encrypted file than expected.",
16656
+ stale: "This encrypted content is an older revision than expected; it may have been replayed or restored.",
16657
+ unbound: "This encrypted content uses an older format without an authenticated identity, but an identity was expected."
16658
+ };
16659
+ var EncryptedEnvelopeMismatchError = class extends Error {
16660
+ continuity;
16661
+ constructor(continuity) {
16662
+ super(messages[continuity] ?? "Unexpected encrypted content.");
16663
+ this.name = "EncryptedEnvelopeMismatchError";
16664
+ this.continuity = continuity;
16665
+ }
16666
+ };
16667
+
16668
+ // ../../packages/encryption/src/envelope/readEncryptedEnvelopeIdentity.ts
16669
+ var readEncryptedEnvelopeIdentity = (envelope) => envelope.doctrineEncryptedFile === 4 ? { objectId: envelope.objectId, revision: envelope.revision } : null;
16670
+
16671
+ // ../../packages/encryption/src/envelope/assertEncryptedEnvelopeExpectation.ts
16672
+ var assertEncryptedEnvelopeExpectation = (envelope, { minRevision, objectId }) => {
16673
+ if (objectId === void 0 && minRevision === void 0) {
16674
+ return;
16675
+ }
16676
+ const identity = readEncryptedEnvelopeIdentity(envelope);
16677
+ if (!identity) {
16678
+ throw new EncryptedEnvelopeMismatchError("unbound");
16679
+ }
16680
+ if (objectId !== void 0 && identity.objectId !== objectId) {
16681
+ throw new EncryptedEnvelopeMismatchError("different_object");
16682
+ }
16683
+ if (minRevision !== void 0 && identity.revision < minRevision) {
16684
+ throw new EncryptedEnvelopeMismatchError("stale");
16685
+ }
16686
+ };
16687
+
16688
+ // ../../packages/encryption/src/envelope/createEncryptedEnvelopeIdentity.ts
16689
+ var createEncryptedEnvelopeIdentity = () => ({
16690
+ objectId: crypto.randomUUID(),
16691
+ revision: 0
16692
+ });
16693
+
16694
+ // ../../packages/encryption/src/envelope/encryptedEnvelopeLimits.ts
16695
+ var encryptedEnvelopeLimits = {
16696
+ maxEnvelopeChars: 16 * 1024 * 1024,
16697
+ maxLabelChars: 512,
16698
+ maxRecipientIdChars: 256,
16699
+ maxRecipients: 256,
16700
+ maxRevision: Number.MAX_SAFE_INTEGER,
16701
+ maxWrappedKeyChars: 2048
16702
+ };
16703
+
16704
+ // ../../packages/encryption/src/envelope/continueEncryptedEnvelopeIdentity.ts
16705
+ var continueEncryptedEnvelopeIdentity = (envelope, { floorRevision = 0 } = {}) => {
16706
+ const current = readEncryptedEnvelopeIdentity(envelope);
16707
+ if (!current) {
16708
+ return createEncryptedEnvelopeIdentity();
16709
+ }
16710
+ const revision = Math.max(current.revision, floorRevision) + 1;
16711
+ if (revision > encryptedEnvelopeLimits.maxRevision) {
16712
+ throw new Error("Encrypted file revision limit reached.");
16713
+ }
16714
+ return { objectId: current.objectId, revision };
16715
+ };
16716
+
16717
+ // ../../packages/encryption/src/envelope/createEncryptedEnvelopeBinding.ts
16718
+ var encryptedEnvelopeBindingPurpose = "forum-encrypted-file-envelope";
16719
+ var textEncoder = new TextEncoder();
16720
+ var createEncryptedEnvelopeBinding = (header2) => textEncoder.encode(
16721
+ JSON.stringify([
16722
+ encryptedEnvelopeBindingPurpose,
16723
+ header2.doctrineEncryptedFile,
16724
+ header2.cipher,
16725
+ header2.objectId,
16726
+ header2.revision,
16727
+ header2.workspaceAccess,
16728
+ header2.recipients.map((recipient) => [
16729
+ recipient.recipientId,
16730
+ recipient.label ?? null,
16731
+ recipient.wrappedDataKey.cipher,
16732
+ recipient.wrappedDataKey.data,
16733
+ recipient.wrappedDataKey.cipher === encryptedFileCipher ? recipient.wrappedDataKey.iv : null
16734
+ ])
16735
+ ])
16736
+ );
16737
+
16738
+ // ../../packages/encryption/src/envelope/EncryptedEnvelopeFormatError.ts
16739
+ var EncryptedEnvelopeFormatError = class extends Error {
16740
+ constructor(detail) {
16741
+ super(
16742
+ detail ? `Unsupported encrypted file format: ${detail}` : "Unsupported encrypted file format."
16743
+ );
16744
+ this.name = "EncryptedEnvelopeFormatError";
16745
+ }
16746
+ };
16747
+
16748
+ // ../../packages/encryption/src/envelope/encryptedEnvelopeVersions.ts
16749
+ var legacyEncryptedEnvelopeVersion = 2;
16750
+ var unboundEncryptedEnvelopeVersion = 3;
16751
+ var boundEncryptedEnvelopeVersion = 4;
16752
+
16753
+ // ../../packages/encryption/src/envelope/encryptedEnvelopeSchemas.ts
16754
+ var base64Pattern = /^[A-Za-z0-9+/]+={0,2}$/;
16755
+ var base643 = (maxChars) => external_exports.string().min(1).max(maxChars).regex(base64Pattern, "Expected base64.");
16756
+ var ivSchema = external_exports.string().length(16).regex(base64Pattern, "Expected base64.");
16757
+ var untrimmedText = (maxChars) => external_exports.string().min(1).max(maxChars).refine((value) => value.trim() === value, "Unexpected whitespace.");
16758
+ var boundAesWrappedKeySchema = external_exports.strictObject({
16759
+ cipher: external_exports.literal(encryptedFileCipher),
16760
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars),
16761
+ iv: ivSchema
16762
+ });
16763
+ var boundPublicKeyWrappedKeySchema = external_exports.strictObject({
16764
+ cipher: external_exports.literal(publicKeyCipher),
16765
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars)
16766
+ });
16767
+ var boundRecipientSchema = external_exports.strictObject({
16768
+ label: untrimmedText(encryptedEnvelopeLimits.maxLabelChars).optional(),
16769
+ recipientId: untrimmedText(encryptedEnvelopeLimits.maxRecipientIdChars),
16770
+ wrappedDataKey: external_exports.discriminatedUnion("cipher", [
16771
+ boundAesWrappedKeySchema,
16772
+ boundPublicKeyWrappedKeySchema
16773
+ ])
16774
+ });
16775
+ var hasUniqueRecipientIds = (recipients) => new Set(recipients.map((recipient) => recipient.recipientId)).size === recipients.length;
16776
+ var boundHeaderShape = {
16777
+ doctrineEncryptedFile: external_exports.literal(boundEncryptedEnvelopeVersion),
16778
+ cipher: external_exports.literal(encryptedFileCipher),
16779
+ objectId: external_exports.uuid(),
16780
+ revision: external_exports.number().int().min(0).max(encryptedEnvelopeLimits.maxRevision),
16781
+ workspaceAccess: external_exports.enum(["personal", "team"]),
16782
+ recipients: external_exports.array(boundRecipientSchema).min(1).max(encryptedEnvelopeLimits.maxRecipients).refine(hasUniqueRecipientIds, "Duplicate recipient id.")
16783
+ };
16784
+ var boundEncryptedEnvelopeHeaderSchema = external_exports.strictObject(boundHeaderShape);
16785
+ var boundEncryptedEnvelopeSchema = external_exports.strictObject({
16786
+ ...boundHeaderShape,
16787
+ data: base643(encryptedEnvelopeLimits.maxEnvelopeChars),
16788
+ iv: ivSchema
16789
+ });
16790
+ var unboundWrappedKeySchema = external_exports.discriminatedUnion("cipher", [
16791
+ external_exports.object({
16792
+ cipher: external_exports.literal(encryptedFileCipher),
16793
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars),
16794
+ iv: ivSchema
16795
+ }),
16796
+ external_exports.object({
16797
+ cipher: external_exports.literal(publicKeyCipher),
16798
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars)
16799
+ })
16800
+ ]);
16801
+ var unboundRecipientsSchema = external_exports.array(
16802
+ external_exports.object({
16803
+ label: external_exports.string().trim().min(1).max(encryptedEnvelopeLimits.maxLabelChars).optional(),
16804
+ recipientId: external_exports.string().trim().min(1).max(encryptedEnvelopeLimits.maxRecipientIdChars),
16805
+ wrappedDataKey: unboundWrappedKeySchema
16806
+ })
16807
+ ).min(1).max(encryptedEnvelopeLimits.maxRecipients);
16808
+ var unboundBodyShape = {
16809
+ cipher: external_exports.literal(encryptedFileCipher),
16810
+ data: base643(encryptedEnvelopeLimits.maxEnvelopeChars),
16811
+ iv: ivSchema,
16812
+ recipients: unboundRecipientsSchema
16813
+ };
16814
+ var legacyEncryptedEnvelopeSchema = external_exports.object({
16815
+ ...unboundBodyShape,
16816
+ doctrineEncryptedFile: external_exports.literal(legacyEncryptedEnvelopeVersion)
16817
+ });
16818
+ var unboundEncryptedEnvelopeSchema = external_exports.object({
16819
+ ...unboundBodyShape,
16820
+ doctrineEncryptedFile: external_exports.literal(unboundEncryptedEnvelopeVersion),
16821
+ workspaceAccess: external_exports.enum(["personal", "team"]).default("personal")
16822
+ });
16823
+
16824
+ // ../../packages/encryption/src/envelope/parseBoundEncryptedEnvelopeHeader.ts
16825
+ var parseBoundEncryptedEnvelopeHeader = (header2) => {
16826
+ const result = boundEncryptedEnvelopeHeaderSchema.safeParse(header2);
16827
+ if (!result.success) {
16828
+ const path36 = result.error.issues[0]?.path.join(".") || "envelope";
16829
+ throw new EncryptedEnvelopeFormatError(`invalid ${path36}.`);
16830
+ }
16831
+ return result.data;
16832
+ };
16833
+
16834
+ // ../../packages/encryption/src/envelope/parseEncryptedEnvelope.ts
16835
+ var schemaByVersion = /* @__PURE__ */ new Map([
16836
+ [2, legacyEncryptedEnvelopeSchema],
16837
+ [3, unboundEncryptedEnvelopeSchema],
16838
+ [4, boundEncryptedEnvelopeSchema]
16839
+ ]);
16840
+ var readVersion = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value.doctrineEncryptedFile : void 0;
16841
+ var parseEncryptedEnvelope = (encryptedText) => {
16842
+ if (typeof encryptedText !== "string") {
16843
+ throw new EncryptedEnvelopeFormatError("expected text.");
16844
+ }
16845
+ if (encryptedText.length > encryptedEnvelopeLimits.maxEnvelopeChars) {
16846
+ throw new EncryptedEnvelopeFormatError("the file is too large.");
16847
+ }
16848
+ let parsed;
16849
+ try {
16850
+ parsed = JSON.parse(encryptedText);
16851
+ } catch {
16852
+ throw new EncryptedEnvelopeFormatError("not valid JSON.");
16853
+ }
16854
+ const schema = schemaByVersion.get(readVersion(parsed));
16855
+ if (!schema) {
16856
+ throw new EncryptedEnvelopeFormatError("unknown envelope version.");
16857
+ }
16858
+ const result = schema.safeParse(parsed);
16859
+ if (!result.success) {
16860
+ const issue2 = result.error.issues[0];
16861
+ const path36 = issue2?.path?.join(".") || "envelope";
16862
+ throw new EncryptedEnvelopeFormatError(`invalid ${path36}.`);
16863
+ }
16864
+ return result.data;
16865
+ };
16866
+
16649
16867
  // ../../packages/encryption/src/keyBinding/UserEncryptionKeyMismatchError.ts
16650
16868
  var UserEncryptionKeyMismatchError = class extends Error {
16651
16869
  constructor(message = "Encryption key record is inconsistent: its public key does not match the protected private key.") {
@@ -16710,8 +16928,8 @@ var encodeUserEncryptionKdfBinding = (kdf) => kdf.name === "Argon2id" ? [
16710
16928
 
16711
16929
  // ../../packages/encryption/src/keyBinding/createUserEncryptionKeyBinding.ts
16712
16930
  var userEncryptionKeyBindingPurpose = "forum-user-encryption-key";
16713
- var textEncoder = new TextEncoder();
16714
- var createUserEncryptionKeyBinding = (metadata) => textEncoder.encode(
16931
+ var textEncoder2 = new TextEncoder();
16932
+ var createUserEncryptionKeyBinding = (metadata) => textEncoder2.encode(
16715
16933
  JSON.stringify([
16716
16934
  userEncryptionKeyBindingPurpose,
16717
16935
  metadata.version,
@@ -16820,7 +17038,7 @@ function getGlobal() {
16820
17038
  }
16821
17039
  var globalObject = getGlobal();
16822
17040
  var nodeBuffer = (_a3 = globalObject.Buffer) !== null && _a3 !== void 0 ? _a3 : null;
16823
- var textEncoder2 = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
17041
+ var textEncoder3 = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
16824
17042
  function hexCharCodesToInt(a, b) {
16825
17043
  return (a & 15) + (a >> 6 | a >> 3 & 8) << 4 | (b & 15) + (b >> 6 | b >> 3 & 8);
16826
17044
  }
@@ -16869,7 +17087,7 @@ var getUInt8Buffer = nodeBuffer !== null ? (data) => {
16869
17087
  throw new Error("Invalid data type!");
16870
17088
  } : (data) => {
16871
17089
  if (typeof data === "string") {
16872
- return textEncoder2.encode(data);
17090
+ return textEncoder3.encode(data);
16873
17091
  }
16874
17092
  if (ArrayBuffer.isView(data)) {
16875
17093
  return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
@@ -17448,12 +17666,12 @@ var userEncryptionKdfSchema = external_exports.union([
17448
17666
  ]);
17449
17667
 
17450
17668
  // ../../packages/encryption/src/kdf/deriveUserEncryptionPasswordKey.ts
17451
- var textEncoder3 = new TextEncoder();
17669
+ var textEncoder4 = new TextEncoder();
17452
17670
  var aesKeyAlgorithm = { length: 256, name: "AES-GCM" };
17453
17671
  var derivePbkdf2Key = async (kdf, password) => {
17454
17672
  const passwordKey = await crypto.subtle.importKey(
17455
17673
  "raw",
17456
- toBufferSource(textEncoder3.encode(password)),
17674
+ toBufferSource(textEncoder4.encode(password)),
17457
17675
  "PBKDF2",
17458
17676
  false,
17459
17677
  ["deriveKey"]
@@ -17478,7 +17696,7 @@ var deriveArgon2idKey = async (kdf, password) => {
17478
17696
  memorySize: kdf.memoryKiB,
17479
17697
  outputType: "binary",
17480
17698
  parallelism: kdf.parallelism,
17481
- password: textEncoder3.encode(normalizeEncryptionPassword(password)),
17699
+ password: textEncoder4.encode(normalizeEncryptionPassword(password)),
17482
17700
  salt: base64ToBytes(kdf.salt)
17483
17701
  });
17484
17702
  try {
@@ -17516,8 +17734,6 @@ var meetsCurrentUserEncryptionKdfPolicy = (kdf) => {
17516
17734
  // ../../packages/encryption/src/fileEncryption.ts
17517
17735
  var legacyEncryptedFileVersion = 2;
17518
17736
  var currentEncryptedFileVersion = 3;
17519
- var encryptedFileCipher = "AES-GCM";
17520
- var publicKeyCipher = "RSA-OAEP-SHA-256";
17521
17737
  var externalRecipientSecretPrefix = "doctrine-recipient-v1_";
17522
17738
  var forumRecipientSecretPrefix = externalRecipientSecretPrefix;
17523
17739
  var verificationText = "doctrine-user-encryption-v1";
@@ -17611,7 +17827,7 @@ var userEncryptionMetadataSchema = external_exports.union([
17611
17827
  unboundUserEncryptionMetadataSchema,
17612
17828
  boundUserEncryptionMetadataSchema
17613
17829
  ]);
17614
- var textEncoder4 = new TextEncoder();
17830
+ var textEncoder5 = new TextEncoder();
17615
17831
  var textDecoder = new TextDecoder();
17616
17832
  var rsaAlgorithm2 = {
17617
17833
  hash: "SHA-256",
@@ -17667,6 +17883,30 @@ var decryptBytes = async ({
17667
17883
  toBufferSource(base64ToBytes(data))
17668
17884
  )
17669
17885
  );
17886
+ var envelopeAdditionalData = (envelope) => envelope.doctrineEncryptedFile === boundEncryptedEnvelopeVersion ? createEncryptedEnvelopeBinding(envelope) : void 0;
17887
+ var decryptEnvelopeBytes = async ({
17888
+ envelope,
17889
+ expectation,
17890
+ fileKey
17891
+ }) => {
17892
+ let bytes;
17893
+ try {
17894
+ bytes = await decryptBytes({
17895
+ additionalData: envelopeAdditionalData(envelope),
17896
+ data: envelope.data,
17897
+ iv: envelope.iv,
17898
+ key: fileKey
17899
+ });
17900
+ } catch {
17901
+ throw new Error(
17902
+ "Could not decrypt the encrypted file: the key is wrong, or the encrypted file or its protected metadata was modified."
17903
+ );
17904
+ }
17905
+ if (expectation) {
17906
+ assertEncryptedEnvelopeExpectation(envelope, expectation);
17907
+ }
17908
+ return bytes;
17909
+ };
17670
17910
  var exportKeyBytes = async (format, key) => new Uint8Array(await crypto.subtle.exportKey(format, key));
17671
17911
  var importPublicKey = async (value) => crypto.subtle.importKey(
17672
17912
  "spki",
@@ -17864,21 +18104,7 @@ var upgradeUserEncryptionKdf = async ({
17864
18104
  nextPassword: password
17865
18105
  });
17866
18106
  };
17867
- var parseEncryptedPlainTextPayload = (encryptedText) => {
17868
- const parsed = JSON.parse(
17869
- encryptedText
17870
- );
17871
- if (parsed.doctrineEncryptedFile !== legacyEncryptedFileVersion && parsed.doctrineEncryptedFile !== currentEncryptedFileVersion || parsed.cipher !== encryptedFileCipher || typeof parsed.data !== "string" || typeof parsed.iv !== "string" || !Array.isArray(parsed.recipients) || parsed.workspaceAccess !== void 0 && parsed.workspaceAccess !== "personal" && parsed.workspaceAccess !== "team") {
17872
- throw new Error("Unsupported encrypted file format.");
17873
- }
17874
- if (parsed.doctrineEncryptedFile === currentEncryptedFileVersion) {
17875
- return {
17876
- ...parsed,
17877
- workspaceAccess: parsed.workspaceAccess ?? "personal"
17878
- };
17879
- }
17880
- return parsed;
17881
- };
18107
+ var parseEncryptedPlainTextPayload = (encryptedText) => parseEncryptedEnvelope(encryptedText);
17882
18108
  var findEncryptionRecipient = ({
17883
18109
  recipients,
17884
18110
  recipientId
@@ -17934,17 +18160,10 @@ var unwrapFileKeyBytesForRecipientSecret = async ({
17934
18160
  }
17935
18161
  throw new Error("No recipient matched the Forum recipient secret.");
17936
18162
  };
17937
- var parseForumEncryptedFilePayload = (encryptedText) => {
17938
- const parsed = JSON.parse(
17939
- encryptedText
17940
- );
17941
- if (parsed.doctrineEncryptedFile !== legacyEncryptedFileVersion && parsed.doctrineEncryptedFile !== currentEncryptedFileVersion || parsed.cipher !== encryptedFileCipher || typeof parsed.data !== "string" || typeof parsed.iv !== "string" || !Array.isArray(parsed.recipients)) {
17942
- throw new Error("Unsupported Forum encrypted file format.");
17943
- }
17944
- return parsed;
17945
- };
18163
+ var parseForumEncryptedFilePayload = (encryptedText) => parseEncryptedEnvelope(encryptedText);
17946
18164
  var decryptForumEncryptedFile = async ({
17947
18165
  encryptedText,
18166
+ expectation,
17948
18167
  recipientSecret
17949
18168
  }) => {
17950
18169
  const payload = parseForumEncryptedFilePayload(encryptedText);
@@ -17954,11 +18173,7 @@ var decryptForumEncryptedFile = async ({
17954
18173
  recipients: payload.recipients
17955
18174
  });
17956
18175
  const fileKey = await importAesKey(fileKeyBytes, false);
17957
- return decryptBytes({
17958
- data: payload.data,
17959
- iv: payload.iv,
17960
- key: fileKey
17961
- });
18176
+ return decryptEnvelopeBytes({ envelope: payload, expectation, fileKey });
17962
18177
  };
17963
18178
  var decryptForumEncryptedFileText = async (input) => textDecoder.decode(await decryptForumEncryptedFile(input));
17964
18179
  var createExternalRecipientGrant = async ({
@@ -18007,50 +18222,60 @@ var createUserRecipientGrant = async ({
18007
18222
  };
18008
18223
  var encryptPlainTextWithFileKey = async ({
18009
18224
  fileKey,
18225
+ identity,
18010
18226
  plaintext,
18011
18227
  recipients,
18012
- version: version2 = currentEncryptedFileVersion,
18013
18228
  workspaceAccess = "personal"
18014
18229
  }) => {
18015
- const encrypted = await encryptBytes(fileKey, textEncoder4.encode(plaintext));
18016
- const payload = {
18230
+ const header2 = parseBoundEncryptedEnvelopeHeader({
18231
+ doctrineEncryptedFile: boundEncryptedEnvelopeVersion,
18017
18232
  cipher: encryptedFileCipher,
18018
- data: encrypted.data,
18019
- doctrineEncryptedFile: version2,
18020
- iv: encrypted.iv,
18021
- recipients,
18022
- ...version2 === currentEncryptedFileVersion ? { workspaceAccess } : {}
18023
- };
18024
- return JSON.stringify(payload, null, 2);
18233
+ objectId: identity.objectId,
18234
+ revision: identity.revision,
18235
+ workspaceAccess,
18236
+ recipients
18237
+ });
18238
+ const encrypted = await encryptBytes(
18239
+ fileKey,
18240
+ textEncoder5.encode(plaintext),
18241
+ createEncryptedEnvelopeBinding(header2)
18242
+ );
18243
+ const text = JSON.stringify({ ...header2, ...encrypted }, null, 2);
18244
+ if (text.length > encryptedEnvelopeLimits.maxEnvelopeChars) {
18245
+ throw new EncryptedEnvelopeFormatError("the file is too large.");
18246
+ }
18247
+ return text;
18025
18248
  };
18026
18249
  var decryptPlainTextWithFileKey = async ({
18027
18250
  encryptedText,
18251
+ expectation,
18028
18252
  fileKey
18029
- }) => {
18030
- const payload = parseEncryptedPlainTextPayload(encryptedText);
18031
- return textDecoder.decode(
18032
- await decryptBytes({
18033
- data: payload.data,
18034
- iv: payload.iv,
18035
- key: fileKey
18036
- })
18037
- );
18038
- };
18039
- var updateEncryptedPlainTextRecipients = ({
18253
+ }) => textDecoder.decode(
18254
+ await decryptEnvelopeBytes({
18255
+ envelope: parseEncryptedPlainTextPayload(encryptedText),
18256
+ expectation,
18257
+ fileKey
18258
+ })
18259
+ );
18260
+ var updateEncryptedPlainTextRecipients = async ({
18040
18261
  encryptedText,
18262
+ fileKey,
18263
+ identity,
18041
18264
  recipients,
18042
18265
  workspaceAccess
18043
18266
  }) => {
18044
- const payload = parseEncryptedPlainTextPayload(encryptedText);
18045
- return JSON.stringify(
18046
- {
18047
- ...payload,
18048
- recipients,
18049
- ...payload.doctrineEncryptedFile === currentEncryptedFileVersion ? { workspaceAccess: workspaceAccess ?? payload.workspaceAccess } : {}
18050
- },
18051
- null,
18052
- 2
18053
- );
18267
+ const envelope = parseEncryptedPlainTextPayload(encryptedText);
18268
+ const plaintext = await decryptPlainTextWithFileKey({
18269
+ encryptedText,
18270
+ fileKey
18271
+ });
18272
+ return encryptPlainTextWithFileKey({
18273
+ fileKey,
18274
+ identity: identity ?? continueEncryptedEnvelopeIdentity(envelope),
18275
+ plaintext,
18276
+ recipients,
18277
+ workspaceAccess: workspaceAccess ?? envelope.workspaceAccess ?? "personal"
18278
+ });
18054
18279
  };
18055
18280
  var bytesEqual = (left, right) => left.length === right.length && left.every((byte, index) => byte === right[index]);
18056
18281
  var createCurrentRecipient = async ({
@@ -18147,9 +18372,9 @@ var createEncryptedPlainTextFile = async ({
18147
18372
  };
18148
18373
  const text = await encryptPlainTextWithFileKey({
18149
18374
  fileKey,
18375
+ identity: createEncryptedEnvelopeIdentity(),
18150
18376
  plaintext,
18151
18377
  recipients: encryption.recipients,
18152
- version: currentEncryptedFileVersion,
18153
18378
  workspaceAccess
18154
18379
  });
18155
18380
  return {
@@ -18182,6 +18407,7 @@ var encryptTextForUser = async ({
18182
18407
  };
18183
18408
  var decryptTextForUser = async ({
18184
18409
  encryptedText,
18410
+ expectation,
18185
18411
  password,
18186
18412
  userEncryption
18187
18413
  }) => {
@@ -18197,10 +18423,35 @@ var decryptTextForUser = async ({
18197
18423
  });
18198
18424
  return decryptPlainTextWithFileKey({
18199
18425
  encryptedText,
18426
+ expectation,
18200
18427
  fileKey
18201
18428
  });
18202
18429
  };
18203
18430
 
18431
+ // ../../packages/encryption/src/envelope/parseEncryptedEnvelopeExpectation.ts
18432
+ var objectIdSchema = external_exports.uuid();
18433
+ var revisionPattern = /^\d{1,16}$/;
18434
+ var parseEncryptedEnvelopeExpectation = ({
18435
+ minRevision,
18436
+ objectId
18437
+ }) => {
18438
+ const expectation = {};
18439
+ if (objectId != null) {
18440
+ if (!objectIdSchema.safeParse(objectId).success) {
18441
+ throw new Error("--expect-object must be an encrypted object id (UUID).");
18442
+ }
18443
+ expectation.objectId = objectId.toLowerCase();
18444
+ }
18445
+ if (minRevision != null) {
18446
+ const revision = Number(minRevision);
18447
+ if (!revisionPattern.test(minRevision) || revision > encryptedEnvelopeLimits.maxRevision) {
18448
+ throw new Error("--min-revision must be a non-negative integer.");
18449
+ }
18450
+ expectation.minRevision = revision;
18451
+ }
18452
+ return expectation;
18453
+ };
18454
+
18204
18455
  // ../../packages/encryption/src/keyBinding/formatEncryptionFingerprint.ts
18205
18456
  var formatEncryptionFingerprint = (fingerprint) => (fingerprint.toUpperCase().match(/.{1,4}/g) ?? []).join(" ");
18206
18457
 
@@ -18328,6 +18579,7 @@ var rekeyEncryptedPlainText = async ({
18328
18579
  actorUserKey,
18329
18580
  encryptedText,
18330
18581
  fileKey,
18582
+ identity,
18331
18583
  plan,
18332
18584
  workspaceAccess
18333
18585
  }) => {
@@ -18390,9 +18642,9 @@ var rekeyEncryptedPlainText = async ({
18390
18642
  const nextWorkspaceAccess = workspaceAccess ?? payload.workspaceAccess ?? "personal";
18391
18643
  const nextEncryptedText = await encryptPlainTextWithFileKey({
18392
18644
  fileKey: nextFileKey,
18645
+ identity: identity ?? continueEncryptedEnvelopeIdentity(payload),
18393
18646
  plaintext,
18394
18647
  recipients,
18395
- version: currentEncryptedFileVersion,
18396
18648
  workspaceAccess: nextWorkspaceAccess
18397
18649
  });
18398
18650
  const verified = await decryptPlainTextWithFileKey({
@@ -18465,6 +18717,494 @@ var validateEncryptionPassphrase = (password) => {
18465
18717
  return null;
18466
18718
  };
18467
18719
 
18720
+ // ../../packages/encryption/src/backup/EncryptionBackupError.ts
18721
+ var EncryptionBackupError = class extends Error {
18722
+ code;
18723
+ constructor(code, message) {
18724
+ super(message);
18725
+ this.code = code;
18726
+ this.name = "EncryptionBackupError";
18727
+ }
18728
+ };
18729
+
18730
+ // ../../packages/encryption/src/backup/isSafeEncryptionBackupPath.ts
18731
+ var isSafeEncryptionBackupPath = (path36) => {
18732
+ if (path36.length === 0 || path36.length > 1024) {
18733
+ return false;
18734
+ }
18735
+ if (/[\u0000-\u001f\u007f\\:]/.test(path36) || path36.startsWith("/")) {
18736
+ return false;
18737
+ }
18738
+ return path36.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
18739
+ };
18740
+
18741
+ // ../../packages/encryption/src/backup/assertEncryptionBackupPaths.ts
18742
+ var assertEncryptionBackupPaths = (paths) => {
18743
+ const seen = /* @__PURE__ */ new Set();
18744
+ for (const path36 of paths) {
18745
+ if (!isSafeEncryptionBackupPath(path36)) {
18746
+ throw new EncryptionBackupError(
18747
+ "invalid_path",
18748
+ `Refusing unsafe backup path ${JSON.stringify(path36)}.`
18749
+ );
18750
+ }
18751
+ if (seen.has(path36)) {
18752
+ throw new EncryptionBackupError(
18753
+ "duplicate_path",
18754
+ `The backup lists ${path36} more than once.`
18755
+ );
18756
+ }
18757
+ seen.add(path36);
18758
+ }
18759
+ };
18760
+
18761
+ // ../../packages/encryption/src/backup/canonicalJson.ts
18762
+ var canonicalJson = (value) => {
18763
+ if (Array.isArray(value)) {
18764
+ return `[${value.map(canonicalJson).join(",")}]`;
18765
+ }
18766
+ if (value !== null && typeof value === "object") {
18767
+ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`);
18768
+ return `{${entries.join(",")}}`;
18769
+ }
18770
+ return JSON.stringify(value);
18771
+ };
18772
+
18773
+ // ../../packages/encryption/src/backup/sha256Hex.ts
18774
+ var sha256Hex = async (text) => bytesToHex(
18775
+ new Uint8Array(
18776
+ await crypto.subtle.digest(
18777
+ "SHA-256",
18778
+ toBufferSource(new TextEncoder().encode(text))
18779
+ )
18780
+ )
18781
+ );
18782
+
18783
+ // ../../packages/encryption/src/backup/computeEncryptionBackupDigest.ts
18784
+ var computeEncryptionBackupDigest = (backup) => sha256Hex(
18785
+ canonicalJson({
18786
+ createdAt: backup.createdAt,
18787
+ files: backup.files,
18788
+ fingerprint: backup.fingerprint,
18789
+ format: backup.format,
18790
+ identity: backup.identity,
18791
+ version: backup.version
18792
+ })
18793
+ );
18794
+
18795
+ // ../../packages/encryption/src/backup/encryptionBackupFormat.ts
18796
+ var encryptionBackupFormat = {
18797
+ name: "forum-encryption-backup",
18798
+ version: 1
18799
+ };
18800
+
18801
+ // ../../packages/encryption/src/backup/decryptEncryptionBackupFile.ts
18802
+ var decryptEncryptionBackupFile = async ({
18803
+ encryptedText,
18804
+ keyId,
18805
+ path: path36,
18806
+ userKey
18807
+ }) => {
18808
+ let recipients;
18809
+ try {
18810
+ recipients = parseEncryptedPlainTextPayload(encryptedText).recipients;
18811
+ } catch {
18812
+ throw new EncryptionBackupError(
18813
+ "corrupt",
18814
+ `${path36} is not a readable Forum encrypted file.`
18815
+ );
18816
+ }
18817
+ if (!findEncryptionRecipient({ recipients, recipientId: keyId })) {
18818
+ throw new EncryptionBackupError(
18819
+ "identity_mismatch",
18820
+ `${path36} is not encrypted for this identity.`
18821
+ );
18822
+ }
18823
+ try {
18824
+ const fileKey = await unwrapFileKey({
18825
+ recipients,
18826
+ recipientId: keyId,
18827
+ userKey
18828
+ });
18829
+ return await decryptPlainTextWithFileKey({ encryptedText, fileKey });
18830
+ } catch {
18831
+ throw new EncryptionBackupError(
18832
+ "corrupt",
18833
+ `${path36} failed integrity checks and could not be decrypted.`
18834
+ );
18835
+ }
18836
+ };
18837
+
18838
+ // ../../packages/encryption/src/backup/findEncryptionBackupExclusion.ts
18839
+ var findEncryptionBackupExclusion = async ({
18840
+ encryptedText,
18841
+ keyId,
18842
+ path: path36,
18843
+ userKey
18844
+ }) => {
18845
+ let recipients;
18846
+ try {
18847
+ recipients = parseEncryptedPlainTextPayload(encryptedText).recipients;
18848
+ } catch {
18849
+ return "not_encrypted";
18850
+ }
18851
+ if (!findEncryptionRecipient({ recipients, recipientId: keyId })) {
18852
+ return "not_a_recipient";
18853
+ }
18854
+ try {
18855
+ await decryptEncryptionBackupFile({ encryptedText, keyId, path: path36, userKey });
18856
+ return null;
18857
+ } catch {
18858
+ return "undecryptable";
18859
+ }
18860
+ };
18861
+
18862
+ // ../../packages/encryption/src/backup/unlockEncryptionBackupIdentity.ts
18863
+ var unlockEncryptionBackupIdentity = async ({
18864
+ identity,
18865
+ password
18866
+ }) => {
18867
+ let fingerprint;
18868
+ try {
18869
+ fingerprint = await verifyUserEncryptionPublicKey(identity);
18870
+ } catch (error51) {
18871
+ throw new EncryptionBackupError(
18872
+ "identity_mismatch",
18873
+ error51 instanceof Error ? error51.message : "The backed-up key record is inconsistent."
18874
+ );
18875
+ }
18876
+ try {
18877
+ return {
18878
+ fingerprint,
18879
+ userKey: await unlockUserEncryption({ metadata: identity, password })
18880
+ };
18881
+ } catch (error51) {
18882
+ if (error51 instanceof UserEncryptionKeyMismatchError) {
18883
+ throw new EncryptionBackupError("identity_mismatch", error51.message);
18884
+ }
18885
+ throw new EncryptionBackupError(
18886
+ "wrong_password",
18887
+ "The encryption password does not unlock this backup's key record. Check the password that was current when the backup was made."
18888
+ );
18889
+ }
18890
+ };
18891
+
18892
+ // ../../packages/encryption/src/backup/createEncryptionBackup.ts
18893
+ var createEncryptionBackup = async ({
18894
+ createdAt = /* @__PURE__ */ new Date(),
18895
+ files,
18896
+ identity,
18897
+ password
18898
+ }) => {
18899
+ if (identity.version === 1) {
18900
+ throw new EncryptionBackupError(
18901
+ "unsupported_identity",
18902
+ "Legacy (v1) encryption cannot be backed up. Run `fm encryption migrate` first."
18903
+ );
18904
+ }
18905
+ assertEncryptionBackupPaths(files.map((file2) => file2.path));
18906
+ const { fingerprint, userKey } = await unlockEncryptionBackupIdentity({
18907
+ identity,
18908
+ password
18909
+ });
18910
+ const included = [];
18911
+ const excluded = [];
18912
+ for (const file2 of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
18913
+ const reason = await findEncryptionBackupExclusion({
18914
+ encryptedText: file2.encryptedText,
18915
+ keyId: identity.keyId,
18916
+ path: file2.path,
18917
+ userKey
18918
+ });
18919
+ if (reason) {
18920
+ excluded.push({ path: file2.path, reason });
18921
+ continue;
18922
+ }
18923
+ included.push({
18924
+ encryptedText: file2.encryptedText,
18925
+ path: file2.path,
18926
+ sha256: await sha256Hex(file2.encryptedText)
18927
+ });
18928
+ }
18929
+ const unsigned = {
18930
+ createdAt: createdAt.toISOString(),
18931
+ files: included,
18932
+ fingerprint,
18933
+ format: encryptionBackupFormat.name,
18934
+ identity,
18935
+ version: encryptionBackupFormat.version
18936
+ };
18937
+ return {
18938
+ backup: {
18939
+ ...unsigned,
18940
+ digest: await computeEncryptionBackupDigest(unsigned)
18941
+ },
18942
+ excluded
18943
+ };
18944
+ };
18945
+
18946
+ // ../../packages/encryption/src/backup/decryptEncryptionBackup.ts
18947
+ var decryptEncryptionBackup = async ({
18948
+ backup,
18949
+ password
18950
+ }) => {
18951
+ const { fingerprint, userKey } = await unlockEncryptionBackupIdentity({
18952
+ identity: backup.identity,
18953
+ password
18954
+ });
18955
+ const files = [];
18956
+ for (const file2 of backup.files) {
18957
+ files.push({
18958
+ path: file2.path,
18959
+ plaintext: await decryptEncryptionBackupFile({
18960
+ encryptedText: file2.encryptedText,
18961
+ keyId: backup.identity.keyId,
18962
+ path: file2.path,
18963
+ userKey
18964
+ })
18965
+ });
18966
+ }
18967
+ return { files, fingerprint };
18968
+ };
18969
+
18970
+ // ../../packages/encryption/src/backup/encryptionBackupSchema.ts
18971
+ var sha256HexSchema = external_exports.string().regex(/^[0-9a-f]{64}$/);
18972
+ var encryptionBackupFileSchema = external_exports.strictObject({
18973
+ path: external_exports.string(),
18974
+ // The file's encrypted envelope exactly as Forum stores it.
18975
+ encryptedText: external_exports.string().min(1),
18976
+ sha256: sha256HexSchema
18977
+ });
18978
+ var encryptionBackupSchema = external_exports.strictObject({
18979
+ format: external_exports.literal(encryptionBackupFormat.name),
18980
+ version: external_exports.literal(encryptionBackupFormat.version),
18981
+ createdAt: external_exports.iso.datetime(),
18982
+ identity: currentUserEncryptionMetadataSchema,
18983
+ fingerprint: sha256HexSchema,
18984
+ files: external_exports.array(encryptionBackupFileSchema),
18985
+ digest: sha256HexSchema
18986
+ });
18987
+
18988
+ // ../../packages/encryption/src/backup/parseEncryptionBackup.ts
18989
+ var corrupt = (detail) => new EncryptionBackupError("corrupt", `The backup is damaged: ${detail}`);
18990
+ var parseJson = (text) => {
18991
+ try {
18992
+ return JSON.parse(text);
18993
+ } catch {
18994
+ throw corrupt("it is not valid JSON (possibly truncated).");
18995
+ }
18996
+ };
18997
+ var assertFormatAndVersion = (value) => {
18998
+ const header2 = value ?? {};
18999
+ if (header2.format !== encryptionBackupFormat.name) {
19000
+ throw new EncryptionBackupError(
19001
+ "corrupt",
19002
+ "This file is not a Forum encryption backup."
19003
+ );
19004
+ }
19005
+ if (header2.version !== encryptionBackupFormat.version) {
19006
+ throw new EncryptionBackupError(
19007
+ "unsupported_version",
19008
+ `Unsupported backup version ${JSON.stringify(header2.version)}; this CLI reads version ${encryptionBackupFormat.version}. Update fm to restore it.`
19009
+ );
19010
+ }
19011
+ };
19012
+ var assertIdentity = async (backup) => {
19013
+ const fingerprint = await computeEncryptionFingerprint(
19014
+ backup.identity.publicKey
19015
+ );
19016
+ if (fingerprint !== backup.fingerprint || backup.identity.version === 3 && backup.identity.keyId !== fingerprint) {
19017
+ throw new EncryptionBackupError(
19018
+ "identity_mismatch",
19019
+ "The backup's key record does not match its recorded fingerprint."
19020
+ );
19021
+ }
19022
+ };
19023
+ var assertFileChecksums = async (backup) => {
19024
+ for (const file2 of backup.files) {
19025
+ if (await sha256Hex(file2.encryptedText) !== file2.sha256) {
19026
+ throw corrupt(`${file2.path} does not match its checksum.`);
19027
+ }
19028
+ }
19029
+ };
19030
+ var parseEncryptionBackup = async (text) => {
19031
+ const value = parseJson(text);
19032
+ assertFormatAndVersion(value);
19033
+ const parsed = encryptionBackupSchema.safeParse(value);
19034
+ if (!parsed.success) {
19035
+ if (value.identity?.version === 1) {
19036
+ throw new EncryptionBackupError(
19037
+ "unsupported_identity",
19038
+ "The backup holds a legacy (v1) key record, which is not supported."
19039
+ );
19040
+ }
19041
+ throw corrupt("its structure is invalid.");
19042
+ }
19043
+ const backup = parsed.data;
19044
+ const { digest, ...unsigned } = backup;
19045
+ if (await computeEncryptionBackupDigest(unsigned) !== digest) {
19046
+ throw corrupt("its contents do not match the recorded digest.");
19047
+ }
19048
+ assertEncryptionBackupPaths(backup.files.map((file2) => file2.path));
19049
+ await assertFileChecksums(backup);
19050
+ await assertIdentity(backup);
19051
+ return backup;
19052
+ };
19053
+
19054
+ // ../../packages/encryption/src/backup/serializeEncryptionBackup.ts
19055
+ var serializeEncryptionBackup = (backup) => `${JSON.stringify(backup, null, 2)}
19056
+ `;
19057
+
19058
+ // ../../packages/encryption/src/machineKeys/machineKeyAlgorithms.ts
19059
+ var machineRsaAlgorithm = {
19060
+ hash: "SHA-256",
19061
+ name: "RSA-OAEP"
19062
+ };
19063
+ var machineRsaKeyGenerationAlgorithm = {
19064
+ ...machineRsaAlgorithm,
19065
+ modulusLength: 2048,
19066
+ publicExponent: Uint8Array.from([1, 0, 1])
19067
+ };
19068
+
19069
+ // ../../packages/encryption/src/machineKeys/machineKeySecretPrefix.ts
19070
+ var machineKeySecretPrefix = "forum-machine-key-v1_";
19071
+
19072
+ // ../../packages/encryption/src/machineKeys/createMachineEncryptionKey.ts
19073
+ var createMachineEncryptionKey = async () => {
19074
+ const keyPair = await crypto.subtle.generateKey(
19075
+ machineRsaKeyGenerationAlgorithm,
19076
+ true,
19077
+ ["encrypt", "decrypt"]
19078
+ );
19079
+ const publicKey = {
19080
+ algorithm: publicKeyCipher,
19081
+ data: bytesToBase64(
19082
+ new Uint8Array(await crypto.subtle.exportKey("spki", keyPair.publicKey))
19083
+ )
19084
+ };
19085
+ const privateKeyBytes = new Uint8Array(
19086
+ await crypto.subtle.exportKey("pkcs8", keyPair.privateKey)
19087
+ );
19088
+ return {
19089
+ recipient: {
19090
+ keyId: await computeEncryptionFingerprint(publicKey),
19091
+ publicKey,
19092
+ version: 3
19093
+ },
19094
+ secret: `${machineKeySecretPrefix}${bytesToBase64(privateKeyBytes)}`
19095
+ };
19096
+ };
19097
+
19098
+ // ../../packages/encryption/src/machineKeys/formatMachineRecipientLabel.ts
19099
+ var machineRecipientLabelPrefix = "machine:";
19100
+ var formatMachineRecipientLabel = ({
19101
+ credentialId,
19102
+ name
19103
+ }) => `${machineRecipientLabelPrefix}${credentialId}:${encodeURIComponent(name)}`;
19104
+
19105
+ // ../../packages/encryption/src/machineKeys/createMachineRecipientGrant.ts
19106
+ var createMachineRecipientGrant = async ({
19107
+ credentialId,
19108
+ expectedFingerprint,
19109
+ fileKey,
19110
+ name,
19111
+ recipient
19112
+ }) => createUserRecipientGrant({
19113
+ expectedFingerprint,
19114
+ fileKey,
19115
+ label: formatMachineRecipientLabel({ credentialId, name }),
19116
+ userEncryption: recipient
19117
+ });
19118
+
19119
+ // ../../packages/encryption/src/machineKeys/importMachineEncryptionKey.ts
19120
+ var importMachineEncryptionKey = async (secret) => {
19121
+ const value = secret.trim();
19122
+ if (!value.startsWith(machineKeySecretPrefix)) {
19123
+ throw new Error(
19124
+ `Unsupported machine key. Expected a ${machineKeySecretPrefix}\u2026 value.`
19125
+ );
19126
+ }
19127
+ const pkcs8 = toBufferSource(
19128
+ base64ToBytes(value.slice(machineKeySecretPrefix.length))
19129
+ );
19130
+ const extractable = await crypto.subtle.importKey(
19131
+ "pkcs8",
19132
+ pkcs8,
19133
+ machineRsaAlgorithm,
19134
+ true,
19135
+ ["decrypt"]
19136
+ );
19137
+ const { e, kty, n } = await crypto.subtle.exportKey("jwk", extractable);
19138
+ const publicCryptoKey = await crypto.subtle.importKey(
19139
+ "jwk",
19140
+ { alg: "RSA-OAEP-256", e, ext: true, kty, n },
19141
+ machineRsaAlgorithm,
19142
+ true,
19143
+ ["encrypt"]
19144
+ );
19145
+ const publicKey = {
19146
+ algorithm: publicKeyCipher,
19147
+ data: bytesToBase64(
19148
+ new Uint8Array(await crypto.subtle.exportKey("spki", publicCryptoKey))
19149
+ )
19150
+ };
19151
+ return {
19152
+ privateKey: await crypto.subtle.importKey(
19153
+ "pkcs8",
19154
+ pkcs8,
19155
+ machineRsaAlgorithm,
19156
+ false,
19157
+ ["decrypt"]
19158
+ ),
19159
+ recipient: {
19160
+ keyId: await computeEncryptionFingerprint(publicKey),
19161
+ publicKey,
19162
+ version: 3
19163
+ }
19164
+ };
19165
+ };
19166
+
19167
+ // ../../packages/encryption/src/machineKeys/decryptForumEncryptedFileTextWithMachineKey.ts
19168
+ var decryptForumEncryptedFileTextWithMachineKey = async ({
19169
+ encryptedText,
19170
+ expectation,
19171
+ machineKey
19172
+ }) => {
19173
+ const payload = parseEncryptedPlainTextPayload(encryptedText);
19174
+ const { privateKey, recipient } = await importMachineEncryptionKey(machineKey);
19175
+ const entry = findEncryptionRecipient({
19176
+ recipientId: recipient.keyId,
19177
+ recipients: payload.recipients
19178
+ });
19179
+ if (!entry || entry.wrappedDataKey.cipher !== publicKeyCipher) {
19180
+ throw new Error(
19181
+ `This file has no grant for machine key ${recipient.keyId}. It may have been rekeyed without this machine.`
19182
+ );
19183
+ }
19184
+ const fileKey = await unwrapFileKey({
19185
+ recipientId: recipient.keyId,
19186
+ recipients: payload.recipients,
19187
+ userKey: privateKey
19188
+ });
19189
+ return decryptPlainTextWithFileKey({ encryptedText, expectation, fileKey });
19190
+ };
19191
+
19192
+ // ../../packages/encryption/src/machineKeys/parseMachineRecipientLabel.ts
19193
+ var parseMachineRecipientLabel = (label) => {
19194
+ if (!label?.startsWith(machineRecipientLabelPrefix)) return null;
19195
+ const value = label.slice(machineRecipientLabelPrefix.length);
19196
+ const separatorIndex = value.indexOf(":");
19197
+ const credentialId = separatorIndex === -1 ? value : value.slice(0, separatorIndex);
19198
+ if (!credentialId) return null;
19199
+ if (separatorIndex === -1) return { credentialId, name: null };
19200
+ const encodedName = value.slice(separatorIndex + 1);
19201
+ try {
19202
+ return { credentialId, name: decodeURIComponent(encodedName) || null };
19203
+ } catch {
19204
+ return { credentialId, name: encodedName || null };
19205
+ }
19206
+ };
19207
+
18468
19208
  // ../../packages/core/src/fileTypes.ts
18469
19209
  var textStorageClass = "text";
18470
19210
  var binaryStorageClass = "binary";
@@ -18495,6 +19235,7 @@ var fileTypeIdSchema = external_exports.union([
18495
19235
  external_exports.literal("signing-packet"),
18496
19236
  external_exports.literal("html"),
18497
19237
  external_exports.literal("web-link"),
19238
+ external_exports.literal("vault"),
18498
19239
  external_exports.literal("excalidraw"),
18499
19240
  external_exports.literal("audio"),
18500
19241
  external_exports.literal("image"),
@@ -18619,6 +19360,12 @@ var fileTypeDefinitions = [
18619
19360
  extensions: [".link.json"],
18620
19361
  storageClass: textStorageClass
18621
19362
  },
19363
+ {
19364
+ id: "vault",
19365
+ label: "Password vault",
19366
+ extensions: [".vault.json"],
19367
+ storageClass: textStorageClass
19368
+ },
18622
19369
  {
18623
19370
  id: "excalidraw",
18624
19371
  label: "Excalidraw",
@@ -18789,8 +19536,8 @@ var normalizeStorePath = (value) => {
18789
19536
  }
18790
19537
  return segments2.length === 0 ? "/" : `/${segments2.join("/")}`;
18791
19538
  };
18792
- var storePathToArray = (path28) => {
18793
- const normalizedPath = normalizeStorePath(path28);
19539
+ var storePathToArray = (path36) => {
19540
+ const normalizedPath = normalizeStorePath(path36);
18794
19541
  return normalizedPath === "/" ? [] : normalizedPath.split("/").filter(Boolean);
18795
19542
  };
18796
19543
  var storePathSchema = external_exports.string().trim().min(1).transform((value) => normalizeStorePath(value));
@@ -20887,21 +21634,21 @@ var isKey = (value) => /^\w*$/.test(value);
20887
21634
  var isUndefined = (val) => val === void 0;
20888
21635
  var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
20889
21636
  var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
20890
- var get = (object2, path28, defaultValue) => {
20891
- if (!path28 || !isObject2(object2)) {
21637
+ var get = (object2, path36, defaultValue) => {
21638
+ if (!path36 || !isObject2(object2)) {
20892
21639
  return defaultValue;
20893
21640
  }
20894
- const paths = isKey(path28) ? [path28] : stringToPath(path28);
21641
+ const paths = isKey(path36) ? [path36] : stringToPath(path36);
20895
21642
  const result = paths.reduce((result2, key) => {
20896
21643
  return isNullOrUndefined(result2) ? void 0 : result2[key];
20897
21644
  }, object2);
20898
- return isUndefined(result) || result === object2 ? isUndefined(object2[path28]) ? defaultValue : object2[path28] : result;
21645
+ return isUndefined(result) || result === object2 ? isUndefined(object2[path36]) ? defaultValue : object2[path36] : result;
20899
21646
  };
20900
21647
  var isBoolean = (value) => typeof value === "boolean";
20901
21648
  var isFunction = (value) => typeof value === "function";
20902
- var set2 = (object2, path28, value) => {
21649
+ var set2 = (object2, path36, value) => {
20903
21650
  let index = -1;
20904
- const tempPath = isKey(path28) ? [path28] : stringToPath(path28);
21651
+ const tempPath = isKey(path36) ? [path36] : stringToPath(path36);
20905
21652
  const length = tempPath.length;
20906
21653
  const lastIndex = length - 1;
20907
21654
  while (++index < length) {
@@ -21099,12 +21846,12 @@ function isEmptyArray(obj) {
21099
21846
  }
21100
21847
  return true;
21101
21848
  }
21102
- function unset(object2, path28) {
21103
- if (isString(path28) && Object.prototype.hasOwnProperty.call(object2, path28)) {
21104
- delete object2[path28];
21849
+ function unset(object2, path36) {
21850
+ if (isString(path36) && Object.prototype.hasOwnProperty.call(object2, path36)) {
21851
+ delete object2[path36];
21105
21852
  return object2;
21106
21853
  }
21107
- const paths = Array.isArray(path28) ? path28 : isKey(path28) ? [path28] : stringToPath(path28);
21854
+ const paths = Array.isArray(path36) ? path36 : isKey(path36) ? [path36] : stringToPath(path36);
21108
21855
  const childObject = paths.length === 1 ? object2 : baseGet(object2, paths);
21109
21856
  const index = paths.length - 1;
21110
21857
  const key = paths[index];
@@ -23950,6 +24697,37 @@ var redeemPromoCodeResultSchema = external_exports.object({
23950
24697
  grantAmount: external_exports.number().int().nonnegative()
23951
24698
  });
23952
24699
 
24700
+ // ../../packages/core/src/vault/vaultSchemaVersion.ts
24701
+ var vaultSchemaVersion = 1;
24702
+
24703
+ // ../../packages/core/src/vault/vaultEntrySchema.ts
24704
+ var vaultEntrySchema = external_exports.object({
24705
+ id: external_exports.string().min(1),
24706
+ title: external_exports.string().default(""),
24707
+ username: external_exports.string().default(""),
24708
+ password: external_exports.string().default(""),
24709
+ url: external_exports.string().optional(),
24710
+ notes: external_exports.string().optional()
24711
+ }).passthrough();
24712
+
24713
+ // ../../packages/core/src/vault/vaultPayloadSchema.ts
24714
+ var vaultPayloadSchema = external_exports.object({
24715
+ version: external_exports.literal(vaultSchemaVersion),
24716
+ entries: external_exports.array(vaultEntrySchema).default([])
24717
+ }).passthrough().superRefine((vault, context) => {
24718
+ const seen = /* @__PURE__ */ new Set();
24719
+ vault.entries.forEach((entry, index) => {
24720
+ if (seen.has(entry.id)) {
24721
+ context.addIssue({
24722
+ code: "custom",
24723
+ message: `Duplicate entry id "${entry.id}".`,
24724
+ path: ["entries", index, "id"]
24725
+ });
24726
+ }
24727
+ seen.add(entry.id);
24728
+ });
24729
+ });
24730
+
23953
24731
  // ../../packages/core/src/structuredFileSchemas.ts
23954
24732
  var structuredSchemaReferenceShape = {
23955
24733
  $schema: external_exports.string().url().optional()
@@ -24831,7 +25609,7 @@ var publicActionSubmitResultSchema = external_exports.unknown();
24831
25609
 
24832
25610
  // ../../packages/core/src/widgetRuntime.ts
24833
25611
  var widgetRuntimeOutputPathSchema = storePathSchema.refine(
24834
- (path28) => path28 !== "/",
25612
+ (path36) => path36 !== "/",
24835
25613
  {
24836
25614
  message: "Path must not be the root directory."
24837
25615
  }
@@ -24881,7 +25659,7 @@ var widgetRuntimeCompleteAttachmentUploadInputSchema = storeRefSchema.safeExtend
24881
25659
  treeVisibility: external_exports.enum(["visible", "hidden"]).optional(),
24882
25660
  uploadIntentId: external_exports.string().trim().min(1)
24883
25661
  });
24884
- var widgetRuntimeLinkPathSchema = external_exports.string().trim().min(1).max(2048).refine((path28) => path28.startsWith("/") && !path28.startsWith("//"), {
25662
+ var widgetRuntimeLinkPathSchema = external_exports.string().trim().min(1).max(2048).refine((path36) => path36.startsWith("/") && !path36.startsWith("//"), {
24885
25663
  message: "Link path must be a relative application path."
24886
25664
  });
24887
25665
  var widgetRuntimeCreateSigningLinkInputSchema = storeRefSchema.safeExtend({
@@ -24991,10 +25769,138 @@ var listOwnCliSessionsInputSchema = external_exports.object({});
24991
25769
  // ../../packages/core/src/cliSessions/revokeCurrentCliSessionInputSchema.ts
24992
25770
  var revokeCurrentCliSessionInputSchema = external_exports.object({});
24993
25771
 
25772
+ // ../../packages/core/src/machineCredentials/machineTokenFormat.ts
25773
+ var machineTokenPrefix = "forum-machine-v1.";
25774
+
25775
+ // ../../packages/core/src/machineCredentials/isMachineToken.ts
25776
+ var isMachineToken = (token) => token.startsWith(machineTokenPrefix);
25777
+
25778
+ // ../../packages/core/src/machineCredentials/machineAccessInputSchemas.ts
25779
+ var machineAccessInputSchemas = {
25780
+ whoami: external_exports.object({}),
25781
+ listFiles: external_exports.object({}),
25782
+ // Address a file by stable id, or by store (UUID or slug in the machine's
25783
+ // workspace) plus path. Either way the grant is checked against the
25784
+ // resolved store UUID and file id, never the name used to find it.
25785
+ readFile: external_exports.union([
25786
+ external_exports.object({ fileId: external_exports.string().trim().min(1) }).strict(),
25787
+ external_exports.object({ store: external_exports.string().trim().min(1), path: storePathSchema }).strict()
25788
+ ])
25789
+ };
25790
+
25791
+ // ../../packages/core/src/machineCredentials/machineAccessOperationSchema.ts
25792
+ var machineAccessOperationSchema = external_exports.enum(["read"]);
25793
+
25794
+ // ../../packages/core/src/machineCredentials/machineCredentialGrantSchema.ts
25795
+ var maxMachineGrantFileIds = 200;
25796
+ var machineCredentialGrantSchema = external_exports.object({
25797
+ storeId: storeUuidSchema,
25798
+ fileIds: external_exports.array(external_exports.string().trim().min(1)).min(1).max(maxMachineGrantFileIds).nullable(),
25799
+ operations: external_exports.array(machineAccessOperationSchema).min(1)
25800
+ });
25801
+
25802
+ // ../../packages/core/src/machineCredentials/machineCredentialPolicy.ts
25803
+ var dayMs = 24 * 60 * 60 * 1e3;
25804
+ var machineCredentialPolicy = {
25805
+ defaultLifetimeDays: 90,
25806
+ maxLifetimeDays: 365,
25807
+ dayMs,
25808
+ lastUsedWriteIntervalMs: 5 * 60 * 1e3
25809
+ };
25810
+
25811
+ // ../../packages/core/src/machineCredentials/machineCredentialNameSchema.ts
25812
+ var machineCredentialNameSchema = external_exports.string().trim().min(1).max(64).regex(
25813
+ /^[a-z0-9][a-z0-9._-]*$/,
25814
+ "Use lowercase letters, digits, dots, hyphens or underscores."
25815
+ );
25816
+
25817
+ // ../../packages/core/src/machineCredentials/machineCredentialRecipientSchema.ts
25818
+ var machineCredentialRecipientSchema = external_exports.object({
25819
+ version: external_exports.literal(3),
25820
+ keyId: encryptionFingerprintSchema,
25821
+ publicKey: publicKeyValueSchema,
25822
+ registeredAt: external_exports.string().datetime()
25823
+ });
25824
+
25825
+ // ../../packages/core/src/machineCredentials/machineCredentialSchema.ts
25826
+ var maxMachineCredentialGrants = 50;
25827
+ var machineCredentialSchema = external_exports.object({
25828
+ id: external_exports.string().uuid(),
25829
+ workspaceId: external_exports.string().trim().min(1),
25830
+ name: machineCredentialNameSchema,
25831
+ createdByUserId: external_exports.string().trim().min(1),
25832
+ createdAt: external_exports.string().datetime(),
25833
+ updatedAt: external_exports.string().datetime(),
25834
+ tokenHash: external_exports.string().regex(/^[0-9a-f]{64}$/),
25835
+ tokenIssuedAt: external_exports.string().datetime(),
25836
+ expiresAt: external_exports.string().datetime(),
25837
+ lastUsedAt: external_exports.string().datetime().nullable().default(null),
25838
+ revokedAt: external_exports.string().datetime().nullable().default(null),
25839
+ revokedByUserId: external_exports.string().trim().min(1).nullable().default(null),
25840
+ grants: external_exports.array(machineCredentialGrantSchema).max(maxMachineCredentialGrants).default([]),
25841
+ recipient: machineCredentialRecipientSchema.nullable().default(null),
25842
+ // Superseded recipient fingerprints, newest last. Ids only, never keys.
25843
+ recipientHistory: external_exports.array(
25844
+ external_exports.object({
25845
+ keyId: encryptionFingerprintSchema,
25846
+ replacedAt: external_exports.string().datetime()
25847
+ })
25848
+ ).max(20).default([])
25849
+ });
25850
+
25851
+ // ../../packages/core/src/machineCredentials/machineGrantInputSchema.ts
25852
+ var machineGrantInputSchema = external_exports.object({
25853
+ store: external_exports.string().trim().min(1),
25854
+ paths: external_exports.array(storePathSchema).max(maxMachineGrantFileIds).optional(),
25855
+ fileIds: external_exports.array(external_exports.string().trim().min(1)).max(maxMachineGrantFileIds).optional(),
25856
+ operations: external_exports.array(machineAccessOperationSchema).min(1).default(["read"])
25857
+ });
25858
+
25859
+ // ../../packages/core/src/machineCredentials/machineRecipientInputSchema.ts
25860
+ var machineRecipientInputSchema = external_exports.object({
25861
+ version: external_exports.literal(3),
25862
+ keyId: encryptionFingerprintSchema,
25863
+ publicKey: publicKeyValueSchema
25864
+ });
25865
+
25866
+ // ../../packages/core/src/machineCredentials/machineCredentialInputSchemas.ts
25867
+ var expiresInDaysSchema = external_exports.number().int().min(1).max(machineCredentialPolicy.maxLifetimeDays);
25868
+ var credentialIdSchema = external_exports.string().uuid();
25869
+ var grantsSchema = external_exports.array(machineGrantInputSchema).max(maxMachineCredentialGrants);
25870
+ var machineCredentialInputSchemas = {
25871
+ create: external_exports.object({
25872
+ name: machineCredentialNameSchema,
25873
+ grants: grantsSchema,
25874
+ expiresInDays: expiresInDaysSchema.optional(),
25875
+ recipient: machineRecipientInputSchema.nullable().default(null)
25876
+ }),
25877
+ list: external_exports.object({ includeInactive: external_exports.boolean().default(false) }),
25878
+ read: external_exports.object({ credentialId: credentialIdSchema }),
25879
+ rotateToken: external_exports.object({
25880
+ credentialId: credentialIdSchema,
25881
+ expiresInDays: expiresInDaysSchema.optional()
25882
+ }),
25883
+ replaceRecipient: external_exports.object({
25884
+ credentialId: credentialIdSchema,
25885
+ // The recipient the caller last saw (null if none), so a concurrent
25886
+ // replacement fails with CONFLICT instead of being silently overwritten.
25887
+ expectedKeyId: encryptionFingerprintSchema.nullable(),
25888
+ recipient: machineRecipientInputSchema
25889
+ }),
25890
+ setGrants: external_exports.object({
25891
+ credentialId: credentialIdSchema,
25892
+ grants: grantsSchema
25893
+ }),
25894
+ revoke: external_exports.object({ credentialId: credentialIdSchema }),
25895
+ readRecipients: external_exports.object({
25896
+ credentialIds: external_exports.array(credentialIdSchema).min(1).max(50)
25897
+ })
25898
+ };
25899
+
24994
25900
  // ../../packages/store-tree/src/patterns.ts
24995
25901
  var escapeRegex2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24996
- var basename2 = (path28) => {
24997
- const segments2 = path28.split("/").filter(Boolean);
25902
+ var basename2 = (path36) => {
25903
+ const segments2 = path36.split("/").filter(Boolean);
24998
25904
  return segments2[segments2.length - 1] ?? "";
24999
25905
  };
25000
25906
  var normalizeStorePathPattern = (pattern) => pattern.trim();
@@ -25012,7 +25918,7 @@ var storePathPatternToRegex = (pattern) => {
25012
25918
  return new RegExp(source, "i");
25013
25919
  };
25014
25920
  var doesStorePathPatternMatch = ({
25015
- path: path28,
25921
+ path: path36,
25016
25922
  pattern,
25017
25923
  mode = "path"
25018
25924
  }) => {
@@ -25020,7 +25926,7 @@ var doesStorePathPatternMatch = ({
25020
25926
  if (!normalizedPattern) {
25021
25927
  return true;
25022
25928
  }
25023
- const normalizedPath = normalizeStorePath(path28);
25929
+ const normalizedPath = normalizeStorePath(path36);
25024
25930
  const target = mode === "basename" ? basename2(normalizedPath) : normalizedPath;
25025
25931
  if (patternHasWildcard(normalizedPattern)) {
25026
25932
  return storePathPatternToRegex(normalizedPattern).test(target);
@@ -25111,8 +26017,8 @@ var isIssueRecord = (value) => {
25111
26017
  return isRecord2(value) && typeof value.message === "string";
25112
26018
  };
25113
26019
  var formatIssue = (issue2) => {
25114
- const path28 = Array.isArray(issue2.path) && issue2.path.length > 0 ? issue2.path.map(String).join(".") : "";
25115
- return path28 ? `${path28}: ${issue2.message}` : issue2.message;
26020
+ const path36 = Array.isArray(issue2.path) && issue2.path.length > 0 ? issue2.path.map(String).join(".") : "";
26021
+ return path36 ? `${path36}: ${issue2.message}` : issue2.message;
25116
26022
  };
25117
26023
  var formatIssueArray = (issues) => {
25118
26024
  if (!issues.every(isIssueRecord)) {
@@ -25416,12 +26322,12 @@ var waitForLoginBrowser = () => new Promise((resolve, reject) => {
25416
26322
 
25417
26323
  // src/auth.ts
25418
26324
  var interactiveLogin = async ({
25419
- apiBaseUrl,
26325
+ apiBaseUrl: apiBaseUrl2,
25420
26326
  timeoutMs = 2 * 60 * 1e3,
25421
26327
  openBrowser = true
25422
26328
  }) => {
25423
26329
  const startResponse = await fetch(
25424
- `${apiBaseUrl.replace(/\/$/, "")}/cli-auth/start`,
26330
+ `${apiBaseUrl2.replace(/\/$/, "")}/cli-auth/start`,
25425
26331
  {
25426
26332
  method: "POST",
25427
26333
  headers: { "Content-Type": "application/json" },
@@ -25450,7 +26356,7 @@ var interactiveLogin = async ({
25450
26356
  while (Date.now() - startedAt < timeoutMs) {
25451
26357
  await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
25452
26358
  const pollResponse = await fetch(
25453
- `${apiBaseUrl.replace(/\/$/, "")}/cli-auth/poll`,
26359
+ `${apiBaseUrl2.replace(/\/$/, "")}/cli-auth/poll`,
25454
26360
  {
25455
26361
  method: "POST",
25456
26362
  headers: { "Content-Type": "application/json" },
@@ -25530,7 +26436,7 @@ var localRenameConflictPatterns = [
25530
26436
  ];
25531
26437
  var readOnlyLocalChangeMessage = "read-only sync requires reverting local tracked changes before pulling remote updates";
25532
26438
  var conflictPaths = (issues, types) => issues.filter((issue2) => types.includes(issue2.details.type)).map((issue2) => issue2.details.details.path).sort((left, right) => left.localeCompare(right));
25533
- var pathSubject = (paths, singular, plural) => paths.length === 1 ? singular(paths[0]) : plural(paths.length);
26439
+ var pathSubject = (paths, singular, plural2) => paths.length === 1 ? singular(paths[0]) : plural2(paths.length);
25534
26440
  var formatPathList = (paths) => {
25535
26441
  if (paths.length <= 3) {
25536
26442
  return paths;
@@ -25586,7 +26492,7 @@ var buildContentChangedConflictExplainer = (issues) => {
25586
26492
  body: [
25587
26493
  pathSubject(
25588
26494
  paths,
25589
- (path28) => `${path28} changed both locally and remotely.`,
26495
+ (path36) => `${path36} changed both locally and remotely.`,
25590
26496
  (count) => `${count} files changed both locally and remotely.`
25591
26497
  ),
25592
26498
  "Forum left these files alone because either overwrite direction could lose work."
@@ -25618,7 +26524,7 @@ var buildLocalDeleteRemoteChangeExplainer = (issues) => {
25618
26524
  body: [
25619
26525
  pathSubject(
25620
26526
  paths,
25621
- (path28) => `${path28} was deleted locally, but the remote file changed.`,
26527
+ (path36) => `${path36} was deleted locally, but the remote file changed.`,
25622
26528
  (count) => `${count} files were deleted locally, but changed remotely.`
25623
26529
  ),
25624
26530
  "Forum did not delete newer remote work automatically."
@@ -25650,7 +26556,7 @@ var buildMoveDestinationConflictExplainer = (issues) => {
25650
26556
  body: [
25651
26557
  pathSubject(
25652
26558
  paths,
25653
- (path28) => `${path28} is the destination of a remote move, but already exists locally.`,
26559
+ (path36) => `${path36} is the destination of a remote move, but already exists locally.`,
25654
26560
  (count) => `${count} paths are remote move destinations that already exist locally.`
25655
26561
  ),
25656
26562
  "Forum synced unrelated files but left these paths alone."
@@ -25685,7 +26591,7 @@ var buildMoveRemoteChangeConflictExplainer = (issues) => {
25685
26591
  body: [
25686
26592
  pathSubject(
25687
26593
  paths,
25688
- (path28) => `${path28} was involved in a move while the other side changed it.`,
26594
+ (path36) => `${path36} was involved in a move while the other side changed it.`,
25689
26595
  (count) => `${count} files were involved in moves while the other side changed them.`
25690
26596
  ),
25691
26597
  "Forum did not combine the move and content change automatically."
@@ -25717,7 +26623,7 @@ var buildMoveMoveConflictExplainer = (issues) => {
25717
26623
  body: [
25718
26624
  pathSubject(
25719
26625
  paths,
25720
- (path28) => `${path28} moved locally and remotely to different paths.`,
26626
+ (path36) => `${path36} moved locally and remotely to different paths.`,
25721
26627
  (count) => `${count} files moved locally and remotely to different paths.`
25722
26628
  ),
25723
26629
  "Forum left these moves unresolved because choosing a path automatically could hide work."
@@ -25749,7 +26655,7 @@ var buildDeleteMoveConflictExplainer = (issues) => {
25749
26655
  body: [
25750
26656
  pathSubject(
25751
26657
  paths,
25752
- (path28) => `${path28} was deleted on one side and moved on the other.`,
26658
+ (path36) => `${path36} was deleted on one side and moved on the other.`,
25753
26659
  (count) => `${count} files were deleted on one side and moved on the other.`
25754
26660
  ),
25755
26661
  "Forum did not choose between delete and move automatically."
@@ -25781,7 +26687,7 @@ var buildReferenceLocalFileConflictExplainer = (issues) => {
25781
26687
  body: [
25782
26688
  pathSubject(
25783
26689
  paths,
25784
- (path28) => `${path28} is now a remote reference, but the local file has changes.`,
26690
+ (path36) => `${path36} is now a remote reference, but the local file has changes.`,
25785
26691
  (count) => `${count} paths are now remote references, but local files have changes.`
25786
26692
  ),
25787
26693
  "Forum left the local files alone because replacing them would discard local work."
@@ -25813,7 +26719,7 @@ var buildUnsupportedLocalEntryExplainer = (issues) => {
25813
26719
  body: [
25814
26720
  pathSubject(
25815
26721
  paths,
25816
- (path28) => `${path28} is an unsupported local filesystem entry.`,
26722
+ (path36) => `${path36} is an unsupported local filesystem entry.`,
25817
26723
  (count) => `${count} local filesystem entries are unsupported.`
25818
26724
  ),
25819
26725
  "Forum skipped these paths and continued with unrelated files where it could."
@@ -25845,7 +26751,7 @@ var buildReadOnlyLocalChangeExplainer = (issues) => {
25845
26751
  body: [
25846
26752
  pathSubject(
25847
26753
  paths,
25848
- (path28) => `${path28} has local changes, but its sync rule is read-only.`,
26754
+ (path36) => `${path36} has local changes, but its sync rule is read-only.`,
25849
26755
  (count) => `${count} files have local changes, but their sync rules are read-only.`
25850
26756
  ),
25851
26757
  "Forum left these files alone so remote updates cannot overwrite local work."
@@ -25942,7 +26848,7 @@ var checkoutConflictIssuesFromResult = (result) => checkoutIssuesFromResult(resu
25942
26848
  (issue2) => issue2.type === "conflict"
25943
26849
  );
25944
26850
  var formatCheckoutExplainer = (explainer) => {
25945
- const pathLines = explainer.paths.length <= 1 ? [] : ["", ...formatPathList(explainer.paths).map((path28) => ` ${path28}`)];
26851
+ const pathLines = explainer.paths.length <= 1 ? [] : ["", ...formatPathList(explainer.paths).map((path36) => ` ${path36}`)];
25946
26852
  const actionLines = explainer.actions.map(
25947
26853
  (action) => `${styleText.bold(`${action.label}:`)} ${action.text}`
25948
26854
  );
@@ -26132,19 +27038,19 @@ import { TextDecoder as TextDecoder2 } from "util";
26132
27038
  import ignore2 from "ignore";
26133
27039
 
26134
27040
  // src/buildCheckoutFileManifestEntry.ts
26135
- var toManifestRemotePath = (path28) => path28.startsWith("/") ? path28 : `/${path28}`;
27041
+ var toManifestRemotePath = (path36) => path36.startsWith("/") ? path36 : `/${path36}`;
26136
27042
  var buildCheckoutFileManifestEntry = ({
26137
27043
  storageClass,
26138
27044
  hash: hash2,
26139
27045
  manifestEntry,
26140
- path: path28,
27046
+ path: path36,
26141
27047
  remoteFile,
26142
27048
  source,
26143
27049
  syncedAt
26144
27050
  }) => {
26145
27051
  const remoteFileId = remoteFile.id ?? remoteFile._id ?? manifestEntry?.remoteFileId;
26146
27052
  if (!remoteFileId) {
26147
- throw new Error(`Remote file ${path28} did not include a file id`);
27053
+ throw new Error(`Remote file ${path36} did not include a file id`);
26148
27054
  }
26149
27055
  return {
26150
27056
  storageClass,
@@ -26152,7 +27058,7 @@ var buildCheckoutFileManifestEntry = ({
26152
27058
  isExecutable: storageClass === "text" ? remoteFile.isExecutable === true || void 0 : void 0,
26153
27059
  lastSyncedAt: syncedAt,
26154
27060
  remoteFileId,
26155
- remotePath: remoteFile.path ?? manifestEntry?.remotePath ?? toManifestRemotePath(path28),
27061
+ remotePath: remoteFile.path ?? manifestEntry?.remotePath ?? toManifestRemotePath(path36),
26156
27062
  remoteUpdatedAt: remoteFile.updatedAt ?? null,
26157
27063
  remoteRevisionNumber: remoteFile.revisionNumber ?? null,
26158
27064
  ...source ? { source } : {}
@@ -28917,16 +29823,16 @@ var updateFileManifestEntry = ({
28917
29823
  hash: hash2,
28918
29824
  manifest,
28919
29825
  manifestEntry,
28920
- path: path28,
29826
+ path: path36,
28921
29827
  remoteFile,
28922
29828
  source,
28923
29829
  syncedAt
28924
29830
  }) => {
28925
- manifest.files[path28] = buildCheckoutFileManifestEntry({
29831
+ manifest.files[path36] = buildCheckoutFileManifestEntry({
28926
29832
  storageClass,
28927
29833
  hash: hash2,
28928
29834
  manifestEntry,
28929
- path: path28,
29835
+ path: path36,
28930
29836
  remoteFile,
28931
29837
  source,
28932
29838
  syncedAt
@@ -30407,7 +31313,7 @@ var remoteFileHash = async ({
30407
31313
  client,
30408
31314
  remoteFile,
30409
31315
  storeRef,
30410
- path: path28
31316
+ path: path36
30411
31317
  }) => {
30412
31318
  const textHash = remoteTextHash(remoteFile);
30413
31319
  if (textHash) {
@@ -30418,7 +31324,7 @@ var remoteFileHash = async ({
30418
31324
  }
30419
31325
  const { downloadUrl } = await client.createFileDownloadUrlByRef({
30420
31326
  ...storeRef,
30421
- path: path28
31327
+ path: path36
30422
31328
  });
30423
31329
  const response = await fetch(downloadUrl);
30424
31330
  if (!response.ok) {
@@ -31845,9 +32751,9 @@ var createHumanWatchSubscriber = ({
31845
32751
  return;
31846
32752
  }
31847
32753
  case "sync.watch.conflict.raised": {
31848
- const path28 = String(details.path ?? "");
32754
+ const path36 = String(details.path ?? "");
31849
32755
  const suggestions = details.suggestions ?? [];
31850
- error51(`Conflict: ${path28} \u2014 ${event.message ?? "needs attention"}`);
32756
+ error51(`Conflict: ${path36} \u2014 ${event.message ?? "needs attention"}`);
31851
32757
  if (suggestions.length > 0) {
31852
32758
  error51(` ${formatSuggestions(suggestions)}`);
31853
32759
  }
@@ -31876,10 +32782,10 @@ import notifier from "node-notifier";
31876
32782
  var createNotifyWatchSubscriber = () => {
31877
32783
  return (event) => {
31878
32784
  if (event.eventType === "sync.watch.conflict.raised") {
31879
- const path28 = event.details?.path;
32785
+ const path36 = event.details?.path;
31880
32786
  notifier.notify({
31881
32787
  title: "Forum sync conflict",
31882
- message: typeof path28 === "string" ? `${path28} needs attention` : event.message ?? "A file needs attention"
32788
+ message: typeof path36 === "string" ? `${path36} needs attention` : event.message ?? "A file needs attention"
31883
32789
  });
31884
32790
  return;
31885
32791
  }
@@ -31995,10 +32901,10 @@ var createConflictTracker = () => {
31995
32901
  );
31996
32902
  const raised = current.filter((conflict) => !active.has(conflict.path));
31997
32903
  const cleared = [...active.keys()].filter(
31998
- (path28) => !currentByPath.has(path28)
32904
+ (path36) => !currentByPath.has(path36)
31999
32905
  );
32000
- for (const path28 of cleared) {
32001
- active.delete(path28);
32906
+ for (const path36 of cleared) {
32907
+ active.delete(path36);
32002
32908
  }
32003
32909
  for (const conflict of current) {
32004
32910
  active.set(conflict.path, conflict);
@@ -32009,13 +32915,13 @@ var createConflictTracker = () => {
32009
32915
  };
32010
32916
 
32011
32917
  // src/watch/conflictResolutionHints.ts
32012
- var keepLocal = (path28) => ({
32918
+ var keepLocal = (path36) => ({
32013
32919
  label: "Keep local",
32014
- command: `fm push --force ${path28}`
32920
+ command: `fm push --force ${path36}`
32015
32921
  });
32016
- var acceptRemote = (path28) => ({
32922
+ var acceptRemote = (path36) => ({
32017
32923
  label: "Accept remote",
32018
- command: `fm pull --force ${path28}`
32924
+ command: `fm pull --force ${path36}`
32019
32925
  });
32020
32926
  var review = (label, command) => ({
32021
32927
  label,
@@ -32031,23 +32937,23 @@ var forceResolvableTypes = /* @__PURE__ */ new Set([
32031
32937
  "reference-local-file",
32032
32938
  "read-only-local-change"
32033
32939
  ]);
32034
- var conflictResolutionSuggestions = (conflictType, path28) => {
32940
+ var conflictResolutionSuggestions = (conflictType, path36) => {
32035
32941
  if (forceResolvableTypes.has(conflictType)) {
32036
- return [keepLocal(path28), acceptRemote(path28)];
32942
+ return [keepLocal(path36), acceptRemote(path36)];
32037
32943
  }
32038
- return [review("Review", `fm status ${path28}`)];
32944
+ return [review("Review", `fm status ${path36}`)];
32039
32945
  };
32040
32946
 
32041
32947
  // src/watch/extractWatchConflicts.ts
32042
32948
  var toWatchConflict = (issue2) => {
32043
- const { path: path28, message, relatedPaths } = issue2.details.details;
32949
+ const { path: path36, message, relatedPaths } = issue2.details.details;
32044
32950
  const conflictType = issue2.details.type;
32045
32951
  return {
32046
- path: path28,
32952
+ path: path36,
32047
32953
  conflictType,
32048
32954
  message,
32049
32955
  relatedPaths: relatedPaths ?? [],
32050
- suggestions: conflictResolutionSuggestions(conflictType, path28)
32956
+ suggestions: conflictResolutionSuggestions(conflictType, path36)
32051
32957
  };
32052
32958
  };
32053
32959
  var extractWatchConflicts = (result) => {
@@ -32138,9 +33044,9 @@ var createCheckoutWatcher = ({
32138
33044
  })
32139
33045
  );
32140
33046
  }
32141
- for (const path28 of cleared) {
33047
+ for (const path36 of cleared) {
32142
33048
  bus.emit(
32143
- watchEvent("sync.watch.conflict.cleared", void 0, { path: path28 })
33049
+ watchEvent("sync.watch.conflict.cleared", void 0, { path: path36 })
32144
33050
  );
32145
33051
  }
32146
33052
  bus.emit(
@@ -32711,6 +33617,12 @@ var retrySafeOperations = /* @__PURE__ */ new Set([
32711
33617
  "stores.list",
32712
33618
  "stores.readByRef",
32713
33619
  "cliSessions.list",
33620
+ "machineAccess.listFiles",
33621
+ "machineAccess.readFile",
33622
+ "machineAccess.whoami",
33623
+ "machineCredentials.list",
33624
+ "machineCredentials.read",
33625
+ "machineCredentials.readRecipients",
32714
33626
  "userPreferences.read",
32715
33627
  "files.listDirectory",
32716
33628
  "files.listDirectoryByRef",
@@ -32789,14 +33701,14 @@ var fetchWithReadableErrors = async (input, init) => {
32789
33701
  return response;
32790
33702
  };
32791
33703
  var createStoreClient = ({
32792
- apiBaseUrl,
33704
+ apiBaseUrl: apiBaseUrl2,
32793
33705
  getToken,
32794
33706
  transientRetryDelayMs = defaultTransientRetryDelayMs
32795
33707
  }) => {
32796
33708
  const trpc = createTRPCProxyClient({
32797
33709
  links: [
32798
33710
  httpBatchLink({
32799
- url: `${apiBaseUrl}/trpc`,
33711
+ url: `${apiBaseUrl2}/trpc`,
32800
33712
  transformer: superjson,
32801
33713
  fetch: fetchWithReadableErrors,
32802
33714
  headers: async () => {
@@ -32815,7 +33727,7 @@ var createStoreClient = ({
32815
33727
  { retryDelayMs: transientRetryDelayMs }
32816
33728
  );
32817
33729
  return {
32818
- createRawFileUrl: (fileId) => `${apiBaseUrl.replace(/\/+$/, "")}/raw-file/${encodeURIComponent(fileId)}`,
33730
+ createRawFileUrl: (fileId) => `${apiBaseUrl2.replace(/\/+$/, "")}/raw-file/${encodeURIComponent(fileId)}`,
32819
33731
  listStores: (input = {}) => call("stores.list", () => trpc.stores.list.query(input)),
32820
33732
  createStore: (input) => call("stores.create", () => trpc.stores.create.mutate(input)),
32821
33733
  deleteStore: (input) => call("stores.delete", () => trpc.stores.delete.mutate(input)),
@@ -32838,6 +33750,47 @@ var createStoreClient = ({
32838
33750
  "cliSessions.revokeCurrent",
32839
33751
  () => trpc.cliSessions.revokeCurrent.mutate({})
32840
33752
  ),
33753
+ createMachineCredential: (input) => call(
33754
+ "machineCredentials.create",
33755
+ () => trpc.machineCredentials.create.mutate(input)
33756
+ ),
33757
+ listMachineCredentials: (input = {}) => call(
33758
+ "machineCredentials.list",
33759
+ () => trpc.machineCredentials.list.query(input)
33760
+ ),
33761
+ readMachineCredential: (input) => call(
33762
+ "machineCredentials.read",
33763
+ () => trpc.machineCredentials.read.query(input)
33764
+ ),
33765
+ rotateMachineCredentialToken: (input) => call(
33766
+ "machineCredentials.rotateToken",
33767
+ () => trpc.machineCredentials.rotateToken.mutate(input)
33768
+ ),
33769
+ replaceMachineCredentialRecipient: (input) => call(
33770
+ "machineCredentials.replaceRecipient",
33771
+ () => trpc.machineCredentials.replaceRecipient.mutate(input)
33772
+ ),
33773
+ setMachineCredentialGrants: (input) => call(
33774
+ "machineCredentials.setGrants",
33775
+ () => trpc.machineCredentials.setGrants.mutate(input)
33776
+ ),
33777
+ revokeMachineCredential: (input) => call(
33778
+ "machineCredentials.revoke",
33779
+ () => trpc.machineCredentials.revoke.mutate(input)
33780
+ ),
33781
+ readMachineRecipients: (input) => call(
33782
+ "machineCredentials.readRecipients",
33783
+ () => trpc.machineCredentials.readRecipients.query(input)
33784
+ ),
33785
+ machineWhoami: () => call("machineAccess.whoami", () => trpc.machineAccess.whoami.query({})),
33786
+ listMachineFiles: () => call(
33787
+ "machineAccess.listFiles",
33788
+ () => trpc.machineAccess.listFiles.query({})
33789
+ ),
33790
+ readMachineFile: (input) => call(
33791
+ "machineAccess.readFile",
33792
+ () => trpc.machineAccess.readFile.query(input)
33793
+ ),
32841
33794
  readUserPreferences: () => call("userPreferences.read", () => trpc.userPreferences.read.query({})),
32842
33795
  readPublicEncryptionKeys: (input) => call(
32843
33796
  "userPreferences.readPublicEncryptionKeys",
@@ -33406,9 +34359,9 @@ import path21 from "path";
33406
34359
  var createSkillClient = async (options2) => {
33407
34360
  const stateDir = options2.stateDir ? path21.resolve(options2.stateDir) : defaultStateDir();
33408
34361
  const saved = await readConfig(stateDir);
33409
- const apiBaseUrl = (process.env.DOCTRINE_API_URL || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
34362
+ const apiBaseUrl2 = (process.env.DOCTRINE_API_URL || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
33410
34363
  const token = options2.token || process.env.DOCTRINE_TOKEN || saved.token;
33411
- return { client: createClient({ apiBaseUrl, token }), apiBaseUrl };
34364
+ return { client: createClient({ apiBaseUrl: apiBaseUrl2, token }), apiBaseUrl: apiBaseUrl2 };
33412
34365
  };
33413
34366
 
33414
34367
  // src/skills/skillConnectionOptions.ts
@@ -33747,9 +34700,9 @@ var loadSkillStubs = async (input) => {
33747
34700
  return {
33748
34701
  dryRun: input.dryRun,
33749
34702
  source: input.source,
33750
- changes: changes.map(({ agent, path: path28, slug, action }) => ({
34703
+ changes: changes.map(({ agent, path: path36, slug, action }) => ({
33751
34704
  agent,
33752
- path: path28,
34705
+ path: path36,
33753
34706
  slug,
33754
34707
  action
33755
34708
  }))
@@ -33849,7 +34802,7 @@ var loadSkillsCommand = async (folder, _options, command) => {
33849
34802
  throw new Error(
33850
34803
  "Interactive setup needs a terminal. Supply a folder and --store for non-interactive use."
33851
34804
  );
33852
- const { client, apiBaseUrl } = await createSkillClient(options2);
34805
+ const { client, apiBaseUrl: apiBaseUrl2 } = await createSkillClient(options2);
33853
34806
  if (options2.interactive)
33854
34807
  options2 = await promptSkillConnection(client, options2);
33855
34808
  if (!options2.store || options2.folder === void 0)
@@ -33861,7 +34814,7 @@ var loadSkillsCommand = async (folder, _options, command) => {
33861
34814
  folder: options2.folder
33862
34815
  });
33863
34816
  const result = await connectSkillCollection(collection, {
33864
- apiBaseUrl,
34817
+ apiBaseUrl: apiBaseUrl2,
33865
34818
  agents: options2.agents ?? ["codex", "claude"],
33866
34819
  directory: process.cwd(),
33867
34820
  home: os2.homedir(),
@@ -33951,6 +34904,589 @@ var runSkillsCommand = async (argv) => {
33951
34904
  }
33952
34905
  };
33953
34906
 
34907
+ // src/machine/runMachineCommand.ts
34908
+ import { CommanderError as CommanderError2 } from "commander";
34909
+
34910
+ // src/machine/createMachineCommand.ts
34911
+ import { Command as Command2, InvalidArgumentError as InvalidArgumentError2 } from "commander";
34912
+
34913
+ // src/machine/createMachineCommandClient.ts
34914
+ import path26 from "path";
34915
+ var machineTokenEnvVar = "FORUM_MACHINE_TOKEN";
34916
+ var apiBaseUrl = () => (process.env.DOCTRINE_API_URL || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
34917
+ var createMachineAdminClient = async (options2) => {
34918
+ const stateDir = options2.stateDir ? path26.resolve(options2.stateDir) : defaultStateDir();
34919
+ const token = options2.token || process.env.DOCTRINE_TOKEN || (await readConfig(stateDir)).token;
34920
+ registerRedactedSecret(token);
34921
+ if (token && isMachineToken(token)) {
34922
+ throw new Error(
34923
+ "Machine tokens cannot manage machine credentials. Sign in with fm auth login."
34924
+ );
34925
+ }
34926
+ return createClient({ apiBaseUrl: apiBaseUrl(), token: token ?? null });
34927
+ };
34928
+ var createMachineTokenClient = (options2) => {
34929
+ const token = options2.token || process.env[machineTokenEnvVar];
34930
+ registerRedactedSecret(token);
34931
+ if (!token || !isMachineToken(token)) {
34932
+ throw new Error(
34933
+ `A machine token is required. Set ${machineTokenEnvVar} (or pass --token) to a forum-machine-v1 token from fm machine create.`
34934
+ );
34935
+ }
34936
+ return createClient({ apiBaseUrl: apiBaseUrl(), token });
34937
+ };
34938
+
34939
+ // src/machine/describeMachineGrants.ts
34940
+ var describeMachineGrants = (grants) => grants.length ? grants.map(
34941
+ (grant) => ` store ${grant.storeId}: ${grant.fileIds === null ? "every file" : `files ${grant.fileIds.join(", ")}`} (${grant.operations.join(", ")})`
34942
+ ) : [" (no grants)"];
34943
+
34944
+ // src/machine/describeMachineCredential.ts
34945
+ var describeMachineCredential = (credential) => [
34946
+ `${credential.name} (${credential.id}) \u2014 ${credential.status}`,
34947
+ ` token issued ${credential.tokenIssuedAt}, expires ${credential.expiresAt}`,
34948
+ ` last used ${credential.lastUsedAt ?? "never"}`,
34949
+ ...credential.revokedAt ? [` revoked ${credential.revokedAt}`] : [],
34950
+ ` recipient ${credential.recipient ? formatEncryptionFingerprint(credential.recipient.keyId) : "none"}`,
34951
+ " grants:",
34952
+ ...describeMachineGrants(credential.grants).map((line) => ` ${line}`)
34953
+ ].join("\n");
34954
+
34955
+ // src/machine/emitIssuedSecrets.ts
34956
+ import path27 from "path";
34957
+
34958
+ // src/machine/machineKeyEnvVar.ts
34959
+ var machineKeyEnvVar = "FORUM_MACHINE_KEY";
34960
+
34961
+ // src/machine/writeSecretFile.ts
34962
+ import { writeFile as writeFile5 } from "fs/promises";
34963
+ var writeSecretFile = async (filePath, secret) => {
34964
+ await writeFile5(filePath, `${secret}
34965
+ `, { flag: "wx", mode: 384 });
34966
+ };
34967
+
34968
+ // src/machine/emitIssuedSecrets.ts
34969
+ var emitIssuedSecrets = async ({
34970
+ keyFile,
34971
+ machineKey,
34972
+ token,
34973
+ tokenFile
34974
+ }) => {
34975
+ const secrets = [
34976
+ { env: machineTokenEnvVar, file: tokenFile, value: token },
34977
+ { env: machineKeyEnvVar, file: keyFile, value: machineKey }
34978
+ ];
34979
+ const printed = {};
34980
+ const written = {};
34981
+ for (const secret of secrets) {
34982
+ if (!secret.value) continue;
34983
+ if (secret.file) {
34984
+ const filePath = path27.resolve(secret.file);
34985
+ await writeSecretFile(filePath, secret.value);
34986
+ written[secret.env] = filePath;
34987
+ } else {
34988
+ printed[secret.env] = secret.value;
34989
+ }
34990
+ }
34991
+ return { printed, written };
34992
+ };
34993
+
34994
+ // src/machine/parseMachineGrantSpec.ts
34995
+ var parseMachineGrantSpec = (value) => {
34996
+ const separator = value.indexOf(":");
34997
+ const store = (separator === -1 ? value : value.slice(0, separator)).trim();
34998
+ const path36 = separator === -1 ? "" : value.slice(separator + 1).trim();
34999
+ if (!store) {
35000
+ throw new Error(
35001
+ `Invalid --grant "${value}". Use <store> or <store>:<path>.`
35002
+ );
35003
+ }
35004
+ if (separator === -1) return { store };
35005
+ if (!path36.startsWith("/")) {
35006
+ throw new Error(
35007
+ `Invalid --grant "${value}". File paths start with /, for example ${store}:/prod.env.enc.`
35008
+ );
35009
+ }
35010
+ return { paths: [path36], store };
35011
+ };
35012
+
35013
+ // src/machine/provisionMachineCredential.ts
35014
+ var provisionMachineCredential = async ({
35015
+ client,
35016
+ expiresInDays,
35017
+ grants,
35018
+ name,
35019
+ withRecipient
35020
+ }) => {
35021
+ const key = withRecipient ? await createMachineEncryptionKey() : null;
35022
+ const issued = await client.createMachineCredential({
35023
+ ...expiresInDays === void 0 ? {} : { expiresInDays },
35024
+ grants,
35025
+ name,
35026
+ recipient: key?.recipient ?? null
35027
+ });
35028
+ return { ...issued, machineKey: key?.secret ?? null };
35029
+ };
35030
+
35031
+ // src/machine/renderIssuedSecrets.ts
35032
+ var renderIssuedSecrets = (secrets) => {
35033
+ for (const [env, filePath] of Object.entries(secrets.written)) {
35034
+ renderWarning(`${env} written to ${filePath} (mode 600).`);
35035
+ }
35036
+ const printed = Object.entries(secrets.printed);
35037
+ if (!printed.length) return;
35038
+ renderWarning(
35039
+ "Shown once \u2014 store each as its own CI secret. The key is only needed to decrypt; the token only to fetch:"
35040
+ );
35041
+ renderOutput(printed.map(([env, value]) => `${env}=${value}`).join("\n"));
35042
+ };
35043
+
35044
+ // src/machine/runMachineCreate.ts
35045
+ var runMachineCreate = async (name, _options, command) => {
35046
+ const options2 = command.optsWithGlobals();
35047
+ configureRenderer({ json: Boolean(options2.json) });
35048
+ const provisioned = await provisionMachineCredential({
35049
+ client: await createMachineAdminClient(options2),
35050
+ expiresInDays: options2.expiresInDays,
35051
+ grants: (options2.grant ?? []).map(parseMachineGrantSpec),
35052
+ name,
35053
+ withRecipient: options2.recipient !== false
35054
+ });
35055
+ const secrets = await emitIssuedSecrets({
35056
+ keyFile: options2.keyFile,
35057
+ machineKey: provisioned.machineKey,
35058
+ token: provisioned.token,
35059
+ tokenFile: options2.tokenFile
35060
+ });
35061
+ if (options2.json) {
35062
+ renderOutput({
35063
+ cappedByCliSession: provisioned.cappedByCliSession,
35064
+ credential: provisioned.credential,
35065
+ secrets: secrets.printed,
35066
+ writtenSecretFiles: secrets.written
35067
+ });
35068
+ return;
35069
+ }
35070
+ renderWarning(describeMachineCredential(provisioned.credential));
35071
+ if (provisioned.cappedByCliSession) {
35072
+ renderWarning(
35073
+ "The token expires with your CLI session. Create it from a fresh login, or rotate it later, for a longer lifetime."
35074
+ );
35075
+ }
35076
+ if (provisioned.credential.recipient) {
35077
+ renderWarning(
35078
+ `Machine key fingerprint (record it; pass it as --fingerprint when granting files): ${formatEncryptionFingerprint(provisioned.credential.recipient.keyId)}`
35079
+ );
35080
+ }
35081
+ renderIssuedSecrets(secrets);
35082
+ };
35083
+
35084
+ // src/machine/resolveMachineCredentialRefs.ts
35085
+ var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35086
+ var resolveMachineCredentialRefs = async ({
35087
+ client,
35088
+ refs
35089
+ }) => {
35090
+ const names = refs.filter((ref) => !uuidPattern.test(ref));
35091
+ const credentials = names.length ? await client.listMachineCredentials({ includeInactive: false }) : [];
35092
+ return refs.map((ref) => {
35093
+ if (uuidPattern.test(ref)) return ref.toLowerCase();
35094
+ const match = credentials.find((credential) => credential.name === ref);
35095
+ if (!match) {
35096
+ throw new Error(`No active machine credential is named "${ref}".`);
35097
+ }
35098
+ return match.id;
35099
+ });
35100
+ };
35101
+
35102
+ // src/machine/runMachineCredentialAction.ts
35103
+ var runMachineCredentialAction = (act) => async (ref, _options, command) => {
35104
+ const options2 = command.optsWithGlobals();
35105
+ configureRenderer({ json: Boolean(options2.json) });
35106
+ const client = await createMachineAdminClient(options2);
35107
+ const [credentialId] = await resolveMachineCredentialRefs({
35108
+ client,
35109
+ refs: [ref]
35110
+ });
35111
+ const credential = await act({
35112
+ client,
35113
+ credentialId,
35114
+ options: options2
35115
+ });
35116
+ renderOutput(
35117
+ options2.json ? credential : describeMachineCredential(credential)
35118
+ );
35119
+ };
35120
+
35121
+ // src/machine/runMachineFetch.ts
35122
+ import path28 from "path";
35123
+
35124
+ // src/machine/fetchMachineFile.ts
35125
+ var fetchMachineFile = async ({
35126
+ client,
35127
+ outputPath,
35128
+ ref
35129
+ }) => {
35130
+ const file2 = await client.readMachineFile(ref);
35131
+ if (outputPath) await atomicWriteTextFile(outputPath, file2.text);
35132
+ return file2;
35133
+ };
35134
+
35135
+ // src/machine/parseMachineFileRef.ts
35136
+ var parseMachineFileRef = ({
35137
+ fileId,
35138
+ path: path36,
35139
+ store
35140
+ }) => {
35141
+ if (fileId && !store && !path36) return { fileId };
35142
+ if (!fileId && store && path36) return { path: path36, store };
35143
+ throw new Error(
35144
+ "Pass either --file-id <id>, or --store <store> --path <path>."
35145
+ );
35146
+ };
35147
+
35148
+ // src/machine/runMachineFetch.ts
35149
+ var runMachineFetch = async (_options, command) => {
35150
+ const options2 = command.optsWithGlobals();
35151
+ configureRenderer({ json: Boolean(options2.json) });
35152
+ const outputPath = options2.output ? path28.resolve(options2.output) : null;
35153
+ const file2 = await fetchMachineFile({
35154
+ client: createMachineTokenClient(options2),
35155
+ outputPath,
35156
+ ref: parseMachineFileRef(options2)
35157
+ });
35158
+ if (options2.json) {
35159
+ const { text, ...metadata } = file2;
35160
+ renderOutput(
35161
+ outputPath ? { ...metadata, outputPath } : { ...metadata, text }
35162
+ );
35163
+ return;
35164
+ }
35165
+ if (!outputPath) {
35166
+ renderOutput(file2.text);
35167
+ return;
35168
+ }
35169
+ renderWarning(
35170
+ `Wrote ${file2.storeSlug}:${file2.path} (revision ${file2.revisionNumber}) to ${outputPath}.${file2.encrypted ? " It is still encrypted: decrypt with fm decrypt --file and FORUM_MACHINE_KEY (no token needed)." : ""}`
35171
+ );
35172
+ };
35173
+
35174
+ // src/machine/runMachineFiles.ts
35175
+ var runMachineFiles = async (_options, command) => {
35176
+ const options2 = command.optsWithGlobals();
35177
+ configureRenderer({ json: Boolean(options2.json) });
35178
+ const files = await createMachineTokenClient(options2).listMachineFiles();
35179
+ renderOutput(
35180
+ options2.json ? files : files.length ? files.map((file2) => `${file2.storeSlug}:${file2.path} ${file2.fileId}`).join("\n") : "No granted files."
35181
+ );
35182
+ };
35183
+
35184
+ // src/machine/runMachineList.ts
35185
+ var runMachineList = async (_options, command) => {
35186
+ const options2 = command.optsWithGlobals();
35187
+ configureRenderer({ json: Boolean(options2.json) });
35188
+ const credentials = await (await createMachineAdminClient(options2)).listMachineCredentials({ includeInactive: Boolean(options2.all) });
35189
+ renderOutput(
35190
+ options2.json ? credentials : credentials.length ? credentials.map(describeMachineCredential).join("\n\n") : "No machine credentials."
35191
+ );
35192
+ };
35193
+
35194
+ // src/machine/replaceMachineKey.ts
35195
+ var replaceMachineKey = async ({
35196
+ client,
35197
+ credentialId
35198
+ }) => {
35199
+ const current = await client.readMachineCredential({ credentialId });
35200
+ const key = await createMachineEncryptionKey();
35201
+ const credential = await client.replaceMachineCredentialRecipient({
35202
+ credentialId,
35203
+ expectedKeyId: current.recipient?.keyId ?? null,
35204
+ recipient: key.recipient
35205
+ });
35206
+ return {
35207
+ credential,
35208
+ machineKey: key.secret,
35209
+ previousKeyId: current.recipient?.keyId ?? null
35210
+ };
35211
+ };
35212
+
35213
+ // src/machine/runMachineReplaceKey.ts
35214
+ var runMachineReplaceKey = async (ref, _options, command) => {
35215
+ const options2 = command.optsWithGlobals();
35216
+ configureRenderer({ json: Boolean(options2.json) });
35217
+ const client = await createMachineAdminClient(options2);
35218
+ const [credentialId] = await resolveMachineCredentialRefs({
35219
+ client,
35220
+ refs: [ref]
35221
+ });
35222
+ const replaced = await replaceMachineKey({
35223
+ client,
35224
+ credentialId
35225
+ });
35226
+ const secrets = await emitIssuedSecrets({
35227
+ keyFile: options2.keyFile,
35228
+ machineKey: replaced.machineKey,
35229
+ token: null
35230
+ });
35231
+ if (options2.json) {
35232
+ renderOutput({
35233
+ credential: replaced.credential,
35234
+ previousKeyId: replaced.previousKeyId,
35235
+ secrets: secrets.printed,
35236
+ writtenSecretFiles: secrets.written
35237
+ });
35238
+ return;
35239
+ }
35240
+ renderWarning(
35241
+ `New machine key fingerprint: ${formatEncryptionFingerprint(replaced.credential.recipient.keyId)}`
35242
+ );
35243
+ renderWarning(
35244
+ [
35245
+ "No file changed yet. For each file granted to this machine, rekey it so the old key cannot read new versions and the new key can:",
35246
+ ` fm encrypt-rekey --file <file> --remove ${replaced.previousKeyId ?? "<old-recipient>"} --grant-machine ${replaced.credential.id}`,
35247
+ "Copies saved before the rekey (snapshots, backups, history) stay readable with the old key."
35248
+ ].join("\n")
35249
+ );
35250
+ renderIssuedSecrets(secrets);
35251
+ };
35252
+
35253
+ // src/machine/runMachineRotateToken.ts
35254
+ var runMachineRotateToken = async (ref, _options, command) => {
35255
+ const options2 = command.optsWithGlobals();
35256
+ configureRenderer({ json: Boolean(options2.json) });
35257
+ const client = await createMachineAdminClient(options2);
35258
+ const [credentialId] = await resolveMachineCredentialRefs({
35259
+ client,
35260
+ refs: [ref]
35261
+ });
35262
+ const rotated = await client.rotateMachineCredentialToken({
35263
+ credentialId,
35264
+ ...options2.expiresInDays === void 0 ? {} : { expiresInDays: options2.expiresInDays }
35265
+ });
35266
+ const secrets = await emitIssuedSecrets({
35267
+ machineKey: null,
35268
+ token: rotated.token,
35269
+ tokenFile: options2.tokenFile
35270
+ });
35271
+ if (options2.json) {
35272
+ renderOutput({
35273
+ cappedByCliSession: rotated.cappedByCliSession,
35274
+ credential: rotated.credential,
35275
+ secrets: secrets.printed,
35276
+ writtenSecretFiles: secrets.written
35277
+ });
35278
+ return;
35279
+ }
35280
+ renderWarning(describeMachineCredential(rotated.credential));
35281
+ renderWarning(
35282
+ "The previous token no longer works. The machine key is unchanged."
35283
+ );
35284
+ renderIssuedSecrets(secrets);
35285
+ };
35286
+
35287
+ // src/machine/createMachineCommand.ts
35288
+ var collect = (value, previous = []) => [
35289
+ ...previous,
35290
+ value
35291
+ ];
35292
+ var parseDays = (value) => {
35293
+ const days = Number(value);
35294
+ if (!Number.isInteger(days) || days < 1) {
35295
+ throw new InvalidArgumentError2("Expected a whole number of days.");
35296
+ }
35297
+ return days;
35298
+ };
35299
+ var grantOption = [
35300
+ "--grant <store[:path]>",
35301
+ "Grant read access to a whole store, or to one file with store:/path (repeatable)",
35302
+ collect
35303
+ ];
35304
+ var createMachineCommand = () => {
35305
+ const program = new Command2().name("fm").description("Forum machine credentials").option(
35306
+ "--token <token>",
35307
+ "Forum access token (user token for admin commands, machine token for files/fetch)"
35308
+ ).option("--state-dir <path>", "Read CLI configuration from this directory").option("--json", "Print structured JSON").exitOverride();
35309
+ const machine = program.command("machine").description(
35310
+ "Named, read-only machine identities for automation. Admin commands need a workspace administrator; files/fetch need a machine token (FORUM_MACHINE_TOKEN)."
35311
+ );
35312
+ machine.command("create").description(
35313
+ "Create a machine credential; prints its API token and locally generated decryption key once"
35314
+ ).argument("<name>", "Workspace-unique name, e.g. github-deploy-prod").option(...grantOption).option(
35315
+ "--expires-in-days <days>",
35316
+ "Token lifetime (default 90, max 365)",
35317
+ parseDays
35318
+ ).option(
35319
+ "--no-recipient",
35320
+ "Create without an encryption recipient (plain files only)"
35321
+ ).option(
35322
+ "--token-file <path>",
35323
+ "Write the API token to this new file (mode 600) instead of printing it"
35324
+ ).option(
35325
+ "--key-file <path>",
35326
+ "Write the machine key to this new file (mode 600) instead of printing it"
35327
+ ).action(runMachineCreate);
35328
+ machine.command("list").description("List the workspace's machine credentials").option("--all", "Include revoked and expired credentials").action(runMachineList);
35329
+ machine.command("show").description("Show one machine credential").argument("<machine>", "Credential id or name").action(
35330
+ runMachineCredentialAction(
35331
+ ({ client, credentialId }) => client.readMachineCredential({ credentialId })
35332
+ )
35333
+ );
35334
+ machine.command("rotate-token").description("Issue a new API token; the old one stops working immediately").argument("<machine>", "Credential id or name").option("--expires-in-days <days>", "Lifetime of the new token", parseDays).option(
35335
+ "--token-file <path>",
35336
+ "Write the new token to this new file (mode 600)"
35337
+ ).action(runMachineRotateToken);
35338
+ machine.command("replace-key").description(
35339
+ "Generate a new machine decryption key; files must then be rekeyed to it"
35340
+ ).argument("<machine>", "Credential id or name").option(
35341
+ "--key-file <path>",
35342
+ "Write the new key to this new file (mode 600)"
35343
+ ).action(runMachineReplaceKey);
35344
+ machine.command("set-grants").description(
35345
+ "Replace the machine's grants (no --grant removes every grant)"
35346
+ ).argument("<machine>", "Credential id or name").option(...grantOption).action(
35347
+ runMachineCredentialAction(
35348
+ ({ client, credentialId, options: options2 }) => client.setMachineCredentialGrants({
35349
+ credentialId,
35350
+ grants: (options2.grant ?? []).map(parseMachineGrantSpec)
35351
+ })
35352
+ )
35353
+ );
35354
+ machine.command("revoke").description(
35355
+ "Permanently revoke API access (does not revoke decryption of files already granted)"
35356
+ ).argument("<machine>", "Credential id or name").action(
35357
+ runMachineCredentialAction(
35358
+ ({ client, credentialId }) => client.revokeMachineCredential({ credentialId })
35359
+ )
35360
+ );
35361
+ machine.command("files").description("As a machine: list the files this machine token can read").action(runMachineFiles);
35362
+ machine.command("fetch").description(
35363
+ "As a machine: download one granted file (encrypted files stay encrypted)"
35364
+ ).option("--file-id <id>", "Stable file id").option("--store <store>", "Store slug or id").option("--path <path>", "File path in the store").option("-o, --output <path>", "Write to this local file instead of stdout").action(runMachineFetch);
35365
+ return program;
35366
+ };
35367
+
35368
+ // src/machine/runMachineCommand.ts
35369
+ var runMachineCommand = async (argv) => {
35370
+ try {
35371
+ await createMachineCommand().parseAsync(argv, { from: "user" });
35372
+ } catch (error51) {
35373
+ if (error51 instanceof CommanderError2 && error51.exitCode === 0) return;
35374
+ throw error51;
35375
+ }
35376
+ };
35377
+
35378
+ // src/machine/decryptTextForMachineKey.ts
35379
+ var decryptTextForMachineKey = async (encryptedText, machineKeyArg, expectation) => {
35380
+ const machineKey = machineKeyArg ?? process.env[machineKeyEnvVar];
35381
+ if (!machineKey) {
35382
+ throw new Error(
35383
+ `A machine key is required. Pass --machine-key or set ${machineKeyEnvVar}.`
35384
+ );
35385
+ }
35386
+ try {
35387
+ return await decryptForumEncryptedFileTextWithMachineKey({
35388
+ encryptedText,
35389
+ expectation,
35390
+ machineKey
35391
+ });
35392
+ } catch (error51) {
35393
+ throw new Error(
35394
+ `Failed to decrypt with machine key: ${error51 instanceof Error ? error51.message : String(error51)}`
35395
+ );
35396
+ }
35397
+ };
35398
+
35399
+ // src/machine/toMachineRecipientPublicKey.ts
35400
+ var toMachineRecipientPublicKey = (view) => view.recipient ? {
35401
+ keyId: view.recipient.keyId,
35402
+ publicKey: view.recipient.publicKey,
35403
+ version: 3
35404
+ } : null;
35405
+
35406
+ // src/machine/grantMachineRecipients.ts
35407
+ var grantMachineRecipients = async ({
35408
+ fileKey,
35409
+ lookupMachineRecipients,
35410
+ machines,
35411
+ recipients
35412
+ }) => {
35413
+ if (!machines.length) return [];
35414
+ const views = await lookupMachineRecipients(
35415
+ machines.map((machine) => machine.credentialId)
35416
+ );
35417
+ const grants = [];
35418
+ for (const machine of machines) {
35419
+ const view = views.find(
35420
+ (candidate) => candidate.credentialId === machine.credentialId
35421
+ );
35422
+ if (!view) {
35423
+ throw new Error(
35424
+ `Machine ${machine.credentialId} was not found in this workspace.`
35425
+ );
35426
+ }
35427
+ if (view.status === "revoked") {
35428
+ throw new Error(
35429
+ `Machine "${view.name}" is revoked; it cannot be granted.`
35430
+ );
35431
+ }
35432
+ const recipient = toMachineRecipientPublicKey(view);
35433
+ if (!recipient) {
35434
+ throw new Error(
35435
+ `Machine "${view.name}" has no encryption recipient. Run fm machine replace-key ${view.credentialId} first.`
35436
+ );
35437
+ }
35438
+ if (findEncryptionRecipient({ recipientId: recipient.keyId, recipients }) || grants.some((grant) => grant.recipientId === recipient.keyId)) {
35439
+ throw new Error(
35440
+ `Machine "${view.name}" already has a grant for its current key.`
35441
+ );
35442
+ }
35443
+ grants.push(
35444
+ await createMachineRecipientGrant({
35445
+ credentialId: view.credentialId,
35446
+ expectedFingerprint: machine.expectedFingerprint ?? recipient.keyId,
35447
+ fileKey,
35448
+ name: view.name,
35449
+ recipient
35450
+ })
35451
+ );
35452
+ }
35453
+ return grants;
35454
+ };
35455
+
35456
+ // src/machine/addMachineRecipientsToEncryptedText.ts
35457
+ var addMachineRecipientsToEncryptedText = async ({
35458
+ encryptedText,
35459
+ lookupMachineRecipients,
35460
+ machines,
35461
+ password,
35462
+ userEncryption
35463
+ }) => {
35464
+ const { recipients } = parseEncryptedPlainTextPayload(encryptedText);
35465
+ const userKey = await unlockUserEncryption({
35466
+ metadata: userEncryption,
35467
+ password
35468
+ });
35469
+ const fileKey = await unwrapFileKey({
35470
+ recipientId: userEncryption.keyId,
35471
+ recipients,
35472
+ userKey
35473
+ });
35474
+ const grants = await grantMachineRecipients({
35475
+ fileKey,
35476
+ lookupMachineRecipients,
35477
+ machines,
35478
+ recipients
35479
+ });
35480
+ return {
35481
+ encryptedText: await updateEncryptedPlainTextRecipients({
35482
+ encryptedText,
35483
+ fileKey,
35484
+ recipients: [...recipients, ...grants]
35485
+ }),
35486
+ recipientIds: grants.map((grant) => grant.recipientId)
35487
+ };
35488
+ };
35489
+
33954
35490
  // src/fileSchemas.ts
33955
35491
  var textFieldSchema = {
33956
35492
  type: "string"
@@ -34310,11 +35846,12 @@ var readRecipientSecret = (secretArg) => {
34310
35846
  };
34311
35847
 
34312
35848
  // src/decryptTextForRecipientSecret.ts
34313
- var decryptTextForRecipientSecret = async (encryptedText, secretArg) => {
35849
+ var decryptTextForRecipientSecret = async (encryptedText, secretArg, expectation) => {
34314
35850
  const recipientSecret = readRecipientSecret(secretArg);
34315
35851
  try {
34316
35852
  return await decryptForumEncryptedFileText({
34317
35853
  encryptedText,
35854
+ expectation,
34318
35855
  recipientSecret
34319
35856
  });
34320
35857
  } catch (error51) {
@@ -34324,23 +35861,777 @@ var decryptTextForRecipientSecret = async (encryptedText, secretArg) => {
34324
35861
  }
34325
35862
  };
34326
35863
 
35864
+ // src/decryptRun/runDecryptRunCommand.ts
35865
+ import { readFile as readFile9 } from "fs/promises";
35866
+ import path29 from "path";
35867
+
35868
+ // ../../packages/doctrine-secrets/src/credentials/credentialEnvironmentNames.ts
35869
+ var credentialEnvironmentNames = [
35870
+ "DOCTRINE_RECIPIENT_SECRET",
35871
+ "DOCTRINE_ENCRYPTION_PASSWORD",
35872
+ "DOCTRINE_NEW_ENCRYPTION_PASSWORD",
35873
+ "DOCTRINE_TOKEN"
35874
+ ];
35875
+
35876
+ // ../../packages/doctrine-secrets/src/credentials/readCredentialFromFd.ts
35877
+ import { createReadStream } from "fs";
35878
+ var maxCredentialBytes = 64 * 1024;
35879
+ var readCredentialFromFd = async (fd, label) => {
35880
+ if (!Number.isInteger(fd) || fd < 0 || fd === 1 || fd === 2) {
35881
+ throw new Error(
35882
+ `${label} file descriptor must be 0 or 3 and above (got ${fd}).`
35883
+ );
35884
+ }
35885
+ const chunks = [];
35886
+ let size = 0;
35887
+ try {
35888
+ for await (const chunk of createReadStream("", { autoClose: true, fd })) {
35889
+ const buffer = chunk;
35890
+ size += buffer.length;
35891
+ if (size > maxCredentialBytes) {
35892
+ throw new Error(`${label} on fd ${fd} is too large.`);
35893
+ }
35894
+ chunks.push(buffer);
35895
+ }
35896
+ } catch (error51) {
35897
+ if (error51 instanceof Error && error51.message.endsWith("is too large.")) {
35898
+ throw error51;
35899
+ }
35900
+ throw new Error(
35901
+ `Could not read ${label} from fd ${fd}. Open it in the shell, e.g. ${fd}<file.`
35902
+ );
35903
+ }
35904
+ const value = Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
35905
+ if (!value) {
35906
+ throw new Error(`${label} on fd ${fd} is empty.`);
35907
+ }
35908
+ return value;
35909
+ };
35910
+
35911
+ // ../../packages/doctrine-secrets/src/selection/isEnvironmentName.ts
35912
+ var environmentNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
35913
+ var isEnvironmentName = (name) => environmentNamePattern.test(name);
35914
+
35915
+ // ../../packages/doctrine-secrets/src/source/parseDotenvValue.ts
35916
+ var doubleQuoteEscapes = {
35917
+ '"': '"',
35918
+ "\\": "\\",
35919
+ n: "\n",
35920
+ r: "\r",
35921
+ t: " "
35922
+ };
35923
+ var isCommentOrEnd = (rest) => {
35924
+ const trimmed = rest.trim();
35925
+ return trimmed === "" || trimmed.startsWith("#");
35926
+ };
35927
+ var parseDoubleQuoted = (raw) => {
35928
+ let value = "";
35929
+ for (let index = 1; index < raw.length; index += 1) {
35930
+ const char = raw[index];
35931
+ if (char === "\\") {
35932
+ const escaped = doubleQuoteEscapes[raw[index + 1] ?? ""];
35933
+ if (escaped === void 0) {
35934
+ return null;
35935
+ }
35936
+ value += escaped;
35937
+ index += 1;
35938
+ continue;
35939
+ }
35940
+ if (char === '"') {
35941
+ return isCommentOrEnd(raw.slice(index + 1)) ? value : null;
35942
+ }
35943
+ value += char;
35944
+ }
35945
+ return null;
35946
+ };
35947
+ var parseSingleQuoted = (raw) => {
35948
+ const end = raw.indexOf("'", 1);
35949
+ if (end === -1 || !isCommentOrEnd(raw.slice(end + 1))) {
35950
+ return null;
35951
+ }
35952
+ return raw.slice(1, end);
35953
+ };
35954
+ var parseUnquoted = (raw) => {
35955
+ const comment = raw.search(/\s#/);
35956
+ return (comment === -1 ? raw : raw.slice(0, comment)).trim();
35957
+ };
35958
+ var parseDotenvValue = (rawValue) => {
35959
+ const raw = rawValue.trimStart();
35960
+ if (raw.startsWith('"')) {
35961
+ return parseDoubleQuoted(raw);
35962
+ }
35963
+ if (raw.startsWith("'")) {
35964
+ return parseSingleQuoted(raw);
35965
+ }
35966
+ return parseUnquoted(raw);
35967
+ };
35968
+
35969
+ // ../../packages/doctrine-secrets/src/source/parseDotenvSecretSource.ts
35970
+ var assignmentPattern = /^(?:export\s+)?([^=\s]+)\s*=(.*)$/;
35971
+ var parseDotenvSecretSource = (plaintext) => {
35972
+ const values = {};
35973
+ const lines = plaintext.split("\n");
35974
+ lines.forEach((rawLine, index) => {
35975
+ const lineNumber = index + 1;
35976
+ const line = rawLine.replace(/\r$/, "").trim();
35977
+ if (line === "" || line.startsWith("#")) {
35978
+ return;
35979
+ }
35980
+ const match = assignmentPattern.exec(line);
35981
+ if (!match || !isEnvironmentName(match[1])) {
35982
+ throw new Error(
35983
+ `Invalid env source line ${lineNumber}: expected KEY=value (contents omitted).`
35984
+ );
35985
+ }
35986
+ const [, key, rawValue] = match;
35987
+ const value = parseDotenvValue(rawValue);
35988
+ if (value === null) {
35989
+ throw new Error(
35990
+ `Invalid value for ${key} on env source line ${lineNumber} (value omitted).`
35991
+ );
35992
+ }
35993
+ if (Object.hasOwn(values, key)) {
35994
+ throw new Error(
35995
+ `Ambiguous env source: ${key} is defined more than once (line ${lineNumber}).`
35996
+ );
35997
+ }
35998
+ values[key] = value;
35999
+ });
36000
+ return values;
36001
+ };
36002
+
36003
+ // ../../packages/doctrine-secrets/src/source/parseJsonSecretSource.ts
36004
+ var parseJsonSecretSource = (plaintext) => {
36005
+ let decoded;
36006
+ try {
36007
+ decoded = JSON.parse(plaintext);
36008
+ } catch {
36009
+ throw new Error("Secret source is not valid JSON (contents omitted).");
36010
+ }
36011
+ if (!decoded || Array.isArray(decoded) || typeof decoded !== "object") {
36012
+ throw new Error("Secret source JSON must be an object of named values.");
36013
+ }
36014
+ return decoded;
36015
+ };
36016
+
36017
+ // ../../packages/doctrine-secrets/src/source/parseSecretSource.ts
36018
+ var parseSecretSource = (plaintext, format) => {
36019
+ const resolved = format ?? (plaintext.trimStart().startsWith("{") ? "json" : "env");
36020
+ return resolved === "json" ? parseJsonSecretSource(plaintext) : parseDotenvSecretSource(plaintext);
36021
+ };
36022
+
36023
+ // ../../packages/doctrine-secrets/src/selection/parseSecretSelection.ts
36024
+ var parseSecretSelection = (spec) => {
36025
+ const separator = spec.indexOf("=");
36026
+ const output = separator === -1 ? spec : spec.slice(0, separator);
36027
+ const source = separator === -1 ? spec : spec.slice(separator + 1);
36028
+ if (!isEnvironmentName(output)) {
36029
+ throw new Error(
36030
+ `Invalid variable name "${output}". Use letters, digits and underscores, not starting with a digit.`
36031
+ );
36032
+ }
36033
+ if (!source) {
36034
+ throw new Error(`Missing source key in "${spec}". Use OUTPUT=SOURCE_KEY.`);
36035
+ }
36036
+ return { output, source };
36037
+ };
36038
+
36039
+ // ../../packages/doctrine-secrets/src/selection/isUsableSecretValue.ts
36040
+ var isUsableSecretValue = (value) => typeof value === "string" && value.trim() !== "" && !value.includes("\0");
36041
+
36042
+ // ../../packages/doctrine-secrets/src/selection/selectSecretVariables.ts
36043
+ var selectAll = (values) => Object.keys(values).map((key) => {
36044
+ if (!isEnvironmentName(key)) {
36045
+ throw new Error(
36046
+ `Source key "${key}" is not a valid variable name; select it with OUTPUT=${key}.`
36047
+ );
36048
+ }
36049
+ return { output: key, source: key };
36050
+ });
36051
+ var assertUniqueOutputs = (selections) => {
36052
+ const seen = /* @__PURE__ */ new Set();
36053
+ for (const { output } of selections) {
36054
+ if (seen.has(output)) {
36055
+ throw new Error(`Variable ${output} is requested more than once.`);
36056
+ }
36057
+ seen.add(output);
36058
+ }
36059
+ };
36060
+ var selectSecretVariables = (values, selections) => {
36061
+ const resolved = selections === "all" ? selectAll(values) : selections;
36062
+ assertUniqueOutputs(resolved);
36063
+ const missing = resolved.filter(({ source }) => !Object.hasOwn(values, source)).map(({ source }) => source);
36064
+ if (missing.length) {
36065
+ throw new Error(
36066
+ `Missing secret${missing.length > 1 ? "s" : ""} in source: ${missing.join(", ")}.`
36067
+ );
36068
+ }
36069
+ return Object.fromEntries(
36070
+ resolved.map(({ output, source }) => {
36071
+ const value = values[source];
36072
+ if (!isUsableSecretValue(value)) {
36073
+ throw new Error(
36074
+ `Invalid value for ${source}: expected a non-empty string without NUL bytes (value omitted).`
36075
+ );
36076
+ }
36077
+ return [output, value];
36078
+ })
36079
+ );
36080
+ };
36081
+
36082
+ // ../../packages/doctrine-secrets/src/run/minimalEnvironmentNames.ts
36083
+ var minimalEnvironmentNames = [
36084
+ "PATH",
36085
+ "HOME",
36086
+ "USER",
36087
+ "LOGNAME",
36088
+ "SHELL",
36089
+ "LANG",
36090
+ "LC_ALL",
36091
+ "TERM",
36092
+ "TZ",
36093
+ "TMPDIR",
36094
+ "TMP",
36095
+ "TEMP",
36096
+ "SystemRoot",
36097
+ "ComSpec",
36098
+ "PATHEXT",
36099
+ "WINDIR",
36100
+ "USERPROFILE",
36101
+ "APPDATA",
36102
+ "LOCALAPPDATA"
36103
+ ];
36104
+
36105
+ // ../../packages/doctrine-secrets/src/run/buildChildEnvironment.ts
36106
+ var pickNames = (environment, names) => Object.fromEntries(
36107
+ names.filter((name) => environment[name] !== void 0).map((name) => [name, environment[name]])
36108
+ );
36109
+ var buildChildEnvironment = ({
36110
+ cleanEnv,
36111
+ credentialValues,
36112
+ parentEnvironment,
36113
+ secrets
36114
+ }) => {
36115
+ const reserved = Object.keys(secrets).filter(
36116
+ (name) => credentialEnvironmentNames.includes(name)
36117
+ );
36118
+ if (reserved.length) {
36119
+ throw new Error(
36120
+ `${reserved.join(", ")} is reserved for Forum credentials and cannot be passed to the command.`
36121
+ );
36122
+ }
36123
+ const base = cleanEnv ? pickNames(parentEnvironment, minimalEnvironmentNames) : { ...parentEnvironment };
36124
+ const credentials = new Set(credentialValues.filter(Boolean));
36125
+ const removed = [];
36126
+ const environment = {};
36127
+ for (const [name, value] of Object.entries(base)) {
36128
+ if (value === void 0) {
36129
+ continue;
36130
+ }
36131
+ if (credentialEnvironmentNames.includes(name) || credentials.has(value)) {
36132
+ removed.push(name);
36133
+ continue;
36134
+ }
36135
+ environment[name] = value;
36136
+ }
36137
+ return { environment: { ...environment, ...secrets }, removed };
36138
+ };
36139
+
36140
+ // ../../packages/doctrine-secrets/src/run/createSecretRedactor.ts
36141
+ var redactedMarker = "[redacted]";
36142
+ var minimumRedactedLength = 4;
36143
+ var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36144
+ var createSecretRedactor = (values) => {
36145
+ const redacted = [...new Set(values)].filter((value) => value.length >= minimumRedactedLength).sort((left, right) => right.length - left.length);
36146
+ const pattern = redacted.length ? new RegExp(redacted.map(escapeRegExp).join("|"), "g") : null;
36147
+ const holdBack = redacted.length ? redacted[0].length - 1 : 0;
36148
+ let pending = "";
36149
+ const replace = (text) => pattern ? text.replace(pattern, redactedMarker) : text;
36150
+ return {
36151
+ flush: () => {
36152
+ const text = replace(pending);
36153
+ pending = "";
36154
+ return text;
36155
+ },
36156
+ push: (chunk) => {
36157
+ const text = replace(pending + chunk);
36158
+ const emitLength = Math.max(0, text.length - holdBack);
36159
+ pending = text.slice(emitLength);
36160
+ return text.slice(0, emitLength);
36161
+ }
36162
+ };
36163
+ };
36164
+
36165
+ // ../../packages/doctrine-secrets/src/run/forwardSignals.ts
36166
+ var forwardedSignals = process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
36167
+ var forwardSignals = (child, source = process) => {
36168
+ const listeners = forwardedSignals.map((signal) => {
36169
+ const listener = () => {
36170
+ if (child.exitCode === null && child.signalCode === null) {
36171
+ child.kill(signal);
36172
+ }
36173
+ };
36174
+ source.on(signal, listener);
36175
+ return { listener, signal };
36176
+ });
36177
+ return () => {
36178
+ for (const { listener, signal } of listeners) {
36179
+ source.off(signal, listener);
36180
+ }
36181
+ };
36182
+ };
36183
+
36184
+ // ../../packages/doctrine-secrets/src/run/runCommandWithSecrets.ts
36185
+ import { spawn } from "child_process";
36186
+
36187
+ // ../../packages/doctrine-secrets/src/run/exitCodeForSignal.ts
36188
+ import { constants as constants4 } from "os";
36189
+ var exitCodeForSignal = (signal) => 128 + (constants4.signals[signal] ?? 0);
36190
+
36191
+ // ../../packages/doctrine-secrets/src/run/pipeRedacted.ts
36192
+ import { StringDecoder } from "string_decoder";
36193
+ var idleFlushMs = 50;
36194
+ var pipeRedacted = (source, target, values) => new Promise((resolve) => {
36195
+ const decoder = new StringDecoder("utf8");
36196
+ const redactor = createSecretRedactor(values);
36197
+ let idleTimer = null;
36198
+ const write = (text) => {
36199
+ if (text) {
36200
+ target.write(text);
36201
+ }
36202
+ };
36203
+ const clearIdle = () => {
36204
+ if (idleTimer) {
36205
+ clearTimeout(idleTimer);
36206
+ idleTimer = null;
36207
+ }
36208
+ };
36209
+ source.on("data", (chunk) => {
36210
+ clearIdle();
36211
+ write(redactor.push(decoder.write(chunk)));
36212
+ idleTimer = setTimeout(() => write(redactor.flush()), idleFlushMs);
36213
+ });
36214
+ source.on("close", () => {
36215
+ clearIdle();
36216
+ write(redactor.push(decoder.end()));
36217
+ write(redactor.flush());
36218
+ resolve();
36219
+ });
36220
+ });
36221
+
36222
+ // ../../packages/doctrine-secrets/src/run/runCommandWithSecrets.ts
36223
+ var launchFailureFor = (error51) => error51.code === "ENOENT" ? "not_found" : error51.code === "EACCES" ? "not_executable" : "spawn_failed";
36224
+ var exitCodeForLaunchFailure = {
36225
+ not_executable: 126,
36226
+ not_found: 127,
36227
+ spawn_failed: 1
36228
+ };
36229
+ var outputStdio = (output) => output === "inherit" ? "inherit" : output === "withhold" ? "ignore" : "pipe";
36230
+ var runCommandWithSecrets = ({
36231
+ command,
36232
+ cwd,
36233
+ environment,
36234
+ output,
36235
+ redactValues,
36236
+ signalSource,
36237
+ stderr = process.stderr,
36238
+ stdin,
36239
+ stdout = process.stdout
36240
+ }) => {
36241
+ const [file2, ...args] = command;
36242
+ if (!file2) {
36243
+ throw new Error("Supply a command to run after --.");
36244
+ }
36245
+ const stdio = [stdin, outputStdio(output), outputStdio(output)];
36246
+ return new Promise((resolve) => {
36247
+ const child = spawn(file2, args, {
36248
+ cwd,
36249
+ env: environment,
36250
+ shell: false,
36251
+ stdio,
36252
+ windowsHide: true
36253
+ });
36254
+ const stopForwarding = forwardSignals(child, signalSource);
36255
+ const pipes = output === "redact" && child.stdout && child.stderr ? [
36256
+ pipeRedacted(child.stdout, stdout, redactValues),
36257
+ pipeRedacted(child.stderr, stderr, redactValues)
36258
+ ] : [];
36259
+ let settled = false;
36260
+ const settle = async (result) => {
36261
+ if (settled) {
36262
+ return;
36263
+ }
36264
+ settled = true;
36265
+ stopForwarding();
36266
+ await Promise.all(pipes);
36267
+ resolve(result);
36268
+ };
36269
+ child.on("error", (error51) => {
36270
+ if (child.pid !== void 0) {
36271
+ return;
36272
+ }
36273
+ const launchFailure = launchFailureFor(error51);
36274
+ void settle({
36275
+ exitCode: exitCodeForLaunchFailure[launchFailure],
36276
+ launchFailure,
36277
+ signal: null
36278
+ });
36279
+ });
36280
+ child.once("close", (code, signal) => {
36281
+ void settle({
36282
+ exitCode: signal ? exitCodeForSignal(signal) : code ?? 1,
36283
+ launchFailure: null,
36284
+ signal
36285
+ });
36286
+ });
36287
+ });
36288
+ };
36289
+
36290
+ // ../../packages/doctrine-secrets/src/run/SecretOutputMode.ts
36291
+ var secretOutputModes = [
36292
+ "redact",
36293
+ "inherit",
36294
+ "withhold"
36295
+ ];
36296
+
36297
+ // src/readHiddenLine.ts
36298
+ var readHiddenLine = async (prompt, {
36299
+ missingMessage = "Missing encryption password. Provide --password or DOCTRINE_ENCRYPTION_PASSWORD."
36300
+ } = {}) => {
36301
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
36302
+ throw new Error(missingMessage);
36303
+ }
36304
+ return new Promise((resolve, reject) => {
36305
+ const stdin = process.stdin;
36306
+ const stdout = process.stdout;
36307
+ const wasRaw = stdin.isRaw;
36308
+ let value = "";
36309
+ const cleanup = () => {
36310
+ stdin.off("data", readChunk);
36311
+ stdin.pause();
36312
+ stdin.setRawMode(wasRaw);
36313
+ stdout.write("\n");
36314
+ };
36315
+ const finish = () => {
36316
+ cleanup();
36317
+ resolve(value);
36318
+ };
36319
+ const cancel = () => {
36320
+ cleanup();
36321
+ reject(new Error("Encryption password prompt cancelled."));
36322
+ };
36323
+ const readChunk = (chunk) => {
36324
+ for (const byte of chunk) {
36325
+ if (byte === 3) {
36326
+ cancel();
36327
+ return;
36328
+ }
36329
+ if (byte === 13 || byte === 10) {
36330
+ finish();
36331
+ return;
36332
+ }
36333
+ if (byte === 127) {
36334
+ value = value.slice(0, -1);
36335
+ continue;
36336
+ }
36337
+ value += String.fromCharCode(byte);
36338
+ }
36339
+ };
36340
+ stdin.setRawMode(true);
36341
+ stdin.on("data", readChunk);
36342
+ stdin.resume();
36343
+ stdout.write(prompt);
36344
+ });
36345
+ };
36346
+
36347
+ // src/decryptRun/decryptRunUsage.ts
36348
+ var decryptRunUsage = `Usage:
36349
+ fm decrypt-run (<localPath>|--file|-f <localPath>) (--env|-e <NAME|OUTPUT=SOURCE_KEY>... | --all)
36350
+ [--secret-fd <n> | --password-fd <n> | --recipient]
36351
+ [--format json|env] [--output redact|inherit|withhold] [--clean-env]
36352
+ -- <command> [args...]
36353
+
36354
+ Decrypts a local encrypted JSON or dotenv file in memory and runs <command>
36355
+ with only the selected values added to its environment. No plaintext file is
36356
+ written. Missing, repeated or invalid values fail before the command starts.
36357
+
36358
+ Credentials (never as arguments, which leak into process lists and history):
36359
+ --secret-fd <n> read an external recipient secret from fd n, e.g. 3<secret.txt
36360
+ --password-fd <n> read your encryption password from fd n (account mode)
36361
+ --recipient use DOCTRINE_RECIPIENT_SECRET, or prompt for a recipient secret
36362
+ Otherwise DOCTRINE_RECIPIENT_SECRET selects recipient mode; else your account is
36363
+ used with DOCTRINE_ENCRYPTION_PASSWORD or a hidden prompt. fd 0 reads stdin and
36364
+ then gives the command no stdin.
36365
+
36366
+ Child environment:
36367
+ The parent environment is inherited (only PATH, HOME, locale and similar with
36368
+ --clean-env) minus DOCTRINE_RECIPIENT_SECRET, DOCTRINE_ENCRYPTION_PASSWORD,
36369
+ DOCTRINE_NEW_ENCRYPTION_PASSWORD, DOCTRINE_TOKEN and any variable holding the
36370
+ same value as the credential used.
36371
+
36372
+ Output (--output):
36373
+ redact default: stdout/stderr are piped and exact secret values are replaced
36374
+ with [redacted]. Best-effort only; encoded or transformed values pass.
36375
+ inherit raw passthrough; the command owns the terminal (colours, prompts).
36376
+ withhold discard command output; only the exit status is reported.
36377
+ The command can always read, and deliberately disclose, the values it is given.
36378
+
36379
+ Exit status: the command's own status, 128+n when killed by signal n, 127 if the
36380
+ command is not found, 126 if it is not executable, 1 if fm fails before starting.
36381
+ `;
36382
+
36383
+ // src/decryptRun/describeLaunchFailure.ts
36384
+ var reasons = {
36385
+ not_executable: "is not executable",
36386
+ not_found: "was not found",
36387
+ spawn_failed: "could not be started"
36388
+ };
36389
+ var describeLaunchFailure = (command, failure) => `fm decrypt-run: command ${command} ${reasons[failure]}.
36390
+ `;
36391
+
36392
+ // src/decryptRun/parseDecryptRunArgs.ts
36393
+ var commandName = "decrypt-run";
36394
+ var accountValueFlags = /* @__PURE__ */ new Set(["--token", "--state-dir"]);
36395
+ var sourceFormats = ["json", "env"];
36396
+ var argvCredentialMessage = "decrypt-run does not take credentials as arguments: they leak into process lists and shell history. Use --secret-fd/--password-fd, DOCTRINE_RECIPIENT_SECRET/DOCTRINE_ENCRYPTION_PASSWORD from a secret manager, or the hidden prompt.";
36397
+ var parseFd = (flag, value) => {
36398
+ if (!value || !/^\d+$/.test(value)) {
36399
+ throw new Error(
36400
+ `${flag} requires a file descriptor number, e.g. ${flag} 3.`
36401
+ );
36402
+ }
36403
+ return Number(value);
36404
+ };
36405
+ var parseChoice = (flag, value, choices) => {
36406
+ if (!value || !choices.includes(value)) {
36407
+ throw new Error(`${flag} must be one of: ${choices.join(", ")}.`);
36408
+ }
36409
+ return value;
36410
+ };
36411
+ var splitAtSeparator = (argv) => {
36412
+ const separator = argv.indexOf("--");
36413
+ if (separator === -1 || separator === argv.length - 1) {
36414
+ throw new Error(
36415
+ "Supply the command to run after --, e.g. fm decrypt-run secrets.env.enc --env API_KEY -- npm start"
36416
+ );
36417
+ }
36418
+ return {
36419
+ command: argv.slice(separator + 1),
36420
+ options: argv.slice(0, separator)
36421
+ };
36422
+ };
36423
+ var splitInlineValue = (arg) => {
36424
+ const equals = arg.indexOf("=");
36425
+ return arg.startsWith("--") && equals !== -1 ? [arg.slice(0, equals), arg.slice(equals + 1)] : [arg, void 0];
36426
+ };
36427
+ var parseDecryptRunArgs = (argv) => {
36428
+ const separator = argv.indexOf("--");
36429
+ const beforeCommand = separator === -1 ? argv : argv.slice(0, separator);
36430
+ if (beforeCommand.includes("--help") || beforeCommand.includes("-h")) {
36431
+ return "help";
36432
+ }
36433
+ const { command, options: options2 } = splitAtSeparator(argv);
36434
+ const accountArgs = [];
36435
+ const selections = [];
36436
+ let all = false;
36437
+ let cleanEnv = false;
36438
+ let filePath = null;
36439
+ let format;
36440
+ let output = "redact";
36441
+ let passwordFd = null;
36442
+ let recipient = false;
36443
+ let secretFd = null;
36444
+ let seenCommandName = false;
36445
+ for (let index = 0; index < options2.length; index += 1) {
36446
+ const [flag, inlineValue] = splitInlineValue(options2[index]);
36447
+ const takeValue = () => {
36448
+ if (inlineValue !== void 0) {
36449
+ return inlineValue;
36450
+ }
36451
+ index += 1;
36452
+ return options2[index];
36453
+ };
36454
+ if (flag === "--secret" || flag === "--password") {
36455
+ throw new Error(argvCredentialMessage);
36456
+ }
36457
+ if (accountValueFlags.has(flag)) {
36458
+ accountArgs.push(flag, takeValue() ?? "");
36459
+ } else if (flag === "--file" || flag === "-f") {
36460
+ filePath = takeValue() ?? null;
36461
+ } else if (flag === "--env" || flag === "-e") {
36462
+ selections.push(parseSecretSelection(takeValue() ?? ""));
36463
+ } else if (flag === "--all") {
36464
+ all = true;
36465
+ } else if (flag === "--format") {
36466
+ format = parseChoice(flag, takeValue(), sourceFormats);
36467
+ } else if (flag === "--output") {
36468
+ output = parseChoice(flag, takeValue(), secretOutputModes);
36469
+ } else if (flag === "--clean-env") {
36470
+ cleanEnv = true;
36471
+ } else if (flag === "--secret-fd") {
36472
+ secretFd = parseFd(flag, takeValue());
36473
+ } else if (flag === "--password-fd") {
36474
+ passwordFd = parseFd(flag, takeValue());
36475
+ } else if (flag === "--recipient") {
36476
+ recipient = true;
36477
+ } else if (flag.startsWith("-")) {
36478
+ throw new Error(`Unknown decrypt-run option: ${flag}`);
36479
+ } else if (flag === commandName && !seenCommandName) {
36480
+ seenCommandName = true;
36481
+ } else if (filePath === null) {
36482
+ filePath = flag;
36483
+ } else {
36484
+ throw new Error(`Unexpected argument before --: ${flag}`);
36485
+ }
36486
+ }
36487
+ if (!filePath) {
36488
+ throw new Error(
36489
+ "Supply the encrypted file: fm decrypt-run <localPath> ..."
36490
+ );
36491
+ }
36492
+ if (all === selections.length > 0) {
36493
+ throw new Error(
36494
+ "Select variables with --env NAME (repeatable) or pass --all, but not both."
36495
+ );
36496
+ }
36497
+ if ([secretFd !== null, passwordFd !== null, recipient].filter(Boolean).length > 1) {
36498
+ throw new Error(
36499
+ "Use only one of --secret-fd, --password-fd and --recipient."
36500
+ );
36501
+ }
36502
+ return {
36503
+ accountArgs,
36504
+ cleanEnv,
36505
+ command,
36506
+ filePath,
36507
+ format,
36508
+ output,
36509
+ passwordFd,
36510
+ recipient,
36511
+ secretFd,
36512
+ selections: all ? "all" : selections
36513
+ };
36514
+ };
36515
+
36516
+ // src/decryptRun/resolveDecryptRunCredential.ts
36517
+ var fromFd = async (fd, mode) => ({
36518
+ consumedStdin: fd === 0,
36519
+ mode,
36520
+ value: await readCredentialFromFd(
36521
+ fd,
36522
+ mode === "recipient" ? "Recipient secret" : "Encryption password"
36523
+ )
36524
+ });
36525
+ var resolveDecryptRunCredential = async ({
36526
+ args,
36527
+ environment,
36528
+ readHidden
36529
+ }) => {
36530
+ if (args.secretFd !== null) {
36531
+ return fromFd(args.secretFd, "recipient");
36532
+ }
36533
+ if (args.passwordFd !== null) {
36534
+ return fromFd(args.passwordFd, "user");
36535
+ }
36536
+ const recipientSecret = environment.DOCTRINE_RECIPIENT_SECRET;
36537
+ if (args.recipient || recipientSecret) {
36538
+ return {
36539
+ consumedStdin: false,
36540
+ mode: "recipient",
36541
+ value: recipientSecret || await readHidden("Recipient secret: ", {
36542
+ missingMessage: "Missing recipient secret. Use --secret-fd <n> or DOCTRINE_RECIPIENT_SECRET."
36543
+ })
36544
+ };
36545
+ }
36546
+ return {
36547
+ consumedStdin: false,
36548
+ mode: "user",
36549
+ value: environment.DOCTRINE_ENCRYPTION_PASSWORD || await readHidden("Encryption password: ", {
36550
+ missingMessage: "Missing encryption password. Use --password-fd <n>, DOCTRINE_ENCRYPTION_PASSWORD, or run in a terminal to be prompted."
36551
+ })
36552
+ };
36553
+ };
36554
+
36555
+ // src/decryptRun/runDecryptRunCommand.ts
36556
+ var runDecryptRunCommand = async ({
36557
+ argv,
36558
+ decryptAsUser,
36559
+ environment = process.env,
36560
+ readHidden = readHiddenLine,
36561
+ signalSource,
36562
+ stderr = process.stderr,
36563
+ stdout = process.stdout
36564
+ }) => {
36565
+ const args = parseDecryptRunArgs(argv);
36566
+ if (args === "help") {
36567
+ stdout.write(decryptRunUsage);
36568
+ return 0;
36569
+ }
36570
+ const encryptedText = await readFile9(path29.resolve(args.filePath), "utf8");
36571
+ const credential = await resolveDecryptRunCredential({
36572
+ args,
36573
+ environment,
36574
+ readHidden
36575
+ });
36576
+ registerRedactedSecret(credential.value);
36577
+ const plaintext = credential.mode === "recipient" ? await decryptTextForRecipientSecret(encryptedText, credential.value) : await decryptAsUser({
36578
+ accountArgs: args.accountArgs,
36579
+ encryptedText,
36580
+ password: credential.value
36581
+ });
36582
+ const secrets = selectSecretVariables(
36583
+ parseSecretSource(plaintext, args.format),
36584
+ args.selections
36585
+ );
36586
+ const secretValues = Object.values(secrets);
36587
+ secretValues.forEach(registerRedactedSecret);
36588
+ const { environment: childEnvironment } = buildChildEnvironment({
36589
+ cleanEnv: args.cleanEnv,
36590
+ credentialValues: [
36591
+ credential.value,
36592
+ environment.DOCTRINE_TOKEN,
36593
+ environment.DOCTRINE_RECIPIENT_SECRET,
36594
+ environment.DOCTRINE_ENCRYPTION_PASSWORD
36595
+ ],
36596
+ parentEnvironment: environment,
36597
+ secrets
36598
+ });
36599
+ const result = await runCommandWithSecrets({
36600
+ command: args.command,
36601
+ environment: childEnvironment,
36602
+ output: args.output,
36603
+ redactValues: [...secretValues, credential.value],
36604
+ signalSource,
36605
+ stderr,
36606
+ stdin: credential.consumedStdin ? "ignore" : "inherit",
36607
+ stdout
36608
+ });
36609
+ if (result.launchFailure) {
36610
+ stderr.write(describeLaunchFailure(args.command[0], result.launchFailure));
36611
+ }
36612
+ return result.exitCode;
36613
+ };
36614
+
34327
36615
  // src/describeRekeyIssues.ts
34328
36616
  var reasonText = {
34329
36617
  public_key_unavailable: "their current public encryption key is unavailable, so the new file key cannot be wrapped for them",
34330
36618
  public_key_unverified: "their legacy encryption key has no fingerprint you have verified, so the new file key will not be wrapped for them (verify their key in the web app first)",
34331
36619
  secret_not_retained: "its secret is not stored by Forum, so it cannot be carried onto a new file key"
34332
36620
  };
36621
+ var machineHint = "A machine recipient is reported when the machine was revoked or its key was replaced: pass --remove <label-or-id> for the old entry, and --grant-machine <machine> to grant the machine's current key.";
34333
36622
  var describeRekeyIssues = (issues) => [
34334
36623
  "Rekeying would not preserve every remaining recipient:",
34335
36624
  ...issues.map(
34336
36625
  (issue2) => ` - ${issue2.label ?? issue2.recipientId} (${issue2.recipientId}): ${reasonText[issue2.reason]}.`
34337
36626
  ),
34338
- "Decide for each one: pass --reissue <label-or-id> to mint a new secret (external recipients only) or --remove <label-or-id> to revoke it. Nothing was changed."
36627
+ "Decide for each one: pass --reissue <label-or-id> to mint a new secret (external recipients only) or --remove <label-or-id> to revoke it. Nothing was changed.",
36628
+ ...issues.some((issue2) => parseMachineRecipientLabel(issue2.label)) ? [machineHint] : []
34339
36629
  ].join("\n");
34340
36630
 
34341
36631
  // src/resolveRecipientPublicKeys.ts
34342
36632
  var resolveRecipientPublicKeys = async ({
34343
36633
  actor,
36634
+ lookupMachineRecipients,
34344
36635
  lookupPublicKeys,
34345
36636
  recipients
34346
36637
  }) => {
@@ -34350,6 +36641,20 @@ var resolveRecipientPublicKeys = async ({
34350
36641
  )
34351
36642
  ];
34352
36643
  const others = userIds.length ? await lookupPublicKeys(userIds) : [];
36644
+ const machineIds = [
36645
+ ...new Set(
36646
+ recipients.map(
36647
+ (recipient) => parseMachineRecipientLabel(recipient.label)?.credentialId
36648
+ ).filter(
36649
+ (credentialId) => Boolean(credentialId)
36650
+ )
36651
+ )
36652
+ ];
36653
+ const machines = machineIds.length && lookupMachineRecipients ? await lookupMachineRecipients(machineIds) : [];
36654
+ const machineCandidates = machines.flatMap((view) => {
36655
+ const recipient = view.status === "revoked" ? null : toMachineRecipientPublicKey(view);
36656
+ return recipient ? [{ userEncryption: recipient }] : [];
36657
+ });
34353
36658
  const actorKey = actor.version === 3 ? { keyId: actor.keyId, publicKey: actor.publicKey, version: 3 } : { keyId: actor.keyId, publicKey: actor.publicKey, version: 2 };
34354
36659
  return [
34355
36660
  {
@@ -34363,7 +36668,8 @@ var resolveRecipientPublicKeys = async ({
34363
36668
  userEncryption: entry.encryption
34364
36669
  }
34365
36670
  ] : []
34366
- )
36671
+ ),
36672
+ ...machineCandidates
34367
36673
  ];
34368
36674
  };
34369
36675
 
@@ -34395,6 +36701,8 @@ var resolveRecipientSelectors = ({
34395
36701
  // src/rekeyEncryptedTextForUser.ts
34396
36702
  var rekeyEncryptedTextForUser = async ({
34397
36703
  encryptedText,
36704
+ grantMachines = [],
36705
+ lookupMachineRecipients,
34398
36706
  lookupPublicKeys,
34399
36707
  password,
34400
36708
  reissue,
@@ -34434,6 +36742,7 @@ var rekeyEncryptedTextForUser = async ({
34434
36742
  });
34435
36743
  const candidates = await resolveRecipientPublicKeys({
34436
36744
  actor: userEncryption,
36745
+ lookupMachineRecipients,
34437
36746
  lookupPublicKeys,
34438
36747
  recipients
34439
36748
  });
@@ -34453,8 +36762,21 @@ var rekeyEncryptedTextForUser = async ({
34453
36762
  fileKey,
34454
36763
  plan
34455
36764
  });
36765
+ if (grantMachines.length && !lookupMachineRecipients) {
36766
+ throw new Error("Machine recipient lookup is required to grant machines.");
36767
+ }
36768
+ const machineGrants = lookupMachineRecipients ? await grantMachineRecipients({
36769
+ fileKey: result.fileKey,
36770
+ lookupMachineRecipients,
36771
+ machines: grantMachines,
36772
+ recipients: result.encryption.recipients
36773
+ }) : [];
34456
36774
  return {
34457
- encryptedText: result.encryptedText,
36775
+ encryptedText: machineGrants.length ? await updateEncryptedPlainTextRecipients({
36776
+ encryptedText: result.encryptedText,
36777
+ fileKey: result.fileKey,
36778
+ recipients: [...result.encryption.recipients, ...machineGrants]
36779
+ }) : result.encryptedText,
34458
36780
  issuedSecrets: result.issuedSecrets,
34459
36781
  removedRecipientIds: result.removedRecipientIds
34460
36782
  };
@@ -34464,6 +36786,7 @@ var rekeyEncryptedTextForUser = async ({
34464
36786
  var addExternalRecipientToEncryptedText = async ({
34465
36787
  encryptedText,
34466
36788
  force,
36789
+ lookupMachineRecipients,
34467
36790
  lookupPublicKeys,
34468
36791
  name,
34469
36792
  password,
@@ -34486,6 +36809,7 @@ var addExternalRecipientToEncryptedText = async ({
34486
36809
  );
34487
36810
  const result = await rekeyEncryptedTextForUser({
34488
36811
  encryptedText,
36812
+ lookupMachineRecipients,
34489
36813
  lookupPublicKeys,
34490
36814
  password,
34491
36815
  reissue: [replaced, ...reissue],
@@ -34525,8 +36849,9 @@ var addExternalRecipientToEncryptedText = async ({
34525
36849
  name
34526
36850
  });
34527
36851
  return {
34528
- encryptedText: updateEncryptedPlainTextRecipients({
36852
+ encryptedText: await updateEncryptedPlainTextRecipients({
34529
36853
  encryptedText,
36854
+ fileKey,
34530
36855
  recipients: [...payload.recipients, recipient]
34531
36856
  }),
34532
36857
  otherIssuedSecrets: [],
@@ -34572,10 +36897,10 @@ var editEncryptedText = async ({
34572
36897
  }
34573
36898
  const reencrypted = await encryptPlainTextWithFileKey({
34574
36899
  fileKey,
36900
+ identity: continueEncryptedEnvelopeIdentity(payload),
34575
36901
  plaintext: editedPlaintext,
34576
36902
  recipients: payload.recipients,
34577
- version: payload.doctrineEncryptedFile,
34578
- workspaceAccess: payload.workspaceAccess
36903
+ workspaceAccess: payload.workspaceAccess ?? "personal"
34579
36904
  });
34580
36905
  const verified = await decryptPlainTextWithFileKey({
34581
36906
  encryptedText: reencrypted,
@@ -34765,7 +37090,7 @@ var runEncryptionIdentityCommand = async ({
34765
37090
  `Encryption password changed. Your identity is unchanged: ${formatEncryptionFingerprint(fingerprint2)}`
34766
37091
  );
34767
37092
  render(
34768
- "Copies of your old key record (exports, backups) remain protected by the old password. A password change does not revoke access to files already shared with you or by you."
37093
+ "Existing backups (`fm encryption backup`) still open with your OLD password, and hold the same private key, so they can also open files encrypted for you later. Make a new backup and delete old ones if the old password may be known. A password change does not revoke access to files already shared with you or by you."
34769
37094
  );
34770
37095
  return;
34771
37096
  }
@@ -34782,16 +37107,19 @@ var runEncryptionIdentityCommand = async ({
34782
37107
  render(
34783
37108
  "Files encrypted for your previous identity cannot be opened with the new one. Teammates must verify this fingerprint before granting you access again."
34784
37109
  );
37110
+ render(
37111
+ "Backups made before the reset still open the files they contain with your previous password, but cannot open anything encrypted for the new identity. Run `fm encryption backup` again."
37112
+ );
34785
37113
  };
34786
37114
 
34787
37115
  // src/writeTextFileIfUnchanged.ts
34788
- import { readFile as readFile9 } from "fs/promises";
37116
+ import { readFile as readFile10 } from "fs/promises";
34789
37117
  var writeTextFileIfUnchanged = async ({
34790
37118
  expectedText,
34791
37119
  filePath,
34792
37120
  text
34793
37121
  }) => {
34794
- const current = await readFile9(filePath, "utf8");
37122
+ const current = await readFile10(filePath, "utf8");
34795
37123
  if (current !== expectedText) {
34796
37124
  throw new Error(
34797
37125
  `${filePath} changed while this command was running; nothing was written. Re-run against the latest version.`
@@ -34801,83 +37129,72 @@ var writeTextFileIfUnchanged = async ({
34801
37129
  };
34802
37130
 
34803
37131
  // src/openInEditor.ts
34804
- import { spawn } from "child_process";
34805
- import { mkdtemp as mkdtemp2, readFile as readFile10, rm as rm7, writeFile as writeFile5 } from "fs/promises";
37132
+ import { spawn as spawn2 } from "child_process";
37133
+ import { rmSync } from "fs";
37134
+ import { chmod as chmod3, mkdtemp as mkdtemp2, readFile as readFile11, rm as rm7, writeFile as writeFile6 } from "fs/promises";
37135
+ import path30 from "path";
37136
+
37137
+ // src/resolvePrivateTempBase.ts
37138
+ import { statSync } from "fs";
34806
37139
  import { tmpdir } from "os";
34807
- import path26 from "path";
34808
- var openInEditor = async (currentText, { extension = "" } = {}) => {
37140
+ var resolvePrivateTempBase = (environment = process.env) => {
37141
+ const runtimeDir = environment.XDG_RUNTIME_DIR;
37142
+ if (runtimeDir && usesPosixPermissions()) {
37143
+ try {
37144
+ const stats = statSync(runtimeDir);
37145
+ if (stats.isDirectory() && stats.uid === process.getuid?.() && (stats.mode & 63) === 0) {
37146
+ return runtimeDir;
37147
+ }
37148
+ } catch {
37149
+ }
37150
+ }
37151
+ return tmpdir();
37152
+ };
37153
+
37154
+ // src/openInEditor.ts
37155
+ var runEditor = (tempPath, signalSource) => new Promise((resolve, reject) => {
34809
37156
  const editor = process.env.EDITOR?.trim() || "vi";
34810
- const dir = await mkdtemp2(path26.join(tmpdir(), "fm-edit-"));
34811
- const tempPath = path26.join(dir, `edit${extension}`);
37157
+ const child = spawn2(
37158
+ "/bin/sh",
37159
+ ["-c", `exec ${editor} "$1"`, "fm-editor", tempPath],
37160
+ { stdio: "inherit" }
37161
+ );
37162
+ const stopForwarding = forwardSignals(child, signalSource);
37163
+ child.on("error", (error51) => {
37164
+ stopForwarding();
37165
+ reject(error51);
37166
+ });
37167
+ child.on("exit", (code) => {
37168
+ stopForwarding();
37169
+ resolve(code ?? 1);
37170
+ });
37171
+ });
37172
+ var openInEditor = async (currentText, {
37173
+ extension = "",
37174
+ signalSource
37175
+ } = {}) => {
37176
+ const dir = await mkdtemp2(path30.join(resolvePrivateTempBase(), "fm-edit-"));
37177
+ const removeOnExit = () => rmSync(dir, { force: true, recursive: true });
37178
+ process.once("exit", removeOnExit);
34812
37179
  try {
34813
- await writeFile5(tempPath, currentText, "utf8");
34814
- const exitCode = await new Promise((resolve, reject) => {
34815
- const child = spawn(
34816
- "/bin/sh",
34817
- ["-c", `exec ${editor} "$1"`, "fm-editor", tempPath],
34818
- { stdio: "inherit" }
34819
- );
34820
- child.on("error", reject);
34821
- child.on("exit", (code) => resolve(code ?? 1));
37180
+ await chmod3(dir, privateModes.directory);
37181
+ const tempPath = path30.join(dir, `edit${extension}`);
37182
+ await writeFile6(tempPath, currentText, {
37183
+ encoding: "utf8",
37184
+ flag: "wx",
37185
+ mode: privateModes.file
34822
37186
  });
34823
- if (exitCode !== 0) {
37187
+ if (await runEditor(tempPath, signalSource) !== 0) {
34824
37188
  return null;
34825
37189
  }
34826
- return await readFile10(tempPath, "utf8");
37190
+ return await readFile11(tempPath, "utf8");
34827
37191
  } finally {
34828
- await rm7(dir, { force: true, recursive: true }).catch(() => {
34829
- });
34830
- }
34831
- };
34832
-
34833
- // src/readHiddenLine.ts
34834
- var readHiddenLine = async (prompt) => {
34835
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
34836
- throw new Error(
34837
- "Missing encryption password. Provide --password or DOCTRINE_ENCRYPTION_PASSWORD."
34838
- );
37192
+ try {
37193
+ await rm7(dir, { force: true, recursive: true });
37194
+ process.off("exit", removeOnExit);
37195
+ } catch {
37196
+ }
34839
37197
  }
34840
- return new Promise((resolve, reject) => {
34841
- const stdin = process.stdin;
34842
- const stdout = process.stdout;
34843
- const wasRaw = stdin.isRaw;
34844
- let value = "";
34845
- const cleanup = () => {
34846
- stdin.off("data", readChunk);
34847
- stdin.pause();
34848
- stdin.setRawMode(wasRaw);
34849
- stdout.write("\n");
34850
- };
34851
- const finish = () => {
34852
- cleanup();
34853
- resolve(value);
34854
- };
34855
- const cancel = () => {
34856
- cleanup();
34857
- reject(new Error("Encryption password prompt cancelled."));
34858
- };
34859
- const readChunk = (chunk) => {
34860
- for (const byte of chunk) {
34861
- if (byte === 3) {
34862
- cancel();
34863
- return;
34864
- }
34865
- if (byte === 13 || byte === 10) {
34866
- finish();
34867
- return;
34868
- }
34869
- if (byte === 127) {
34870
- value = value.slice(0, -1);
34871
- continue;
34872
- }
34873
- value += String.fromCharCode(byte);
34874
- }
34875
- };
34876
- stdin.setRawMode(true);
34877
- stdin.on("data", readChunk);
34878
- stdin.resume();
34879
- stdout.write(prompt);
34880
- });
34881
37198
  };
34882
37199
 
34883
37200
  // src/compileMarkdown.ts
@@ -34912,7 +37229,7 @@ var standaloneIncludeId = (paragraph) => {
34912
37229
  var textContent = (file2) => file2?.content && "text" in file2.content ? file2.content.text : null;
34913
37230
  var compileMarkdown = async ({
34914
37231
  entry,
34915
- readFile: readFile12,
37232
+ readFile: readFile13,
34916
37233
  optional: optional2,
34917
37234
  limits = {}
34918
37235
  }) => {
@@ -34956,7 +37273,7 @@ var compileMarkdown = async ({
34956
37273
  throw new Error(`Include cycle: ${[...chain, id].join(" -> ")}`);
34957
37274
  let target;
34958
37275
  try {
34959
- target = await readFile12(id);
37276
+ target = await readFile13(id);
34960
37277
  } catch (error51) {
34961
37278
  if (optional2) {
34962
37279
  warnings.push(`Omitted unreadable include ${id} from ${label}.`);
@@ -34988,11 +37305,21 @@ var compileMarkdown = async ({
34988
37305
  // src/resolveDecryptAuthMode.ts
34989
37306
  var resolveDecryptAuthMode = ({
34990
37307
  encryptionPassword,
37308
+ hasMachineKeyEnv = false,
34991
37309
  hasRecipientSecretEnv,
37310
+ machineKey = null,
34992
37311
  recipientSecret,
34993
37312
  token
34994
37313
  }) => {
34995
37314
  const hasPasswordOrToken = encryptionPassword !== null || token !== null;
37315
+ if (machineKey !== null) {
37316
+ if (hasPasswordOrToken || recipientSecret !== null) {
37317
+ throw new Error(
37318
+ "--machine-key cannot be combined with --secret, --password or --token."
37319
+ );
37320
+ }
37321
+ return "machine-key";
37322
+ }
34996
37323
  if (recipientSecret !== null) {
34997
37324
  if (hasPasswordOrToken) {
34998
37325
  throw new Error(
@@ -35001,12 +37328,331 @@ var resolveDecryptAuthMode = ({
35001
37328
  }
35002
37329
  return "recipient-secret";
35003
37330
  }
35004
- if (hasRecipientSecretEnv && !hasPasswordOrToken) {
35005
- return "recipient-secret";
37331
+ if (hasPasswordOrToken) return "user";
37332
+ if (hasMachineKeyEnv && hasRecipientSecretEnv) {
37333
+ throw new Error(
37334
+ "Both FORUM_MACHINE_KEY and DOCTRINE_RECIPIENT_SECRET are set. Pass --machine-key or --secret to choose one."
37335
+ );
35006
37336
  }
37337
+ if (hasMachineKeyEnv) return "machine-key";
37338
+ if (hasRecipientSecretEnv) return "recipient-secret";
35007
37339
  return "user";
35008
37340
  };
35009
37341
 
37342
+ // src/encryptionBackup/encryptionBackupSubcommands.ts
37343
+ var encryptionBackupSubcommands = [
37344
+ "backup",
37345
+ "restore",
37346
+ "verify-backup"
37347
+ ];
37348
+
37349
+ // src/encryptionBackup/isEncryptionBackupSubcommand.ts
37350
+ var isEncryptionBackupSubcommand = (value) => encryptionBackupSubcommands.includes(value);
37351
+
37352
+ // src/encryptionBackup/createEncryptionBackupFile.ts
37353
+ import fs4 from "fs/promises";
37354
+ import path33 from "path";
37355
+
37356
+ // src/encryptionBackup/collectEncryptedFileCandidates.ts
37357
+ import fs from "fs/promises";
37358
+ import path31 from "path";
37359
+
37360
+ // src/encryptionBackup/isEncryptedEnvelopeText.ts
37361
+ var isEncryptedEnvelopeText = (text) => {
37362
+ if (!text.trimStart().startsWith("{") || !text.includes("doctrineEncryptedFile")) {
37363
+ return false;
37364
+ }
37365
+ try {
37366
+ const parsed = JSON.parse(text);
37367
+ return typeof parsed.doctrineEncryptedFile === "number";
37368
+ } catch {
37369
+ return false;
37370
+ }
37371
+ };
37372
+
37373
+ // src/encryptionBackup/collectEncryptedFileCandidates.ts
37374
+ var skippedDirectories = /* @__PURE__ */ new Set([".forum", ".git", "node_modules"]);
37375
+ var maxEnvelopeBytes = 32 * 1024 * 1024;
37376
+ var collectEncryptedFileCandidates = async ({
37377
+ excludePaths = [],
37378
+ rootDir
37379
+ }) => {
37380
+ const excluded = new Set(excludePaths.map((entry) => path31.resolve(entry)));
37381
+ const candidates = [];
37382
+ const walk = async (directory) => {
37383
+ const entries = await fs.readdir(directory, { withFileTypes: true });
37384
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
37385
+ const absolute = path31.join(directory, entry.name);
37386
+ if (entry.isDirectory() && !skippedDirectories.has(entry.name)) {
37387
+ await walk(absolute);
37388
+ continue;
37389
+ }
37390
+ if (!entry.isFile() || excluded.has(absolute)) {
37391
+ continue;
37392
+ }
37393
+ if ((await fs.stat(absolute)).size > maxEnvelopeBytes) {
37394
+ continue;
37395
+ }
37396
+ const text = await fs.readFile(absolute, "utf8");
37397
+ if (isEncryptedEnvelopeText(text)) {
37398
+ candidates.push({
37399
+ encryptedText: text,
37400
+ path: path31.relative(rootDir, absolute).split(path31.sep).join("/")
37401
+ });
37402
+ }
37403
+ }
37404
+ };
37405
+ await walk(path31.resolve(rootDir));
37406
+ return candidates;
37407
+ };
37408
+
37409
+ // src/encryptionBackup/isFileExistsError.ts
37410
+ var isFileExistsError = (error51) => error51?.code === "EEXIST";
37411
+
37412
+ // src/encryptionBackup/pathExists.ts
37413
+ import fs2 from "fs/promises";
37414
+ var pathExists4 = async (target) => {
37415
+ try {
37416
+ await fs2.lstat(target);
37417
+ return true;
37418
+ } catch {
37419
+ return false;
37420
+ }
37421
+ };
37422
+
37423
+ // src/encryptionBackup/writeFileExclusive.ts
37424
+ import { randomUUID } from "crypto";
37425
+ import fs3 from "fs/promises";
37426
+ import path32 from "path";
37427
+ var writeFileExclusive = async (target, content, mode = 384) => {
37428
+ const temporary = path32.join(
37429
+ path32.dirname(target),
37430
+ `.${path32.basename(target)}.${randomUUID()}.partial`
37431
+ );
37432
+ try {
37433
+ await fs3.writeFile(temporary, content, { flag: "wx", mode });
37434
+ await fs3.link(temporary, target);
37435
+ } finally {
37436
+ await fs3.rm(temporary, { force: true });
37437
+ }
37438
+ };
37439
+
37440
+ // src/encryptionBackup/createEncryptionBackupFile.ts
37441
+ var existingOutputError = (outputPath) => new Error(
37442
+ `${outputPath} already exists. Choose a new backup file name; existing backups are never overwritten.`
37443
+ );
37444
+ var createEncryptionBackupFile = async ({
37445
+ client,
37446
+ now,
37447
+ outputPath,
37448
+ password,
37449
+ sourceDir
37450
+ }) => {
37451
+ const resolvedOutput = path33.resolve(outputPath);
37452
+ if (await pathExists4(resolvedOutput)) {
37453
+ throw existingOutputError(outputPath);
37454
+ }
37455
+ const { encryption } = await client.readUserPreferences();
37456
+ if (!encryption) {
37457
+ throw new Error(
37458
+ "Encryption is not set up for this account; there is nothing to back up."
37459
+ );
37460
+ }
37461
+ const { backup, excluded } = await createEncryptionBackup({
37462
+ createdAt: now,
37463
+ files: await collectEncryptedFileCandidates({
37464
+ excludePaths: [resolvedOutput],
37465
+ rootDir: sourceDir
37466
+ }),
37467
+ identity: encryption,
37468
+ password
37469
+ });
37470
+ await fs4.mkdir(path33.dirname(resolvedOutput), { recursive: true });
37471
+ try {
37472
+ await writeFileExclusive(resolvedOutput, serializeEncryptionBackup(backup));
37473
+ } catch (error51) {
37474
+ throw isFileExistsError(error51) ? existingOutputError(outputPath) : error51;
37475
+ }
37476
+ return {
37477
+ excluded,
37478
+ fileCount: backup.files.length,
37479
+ fingerprint: backup.fingerprint
37480
+ };
37481
+ };
37482
+
37483
+ // src/encryptionBackup/encryptionBackupGuidance.ts
37484
+ var encryptionBackupGuidance = [
37485
+ "Store this backup and your encryption password separately (for example the file in cloud storage, the password in a password manager or on paper).",
37486
+ "The backup is useless without that password, and Forum cannot recover a lost password: there is no administrator or server-held recovery key.",
37487
+ "Changing your password later does not update this file: it keeps opening with today's password. Make a new backup after a password change or reset, then delete old ones."
37488
+ ];
37489
+
37490
+ // src/encryptionBackup/restoreEncryptionBackupFile.ts
37491
+ import fs8 from "fs/promises";
37492
+
37493
+ // src/encryptionBackup/readEncryptionBackupFile.ts
37494
+ import fs5 from "fs/promises";
37495
+ var readEncryptionBackupFile = async (backupPath) => parseEncryptionBackup(await fs5.readFile(backupPath, "utf8"));
37496
+
37497
+ // src/encryptionBackup/restoreDecryptedFile.ts
37498
+ import fs7 from "fs/promises";
37499
+
37500
+ // src/encryptionBackup/resolveRestoreTarget.ts
37501
+ import fs6 from "fs/promises";
37502
+ import path34 from "path";
37503
+ var resolveRestoreTarget = async (targetDir, relativePath) => {
37504
+ const root = await fs6.realpath(targetDir);
37505
+ const target = path34.join(root, ...relativePath.split("/"));
37506
+ const parent = path34.dirname(target);
37507
+ await fs6.mkdir(parent, { mode: 448, recursive: true });
37508
+ const realParent = await fs6.realpath(parent);
37509
+ if (realParent !== root && !realParent.startsWith(`${root}${path34.sep}`)) {
37510
+ throw new Error(
37511
+ `Refusing to restore ${relativePath} outside ${targetDir}.`
37512
+ );
37513
+ }
37514
+ return path34.join(realParent, path34.basename(target));
37515
+ };
37516
+
37517
+ // src/encryptionBackup/restoreDecryptedFile.ts
37518
+ var readExisting = async (target) => {
37519
+ try {
37520
+ return await fs7.readFile(target, "utf8");
37521
+ } catch {
37522
+ return null;
37523
+ }
37524
+ };
37525
+ var restoreDecryptedFile = async ({
37526
+ path: relativePath,
37527
+ plaintext,
37528
+ targetDir
37529
+ }) => {
37530
+ const target = await resolveRestoreTarget(targetDir, relativePath);
37531
+ try {
37532
+ await writeFileExclusive(target, plaintext);
37533
+ return { path: relativePath, status: "restored" };
37534
+ } catch (error51) {
37535
+ if (!isFileExistsError(error51)) {
37536
+ throw error51;
37537
+ }
37538
+ }
37539
+ return {
37540
+ path: relativePath,
37541
+ status: await readExisting(target) === plaintext ? "unchanged" : "conflict"
37542
+ };
37543
+ };
37544
+
37545
+ // src/encryptionBackup/toRestoredPlaintextPath.ts
37546
+ var toRestoredPlaintextPath = (backupPath) => {
37547
+ const stripped = backupPath.replace(/\.enc$/i, "");
37548
+ return stripped === "" || stripped.endsWith("/") ? backupPath : stripped;
37549
+ };
37550
+
37551
+ // src/encryptionBackup/restoreEncryptionBackupFile.ts
37552
+ var assertUniqueTargets = (paths) => {
37553
+ const seen = /* @__PURE__ */ new Set();
37554
+ for (const target of paths) {
37555
+ if (seen.has(target)) {
37556
+ throw new Error(
37557
+ `Two backed-up files would both restore to ${target}. Restore them separately.`
37558
+ );
37559
+ }
37560
+ seen.add(target);
37561
+ }
37562
+ };
37563
+ var restoreEncryptionBackupFile = async ({
37564
+ backupPath,
37565
+ password,
37566
+ targetDir
37567
+ }) => {
37568
+ const backup = await readEncryptionBackupFile(backupPath);
37569
+ const { files, fingerprint } = await decryptEncryptionBackup({
37570
+ backup,
37571
+ password
37572
+ });
37573
+ const targets = files.map((file2) => ({
37574
+ path: toRestoredPlaintextPath(file2.path),
37575
+ plaintext: file2.plaintext
37576
+ }));
37577
+ assertUniqueTargets(targets.map((file2) => file2.path));
37578
+ await fs8.mkdir(targetDir, { mode: 448, recursive: true });
37579
+ const outcomes = [];
37580
+ for (const file2 of targets) {
37581
+ outcomes.push(await restoreDecryptedFile({ ...file2, targetDir }));
37582
+ }
37583
+ return { fingerprint, outcomes };
37584
+ };
37585
+
37586
+ // src/encryptionBackup/verifyEncryptionBackupFile.ts
37587
+ var verifyEncryptionBackupFile = async ({
37588
+ backupPath,
37589
+ password
37590
+ }) => {
37591
+ const backup = await readEncryptionBackupFile(backupPath);
37592
+ const { files, fingerprint } = await decryptEncryptionBackup({
37593
+ backup,
37594
+ password
37595
+ });
37596
+ return { createdAt: backup.createdAt, fileCount: files.length, fingerprint };
37597
+ };
37598
+
37599
+ // src/encryptionBackup/runEncryptionBackupCommand.ts
37600
+ var plural = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
37601
+ var runEncryptionBackupCommand = async ({
37602
+ args,
37603
+ readClient,
37604
+ readPassword,
37605
+ render,
37606
+ subcommand,
37607
+ usage: usage2
37608
+ }) => {
37609
+ const [first, second] = args;
37610
+ if (!first || subcommand === "restore" && !second) {
37611
+ throw new Error(usage2);
37612
+ }
37613
+ if (subcommand === "backup") {
37614
+ const result = await createEncryptionBackupFile({
37615
+ client: readClient(),
37616
+ outputPath: first,
37617
+ password: await readPassword(),
37618
+ sourceDir: second ?? process.cwd()
37619
+ });
37620
+ render(
37621
+ `Backed up ${plural(result.fileCount, "encrypted file")} for identity ${formatEncryptionFingerprint(result.fingerprint)} to ${first}.`
37622
+ );
37623
+ for (const { path: path36, reason } of result.excluded) {
37624
+ render(`Not included (${reason.replaceAll("_", " ")}): ${path36}`);
37625
+ }
37626
+ encryptionBackupGuidance.forEach((line) => render(line));
37627
+ return;
37628
+ }
37629
+ if (subcommand === "verify-backup") {
37630
+ const result = await verifyEncryptionBackupFile({
37631
+ backupPath: first,
37632
+ password: await readPassword()
37633
+ });
37634
+ render(
37635
+ `Backup OK: ${plural(result.fileCount, "file")} for identity ${formatEncryptionFingerprint(result.fingerprint)}, created ${result.createdAt}. The password opens every file.`
37636
+ );
37637
+ return;
37638
+ }
37639
+ const { fingerprint, outcomes } = await restoreEncryptionBackupFile({
37640
+ backupPath: first,
37641
+ password: await readPassword(),
37642
+ targetDir: second
37643
+ });
37644
+ outcomes.forEach(({ path: path36, status }) => render(`${status}: ${path36}`));
37645
+ const conflicts = outcomes.filter((outcome) => outcome.status === "conflict");
37646
+ render(
37647
+ `Restored backup for identity ${formatEncryptionFingerprint(fingerprint)} into ${second}: ${plural(outcomes.length - conflicts.length, "file")} in place.`
37648
+ );
37649
+ if (conflicts.length) {
37650
+ throw new Error(
37651
+ `${plural(conflicts.length, "file")} already existed with different content and ${conflicts.length === 1 ? "was" : "were"} not overwritten. Move ${conflicts.length === 1 ? "it" : "them"} aside or restore into an empty directory.`
37652
+ );
37653
+ }
37654
+ };
37655
+
35010
37656
  // src/index.ts
35011
37657
  var getTextContent = (content) => content && "text" in content ? content.text : null;
35012
37658
  var RenderedCommandError = class extends Error {
@@ -35031,13 +37677,18 @@ Usage:
35031
37677
  fm file info <filePath> [--store <storeId>] [--token <jwt>]
35032
37678
  fm file move <sourcePath> <destinationPath> [--store <storeId>] [--token <jwt>]
35033
37679
  fm file delete <filePath> [--store <storeId>] [--token <jwt>]
35034
- fm file write <filePath> (<text>|--file|-f <localPath>) [--store <storeId>] [--token <jwt>] [--force]
37680
+ fm file write <filePath> [<text>|--file|-f <localPath>] [--store <storeId>] [--token <jwt>] [--force]
35035
37681
  fm hash <filePath> [--store <storeId>] [--token <jwt>] [--local]
35036
37682
  fm encrypt (<text>|--file|-f <localPath>) [--password <password>] [--token <jwt>]
35037
- fm decrypt (<encrypted-json>|--file|-f <localPath>) [--secret <recipient-secret>] [--password <password>] [--token <jwt>]
37683
+ fm decrypt (<encrypted-json>|--file|-f <localPath>) [--secret <recipient-secret>|--machine-key <machine-key>] [--expect-object <object-id>] [--min-revision <n>] [--password <password>] [--token <jwt>]
37684
+ fm decrypt-run <localPath> (--env|-e <NAME|OUTPUT=SOURCE_KEY>...|--all) [--secret-fd <n>|--password-fd <n>|--recipient] [--output redact|inherit|withhold] [--clean-env] -- <command> [args...]
35038
37685
  fm encrypt-add-recipient (<encrypted-json>|--file|-f <localPath>) --name <recipient-name> [--force [--reissue <label-or-id>]... [--remove <label-or-id>]...] [--json] [--password <password>] [--token <jwt>]
35039
- fm encrypt-rekey (<encrypted-json>|--file|-f <localPath>) [--remove <label-or-id>]... [--reissue <label-or-id>]... [--json] [--password <password>] [--token <jwt>]
37686
+ fm encrypt-rekey (<encrypted-json>|--file|-f <localPath>) [--remove <label-or-id>]... [--reissue <label-or-id>]... [--grant-machine <id-or-name>]... [--json] [--password <password>] [--token <jwt>]
37687
+ fm encrypt-add-machine (<encrypted-json>|--file|-f <localPath>) --machine <id-or-name>... [--fingerprint <fingerprint>] [--json] [--password <password>] [--token <jwt>]
35040
37688
  fm edit (<localPath>|--file|-f <localPath>) [--password <password>] [--token <jwt>]
37689
+ fm encryption backup <backup-file> [source-dir] [--password <password>] [--token <jwt>]
37690
+ fm encryption verify-backup <backup-file> [--password <password>]
37691
+ fm encryption restore <backup-file> <target-dir> [--password <password>]
35041
37692
  fm query <filename-or-path> [-s <storeIds>] [--token <jwt>]
35042
37693
  fm q <filename-or-path> [-s <storeIds>] [--token <jwt>]
35043
37694
  fm search <query> [--store <storeId>] [--fast|--deep] [--limit <n>] [--token <jwt>]
@@ -35063,9 +37714,11 @@ Usage:
35063
37714
  fm tree [path-filter] [--store <storeId>] [--token <jwt>]
35064
37715
  fm delete <filePath> [--store <storeId>] [--token <jwt>]
35065
37716
  fm rm <filePath> [--store <storeId>] [--token <jwt>]
35066
- fm write <filename-or-path> (<text>|--file|-f <localPath>) [-s <storeIds>] [--token <jwt>] [--force]
37717
+ fm write <filename-or-path> [<text>|--file|-f <localPath>] [-s <storeIds>] [--token <jwt>] [--force]
37718
+ write and file write read stdin when text and --file are omitted.
35067
37719
 
35068
37720
  fm skills --help
37721
+ fm machine --help read-only machine credentials for automation (create, list, show, rotate-token, replace-key, set-grants, revoke, files, fetch)
35069
37722
 
35070
37723
  Local checkout commands:
35071
37724
  fm clone <storeId> [localPath] [--token <jwt>] [--readonly] [--verbose]
@@ -35115,11 +37768,16 @@ Store creation:
35115
37768
  Auth:
35116
37769
  Provide a Clerk session token via --token or DOCTRINE_TOKEN.
35117
37770
  Encryption:
35118
- Provide your encryption password interactively, via --password, or via DOCTRINE_ENCRYPTION_PASSWORD.
35119
- To decrypt as an external recipient (no account/login), pass --secret <recipient-secret> or set DOCTRINE_RECIPIENT_SECRET.
37771
+ Provide your encryption password at the hidden prompt or via DOCTRINE_ENCRYPTION_PASSWORD from a secret manager. --password <password> still works but leaks into process lists and shell history.
37772
+ To decrypt as an external recipient (no account/login), set DOCTRINE_RECIPIENT_SECRET from your CI secret store. --secret <recipient-secret> has the same argv/history exposure.
37773
+ decrypt-run is the safe way to use secrets: it decrypts in memory and runs a command with only the selected values in its environment, without writing plaintext or inheriting Forum credentials. Use decrypt only for an explicit export. See fm decrypt-run --help.
37774
+ decrypt --expect-object/--min-revision refuse content from another encrypted object or an older revision (see the file's objectId and revision); without them any authentic version is accepted.
37775
+ To decrypt as a machine (no account/login, no token, offline), pass --machine-key <key> or set FORUM_MACHINE_KEY.
37776
+ encrypt-add-machine grants a machine credential's current key access to a file without rekeying. To replace a machine's old key, rekey: encrypt-rekey --remove <old-recipient> --grant-machine <machine>.
35120
37777
  encrypt-add-recipient grants a new external recipient (you must already be a recipient) and prints its doctrine-recipient-v1_ secret once \u2014 hand it to CI; with --file the secret is the only stdout line so SECRET=$(fm encrypt-add-recipient \u2026) captures it.
35121
37778
  encrypt-add-recipient --force replaces a same-name recipient by REKEYING the file (new file key, plaintext re-encrypted): the old secret cannot read the new or later versions. Remaining Forum users are kept by public key; other external recipients need --reissue (new secret) or --remove.
35122
37779
  encrypt-rekey revokes recipients (--remove) and/or reissues external secrets (--reissue) under a new file key. It refuses to drop anyone not named. Revocation covers future versions only \u2014 not earlier versions, backups, or already-copied plaintext/credentials.
37780
+ encryption backup writes your password-protected key record plus the encrypted files found in source-dir (default: current directory; use a checkout or an extracted store export) to a new file. It checks your password and proves every included file can be restored. verify-backup and restore work offline with no account; restore decrypts into target-dir and never overwrites existing files. Keep the backup and your encryption password separately: a lost password cannot be recovered.
35123
37781
  edit opens an encrypted file's plaintext in $EDITOR (fallback vi) and re-encrypts in place on save, keeping the SAME data key and recipients (unlike encrypt, which rotates the key and drops external recipients). Sync/commit afterward; run fm push for store-synced projects. Editing is not revocation: use encrypt-rekey to cut off a recipient.
35124
37782
  API:
35125
37783
  Uses ${DEFAULT_API_BASE_URL} by default. Set DOCTRINE_API_URL for local development.
@@ -35129,7 +37787,7 @@ Output:
35129
37787
  `;
35130
37788
  var readCliVersion = async () => {
35131
37789
  const packageJson = JSON.parse(
35132
- await readFile11(new URL("../package.json", import.meta.url), "utf8")
37790
+ await readFile12(new URL("../package.json", import.meta.url), "utf8")
35133
37791
  );
35134
37792
  return typeof packageJson.version === "string" ? packageJson.version : "unknown";
35135
37793
  };
@@ -35147,7 +37805,11 @@ var parseArgvCommandName = (argv) => {
35147
37805
  "--target",
35148
37806
  "--state-dir",
35149
37807
  "--interval-ms",
35150
- "--paths-file"
37808
+ "--paths-file",
37809
+ "--machine-key",
37810
+ "--machine",
37811
+ "--grant-machine",
37812
+ "--fingerprint"
35151
37813
  ]);
35152
37814
  for (let index = 0; index < argv.length; index += 1) {
35153
37815
  const current = argv[index];
@@ -35179,9 +37841,15 @@ var parseArgs = (argv) => {
35179
37841
  let ref = null;
35180
37842
  let encryptionPassword = null;
35181
37843
  let recipientSecret = null;
37844
+ let expectObjectId = null;
37845
+ let minRevision = null;
35182
37846
  let recipientName = null;
35183
37847
  const removeRecipients = [];
35184
37848
  const reissueRecipients = [];
37849
+ let machineKey = null;
37850
+ const machines = [];
37851
+ const grantMachines = [];
37852
+ let fingerprint = null;
35185
37853
  let syncPath = null;
35186
37854
  let syncTarget = null;
35187
37855
  let pathsFile = null;
@@ -35246,13 +37914,13 @@ var parseArgs = (argv) => {
35246
37914
  continue;
35247
37915
  }
35248
37916
  if (current === "--file" || current === "-f") {
35249
- inputFilePath = next ? path27.resolve(next) : inputFilePath;
37917
+ inputFilePath = next ? path35.resolve(next) : inputFilePath;
35250
37918
  index += 1;
35251
37919
  continue;
35252
37920
  }
35253
37921
  if (current === "--output" || current === "-o") {
35254
37922
  if (!next) throw new Error(`${current} requires a local output path.`);
35255
- outputFilePath = path27.resolve(next);
37923
+ outputFilePath = path35.resolve(next);
35256
37924
  index += 1;
35257
37925
  continue;
35258
37926
  }
@@ -35270,6 +37938,24 @@ var parseArgs = (argv) => {
35270
37938
  recipientSecret = current.slice("--secret=".length);
35271
37939
  continue;
35272
37940
  }
37941
+ if (current === "--expect-object") {
37942
+ expectObjectId = next ?? expectObjectId;
37943
+ index += 1;
37944
+ continue;
37945
+ }
37946
+ if (current.startsWith("--expect-object=")) {
37947
+ expectObjectId = current.slice("--expect-object=".length);
37948
+ continue;
37949
+ }
37950
+ if (current === "--min-revision") {
37951
+ minRevision = next ?? minRevision;
37952
+ index += 1;
37953
+ continue;
37954
+ }
37955
+ if (current.startsWith("--min-revision=")) {
37956
+ minRevision = current.slice("--min-revision=".length);
37957
+ continue;
37958
+ }
35273
37959
  if (current === "--name") {
35274
37960
  recipientName = next ?? recipientName;
35275
37961
  index += 1;
@@ -35279,6 +37965,24 @@ var parseArgs = (argv) => {
35279
37965
  recipientName = current.slice("--name=".length);
35280
37966
  continue;
35281
37967
  }
37968
+ if (current === "--machine-key") {
37969
+ if (!next) throw new Error("--machine-key requires a machine key.");
37970
+ machineKey = next;
37971
+ index += 1;
37972
+ continue;
37973
+ }
37974
+ if (current === "--machine" || current === "--grant-machine") {
37975
+ if (!next) throw new Error(`${current} requires a machine id or name.`);
37976
+ (current === "--machine" ? machines : grantMachines).push(next);
37977
+ index += 1;
37978
+ continue;
37979
+ }
37980
+ if (current === "--fingerprint") {
37981
+ if (!next) throw new Error("--fingerprint requires a key fingerprint.");
37982
+ fingerprint = next.replace(/\s+/g, "").toLowerCase();
37983
+ index += 1;
37984
+ continue;
37985
+ }
35282
37986
  if (current === "--remove" || current === "--reissue") {
35283
37987
  if (next) {
35284
37988
  (current === "--remove" ? removeRecipients : reissueRecipients).push(
@@ -35326,7 +38030,7 @@ var parseArgs = (argv) => {
35326
38030
  continue;
35327
38031
  }
35328
38032
  if (current === "--state-dir") {
35329
- stateDir = path27.resolve(next ?? stateDir);
38033
+ stateDir = path35.resolve(next ?? stateDir);
35330
38034
  index += 1;
35331
38035
  continue;
35332
38036
  }
@@ -35334,12 +38038,12 @@ var parseArgs = (argv) => {
35334
38038
  if (!next) {
35335
38039
  throw new Error("--paths-file requires a file path.");
35336
38040
  }
35337
- pathsFile = path27.resolve(expandHomePath(next));
38041
+ pathsFile = path35.resolve(expandHomePath(next));
35338
38042
  index += 1;
35339
38043
  continue;
35340
38044
  }
35341
38045
  if (current.startsWith("--paths-file=")) {
35342
- pathsFile = path27.resolve(
38046
+ pathsFile = path35.resolve(
35343
38047
  expandHomePath(current.slice("--paths-file=".length))
35344
38048
  );
35345
38049
  continue;
@@ -35437,6 +38141,12 @@ var parseArgs = (argv) => {
35437
38141
  ref,
35438
38142
  encryptionPassword,
35439
38143
  recipientSecret,
38144
+ expectObjectId,
38145
+ minRevision,
38146
+ machineKey,
38147
+ machines,
38148
+ grantMachines,
38149
+ fingerprint,
35440
38150
  recipientName,
35441
38151
  removeRecipients,
35442
38152
  reissueRecipients,
@@ -35463,20 +38173,20 @@ var parseArgs = (argv) => {
35463
38173
  version: version2
35464
38174
  };
35465
38175
  };
35466
- var describeCommand = (commandName, rest) => {
35467
- if (commandName === "sync" && rest[0] === "reset") {
38176
+ var describeCommand = (commandName2, rest) => {
38177
+ if (commandName2 === "sync" && rest[0] === "reset") {
35468
38178
  return "sync reset";
35469
38179
  }
35470
- return commandName;
38180
+ return commandName2;
35471
38181
  };
35472
- var supportsDryRun = (commandName, rest) => {
35473
- if (commandName === "push") {
38182
+ var supportsDryRun = (commandName2, rest) => {
38183
+ if (commandName2 === "push") {
35474
38184
  return true;
35475
38185
  }
35476
- if (commandName === "sync") {
38186
+ if (commandName2 === "sync") {
35477
38187
  return rest[0] !== "reset";
35478
38188
  }
35479
- return commandName === "encryption" && rest[0] === "migrate";
38189
+ return commandName2 === "encryption" && rest[0] === "migrate";
35480
38190
  };
35481
38191
  var assertDryRunSupported = (parsed, command, rest) => {
35482
38192
  if (!parsed.dryRun || supportsDryRun(command, rest)) {
@@ -35514,11 +38224,11 @@ var readEffectiveConfigSnapshot = async (parsed) => {
35514
38224
  effective
35515
38225
  };
35516
38226
  };
35517
- var ensureApiBaseUrl = (apiBaseUrl) => {
35518
- if (!apiBaseUrl) {
38227
+ var ensureApiBaseUrl = (apiBaseUrl2) => {
38228
+ if (!apiBaseUrl2) {
35519
38229
  throw new Error("Missing API URL. Set DOCTRINE_API_URL.");
35520
38230
  }
35521
- return apiBaseUrl;
38231
+ return apiBaseUrl2;
35522
38232
  };
35523
38233
  var listDirectoryEntries = async (listDirectory, directoryPath) => {
35524
38234
  const listing = await listDirectory({ directoryPath });
@@ -35533,10 +38243,10 @@ var listDirectoryEntries = async (listDirectory, directoryPath) => {
35533
38243
  if (left.type !== "directory" && right.type === "directory") {
35534
38244
  return 1;
35535
38245
  }
35536
- return path27.basename(left.path).localeCompare(path27.basename(right.path));
38246
+ return path35.basename(left.path).localeCompare(path35.basename(right.path));
35537
38247
  }).forEach((entry) => {
35538
38248
  const suffix = entry.type === "directory" ? "/" : "";
35539
- renderOutput(`${path27.basename(entry.path)}${suffix}`);
38249
+ renderOutput(`${path35.basename(entry.path)}${suffix}`);
35540
38250
  });
35541
38251
  };
35542
38252
  var listStores = async (listStoresMetadata) => {
@@ -35915,10 +38625,10 @@ var runFileCommand = async (subcommand, args, parsed, client) => {
35915
38625
  }
35916
38626
  if (subcommand === "write") {
35917
38627
  const filePath = args[0];
35918
- const text = await readWriteTextInput(args[1], parsed.inputFilePath);
38628
+ const text = filePath ? await readCommandTextInput(args[1], parsed.inputFilePath) : null;
35919
38629
  if (!filePath || text === null) {
35920
38630
  throw new Error(
35921
- `Missing arguments. Usage: ${commandNames} file write <filePath> <text|--file localPath>`
38631
+ `Missing arguments. Usage: ${commandNames} file write <filePath> [<text>|--file localPath] (or pipe text via stdin)`
35922
38632
  );
35923
38633
  }
35924
38634
  const file2 = await writeTextFile(
@@ -35940,7 +38650,7 @@ var readWriteTextInput = async (inlineText, inputFilePath) => {
35940
38650
  throw new Error("Provide either inline text or --file, not both.");
35941
38651
  }
35942
38652
  if (inputFilePath) {
35943
- return readFile11(inputFilePath, "utf8");
38653
+ return readFile12(inputFilePath, "utf8");
35944
38654
  }
35945
38655
  return inlineText ?? null;
35946
38656
  };
@@ -35956,7 +38666,7 @@ var readRemoteTextFile = async (filePath, storeRef, client) => {
35956
38666
  return text;
35957
38667
  };
35958
38668
  var normalizeRemotePath = (input) => {
35959
- const normalized = path27.posix.normalize(`/${input.trim()}`);
38669
+ const normalized = path35.posix.normalize(`/${input.trim()}`);
35960
38670
  if (normalized.includes("\0")) {
35961
38671
  throw new Error("Path contains an invalid null byte.");
35962
38672
  }
@@ -36250,7 +38960,7 @@ var diffRemoteFiles = async ({
36250
38960
  storeRef
36251
38961
  }) => {
36252
38962
  const leftText = await readRemoteTextFile(leftPath, storeRef, client);
36253
- const rightText = localRight ? await readFile11(path27.resolve(rightPath), "utf8") : await readRemoteTextFile(rightPath, storeRef, client);
38963
+ const rightText = localRight ? await readFile12(path35.resolve(rightPath), "utf8") : await readRemoteTextFile(rightPath, storeRef, client);
36254
38964
  return buildUnifiedDiff({
36255
38965
  leftLabel: leftPath,
36256
38966
  leftText,
@@ -36317,8 +39027,8 @@ var copyRemotePath = async (args, storeRef, client) => {
36317
39027
  (entry) => entry.path.startsWith(`${normalizedSource}/`)
36318
39028
  );
36319
39029
  for (const entry of descendants) {
36320
- const relativePath = path27.posix.relative(normalizedSource, entry.path);
36321
- const targetPath = path27.posix.join(normalizedDestination, relativePath);
39030
+ const relativePath = path35.posix.relative(normalizedSource, entry.path);
39031
+ const targetPath = path35.posix.join(normalizedDestination, relativePath);
36322
39032
  if (entry.type === "directory") {
36323
39033
  await createRemoteDirectory(targetPath, storeRef, client);
36324
39034
  continue;
@@ -36502,6 +39212,10 @@ var runEncryptCommand = async (rest, parsed, client) => {
36502
39212
  })
36503
39213
  );
36504
39214
  };
39215
+ var readEncryptedEnvelopeExpectation = (parsed) => parseEncryptedEnvelopeExpectation({
39216
+ minRevision: parsed.minRevision,
39217
+ objectId: parsed.expectObjectId
39218
+ });
36505
39219
  var runDecryptCommand = async (rest, parsed, client) => {
36506
39220
  const encryptedText = await readCommandTextInput(
36507
39221
  rest.length ? rest.join(" ") : void 0,
@@ -36509,9 +39223,10 @@ var runDecryptCommand = async (rest, parsed, client) => {
36509
39223
  );
36510
39224
  if (encryptedText === null) {
36511
39225
  throw new Error(
36512
- `Usage: ${commandNames} decrypt <encrypted-json|--file localPath> [--secret <recipient-secret>] [--password <password>]`
39226
+ `Usage: ${commandNames} decrypt <encrypted-json|--file localPath> [--secret <recipient-secret>] [--expect-object <object-id>] [--min-revision <n>] [--password <password>]`
36513
39227
  );
36514
39228
  }
39229
+ const expectation = readEncryptedEnvelopeExpectation(parsed);
36515
39230
  const [password, userEncryption] = await Promise.all([
36516
39231
  readEncryptionPassword(parsed),
36517
39232
  readUserEncryption(client)
@@ -36519,25 +39234,26 @@ var runDecryptCommand = async (rest, parsed, client) => {
36519
39234
  renderOutput(
36520
39235
  await decryptTextForUser({
36521
39236
  encryptedText,
39237
+ expectation,
36522
39238
  password,
36523
39239
  userEncryption: userEncryption.userEncryption
36524
39240
  })
36525
39241
  );
36526
39242
  };
36527
39243
  var runEditCommand = async (rest, parsed, client) => {
36528
- const filePath = parsed.inputFilePath ?? (rest[0] ? path27.resolve(rest[0]) : null);
39244
+ const filePath = parsed.inputFilePath ?? (rest[0] ? path35.resolve(rest[0]) : null);
36529
39245
  if (!filePath) {
36530
39246
  throw new Error(
36531
39247
  `Usage: ${commandNames} edit (<localPath>|--file|-f <localPath>) [--password <password>] [--token <jwt>]`
36532
39248
  );
36533
39249
  }
36534
- const encryptedText = await readFile11(filePath, "utf8");
39250
+ const encryptedText = await readFile12(filePath, "utf8");
36535
39251
  const [password, userEncryption] = await Promise.all([
36536
39252
  readEncryptionPassword(parsed),
36537
39253
  readUserEncryption(client)
36538
39254
  ]);
36539
39255
  const result = await editEncryptedText({
36540
- edit: (currentPlaintext) => openInEditor(currentPlaintext, { extension: path27.extname(filePath) }),
39256
+ edit: (currentPlaintext) => openInEditor(currentPlaintext, { extension: path35.extname(filePath) }),
36541
39257
  encryptedText,
36542
39258
  password,
36543
39259
  userEncryption: userEncryption.userEncryption
@@ -36562,12 +39278,92 @@ var runRecipientSecretDecryptCommand = async (rest, parsed) => {
36562
39278
  );
36563
39279
  if (encryptedText === null) {
36564
39280
  throw new Error(
36565
- `Usage: ${commandNames} decrypt <encrypted-json|--file localPath> [--secret <recipient-secret>] [--password <password>]`
39281
+ `Usage: ${commandNames} decrypt <encrypted-json|--file localPath> [--secret <recipient-secret>] [--expect-object <object-id>] [--min-revision <n>] [--password <password>]`
36566
39282
  );
36567
39283
  }
36568
39284
  process.stdout.write(
36569
- await decryptTextForRecipientSecret(encryptedText, parsed.recipientSecret)
39285
+ await decryptTextForRecipientSecret(
39286
+ encryptedText,
39287
+ parsed.recipientSecret,
39288
+ readEncryptedEnvelopeExpectation(parsed)
39289
+ )
39290
+ );
39291
+ };
39292
+ var runMachineKeyDecryptCommand = async (rest, parsed) => {
39293
+ const encryptedText = await readCommandTextInput(
39294
+ rest.length ? rest.join(" ") : void 0,
39295
+ parsed.inputFilePath
36570
39296
  );
39297
+ if (encryptedText === null) {
39298
+ throw new Error(
39299
+ `Usage: ${commandNames} decrypt <encrypted-json|--file localPath> [--machine-key <machine-key>] [--expect-object <object-id>] [--min-revision <n>]`
39300
+ );
39301
+ }
39302
+ registerRedactedSecret(parsed.machineKey);
39303
+ registerRedactedSecret(process.env[machineKeyEnvVar]);
39304
+ process.stdout.write(
39305
+ await decryptTextForMachineKey(
39306
+ encryptedText,
39307
+ parsed.machineKey,
39308
+ readEncryptedEnvelopeExpectation(parsed)
39309
+ )
39310
+ );
39311
+ };
39312
+ var createMachineRecipientLookup = (client) => (credentialIds) => client.readMachineRecipients({ credentialIds });
39313
+ var resolveMachineGrantRequests = async (client, refs, fingerprint) => {
39314
+ if (fingerprint && refs.length !== 1) {
39315
+ throw new Error("--fingerprint pins exactly one machine.");
39316
+ }
39317
+ const credentialIds = await resolveMachineCredentialRefs({ client, refs });
39318
+ return credentialIds.map((credentialId) => ({
39319
+ credentialId,
39320
+ ...fingerprint ? { expectedFingerprint: fingerprint } : {}
39321
+ }));
39322
+ };
39323
+ var runEncryptAddMachineCommand = async (rest, parsed, client) => {
39324
+ const usage2 = `Usage: ${commandNames} encrypt-add-machine (<encrypted-json>|--file <localPath>) --machine <id-or-name>... [--fingerprint <fingerprint>] [--json]`;
39325
+ if (!parsed.machines.length) {
39326
+ throw new Error(usage2);
39327
+ }
39328
+ const encryptedText = await readCommandTextInput(
39329
+ rest.length ? rest.join(" ") : void 0,
39330
+ parsed.inputFilePath
39331
+ );
39332
+ if (encryptedText === null) {
39333
+ throw new Error(usage2);
39334
+ }
39335
+ const [password, userEncryption, machines] = await Promise.all([
39336
+ readEncryptionPassword(parsed),
39337
+ readUserEncryption(client),
39338
+ resolveMachineGrantRequests(client, parsed.machines, parsed.fingerprint)
39339
+ ]);
39340
+ const result = await addMachineRecipientsToEncryptedText({
39341
+ encryptedText,
39342
+ lookupMachineRecipients: createMachineRecipientLookup(client),
39343
+ machines,
39344
+ password,
39345
+ userEncryption: userEncryption.userEncryption
39346
+ });
39347
+ if (parsed.inputFilePath) {
39348
+ await writeTextFileIfUnchanged({
39349
+ expectedText: encryptedText,
39350
+ filePath: parsed.inputFilePath,
39351
+ text: result.encryptedText
39352
+ });
39353
+ }
39354
+ if (parsed.json) {
39355
+ renderOutput({
39356
+ recipientIds: result.recipientIds,
39357
+ ...parsed.inputFilePath ? {} : { ciphertext: result.encryptedText }
39358
+ });
39359
+ return;
39360
+ }
39361
+ renderWarning(
39362
+ `Granted ${result.recipientIds.length} machine recipient(s). Sync or push the file so the machine can fetch it.`
39363
+ );
39364
+ if (!parsed.inputFilePath) {
39365
+ renderOutput(result.encryptedText);
39366
+ }
36571
39367
  };
36572
39368
  var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
36573
39369
  const name = parsed.recipientName?.trim();
@@ -36589,6 +39385,7 @@ var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
36589
39385
  const result = await addExternalRecipientToEncryptedText({
36590
39386
  encryptedText,
36591
39387
  force: parsed.force,
39388
+ lookupMachineRecipients: createMachineRecipientLookup(client),
36592
39389
  lookupPublicKeys: createPublicKeyLookup(client),
36593
39390
  name,
36594
39391
  password,
@@ -36673,8 +39470,15 @@ var runEncryptRekeyCommand = async (rest, parsed, client) => {
36673
39470
  readEncryptionPassword(parsed),
36674
39471
  readUserEncryption(client)
36675
39472
  ]);
39473
+ const grantMachines = parsed.grantMachines.length ? await resolveMachineGrantRequests(
39474
+ client,
39475
+ parsed.grantMachines,
39476
+ parsed.fingerprint
39477
+ ) : [];
36676
39478
  const result = await rekeyEncryptedTextForUser({
36677
39479
  encryptedText,
39480
+ grantMachines,
39481
+ lookupMachineRecipients: createMachineRecipientLookup(client),
36678
39482
  lookupPublicKeys: createPublicKeyLookup(client),
36679
39483
  password,
36680
39484
  reissue: parsed.reissueRecipients,
@@ -36702,11 +39506,11 @@ var runEncryptRekeyCommand = async (rest, parsed, client) => {
36702
39506
  parsed.inputFilePath ? `Updated ${parsed.inputFilePath}. Run \`${commandNames} push\` (and commit) for store-synced projects.` : result.encryptedText
36703
39507
  );
36704
39508
  };
36705
- var defaultEncryptionMigrationBackupPath = () => path27.resolve(process.cwd(), "doctrine-encryption-migration.json");
36706
- var readEncryptionMigrationBackup = async (backupPath) => JSON.parse(await readFile11(backupPath, "utf8"));
39509
+ var defaultEncryptionMigrationBackupPath = () => path35.resolve(process.cwd(), "doctrine-encryption-migration.json");
39510
+ var readEncryptionMigrationBackup = async (backupPath) => JSON.parse(await readFile12(backupPath, "utf8"));
36707
39511
  var writeEncryptionMigrationBackup = async (backupPath, backup) => {
36708
- await mkdir7(path27.dirname(backupPath), { recursive: true });
36709
- await writeFile6(backupPath, `${JSON.stringify(backup, null, 2)}
39512
+ await mkdir7(path35.dirname(backupPath), { recursive: true });
39513
+ await writeFile7(backupPath, `${JSON.stringify(backup, null, 2)}
36710
39514
  `, "utf8");
36711
39515
  };
36712
39516
  var confirmEncryptionMigration = async ({
@@ -36997,7 +39801,7 @@ var runEncryptionMigrateCommand = async (rest, parsed, client) => {
36997
39801
  `Usage: ${commandNames} encryption migrate [backup-file] [--store <storeId>] [--password <password>] [--dry-run] [--yes]`
36998
39802
  );
36999
39803
  }
37000
- const backupPath = path27.resolve(
39804
+ const backupPath = path35.resolve(
37001
39805
  rest[1] ?? defaultEncryptionMigrationBackupPath()
37002
39806
  );
37003
39807
  const password = await readEncryptionPassword(parsed);
@@ -37078,7 +39882,7 @@ var doesRemoteQueryMatchPath = (query, filePath) => {
37078
39882
  if (query.startsWith("/")) {
37079
39883
  return normalizedPath === query;
37080
39884
  }
37081
- const filename = path27.basename(filePath).toLowerCase();
39885
+ const filename = path35.basename(filePath).toLowerCase();
37082
39886
  return filename === query || normalizedPath === query || filename.includes(query) || normalizedPath.includes(query);
37083
39887
  };
37084
39888
  var queryRemoteFiles = async (query, storeFilters, client) => {
@@ -37150,7 +39954,7 @@ var printRemoteQueryMatches = (matches) => {
37150
39954
  });
37151
39955
  };
37152
39956
  var normalizeRemoteDirectoryPath = (input) => {
37153
- const normalized = path27.posix.normalize(`/${input.trim()}`);
39957
+ const normalized = path35.posix.normalize(`/${input.trim()}`);
37154
39958
  if (normalized.includes("\0")) {
37155
39959
  throw new Error("Path contains an invalid null byte.");
37156
39960
  }
@@ -37270,12 +40074,12 @@ var labelFromTreeDirectoryPath = (directoryPath) => {
37270
40074
  if (directoryPath === "/") {
37271
40075
  return "./";
37272
40076
  }
37273
- return `${path27.posix.basename(directoryPath)}/`;
40077
+ return `${path35.posix.basename(directoryPath)}/`;
37274
40078
  };
37275
40079
  var doesTreeFilterMatchDirectory = (filter, directoryPath) => {
37276
40080
  const normalizedFilter = filter.trim().toLowerCase();
37277
40081
  const normalizedPath = directoryPath.toLowerCase();
37278
- const basename3 = path27.posix.basename(directoryPath).toLowerCase();
40082
+ const basename3 = path35.posix.basename(directoryPath).toLowerCase();
37279
40083
  return basename3.includes(normalizedFilter) || normalizedPath.includes(normalizedFilter);
37280
40084
  };
37281
40085
  var resolveTreeDirectoryPath = async ({
@@ -37330,7 +40134,7 @@ var printRemoteTreeChildren = async ({
37330
40134
  const childPrefix = isLast ? " " : "\u2502 ";
37331
40135
  const suffix = entry.type === "directory" ? "/" : "";
37332
40136
  lines.push(
37333
- `${prefix}${connector}${path27.posix.basename(entry.path)}${suffix}`
40137
+ `${prefix}${connector}${path35.posix.basename(entry.path)}${suffix}`
37334
40138
  );
37335
40139
  if (entry.type === "directory") {
37336
40140
  await printRemoteTreeChildren({
@@ -37940,9 +40744,9 @@ var shouldPrintCheckoutDetail = (detail, verbose) => {
37940
40744
  var formatCheckoutDetail = (detail, options2) => {
37941
40745
  const status = checkoutStatusLabel(detail, options2);
37942
40746
  const direction = checkoutDirectionLabel(detail);
37943
- const path28 = formatCheckoutDetailPath(detail, options2.syncRules);
40747
+ const path36 = formatCheckoutDetailPath(detail, options2.syncRules);
37944
40748
  const reason = styleText.dim(checkoutDetailMessage(detail));
37945
- return direction ? `${direction} ${status} ${path28} ${reason}` : `${status} ${path28} ${reason}`;
40749
+ return direction ? `${direction} ${status} ${path36} ${reason}` : `${status} ${path36} ${reason}`;
37946
40750
  };
37947
40751
  var formatCheckoutDetailPath = (detail, syncRules) => {
37948
40752
  const localPath = formatLocalCheckoutPath(detail.relativePath);
@@ -38154,9 +40958,9 @@ var checkoutReportGroups = (details, options2) => {
38154
40958
  );
38155
40959
  };
38156
40960
  var checkoutReportDetailLine = (detail, options2) => {
38157
- const path28 = formatCheckoutDetailPath(detail, options2.syncRules);
40961
+ const path36 = formatCheckoutDetailPath(detail, options2.syncRules);
38158
40962
  const message = detail.status === "failed" || detail.status === "skipped" || detail.status === "ignored" ? detail.message ?? checkoutDetailMessage(detail) : "";
38159
- return message ? ` ${path28} ${styleText.dim(message)}` : ` ${path28}`;
40963
+ return message ? ` ${path36} ${styleText.dim(message)}` : ` ${path36}`;
38160
40964
  };
38161
40965
  var checkoutReportGroupBlock = ({
38162
40966
  dryRun,
@@ -38283,13 +41087,13 @@ var statusChangeKind = (detail) => {
38283
41087
  var formatStatusChange = (detail, syncRules) => {
38284
41088
  const kind = statusChangeKind(detail);
38285
41089
  const tone = kind === "deleted" ? "error" : kind === "added" ? "ok" : "warn";
38286
- const path28 = formatCheckoutDetailPath(detail, syncRules);
38287
- return ` ${styleText.color(tone, kind.padEnd(8))} ${path28}`;
41090
+ const path36 = formatCheckoutDetailPath(detail, syncRules);
41091
+ return ` ${styleText.color(tone, kind.padEnd(8))} ${path36}`;
38288
41092
  };
38289
41093
  var formatStatusBlock = (detail, syncRules) => {
38290
41094
  const message = detail.message ? ` ${styleText.dim(detail.message)}` : "";
38291
- const path28 = formatCheckoutDetailPath(detail, syncRules);
38292
- return ` ${styleText.color("error", "blocked ".padEnd(8))} ${path28}${message}`;
41095
+ const path36 = formatCheckoutDetailPath(detail, syncRules);
41096
+ return ` ${styleText.color("error", "blocked ".padEnd(8))} ${path36}${message}`;
38293
41097
  };
38294
41098
  var actionableStatusDetails = (result) => result.details.filter(
38295
41099
  (detail) => detail.status === "succeeded" || detail.status === "deleted"
@@ -38448,8 +41252,8 @@ var summarizeReferenceStructuralWrites = (details) => {
38448
41252
  counts.set(label, (counts.get(label) ?? 0) + 1);
38449
41253
  }
38450
41254
  return [...counts.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([label, count]) => {
38451
- const plural = label === "moved" ? "moves" : label === "created" ? "creates" : label === "delete" ? "deletes" : `${label}s`;
38452
- return `${count} ${count === 1 ? label : plural}`;
41255
+ const plural2 = label === "moved" ? "moves" : label === "created" ? "creates" : label === "delete" ? "deletes" : `${label}s`;
41256
+ return `${count} ${count === 1 ? label : plural2}`;
38453
41257
  }).join(", ");
38454
41258
  };
38455
41259
  var confirmReferenceStructuralWrites = async (details, assumeYes) => {
@@ -38948,15 +41752,15 @@ var runCheckoutStatus = async ({
38948
41752
  var isCheckoutStateGitPath = isCheckoutStateDirectoryPath;
38949
41753
  var checkoutFilesManifestPath2 = () => `${resolveCheckoutStateDirectoryName()}/files.json`;
38950
41754
  var isInsideOrEqual = (parentPath, childPath2) => {
38951
- const relativePath = path27.relative(parentPath, childPath2);
38952
- return relativePath === "" || !relativePath.startsWith("..") && !path27.isAbsolute(relativePath);
41755
+ const relativePath = path35.relative(parentPath, childPath2);
41756
+ return relativePath === "" || !relativePath.startsWith("..") && !path35.isAbsolute(relativePath);
38953
41757
  };
38954
41758
  var resolveSyncTargetPaths = (checkout) => checkout.syncRules.map(
38955
- (rule) => path27.resolve(checkout.rootDir, rule.target || ".")
41759
+ (rule) => path35.resolve(checkout.rootDir, rule.target || ".")
38956
41760
  );
38957
- var resolveCheckoutManifestGitPath = (checkout, gitRoot) => path27.relative(
41761
+ var resolveCheckoutManifestGitPath = (checkout, gitRoot) => path35.relative(
38958
41762
  gitRoot,
38959
- path27.join(checkout.rootDir, checkoutFilesManifestPath2())
41763
+ path35.join(checkout.rootDir, checkoutFilesManifestPath2())
38960
41764
  ) || checkoutFilesManifestPath2();
38961
41765
  var stageCheckoutManifest = async ({
38962
41766
  checkout,
@@ -38982,7 +41786,7 @@ var assertGitChangesStayInSyncTargets = async ({
38982
41786
  if (isCheckoutStateGitPath(entry.path)) {
38983
41787
  return false;
38984
41788
  }
38985
- const absolutePath = path27.resolve(gitRoot, entry.path);
41789
+ const absolutePath = path35.resolve(gitRoot, entry.path);
38986
41790
  return !allowedPaths.some(
38987
41791
  (allowedPath) => isInsideOrEqual(allowedPath, absolutePath)
38988
41792
  );
@@ -39004,7 +41808,7 @@ var stageGitSyncTargets = async ({
39004
41808
  }) => {
39005
41809
  const targetPaths = [];
39006
41810
  for (const targetPath of resolveSyncTargetPaths(checkout)) {
39007
- const relativePath = path27.relative(gitRoot, targetPath) || ".";
41811
+ const relativePath = path35.relative(gitRoot, targetPath) || ".";
39008
41812
  const tracked = await runGit(gitRoot, ["ls-files", "--", relativePath]);
39009
41813
  if (await pathExists3(targetPath) || tracked.stdout.trim()) {
39010
41814
  targetPaths.push(relativePath);
@@ -39304,7 +42108,7 @@ var writeCheckoutConfig = async (directoryPath, metadata, workspaceSlug, options
39304
42108
  );
39305
42109
  }
39306
42110
  await writeForumProjectConfig(
39307
- path27.join(directoryPath, defaultProjectConfigFilename),
42111
+ path35.join(directoryPath, defaultProjectConfigFilename),
39308
42112
  {
39309
42113
  syncRules: [
39310
42114
  {
@@ -39341,7 +42145,7 @@ var normalizeProjectConfigPath = (value, fieldName, allowCurrentDirectory = fals
39341
42145
  }
39342
42146
  throw new Error(`${fieldName} must be a non-empty relative path.`);
39343
42147
  }
39344
- if (path27.isAbsolute(value)) {
42148
+ if (path35.isAbsolute(value)) {
39345
42149
  throw new Error(`${fieldName} must be a relative path.`);
39346
42150
  }
39347
42151
  const segments2 = trimmed.split("/");
@@ -39523,7 +42327,7 @@ var defaultCloneDirectoryName = (storeId) => {
39523
42327
  var fsErrorCode = (error51) => error51 instanceof Error && "code" in error51 ? String(error51.code ?? "") : "";
39524
42328
  var ensureGitMetadataExists = async (directoryPath) => {
39525
42329
  try {
39526
- await lstat6(path27.join(directoryPath, ".git"));
42330
+ await lstat6(path35.join(directoryPath, ".git"));
39527
42331
  } catch (error51) {
39528
42332
  if (fsErrorCode(error51) === "ENOENT") {
39529
42333
  throw new Error(
@@ -39561,8 +42365,8 @@ var confirmGitMetadataDeletion = async (localPath, assumeYes) => {
39561
42365
  "Refusing to delete .git without interactive confirmation. Rerun with --yes to confirm in a non-interactive shell."
39562
42366
  );
39563
42367
  }
39564
- const gitPath = path27.join(localPath, ".git");
39565
- const gitignorePath = path27.join(localPath, ".gitignore");
42368
+ const gitPath = path35.join(localPath, ".git");
42369
+ const gitignorePath = path35.join(localPath, ".gitignore");
39566
42370
  const confirmationPhrase = "DELETE GIT";
39567
42371
  renderWarning("");
39568
42372
  renderWarning("DANGER: Forum is about to remove Git from this checkout.");
@@ -39608,7 +42412,7 @@ var runGitConvertCommand = async ({
39608
42412
  );
39609
42413
  }
39610
42414
  await writeForumProjectConfig(
39611
- path27.join(localPath, defaultProjectConfigFilename),
42415
+ path35.join(localPath, defaultProjectConfigFilename),
39612
42416
  {
39613
42417
  syncRules: [
39614
42418
  {
@@ -39670,18 +42474,44 @@ var runGitConvertCommand = async ({
39670
42474
  "Aborted before deleting Git metadata. The Forum push completed, but .git and .gitignore were left in place."
39671
42475
  );
39672
42476
  }
39673
- await rm8(path27.join(localPath, ".gitignore"), { force: true });
39674
- await rm8(path27.join(localPath, ".git"), { recursive: true, force: true });
42477
+ await rm8(path35.join(localPath, ".gitignore"), { force: true });
42478
+ await rm8(path35.join(localPath, ".git"), { recursive: true, force: true });
39675
42479
  renderOutput(
39676
42480
  `${created ? "Created" : "Using existing"} store ${metadata.slug}`
39677
42481
  );
39678
42482
  renderOutput(`Converted Git repository to Forum checkout at ${localPath}`);
39679
42483
  };
42484
+ var decryptRunAsUser = async ({
42485
+ accountArgs,
42486
+ encryptedText,
42487
+ password
42488
+ }) => {
42489
+ const parsed = parseArgs(accountArgs);
42490
+ await ensureStateDir(parsed.stateDir);
42491
+ const config2 = await resolveConfig(parsed);
42492
+ const client = createClient({
42493
+ ...config2,
42494
+ apiBaseUrl: ensureApiBaseUrl(config2.apiBaseUrl)
42495
+ });
42496
+ const { userEncryption } = await readUserEncryption(client);
42497
+ return decryptTextForUser({ encryptedText, password, userEncryption });
42498
+ };
39680
42499
  var main = async (argv = process.argv.slice(2)) => {
39681
42500
  if (parseArgvCommandName(argv) === "skills") {
39682
42501
  await runSkillsCommand(argv);
39683
42502
  return;
39684
42503
  }
42504
+ if (parseArgvCommandName(argv) === "decrypt-run") {
42505
+ process.exitCode = await runDecryptRunCommand({
42506
+ argv,
42507
+ decryptAsUser: decryptRunAsUser
42508
+ });
42509
+ return;
42510
+ }
42511
+ if (parseArgvCommandName(argv) === "machine") {
42512
+ await runMachineCommand(argv);
42513
+ return;
42514
+ }
39685
42515
  const parsed = parseArgs(argv);
39686
42516
  configureRenderer({ json: parsed.json });
39687
42517
  let [command, ...rest] = parsed.args;
@@ -39718,11 +42548,11 @@ var main = async (argv = process.argv.slice(2)) => {
39718
42548
  const subcommand = rest[0];
39719
42549
  const config3 = await resolveConfig(parsed);
39720
42550
  if (subcommand === "login") {
39721
- const apiBaseUrl2 = ensureApiBaseUrl(config3.apiBaseUrl);
42551
+ const apiBaseUrl3 = ensureApiBaseUrl(config3.apiBaseUrl);
39722
42552
  const token = await withActivity(
39723
42553
  "Starting login",
39724
42554
  () => interactiveLogin({
39725
- apiBaseUrl: apiBaseUrl2,
42555
+ apiBaseUrl: apiBaseUrl3,
39726
42556
  openBrowser: parsed.openBrowser
39727
42557
  })
39728
42558
  );
@@ -39827,7 +42657,7 @@ var main = async (argv = process.argv.slice(2)) => {
39827
42657
  }
39828
42658
  if (command === "hash" && parsed.local) {
39829
42659
  const filePath = rest[0];
39830
- renderOutput(await hashLocalFile(path27.resolve(filePath)));
42660
+ renderOutput(await hashLocalFile(path35.resolve(filePath)));
39831
42661
  return;
39832
42662
  }
39833
42663
  const config2 = await resolveConfig(parsed);
@@ -39843,17 +42673,37 @@ var main = async (argv = process.argv.slice(2)) => {
39843
42673
  if (command === "decrypt") {
39844
42674
  const authMode = resolveDecryptAuthMode({
39845
42675
  encryptionPassword: parsed.encryptionPassword,
42676
+ hasMachineKeyEnv: Boolean(process.env[machineKeyEnvVar]),
39846
42677
  hasRecipientSecretEnv: Boolean(process.env.DOCTRINE_RECIPIENT_SECRET),
42678
+ machineKey: parsed.machineKey,
39847
42679
  recipientSecret: parsed.recipientSecret,
39848
42680
  token: parsed.token
39849
42681
  });
42682
+ if (authMode === "machine-key") {
42683
+ await runMachineKeyDecryptCommand(rest, parsed);
42684
+ return;
42685
+ }
39850
42686
  if (authMode === "recipient-secret") {
39851
42687
  await runRecipientSecretDecryptCommand(rest, parsed);
39852
42688
  return;
39853
42689
  }
39854
42690
  }
39855
- const apiBaseUrl = ensureApiBaseUrl(config2.apiBaseUrl);
39856
- const client = createClient({ ...config2, apiBaseUrl });
42691
+ if (command === "encryption" && isEncryptionBackupSubcommand(rest[0])) {
42692
+ await runEncryptionBackupCommand({
42693
+ args: rest.slice(1),
42694
+ readClient: () => createClient({
42695
+ ...config2,
42696
+ apiBaseUrl: ensureApiBaseUrl(config2.apiBaseUrl)
42697
+ }),
42698
+ readPassword: () => readEncryptionPassword(parsed),
42699
+ render: renderOutput,
42700
+ subcommand: rest[0],
42701
+ usage: `Usage: ${commandNames} encryption backup <backup-file> [source-dir] | verify-backup <backup-file> | restore <backup-file> <target-dir> [--password <password>]`
42702
+ });
42703
+ return;
42704
+ }
42705
+ const apiBaseUrl2 = ensureApiBaseUrl(config2.apiBaseUrl);
42706
+ const client = createClient({ ...config2, apiBaseUrl: apiBaseUrl2 });
39857
42707
  if (command === "encrypt") {
39858
42708
  await runEncryptCommand(rest, parsed, client);
39859
42709
  return;
@@ -39866,6 +42716,10 @@ var main = async (argv = process.argv.slice(2)) => {
39866
42716
  await runEncryptAddRecipientCommand(rest, parsed, client);
39867
42717
  return;
39868
42718
  }
42719
+ if (command === "encrypt-add-machine") {
42720
+ await runEncryptAddMachineCommand(rest, parsed, client);
42721
+ return;
42722
+ }
39869
42723
  if (command === "decrypt") {
39870
42724
  await runDecryptCommand(rest, parsed, client);
39871
42725
  return;
@@ -40333,8 +43187,8 @@ var main = async (argv = process.argv.slice(2)) => {
40333
43187
  `Usage: ${commandNames} clone <storeId> [localPath] [--readonly]`
40334
43188
  );
40335
43189
  }
40336
- const localPath = path27.resolve(
40337
- rest[1] ?? path27.join(process.cwd(), defaultCloneDirectoryName(remoteInput))
43190
+ const localPath = path35.resolve(
43191
+ rest[1] ?? path35.join(process.cwd(), defaultCloneDirectoryName(remoteInput))
40338
43192
  );
40339
43193
  const { metadata, workspaceSlug, storeRef } = await resolveReadableStore(
40340
43194
  remoteInput,
@@ -40362,7 +43216,7 @@ var main = async (argv = process.argv.slice(2)) => {
40362
43216
  storeRef,
40363
43217
  syncRules: checkout.syncRules
40364
43218
  });
40365
- renderOutput(`Cloned store ${metadata.slug} to ${path27.resolve(localPath)}`);
43219
+ renderOutput(`Cloned store ${metadata.slug} to ${path35.resolve(localPath)}`);
40366
43220
  formatCheckoutResult("Pulled", result, {
40367
43221
  detailsRendered: Boolean(progress),
40368
43222
  verbose: parsed.verbose
@@ -40412,7 +43266,7 @@ var main = async (argv = process.argv.slice(2)) => {
40412
43266
  });
40413
43267
  result.warnings.forEach((warning) => renderWarning(warning));
40414
43268
  if (parsed.outputFilePath) {
40415
- await writeFile6(parsed.outputFilePath, result.text, "utf8");
43269
+ await writeFile7(parsed.outputFilePath, result.text, "utf8");
40416
43270
  } else {
40417
43271
  renderOutput(result.text);
40418
43272
  }
@@ -40592,10 +43446,10 @@ var main = async (argv = process.argv.slice(2)) => {
40592
43446
  }
40593
43447
  if (command === "write") {
40594
43448
  const query = rest[0];
40595
- const text = await readWriteTextInput(rest[1], parsed.inputFilePath);
43449
+ const text = query ? await readCommandTextInput(rest[1], parsed.inputFilePath) : null;
40596
43450
  if (!query || text === null) {
40597
43451
  throw new Error(
40598
- `Missing arguments. Usage: ${commandNames} write <filename-or-path> <text|--file localPath>`
43452
+ `Missing arguments. Usage: ${commandNames} write <filename-or-path> [<text>|--file localPath] (or pipe text via stdin)`
40599
43453
  );
40600
43454
  }
40601
43455
  const storeRef = await resolveOptionalSingleStoreRef(