@mp-lb/forum-cli 0.1.49 → 0.1.51

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 path25 of paths) {
1883
- const rule = rules.find((candidate) => candidate.matches(path25));
1882
+ for (const path28 of paths) {
1883
+ const rule = rules.find((candidate) => candidate.matches(path28));
1884
1884
  if (!rule) continue;
1885
1885
  const existing = grouped.get(rule);
1886
- if (existing) existing.push(path25);
1887
- else grouped.set(rule, [path25]);
1886
+ if (existing) existing.push(path28);
1887
+ else grouped.set(rule, [path28]);
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 path24 from "path";
2106
- import { lstat as lstat5, mkdir as mkdir7, readFile as readFile10, rm as rm6, writeFile as writeFile7 } from "fs/promises";
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";
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, path25) {
2877
- if (!path25)
2876
+ function getElementAtPath(obj, path28) {
2877
+ if (!path28)
2878
2878
  return obj;
2879
- return path25.reduce((acc, key) => acc?.[key], obj);
2879
+ return path28.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(path25, issues) {
3288
+ function prefixIssues(path28, issues) {
3289
3289
  return issues.map((iss) => {
3290
3290
  var _a3;
3291
3291
  (_a3 = iss).path ?? (_a3.path = []);
3292
- iss.path.unshift(path25);
3292
+ iss.path.unshift(path28);
3293
3293
  return iss;
3294
3294
  });
3295
3295
  }
@@ -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, path25 = []) => {
3439
+ const processError = (error52, path28 = []) => {
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 }, [...path25, ...issue2.path]));
3442
+ issue2.errors.map((issues) => processError({ issues }, [...path28, ...issue2.path]));
3443
3443
  } else if (issue2.code === "invalid_key") {
3444
- processError({ issues: issue2.issues }, [...path25, ...issue2.path]);
3444
+ processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3445
3445
  } else if (issue2.code === "invalid_element") {
3446
- processError({ issues: issue2.issues }, [...path25, ...issue2.path]);
3446
+ processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3447
3447
  } else {
3448
- const fullpath = [...path25, ...issue2.path];
3448
+ const fullpath = [...path28, ...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, path25 = []) => {
3475
+ const processError = (error52, path28 = []) => {
3476
3476
  var _a3, _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 }, [...path25, ...issue2.path]));
3479
+ issue2.errors.map((issues) => processError({ issues }, [...path28, ...issue2.path]));
3480
3480
  } else if (issue2.code === "invalid_key") {
3481
- processError({ issues: issue2.issues }, [...path25, ...issue2.path]);
3481
+ processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3482
3482
  } else if (issue2.code === "invalid_element") {
3483
- processError({ issues: issue2.issues }, [...path25, ...issue2.path]);
3483
+ processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
3484
3484
  } else {
3485
- const fullpath = [...path25, ...issue2.path];
3485
+ const fullpath = [...path28, ...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 path25 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3518
- for (const seg of path25) {
3517
+ const path28 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3518
+ for (const seg of path28) {
3519
3519
  if (typeof seg === "number")
3520
3520
  segs.push(`[${seg}]`);
3521
3521
  else if (typeof seg === "symbol")
@@ -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 path25 = ref.slice(1).split("/").filter(Boolean);
16211
- if (path25.length === 0) {
16210
+ const path28 = ref.slice(1).split("/").filter(Boolean);
16211
+ if (path28.length === 0) {
16212
16212
  return ctx.rootSchema;
16213
16213
  }
16214
16214
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
16215
- if (path25[0] === defsKey) {
16216
- const key = path25[1];
16215
+ if (path28[0] === defsKey) {
16216
+ const key = path28[1];
16217
16217
  if (!key || !ctx.defs[key]) {
16218
16218
  throw new Error(`Reference not found: ${ref}`);
16219
16219
  }
@@ -16621,6 +16621,110 @@ function date4(params) {
16621
16621
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
16622
16622
  config(en_default());
16623
16623
 
16624
+ // ../../packages/encryption/src/bytes/base64ToBytes.ts
16625
+ var base64ToBytes = (base643) => {
16626
+ const binary = atob(base643);
16627
+ const bytes = new Uint8Array(binary.length);
16628
+ for (let index = 0; index < binary.length; index += 1) {
16629
+ bytes[index] = binary.charCodeAt(index);
16630
+ }
16631
+ return bytes;
16632
+ };
16633
+
16634
+ // ../../packages/encryption/src/bytes/bytesToBase64.ts
16635
+ var bytesToBase64 = (bytes) => {
16636
+ let binary = "";
16637
+ for (const byte of bytes) {
16638
+ binary += String.fromCharCode(byte);
16639
+ }
16640
+ return btoa(binary);
16641
+ };
16642
+
16643
+ // ../../packages/encryption/src/bytes/toBufferSource.ts
16644
+ var toBufferSource = (bytes) => bytes.buffer.slice(
16645
+ bytes.byteOffset,
16646
+ bytes.byteOffset + bytes.byteLength
16647
+ );
16648
+
16649
+ // ../../packages/encryption/src/keyBinding/UserEncryptionKeyMismatchError.ts
16650
+ var UserEncryptionKeyMismatchError = class extends Error {
16651
+ constructor(message = "Encryption key record is inconsistent: its public key does not match the protected private key.") {
16652
+ super(message);
16653
+ this.name = "UserEncryptionKeyMismatchError";
16654
+ }
16655
+ };
16656
+
16657
+ // ../../packages/encryption/src/keyBinding/assertPrivateKeyMatchesPublicKey.ts
16658
+ var rsaAlgorithm = { hash: "SHA-256", name: "RSA-OAEP" };
16659
+ var exportRsaComponents = async (format, bytes) => {
16660
+ const key = await crypto.subtle.importKey(
16661
+ format,
16662
+ toBufferSource(bytes),
16663
+ rsaAlgorithm,
16664
+ true,
16665
+ format === "pkcs8" ? ["decrypt"] : ["encrypt"]
16666
+ );
16667
+ return crypto.subtle.exportKey("jwk", key);
16668
+ };
16669
+ var assertPrivateKeyMatchesPublicKey = async ({
16670
+ privateKeyBytes,
16671
+ publicKey
16672
+ }) => {
16673
+ let privateComponents;
16674
+ let publicComponents;
16675
+ try {
16676
+ [privateComponents, publicComponents] = await Promise.all([
16677
+ exportRsaComponents("pkcs8", privateKeyBytes),
16678
+ exportRsaComponents("spki", base64ToBytes(publicKey.data))
16679
+ ]);
16680
+ } catch {
16681
+ throw new UserEncryptionKeyMismatchError();
16682
+ }
16683
+ if (!privateComponents.n || privateComponents.n !== publicComponents.n || privateComponents.e !== publicComponents.e) {
16684
+ throw new UserEncryptionKeyMismatchError();
16685
+ }
16686
+ };
16687
+
16688
+ // ../../packages/encryption/src/bytes/bytesToHex.ts
16689
+ var bytesToHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
16690
+
16691
+ // ../../packages/encryption/src/keyBinding/computeEncryptionFingerprint.ts
16692
+ var computeEncryptionFingerprint = async (publicKey) => bytesToHex(
16693
+ new Uint8Array(
16694
+ await crypto.subtle.digest(
16695
+ "SHA-256",
16696
+ toBufferSource(base64ToBytes(publicKey.data))
16697
+ )
16698
+ )
16699
+ );
16700
+
16701
+ // ../../packages/encryption/src/keyBinding/createUserEncryptionKeyBinding.ts
16702
+ var userEncryptionKeyBindingPurpose = "forum-user-encryption-key";
16703
+ var textEncoder = new TextEncoder();
16704
+ var createUserEncryptionKeyBinding = (metadata) => textEncoder.encode(
16705
+ JSON.stringify([
16706
+ userEncryptionKeyBindingPurpose,
16707
+ metadata.version,
16708
+ metadata.keyId,
16709
+ metadata.kdf.name,
16710
+ metadata.kdf.iterations,
16711
+ metadata.kdf.salt,
16712
+ metadata.publicKey.algorithm,
16713
+ metadata.publicKey.data
16714
+ ])
16715
+ );
16716
+
16717
+ // ../../packages/encryption/src/keyBinding/verifyUserEncryptionPublicKey.ts
16718
+ var verifyUserEncryptionPublicKey = async (record2) => {
16719
+ const fingerprint = await computeEncryptionFingerprint(record2.publicKey);
16720
+ if (record2.version === 3 && record2.keyId !== fingerprint) {
16721
+ throw new UserEncryptionKeyMismatchError(
16722
+ "Encryption key record is inconsistent: its key id does not match its public key fingerprint."
16723
+ );
16724
+ }
16725
+ return fingerprint;
16726
+ };
16727
+
16624
16728
  // ../../packages/encryption/src/fileEncryption.ts
16625
16729
  var legacyEncryptedFileVersion = 2;
16626
16730
  var currentEncryptedFileVersion = 3;
@@ -16689,29 +16793,50 @@ var legacyUserEncryptionMetadataSchema = external_exports.object({
16689
16793
  wrappedUserKey: encryptedValueSchema,
16690
16794
  verification: encryptedValueSchema
16691
16795
  });
16692
- var currentUserEncryptionMetadataSchema = external_exports.object({
16796
+ var userEncryptionKdfSchema = external_exports.object({
16797
+ name: external_exports.literal(encryptedFileKdf),
16798
+ iterations: external_exports.number().int().positive(),
16799
+ salt: external_exports.string().trim().min(1)
16800
+ });
16801
+ var encryptionFingerprintSchema = external_exports.string().regex(/^[0-9a-f]{64}$/, "Expected a lowercase hex SHA-256 fingerprint.");
16802
+ var unboundUserEncryptionMetadataSchema = external_exports.object({
16693
16803
  version: external_exports.literal(2),
16694
16804
  keyId: external_exports.string().trim().min(1),
16695
- kdf: external_exports.object({
16696
- name: external_exports.literal(encryptedFileKdf),
16697
- iterations: external_exports.number().int().positive(),
16698
- salt: external_exports.string().trim().min(1)
16699
- }),
16805
+ kdf: userEncryptionKdfSchema,
16700
16806
  publicKey: publicKeyValueSchema,
16701
16807
  wrappedPrivateKey: encryptedValueSchema
16702
16808
  });
16703
- var userEncryptionPublicKeySchema = external_exports.object({
16704
- version: external_exports.literal(2),
16705
- keyId: external_exports.string().trim().min(1),
16706
- publicKey: publicKeyValueSchema
16809
+ var boundUserEncryptionMetadataSchema = external_exports.object({
16810
+ version: external_exports.literal(3),
16811
+ keyId: encryptionFingerprintSchema,
16812
+ kdf: userEncryptionKdfSchema,
16813
+ publicKey: publicKeyValueSchema,
16814
+ wrappedPrivateKey: encryptedValueSchema
16707
16815
  });
16816
+ var currentUserEncryptionMetadataSchema = external_exports.discriminatedUnion(
16817
+ "version",
16818
+ [unboundUserEncryptionMetadataSchema, boundUserEncryptionMetadataSchema]
16819
+ );
16820
+ var userEncryptionPublicKeySchema = external_exports.discriminatedUnion("version", [
16821
+ external_exports.object({
16822
+ version: external_exports.literal(2),
16823
+ keyId: external_exports.string().trim().min(1),
16824
+ publicKey: publicKeyValueSchema
16825
+ }),
16826
+ external_exports.object({
16827
+ version: external_exports.literal(3),
16828
+ keyId: encryptionFingerprintSchema,
16829
+ publicKey: publicKeyValueSchema
16830
+ })
16831
+ ]);
16708
16832
  var userEncryptionMetadataSchema = external_exports.union([
16709
16833
  legacyUserEncryptionMetadataSchema,
16710
- currentUserEncryptionMetadataSchema
16834
+ unboundUserEncryptionMetadataSchema,
16835
+ boundUserEncryptionMetadataSchema
16711
16836
  ]);
16712
- var textEncoder = new TextEncoder();
16837
+ var textEncoder2 = new TextEncoder();
16713
16838
  var textDecoder = new TextDecoder();
16714
- var rsaAlgorithm = {
16839
+ var rsaAlgorithm2 = {
16715
16840
  hash: "SHA-256",
16716
16841
  name: "RSA-OAEP"
16717
16842
  };
@@ -16721,30 +16846,11 @@ var rsaKeyGenerationAlgorithm = {
16721
16846
  name: "RSA-OAEP",
16722
16847
  publicExponent: Uint8Array.from([1, 0, 1])
16723
16848
  };
16724
- var bytesToBase64 = (bytes) => {
16725
- let binary = "";
16726
- for (const byte of bytes) {
16727
- binary += String.fromCharCode(byte);
16728
- }
16729
- return btoa(binary);
16730
- };
16731
- var base64ToBytes = (base643) => {
16732
- const binary = atob(base643);
16733
- const bytes = new Uint8Array(binary.length);
16734
- for (let index = 0; index < binary.length; index += 1) {
16735
- bytes[index] = binary.charCodeAt(index);
16736
- }
16737
- return bytes;
16738
- };
16739
16849
  var createRandomBytes = (length) => {
16740
16850
  const bytes = new Uint8Array(length);
16741
16851
  crypto.getRandomValues(bytes);
16742
16852
  return bytes;
16743
16853
  };
16744
- var toBufferSource = (bytes) => bytes.buffer.slice(
16745
- bytes.byteOffset,
16746
- bytes.byteOffset + bytes.byteLength
16747
- );
16748
16854
  var createIv = () => createRandomBytes(12);
16749
16855
  var importAesKey = async (bytes, extractable) => crypto.subtle.importKey(
16750
16856
  "raw",
@@ -16755,7 +16861,7 @@ var importAesKey = async (bytes, extractable) => crypto.subtle.importKey(
16755
16861
  );
16756
16862
  var importPasswordKey = async (password) => crypto.subtle.importKey(
16757
16863
  "raw",
16758
- toBufferSource(textEncoder.encode(password)),
16864
+ toBufferSource(textEncoder2.encode(password)),
16759
16865
  "PBKDF2",
16760
16866
  false,
16761
16867
  ["deriveKey"]
@@ -16779,11 +16885,16 @@ var derivePasswordKey = async ({
16779
16885
  ["decrypt", "encrypt"]
16780
16886
  );
16781
16887
  };
16782
- var encryptBytes = async (key, bytes) => {
16888
+ var createAesGcmParams = (iv, additionalData) => ({
16889
+ iv: toBufferSource(iv),
16890
+ name: encryptedFileCipher,
16891
+ ...additionalData ? { additionalData: toBufferSource(additionalData) } : {}
16892
+ });
16893
+ var encryptBytes = async (key, bytes, additionalData) => {
16783
16894
  const iv = createIv();
16784
16895
  const encryptedBytes = new Uint8Array(
16785
16896
  await crypto.subtle.encrypt(
16786
- { iv: toBufferSource(iv), name: encryptedFileCipher },
16897
+ createAesGcmParams(iv, additionalData),
16787
16898
  key,
16788
16899
  toBufferSource(bytes)
16789
16900
  )
@@ -16794,12 +16905,13 @@ var encryptBytes = async (key, bytes) => {
16794
16905
  };
16795
16906
  };
16796
16907
  var decryptBytes = async ({
16908
+ additionalData,
16797
16909
  data,
16798
16910
  iv,
16799
16911
  key
16800
16912
  }) => new Uint8Array(
16801
16913
  await crypto.subtle.decrypt(
16802
- { iv: toBufferSource(base64ToBytes(iv)), name: encryptedFileCipher },
16914
+ createAesGcmParams(base64ToBytes(iv), additionalData),
16803
16915
  key,
16804
16916
  toBufferSource(base64ToBytes(data))
16805
16917
  )
@@ -16808,11 +16920,11 @@ var exportKeyBytes = async (format, key) => new Uint8Array(await crypto.subtle.e
16808
16920
  var importPublicKey = async (value) => crypto.subtle.importKey(
16809
16921
  "spki",
16810
16922
  toBufferSource(base64ToBytes(value.data)),
16811
- rsaAlgorithm,
16923
+ rsaAlgorithm2,
16812
16924
  true,
16813
16925
  ["encrypt"]
16814
16926
  );
16815
- var importPrivateKey = async (bytes) => crypto.subtle.importKey("pkcs8", toBufferSource(bytes), rsaAlgorithm, false, [
16927
+ var importPrivateKey = async (bytes) => crypto.subtle.importKey("pkcs8", toBufferSource(bytes), rsaAlgorithm2, false, [
16816
16928
  "decrypt"
16817
16929
  ]);
16818
16930
  var encryptFileKeyForPublicKey = async ({
@@ -16821,7 +16933,7 @@ var encryptFileKeyForPublicKey = async ({
16821
16933
  }) => {
16822
16934
  const encrypted = new Uint8Array(
16823
16935
  await crypto.subtle.encrypt(
16824
- rsaAlgorithm,
16936
+ rsaAlgorithm2,
16825
16937
  publicKey,
16826
16938
  toBufferSource(rawFileKey)
16827
16939
  )
@@ -16836,19 +16948,48 @@ var decryptFileKeyFromPublicKeyRecipient = async ({
16836
16948
  wrappedDataKey
16837
16949
  }) => new Uint8Array(
16838
16950
  await crypto.subtle.decrypt(
16839
- rsaAlgorithm,
16951
+ rsaAlgorithm2,
16840
16952
  privateKey,
16841
16953
  toBufferSource(base64ToBytes(wrappedDataKey.data))
16842
16954
  )
16843
16955
  );
16844
16956
  var isLegacyUserEncryptionMetadata = (metadata) => metadata.version === 1;
16845
- var createUserEncryptionSetup = async (password) => {
16957
+ var wrapUserPrivateKey = async ({
16958
+ keyId,
16959
+ password,
16960
+ privateKeyBytes,
16961
+ publicKey,
16962
+ version: version2
16963
+ }) => {
16846
16964
  const salt = createRandomBytes(16);
16847
- const passwordKey = await derivePasswordKey({
16965
+ const kdf = {
16848
16966
  iterations: encryptedFileIterations,
16967
+ name: encryptedFileKdf,
16968
+ salt: bytesToBase64(salt)
16969
+ };
16970
+ const passwordKey = await derivePasswordKey({
16971
+ iterations: kdf.iterations,
16849
16972
  password,
16850
16973
  salt
16851
16974
  });
16975
+ const additionalData = version2 === 3 ? createUserEncryptionKeyBinding({ kdf, keyId, publicKey, version: 3 }) : void 0;
16976
+ const wrappedPrivateKey = await encryptBytes(
16977
+ passwordKey,
16978
+ privateKeyBytes,
16979
+ additionalData
16980
+ );
16981
+ return {
16982
+ keyId,
16983
+ kdf,
16984
+ publicKey,
16985
+ version: version2,
16986
+ wrappedPrivateKey: {
16987
+ cipher: encryptedFileCipher,
16988
+ ...wrappedPrivateKey
16989
+ }
16990
+ };
16991
+ };
16992
+ var createUserEncryptionSetup = async (password) => {
16852
16993
  const keyPair = await crypto.subtle.generateKey(
16853
16994
  rsaKeyGenerationAlgorithm,
16854
16995
  true,
@@ -16858,66 +16999,116 @@ var createUserEncryptionSetup = async (password) => {
16858
16999
  exportKeyBytes("spki", keyPair.publicKey),
16859
17000
  exportKeyBytes("pkcs8", keyPair.privateKey)
16860
17001
  ]);
16861
- const wrappedPrivateKey = await encryptBytes(passwordKey, privateKeyBytes);
17002
+ const publicKey = {
17003
+ algorithm: publicKeyCipher,
17004
+ data: bytesToBase64(publicKeyBytes)
17005
+ };
17006
+ const metadata = await wrapUserPrivateKey({
17007
+ keyId: await computeEncryptionFingerprint(publicKey),
17008
+ password,
17009
+ privateKeyBytes,
17010
+ publicKey,
17011
+ version: 3
17012
+ });
16862
17013
  return {
16863
- metadata: {
16864
- keyId: crypto.randomUUID(),
16865
- kdf: {
16866
- iterations: encryptedFileIterations,
16867
- name: encryptedFileKdf,
16868
- salt: bytesToBase64(salt)
16869
- },
16870
- publicKey: {
16871
- algorithm: publicKeyCipher,
16872
- data: bytesToBase64(publicKeyBytes)
16873
- },
16874
- version: 2,
16875
- wrappedPrivateKey: {
16876
- cipher: encryptedFileCipher,
16877
- ...wrappedPrivateKey
16878
- }
16879
- },
16880
- userKey: keyPair.privateKey
17014
+ metadata,
17015
+ userKey: await importPrivateKey(privateKeyBytes)
16881
17016
  };
16882
17017
  };
16883
- var unlockUserEncryption = async ({
17018
+ var unlockLegacyUserKey = async ({
17019
+ metadata,
17020
+ passwordKey
17021
+ }) => {
17022
+ const rawUserKey = await decryptBytes({
17023
+ data: metadata.wrappedUserKey.data,
17024
+ iv: metadata.wrappedUserKey.iv,
17025
+ key: passwordKey
17026
+ });
17027
+ const userKey = await importAesKey(rawUserKey, false);
17028
+ const verification = textDecoder.decode(
17029
+ await decryptBytes({
17030
+ data: metadata.verification.data,
17031
+ iv: metadata.verification.iv,
17032
+ key: userKey
17033
+ })
17034
+ );
17035
+ if (verification !== verificationText) {
17036
+ throw new Error("Invalid encryption password.");
17037
+ }
17038
+ return userKey;
17039
+ };
17040
+ var unwrapVerifiedPrivateKeyBytes = async ({
16884
17041
  metadata,
16885
17042
  password
16886
17043
  }) => {
17044
+ if (metadata.version === 3) {
17045
+ await verifyUserEncryptionPublicKey(metadata);
17046
+ }
16887
17047
  const passwordKey = await derivePasswordKey({
16888
17048
  iterations: metadata.kdf.iterations,
16889
17049
  password,
16890
17050
  salt: base64ToBytes(metadata.kdf.salt)
16891
17051
  });
16892
- if (metadata.version === 1) {
16893
- const rawUserKey = await decryptBytes({
16894
- data: metadata.wrappedUserKey.data,
16895
- iv: metadata.wrappedUserKey.iv,
16896
- key: passwordKey
16897
- });
16898
- const userKey = await importAesKey(rawUserKey, false);
16899
- const verification = textDecoder.decode(
16900
- await decryptBytes({
16901
- data: metadata.verification.data,
16902
- iv: metadata.verification.iv,
16903
- key: userKey
16904
- })
16905
- );
16906
- if (verification !== verificationText) {
16907
- throw new Error("Invalid encryption password.");
16908
- }
16909
- return userKey;
16910
- }
17052
+ let privateKeyBytes;
16911
17053
  try {
16912
- const privateKeyBytes = await decryptBytes({
17054
+ privateKeyBytes = await decryptBytes({
17055
+ additionalData: metadata.version === 3 ? createUserEncryptionKeyBinding(metadata) : void 0,
16913
17056
  data: metadata.wrappedPrivateKey.data,
16914
17057
  iv: metadata.wrappedPrivateKey.iv,
16915
17058
  key: passwordKey
16916
17059
  });
16917
- return await importPrivateKey(privateKeyBytes);
16918
17060
  } catch {
16919
- throw new Error("Invalid encryption password.");
17061
+ throw new Error(
17062
+ metadata.version === 3 ? "Invalid encryption password, or the encryption key record was modified." : "Invalid encryption password."
17063
+ );
16920
17064
  }
17065
+ await assertPrivateKeyMatchesPublicKey({
17066
+ privateKeyBytes,
17067
+ publicKey: metadata.publicKey
17068
+ });
17069
+ return privateKeyBytes;
17070
+ };
17071
+ var unlockUserEncryption = async ({
17072
+ metadata,
17073
+ password
17074
+ }) => {
17075
+ if (metadata.version === 1) {
17076
+ return unlockLegacyUserKey({
17077
+ metadata,
17078
+ passwordKey: await derivePasswordKey({
17079
+ iterations: metadata.kdf.iterations,
17080
+ password,
17081
+ salt: base64ToBytes(metadata.kdf.salt)
17082
+ })
17083
+ });
17084
+ }
17085
+ return importPrivateKey(
17086
+ await unwrapVerifiedPrivateKeyBytes({ metadata, password })
17087
+ );
17088
+ };
17089
+ var rewrapUserEncryption = async ({
17090
+ currentPassword,
17091
+ metadata,
17092
+ nextPassword
17093
+ }) => {
17094
+ if (metadata.version === 1) {
17095
+ throw new Error(
17096
+ "Legacy encryption must be migrated before changing the encryption password."
17097
+ );
17098
+ }
17099
+ const privateKeyBytes = await unwrapVerifiedPrivateKeyBytes({
17100
+ metadata,
17101
+ password: currentPassword
17102
+ });
17103
+ const next = await wrapUserPrivateKey({
17104
+ keyId: metadata.keyId,
17105
+ password: nextPassword,
17106
+ privateKeyBytes,
17107
+ publicKey: metadata.publicKey,
17108
+ version: metadata.version
17109
+ });
17110
+ await unlockUserEncryption({ metadata: next, password: nextPassword });
17111
+ return next;
16921
17112
  };
16922
17113
  var parseEncryptedPlainTextPayload = (encryptedText) => {
16923
17114
  const parsed = JSON.parse(
@@ -17037,10 +17228,17 @@ var createExternalRecipientGrant = async ({
17037
17228
  };
17038
17229
  };
17039
17230
  var createUserRecipientGrant = async ({
17231
+ expectedFingerprint,
17040
17232
  fileKey,
17041
17233
  label,
17042
17234
  userEncryption
17043
17235
  }) => {
17236
+ const fingerprint = await verifyUserEncryptionPublicKey(userEncryption);
17237
+ if (fingerprint !== expectedFingerprint) {
17238
+ throw new UserEncryptionKeyMismatchError(
17239
+ "Recipient encryption key does not match the trusted fingerprint."
17240
+ );
17241
+ }
17044
17242
  const publicKey = await importPublicKey(userEncryption.publicKey);
17045
17243
  const rawFileKey = await exportKeyBytes("raw", fileKey);
17046
17244
  const wrappedDataKey = await encryptFileKeyForPublicKey({
@@ -17060,7 +17258,7 @@ var encryptPlainTextWithFileKey = async ({
17060
17258
  version: version2 = currentEncryptedFileVersion,
17061
17259
  workspaceAccess = "personal"
17062
17260
  }) => {
17063
- const encrypted = await encryptBytes(fileKey, textEncoder.encode(plaintext));
17261
+ const encrypted = await encryptBytes(fileKey, textEncoder2.encode(plaintext));
17064
17262
  const payload = {
17065
17263
  cipher: encryptedFileCipher,
17066
17264
  data: encrypted.data,
@@ -17100,10 +17298,13 @@ var updateEncryptedPlainTextRecipients = ({
17100
17298
  2
17101
17299
  );
17102
17300
  };
17301
+ var bytesEqual = (left, right) => left.length === right.length && left.every((byte, index) => byte === right[index]);
17103
17302
  var createCurrentRecipient = async ({
17104
17303
  label,
17105
- userEncryption
17304
+ userEncryption,
17305
+ userKey
17106
17306
  }) => {
17307
+ await verifyUserEncryptionPublicKey(userEncryption);
17107
17308
  const rawFileKey = createRandomBytes(32);
17108
17309
  const fileKey = await importAesKey(rawFileKey, true);
17109
17310
  const publicKey = await importPublicKey(userEncryption.publicKey);
@@ -17111,6 +17312,18 @@ var createCurrentRecipient = async ({
17111
17312
  publicKey,
17112
17313
  rawFileKey
17113
17314
  });
17315
+ let roundTripFileKey;
17316
+ try {
17317
+ roundTripFileKey = await decryptFileKeyFromPublicKeyRecipient({
17318
+ privateKey: userKey,
17319
+ wrappedDataKey
17320
+ });
17321
+ } catch {
17322
+ throw new UserEncryptionKeyMismatchError();
17323
+ }
17324
+ if (!bytesEqual(roundTripFileKey, rawFileKey)) {
17325
+ throw new UserEncryptionKeyMismatchError();
17326
+ }
17114
17327
  return {
17115
17328
  ...label ? { label } : {},
17116
17329
  fileKey,
@@ -17121,11 +17334,13 @@ var createCurrentRecipient = async ({
17121
17334
  var createCurrentRecipients = async ({
17122
17335
  additionalRecipients = [],
17123
17336
  label,
17124
- userEncryption
17337
+ userEncryption,
17338
+ userKey
17125
17339
  }) => {
17126
17340
  const { fileKey, ...currentRecipient } = await createCurrentRecipient({
17127
17341
  label,
17128
- userEncryption
17342
+ userEncryption,
17343
+ userKey
17129
17344
  });
17130
17345
  const recipients = [currentRecipient];
17131
17346
  const additionalCurrentRecipients = await Promise.all(
@@ -17133,9 +17348,8 @@ var createCurrentRecipients = async ({
17133
17348
  (recipient) => recipient.userEncryption.keyId !== userEncryption.keyId
17134
17349
  ).map(
17135
17350
  async (recipient) => createUserRecipientGrant({
17136
- fileKey,
17137
- label: recipient.label,
17138
- userEncryption: recipient.userEncryption
17351
+ ...recipient,
17352
+ fileKey
17139
17353
  })
17140
17354
  )
17141
17355
  );
@@ -17156,6 +17370,7 @@ var createEncryptedPlainTextFile = async ({
17156
17370
  label,
17157
17371
  plaintext,
17158
17372
  userEncryption,
17373
+ userKey,
17159
17374
  workspaceAccess = "personal",
17160
17375
  workspaceRecipients = []
17161
17376
  }) => {
@@ -17167,7 +17382,8 @@ var createEncryptedPlainTextFile = async ({
17167
17382
  const { fileKey, recipients } = await createCurrentRecipients({
17168
17383
  additionalRecipients: workspaceRecipients,
17169
17384
  label,
17170
- userEncryption
17385
+ userEncryption,
17386
+ userKey
17171
17387
  });
17172
17388
  const encryption = {
17173
17389
  kind: "encrypted-file",
@@ -17199,11 +17415,15 @@ var encryptTextForUser = async ({
17199
17415
  "Legacy encryption must be migrated before creating new encrypted files."
17200
17416
  );
17201
17417
  }
17202
- await unlockUserEncryption({ metadata: userEncryption, password });
17418
+ const userKey = await unlockUserEncryption({
17419
+ metadata: userEncryption,
17420
+ password
17421
+ });
17203
17422
  return (await createEncryptedPlainTextFile({
17204
17423
  label,
17205
17424
  plaintext,
17206
- userEncryption
17425
+ userEncryption,
17426
+ userKey
17207
17427
  })).text;
17208
17428
  };
17209
17429
  var decryptTextForUser = async ({
@@ -17227,6 +17447,247 @@ var decryptTextForUser = async ({
17227
17447
  });
17228
17448
  };
17229
17449
 
17450
+ // ../../packages/encryption/src/keyBinding/formatEncryptionFingerprint.ts
17451
+ var formatEncryptionFingerprint = (fingerprint) => (fingerprint.toUpperCase().match(/.{1,4}/g) ?? []).join(" ");
17452
+
17453
+ // ../../packages/encryption/src/rekey/resolveKeepFingerprint.ts
17454
+ var resolveKeepFingerprint = (recipientId, candidate) => encryptionFingerprintSchema.safeParse(recipientId).success ? recipientId : candidate.trustedFingerprint ?? null;
17455
+
17456
+ // ../../packages/encryption/src/rekey/planRecipientRekey.ts
17457
+ var planRecipientRekey = ({
17458
+ candidates,
17459
+ recipients,
17460
+ reissueRecipientIds = [],
17461
+ removeRecipientIds = []
17462
+ }) => {
17463
+ const known = new Set(recipients.map((recipient) => recipient.recipientId));
17464
+ for (const recipientId of [...removeRecipientIds, ...reissueRecipientIds]) {
17465
+ if (!known.has(recipientId)) {
17466
+ throw new Error(`Unknown encryption recipient: ${recipientId}`);
17467
+ }
17468
+ }
17469
+ const removed = new Set(removeRecipientIds);
17470
+ const reissued = new Set(reissueRecipientIds);
17471
+ for (const recipientId of removed) {
17472
+ if (reissued.has(recipientId)) {
17473
+ throw new Error(
17474
+ `Recipient ${recipientId} cannot be both removed and reissued.`
17475
+ );
17476
+ }
17477
+ }
17478
+ const candidateById = new Map(
17479
+ candidates.map((candidate) => [candidate.userEncryption.keyId, candidate])
17480
+ );
17481
+ const plan = [];
17482
+ const issues = [];
17483
+ for (const recipient of recipients) {
17484
+ const { label, recipientId } = recipient;
17485
+ if (removed.has(recipientId)) {
17486
+ plan.push({ action: "remove", recipientId });
17487
+ continue;
17488
+ }
17489
+ if (reissued.has(recipientId)) {
17490
+ plan.push({ action: "reissue", recipientId });
17491
+ continue;
17492
+ }
17493
+ const candidate = candidateById.get(recipientId);
17494
+ if (candidate) {
17495
+ const expectedFingerprint = resolveKeepFingerprint(
17496
+ recipientId,
17497
+ candidate
17498
+ );
17499
+ if (expectedFingerprint) {
17500
+ plan.push({
17501
+ action: "keep",
17502
+ expectedFingerprint,
17503
+ recipientId,
17504
+ userEncryption: candidate.userEncryption
17505
+ });
17506
+ } else {
17507
+ issues.push({
17508
+ ...label ? { label } : {},
17509
+ reason: "public_key_unverified",
17510
+ recipientId
17511
+ });
17512
+ }
17513
+ continue;
17514
+ }
17515
+ issues.push({
17516
+ ...label ? { label } : {},
17517
+ reason: recipient.wrappedDataKey.cipher === publicKeyCipher ? "public_key_unavailable" : "secret_not_retained",
17518
+ recipientId
17519
+ });
17520
+ }
17521
+ return { issues, plan };
17522
+ };
17523
+
17524
+ // ../../packages/encryption/src/rekey/assertCompleteRekeyPlan.ts
17525
+ var assertCompleteRekeyPlan = ({
17526
+ actorKeyId,
17527
+ plan,
17528
+ recipients
17529
+ }) => {
17530
+ const current = new Set(recipients.map((recipient) => recipient.recipientId));
17531
+ const seen = /* @__PURE__ */ new Set();
17532
+ for (const entry of plan) {
17533
+ if (!current.has(entry.recipientId)) {
17534
+ throw new Error(`Unknown encryption recipient: ${entry.recipientId}`);
17535
+ }
17536
+ if (seen.has(entry.recipientId)) {
17537
+ throw new Error(
17538
+ `Recipient ${entry.recipientId} appears more than once in the rekey plan.`
17539
+ );
17540
+ }
17541
+ seen.add(entry.recipientId);
17542
+ if (entry.action === "keep" && entry.userEncryption.keyId !== entry.recipientId) {
17543
+ throw new Error(
17544
+ `Recipient ${entry.recipientId} cannot be kept under a different public key.`
17545
+ );
17546
+ }
17547
+ }
17548
+ const missing = [...current].filter((recipientId) => !seen.has(recipientId));
17549
+ if (missing.length) {
17550
+ throw new Error(
17551
+ `Rekey plan does not say what to do with recipient(s): ${missing.join(", ")}`
17552
+ );
17553
+ }
17554
+ if (!plan.some(
17555
+ (entry) => entry.action === "keep" && entry.recipientId === actorKeyId
17556
+ )) {
17557
+ throw new Error(
17558
+ "Rekey must keep your own access, otherwise nobody could save later versions."
17559
+ );
17560
+ }
17561
+ };
17562
+
17563
+ // ../../packages/encryption/src/rekey/generateFileKey.ts
17564
+ var generateFileKey = async () => crypto.subtle.generateKey({ length: 256, name: encryptedFileCipher }, true, [
17565
+ "decrypt",
17566
+ "encrypt"
17567
+ ]);
17568
+
17569
+ // ../../packages/encryption/src/rekey/rekeyEncryptedPlainText.ts
17570
+ var keyBytes = async (key) => new Uint8Array(await crypto.subtle.exportKey("raw", key));
17571
+ var sameBytes = (left, right) => left.length === right.length && left.every((byte, i) => byte === right[i]);
17572
+ var rekeyEncryptedPlainText = async ({
17573
+ actorKeyId,
17574
+ actorUserKey,
17575
+ encryptedText,
17576
+ fileKey,
17577
+ plan,
17578
+ workspaceAccess
17579
+ }) => {
17580
+ const payload = parseEncryptedPlainTextPayload(encryptedText);
17581
+ assertCompleteRekeyPlan({ actorKeyId, plan, recipients: payload.recipients });
17582
+ const plaintext = await decryptPlainTextWithFileKey({
17583
+ encryptedText,
17584
+ fileKey
17585
+ });
17586
+ const nextFileKey = await generateFileKey();
17587
+ if (sameBytes(await keyBytes(fileKey), await keyBytes(nextFileKey))) {
17588
+ throw new Error("Rekey produced the same file key; refusing to continue.");
17589
+ }
17590
+ const byId = new Map(
17591
+ payload.recipients.map((recipient) => [recipient.recipientId, recipient])
17592
+ );
17593
+ const recipients = [];
17594
+ const issuedSecrets = [];
17595
+ const removedRecipientIds = [];
17596
+ for (const entry of plan) {
17597
+ const previous = byId.get(entry.recipientId);
17598
+ if (entry.action === "remove") {
17599
+ removedRecipientIds.push(entry.recipientId);
17600
+ continue;
17601
+ }
17602
+ if (entry.action === "keep") {
17603
+ recipients.push(
17604
+ await createUserRecipientGrant({
17605
+ expectedFingerprint: entry.expectedFingerprint,
17606
+ fileKey: nextFileKey,
17607
+ label: previous.label,
17608
+ userEncryption: entry.userEncryption
17609
+ })
17610
+ );
17611
+ continue;
17612
+ }
17613
+ const label = previous.label ?? entry.recipientId;
17614
+ const grant = await createExternalRecipientGrant({
17615
+ fileKey: nextFileKey,
17616
+ name: label
17617
+ });
17618
+ recipients.push(grant.recipient);
17619
+ issuedSecrets.push({
17620
+ label,
17621
+ previousRecipientId: entry.recipientId,
17622
+ recipientId: grant.recipient.recipientId,
17623
+ secret: grant.secret
17624
+ });
17625
+ }
17626
+ const actorFileKey = await unwrapFileKey({
17627
+ recipients,
17628
+ recipientId: actorKeyId,
17629
+ userKey: actorUserKey
17630
+ }).catch(() => null);
17631
+ if (!actorFileKey || !sameBytes(await keyBytes(actorFileKey), await keyBytes(nextFileKey))) {
17632
+ throw new Error(
17633
+ "Your new grant does not open with your unlocked key; refusing to rekey."
17634
+ );
17635
+ }
17636
+ const nextWorkspaceAccess = workspaceAccess ?? payload.workspaceAccess ?? "personal";
17637
+ const nextEncryptedText = await encryptPlainTextWithFileKey({
17638
+ fileKey: nextFileKey,
17639
+ plaintext,
17640
+ recipients,
17641
+ version: currentEncryptedFileVersion,
17642
+ workspaceAccess: nextWorkspaceAccess
17643
+ });
17644
+ const verified = await decryptPlainTextWithFileKey({
17645
+ encryptedText: nextEncryptedText,
17646
+ fileKey: nextFileKey
17647
+ });
17648
+ if (verified !== plaintext) {
17649
+ throw new Error("Rekeyed file did not round-trip; refusing to write.");
17650
+ }
17651
+ return {
17652
+ encryptedText: nextEncryptedText,
17653
+ encryption: {
17654
+ kind: "encrypted-file",
17655
+ recipients,
17656
+ version: currentEncryptedFileVersion,
17657
+ workspaceAccess: nextWorkspaceAccess
17658
+ },
17659
+ fileKey: nextFileKey,
17660
+ issuedSecrets,
17661
+ removedRecipientIds
17662
+ };
17663
+ };
17664
+
17665
+ // ../../packages/encryption/src/parseUserRecipientLabel.ts
17666
+ var userRecipientLabelPrefix = "user:";
17667
+ var parseUserRecipientLabel = (label) => {
17668
+ if (!label?.startsWith(userRecipientLabelPrefix)) {
17669
+ return null;
17670
+ }
17671
+ const value = label.slice(userRecipientLabelPrefix.length);
17672
+ const separatorIndex = value.indexOf(":");
17673
+ if (separatorIndex === -1) {
17674
+ return { displayName: null, userId: value };
17675
+ }
17676
+ const userId = value.slice(0, separatorIndex);
17677
+ const encodedDisplayName = value.slice(separatorIndex + 1);
17678
+ if (!encodedDisplayName) {
17679
+ return { displayName: null, userId };
17680
+ }
17681
+ try {
17682
+ return {
17683
+ displayName: decodeURIComponent(encodedDisplayName),
17684
+ userId
17685
+ };
17686
+ } catch {
17687
+ return { displayName: encodedDisplayName, userId };
17688
+ }
17689
+ };
17690
+
17230
17691
  // ../../packages/core/src/fileTypes.ts
17231
17692
  var textStorageClass = "text";
17232
17693
  var binaryStorageClass = "binary";
@@ -17551,8 +18012,8 @@ var normalizeStorePath = (value) => {
17551
18012
  }
17552
18013
  return segments2.length === 0 ? "/" : `/${segments2.join("/")}`;
17553
18014
  };
17554
- var storePathToArray = (path25) => {
17555
- const normalizedPath = normalizeStorePath(path25);
18015
+ var storePathToArray = (path28) => {
18016
+ const normalizedPath = normalizeStorePath(path28);
17556
18017
  return normalizedPath === "/" ? [] : normalizedPath.split("/").filter(Boolean);
17557
18018
  };
17558
18019
  var storePathSchema = external_exports.string().trim().min(1).transform((value) => normalizeStorePath(value));
@@ -18819,6 +19280,20 @@ var recentFilesValueSchema = external_exports.array(recentFileVisitSchema);
18819
19280
  var pinnedStoreIdsSchema = pinnedStoreIdsValueSchema.default([]);
18820
19281
  var recentStoresSchema = recentStoresValueSchema.default([]);
18821
19282
  var recentFilesSchema = recentFilesValueSchema.default([]);
19283
+ var encryptionKeyHistoryEntrySchema = external_exports.object({
19284
+ fingerprint: encryptionFingerprintSchema.nullable(),
19285
+ keyId: external_exports.string().trim().min(1),
19286
+ reason: external_exports.enum(["legacy_replaced", "reset"]),
19287
+ replacedAt: external_exports.string().datetime()
19288
+ });
19289
+ var encryptionTrustedKeySchema = external_exports.object({
19290
+ fingerprint: encryptionFingerprintSchema,
19291
+ trustedAt: external_exports.string().datetime()
19292
+ });
19293
+ var encryptionTrustedKeysSchema = external_exports.record(
19294
+ storeOwnerIdSchema,
19295
+ encryptionTrustedKeySchema
19296
+ );
18822
19297
  var createTypeLastUsedAtSchema = external_exports.record(
18823
19298
  external_exports.string().min(1).max(100),
18824
19299
  external_exports.string().datetime()
@@ -18842,6 +19317,9 @@ var userPreferencesSchema = external_exports.object({
18842
19317
  source: "generated"
18843
19318
  }),
18844
19319
  encryption: userEncryptionMetadataSchema.nullable().default(null),
19320
+ encryptionIdentityChangedAt: external_exports.string().datetime().nullable().default(null),
19321
+ encryptionKeyHistory: external_exports.array(encryptionKeyHistoryEntrySchema).default([]),
19322
+ encryptionTrustedKeys: encryptionTrustedKeysSchema.default({}),
18845
19323
  createdAt: external_exports.string().datetime().default(() => (/* @__PURE__ */ new Date()).toISOString()),
18846
19324
  updatedAt: external_exports.string().datetime().default(() => (/* @__PURE__ */ new Date()).toISOString())
18847
19325
  });
@@ -18858,7 +19336,39 @@ var userPreferencesUpdateSchema = external_exports.object({
18858
19336
  markdownEditorMode: markdownEditorModeSchema,
18859
19337
  htmlEditorMode: htmlEditorModeSchema,
18860
19338
  avatar: avatarPreferencesSchema,
18861
- encryption: userEncryptionMetadataSchema.nullable()
19339
+ encryption: userEncryptionMetadataSchema.nullable(),
19340
+ encryptionIdentityChangedAt: external_exports.string().datetime().nullable(),
19341
+ encryptionKeyHistory: external_exports.array(encryptionKeyHistoryEntrySchema),
19342
+ encryptionTrustedKeys: encryptionTrustedKeysSchema
19343
+ });
19344
+ var ownUserPreferencesPatchSchema = userPreferencesUpdateSchema.omit({
19345
+ encryption: true,
19346
+ encryptionIdentityChangedAt: true,
19347
+ encryptionKeyHistory: true,
19348
+ encryptionTrustedKeys: true
19349
+ }).strict();
19350
+ var setupOwnEncryptionInputSchema = external_exports.object({
19351
+ encryption: boundUserEncryptionMetadataSchema,
19352
+ // Required when replacing a legacy (v1) record, which has no public identity.
19353
+ expectedKeyId: external_exports.string().trim().min(1).nullable().default(null)
19354
+ });
19355
+ var rewrapOwnEncryptionInputSchema = external_exports.object({
19356
+ encryption: currentUserEncryptionMetadataSchema,
19357
+ expectedKeyId: external_exports.string().trim().min(1)
19358
+ });
19359
+ var resetEncryptionIdentityConfirmation = "reset-encryption-identity";
19360
+ var resetOwnEncryptionInputSchema = external_exports.object({
19361
+ confirmation: external_exports.literal(resetEncryptionIdentityConfirmation),
19362
+ encryption: boundUserEncryptionMetadataSchema,
19363
+ expectedKeyId: external_exports.string().trim().min(1)
19364
+ });
19365
+ var trustEncryptionKeyInputSchema = external_exports.object({
19366
+ keys: external_exports.array(
19367
+ external_exports.object({
19368
+ fingerprint: encryptionFingerprintSchema,
19369
+ userId: storeOwnerIdSchema
19370
+ })
19371
+ ).min(1).max(100)
18862
19372
  });
18863
19373
  var readUserPreferencesInputSchema = external_exports.object({
18864
19374
  userId: storeOwnerIdSchema
@@ -18894,7 +19404,7 @@ var upsertUserPreferencesInputSchema = external_exports.object({
18894
19404
  patch: userPreferencesUpdateSchema.partial().default({})
18895
19405
  });
18896
19406
  var upsertOwnUserPreferencesInputSchema = external_exports.object({
18897
- patch: userPreferencesUpdateSchema.partial().default({})
19407
+ patch: ownUserPreferencesPatchSchema.partial().default({})
18898
19408
  });
18899
19409
 
18900
19410
  // ../../packages/core/src/storeChat.ts
@@ -19600,21 +20110,21 @@ var isKey = (value) => /^\w*$/.test(value);
19600
20110
  var isUndefined = (val) => val === void 0;
19601
20111
  var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
19602
20112
  var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
19603
- var get = (object2, path25, defaultValue) => {
19604
- if (!path25 || !isObject2(object2)) {
20113
+ var get = (object2, path28, defaultValue) => {
20114
+ if (!path28 || !isObject2(object2)) {
19605
20115
  return defaultValue;
19606
20116
  }
19607
- const paths = isKey(path25) ? [path25] : stringToPath(path25);
20117
+ const paths = isKey(path28) ? [path28] : stringToPath(path28);
19608
20118
  const result = paths.reduce((result2, key) => {
19609
20119
  return isNullOrUndefined(result2) ? void 0 : result2[key];
19610
20120
  }, object2);
19611
- return isUndefined(result) || result === object2 ? isUndefined(object2[path25]) ? defaultValue : object2[path25] : result;
20121
+ return isUndefined(result) || result === object2 ? isUndefined(object2[path28]) ? defaultValue : object2[path28] : result;
19612
20122
  };
19613
20123
  var isBoolean = (value) => typeof value === "boolean";
19614
20124
  var isFunction = (value) => typeof value === "function";
19615
- var set2 = (object2, path25, value) => {
20125
+ var set2 = (object2, path28, value) => {
19616
20126
  let index = -1;
19617
- const tempPath = isKey(path25) ? [path25] : stringToPath(path25);
20127
+ const tempPath = isKey(path28) ? [path28] : stringToPath(path28);
19618
20128
  const length = tempPath.length;
19619
20129
  const lastIndex = length - 1;
19620
20130
  while (++index < length) {
@@ -19812,12 +20322,12 @@ function isEmptyArray(obj) {
19812
20322
  }
19813
20323
  return true;
19814
20324
  }
19815
- function unset(object2, path25) {
19816
- if (isString(path25) && Object.prototype.hasOwnProperty.call(object2, path25)) {
19817
- delete object2[path25];
20325
+ function unset(object2, path28) {
20326
+ if (isString(path28) && Object.prototype.hasOwnProperty.call(object2, path28)) {
20327
+ delete object2[path28];
19818
20328
  return object2;
19819
20329
  }
19820
- const paths = Array.isArray(path25) ? path25 : isKey(path25) ? [path25] : stringToPath(path25);
20330
+ const paths = Array.isArray(path28) ? path28 : isKey(path28) ? [path28] : stringToPath(path28);
19821
20331
  const childObject = paths.length === 1 ? object2 : baseGet(object2, paths);
19822
20332
  const index = paths.length - 1;
19823
20333
  const key = paths[index];
@@ -23544,7 +24054,7 @@ var publicActionSubmitResultSchema = external_exports.unknown();
23544
24054
 
23545
24055
  // ../../packages/core/src/widgetRuntime.ts
23546
24056
  var widgetRuntimeOutputPathSchema = storePathSchema.refine(
23547
- (path25) => path25 !== "/",
24057
+ (path28) => path28 !== "/",
23548
24058
  {
23549
24059
  message: "Path must not be the root directory."
23550
24060
  }
@@ -23594,7 +24104,7 @@ var widgetRuntimeCompleteAttachmentUploadInputSchema = storeRefSchema.safeExtend
23594
24104
  treeVisibility: external_exports.enum(["visible", "hidden"]).optional(),
23595
24105
  uploadIntentId: external_exports.string().trim().min(1)
23596
24106
  });
23597
- var widgetRuntimeLinkPathSchema = external_exports.string().trim().min(1).max(2048).refine((path25) => path25.startsWith("/") && !path25.startsWith("//"), {
24107
+ var widgetRuntimeLinkPathSchema = external_exports.string().trim().min(1).max(2048).refine((path28) => path28.startsWith("/") && !path28.startsWith("//"), {
23598
24108
  message: "Link path must be a relative application path."
23599
24109
  });
23600
24110
  var widgetRuntimeCreateSigningLinkInputSchema = storeRefSchema.safeExtend({
@@ -23683,8 +24193,8 @@ var skillScanSchema = external_exports.object({
23683
24193
 
23684
24194
  // ../../packages/store-tree/src/patterns.ts
23685
24195
  var escapeRegex2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23686
- var basename2 = (path25) => {
23687
- const segments2 = path25.split("/").filter(Boolean);
24196
+ var basename2 = (path28) => {
24197
+ const segments2 = path28.split("/").filter(Boolean);
23688
24198
  return segments2[segments2.length - 1] ?? "";
23689
24199
  };
23690
24200
  var normalizeStorePathPattern = (pattern) => pattern.trim();
@@ -23702,7 +24212,7 @@ var storePathPatternToRegex = (pattern) => {
23702
24212
  return new RegExp(source, "i");
23703
24213
  };
23704
24214
  var doesStorePathPatternMatch = ({
23705
- path: path25,
24215
+ path: path28,
23706
24216
  pattern,
23707
24217
  mode = "path"
23708
24218
  }) => {
@@ -23710,7 +24220,7 @@ var doesStorePathPatternMatch = ({
23710
24220
  if (!normalizedPattern) {
23711
24221
  return true;
23712
24222
  }
23713
- const normalizedPath = normalizeStorePath(path25);
24223
+ const normalizedPath = normalizeStorePath(path28);
23714
24224
  const target = mode === "basename" ? basename2(normalizedPath) : normalizedPath;
23715
24225
  if (patternHasWildcard(normalizedPattern)) {
23716
24226
  return storePathPatternToRegex(normalizedPattern).test(target);
@@ -23798,8 +24308,8 @@ var isIssueRecord = (value) => {
23798
24308
  return isRecord2(value) && typeof value.message === "string";
23799
24309
  };
23800
24310
  var formatIssue = (issue2) => {
23801
- const path25 = Array.isArray(issue2.path) && issue2.path.length > 0 ? issue2.path.map(String).join(".") : "";
23802
- return path25 ? `${path25}: ${issue2.message}` : issue2.message;
24311
+ const path28 = Array.isArray(issue2.path) && issue2.path.length > 0 ? issue2.path.map(String).join(".") : "";
24312
+ return path28 ? `${path28}: ${issue2.message}` : issue2.message;
23803
24313
  };
23804
24314
  var formatIssueArray = (issues) => {
23805
24315
  if (!issues.every(isIssueRecord)) {
@@ -24272,7 +24782,7 @@ var buildContentChangedConflictExplainer = (issues) => {
24272
24782
  body: [
24273
24783
  pathSubject(
24274
24784
  paths,
24275
- (path25) => `${path25} changed both locally and remotely.`,
24785
+ (path28) => `${path28} changed both locally and remotely.`,
24276
24786
  (count) => `${count} files changed both locally and remotely.`
24277
24787
  ),
24278
24788
  "Forum left these files alone because either overwrite direction could lose work."
@@ -24304,7 +24814,7 @@ var buildLocalDeleteRemoteChangeExplainer = (issues) => {
24304
24814
  body: [
24305
24815
  pathSubject(
24306
24816
  paths,
24307
- (path25) => `${path25} was deleted locally, but the remote file changed.`,
24817
+ (path28) => `${path28} was deleted locally, but the remote file changed.`,
24308
24818
  (count) => `${count} files were deleted locally, but changed remotely.`
24309
24819
  ),
24310
24820
  "Forum did not delete newer remote work automatically."
@@ -24336,7 +24846,7 @@ var buildMoveDestinationConflictExplainer = (issues) => {
24336
24846
  body: [
24337
24847
  pathSubject(
24338
24848
  paths,
24339
- (path25) => `${path25} is the destination of a remote move, but already exists locally.`,
24849
+ (path28) => `${path28} is the destination of a remote move, but already exists locally.`,
24340
24850
  (count) => `${count} paths are remote move destinations that already exist locally.`
24341
24851
  ),
24342
24852
  "Forum synced unrelated files but left these paths alone."
@@ -24371,7 +24881,7 @@ var buildMoveRemoteChangeConflictExplainer = (issues) => {
24371
24881
  body: [
24372
24882
  pathSubject(
24373
24883
  paths,
24374
- (path25) => `${path25} was involved in a move while the other side changed it.`,
24884
+ (path28) => `${path28} was involved in a move while the other side changed it.`,
24375
24885
  (count) => `${count} files were involved in moves while the other side changed them.`
24376
24886
  ),
24377
24887
  "Forum did not combine the move and content change automatically."
@@ -24403,7 +24913,7 @@ var buildMoveMoveConflictExplainer = (issues) => {
24403
24913
  body: [
24404
24914
  pathSubject(
24405
24915
  paths,
24406
- (path25) => `${path25} moved locally and remotely to different paths.`,
24916
+ (path28) => `${path28} moved locally and remotely to different paths.`,
24407
24917
  (count) => `${count} files moved locally and remotely to different paths.`
24408
24918
  ),
24409
24919
  "Forum left these moves unresolved because choosing a path automatically could hide work."
@@ -24435,7 +24945,7 @@ var buildDeleteMoveConflictExplainer = (issues) => {
24435
24945
  body: [
24436
24946
  pathSubject(
24437
24947
  paths,
24438
- (path25) => `${path25} was deleted on one side and moved on the other.`,
24948
+ (path28) => `${path28} was deleted on one side and moved on the other.`,
24439
24949
  (count) => `${count} files were deleted on one side and moved on the other.`
24440
24950
  ),
24441
24951
  "Forum did not choose between delete and move automatically."
@@ -24467,7 +24977,7 @@ var buildReferenceLocalFileConflictExplainer = (issues) => {
24467
24977
  body: [
24468
24978
  pathSubject(
24469
24979
  paths,
24470
- (path25) => `${path25} is now a remote reference, but the local file has changes.`,
24980
+ (path28) => `${path28} is now a remote reference, but the local file has changes.`,
24471
24981
  (count) => `${count} paths are now remote references, but local files have changes.`
24472
24982
  ),
24473
24983
  "Forum left the local files alone because replacing them would discard local work."
@@ -24499,7 +25009,7 @@ var buildUnsupportedLocalEntryExplainer = (issues) => {
24499
25009
  body: [
24500
25010
  pathSubject(
24501
25011
  paths,
24502
- (path25) => `${path25} is an unsupported local filesystem entry.`,
25012
+ (path28) => `${path28} is an unsupported local filesystem entry.`,
24503
25013
  (count) => `${count} local filesystem entries are unsupported.`
24504
25014
  ),
24505
25015
  "Forum skipped these paths and continued with unrelated files where it could."
@@ -24531,7 +25041,7 @@ var buildReadOnlyLocalChangeExplainer = (issues) => {
24531
25041
  body: [
24532
25042
  pathSubject(
24533
25043
  paths,
24534
- (path25) => `${path25} has local changes, but its sync rule is read-only.`,
25044
+ (path28) => `${path28} has local changes, but its sync rule is read-only.`,
24535
25045
  (count) => `${count} files have local changes, but their sync rules are read-only.`
24536
25046
  ),
24537
25047
  "Forum left these files alone so remote updates cannot overwrite local work."
@@ -24628,7 +25138,7 @@ var checkoutConflictIssuesFromResult = (result) => checkoutIssuesFromResult(resu
24628
25138
  (issue2) => issue2.type === "conflict"
24629
25139
  );
24630
25140
  var formatCheckoutExplainer = (explainer) => {
24631
- const pathLines = explainer.paths.length <= 1 ? [] : ["", ...formatPathList(explainer.paths).map((path25) => ` ${path25}`)];
25141
+ const pathLines = explainer.paths.length <= 1 ? [] : ["", ...formatPathList(explainer.paths).map((path28) => ` ${path28}`)];
24632
25142
  const actionLines = explainer.actions.map(
24633
25143
  (action) => `${styleText.bold(`${action.label}:`)} ${action.text}`
24634
25144
  );
@@ -24818,19 +25328,19 @@ import { TextDecoder as TextDecoder2 } from "util";
24818
25328
  import ignore2 from "ignore";
24819
25329
 
24820
25330
  // src/buildCheckoutFileManifestEntry.ts
24821
- var toManifestRemotePath = (path25) => path25.startsWith("/") ? path25 : `/${path25}`;
25331
+ var toManifestRemotePath = (path28) => path28.startsWith("/") ? path28 : `/${path28}`;
24822
25332
  var buildCheckoutFileManifestEntry = ({
24823
25333
  storageClass,
24824
25334
  hash: hash2,
24825
25335
  manifestEntry,
24826
- path: path25,
25336
+ path: path28,
24827
25337
  remoteFile,
24828
25338
  source,
24829
25339
  syncedAt
24830
25340
  }) => {
24831
25341
  const remoteFileId = remoteFile.id ?? remoteFile._id ?? manifestEntry?.remoteFileId;
24832
25342
  if (!remoteFileId) {
24833
- throw new Error(`Remote file ${path25} did not include a file id`);
25343
+ throw new Error(`Remote file ${path28} did not include a file id`);
24834
25344
  }
24835
25345
  return {
24836
25346
  storageClass,
@@ -24838,7 +25348,7 @@ var buildCheckoutFileManifestEntry = ({
24838
25348
  isExecutable: storageClass === "text" ? remoteFile.isExecutable === true || void 0 : void 0,
24839
25349
  lastSyncedAt: syncedAt,
24840
25350
  remoteFileId,
24841
- remotePath: remoteFile.path ?? manifestEntry?.remotePath ?? toManifestRemotePath(path25),
25351
+ remotePath: remoteFile.path ?? manifestEntry?.remotePath ?? toManifestRemotePath(path28),
24842
25352
  remoteUpdatedAt: remoteFile.updatedAt ?? null,
24843
25353
  remoteRevisionNumber: remoteFile.revisionNumber ?? null,
24844
25354
  ...source ? { source } : {}
@@ -27603,16 +28113,16 @@ var updateFileManifestEntry = ({
27603
28113
  hash: hash2,
27604
28114
  manifest,
27605
28115
  manifestEntry,
27606
- path: path25,
28116
+ path: path28,
27607
28117
  remoteFile,
27608
28118
  source,
27609
28119
  syncedAt
27610
28120
  }) => {
27611
- manifest.files[path25] = buildCheckoutFileManifestEntry({
28121
+ manifest.files[path28] = buildCheckoutFileManifestEntry({
27612
28122
  storageClass,
27613
28123
  hash: hash2,
27614
28124
  manifestEntry,
27615
- path: path25,
28125
+ path: path28,
27616
28126
  remoteFile,
27617
28127
  source,
27618
28128
  syncedAt
@@ -29093,7 +29603,7 @@ var remoteFileHash = async ({
29093
29603
  client,
29094
29604
  remoteFile,
29095
29605
  storeRef,
29096
- path: path25
29606
+ path: path28
29097
29607
  }) => {
29098
29608
  const textHash = remoteTextHash(remoteFile);
29099
29609
  if (textHash) {
@@ -29104,7 +29614,7 @@ var remoteFileHash = async ({
29104
29614
  }
29105
29615
  const { downloadUrl } = await client.createFileDownloadUrlByRef({
29106
29616
  ...storeRef,
29107
- path: path25
29617
+ path: path28
29108
29618
  });
29109
29619
  const response = await fetch(downloadUrl);
29110
29620
  if (!response.ok) {
@@ -30531,9 +31041,9 @@ var createHumanWatchSubscriber = ({
30531
31041
  return;
30532
31042
  }
30533
31043
  case "sync.watch.conflict.raised": {
30534
- const path25 = String(details.path ?? "");
31044
+ const path28 = String(details.path ?? "");
30535
31045
  const suggestions = details.suggestions ?? [];
30536
- error51(`Conflict: ${path25} \u2014 ${event.message ?? "needs attention"}`);
31046
+ error51(`Conflict: ${path28} \u2014 ${event.message ?? "needs attention"}`);
30537
31047
  if (suggestions.length > 0) {
30538
31048
  error51(` ${formatSuggestions(suggestions)}`);
30539
31049
  }
@@ -30562,10 +31072,10 @@ import notifier from "node-notifier";
30562
31072
  var createNotifyWatchSubscriber = () => {
30563
31073
  return (event) => {
30564
31074
  if (event.eventType === "sync.watch.conflict.raised") {
30565
- const path25 = event.details?.path;
31075
+ const path28 = event.details?.path;
30566
31076
  notifier.notify({
30567
31077
  title: "Forum sync conflict",
30568
- message: typeof path25 === "string" ? `${path25} needs attention` : event.message ?? "A file needs attention"
31078
+ message: typeof path28 === "string" ? `${path28} needs attention` : event.message ?? "A file needs attention"
30569
31079
  });
30570
31080
  return;
30571
31081
  }
@@ -30681,10 +31191,10 @@ var createConflictTracker = () => {
30681
31191
  );
30682
31192
  const raised = current.filter((conflict) => !active.has(conflict.path));
30683
31193
  const cleared = [...active.keys()].filter(
30684
- (path25) => !currentByPath.has(path25)
31194
+ (path28) => !currentByPath.has(path28)
30685
31195
  );
30686
- for (const path25 of cleared) {
30687
- active.delete(path25);
31196
+ for (const path28 of cleared) {
31197
+ active.delete(path28);
30688
31198
  }
30689
31199
  for (const conflict of current) {
30690
31200
  active.set(conflict.path, conflict);
@@ -30695,13 +31205,13 @@ var createConflictTracker = () => {
30695
31205
  };
30696
31206
 
30697
31207
  // src/watch/conflictResolutionHints.ts
30698
- var keepLocal = (path25) => ({
31208
+ var keepLocal = (path28) => ({
30699
31209
  label: "Keep local",
30700
- command: `fm push --force ${path25}`
31210
+ command: `fm push --force ${path28}`
30701
31211
  });
30702
- var acceptRemote = (path25) => ({
31212
+ var acceptRemote = (path28) => ({
30703
31213
  label: "Accept remote",
30704
- command: `fm pull --force ${path25}`
31214
+ command: `fm pull --force ${path28}`
30705
31215
  });
30706
31216
  var review = (label, command) => ({
30707
31217
  label,
@@ -30717,23 +31227,23 @@ var forceResolvableTypes = /* @__PURE__ */ new Set([
30717
31227
  "reference-local-file",
30718
31228
  "read-only-local-change"
30719
31229
  ]);
30720
- var conflictResolutionSuggestions = (conflictType, path25) => {
31230
+ var conflictResolutionSuggestions = (conflictType, path28) => {
30721
31231
  if (forceResolvableTypes.has(conflictType)) {
30722
- return [keepLocal(path25), acceptRemote(path25)];
31232
+ return [keepLocal(path28), acceptRemote(path28)];
30723
31233
  }
30724
- return [review("Review", `fm status ${path25}`)];
31234
+ return [review("Review", `fm status ${path28}`)];
30725
31235
  };
30726
31236
 
30727
31237
  // src/watch/extractWatchConflicts.ts
30728
31238
  var toWatchConflict = (issue2) => {
30729
- const { path: path25, message, relatedPaths } = issue2.details.details;
31239
+ const { path: path28, message, relatedPaths } = issue2.details.details;
30730
31240
  const conflictType = issue2.details.type;
30731
31241
  return {
30732
- path: path25,
31242
+ path: path28,
30733
31243
  conflictType,
30734
31244
  message,
30735
31245
  relatedPaths: relatedPaths ?? [],
30736
- suggestions: conflictResolutionSuggestions(conflictType, path25)
31246
+ suggestions: conflictResolutionSuggestions(conflictType, path28)
30737
31247
  };
30738
31248
  };
30739
31249
  var extractWatchConflicts = (result) => {
@@ -30824,9 +31334,9 @@ var createCheckoutWatcher = ({
30824
31334
  })
30825
31335
  );
30826
31336
  }
30827
- for (const path25 of cleared) {
31337
+ for (const path28 of cleared) {
30828
31338
  bus.emit(
30829
- watchEvent("sync.watch.conflict.cleared", void 0, { path: path25 })
31339
+ watchEvent("sync.watch.conflict.cleared", void 0, { path: path28 })
30830
31340
  );
30831
31341
  }
30832
31342
  bus.emit(
@@ -31518,10 +32028,26 @@ var createStoreClient = ({
31518
32028
  listSkillFolders: (input) => call("skills.folders", () => trpc.skills.folders.query(input)),
31519
32029
  readSkill: (input) => call("skills.read", () => trpc.skills.read.query(input)),
31520
32030
  readUserPreferences: () => call("userPreferences.read", () => trpc.userPreferences.read.query({})),
32031
+ readPublicEncryptionKeys: (input) => call(
32032
+ "userPreferences.readPublicEncryptionKeys",
32033
+ () => trpc.userPreferences.readPublicEncryptionKeys.query(input)
32034
+ ),
31521
32035
  upsertUserPreferences: (input) => call(
31522
32036
  "userPreferences.upsert",
31523
32037
  () => trpc.userPreferences.upsert.mutate(input)
31524
32038
  ),
32039
+ setupEncryption: (input) => call(
32040
+ "userPreferences.setupEncryption",
32041
+ () => trpc.userPreferences.setupEncryption.mutate(input)
32042
+ ),
32043
+ rewrapEncryption: (input) => call(
32044
+ "userPreferences.rewrapEncryption",
32045
+ () => trpc.userPreferences.rewrapEncryption.mutate(input)
32046
+ ),
32047
+ resetEncryption: (input) => call(
32048
+ "userPreferences.resetEncryption",
32049
+ () => trpc.userPreferences.resetEncryption.mutate(input)
32050
+ ),
31525
32051
  listDirectory: (input) => call("files.listDirectory", () => trpc.files.listDirectory.query(input)),
31526
32052
  listDirectoryByRef: (input) => call(
31527
32053
  "files.listDirectoryByRef",
@@ -31640,61 +32166,307 @@ var createClient = (config2) => {
31640
32166
 
31641
32167
  // src/state.ts
31642
32168
  import { homedir } from "os";
32169
+ import path19 from "path";
32170
+ import { readFile as readFile6 } from "fs/promises";
32171
+
32172
+ // src/credentials/ensurePrivateDir.ts
32173
+ import { chmod as chmod2, mkdir as mkdir5, stat as stat4 } from "fs/promises";
32174
+
32175
+ // src/credentials/UnsafeCredentialPathError.ts
32176
+ var UnsafeCredentialPathError = class extends Error {
32177
+ constructor(filePath, reason) {
32178
+ super(
32179
+ `Refusing to use credential path ${filePath}: ${reason}. Remove or fix it, then run \`fm auth login\` again.`
32180
+ );
32181
+ this.name = "UnsafeCredentialPathError";
32182
+ }
32183
+ };
32184
+
32185
+ // src/credentials/usesPosixPermissions.ts
32186
+ var usesPosixPermissions = () => process.platform !== "win32";
32187
+
32188
+ // src/credentials/assertOwnedByCurrentUser.ts
32189
+ var assertOwnedByCurrentUser = (filePath, stats) => {
32190
+ if (!usesPosixPermissions() || typeof process.getuid !== "function") {
32191
+ return;
32192
+ }
32193
+ const uid = process.getuid();
32194
+ if (stats.uid !== uid) {
32195
+ throw new UnsafeCredentialPathError(
32196
+ filePath,
32197
+ `it is owned by uid ${stats.uid}, not the current user (uid ${uid})`
32198
+ );
32199
+ }
32200
+ };
32201
+
32202
+ // src/credentials/hasBroaderMode.ts
32203
+ var hasBroaderMode = (stats) => usesPosixPermissions() && (stats.mode & 63) !== 0;
32204
+
32205
+ // src/credentials/privateModes.ts
32206
+ var privateModes = {
32207
+ directory: 448,
32208
+ file: 384
32209
+ };
32210
+
32211
+ // src/credentials/ensurePrivateDir.ts
32212
+ var ensurePrivateDir = async (dirPath) => {
32213
+ await mkdir5(dirPath, { recursive: true, mode: privateModes.directory });
32214
+ const stats = await stat4(dirPath);
32215
+ if (!stats.isDirectory()) {
32216
+ throw new UnsafeCredentialPathError(dirPath, "it is not a directory");
32217
+ }
32218
+ assertOwnedByCurrentUser(dirPath, stats);
32219
+ if (hasBroaderMode(stats)) {
32220
+ await chmod2(dirPath, privateModes.directory);
32221
+ }
32222
+ };
32223
+
32224
+ // src/credentials/credentialsPath.ts
31643
32225
  import path16 from "path";
31644
- import { mkdir as mkdir5, readFile as readFile6, rename as rename3, writeFile as writeFile4 } from "fs/promises";
32226
+ var credentialsPath = (stateDir) => path16.join(stateDir, "credentials.json");
32227
+
32228
+ // src/credentials/readPrivateFile.ts
32229
+ import { constants as constants2 } from "fs";
32230
+ import { open } from "fs/promises";
32231
+
32232
+ // src/credentials/noFollowFlag.ts
32233
+ import { constants } from "fs";
32234
+ var noFollowFlag = () => constants.O_NOFOLLOW ?? 0;
32235
+
32236
+ // src/credentials/readPrivateFile.ts
32237
+ var readPrivateFile = async (filePath) => {
32238
+ let handle;
32239
+ try {
32240
+ handle = await open(filePath, constants2.O_RDONLY | noFollowFlag());
32241
+ } catch (error51) {
32242
+ const code = error51.code;
32243
+ if (code === "ENOENT") {
32244
+ return null;
32245
+ }
32246
+ if (code === "ELOOP" || code === "EMLINK") {
32247
+ throw new UnsafeCredentialPathError(filePath, "it is a symbolic link");
32248
+ }
32249
+ throw error51;
32250
+ }
32251
+ try {
32252
+ const stats = await handle.stat();
32253
+ if (!stats.isFile()) {
32254
+ throw new UnsafeCredentialPathError(filePath, "it is not a regular file");
32255
+ }
32256
+ assertOwnedByCurrentUser(filePath, stats);
32257
+ if (hasBroaderMode(stats)) {
32258
+ await handle.chmod(privateModes.file);
32259
+ }
32260
+ return await handle.readFile("utf8");
32261
+ } finally {
32262
+ await handle.close();
32263
+ }
32264
+ };
32265
+
32266
+ // src/credentials/readStoredToken.ts
32267
+ var readStoredToken = async (stateDir) => {
32268
+ const raw = await readPrivateFile(credentialsPath(stateDir));
32269
+ if (raw === null) {
32270
+ return null;
32271
+ }
32272
+ try {
32273
+ const parsed = JSON.parse(raw);
32274
+ return typeof parsed.token === "string" && parsed.token ? parsed.token : null;
32275
+ } catch {
32276
+ return null;
32277
+ }
32278
+ };
32279
+
32280
+ // src/credentials/writePrivateFileAtomic.ts
32281
+ import { constants as constants3 } from "fs";
32282
+ import { open as open2, rename as rename3, rm as rm4 } from "fs/promises";
32283
+ import path18 from "path";
32284
+
32285
+ // src/credentials/lstatIfExists.ts
32286
+ import { lstat as lstat2 } from "fs/promises";
32287
+ var lstatIfExists = async (filePath) => {
32288
+ try {
32289
+ return await lstat2(filePath);
32290
+ } catch (error51) {
32291
+ if (error51.code === "ENOENT") {
32292
+ return null;
32293
+ }
32294
+ throw error51;
32295
+ }
32296
+ };
32297
+
32298
+ // src/credentials/assertReplaceableFile.ts
32299
+ var assertReplaceableFile = async (filePath) => {
32300
+ const stats = await lstatIfExists(filePath);
32301
+ if (!stats) {
32302
+ return;
32303
+ }
32304
+ if (stats.isSymbolicLink()) {
32305
+ throw new UnsafeCredentialPathError(filePath, "it is a symbolic link");
32306
+ }
32307
+ if (!stats.isFile()) {
32308
+ throw new UnsafeCredentialPathError(filePath, "it is not a regular file");
32309
+ }
32310
+ assertOwnedByCurrentUser(filePath, stats);
32311
+ };
32312
+
32313
+ // src/credentials/privateTempPath.ts
32314
+ import { randomBytes } from "crypto";
32315
+ import path17 from "path";
32316
+ var privateTempPath = (filePath) => path17.join(
32317
+ path17.dirname(filePath),
32318
+ `.${path17.basename(filePath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`
32319
+ );
32320
+
32321
+ // src/credentials/writePrivateFileAtomic.ts
32322
+ var writePrivateFileAtomic = async (filePath, text, hooks = {}) => {
32323
+ await ensurePrivateDir(path18.dirname(filePath));
32324
+ await assertReplaceableFile(filePath);
32325
+ const tempPath = privateTempPath(filePath);
32326
+ const handle = await open2(
32327
+ tempPath,
32328
+ constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | noFollowFlag(),
32329
+ privateModes.file
32330
+ );
32331
+ try {
32332
+ try {
32333
+ await handle.chmod(privateModes.file);
32334
+ await handle.writeFile(text, "utf8");
32335
+ await handle.sync();
32336
+ } finally {
32337
+ await handle.close();
32338
+ }
32339
+ await hooks.beforeRename?.(tempPath);
32340
+ await rename3(tempPath, filePath);
32341
+ } catch (error51) {
32342
+ await rm4(tempPath, { force: true }).catch(() => {
32343
+ });
32344
+ throw error51;
32345
+ }
32346
+ };
32347
+
32348
+ // src/credentials/writeStoredToken.ts
32349
+ var writeStoredToken = async (stateDir, token, hooks) => {
32350
+ await writePrivateFileAtomic(
32351
+ credentialsPath(stateDir),
32352
+ `${JSON.stringify({ token }, null, 2)}
32353
+ `,
32354
+ hooks
32355
+ );
32356
+ };
32357
+
32358
+ // src/credentials/migrateLegacyConfigToken.ts
32359
+ var migrateLegacyConfigToken = async (stateDir, legacyToken, rewriteConfigWithoutToken) => {
32360
+ if (typeof legacyToken === "string" && legacyToken) {
32361
+ const storedToken = await readStoredToken(stateDir);
32362
+ if (!storedToken) {
32363
+ await writeStoredToken(stateDir, legacyToken);
32364
+ }
32365
+ }
32366
+ await rewriteConfigWithoutToken();
32367
+ };
32368
+
32369
+ // src/state.ts
31645
32370
  var DEFAULT_STATE_DIRNAME = ".forum";
31646
32371
  var DEFAULT_POLL_INTERVAL_MS = 4e3;
31647
32372
  var DEFAULT_API_BASE_URL = "https://api.forumlabs.net";
31648
- var DEFAULT_CONFIG = {
31649
- token: null,
31650
- pollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
31651
- forceWrites: false
31652
- };
31653
- var defaultStateDir = () => path16.join(homedir(), DEFAULT_STATE_DIRNAME);
31654
- var configPath = (stateDir) => path16.join(stateDir, "config.json");
32373
+ var defaultStateDir = () => path19.join(homedir(), DEFAULT_STATE_DIRNAME);
32374
+ var configPath = (stateDir) => path19.join(stateDir, "config.json");
31655
32375
  var ensureStateDir = async (stateDir) => {
31656
- await mkdir5(stateDir, { recursive: true });
32376
+ await ensurePrivateDir(stateDir);
31657
32377
  };
31658
- var readJson = async (filePath, fallback) => {
32378
+ var readRawConfig = async (stateDir) => {
31659
32379
  try {
31660
- const raw = await readFile6(filePath, "utf8");
31661
- return JSON.parse(raw);
32380
+ const raw = await readFile6(configPath(stateDir), "utf8");
32381
+ const parsed = JSON.parse(raw);
32382
+ return parsed && typeof parsed === "object" ? parsed : {};
31662
32383
  } catch {
31663
- return fallback;
32384
+ return {};
31664
32385
  }
31665
32386
  };
31666
- var writeJsonAtomic = async (filePath, value) => {
31667
- const parentDir = path16.dirname(filePath);
31668
- const tempPath = path16.join(
31669
- parentDir,
31670
- `.${path16.basename(filePath)}.${process.pid}.${Date.now()}.tmp`
32387
+ var normalizeSettings = (raw) => ({
32388
+ pollIntervalMs: typeof raw.pollIntervalMs === "number" && raw.pollIntervalMs > 0 ? raw.pollIntervalMs : DEFAULT_POLL_INTERVAL_MS,
32389
+ forceWrites: raw.forceWrites === true
32390
+ });
32391
+ var writeConfig = async (stateDir, settings) => {
32392
+ const persisted = {
32393
+ pollIntervalMs: settings.pollIntervalMs,
32394
+ forceWrites: settings.forceWrites
32395
+ };
32396
+ await writePrivateFileAtomic(
32397
+ configPath(stateDir),
32398
+ JSON.stringify(persisted, null, 2)
31671
32399
  );
31672
- await mkdir5(parentDir, { recursive: true });
31673
- await writeFile4(tempPath, JSON.stringify(value, null, 2), "utf8");
31674
- await rename3(tempPath, filePath);
31675
32400
  };
31676
32401
  var readConfig = async (stateDir) => {
31677
- const config2 = await readJson(
31678
- configPath(stateDir),
31679
- DEFAULT_CONFIG
31680
- );
32402
+ const raw = await readRawConfig(stateDir);
32403
+ const settings = normalizeSettings(raw);
32404
+ if ("token" in raw) {
32405
+ await migrateLegacyConfigToken(
32406
+ stateDir,
32407
+ raw.token,
32408
+ () => writeConfig(stateDir, settings)
32409
+ );
32410
+ }
31681
32411
  return {
31682
- token: typeof config2.token === "string" ? config2.token : null,
31683
- pollIntervalMs: typeof config2.pollIntervalMs === "number" && config2.pollIntervalMs > 0 ? config2.pollIntervalMs : DEFAULT_POLL_INTERVAL_MS,
31684
- forceWrites: config2.forceWrites === true
32412
+ ...settings,
32413
+ token: await readStoredToken(stateDir)
31685
32414
  };
31686
32415
  };
31687
- var writeConfig = async (stateDir, config2) => {
31688
- await writeJsonAtomic(configPath(stateDir), config2);
32416
+
32417
+ // src/credentials/removePrivateFile.ts
32418
+ import { rm as rm5 } from "fs/promises";
32419
+ var removePrivateFile = async (filePath) => {
32420
+ await rm5(filePath, { force: true });
32421
+ };
32422
+
32423
+ // src/credentials/deleteStoredToken.ts
32424
+ var deleteStoredToken = async (stateDir) => {
32425
+ await removePrivateFile(credentialsPath(stateDir));
32426
+ };
32427
+
32428
+ // src/credentials/redactedSecrets.ts
32429
+ var redactedSecrets = /* @__PURE__ */ new Set();
32430
+
32431
+ // src/credentials/redactSecrets.ts
32432
+ var redactedPlaceholder = "[REDACTED]";
32433
+ var redactSecrets = (text) => {
32434
+ let redacted = text;
32435
+ for (const secret of redactedSecrets) {
32436
+ redacted = redacted.split(secret).join(redactedPlaceholder);
32437
+ }
32438
+ return redacted;
32439
+ };
32440
+
32441
+ // src/credentials/redactError.ts
32442
+ var redactError = (error51) => {
32443
+ if (!(error51 instanceof Error)) {
32444
+ return redactSecrets(String(error51));
32445
+ }
32446
+ const message = redactSecrets(error51.message);
32447
+ if (message === error51.message) {
32448
+ return error51;
32449
+ }
32450
+ const redacted = new Error(message);
32451
+ redacted.name = error51.name;
32452
+ return redacted;
32453
+ };
32454
+
32455
+ // src/credentials/registerRedactedSecret.ts
32456
+ var minimumRedactableLength = 4;
32457
+ var registerRedactedSecret = (secret) => {
32458
+ if (secret && secret.length >= minimumRedactableLength) {
32459
+ redactedSecrets.add(secret);
32460
+ }
31689
32461
  };
31690
32462
 
31691
32463
  // src/expandHomePath.ts
31692
32464
  import os from "os";
31693
- import path17 from "path";
32465
+ import path20 from "path";
31694
32466
  var expandHomePath = (input) => {
31695
32467
  const home = process.env.HOME || os.homedir();
31696
32468
  if (input === "~") return home;
31697
- return input.startsWith("~/") ? path17.join(home, input.slice(2)) : input;
32469
+ return input.startsWith("~/") ? path20.join(home, input.slice(2)) : input;
31698
32470
  };
31699
32471
 
31700
32472
  // src/pathExists.ts
@@ -31727,9 +32499,9 @@ var parseSkillAgents = (value) => {
31727
32499
  import os2 from "os";
31728
32500
 
31729
32501
  // src/skills/createSkillClient.ts
31730
- import path18 from "path";
32502
+ import path21 from "path";
31731
32503
  var createSkillClient = async (options2) => {
31732
- const stateDir = options2.stateDir ? path18.resolve(options2.stateDir) : defaultStateDir();
32504
+ const stateDir = options2.stateDir ? path21.resolve(options2.stateDir) : defaultStateDir();
31733
32505
  const saved = await readConfig(stateDir);
31734
32506
  const apiBaseUrl = (process.env.DOCTRINE_API_URL || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
31735
32507
  const token = options2.token || process.env.DOCTRINE_TOKEN || saved.token;
@@ -31839,12 +32611,12 @@ var promptSkillConnection = async (client, input) => {
31839
32611
  };
31840
32612
 
31841
32613
  // src/skills/loadSkillStubs.ts
31842
- import { lstat as lstat4, mkdir as mkdir6, open, unlink } from "fs/promises";
31843
- import path22 from "path";
32614
+ import { lstat as lstat5, mkdir as mkdir6, open as open3, unlink } from "fs/promises";
32615
+ import path25 from "path";
31844
32616
 
31845
32617
  // src/skills/planSkillStubs.ts
31846
- import { lstat as lstat3, readdir as readdir5, readFile as readFile8 } from "fs/promises";
31847
- import path20 from "path";
32618
+ import { lstat as lstat4, readdir as readdir5, readFile as readFile8 } from "fs/promises";
32619
+ import path23 from "path";
31848
32620
  import { isDeepStrictEqual } from "util";
31849
32621
 
31850
32622
  // src/skills/createSkillStub.ts
@@ -31871,23 +32643,23 @@ var createSkillStub = (item, source) => [
31871
32643
  ].join("\n");
31872
32644
 
31873
32645
  // src/skills/readSkillStubMarker.ts
31874
- import { lstat as lstat2, readFile as readFile7, readdir as readdir4 } from "fs/promises";
31875
- import path19 from "path";
32646
+ import { lstat as lstat3, readFile as readFile7, readdir as readdir4 } from "fs/promises";
32647
+ import path22 from "path";
31876
32648
  import { createHash as createHash3 } from "crypto";
31877
32649
  var readSkillStubMarker = async (directory) => {
31878
- const stat4 = await lstat2(directory).catch((error51) => {
32650
+ const stat5 = await lstat3(directory).catch((error51) => {
31879
32651
  if (error51.code === "ENOENT") return null;
31880
32652
  throw error51;
31881
32653
  });
31882
- if (!stat4) return null;
31883
- if (!stat4.isDirectory() || stat4.isSymbolicLink())
32654
+ if (!stat5) return null;
32655
+ if (!stat5.isDirectory() || stat5.isSymbolicLink())
31884
32656
  throw new Error(
31885
32657
  `Skill destination is not a regular directory: ${directory}`
31886
32658
  );
31887
- const markerPath = path19.join(directory, ".forum-skill.json");
32659
+ const markerPath = path22.join(directory, ".forum-skill.json");
31888
32660
  const names = await readdir4(directory);
31889
32661
  if (!names.includes(".forum-skill.json")) return null;
31890
- const markerStat = await lstat2(markerPath);
32662
+ const markerStat = await lstat3(markerPath);
31891
32663
  if (!markerStat.isFile() || markerStat.isSymbolicLink())
31892
32664
  throw new Error(`Invalid Forum skill marker: ${markerPath}`);
31893
32665
  const marker = JSON.parse(
@@ -31900,8 +32672,8 @@ var readSkillStubMarker = async (directory) => {
31900
32672
  throw new Error(
31901
32673
  `Skill contains local files; refusing to replace it: ${directory}`
31902
32674
  );
31903
- const stubPath = path19.join(directory, "SKILL.md");
31904
- const stubStat = await lstat2(stubPath);
32675
+ const stubPath = path22.join(directory, "SKILL.md");
32676
+ const stubStat = await lstat3(stubPath);
31905
32677
  if (!stubStat.isFile() || stubStat.isSymbolicLink())
31906
32678
  throw new Error(`Invalid generated skill: ${stubPath}`);
31907
32679
  const content = await readFile7(stubPath, "utf8");
@@ -31923,7 +32695,7 @@ var planSkillStubs = async (input, roots) => {
31923
32695
  }
31924
32696
  );
31925
32697
  for (const item of input.skills) {
31926
- const destination = path20.join(root, item.slug);
32698
+ const destination = path23.join(root, item.slug);
31927
32699
  const exists2 = directories.some((entry) => entry.name === item.slug);
31928
32700
  const marker = exists2 ? await readSkillStubMarker(destination) : null;
31929
32701
  if (exists2 && (!marker || !isDeepStrictEqual(marker.source, input.source)))
@@ -31931,7 +32703,7 @@ var planSkillStubs = async (input, roots) => {
31931
32703
  `Skill name collision: ${destination}. Choose a different slug; existing skills are never overwritten.`
31932
32704
  );
31933
32705
  const content = createSkillStub(item, input.source);
31934
- const unchanged = marker && await readFile8(path20.join(destination, "SKILL.md"), "utf8") === content;
32706
+ const unchanged = marker && await readFile8(path23.join(destination, "SKILL.md"), "utf8") === content;
31935
32707
  changes.push({
31936
32708
  agent,
31937
32709
  slug: item.slug,
@@ -31944,9 +32716,9 @@ var planSkillStubs = async (input, roots) => {
31944
32716
  for (const entry of directories) {
31945
32717
  if (!entry.isDirectory() || entry.isSymbolicLink() || slugs.has(entry.name) || entry.name.startsWith("."))
31946
32718
  continue;
31947
- const destination = path20.join(root, entry.name);
31948
- const markerPath = path20.join(destination, ".forum-skill.json");
31949
- const markerStat = await lstat3(markerPath).catch(
32719
+ const destination = path23.join(root, entry.name);
32720
+ const markerPath = path23.join(destination, ".forum-skill.json");
32721
+ const markerStat = await lstat4(markerPath).catch(
31950
32722
  (error51) => {
31951
32723
  if (error51.code === "ENOENT") return null;
31952
32724
  throw error51;
@@ -31969,15 +32741,15 @@ var planSkillStubs = async (input, roots) => {
31969
32741
 
31970
32742
  // src/skills/applySkillStubChanges.ts
31971
32743
  import { createHash as createHash4 } from "crypto";
31972
- import { mkdtemp, rename as rename4, rm as rm4, writeFile as writeFile5 } from "fs/promises";
31973
- import path21 from "path";
32744
+ import { mkdtemp, rename as rename4, rm as rm6, writeFile as writeFile4 } from "fs/promises";
32745
+ import path24 from "path";
31974
32746
  var applySkillStubChanges = async (changes, source) => {
31975
32747
  const applied = [];
31976
32748
  try {
31977
32749
  for (const change of changes) {
31978
32750
  if (change.action === "unchanged") continue;
31979
32751
  const temporary = await mkdtemp(
31980
- path21.join(path21.dirname(change.path), ".forum-skills-")
32752
+ path24.join(path24.dirname(change.path), ".forum-skills-")
31981
32753
  );
31982
32754
  const entry = {
31983
32755
  change,
@@ -31993,9 +32765,9 @@ var applySkillStubChanges = async (changes, source) => {
31993
32765
  source,
31994
32766
  hash: createHash4("sha256").update(content).digest("hex")
31995
32767
  };
31996
- await writeFile5(path21.join(temporary, "SKILL.md"), content, "utf8");
31997
- await writeFile5(
31998
- path21.join(temporary, ".forum-skill.json"),
32768
+ await writeFile4(path24.join(temporary, "SKILL.md"), content, "utf8");
32769
+ await writeFile4(
32770
+ path24.join(temporary, ".forum-skill.json"),
31999
32771
  `${JSON.stringify(marker, null, 2)}
32000
32772
  `,
32001
32773
  "utf8"
@@ -32013,15 +32785,15 @@ var applySkillStubChanges = async (changes, source) => {
32013
32785
  }
32014
32786
  } catch (error51) {
32015
32787
  for (const entry of applied.toReversed()) {
32016
- if (entry.installed) await rm4(entry.change.path, { recursive: true });
32788
+ if (entry.installed) await rm6(entry.change.path, { recursive: true });
32017
32789
  if (entry.backup) await rename4(entry.backup, entry.change.path);
32018
- await rm4(entry.temporary, { recursive: true, force: true });
32790
+ await rm6(entry.temporary, { recursive: true, force: true });
32019
32791
  }
32020
32792
  throw error51;
32021
32793
  }
32022
32794
  for (const entry of applied) {
32023
- if (entry.backup) await rm4(entry.backup, { recursive: true });
32024
- await rm4(entry.temporary, { recursive: true, force: true });
32795
+ if (entry.backup) await rm6(entry.backup, { recursive: true });
32796
+ await rm6(entry.temporary, { recursive: true, force: true });
32025
32797
  }
32026
32798
  };
32027
32799
 
@@ -32032,30 +32804,30 @@ var loadSkillStubs = async (input) => {
32032
32804
  throw new Error("Use a canonical store folder path.");
32033
32805
  if (new Set(input.skills.map((skill) => skill.slug)).size !== input.skills.length)
32034
32806
  throw new Error("Duplicate skill names in collection.");
32035
- const base = path22.resolve(input.global ? input.home : input.directory);
32807
+ const base = path25.resolve(input.global ? input.home : input.directory);
32036
32808
  const roots = [...new Set(input.agents)].map((agent) => ({
32037
32809
  agent,
32038
- root: path22.join(base, agent === "codex" ? ".agents" : ".claude", "skills")
32810
+ root: path25.join(base, agent === "codex" ? ".agents" : ".claude", "skills")
32039
32811
  }));
32040
32812
  const locks = [];
32041
32813
  try {
32042
32814
  for (const { root } of roots) {
32043
- for (const directory of [path22.dirname(root), root]) {
32044
- const stat4 = await lstat4(directory).catch(
32815
+ for (const directory of [path25.dirname(root), root]) {
32816
+ const stat5 = await lstat5(directory).catch(
32045
32817
  (error51) => {
32046
32818
  if (error51.code === "ENOENT") return null;
32047
32819
  throw error51;
32048
32820
  }
32049
32821
  );
32050
- if (stat4 && (!stat4.isDirectory() || stat4.isSymbolicLink()))
32822
+ if (stat5 && (!stat5.isDirectory() || stat5.isSymbolicLink()))
32051
32823
  throw new Error(
32052
32824
  `Skill root must be a regular directory: ${directory}`
32053
32825
  );
32054
32826
  }
32055
32827
  if (!input.dryRun) {
32056
32828
  await mkdir6(root, { recursive: true });
32057
- const lockPath = path22.join(root, ".forum-skills.lock");
32058
- const file2 = await open(lockPath, "wx").catch(
32829
+ const lockPath = path25.join(root, ".forum-skills.lock");
32830
+ const file2 = await open3(lockPath, "wx").catch(
32059
32831
  (error51) => {
32060
32832
  if (error51.code === "EEXIST")
32061
32833
  throw new Error(
@@ -32072,9 +32844,9 @@ var loadSkillStubs = async (input) => {
32072
32844
  return {
32073
32845
  dryRun: input.dryRun,
32074
32846
  source: input.source,
32075
- changes: changes.map(({ agent, path: path25, slug, action }) => ({
32847
+ changes: changes.map(({ agent, path: path28, slug, action }) => ({
32076
32848
  agent,
32077
- path: path25,
32849
+ path: path28,
32078
32850
  slug,
32079
32851
  action
32080
32852
  }))
@@ -32649,21 +33421,191 @@ var decryptTextForRecipientSecret = async (encryptedText, secretArg) => {
32649
33421
  }
32650
33422
  };
32651
33423
 
33424
+ // src/describeRekeyIssues.ts
33425
+ var reasonText = {
33426
+ public_key_unavailable: "their current public encryption key is unavailable, so the new file key cannot be wrapped for them",
33427
+ 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)",
33428
+ secret_not_retained: "its secret is not stored by Forum, so it cannot be carried onto a new file key"
33429
+ };
33430
+ var describeRekeyIssues = (issues) => [
33431
+ "Rekeying would not preserve every remaining recipient:",
33432
+ ...issues.map(
33433
+ (issue2) => ` - ${issue2.label ?? issue2.recipientId} (${issue2.recipientId}): ${reasonText[issue2.reason]}.`
33434
+ ),
33435
+ "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."
33436
+ ].join("\n");
33437
+
33438
+ // src/resolveRecipientPublicKeys.ts
33439
+ var resolveRecipientPublicKeys = async ({
33440
+ actor,
33441
+ lookupPublicKeys,
33442
+ recipients
33443
+ }) => {
33444
+ const userIds = [
33445
+ ...new Set(
33446
+ recipients.filter((recipient) => recipient.recipientId !== actor.keyId).map((recipient) => parseUserRecipientLabel(recipient.label)?.userId).filter((userId) => Boolean(userId))
33447
+ )
33448
+ ];
33449
+ const others = userIds.length ? await lookupPublicKeys(userIds) : [];
33450
+ const actorKey = actor.version === 3 ? { keyId: actor.keyId, publicKey: actor.publicKey, version: 3 } : { keyId: actor.keyId, publicKey: actor.publicKey, version: 2 };
33451
+ return [
33452
+ {
33453
+ trustedFingerprint: await verifyUserEncryptionPublicKey(actorKey),
33454
+ userEncryption: actorKey
33455
+ },
33456
+ ...others.flatMap(
33457
+ (entry) => entry.encryption ? [
33458
+ {
33459
+ ...entry.trustedFingerprint ? { trustedFingerprint: entry.trustedFingerprint } : {},
33460
+ userEncryption: entry.encryption
33461
+ }
33462
+ ] : []
33463
+ )
33464
+ ];
33465
+ };
33466
+
33467
+ // src/resolveRecipientSelectors.ts
33468
+ var resolveRecipientSelectors = ({
33469
+ recipients,
33470
+ selectors
33471
+ }) => selectors.map((selector) => {
33472
+ const byId = recipients.find(
33473
+ (recipient) => recipient.recipientId === selector
33474
+ );
33475
+ if (byId) {
33476
+ return byId.recipientId;
33477
+ }
33478
+ const byLabel = recipients.filter(
33479
+ (recipient) => recipient.label === selector
33480
+ );
33481
+ if (byLabel.length === 1) {
33482
+ return byLabel[0].recipientId;
33483
+ }
33484
+ if (byLabel.length > 1) {
33485
+ throw new Error(
33486
+ `Several recipients are labelled "${selector}"; select one by recipient id: ${byLabel.map((recipient) => recipient.recipientId).join(", ")}`
33487
+ );
33488
+ }
33489
+ throw new Error(`No recipient matches "${selector}".`);
33490
+ });
33491
+
33492
+ // src/rekeyEncryptedTextForUser.ts
33493
+ var rekeyEncryptedTextForUser = async ({
33494
+ encryptedText,
33495
+ lookupPublicKeys,
33496
+ password,
33497
+ reissue,
33498
+ remove,
33499
+ userEncryption
33500
+ }) => {
33501
+ if (userEncryption.version === 1) {
33502
+ throw new Error(
33503
+ "Legacy encryption must be migrated before rekeying (run `fm encryption migrate`)."
33504
+ );
33505
+ }
33506
+ const { recipients } = parseEncryptedPlainTextPayload(encryptedText);
33507
+ if (!findEncryptionRecipient({
33508
+ recipients,
33509
+ recipientId: userEncryption.keyId
33510
+ })) {
33511
+ throw new Error(
33512
+ "You are not a recipient of this file, so its key cannot be unwrapped."
33513
+ );
33514
+ }
33515
+ const removeRecipientIds = resolveRecipientSelectors({
33516
+ recipients,
33517
+ selectors: remove
33518
+ });
33519
+ const reissueRecipientIds = resolveRecipientSelectors({
33520
+ recipients,
33521
+ selectors: reissue
33522
+ });
33523
+ const userKey = await unlockUserEncryption({
33524
+ metadata: userEncryption,
33525
+ password
33526
+ });
33527
+ const fileKey = await unwrapFileKey({
33528
+ recipients,
33529
+ recipientId: userEncryption.keyId,
33530
+ userKey
33531
+ });
33532
+ const candidates = await resolveRecipientPublicKeys({
33533
+ actor: userEncryption,
33534
+ lookupPublicKeys,
33535
+ recipients
33536
+ });
33537
+ const { issues, plan } = planRecipientRekey({
33538
+ candidates,
33539
+ recipients,
33540
+ reissueRecipientIds,
33541
+ removeRecipientIds
33542
+ });
33543
+ if (issues.length) {
33544
+ throw new Error(describeRekeyIssues(issues));
33545
+ }
33546
+ const result = await rekeyEncryptedPlainText({
33547
+ actorKeyId: userEncryption.keyId,
33548
+ actorUserKey: userKey,
33549
+ encryptedText,
33550
+ fileKey,
33551
+ plan
33552
+ });
33553
+ return {
33554
+ encryptedText: result.encryptedText,
33555
+ issuedSecrets: result.issuedSecrets,
33556
+ removedRecipientIds: result.removedRecipientIds
33557
+ };
33558
+ };
33559
+
32652
33560
  // src/addExternalRecipient.ts
32653
33561
  var addExternalRecipientToEncryptedText = async ({
32654
33562
  encryptedText,
32655
33563
  force,
33564
+ lookupPublicKeys,
32656
33565
  name,
32657
33566
  password,
33567
+ reissue = [],
33568
+ remove = [],
32658
33569
  userEncryption
32659
33570
  }) => {
32660
33571
  const payload = parseEncryptedPlainTextPayload(encryptedText);
32661
- const duplicate = payload.recipients.some(
33572
+ const duplicates = payload.recipients.filter(
32662
33573
  (recipient2) => recipient2.label === name
32663
33574
  );
32664
- if (duplicate && !force) {
33575
+ if (duplicates.length && !force) {
32665
33576
  throw new Error(
32666
- `A recipient named "${name}" already exists in this file. Pass --force to replace it.`
33577
+ `A recipient named "${name}" already exists in this file. Pass --force to replace it; this rekeys the file so the old secret cannot read future versions.`
33578
+ );
33579
+ }
33580
+ if (duplicates.length) {
33581
+ const [replaced, ...extraDuplicates] = duplicates.map(
33582
+ (recipient2) => recipient2.recipientId
33583
+ );
33584
+ const result = await rekeyEncryptedTextForUser({
33585
+ encryptedText,
33586
+ lookupPublicKeys,
33587
+ password,
33588
+ reissue: [replaced, ...reissue],
33589
+ remove: [...extraDuplicates, ...remove],
33590
+ userEncryption
33591
+ });
33592
+ const replacement = result.issuedSecrets.find(
33593
+ (issued) => issued.previousRecipientId === replaced
33594
+ );
33595
+ return {
33596
+ encryptedText: result.encryptedText,
33597
+ otherIssuedSecrets: result.issuedSecrets.filter(
33598
+ (issued) => issued !== replacement
33599
+ ),
33600
+ rekeyed: true,
33601
+ recipientId: replacement.recipientId,
33602
+ removedRecipientIds: result.removedRecipientIds,
33603
+ secret: replacement.secret
33604
+ };
33605
+ }
33606
+ if (remove.length || reissue.length) {
33607
+ throw new Error(
33608
+ "--remove/--reissue only apply when replacing a recipient with --force; use `fm encrypt-rekey` to revoke recipients."
32667
33609
  );
32668
33610
  }
32669
33611
  const userKey = await unlockUserEncryption({
@@ -32679,13 +33621,15 @@ var addExternalRecipientToEncryptedText = async ({
32679
33621
  fileKey,
32680
33622
  name
32681
33623
  });
32682
- const retained = force ? payload.recipients.filter((existing) => existing.label !== name) : payload.recipients;
32683
33624
  return {
32684
33625
  encryptedText: updateEncryptedPlainTextRecipients({
32685
33626
  encryptedText,
32686
- recipients: [...retained, recipient]
33627
+ recipients: [...payload.recipients, recipient]
32687
33628
  }),
33629
+ otherIssuedSecrets: [],
33630
+ rekeyed: false,
32688
33631
  recipientId: recipient.recipientId,
33632
+ removedRecipientIds: [],
32689
33633
  secret
32690
33634
  };
32691
33635
  };
@@ -32740,17 +33684,186 @@ var editEncryptedText = async ({
32740
33684
  return { changed: true, encryptedText: reencrypted };
32741
33685
  };
32742
33686
 
33687
+ // src/encryptionIdentity/changeEncryptionPassword.ts
33688
+ var changeEncryptionPassword = async ({
33689
+ client,
33690
+ currentPassword,
33691
+ nextPassword
33692
+ }) => {
33693
+ const { encryption } = await client.readUserPreferences();
33694
+ if (!encryption) {
33695
+ throw new Error("Encryption is not set up. Run `fm encryption setup`.");
33696
+ }
33697
+ const rewrapped = await rewrapUserEncryption({
33698
+ currentPassword,
33699
+ metadata: encryption,
33700
+ nextPassword
33701
+ });
33702
+ await client.rewrapEncryption({
33703
+ encryption: rewrapped,
33704
+ expectedKeyId: encryption.keyId
33705
+ });
33706
+ return {
33707
+ fingerprint: await computeEncryptionFingerprint(rewrapped.publicKey)
33708
+ };
33709
+ };
33710
+
33711
+ // src/encryptionIdentity/readEncryptionFingerprint.ts
33712
+ var readEncryptionFingerprint = async ({
33713
+ client
33714
+ }) => {
33715
+ const { encryption } = await client.readUserPreferences();
33716
+ if (!encryption) {
33717
+ throw new Error("Encryption is not set up. Run `fm encryption setup`.");
33718
+ }
33719
+ if (encryption.version === 1) {
33720
+ throw new Error(
33721
+ "Legacy encryption has no public identity. Run `fm encryption migrate`."
33722
+ );
33723
+ }
33724
+ return {
33725
+ fingerprint: await computeEncryptionFingerprint(encryption.publicKey),
33726
+ version: encryption.version
33727
+ };
33728
+ };
33729
+
33730
+ // src/encryptionIdentity/resetEncryptionIdentity.ts
33731
+ var resetEncryptionIdentity = async ({
33732
+ client,
33733
+ password
33734
+ }) => {
33735
+ const { encryption } = await client.readUserPreferences();
33736
+ if (!encryption) {
33737
+ throw new Error("Encryption is not set up. Run `fm encryption setup`.");
33738
+ }
33739
+ const { metadata } = await createUserEncryptionSetup(password);
33740
+ await client.resetEncryption({
33741
+ confirmation: "reset-encryption-identity",
33742
+ encryption: metadata,
33743
+ expectedKeyId: encryption.keyId
33744
+ });
33745
+ return { fingerprint: metadata.keyId, previousKeyId: encryption.keyId };
33746
+ };
33747
+
33748
+ // src/encryptionIdentity/setupEncryptionIdentity.ts
33749
+ var setupEncryptionIdentity = async ({
33750
+ client,
33751
+ password
33752
+ }) => {
33753
+ const preferences = await client.readUserPreferences();
33754
+ if (preferences.encryption) {
33755
+ throw new Error(
33756
+ preferences.encryption.version === 1 ? "Legacy encryption is set up. Run `fm encryption migrate` instead." : "Encryption is already set up. Use `fm encryption change-password` or `fm encryption reset`."
33757
+ );
33758
+ }
33759
+ const { metadata } = await createUserEncryptionSetup(password);
33760
+ await client.setupEncryption({ encryption: metadata, expectedKeyId: null });
33761
+ return { fingerprint: metadata.keyId };
33762
+ };
33763
+
33764
+ // src/encryptionIdentity/validateNewEncryptionPassword.ts
33765
+ var validateNewEncryptionPassword = (password) => {
33766
+ if (password.trim().length < 12) {
33767
+ throw new Error("Use at least 12 characters for your encryption password.");
33768
+ }
33769
+ };
33770
+
33771
+ // src/encryptionIdentity/runEncryptionIdentityCommand.ts
33772
+ var encryptionIdentitySubcommands = [
33773
+ "change-password",
33774
+ "fingerprint",
33775
+ "reset",
33776
+ "setup"
33777
+ ];
33778
+ var isEncryptionIdentitySubcommand = (value) => encryptionIdentitySubcommands.includes(value);
33779
+ var runEncryptionIdentityCommand = async ({
33780
+ client,
33781
+ confirmReset,
33782
+ readCurrentPassword,
33783
+ readNewPassword,
33784
+ render,
33785
+ subcommand
33786
+ }) => {
33787
+ if (subcommand === "fingerprint") {
33788
+ const { fingerprint: fingerprint2, version: version2 } = await readEncryptionFingerprint({
33789
+ client
33790
+ });
33791
+ render(formatEncryptionFingerprint(fingerprint2));
33792
+ if (version2 === 2) {
33793
+ render(
33794
+ "This key record predates key binding (v2). It is still checked on unlock; changing your password keeps it as v2."
33795
+ );
33796
+ }
33797
+ return;
33798
+ }
33799
+ if (subcommand === "setup") {
33800
+ const password2 = await readNewPassword();
33801
+ validateNewEncryptionPassword(password2);
33802
+ const { fingerprint: fingerprint2 } = await setupEncryptionIdentity({ client, password: password2 });
33803
+ render(
33804
+ `Encryption set up. Fingerprint: ${formatEncryptionFingerprint(fingerprint2)}`
33805
+ );
33806
+ return;
33807
+ }
33808
+ if (subcommand === "change-password") {
33809
+ const currentPassword = await readCurrentPassword();
33810
+ const nextPassword = await readNewPassword();
33811
+ validateNewEncryptionPassword(nextPassword);
33812
+ const { fingerprint: fingerprint2 } = await changeEncryptionPassword({
33813
+ client,
33814
+ currentPassword,
33815
+ nextPassword
33816
+ });
33817
+ render(
33818
+ `Encryption password changed. Your identity is unchanged: ${formatEncryptionFingerprint(fingerprint2)}`
33819
+ );
33820
+ render(
33821
+ "Copies of your old key record (exports, backups) remain protected by the old password."
33822
+ );
33823
+ return;
33824
+ }
33825
+ if (!await confirmReset()) {
33826
+ render("Reset cancelled.");
33827
+ return;
33828
+ }
33829
+ const password = await readNewPassword();
33830
+ validateNewEncryptionPassword(password);
33831
+ const { fingerprint } = await resetEncryptionIdentity({ client, password });
33832
+ render(
33833
+ `Encryption identity reset. New fingerprint: ${formatEncryptionFingerprint(fingerprint)}`
33834
+ );
33835
+ render(
33836
+ "Files encrypted for your previous identity cannot be opened with the new one. Teammates must verify this fingerprint before granting you access again."
33837
+ );
33838
+ };
33839
+
33840
+ // src/writeTextFileIfUnchanged.ts
33841
+ import { readFile as readFile9 } from "fs/promises";
33842
+ var writeTextFileIfUnchanged = async ({
33843
+ expectedText,
33844
+ filePath,
33845
+ text
33846
+ }) => {
33847
+ const current = await readFile9(filePath, "utf8");
33848
+ if (current !== expectedText) {
33849
+ throw new Error(
33850
+ `${filePath} changed while this command was running; nothing was written. Re-run against the latest version.`
33851
+ );
33852
+ }
33853
+ await atomicWriteTextFile(filePath, text);
33854
+ };
33855
+
32743
33856
  // src/openInEditor.ts
32744
33857
  import { spawn } from "child_process";
32745
- import { mkdtemp as mkdtemp2, readFile as readFile9, rm as rm5, writeFile as writeFile6 } from "fs/promises";
33858
+ import { mkdtemp as mkdtemp2, readFile as readFile10, rm as rm7, writeFile as writeFile5 } from "fs/promises";
32746
33859
  import { tmpdir } from "os";
32747
- import path23 from "path";
33860
+ import path26 from "path";
32748
33861
  var openInEditor = async (currentText, { extension = "" } = {}) => {
32749
33862
  const editor = process.env.EDITOR?.trim() || "vi";
32750
- const dir = await mkdtemp2(path23.join(tmpdir(), "fm-edit-"));
32751
- const tempPath = path23.join(dir, `edit${extension}`);
33863
+ const dir = await mkdtemp2(path26.join(tmpdir(), "fm-edit-"));
33864
+ const tempPath = path26.join(dir, `edit${extension}`);
32752
33865
  try {
32753
- await writeFile6(tempPath, currentText, "utf8");
33866
+ await writeFile5(tempPath, currentText, "utf8");
32754
33867
  const exitCode = await new Promise((resolve, reject) => {
32755
33868
  const child = spawn(
32756
33869
  "/bin/sh",
@@ -32763,9 +33876,9 @@ var openInEditor = async (currentText, { extension = "" } = {}) => {
32763
33876
  if (exitCode !== 0) {
32764
33877
  return null;
32765
33878
  }
32766
- return await readFile9(tempPath, "utf8");
33879
+ return await readFile10(tempPath, "utf8");
32767
33880
  } finally {
32768
- await rm5(dir, { force: true, recursive: true }).catch(() => {
33881
+ await rm7(dir, { force: true, recursive: true }).catch(() => {
32769
33882
  });
32770
33883
  }
32771
33884
  };
@@ -32852,7 +33965,7 @@ var standaloneIncludeId = (paragraph) => {
32852
33965
  var textContent = (file2) => file2?.content && "text" in file2.content ? file2.content.text : null;
32853
33966
  var compileMarkdown = async ({
32854
33967
  entry,
32855
- readFile: readFile11,
33968
+ readFile: readFile12,
32856
33969
  optional: optional2,
32857
33970
  limits = {}
32858
33971
  }) => {
@@ -32896,7 +34009,7 @@ var compileMarkdown = async ({
32896
34009
  throw new Error(`Include cycle: ${[...chain, id].join(" -> ")}`);
32897
34010
  let target;
32898
34011
  try {
32899
- target = await readFile11(id);
34012
+ target = await readFile12(id);
32900
34013
  } catch (error51) {
32901
34014
  if (optional2) {
32902
34015
  warnings.push(`Omitted unreadable include ${id} from ${label}.`);
@@ -32975,7 +34088,8 @@ Usage:
32975
34088
  fm hash <filePath> [--store <storeId>] [--token <jwt>] [--local]
32976
34089
  fm encrypt (<text>|--file|-f <localPath>) [--password <password>] [--token <jwt>]
32977
34090
  fm decrypt (<encrypted-json>|--file|-f <localPath>) [--secret <recipient-secret>] [--password <password>] [--token <jwt>]
32978
- fm encrypt-add-recipient (<encrypted-json>|--file|-f <localPath>) --name <recipient-name> [--force] [--json] [--password <password>] [--token <jwt>]
34091
+ 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>]
34092
+ fm encrypt-rekey (<encrypted-json>|--file|-f <localPath>) [--remove <label-or-id>]... [--reissue <label-or-id>]... [--json] [--password <password>] [--token <jwt>]
32979
34093
  fm edit (<localPath>|--file|-f <localPath>) [--password <password>] [--token <jwt>]
32980
34094
  fm query <filename-or-path> [-s <storeIds>] [--token <jwt>]
32981
34095
  fm q <filename-or-path> [-s <storeIds>] [--token <jwt>]
@@ -33030,7 +34144,7 @@ Usage:
33030
34144
  Auth, config:
33031
34145
  fm auth login|logout|status [--no-open]
33032
34146
  fm config show [--state-dir <path>]
33033
- fm config get <key> [--state-dir <path>]
34147
+ fm config get <key> [--reveal] [--state-dir <path>]
33034
34148
  fm config set <key> <value> [--state-dir <path>]
33035
34149
  fm config unset <key> [--state-dir <path>]
33036
34150
  fm config validate
@@ -33055,7 +34169,9 @@ Encryption:
33055
34169
  Provide your encryption password interactively, via --password, or via DOCTRINE_ENCRYPTION_PASSWORD.
33056
34170
  To decrypt as an external recipient (no account/login), pass --secret <recipient-secret> or set DOCTRINE_RECIPIENT_SECRET.
33057
34171
  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.
33058
- 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.
34172
+ 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.
34173
+ 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.
34174
+ 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.
33059
34175
  API:
33060
34176
  Uses ${DEFAULT_API_BASE_URL} by default. Set DOCTRINE_API_URL for local development.
33061
34177
  Output:
@@ -33064,7 +34180,7 @@ Output:
33064
34180
  `;
33065
34181
  var readCliVersion = async () => {
33066
34182
  const packageJson = JSON.parse(
33067
- await readFile10(new URL("../package.json", import.meta.url), "utf8")
34183
+ await readFile11(new URL("../package.json", import.meta.url), "utf8")
33068
34184
  );
33069
34185
  return typeof packageJson.version === "string" ? packageJson.version : "unknown";
33070
34186
  };
@@ -33115,6 +34231,8 @@ var parseArgs = (argv) => {
33115
34231
  let encryptionPassword = null;
33116
34232
  let recipientSecret = null;
33117
34233
  let recipientName = null;
34234
+ const removeRecipients = [];
34235
+ const reissueRecipients = [];
33118
34236
  let syncPath = null;
33119
34237
  let syncTarget = null;
33120
34238
  let pathsFile = null;
@@ -33131,6 +34249,7 @@ var parseArgs = (argv) => {
33131
34249
  let optional2 = false;
33132
34250
  let stdin = false;
33133
34251
  let readonly2 = false;
34252
+ let reveal = false;
33134
34253
  let verbose = false;
33135
34254
  let watch3 = false;
33136
34255
  let yes = false;
@@ -33178,13 +34297,13 @@ var parseArgs = (argv) => {
33178
34297
  continue;
33179
34298
  }
33180
34299
  if (current === "--file" || current === "-f") {
33181
- inputFilePath = next ? path24.resolve(next) : inputFilePath;
34300
+ inputFilePath = next ? path27.resolve(next) : inputFilePath;
33182
34301
  index += 1;
33183
34302
  continue;
33184
34303
  }
33185
34304
  if (current === "--output" || current === "-o") {
33186
34305
  if (!next) throw new Error(`${current} requires a local output path.`);
33187
- outputFilePath = path24.resolve(next);
34306
+ outputFilePath = path27.resolve(next);
33188
34307
  index += 1;
33189
34308
  continue;
33190
34309
  }
@@ -33211,6 +34330,23 @@ var parseArgs = (argv) => {
33211
34330
  recipientName = current.slice("--name=".length);
33212
34331
  continue;
33213
34332
  }
34333
+ if (current === "--remove" || current === "--reissue") {
34334
+ if (next) {
34335
+ (current === "--remove" ? removeRecipients : reissueRecipients).push(
34336
+ next
34337
+ );
34338
+ }
34339
+ index += 1;
34340
+ continue;
34341
+ }
34342
+ if (current.startsWith("--remove=")) {
34343
+ removeRecipients.push(current.slice("--remove=".length));
34344
+ continue;
34345
+ }
34346
+ if (current.startsWith("--reissue=")) {
34347
+ reissueRecipients.push(current.slice("--reissue=".length));
34348
+ continue;
34349
+ }
33214
34350
  if (current === "--ref") {
33215
34351
  if (!next) {
33216
34352
  throw new Error(
@@ -33241,7 +34377,7 @@ var parseArgs = (argv) => {
33241
34377
  continue;
33242
34378
  }
33243
34379
  if (current === "--state-dir") {
33244
- stateDir = path24.resolve(next ?? stateDir);
34380
+ stateDir = path27.resolve(next ?? stateDir);
33245
34381
  index += 1;
33246
34382
  continue;
33247
34383
  }
@@ -33249,12 +34385,12 @@ var parseArgs = (argv) => {
33249
34385
  if (!next) {
33250
34386
  throw new Error("--paths-file requires a file path.");
33251
34387
  }
33252
- pathsFile = path24.resolve(expandHomePath(next));
34388
+ pathsFile = path27.resolve(expandHomePath(next));
33253
34389
  index += 1;
33254
34390
  continue;
33255
34391
  }
33256
34392
  if (current.startsWith("--paths-file=")) {
33257
- pathsFile = path24.resolve(
34393
+ pathsFile = path27.resolve(
33258
34394
  expandHomePath(current.slice("--paths-file=".length))
33259
34395
  );
33260
34396
  continue;
@@ -33309,6 +34445,10 @@ var parseArgs = (argv) => {
33309
34445
  readonly2 = true;
33310
34446
  continue;
33311
34447
  }
34448
+ if (current === "--reveal") {
34449
+ reveal = true;
34450
+ continue;
34451
+ }
33312
34452
  if (current === "--verbose" || current === "--debug" || current === "-v") {
33313
34453
  verbose = true;
33314
34454
  continue;
@@ -33349,6 +34489,8 @@ var parseArgs = (argv) => {
33349
34489
  encryptionPassword,
33350
34490
  recipientSecret,
33351
34491
  recipientName,
34492
+ removeRecipients,
34493
+ reissueRecipients,
33352
34494
  syncPath,
33353
34495
  syncTarget,
33354
34496
  pathsFile,
@@ -33364,6 +34506,7 @@ var parseArgs = (argv) => {
33364
34506
  optional: optional2,
33365
34507
  stdin,
33366
34508
  readonly: readonly2,
34509
+ reveal,
33367
34510
  verbose,
33368
34511
  watch: watch3,
33369
34512
  yes,
@@ -33404,6 +34547,9 @@ var resolveApiBaseUrl = () => {
33404
34547
  };
33405
34548
  var resolveConfig = async (parsed) => {
33406
34549
  const stored = await readConfig(parsed.stateDir);
34550
+ registerRedactedSecret(stored.token);
34551
+ registerRedactedSecret(parsed.token);
34552
+ registerRedactedSecret(process.env.DOCTRINE_TOKEN);
33407
34553
  return {
33408
34554
  apiBaseUrl: resolveApiBaseUrl(),
33409
34555
  token: parsed.token ?? process.env.DOCTRINE_TOKEN ?? stored.token,
@@ -33438,10 +34584,10 @@ var listDirectoryEntries = async (listDirectory, directoryPath) => {
33438
34584
  if (left.type !== "directory" && right.type === "directory") {
33439
34585
  return 1;
33440
34586
  }
33441
- return path24.basename(left.path).localeCompare(path24.basename(right.path));
34587
+ return path27.basename(left.path).localeCompare(path27.basename(right.path));
33442
34588
  }).forEach((entry) => {
33443
34589
  const suffix = entry.type === "directory" ? "/" : "";
33444
- renderOutput(`${path24.basename(entry.path)}${suffix}`);
34590
+ renderOutput(`${path27.basename(entry.path)}${suffix}`);
33445
34591
  });
33446
34592
  };
33447
34593
  var listStores = async (listStoresMetadata) => {
@@ -33845,7 +34991,7 @@ var readWriteTextInput = async (inlineText, inputFilePath) => {
33845
34991
  throw new Error("Provide either inline text or --file, not both.");
33846
34992
  }
33847
34993
  if (inputFilePath) {
33848
- return readFile10(inputFilePath, "utf8");
34994
+ return readFile11(inputFilePath, "utf8");
33849
34995
  }
33850
34996
  return inlineText ?? null;
33851
34997
  };
@@ -33861,7 +35007,7 @@ var readRemoteTextFile = async (filePath, storeRef, client) => {
33861
35007
  return text;
33862
35008
  };
33863
35009
  var normalizeRemotePath = (input) => {
33864
- const normalized = path24.posix.normalize(`/${input.trim()}`);
35010
+ const normalized = path27.posix.normalize(`/${input.trim()}`);
33865
35011
  if (normalized.includes("\0")) {
33866
35012
  throw new Error("Path contains an invalid null byte.");
33867
35013
  }
@@ -34155,7 +35301,7 @@ var diffRemoteFiles = async ({
34155
35301
  storeRef
34156
35302
  }) => {
34157
35303
  const leftText = await readRemoteTextFile(leftPath, storeRef, client);
34158
- const rightText = localRight ? await readFile10(path24.resolve(rightPath), "utf8") : await readRemoteTextFile(rightPath, storeRef, client);
35304
+ const rightText = localRight ? await readFile11(path27.resolve(rightPath), "utf8") : await readRemoteTextFile(rightPath, storeRef, client);
34159
35305
  return buildUnifiedDiff({
34160
35306
  leftLabel: leftPath,
34161
35307
  leftText,
@@ -34222,8 +35368,8 @@ var copyRemotePath = async (args, storeRef, client) => {
34222
35368
  (entry) => entry.path.startsWith(`${normalizedSource}/`)
34223
35369
  );
34224
35370
  for (const entry of descendants) {
34225
- const relativePath = path24.posix.relative(normalizedSource, entry.path);
34226
- const targetPath = path24.posix.join(normalizedDestination, relativePath);
35371
+ const relativePath = path27.posix.relative(normalizedSource, entry.path);
35372
+ const targetPath = path27.posix.join(normalizedDestination, relativePath);
34227
35373
  if (entry.type === "directory") {
34228
35374
  await createRemoteDirectory(targetPath, storeRef, client);
34229
35375
  continue;
@@ -34360,11 +35506,23 @@ var readEncryptionPassword = async (parsed) => {
34360
35506
  }
34361
35507
  return readHiddenLine("Encryption password: ");
34362
35508
  };
35509
+ var readNewEncryptionPassword = async () => {
35510
+ const password = process.env.DOCTRINE_NEW_ENCRYPTION_PASSWORD;
35511
+ if (password) {
35512
+ return password;
35513
+ }
35514
+ const first = await readHiddenLine("New encryption password: ");
35515
+ const second = await readHiddenLine("Repeat new encryption password: ");
35516
+ if (first !== second) {
35517
+ throw new Error("The new encryption passwords do not match.");
35518
+ }
35519
+ return first;
35520
+ };
34363
35521
  var readUserEncryption = async (client) => {
34364
35522
  const preferences = await client.readUserPreferences();
34365
35523
  if (!preferences.encryption) {
34366
35524
  throw new Error(
34367
- "Encryption is not set up for this user. Set it up in the web app first."
35525
+ "Encryption is not set up for this user. Run `fm encryption setup` or set it up in the web app first."
34368
35526
  );
34369
35527
  }
34370
35528
  return {
@@ -34418,19 +35576,19 @@ var runDecryptCommand = async (rest, parsed, client) => {
34418
35576
  );
34419
35577
  };
34420
35578
  var runEditCommand = async (rest, parsed, client) => {
34421
- const filePath = parsed.inputFilePath ?? (rest[0] ? path24.resolve(rest[0]) : null);
35579
+ const filePath = parsed.inputFilePath ?? (rest[0] ? path27.resolve(rest[0]) : null);
34422
35580
  if (!filePath) {
34423
35581
  throw new Error(
34424
35582
  `Usage: ${commandNames} edit (<localPath>|--file|-f <localPath>) [--password <password>] [--token <jwt>]`
34425
35583
  );
34426
35584
  }
34427
- const encryptedText = await readFile10(filePath, "utf8");
35585
+ const encryptedText = await readFile11(filePath, "utf8");
34428
35586
  const [password, userEncryption] = await Promise.all([
34429
35587
  readEncryptionPassword(parsed),
34430
35588
  readUserEncryption(client)
34431
35589
  ]);
34432
35590
  const result = await editEncryptedText({
34433
- edit: (currentPlaintext) => openInEditor(currentPlaintext, { extension: path24.extname(filePath) }),
35591
+ edit: (currentPlaintext) => openInEditor(currentPlaintext, { extension: path27.extname(filePath) }),
34434
35592
  encryptedText,
34435
35593
  password,
34436
35594
  userEncryption: userEncryption.userEncryption
@@ -34439,7 +35597,11 @@ var runEditCommand = async (rest, parsed, client) => {
34439
35597
  renderWarning("No changes; nothing written.");
34440
35598
  return;
34441
35599
  }
34442
- await atomicWriteTextFile(filePath, result.encryptedText);
35600
+ await writeTextFileIfUnchanged({
35601
+ expectedText: encryptedText,
35602
+ filePath,
35603
+ text: result.encryptedText
35604
+ });
34443
35605
  renderOutput(
34444
35606
  `Updated ${filePath}. Run \`${commandNames} push\` (and commit) for store-synced projects.`
34445
35607
  );
@@ -34460,7 +35622,7 @@ var runRecipientSecretDecryptCommand = async (rest, parsed) => {
34460
35622
  };
34461
35623
  var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
34462
35624
  const name = parsed.recipientName?.trim();
34463
- const usage2 = `Usage: ${commandNames} encrypt-add-recipient (<encrypted-json>|--file <localPath>) --name <recipient-name> [--force] [--json]`;
35625
+ const usage2 = `Usage: ${commandNames} encrypt-add-recipient (<encrypted-json>|--file <localPath>) --name <recipient-name> [--force [--reissue <label-or-id>]... [--remove <label-or-id>]...] [--json]`;
34464
35626
  if (!name) {
34465
35627
  throw new Error(usage2);
34466
35628
  }
@@ -34478,24 +35640,38 @@ var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
34478
35640
  const result = await addExternalRecipientToEncryptedText({
34479
35641
  encryptedText,
34480
35642
  force: parsed.force,
35643
+ lookupPublicKeys: createPublicKeyLookup(client),
34481
35644
  name,
34482
35645
  password,
35646
+ reissue: parsed.reissueRecipients,
35647
+ remove: parsed.removeRecipients,
34483
35648
  userEncryption: userEncryption.userEncryption
34484
35649
  });
34485
35650
  if (parsed.inputFilePath) {
34486
- await writeFile7(parsed.inputFilePath, result.encryptedText, "utf8");
35651
+ await writeTextFileIfUnchanged({
35652
+ expectedText: encryptedText,
35653
+ filePath: parsed.inputFilePath,
35654
+ text: result.encryptedText
35655
+ });
34487
35656
  }
34488
35657
  if (parsed.json) {
34489
35658
  renderOutput({
34490
35659
  name,
34491
35660
  recipientId: result.recipientId,
35661
+ rekeyed: result.rekeyed,
35662
+ removedRecipientIds: result.removedRecipientIds,
35663
+ reissued: result.otherIssuedSecrets,
34492
35664
  secret: result.secret,
34493
35665
  ...parsed.inputFilePath ? {} : { ciphertext: result.encryptedText }
34494
35666
  });
34495
35667
  return;
34496
35668
  }
35669
+ if (result.rekeyed) {
35670
+ renderWarning(rekeyNotice(result.removedRecipientIds));
35671
+ }
35672
+ renderIssuedSecretsToStderr(result.otherIssuedSecrets);
34497
35673
  renderWarning(
34498
- `Added recipient "${name}". Recipient secret (shown once \u2014 hand to CI):`
35674
+ `${result.rekeyed ? "Replaced" : "Added"} recipient "${name}". Recipient secret (shown once \u2014 hand to CI):`
34499
35675
  );
34500
35676
  if (parsed.inputFilePath) {
34501
35677
  process.stdout.write(`${result.secret}
@@ -34506,11 +35682,82 @@ var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
34506
35682
  `);
34507
35683
  renderOutput(result.encryptedText);
34508
35684
  };
34509
- var defaultEncryptionMigrationBackupPath = () => path24.resolve(process.cwd(), "doctrine-encryption-migration.json");
34510
- var readEncryptionMigrationBackup = async (backupPath) => JSON.parse(await readFile10(backupPath, "utf8"));
35685
+ var createPublicKeyLookup = (client) => async (userIds) => {
35686
+ const [keys, preferences] = await Promise.all([
35687
+ client.readPublicEncryptionKeys({ userIds }),
35688
+ client.readUserPreferences()
35689
+ ]);
35690
+ const trustedKeys = preferences.encryptionTrustedKeys ?? {};
35691
+ return keys.map((entry) => ({
35692
+ encryption: entry.encryption,
35693
+ ...trustedKeys[entry.userId] ? { trustedFingerprint: trustedKeys[entry.userId].fingerprint } : {},
35694
+ userId: entry.userId
35695
+ }));
35696
+ };
35697
+ var rekeyNotice = (removedRecipientIds) => [
35698
+ "Rekeyed: the file now uses a new file key.",
35699
+ removedRecipientIds.length ? `Revoked recipients: ${removedRecipientIds.join(", ")}.` : null,
35700
+ "Old secrets and wrappers cannot read this or later versions. They can still read earlier versions and backups, and anything already decrypted or copied; rotate the underlying credentials at their providers if that matters."
35701
+ ].filter(Boolean).join(" ");
35702
+ var renderIssuedSecretsToStderr = (issued) => {
35703
+ if (!issued.length) {
35704
+ return;
35705
+ }
35706
+ renderWarning(
35707
+ "Reissued recipient secrets (shown once \u2014 previous secrets no longer read new versions):"
35708
+ );
35709
+ for (const entry of issued) {
35710
+ process.stderr.write(`${entry.label} ${entry.secret}
35711
+ `);
35712
+ }
35713
+ };
35714
+ var runEncryptRekeyCommand = async (rest, parsed, client) => {
35715
+ const usage2 = `Usage: ${commandNames} encrypt-rekey (<encrypted-json>|--file <localPath>) [--remove <label-or-id>]... [--reissue <label-or-id>]... [--json]`;
35716
+ const encryptedText = await readCommandTextInput(
35717
+ rest.length ? rest.join(" ") : void 0,
35718
+ parsed.inputFilePath
35719
+ );
35720
+ if (encryptedText === null) {
35721
+ throw new Error(usage2);
35722
+ }
35723
+ const [password, userEncryption] = await Promise.all([
35724
+ readEncryptionPassword(parsed),
35725
+ readUserEncryption(client)
35726
+ ]);
35727
+ const result = await rekeyEncryptedTextForUser({
35728
+ encryptedText,
35729
+ lookupPublicKeys: createPublicKeyLookup(client),
35730
+ password,
35731
+ reissue: parsed.reissueRecipients,
35732
+ remove: parsed.removeRecipients,
35733
+ userEncryption: userEncryption.userEncryption
35734
+ });
35735
+ if (parsed.inputFilePath) {
35736
+ await writeTextFileIfUnchanged({
35737
+ expectedText: encryptedText,
35738
+ filePath: parsed.inputFilePath,
35739
+ text: result.encryptedText
35740
+ });
35741
+ }
35742
+ if (parsed.json) {
35743
+ renderOutput({
35744
+ reissued: result.issuedSecrets,
35745
+ removedRecipientIds: result.removedRecipientIds,
35746
+ ...parsed.inputFilePath ? {} : { ciphertext: result.encryptedText }
35747
+ });
35748
+ return;
35749
+ }
35750
+ renderWarning(rekeyNotice(result.removedRecipientIds));
35751
+ renderIssuedSecretsToStderr(result.issuedSecrets);
35752
+ renderOutput(
35753
+ parsed.inputFilePath ? `Updated ${parsed.inputFilePath}. Run \`${commandNames} push\` (and commit) for store-synced projects.` : result.encryptedText
35754
+ );
35755
+ };
35756
+ var defaultEncryptionMigrationBackupPath = () => path27.resolve(process.cwd(), "doctrine-encryption-migration.json");
35757
+ var readEncryptionMigrationBackup = async (backupPath) => JSON.parse(await readFile11(backupPath, "utf8"));
34511
35758
  var writeEncryptionMigrationBackup = async (backupPath, backup) => {
34512
- await mkdir7(path24.dirname(backupPath), { recursive: true });
34513
- await writeFile7(backupPath, `${JSON.stringify(backup, null, 2)}
35759
+ await mkdir7(path27.dirname(backupPath), { recursive: true });
35760
+ await writeFile6(backupPath, `${JSON.stringify(backup, null, 2)}
34514
35761
  `, "utf8");
34515
35762
  };
34516
35763
  var confirmEncryptionMigration = async ({
@@ -34692,7 +35939,11 @@ var migrateEncryptionBackupFile = async ({
34692
35939
  const encryptedFile = await createEncryptedPlainTextFile({
34693
35940
  label: backup.currentUserLabel,
34694
35941
  plaintext: legacyPlaintext,
34695
- userEncryption: backup.newUserEncryption
35942
+ userEncryption: backup.newUserEncryption,
35943
+ userKey: await unlockUserEncryption({
35944
+ metadata: backup.newUserEncryption,
35945
+ password
35946
+ })
34696
35947
  });
34697
35948
  const localVerification = await decryptTextForUser({
34698
35949
  encryptedText: encryptedFile.text,
@@ -34797,14 +36048,14 @@ var runEncryptionMigrateCommand = async (rest, parsed, client) => {
34797
36048
  `Usage: ${commandNames} encryption migrate [backup-file] [--store <storeId>] [--password <password>] [--dry-run] [--yes]`
34798
36049
  );
34799
36050
  }
34800
- const backupPath = path24.resolve(
36051
+ const backupPath = path27.resolve(
34801
36052
  rest[1] ?? defaultEncryptionMigrationBackupPath()
34802
36053
  );
34803
36054
  const password = await readEncryptionPassword(parsed);
34804
36055
  const preferences = await client.readUserPreferences();
34805
36056
  if (!preferences.encryption) {
34806
36057
  throw new Error(
34807
- "Encryption is not set up for this user. Set it up in the web app first."
36058
+ "Encryption is not set up for this user. Run `fm encryption setup` or set it up in the web app first."
34808
36059
  );
34809
36060
  }
34810
36061
  const accountIsLegacy = isLegacyUserEncryptionMetadata(
@@ -34859,8 +36110,14 @@ var runEncryptionMigrateCommand = async (rest, parsed, client) => {
34859
36110
  throw error51;
34860
36111
  }
34861
36112
  if (accountIsLegacy) {
34862
- await client.upsertUserPreferences({
34863
- patch: { encryption: backup.newUserEncryption }
36113
+ if (backup.newUserEncryption.version !== 3) {
36114
+ throw new Error(
36115
+ "This migration backup predates key binding. Delete it and re-run the migration to create a new backup."
36116
+ );
36117
+ }
36118
+ await client.setupEncryption({
36119
+ encryption: backup.newUserEncryption,
36120
+ expectedKeyId: backup.oldUserEncryption.keyId
34864
36121
  });
34865
36122
  }
34866
36123
  renderOutput(
@@ -34872,7 +36129,7 @@ var doesRemoteQueryMatchPath = (query, filePath) => {
34872
36129
  if (query.startsWith("/")) {
34873
36130
  return normalizedPath === query;
34874
36131
  }
34875
- const filename = path24.basename(filePath).toLowerCase();
36132
+ const filename = path27.basename(filePath).toLowerCase();
34876
36133
  return filename === query || normalizedPath === query || filename.includes(query) || normalizedPath.includes(query);
34877
36134
  };
34878
36135
  var queryRemoteFiles = async (query, storeFilters, client) => {
@@ -34944,7 +36201,7 @@ var printRemoteQueryMatches = (matches) => {
34944
36201
  });
34945
36202
  };
34946
36203
  var normalizeRemoteDirectoryPath = (input) => {
34947
- const normalized = path24.posix.normalize(`/${input.trim()}`);
36204
+ const normalized = path27.posix.normalize(`/${input.trim()}`);
34948
36205
  if (normalized.includes("\0")) {
34949
36206
  throw new Error("Path contains an invalid null byte.");
34950
36207
  }
@@ -35064,12 +36321,12 @@ var labelFromTreeDirectoryPath = (directoryPath) => {
35064
36321
  if (directoryPath === "/") {
35065
36322
  return "./";
35066
36323
  }
35067
- return `${path24.posix.basename(directoryPath)}/`;
36324
+ return `${path27.posix.basename(directoryPath)}/`;
35068
36325
  };
35069
36326
  var doesTreeFilterMatchDirectory = (filter, directoryPath) => {
35070
36327
  const normalizedFilter = filter.trim().toLowerCase();
35071
36328
  const normalizedPath = directoryPath.toLowerCase();
35072
- const basename3 = path24.posix.basename(directoryPath).toLowerCase();
36329
+ const basename3 = path27.posix.basename(directoryPath).toLowerCase();
35073
36330
  return basename3.includes(normalizedFilter) || normalizedPath.includes(normalizedFilter);
35074
36331
  };
35075
36332
  var resolveTreeDirectoryPath = async ({
@@ -35124,7 +36381,7 @@ var printRemoteTreeChildren = async ({
35124
36381
  const childPrefix = isLast ? " " : "\u2502 ";
35125
36382
  const suffix = entry.type === "directory" ? "/" : "";
35126
36383
  lines.push(
35127
- `${prefix}${connector}${path24.posix.basename(entry.path)}${suffix}`
36384
+ `${prefix}${connector}${path27.posix.basename(entry.path)}${suffix}`
35128
36385
  );
35129
36386
  if (entry.type === "directory") {
35130
36387
  await printRemoteTreeChildren({
@@ -35413,17 +36670,18 @@ var printConfigShow = async (parsed) => {
35413
36670
  var getConfigValue = async (parsed, key) => {
35414
36671
  const stored = await readConfig(parsed.stateDir);
35415
36672
  if (key === "token") {
35416
- return stored.token ?? "";
36673
+ if (parsed.reveal) {
36674
+ return stored.token ?? "";
36675
+ }
36676
+ return stored.token ? "(set)" : "(unset)";
35417
36677
  }
35418
36678
  return String(stored.pollIntervalMs);
35419
36679
  };
35420
36680
  var setConfigValue = async (parsed, key, value) => {
35421
36681
  const stored = await readConfig(parsed.stateDir);
35422
36682
  if (key === "token") {
35423
- await writeConfig(parsed.stateDir, {
35424
- ...stored,
35425
- token: value
35426
- });
36683
+ registerRedactedSecret(value);
36684
+ await writeStoredToken(parsed.stateDir, value);
35427
36685
  renderOutput("Stored token.");
35428
36686
  return;
35429
36687
  }
@@ -35440,10 +36698,7 @@ var setConfigValue = async (parsed, key, value) => {
35440
36698
  var unsetConfigValue = async (parsed, key) => {
35441
36699
  const stored = await readConfig(parsed.stateDir);
35442
36700
  if (key === "token") {
35443
- await writeConfig(parsed.stateDir, {
35444
- ...stored,
35445
- token: null
35446
- });
36701
+ await deleteStoredToken(parsed.stateDir);
35447
36702
  renderOutput("Unset token.");
35448
36703
  return;
35449
36704
  }
@@ -35736,9 +36991,9 @@ var shouldPrintCheckoutDetail = (detail, verbose) => {
35736
36991
  var formatCheckoutDetail = (detail, options2) => {
35737
36992
  const status = checkoutStatusLabel(detail, options2);
35738
36993
  const direction = checkoutDirectionLabel(detail);
35739
- const path25 = formatCheckoutDetailPath(detail, options2.syncRules);
36994
+ const path28 = formatCheckoutDetailPath(detail, options2.syncRules);
35740
36995
  const reason = styleText.dim(checkoutDetailMessage(detail));
35741
- return direction ? `${direction} ${status} ${path25} ${reason}` : `${status} ${path25} ${reason}`;
36996
+ return direction ? `${direction} ${status} ${path28} ${reason}` : `${status} ${path28} ${reason}`;
35742
36997
  };
35743
36998
  var formatCheckoutDetailPath = (detail, syncRules) => {
35744
36999
  const localPath = formatLocalCheckoutPath(detail.relativePath);
@@ -35950,9 +37205,9 @@ var checkoutReportGroups = (details, options2) => {
35950
37205
  );
35951
37206
  };
35952
37207
  var checkoutReportDetailLine = (detail, options2) => {
35953
- const path25 = formatCheckoutDetailPath(detail, options2.syncRules);
37208
+ const path28 = formatCheckoutDetailPath(detail, options2.syncRules);
35954
37209
  const message = detail.status === "failed" || detail.status === "skipped" || detail.status === "ignored" ? detail.message ?? checkoutDetailMessage(detail) : "";
35955
- return message ? ` ${path25} ${styleText.dim(message)}` : ` ${path25}`;
37210
+ return message ? ` ${path28} ${styleText.dim(message)}` : ` ${path28}`;
35956
37211
  };
35957
37212
  var checkoutReportGroupBlock = ({
35958
37213
  dryRun,
@@ -36079,13 +37334,13 @@ var statusChangeKind = (detail) => {
36079
37334
  var formatStatusChange = (detail, syncRules) => {
36080
37335
  const kind = statusChangeKind(detail);
36081
37336
  const tone = kind === "deleted" ? "error" : kind === "added" ? "ok" : "warn";
36082
- const path25 = formatCheckoutDetailPath(detail, syncRules);
36083
- return ` ${styleText.color(tone, kind.padEnd(8))} ${path25}`;
37337
+ const path28 = formatCheckoutDetailPath(detail, syncRules);
37338
+ return ` ${styleText.color(tone, kind.padEnd(8))} ${path28}`;
36084
37339
  };
36085
37340
  var formatStatusBlock = (detail, syncRules) => {
36086
37341
  const message = detail.message ? ` ${styleText.dim(detail.message)}` : "";
36087
- const path25 = formatCheckoutDetailPath(detail, syncRules);
36088
- return ` ${styleText.color("error", "blocked ".padEnd(8))} ${path25}${message}`;
37342
+ const path28 = formatCheckoutDetailPath(detail, syncRules);
37343
+ return ` ${styleText.color("error", "blocked ".padEnd(8))} ${path28}${message}`;
36089
37344
  };
36090
37345
  var actionableStatusDetails = (result) => result.details.filter(
36091
37346
  (detail) => detail.status === "succeeded" || detail.status === "deleted"
@@ -36744,15 +37999,15 @@ var runCheckoutStatus = async ({
36744
37999
  var isCheckoutStateGitPath = isCheckoutStateDirectoryPath;
36745
38000
  var checkoutFilesManifestPath2 = () => `${resolveCheckoutStateDirectoryName()}/files.json`;
36746
38001
  var isInsideOrEqual = (parentPath, childPath2) => {
36747
- const relativePath = path24.relative(parentPath, childPath2);
36748
- return relativePath === "" || !relativePath.startsWith("..") && !path24.isAbsolute(relativePath);
38002
+ const relativePath = path27.relative(parentPath, childPath2);
38003
+ return relativePath === "" || !relativePath.startsWith("..") && !path27.isAbsolute(relativePath);
36749
38004
  };
36750
38005
  var resolveSyncTargetPaths = (checkout) => checkout.syncRules.map(
36751
- (rule) => path24.resolve(checkout.rootDir, rule.target || ".")
38006
+ (rule) => path27.resolve(checkout.rootDir, rule.target || ".")
36752
38007
  );
36753
- var resolveCheckoutManifestGitPath = (checkout, gitRoot) => path24.relative(
38008
+ var resolveCheckoutManifestGitPath = (checkout, gitRoot) => path27.relative(
36754
38009
  gitRoot,
36755
- path24.join(checkout.rootDir, checkoutFilesManifestPath2())
38010
+ path27.join(checkout.rootDir, checkoutFilesManifestPath2())
36756
38011
  ) || checkoutFilesManifestPath2();
36757
38012
  var stageCheckoutManifest = async ({
36758
38013
  checkout,
@@ -36778,7 +38033,7 @@ var assertGitChangesStayInSyncTargets = async ({
36778
38033
  if (isCheckoutStateGitPath(entry.path)) {
36779
38034
  return false;
36780
38035
  }
36781
- const absolutePath = path24.resolve(gitRoot, entry.path);
38036
+ const absolutePath = path27.resolve(gitRoot, entry.path);
36782
38037
  return !allowedPaths.some(
36783
38038
  (allowedPath) => isInsideOrEqual(allowedPath, absolutePath)
36784
38039
  );
@@ -36800,7 +38055,7 @@ var stageGitSyncTargets = async ({
36800
38055
  }) => {
36801
38056
  const targetPaths = [];
36802
38057
  for (const targetPath of resolveSyncTargetPaths(checkout)) {
36803
- const relativePath = path24.relative(gitRoot, targetPath) || ".";
38058
+ const relativePath = path27.relative(gitRoot, targetPath) || ".";
36804
38059
  const tracked = await runGit(gitRoot, ["ls-files", "--", relativePath]);
36805
38060
  if (await pathExists3(targetPath) || tracked.stdout.trim()) {
36806
38061
  targetPaths.push(relativePath);
@@ -37100,7 +38355,7 @@ var writeCheckoutConfig = async (directoryPath, metadata, workspaceSlug, options
37100
38355
  );
37101
38356
  }
37102
38357
  await writeForumProjectConfig(
37103
- path24.join(directoryPath, defaultProjectConfigFilename),
38358
+ path27.join(directoryPath, defaultProjectConfigFilename),
37104
38359
  {
37105
38360
  syncRules: [
37106
38361
  {
@@ -37137,7 +38392,7 @@ var normalizeProjectConfigPath = (value, fieldName, allowCurrentDirectory = fals
37137
38392
  }
37138
38393
  throw new Error(`${fieldName} must be a non-empty relative path.`);
37139
38394
  }
37140
- if (path24.isAbsolute(value)) {
38395
+ if (path27.isAbsolute(value)) {
37141
38396
  throw new Error(`${fieldName} must be a relative path.`);
37142
38397
  }
37143
38398
  const segments2 = trimmed.split("/");
@@ -37319,7 +38574,7 @@ var defaultCloneDirectoryName = (storeId) => {
37319
38574
  var fsErrorCode = (error51) => error51 instanceof Error && "code" in error51 ? String(error51.code ?? "") : "";
37320
38575
  var ensureGitMetadataExists = async (directoryPath) => {
37321
38576
  try {
37322
- await lstat5(path24.join(directoryPath, ".git"));
38577
+ await lstat6(path27.join(directoryPath, ".git"));
37323
38578
  } catch (error51) {
37324
38579
  if (fsErrorCode(error51) === "ENOENT") {
37325
38580
  throw new Error(
@@ -37357,8 +38612,8 @@ var confirmGitMetadataDeletion = async (localPath, assumeYes) => {
37357
38612
  "Refusing to delete .git without interactive confirmation. Rerun with --yes to confirm in a non-interactive shell."
37358
38613
  );
37359
38614
  }
37360
- const gitPath = path24.join(localPath, ".git");
37361
- const gitignorePath = path24.join(localPath, ".gitignore");
38615
+ const gitPath = path27.join(localPath, ".git");
38616
+ const gitignorePath = path27.join(localPath, ".gitignore");
37362
38617
  const confirmationPhrase = "DELETE GIT";
37363
38618
  renderWarning("");
37364
38619
  renderWarning("DANGER: Forum is about to remove Git from this checkout.");
@@ -37404,7 +38659,7 @@ var runGitConvertCommand = async ({
37404
38659
  );
37405
38660
  }
37406
38661
  await writeForumProjectConfig(
37407
- path24.join(localPath, defaultProjectConfigFilename),
38662
+ path27.join(localPath, defaultProjectConfigFilename),
37408
38663
  {
37409
38664
  syncRules: [
37410
38665
  {
@@ -37466,8 +38721,8 @@ var runGitConvertCommand = async ({
37466
38721
  "Aborted before deleting Git metadata. The Forum push completed, but .git and .gitignore were left in place."
37467
38722
  );
37468
38723
  }
37469
- await rm6(path24.join(localPath, ".gitignore"), { force: true });
37470
- await rm6(path24.join(localPath, ".git"), { recursive: true, force: true });
38724
+ await rm8(path27.join(localPath, ".gitignore"), { force: true });
38725
+ await rm8(path27.join(localPath, ".git"), { recursive: true, force: true });
37471
38726
  renderOutput(
37472
38727
  `${created ? "Created" : "Using existing"} store ${metadata.slug}`
37473
38728
  );
@@ -37522,21 +38777,17 @@ var main = async (argv = process.argv.slice(2)) => {
37522
38777
  openBrowser: parsed.openBrowser
37523
38778
  })
37524
38779
  );
37525
- await writeConfig(parsed.stateDir, {
37526
- token,
37527
- pollIntervalMs: config3.pollIntervalMs,
37528
- forceWrites: config3.forceWrites
37529
- });
38780
+ registerRedactedSecret(token);
38781
+ await writeStoredToken(parsed.stateDir, token);
37530
38782
  renderOutput("Login successful. CLI token stored.");
37531
38783
  return;
37532
38784
  }
37533
38785
  if (subcommand === "logout") {
37534
- await writeConfig(parsed.stateDir, {
37535
- token: null,
37536
- pollIntervalMs: config3.pollIntervalMs,
37537
- forceWrites: config3.forceWrites
37538
- });
37539
- renderOutput("Logged out.");
38786
+ await deleteStoredToken(parsed.stateDir);
38787
+ renderOutput("Logged out. Local CLI credential removed.");
38788
+ if (process.env.DOCTRINE_TOKEN) {
38789
+ renderOutput("DOCTRINE_TOKEN is still set in this environment.");
38790
+ }
37540
38791
  return;
37541
38792
  }
37542
38793
  if (subcommand === "status") {
@@ -37594,7 +38845,7 @@ var main = async (argv = process.argv.slice(2)) => {
37594
38845
  }
37595
38846
  if (command === "hash" && parsed.local) {
37596
38847
  const filePath = rest[0];
37597
- renderOutput(await hashLocalFile(path24.resolve(filePath)));
38848
+ renderOutput(await hashLocalFile(path27.resolve(filePath)));
37598
38849
  return;
37599
38850
  }
37600
38851
  const config2 = await resolveConfig(parsed);
@@ -37625,6 +38876,10 @@ var main = async (argv = process.argv.slice(2)) => {
37625
38876
  await runEncryptCommand(rest, parsed, client);
37626
38877
  return;
37627
38878
  }
38879
+ if (command === "encrypt-rekey") {
38880
+ await runEncryptRekeyCommand(rest, parsed, client);
38881
+ return;
38882
+ }
37628
38883
  if (command === "encrypt-add-recipient") {
37629
38884
  await runEncryptAddRecipientCommand(rest, parsed, client);
37630
38885
  return;
@@ -37641,6 +38896,21 @@ var main = async (argv = process.argv.slice(2)) => {
37641
38896
  await runEncryptionMigrateCommand(rest, parsed, client);
37642
38897
  return;
37643
38898
  }
38899
+ if (command === "encryption" && isEncryptionIdentitySubcommand(rest[0])) {
38900
+ await runEncryptionIdentityCommand({
38901
+ client,
38902
+ confirmReset: () => confirmYesNo({
38903
+ assumeYes: parsed.yes,
38904
+ nonInteractiveMessage: "Resetting your encryption identity needs confirmation. Re-run with --yes.",
38905
+ prompt: "Reset your encryption identity? Files encrypted for your current key will not open with the new one, and teammates must re-verify you. [y/N] "
38906
+ }),
38907
+ readCurrentPassword: () => readEncryptionPassword(parsed),
38908
+ readNewPassword: readNewEncryptionPassword,
38909
+ render: renderOutput,
38910
+ subcommand: rest[0]
38911
+ });
38912
+ return;
38913
+ }
37644
38914
  if (command === "inspect") {
37645
38915
  const filePath = rest[0] === "file" ? rest[1] : rest[0];
37646
38916
  if (!filePath) {
@@ -38081,8 +39351,8 @@ var main = async (argv = process.argv.slice(2)) => {
38081
39351
  `Usage: ${commandNames} clone <storeId> [localPath] [--readonly]`
38082
39352
  );
38083
39353
  }
38084
- const localPath = path24.resolve(
38085
- rest[1] ?? path24.join(process.cwd(), defaultCloneDirectoryName(remoteInput))
39354
+ const localPath = path27.resolve(
39355
+ rest[1] ?? path27.join(process.cwd(), defaultCloneDirectoryName(remoteInput))
38086
39356
  );
38087
39357
  const { metadata, workspaceSlug, storeRef } = await resolveReadableStore(
38088
39358
  remoteInput,
@@ -38110,7 +39380,7 @@ var main = async (argv = process.argv.slice(2)) => {
38110
39380
  storeRef,
38111
39381
  syncRules: checkout.syncRules
38112
39382
  });
38113
- renderOutput(`Cloned store ${metadata.slug} to ${path24.resolve(localPath)}`);
39383
+ renderOutput(`Cloned store ${metadata.slug} to ${path27.resolve(localPath)}`);
38114
39384
  formatCheckoutResult("Pulled", result, {
38115
39385
  detailsRendered: Boolean(progress),
38116
39386
  verbose: parsed.verbose
@@ -38160,7 +39430,7 @@ var main = async (argv = process.argv.slice(2)) => {
38160
39430
  });
38161
39431
  result.warnings.forEach((warning) => renderWarning(warning));
38162
39432
  if (parsed.outputFilePath) {
38163
- await writeFile7(parsed.outputFilePath, result.text, "utf8");
39433
+ await writeFile6(parsed.outputFilePath, result.text, "utf8");
38164
39434
  } else {
38165
39435
  renderOutput(result.text);
38166
39436
  }
@@ -38376,7 +39646,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar
38376
39646
  if (error51 instanceof RenderedCommandError) {
38377
39647
  process.exit(1);
38378
39648
  }
38379
- renderError(error51 instanceof Error ? error51 : String(error51));
39649
+ renderError(redactError(error51));
38380
39650
  process.exit(1);
38381
39651
  });
38382
39652
  }