@mp-lb/forum-cli 0.1.49 → 0.1.50

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 readFile10, 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,9 @@ 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
+
17230
17453
  // ../../packages/core/src/fileTypes.ts
17231
17454
  var textStorageClass = "text";
17232
17455
  var binaryStorageClass = "binary";
@@ -17551,8 +17774,8 @@ var normalizeStorePath = (value) => {
17551
17774
  }
17552
17775
  return segments2.length === 0 ? "/" : `/${segments2.join("/")}`;
17553
17776
  };
17554
- var storePathToArray = (path25) => {
17555
- const normalizedPath = normalizeStorePath(path25);
17777
+ var storePathToArray = (path28) => {
17778
+ const normalizedPath = normalizeStorePath(path28);
17556
17779
  return normalizedPath === "/" ? [] : normalizedPath.split("/").filter(Boolean);
17557
17780
  };
17558
17781
  var storePathSchema = external_exports.string().trim().min(1).transform((value) => normalizeStorePath(value));
@@ -18819,6 +19042,20 @@ var recentFilesValueSchema = external_exports.array(recentFileVisitSchema);
18819
19042
  var pinnedStoreIdsSchema = pinnedStoreIdsValueSchema.default([]);
18820
19043
  var recentStoresSchema = recentStoresValueSchema.default([]);
18821
19044
  var recentFilesSchema = recentFilesValueSchema.default([]);
19045
+ var encryptionKeyHistoryEntrySchema = external_exports.object({
19046
+ fingerprint: encryptionFingerprintSchema.nullable(),
19047
+ keyId: external_exports.string().trim().min(1),
19048
+ reason: external_exports.enum(["legacy_replaced", "reset"]),
19049
+ replacedAt: external_exports.string().datetime()
19050
+ });
19051
+ var encryptionTrustedKeySchema = external_exports.object({
19052
+ fingerprint: encryptionFingerprintSchema,
19053
+ trustedAt: external_exports.string().datetime()
19054
+ });
19055
+ var encryptionTrustedKeysSchema = external_exports.record(
19056
+ storeOwnerIdSchema,
19057
+ encryptionTrustedKeySchema
19058
+ );
18822
19059
  var createTypeLastUsedAtSchema = external_exports.record(
18823
19060
  external_exports.string().min(1).max(100),
18824
19061
  external_exports.string().datetime()
@@ -18842,6 +19079,9 @@ var userPreferencesSchema = external_exports.object({
18842
19079
  source: "generated"
18843
19080
  }),
18844
19081
  encryption: userEncryptionMetadataSchema.nullable().default(null),
19082
+ encryptionIdentityChangedAt: external_exports.string().datetime().nullable().default(null),
19083
+ encryptionKeyHistory: external_exports.array(encryptionKeyHistoryEntrySchema).default([]),
19084
+ encryptionTrustedKeys: encryptionTrustedKeysSchema.default({}),
18845
19085
  createdAt: external_exports.string().datetime().default(() => (/* @__PURE__ */ new Date()).toISOString()),
18846
19086
  updatedAt: external_exports.string().datetime().default(() => (/* @__PURE__ */ new Date()).toISOString())
18847
19087
  });
@@ -18858,7 +19098,39 @@ var userPreferencesUpdateSchema = external_exports.object({
18858
19098
  markdownEditorMode: markdownEditorModeSchema,
18859
19099
  htmlEditorMode: htmlEditorModeSchema,
18860
19100
  avatar: avatarPreferencesSchema,
18861
- encryption: userEncryptionMetadataSchema.nullable()
19101
+ encryption: userEncryptionMetadataSchema.nullable(),
19102
+ encryptionIdentityChangedAt: external_exports.string().datetime().nullable(),
19103
+ encryptionKeyHistory: external_exports.array(encryptionKeyHistoryEntrySchema),
19104
+ encryptionTrustedKeys: encryptionTrustedKeysSchema
19105
+ });
19106
+ var ownUserPreferencesPatchSchema = userPreferencesUpdateSchema.omit({
19107
+ encryption: true,
19108
+ encryptionIdentityChangedAt: true,
19109
+ encryptionKeyHistory: true,
19110
+ encryptionTrustedKeys: true
19111
+ }).strict();
19112
+ var setupOwnEncryptionInputSchema = external_exports.object({
19113
+ encryption: boundUserEncryptionMetadataSchema,
19114
+ // Required when replacing a legacy (v1) record, which has no public identity.
19115
+ expectedKeyId: external_exports.string().trim().min(1).nullable().default(null)
19116
+ });
19117
+ var rewrapOwnEncryptionInputSchema = external_exports.object({
19118
+ encryption: currentUserEncryptionMetadataSchema,
19119
+ expectedKeyId: external_exports.string().trim().min(1)
19120
+ });
19121
+ var resetEncryptionIdentityConfirmation = "reset-encryption-identity";
19122
+ var resetOwnEncryptionInputSchema = external_exports.object({
19123
+ confirmation: external_exports.literal(resetEncryptionIdentityConfirmation),
19124
+ encryption: boundUserEncryptionMetadataSchema,
19125
+ expectedKeyId: external_exports.string().trim().min(1)
19126
+ });
19127
+ var trustEncryptionKeyInputSchema = external_exports.object({
19128
+ keys: external_exports.array(
19129
+ external_exports.object({
19130
+ fingerprint: encryptionFingerprintSchema,
19131
+ userId: storeOwnerIdSchema
19132
+ })
19133
+ ).min(1).max(100)
18862
19134
  });
18863
19135
  var readUserPreferencesInputSchema = external_exports.object({
18864
19136
  userId: storeOwnerIdSchema
@@ -18894,7 +19166,7 @@ var upsertUserPreferencesInputSchema = external_exports.object({
18894
19166
  patch: userPreferencesUpdateSchema.partial().default({})
18895
19167
  });
18896
19168
  var upsertOwnUserPreferencesInputSchema = external_exports.object({
18897
- patch: userPreferencesUpdateSchema.partial().default({})
19169
+ patch: ownUserPreferencesPatchSchema.partial().default({})
18898
19170
  });
18899
19171
 
18900
19172
  // ../../packages/core/src/storeChat.ts
@@ -19600,21 +19872,21 @@ var isKey = (value) => /^\w*$/.test(value);
19600
19872
  var isUndefined = (val) => val === void 0;
19601
19873
  var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
19602
19874
  var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
19603
- var get = (object2, path25, defaultValue) => {
19604
- if (!path25 || !isObject2(object2)) {
19875
+ var get = (object2, path28, defaultValue) => {
19876
+ if (!path28 || !isObject2(object2)) {
19605
19877
  return defaultValue;
19606
19878
  }
19607
- const paths = isKey(path25) ? [path25] : stringToPath(path25);
19879
+ const paths = isKey(path28) ? [path28] : stringToPath(path28);
19608
19880
  const result = paths.reduce((result2, key) => {
19609
19881
  return isNullOrUndefined(result2) ? void 0 : result2[key];
19610
19882
  }, object2);
19611
- return isUndefined(result) || result === object2 ? isUndefined(object2[path25]) ? defaultValue : object2[path25] : result;
19883
+ return isUndefined(result) || result === object2 ? isUndefined(object2[path28]) ? defaultValue : object2[path28] : result;
19612
19884
  };
19613
19885
  var isBoolean = (value) => typeof value === "boolean";
19614
19886
  var isFunction = (value) => typeof value === "function";
19615
- var set2 = (object2, path25, value) => {
19887
+ var set2 = (object2, path28, value) => {
19616
19888
  let index = -1;
19617
- const tempPath = isKey(path25) ? [path25] : stringToPath(path25);
19889
+ const tempPath = isKey(path28) ? [path28] : stringToPath(path28);
19618
19890
  const length = tempPath.length;
19619
19891
  const lastIndex = length - 1;
19620
19892
  while (++index < length) {
@@ -19812,12 +20084,12 @@ function isEmptyArray(obj) {
19812
20084
  }
19813
20085
  return true;
19814
20086
  }
19815
- function unset(object2, path25) {
19816
- if (isString(path25) && Object.prototype.hasOwnProperty.call(object2, path25)) {
19817
- delete object2[path25];
20087
+ function unset(object2, path28) {
20088
+ if (isString(path28) && Object.prototype.hasOwnProperty.call(object2, path28)) {
20089
+ delete object2[path28];
19818
20090
  return object2;
19819
20091
  }
19820
- const paths = Array.isArray(path25) ? path25 : isKey(path25) ? [path25] : stringToPath(path25);
20092
+ const paths = Array.isArray(path28) ? path28 : isKey(path28) ? [path28] : stringToPath(path28);
19821
20093
  const childObject = paths.length === 1 ? object2 : baseGet(object2, paths);
19822
20094
  const index = paths.length - 1;
19823
20095
  const key = paths[index];
@@ -23544,7 +23816,7 @@ var publicActionSubmitResultSchema = external_exports.unknown();
23544
23816
 
23545
23817
  // ../../packages/core/src/widgetRuntime.ts
23546
23818
  var widgetRuntimeOutputPathSchema = storePathSchema.refine(
23547
- (path25) => path25 !== "/",
23819
+ (path28) => path28 !== "/",
23548
23820
  {
23549
23821
  message: "Path must not be the root directory."
23550
23822
  }
@@ -23594,7 +23866,7 @@ var widgetRuntimeCompleteAttachmentUploadInputSchema = storeRefSchema.safeExtend
23594
23866
  treeVisibility: external_exports.enum(["visible", "hidden"]).optional(),
23595
23867
  uploadIntentId: external_exports.string().trim().min(1)
23596
23868
  });
23597
- var widgetRuntimeLinkPathSchema = external_exports.string().trim().min(1).max(2048).refine((path25) => path25.startsWith("/") && !path25.startsWith("//"), {
23869
+ var widgetRuntimeLinkPathSchema = external_exports.string().trim().min(1).max(2048).refine((path28) => path28.startsWith("/") && !path28.startsWith("//"), {
23598
23870
  message: "Link path must be a relative application path."
23599
23871
  });
23600
23872
  var widgetRuntimeCreateSigningLinkInputSchema = storeRefSchema.safeExtend({
@@ -23683,8 +23955,8 @@ var skillScanSchema = external_exports.object({
23683
23955
 
23684
23956
  // ../../packages/store-tree/src/patterns.ts
23685
23957
  var escapeRegex2 = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23686
- var basename2 = (path25) => {
23687
- const segments2 = path25.split("/").filter(Boolean);
23958
+ var basename2 = (path28) => {
23959
+ const segments2 = path28.split("/").filter(Boolean);
23688
23960
  return segments2[segments2.length - 1] ?? "";
23689
23961
  };
23690
23962
  var normalizeStorePathPattern = (pattern) => pattern.trim();
@@ -23702,7 +23974,7 @@ var storePathPatternToRegex = (pattern) => {
23702
23974
  return new RegExp(source, "i");
23703
23975
  };
23704
23976
  var doesStorePathPatternMatch = ({
23705
- path: path25,
23977
+ path: path28,
23706
23978
  pattern,
23707
23979
  mode = "path"
23708
23980
  }) => {
@@ -23710,7 +23982,7 @@ var doesStorePathPatternMatch = ({
23710
23982
  if (!normalizedPattern) {
23711
23983
  return true;
23712
23984
  }
23713
- const normalizedPath = normalizeStorePath(path25);
23985
+ const normalizedPath = normalizeStorePath(path28);
23714
23986
  const target = mode === "basename" ? basename2(normalizedPath) : normalizedPath;
23715
23987
  if (patternHasWildcard(normalizedPattern)) {
23716
23988
  return storePathPatternToRegex(normalizedPattern).test(target);
@@ -23798,8 +24070,8 @@ var isIssueRecord = (value) => {
23798
24070
  return isRecord2(value) && typeof value.message === "string";
23799
24071
  };
23800
24072
  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;
24073
+ const path28 = Array.isArray(issue2.path) && issue2.path.length > 0 ? issue2.path.map(String).join(".") : "";
24074
+ return path28 ? `${path28}: ${issue2.message}` : issue2.message;
23803
24075
  };
23804
24076
  var formatIssueArray = (issues) => {
23805
24077
  if (!issues.every(isIssueRecord)) {
@@ -24272,7 +24544,7 @@ var buildContentChangedConflictExplainer = (issues) => {
24272
24544
  body: [
24273
24545
  pathSubject(
24274
24546
  paths,
24275
- (path25) => `${path25} changed both locally and remotely.`,
24547
+ (path28) => `${path28} changed both locally and remotely.`,
24276
24548
  (count) => `${count} files changed both locally and remotely.`
24277
24549
  ),
24278
24550
  "Forum left these files alone because either overwrite direction could lose work."
@@ -24304,7 +24576,7 @@ var buildLocalDeleteRemoteChangeExplainer = (issues) => {
24304
24576
  body: [
24305
24577
  pathSubject(
24306
24578
  paths,
24307
- (path25) => `${path25} was deleted locally, but the remote file changed.`,
24579
+ (path28) => `${path28} was deleted locally, but the remote file changed.`,
24308
24580
  (count) => `${count} files were deleted locally, but changed remotely.`
24309
24581
  ),
24310
24582
  "Forum did not delete newer remote work automatically."
@@ -24336,7 +24608,7 @@ var buildMoveDestinationConflictExplainer = (issues) => {
24336
24608
  body: [
24337
24609
  pathSubject(
24338
24610
  paths,
24339
- (path25) => `${path25} is the destination of a remote move, but already exists locally.`,
24611
+ (path28) => `${path28} is the destination of a remote move, but already exists locally.`,
24340
24612
  (count) => `${count} paths are remote move destinations that already exist locally.`
24341
24613
  ),
24342
24614
  "Forum synced unrelated files but left these paths alone."
@@ -24371,7 +24643,7 @@ var buildMoveRemoteChangeConflictExplainer = (issues) => {
24371
24643
  body: [
24372
24644
  pathSubject(
24373
24645
  paths,
24374
- (path25) => `${path25} was involved in a move while the other side changed it.`,
24646
+ (path28) => `${path28} was involved in a move while the other side changed it.`,
24375
24647
  (count) => `${count} files were involved in moves while the other side changed them.`
24376
24648
  ),
24377
24649
  "Forum did not combine the move and content change automatically."
@@ -24403,7 +24675,7 @@ var buildMoveMoveConflictExplainer = (issues) => {
24403
24675
  body: [
24404
24676
  pathSubject(
24405
24677
  paths,
24406
- (path25) => `${path25} moved locally and remotely to different paths.`,
24678
+ (path28) => `${path28} moved locally and remotely to different paths.`,
24407
24679
  (count) => `${count} files moved locally and remotely to different paths.`
24408
24680
  ),
24409
24681
  "Forum left these moves unresolved because choosing a path automatically could hide work."
@@ -24435,7 +24707,7 @@ var buildDeleteMoveConflictExplainer = (issues) => {
24435
24707
  body: [
24436
24708
  pathSubject(
24437
24709
  paths,
24438
- (path25) => `${path25} was deleted on one side and moved on the other.`,
24710
+ (path28) => `${path28} was deleted on one side and moved on the other.`,
24439
24711
  (count) => `${count} files were deleted on one side and moved on the other.`
24440
24712
  ),
24441
24713
  "Forum did not choose between delete and move automatically."
@@ -24467,7 +24739,7 @@ var buildReferenceLocalFileConflictExplainer = (issues) => {
24467
24739
  body: [
24468
24740
  pathSubject(
24469
24741
  paths,
24470
- (path25) => `${path25} is now a remote reference, but the local file has changes.`,
24742
+ (path28) => `${path28} is now a remote reference, but the local file has changes.`,
24471
24743
  (count) => `${count} paths are now remote references, but local files have changes.`
24472
24744
  ),
24473
24745
  "Forum left the local files alone because replacing them would discard local work."
@@ -24499,7 +24771,7 @@ var buildUnsupportedLocalEntryExplainer = (issues) => {
24499
24771
  body: [
24500
24772
  pathSubject(
24501
24773
  paths,
24502
- (path25) => `${path25} is an unsupported local filesystem entry.`,
24774
+ (path28) => `${path28} is an unsupported local filesystem entry.`,
24503
24775
  (count) => `${count} local filesystem entries are unsupported.`
24504
24776
  ),
24505
24777
  "Forum skipped these paths and continued with unrelated files where it could."
@@ -24531,7 +24803,7 @@ var buildReadOnlyLocalChangeExplainer = (issues) => {
24531
24803
  body: [
24532
24804
  pathSubject(
24533
24805
  paths,
24534
- (path25) => `${path25} has local changes, but its sync rule is read-only.`,
24806
+ (path28) => `${path28} has local changes, but its sync rule is read-only.`,
24535
24807
  (count) => `${count} files have local changes, but their sync rules are read-only.`
24536
24808
  ),
24537
24809
  "Forum left these files alone so remote updates cannot overwrite local work."
@@ -24628,7 +24900,7 @@ var checkoutConflictIssuesFromResult = (result) => checkoutIssuesFromResult(resu
24628
24900
  (issue2) => issue2.type === "conflict"
24629
24901
  );
24630
24902
  var formatCheckoutExplainer = (explainer) => {
24631
- const pathLines = explainer.paths.length <= 1 ? [] : ["", ...formatPathList(explainer.paths).map((path25) => ` ${path25}`)];
24903
+ const pathLines = explainer.paths.length <= 1 ? [] : ["", ...formatPathList(explainer.paths).map((path28) => ` ${path28}`)];
24632
24904
  const actionLines = explainer.actions.map(
24633
24905
  (action) => `${styleText.bold(`${action.label}:`)} ${action.text}`
24634
24906
  );
@@ -24818,19 +25090,19 @@ import { TextDecoder as TextDecoder2 } from "util";
24818
25090
  import ignore2 from "ignore";
24819
25091
 
24820
25092
  // src/buildCheckoutFileManifestEntry.ts
24821
- var toManifestRemotePath = (path25) => path25.startsWith("/") ? path25 : `/${path25}`;
25093
+ var toManifestRemotePath = (path28) => path28.startsWith("/") ? path28 : `/${path28}`;
24822
25094
  var buildCheckoutFileManifestEntry = ({
24823
25095
  storageClass,
24824
25096
  hash: hash2,
24825
25097
  manifestEntry,
24826
- path: path25,
25098
+ path: path28,
24827
25099
  remoteFile,
24828
25100
  source,
24829
25101
  syncedAt
24830
25102
  }) => {
24831
25103
  const remoteFileId = remoteFile.id ?? remoteFile._id ?? manifestEntry?.remoteFileId;
24832
25104
  if (!remoteFileId) {
24833
- throw new Error(`Remote file ${path25} did not include a file id`);
25105
+ throw new Error(`Remote file ${path28} did not include a file id`);
24834
25106
  }
24835
25107
  return {
24836
25108
  storageClass,
@@ -24838,7 +25110,7 @@ var buildCheckoutFileManifestEntry = ({
24838
25110
  isExecutable: storageClass === "text" ? remoteFile.isExecutable === true || void 0 : void 0,
24839
25111
  lastSyncedAt: syncedAt,
24840
25112
  remoteFileId,
24841
- remotePath: remoteFile.path ?? manifestEntry?.remotePath ?? toManifestRemotePath(path25),
25113
+ remotePath: remoteFile.path ?? manifestEntry?.remotePath ?? toManifestRemotePath(path28),
24842
25114
  remoteUpdatedAt: remoteFile.updatedAt ?? null,
24843
25115
  remoteRevisionNumber: remoteFile.revisionNumber ?? null,
24844
25116
  ...source ? { source } : {}
@@ -27603,16 +27875,16 @@ var updateFileManifestEntry = ({
27603
27875
  hash: hash2,
27604
27876
  manifest,
27605
27877
  manifestEntry,
27606
- path: path25,
27878
+ path: path28,
27607
27879
  remoteFile,
27608
27880
  source,
27609
27881
  syncedAt
27610
27882
  }) => {
27611
- manifest.files[path25] = buildCheckoutFileManifestEntry({
27883
+ manifest.files[path28] = buildCheckoutFileManifestEntry({
27612
27884
  storageClass,
27613
27885
  hash: hash2,
27614
27886
  manifestEntry,
27615
- path: path25,
27887
+ path: path28,
27616
27888
  remoteFile,
27617
27889
  source,
27618
27890
  syncedAt
@@ -29093,7 +29365,7 @@ var remoteFileHash = async ({
29093
29365
  client,
29094
29366
  remoteFile,
29095
29367
  storeRef,
29096
- path: path25
29368
+ path: path28
29097
29369
  }) => {
29098
29370
  const textHash = remoteTextHash(remoteFile);
29099
29371
  if (textHash) {
@@ -29104,7 +29376,7 @@ var remoteFileHash = async ({
29104
29376
  }
29105
29377
  const { downloadUrl } = await client.createFileDownloadUrlByRef({
29106
29378
  ...storeRef,
29107
- path: path25
29379
+ path: path28
29108
29380
  });
29109
29381
  const response = await fetch(downloadUrl);
29110
29382
  if (!response.ok) {
@@ -30531,9 +30803,9 @@ var createHumanWatchSubscriber = ({
30531
30803
  return;
30532
30804
  }
30533
30805
  case "sync.watch.conflict.raised": {
30534
- const path25 = String(details.path ?? "");
30806
+ const path28 = String(details.path ?? "");
30535
30807
  const suggestions = details.suggestions ?? [];
30536
- error51(`Conflict: ${path25} \u2014 ${event.message ?? "needs attention"}`);
30808
+ error51(`Conflict: ${path28} \u2014 ${event.message ?? "needs attention"}`);
30537
30809
  if (suggestions.length > 0) {
30538
30810
  error51(` ${formatSuggestions(suggestions)}`);
30539
30811
  }
@@ -30562,10 +30834,10 @@ import notifier from "node-notifier";
30562
30834
  var createNotifyWatchSubscriber = () => {
30563
30835
  return (event) => {
30564
30836
  if (event.eventType === "sync.watch.conflict.raised") {
30565
- const path25 = event.details?.path;
30837
+ const path28 = event.details?.path;
30566
30838
  notifier.notify({
30567
30839
  title: "Forum sync conflict",
30568
- message: typeof path25 === "string" ? `${path25} needs attention` : event.message ?? "A file needs attention"
30840
+ message: typeof path28 === "string" ? `${path28} needs attention` : event.message ?? "A file needs attention"
30569
30841
  });
30570
30842
  return;
30571
30843
  }
@@ -30681,10 +30953,10 @@ var createConflictTracker = () => {
30681
30953
  );
30682
30954
  const raised = current.filter((conflict) => !active.has(conflict.path));
30683
30955
  const cleared = [...active.keys()].filter(
30684
- (path25) => !currentByPath.has(path25)
30956
+ (path28) => !currentByPath.has(path28)
30685
30957
  );
30686
- for (const path25 of cleared) {
30687
- active.delete(path25);
30958
+ for (const path28 of cleared) {
30959
+ active.delete(path28);
30688
30960
  }
30689
30961
  for (const conflict of current) {
30690
30962
  active.set(conflict.path, conflict);
@@ -30695,13 +30967,13 @@ var createConflictTracker = () => {
30695
30967
  };
30696
30968
 
30697
30969
  // src/watch/conflictResolutionHints.ts
30698
- var keepLocal = (path25) => ({
30970
+ var keepLocal = (path28) => ({
30699
30971
  label: "Keep local",
30700
- command: `fm push --force ${path25}`
30972
+ command: `fm push --force ${path28}`
30701
30973
  });
30702
- var acceptRemote = (path25) => ({
30974
+ var acceptRemote = (path28) => ({
30703
30975
  label: "Accept remote",
30704
- command: `fm pull --force ${path25}`
30976
+ command: `fm pull --force ${path28}`
30705
30977
  });
30706
30978
  var review = (label, command) => ({
30707
30979
  label,
@@ -30717,23 +30989,23 @@ var forceResolvableTypes = /* @__PURE__ */ new Set([
30717
30989
  "reference-local-file",
30718
30990
  "read-only-local-change"
30719
30991
  ]);
30720
- var conflictResolutionSuggestions = (conflictType, path25) => {
30992
+ var conflictResolutionSuggestions = (conflictType, path28) => {
30721
30993
  if (forceResolvableTypes.has(conflictType)) {
30722
- return [keepLocal(path25), acceptRemote(path25)];
30994
+ return [keepLocal(path28), acceptRemote(path28)];
30723
30995
  }
30724
- return [review("Review", `fm status ${path25}`)];
30996
+ return [review("Review", `fm status ${path28}`)];
30725
30997
  };
30726
30998
 
30727
30999
  // src/watch/extractWatchConflicts.ts
30728
31000
  var toWatchConflict = (issue2) => {
30729
- const { path: path25, message, relatedPaths } = issue2.details.details;
31001
+ const { path: path28, message, relatedPaths } = issue2.details.details;
30730
31002
  const conflictType = issue2.details.type;
30731
31003
  return {
30732
- path: path25,
31004
+ path: path28,
30733
31005
  conflictType,
30734
31006
  message,
30735
31007
  relatedPaths: relatedPaths ?? [],
30736
- suggestions: conflictResolutionSuggestions(conflictType, path25)
31008
+ suggestions: conflictResolutionSuggestions(conflictType, path28)
30737
31009
  };
30738
31010
  };
30739
31011
  var extractWatchConflicts = (result) => {
@@ -30824,9 +31096,9 @@ var createCheckoutWatcher = ({
30824
31096
  })
30825
31097
  );
30826
31098
  }
30827
- for (const path25 of cleared) {
31099
+ for (const path28 of cleared) {
30828
31100
  bus.emit(
30829
- watchEvent("sync.watch.conflict.cleared", void 0, { path: path25 })
31101
+ watchEvent("sync.watch.conflict.cleared", void 0, { path: path28 })
30830
31102
  );
30831
31103
  }
30832
31104
  bus.emit(
@@ -31522,6 +31794,18 @@ var createStoreClient = ({
31522
31794
  "userPreferences.upsert",
31523
31795
  () => trpc.userPreferences.upsert.mutate(input)
31524
31796
  ),
31797
+ setupEncryption: (input) => call(
31798
+ "userPreferences.setupEncryption",
31799
+ () => trpc.userPreferences.setupEncryption.mutate(input)
31800
+ ),
31801
+ rewrapEncryption: (input) => call(
31802
+ "userPreferences.rewrapEncryption",
31803
+ () => trpc.userPreferences.rewrapEncryption.mutate(input)
31804
+ ),
31805
+ resetEncryption: (input) => call(
31806
+ "userPreferences.resetEncryption",
31807
+ () => trpc.userPreferences.resetEncryption.mutate(input)
31808
+ ),
31525
31809
  listDirectory: (input) => call("files.listDirectory", () => trpc.files.listDirectory.query(input)),
31526
31810
  listDirectoryByRef: (input) => call(
31527
31811
  "files.listDirectoryByRef",
@@ -31640,61 +31924,307 @@ var createClient = (config2) => {
31640
31924
 
31641
31925
  // src/state.ts
31642
31926
  import { homedir } from "os";
31927
+ import path19 from "path";
31928
+ import { readFile as readFile6 } from "fs/promises";
31929
+
31930
+ // src/credentials/ensurePrivateDir.ts
31931
+ import { chmod as chmod2, mkdir as mkdir5, stat as stat4 } from "fs/promises";
31932
+
31933
+ // src/credentials/UnsafeCredentialPathError.ts
31934
+ var UnsafeCredentialPathError = class extends Error {
31935
+ constructor(filePath, reason) {
31936
+ super(
31937
+ `Refusing to use credential path ${filePath}: ${reason}. Remove or fix it, then run \`fm auth login\` again.`
31938
+ );
31939
+ this.name = "UnsafeCredentialPathError";
31940
+ }
31941
+ };
31942
+
31943
+ // src/credentials/usesPosixPermissions.ts
31944
+ var usesPosixPermissions = () => process.platform !== "win32";
31945
+
31946
+ // src/credentials/assertOwnedByCurrentUser.ts
31947
+ var assertOwnedByCurrentUser = (filePath, stats) => {
31948
+ if (!usesPosixPermissions() || typeof process.getuid !== "function") {
31949
+ return;
31950
+ }
31951
+ const uid = process.getuid();
31952
+ if (stats.uid !== uid) {
31953
+ throw new UnsafeCredentialPathError(
31954
+ filePath,
31955
+ `it is owned by uid ${stats.uid}, not the current user (uid ${uid})`
31956
+ );
31957
+ }
31958
+ };
31959
+
31960
+ // src/credentials/hasBroaderMode.ts
31961
+ var hasBroaderMode = (stats) => usesPosixPermissions() && (stats.mode & 63) !== 0;
31962
+
31963
+ // src/credentials/privateModes.ts
31964
+ var privateModes = {
31965
+ directory: 448,
31966
+ file: 384
31967
+ };
31968
+
31969
+ // src/credentials/ensurePrivateDir.ts
31970
+ var ensurePrivateDir = async (dirPath) => {
31971
+ await mkdir5(dirPath, { recursive: true, mode: privateModes.directory });
31972
+ const stats = await stat4(dirPath);
31973
+ if (!stats.isDirectory()) {
31974
+ throw new UnsafeCredentialPathError(dirPath, "it is not a directory");
31975
+ }
31976
+ assertOwnedByCurrentUser(dirPath, stats);
31977
+ if (hasBroaderMode(stats)) {
31978
+ await chmod2(dirPath, privateModes.directory);
31979
+ }
31980
+ };
31981
+
31982
+ // src/credentials/credentialsPath.ts
31643
31983
  import path16 from "path";
31644
- import { mkdir as mkdir5, readFile as readFile6, rename as rename3, writeFile as writeFile4 } from "fs/promises";
31984
+ var credentialsPath = (stateDir) => path16.join(stateDir, "credentials.json");
31985
+
31986
+ // src/credentials/readPrivateFile.ts
31987
+ import { constants as constants2 } from "fs";
31988
+ import { open } from "fs/promises";
31989
+
31990
+ // src/credentials/noFollowFlag.ts
31991
+ import { constants } from "fs";
31992
+ var noFollowFlag = () => constants.O_NOFOLLOW ?? 0;
31993
+
31994
+ // src/credentials/readPrivateFile.ts
31995
+ var readPrivateFile = async (filePath) => {
31996
+ let handle;
31997
+ try {
31998
+ handle = await open(filePath, constants2.O_RDONLY | noFollowFlag());
31999
+ } catch (error51) {
32000
+ const code = error51.code;
32001
+ if (code === "ENOENT") {
32002
+ return null;
32003
+ }
32004
+ if (code === "ELOOP" || code === "EMLINK") {
32005
+ throw new UnsafeCredentialPathError(filePath, "it is a symbolic link");
32006
+ }
32007
+ throw error51;
32008
+ }
32009
+ try {
32010
+ const stats = await handle.stat();
32011
+ if (!stats.isFile()) {
32012
+ throw new UnsafeCredentialPathError(filePath, "it is not a regular file");
32013
+ }
32014
+ assertOwnedByCurrentUser(filePath, stats);
32015
+ if (hasBroaderMode(stats)) {
32016
+ await handle.chmod(privateModes.file);
32017
+ }
32018
+ return await handle.readFile("utf8");
32019
+ } finally {
32020
+ await handle.close();
32021
+ }
32022
+ };
32023
+
32024
+ // src/credentials/readStoredToken.ts
32025
+ var readStoredToken = async (stateDir) => {
32026
+ const raw = await readPrivateFile(credentialsPath(stateDir));
32027
+ if (raw === null) {
32028
+ return null;
32029
+ }
32030
+ try {
32031
+ const parsed = JSON.parse(raw);
32032
+ return typeof parsed.token === "string" && parsed.token ? parsed.token : null;
32033
+ } catch {
32034
+ return null;
32035
+ }
32036
+ };
32037
+
32038
+ // src/credentials/writePrivateFileAtomic.ts
32039
+ import { constants as constants3 } from "fs";
32040
+ import { open as open2, rename as rename3, rm as rm4 } from "fs/promises";
32041
+ import path18 from "path";
32042
+
32043
+ // src/credentials/lstatIfExists.ts
32044
+ import { lstat as lstat2 } from "fs/promises";
32045
+ var lstatIfExists = async (filePath) => {
32046
+ try {
32047
+ return await lstat2(filePath);
32048
+ } catch (error51) {
32049
+ if (error51.code === "ENOENT") {
32050
+ return null;
32051
+ }
32052
+ throw error51;
32053
+ }
32054
+ };
32055
+
32056
+ // src/credentials/assertReplaceableFile.ts
32057
+ var assertReplaceableFile = async (filePath) => {
32058
+ const stats = await lstatIfExists(filePath);
32059
+ if (!stats) {
32060
+ return;
32061
+ }
32062
+ if (stats.isSymbolicLink()) {
32063
+ throw new UnsafeCredentialPathError(filePath, "it is a symbolic link");
32064
+ }
32065
+ if (!stats.isFile()) {
32066
+ throw new UnsafeCredentialPathError(filePath, "it is not a regular file");
32067
+ }
32068
+ assertOwnedByCurrentUser(filePath, stats);
32069
+ };
32070
+
32071
+ // src/credentials/privateTempPath.ts
32072
+ import { randomBytes } from "crypto";
32073
+ import path17 from "path";
32074
+ var privateTempPath = (filePath) => path17.join(
32075
+ path17.dirname(filePath),
32076
+ `.${path17.basename(filePath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`
32077
+ );
32078
+
32079
+ // src/credentials/writePrivateFileAtomic.ts
32080
+ var writePrivateFileAtomic = async (filePath, text, hooks = {}) => {
32081
+ await ensurePrivateDir(path18.dirname(filePath));
32082
+ await assertReplaceableFile(filePath);
32083
+ const tempPath = privateTempPath(filePath);
32084
+ const handle = await open2(
32085
+ tempPath,
32086
+ constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | noFollowFlag(),
32087
+ privateModes.file
32088
+ );
32089
+ try {
32090
+ try {
32091
+ await handle.chmod(privateModes.file);
32092
+ await handle.writeFile(text, "utf8");
32093
+ await handle.sync();
32094
+ } finally {
32095
+ await handle.close();
32096
+ }
32097
+ await hooks.beforeRename?.(tempPath);
32098
+ await rename3(tempPath, filePath);
32099
+ } catch (error51) {
32100
+ await rm4(tempPath, { force: true }).catch(() => {
32101
+ });
32102
+ throw error51;
32103
+ }
32104
+ };
32105
+
32106
+ // src/credentials/writeStoredToken.ts
32107
+ var writeStoredToken = async (stateDir, token, hooks) => {
32108
+ await writePrivateFileAtomic(
32109
+ credentialsPath(stateDir),
32110
+ `${JSON.stringify({ token }, null, 2)}
32111
+ `,
32112
+ hooks
32113
+ );
32114
+ };
32115
+
32116
+ // src/credentials/migrateLegacyConfigToken.ts
32117
+ var migrateLegacyConfigToken = async (stateDir, legacyToken, rewriteConfigWithoutToken) => {
32118
+ if (typeof legacyToken === "string" && legacyToken) {
32119
+ const storedToken = await readStoredToken(stateDir);
32120
+ if (!storedToken) {
32121
+ await writeStoredToken(stateDir, legacyToken);
32122
+ }
32123
+ }
32124
+ await rewriteConfigWithoutToken();
32125
+ };
32126
+
32127
+ // src/state.ts
31645
32128
  var DEFAULT_STATE_DIRNAME = ".forum";
31646
32129
  var DEFAULT_POLL_INTERVAL_MS = 4e3;
31647
32130
  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");
32131
+ var defaultStateDir = () => path19.join(homedir(), DEFAULT_STATE_DIRNAME);
32132
+ var configPath = (stateDir) => path19.join(stateDir, "config.json");
31655
32133
  var ensureStateDir = async (stateDir) => {
31656
- await mkdir5(stateDir, { recursive: true });
32134
+ await ensurePrivateDir(stateDir);
31657
32135
  };
31658
- var readJson = async (filePath, fallback) => {
32136
+ var readRawConfig = async (stateDir) => {
31659
32137
  try {
31660
- const raw = await readFile6(filePath, "utf8");
31661
- return JSON.parse(raw);
32138
+ const raw = await readFile6(configPath(stateDir), "utf8");
32139
+ const parsed = JSON.parse(raw);
32140
+ return parsed && typeof parsed === "object" ? parsed : {};
31662
32141
  } catch {
31663
- return fallback;
32142
+ return {};
31664
32143
  }
31665
32144
  };
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`
32145
+ var normalizeSettings = (raw) => ({
32146
+ pollIntervalMs: typeof raw.pollIntervalMs === "number" && raw.pollIntervalMs > 0 ? raw.pollIntervalMs : DEFAULT_POLL_INTERVAL_MS,
32147
+ forceWrites: raw.forceWrites === true
32148
+ });
32149
+ var writeConfig = async (stateDir, settings) => {
32150
+ const persisted = {
32151
+ pollIntervalMs: settings.pollIntervalMs,
32152
+ forceWrites: settings.forceWrites
32153
+ };
32154
+ await writePrivateFileAtomic(
32155
+ configPath(stateDir),
32156
+ JSON.stringify(persisted, null, 2)
31671
32157
  );
31672
- await mkdir5(parentDir, { recursive: true });
31673
- await writeFile4(tempPath, JSON.stringify(value, null, 2), "utf8");
31674
- await rename3(tempPath, filePath);
31675
32158
  };
31676
32159
  var readConfig = async (stateDir) => {
31677
- const config2 = await readJson(
31678
- configPath(stateDir),
31679
- DEFAULT_CONFIG
31680
- );
32160
+ const raw = await readRawConfig(stateDir);
32161
+ const settings = normalizeSettings(raw);
32162
+ if ("token" in raw) {
32163
+ await migrateLegacyConfigToken(
32164
+ stateDir,
32165
+ raw.token,
32166
+ () => writeConfig(stateDir, settings)
32167
+ );
32168
+ }
31681
32169
  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
32170
+ ...settings,
32171
+ token: await readStoredToken(stateDir)
31685
32172
  };
31686
32173
  };
31687
- var writeConfig = async (stateDir, config2) => {
31688
- await writeJsonAtomic(configPath(stateDir), config2);
32174
+
32175
+ // src/credentials/removePrivateFile.ts
32176
+ import { rm as rm5 } from "fs/promises";
32177
+ var removePrivateFile = async (filePath) => {
32178
+ await rm5(filePath, { force: true });
32179
+ };
32180
+
32181
+ // src/credentials/deleteStoredToken.ts
32182
+ var deleteStoredToken = async (stateDir) => {
32183
+ await removePrivateFile(credentialsPath(stateDir));
32184
+ };
32185
+
32186
+ // src/credentials/redactedSecrets.ts
32187
+ var redactedSecrets = /* @__PURE__ */ new Set();
32188
+
32189
+ // src/credentials/redactSecrets.ts
32190
+ var redactedPlaceholder = "[REDACTED]";
32191
+ var redactSecrets = (text) => {
32192
+ let redacted = text;
32193
+ for (const secret of redactedSecrets) {
32194
+ redacted = redacted.split(secret).join(redactedPlaceholder);
32195
+ }
32196
+ return redacted;
32197
+ };
32198
+
32199
+ // src/credentials/redactError.ts
32200
+ var redactError = (error51) => {
32201
+ if (!(error51 instanceof Error)) {
32202
+ return redactSecrets(String(error51));
32203
+ }
32204
+ const message = redactSecrets(error51.message);
32205
+ if (message === error51.message) {
32206
+ return error51;
32207
+ }
32208
+ const redacted = new Error(message);
32209
+ redacted.name = error51.name;
32210
+ return redacted;
32211
+ };
32212
+
32213
+ // src/credentials/registerRedactedSecret.ts
32214
+ var minimumRedactableLength = 4;
32215
+ var registerRedactedSecret = (secret) => {
32216
+ if (secret && secret.length >= minimumRedactableLength) {
32217
+ redactedSecrets.add(secret);
32218
+ }
31689
32219
  };
31690
32220
 
31691
32221
  // src/expandHomePath.ts
31692
32222
  import os from "os";
31693
- import path17 from "path";
32223
+ import path20 from "path";
31694
32224
  var expandHomePath = (input) => {
31695
32225
  const home = process.env.HOME || os.homedir();
31696
32226
  if (input === "~") return home;
31697
- return input.startsWith("~/") ? path17.join(home, input.slice(2)) : input;
32227
+ return input.startsWith("~/") ? path20.join(home, input.slice(2)) : input;
31698
32228
  };
31699
32229
 
31700
32230
  // src/pathExists.ts
@@ -31727,9 +32257,9 @@ var parseSkillAgents = (value) => {
31727
32257
  import os2 from "os";
31728
32258
 
31729
32259
  // src/skills/createSkillClient.ts
31730
- import path18 from "path";
32260
+ import path21 from "path";
31731
32261
  var createSkillClient = async (options2) => {
31732
- const stateDir = options2.stateDir ? path18.resolve(options2.stateDir) : defaultStateDir();
32262
+ const stateDir = options2.stateDir ? path21.resolve(options2.stateDir) : defaultStateDir();
31733
32263
  const saved = await readConfig(stateDir);
31734
32264
  const apiBaseUrl = (process.env.DOCTRINE_API_URL || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
31735
32265
  const token = options2.token || process.env.DOCTRINE_TOKEN || saved.token;
@@ -31839,12 +32369,12 @@ var promptSkillConnection = async (client, input) => {
31839
32369
  };
31840
32370
 
31841
32371
  // src/skills/loadSkillStubs.ts
31842
- import { lstat as lstat4, mkdir as mkdir6, open, unlink } from "fs/promises";
31843
- import path22 from "path";
32372
+ import { lstat as lstat5, mkdir as mkdir6, open as open3, unlink } from "fs/promises";
32373
+ import path25 from "path";
31844
32374
 
31845
32375
  // src/skills/planSkillStubs.ts
31846
- import { lstat as lstat3, readdir as readdir5, readFile as readFile8 } from "fs/promises";
31847
- import path20 from "path";
32376
+ import { lstat as lstat4, readdir as readdir5, readFile as readFile8 } from "fs/promises";
32377
+ import path23 from "path";
31848
32378
  import { isDeepStrictEqual } from "util";
31849
32379
 
31850
32380
  // src/skills/createSkillStub.ts
@@ -31871,23 +32401,23 @@ var createSkillStub = (item, source) => [
31871
32401
  ].join("\n");
31872
32402
 
31873
32403
  // src/skills/readSkillStubMarker.ts
31874
- import { lstat as lstat2, readFile as readFile7, readdir as readdir4 } from "fs/promises";
31875
- import path19 from "path";
32404
+ import { lstat as lstat3, readFile as readFile7, readdir as readdir4 } from "fs/promises";
32405
+ import path22 from "path";
31876
32406
  import { createHash as createHash3 } from "crypto";
31877
32407
  var readSkillStubMarker = async (directory) => {
31878
- const stat4 = await lstat2(directory).catch((error51) => {
32408
+ const stat5 = await lstat3(directory).catch((error51) => {
31879
32409
  if (error51.code === "ENOENT") return null;
31880
32410
  throw error51;
31881
32411
  });
31882
- if (!stat4) return null;
31883
- if (!stat4.isDirectory() || stat4.isSymbolicLink())
32412
+ if (!stat5) return null;
32413
+ if (!stat5.isDirectory() || stat5.isSymbolicLink())
31884
32414
  throw new Error(
31885
32415
  `Skill destination is not a regular directory: ${directory}`
31886
32416
  );
31887
- const markerPath = path19.join(directory, ".forum-skill.json");
32417
+ const markerPath = path22.join(directory, ".forum-skill.json");
31888
32418
  const names = await readdir4(directory);
31889
32419
  if (!names.includes(".forum-skill.json")) return null;
31890
- const markerStat = await lstat2(markerPath);
32420
+ const markerStat = await lstat3(markerPath);
31891
32421
  if (!markerStat.isFile() || markerStat.isSymbolicLink())
31892
32422
  throw new Error(`Invalid Forum skill marker: ${markerPath}`);
31893
32423
  const marker = JSON.parse(
@@ -31900,8 +32430,8 @@ var readSkillStubMarker = async (directory) => {
31900
32430
  throw new Error(
31901
32431
  `Skill contains local files; refusing to replace it: ${directory}`
31902
32432
  );
31903
- const stubPath = path19.join(directory, "SKILL.md");
31904
- const stubStat = await lstat2(stubPath);
32433
+ const stubPath = path22.join(directory, "SKILL.md");
32434
+ const stubStat = await lstat3(stubPath);
31905
32435
  if (!stubStat.isFile() || stubStat.isSymbolicLink())
31906
32436
  throw new Error(`Invalid generated skill: ${stubPath}`);
31907
32437
  const content = await readFile7(stubPath, "utf8");
@@ -31923,7 +32453,7 @@ var planSkillStubs = async (input, roots) => {
31923
32453
  }
31924
32454
  );
31925
32455
  for (const item of input.skills) {
31926
- const destination = path20.join(root, item.slug);
32456
+ const destination = path23.join(root, item.slug);
31927
32457
  const exists2 = directories.some((entry) => entry.name === item.slug);
31928
32458
  const marker = exists2 ? await readSkillStubMarker(destination) : null;
31929
32459
  if (exists2 && (!marker || !isDeepStrictEqual(marker.source, input.source)))
@@ -31931,7 +32461,7 @@ var planSkillStubs = async (input, roots) => {
31931
32461
  `Skill name collision: ${destination}. Choose a different slug; existing skills are never overwritten.`
31932
32462
  );
31933
32463
  const content = createSkillStub(item, input.source);
31934
- const unchanged = marker && await readFile8(path20.join(destination, "SKILL.md"), "utf8") === content;
32464
+ const unchanged = marker && await readFile8(path23.join(destination, "SKILL.md"), "utf8") === content;
31935
32465
  changes.push({
31936
32466
  agent,
31937
32467
  slug: item.slug,
@@ -31944,9 +32474,9 @@ var planSkillStubs = async (input, roots) => {
31944
32474
  for (const entry of directories) {
31945
32475
  if (!entry.isDirectory() || entry.isSymbolicLink() || slugs.has(entry.name) || entry.name.startsWith("."))
31946
32476
  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(
32477
+ const destination = path23.join(root, entry.name);
32478
+ const markerPath = path23.join(destination, ".forum-skill.json");
32479
+ const markerStat = await lstat4(markerPath).catch(
31950
32480
  (error51) => {
31951
32481
  if (error51.code === "ENOENT") return null;
31952
32482
  throw error51;
@@ -31969,15 +32499,15 @@ var planSkillStubs = async (input, roots) => {
31969
32499
 
31970
32500
  // src/skills/applySkillStubChanges.ts
31971
32501
  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";
32502
+ import { mkdtemp, rename as rename4, rm as rm6, writeFile as writeFile4 } from "fs/promises";
32503
+ import path24 from "path";
31974
32504
  var applySkillStubChanges = async (changes, source) => {
31975
32505
  const applied = [];
31976
32506
  try {
31977
32507
  for (const change of changes) {
31978
32508
  if (change.action === "unchanged") continue;
31979
32509
  const temporary = await mkdtemp(
31980
- path21.join(path21.dirname(change.path), ".forum-skills-")
32510
+ path24.join(path24.dirname(change.path), ".forum-skills-")
31981
32511
  );
31982
32512
  const entry = {
31983
32513
  change,
@@ -31993,9 +32523,9 @@ var applySkillStubChanges = async (changes, source) => {
31993
32523
  source,
31994
32524
  hash: createHash4("sha256").update(content).digest("hex")
31995
32525
  };
31996
- await writeFile5(path21.join(temporary, "SKILL.md"), content, "utf8");
31997
- await writeFile5(
31998
- path21.join(temporary, ".forum-skill.json"),
32526
+ await writeFile4(path24.join(temporary, "SKILL.md"), content, "utf8");
32527
+ await writeFile4(
32528
+ path24.join(temporary, ".forum-skill.json"),
31999
32529
  `${JSON.stringify(marker, null, 2)}
32000
32530
  `,
32001
32531
  "utf8"
@@ -32013,15 +32543,15 @@ var applySkillStubChanges = async (changes, source) => {
32013
32543
  }
32014
32544
  } catch (error51) {
32015
32545
  for (const entry of applied.toReversed()) {
32016
- if (entry.installed) await rm4(entry.change.path, { recursive: true });
32546
+ if (entry.installed) await rm6(entry.change.path, { recursive: true });
32017
32547
  if (entry.backup) await rename4(entry.backup, entry.change.path);
32018
- await rm4(entry.temporary, { recursive: true, force: true });
32548
+ await rm6(entry.temporary, { recursive: true, force: true });
32019
32549
  }
32020
32550
  throw error51;
32021
32551
  }
32022
32552
  for (const entry of applied) {
32023
- if (entry.backup) await rm4(entry.backup, { recursive: true });
32024
- await rm4(entry.temporary, { recursive: true, force: true });
32553
+ if (entry.backup) await rm6(entry.backup, { recursive: true });
32554
+ await rm6(entry.temporary, { recursive: true, force: true });
32025
32555
  }
32026
32556
  };
32027
32557
 
@@ -32032,30 +32562,30 @@ var loadSkillStubs = async (input) => {
32032
32562
  throw new Error("Use a canonical store folder path.");
32033
32563
  if (new Set(input.skills.map((skill) => skill.slug)).size !== input.skills.length)
32034
32564
  throw new Error("Duplicate skill names in collection.");
32035
- const base = path22.resolve(input.global ? input.home : input.directory);
32565
+ const base = path25.resolve(input.global ? input.home : input.directory);
32036
32566
  const roots = [...new Set(input.agents)].map((agent) => ({
32037
32567
  agent,
32038
- root: path22.join(base, agent === "codex" ? ".agents" : ".claude", "skills")
32568
+ root: path25.join(base, agent === "codex" ? ".agents" : ".claude", "skills")
32039
32569
  }));
32040
32570
  const locks = [];
32041
32571
  try {
32042
32572
  for (const { root } of roots) {
32043
- for (const directory of [path22.dirname(root), root]) {
32044
- const stat4 = await lstat4(directory).catch(
32573
+ for (const directory of [path25.dirname(root), root]) {
32574
+ const stat5 = await lstat5(directory).catch(
32045
32575
  (error51) => {
32046
32576
  if (error51.code === "ENOENT") return null;
32047
32577
  throw error51;
32048
32578
  }
32049
32579
  );
32050
- if (stat4 && (!stat4.isDirectory() || stat4.isSymbolicLink()))
32580
+ if (stat5 && (!stat5.isDirectory() || stat5.isSymbolicLink()))
32051
32581
  throw new Error(
32052
32582
  `Skill root must be a regular directory: ${directory}`
32053
32583
  );
32054
32584
  }
32055
32585
  if (!input.dryRun) {
32056
32586
  await mkdir6(root, { recursive: true });
32057
- const lockPath = path22.join(root, ".forum-skills.lock");
32058
- const file2 = await open(lockPath, "wx").catch(
32587
+ const lockPath = path25.join(root, ".forum-skills.lock");
32588
+ const file2 = await open3(lockPath, "wx").catch(
32059
32589
  (error51) => {
32060
32590
  if (error51.code === "EEXIST")
32061
32591
  throw new Error(
@@ -32072,9 +32602,9 @@ var loadSkillStubs = async (input) => {
32072
32602
  return {
32073
32603
  dryRun: input.dryRun,
32074
32604
  source: input.source,
32075
- changes: changes.map(({ agent, path: path25, slug, action }) => ({
32605
+ changes: changes.map(({ agent, path: path28, slug, action }) => ({
32076
32606
  agent,
32077
- path: path25,
32607
+ path: path28,
32078
32608
  slug,
32079
32609
  action
32080
32610
  }))
@@ -32740,17 +33270,170 @@ var editEncryptedText = async ({
32740
33270
  return { changed: true, encryptedText: reencrypted };
32741
33271
  };
32742
33272
 
33273
+ // src/encryptionIdentity/changeEncryptionPassword.ts
33274
+ var changeEncryptionPassword = async ({
33275
+ client,
33276
+ currentPassword,
33277
+ nextPassword
33278
+ }) => {
33279
+ const { encryption } = await client.readUserPreferences();
33280
+ if (!encryption) {
33281
+ throw new Error("Encryption is not set up. Run `fm encryption setup`.");
33282
+ }
33283
+ const rewrapped = await rewrapUserEncryption({
33284
+ currentPassword,
33285
+ metadata: encryption,
33286
+ nextPassword
33287
+ });
33288
+ await client.rewrapEncryption({
33289
+ encryption: rewrapped,
33290
+ expectedKeyId: encryption.keyId
33291
+ });
33292
+ return {
33293
+ fingerprint: await computeEncryptionFingerprint(rewrapped.publicKey)
33294
+ };
33295
+ };
33296
+
33297
+ // src/encryptionIdentity/readEncryptionFingerprint.ts
33298
+ var readEncryptionFingerprint = async ({
33299
+ client
33300
+ }) => {
33301
+ const { encryption } = await client.readUserPreferences();
33302
+ if (!encryption) {
33303
+ throw new Error("Encryption is not set up. Run `fm encryption setup`.");
33304
+ }
33305
+ if (encryption.version === 1) {
33306
+ throw new Error(
33307
+ "Legacy encryption has no public identity. Run `fm encryption migrate`."
33308
+ );
33309
+ }
33310
+ return {
33311
+ fingerprint: await computeEncryptionFingerprint(encryption.publicKey),
33312
+ version: encryption.version
33313
+ };
33314
+ };
33315
+
33316
+ // src/encryptionIdentity/resetEncryptionIdentity.ts
33317
+ var resetEncryptionIdentity = async ({
33318
+ client,
33319
+ password
33320
+ }) => {
33321
+ const { encryption } = await client.readUserPreferences();
33322
+ if (!encryption) {
33323
+ throw new Error("Encryption is not set up. Run `fm encryption setup`.");
33324
+ }
33325
+ const { metadata } = await createUserEncryptionSetup(password);
33326
+ await client.resetEncryption({
33327
+ confirmation: "reset-encryption-identity",
33328
+ encryption: metadata,
33329
+ expectedKeyId: encryption.keyId
33330
+ });
33331
+ return { fingerprint: metadata.keyId, previousKeyId: encryption.keyId };
33332
+ };
33333
+
33334
+ // src/encryptionIdentity/setupEncryptionIdentity.ts
33335
+ var setupEncryptionIdentity = async ({
33336
+ client,
33337
+ password
33338
+ }) => {
33339
+ const preferences = await client.readUserPreferences();
33340
+ if (preferences.encryption) {
33341
+ throw new Error(
33342
+ 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`."
33343
+ );
33344
+ }
33345
+ const { metadata } = await createUserEncryptionSetup(password);
33346
+ await client.setupEncryption({ encryption: metadata, expectedKeyId: null });
33347
+ return { fingerprint: metadata.keyId };
33348
+ };
33349
+
33350
+ // src/encryptionIdentity/validateNewEncryptionPassword.ts
33351
+ var validateNewEncryptionPassword = (password) => {
33352
+ if (password.trim().length < 12) {
33353
+ throw new Error("Use at least 12 characters for your encryption password.");
33354
+ }
33355
+ };
33356
+
33357
+ // src/encryptionIdentity/runEncryptionIdentityCommand.ts
33358
+ var encryptionIdentitySubcommands = [
33359
+ "change-password",
33360
+ "fingerprint",
33361
+ "reset",
33362
+ "setup"
33363
+ ];
33364
+ var isEncryptionIdentitySubcommand = (value) => encryptionIdentitySubcommands.includes(value);
33365
+ var runEncryptionIdentityCommand = async ({
33366
+ client,
33367
+ confirmReset,
33368
+ readCurrentPassword,
33369
+ readNewPassword,
33370
+ render,
33371
+ subcommand
33372
+ }) => {
33373
+ if (subcommand === "fingerprint") {
33374
+ const { fingerprint: fingerprint2, version: version2 } = await readEncryptionFingerprint({
33375
+ client
33376
+ });
33377
+ render(formatEncryptionFingerprint(fingerprint2));
33378
+ if (version2 === 2) {
33379
+ render(
33380
+ "This key record predates key binding (v2). It is still checked on unlock; changing your password keeps it as v2."
33381
+ );
33382
+ }
33383
+ return;
33384
+ }
33385
+ if (subcommand === "setup") {
33386
+ const password2 = await readNewPassword();
33387
+ validateNewEncryptionPassword(password2);
33388
+ const { fingerprint: fingerprint2 } = await setupEncryptionIdentity({ client, password: password2 });
33389
+ render(
33390
+ `Encryption set up. Fingerprint: ${formatEncryptionFingerprint(fingerprint2)}`
33391
+ );
33392
+ return;
33393
+ }
33394
+ if (subcommand === "change-password") {
33395
+ const currentPassword = await readCurrentPassword();
33396
+ const nextPassword = await readNewPassword();
33397
+ validateNewEncryptionPassword(nextPassword);
33398
+ const { fingerprint: fingerprint2 } = await changeEncryptionPassword({
33399
+ client,
33400
+ currentPassword,
33401
+ nextPassword
33402
+ });
33403
+ render(
33404
+ `Encryption password changed. Your identity is unchanged: ${formatEncryptionFingerprint(fingerprint2)}`
33405
+ );
33406
+ render(
33407
+ "Copies of your old key record (exports, backups) remain protected by the old password."
33408
+ );
33409
+ return;
33410
+ }
33411
+ if (!await confirmReset()) {
33412
+ render("Reset cancelled.");
33413
+ return;
33414
+ }
33415
+ const password = await readNewPassword();
33416
+ validateNewEncryptionPassword(password);
33417
+ const { fingerprint } = await resetEncryptionIdentity({ client, password });
33418
+ render(
33419
+ `Encryption identity reset. New fingerprint: ${formatEncryptionFingerprint(fingerprint)}`
33420
+ );
33421
+ render(
33422
+ "Files encrypted for your previous identity cannot be opened with the new one. Teammates must verify this fingerprint before granting you access again."
33423
+ );
33424
+ };
33425
+
32743
33426
  // src/openInEditor.ts
32744
33427
  import { spawn } from "child_process";
32745
- import { mkdtemp as mkdtemp2, readFile as readFile9, rm as rm5, writeFile as writeFile6 } from "fs/promises";
33428
+ import { mkdtemp as mkdtemp2, readFile as readFile9, rm as rm7, writeFile as writeFile5 } from "fs/promises";
32746
33429
  import { tmpdir } from "os";
32747
- import path23 from "path";
33430
+ import path26 from "path";
32748
33431
  var openInEditor = async (currentText, { extension = "" } = {}) => {
32749
33432
  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}`);
33433
+ const dir = await mkdtemp2(path26.join(tmpdir(), "fm-edit-"));
33434
+ const tempPath = path26.join(dir, `edit${extension}`);
32752
33435
  try {
32753
- await writeFile6(tempPath, currentText, "utf8");
33436
+ await writeFile5(tempPath, currentText, "utf8");
32754
33437
  const exitCode = await new Promise((resolve, reject) => {
32755
33438
  const child = spawn(
32756
33439
  "/bin/sh",
@@ -32765,7 +33448,7 @@ var openInEditor = async (currentText, { extension = "" } = {}) => {
32765
33448
  }
32766
33449
  return await readFile9(tempPath, "utf8");
32767
33450
  } finally {
32768
- await rm5(dir, { force: true, recursive: true }).catch(() => {
33451
+ await rm7(dir, { force: true, recursive: true }).catch(() => {
32769
33452
  });
32770
33453
  }
32771
33454
  };
@@ -33030,7 +33713,7 @@ Usage:
33030
33713
  Auth, config:
33031
33714
  fm auth login|logout|status [--no-open]
33032
33715
  fm config show [--state-dir <path>]
33033
- fm config get <key> [--state-dir <path>]
33716
+ fm config get <key> [--reveal] [--state-dir <path>]
33034
33717
  fm config set <key> <value> [--state-dir <path>]
33035
33718
  fm config unset <key> [--state-dir <path>]
33036
33719
  fm config validate
@@ -33131,6 +33814,7 @@ var parseArgs = (argv) => {
33131
33814
  let optional2 = false;
33132
33815
  let stdin = false;
33133
33816
  let readonly2 = false;
33817
+ let reveal = false;
33134
33818
  let verbose = false;
33135
33819
  let watch3 = false;
33136
33820
  let yes = false;
@@ -33178,13 +33862,13 @@ var parseArgs = (argv) => {
33178
33862
  continue;
33179
33863
  }
33180
33864
  if (current === "--file" || current === "-f") {
33181
- inputFilePath = next ? path24.resolve(next) : inputFilePath;
33865
+ inputFilePath = next ? path27.resolve(next) : inputFilePath;
33182
33866
  index += 1;
33183
33867
  continue;
33184
33868
  }
33185
33869
  if (current === "--output" || current === "-o") {
33186
33870
  if (!next) throw new Error(`${current} requires a local output path.`);
33187
- outputFilePath = path24.resolve(next);
33871
+ outputFilePath = path27.resolve(next);
33188
33872
  index += 1;
33189
33873
  continue;
33190
33874
  }
@@ -33241,7 +33925,7 @@ var parseArgs = (argv) => {
33241
33925
  continue;
33242
33926
  }
33243
33927
  if (current === "--state-dir") {
33244
- stateDir = path24.resolve(next ?? stateDir);
33928
+ stateDir = path27.resolve(next ?? stateDir);
33245
33929
  index += 1;
33246
33930
  continue;
33247
33931
  }
@@ -33249,12 +33933,12 @@ var parseArgs = (argv) => {
33249
33933
  if (!next) {
33250
33934
  throw new Error("--paths-file requires a file path.");
33251
33935
  }
33252
- pathsFile = path24.resolve(expandHomePath(next));
33936
+ pathsFile = path27.resolve(expandHomePath(next));
33253
33937
  index += 1;
33254
33938
  continue;
33255
33939
  }
33256
33940
  if (current.startsWith("--paths-file=")) {
33257
- pathsFile = path24.resolve(
33941
+ pathsFile = path27.resolve(
33258
33942
  expandHomePath(current.slice("--paths-file=".length))
33259
33943
  );
33260
33944
  continue;
@@ -33309,6 +33993,10 @@ var parseArgs = (argv) => {
33309
33993
  readonly2 = true;
33310
33994
  continue;
33311
33995
  }
33996
+ if (current === "--reveal") {
33997
+ reveal = true;
33998
+ continue;
33999
+ }
33312
34000
  if (current === "--verbose" || current === "--debug" || current === "-v") {
33313
34001
  verbose = true;
33314
34002
  continue;
@@ -33364,6 +34052,7 @@ var parseArgs = (argv) => {
33364
34052
  optional: optional2,
33365
34053
  stdin,
33366
34054
  readonly: readonly2,
34055
+ reveal,
33367
34056
  verbose,
33368
34057
  watch: watch3,
33369
34058
  yes,
@@ -33404,6 +34093,9 @@ var resolveApiBaseUrl = () => {
33404
34093
  };
33405
34094
  var resolveConfig = async (parsed) => {
33406
34095
  const stored = await readConfig(parsed.stateDir);
34096
+ registerRedactedSecret(stored.token);
34097
+ registerRedactedSecret(parsed.token);
34098
+ registerRedactedSecret(process.env.DOCTRINE_TOKEN);
33407
34099
  return {
33408
34100
  apiBaseUrl: resolveApiBaseUrl(),
33409
34101
  token: parsed.token ?? process.env.DOCTRINE_TOKEN ?? stored.token,
@@ -33438,10 +34130,10 @@ var listDirectoryEntries = async (listDirectory, directoryPath) => {
33438
34130
  if (left.type !== "directory" && right.type === "directory") {
33439
34131
  return 1;
33440
34132
  }
33441
- return path24.basename(left.path).localeCompare(path24.basename(right.path));
34133
+ return path27.basename(left.path).localeCompare(path27.basename(right.path));
33442
34134
  }).forEach((entry) => {
33443
34135
  const suffix = entry.type === "directory" ? "/" : "";
33444
- renderOutput(`${path24.basename(entry.path)}${suffix}`);
34136
+ renderOutput(`${path27.basename(entry.path)}${suffix}`);
33445
34137
  });
33446
34138
  };
33447
34139
  var listStores = async (listStoresMetadata) => {
@@ -33861,7 +34553,7 @@ var readRemoteTextFile = async (filePath, storeRef, client) => {
33861
34553
  return text;
33862
34554
  };
33863
34555
  var normalizeRemotePath = (input) => {
33864
- const normalized = path24.posix.normalize(`/${input.trim()}`);
34556
+ const normalized = path27.posix.normalize(`/${input.trim()}`);
33865
34557
  if (normalized.includes("\0")) {
33866
34558
  throw new Error("Path contains an invalid null byte.");
33867
34559
  }
@@ -34155,7 +34847,7 @@ var diffRemoteFiles = async ({
34155
34847
  storeRef
34156
34848
  }) => {
34157
34849
  const leftText = await readRemoteTextFile(leftPath, storeRef, client);
34158
- const rightText = localRight ? await readFile10(path24.resolve(rightPath), "utf8") : await readRemoteTextFile(rightPath, storeRef, client);
34850
+ const rightText = localRight ? await readFile10(path27.resolve(rightPath), "utf8") : await readRemoteTextFile(rightPath, storeRef, client);
34159
34851
  return buildUnifiedDiff({
34160
34852
  leftLabel: leftPath,
34161
34853
  leftText,
@@ -34222,8 +34914,8 @@ var copyRemotePath = async (args, storeRef, client) => {
34222
34914
  (entry) => entry.path.startsWith(`${normalizedSource}/`)
34223
34915
  );
34224
34916
  for (const entry of descendants) {
34225
- const relativePath = path24.posix.relative(normalizedSource, entry.path);
34226
- const targetPath = path24.posix.join(normalizedDestination, relativePath);
34917
+ const relativePath = path27.posix.relative(normalizedSource, entry.path);
34918
+ const targetPath = path27.posix.join(normalizedDestination, relativePath);
34227
34919
  if (entry.type === "directory") {
34228
34920
  await createRemoteDirectory(targetPath, storeRef, client);
34229
34921
  continue;
@@ -34360,11 +35052,23 @@ var readEncryptionPassword = async (parsed) => {
34360
35052
  }
34361
35053
  return readHiddenLine("Encryption password: ");
34362
35054
  };
35055
+ var readNewEncryptionPassword = async () => {
35056
+ const password = process.env.DOCTRINE_NEW_ENCRYPTION_PASSWORD;
35057
+ if (password) {
35058
+ return password;
35059
+ }
35060
+ const first = await readHiddenLine("New encryption password: ");
35061
+ const second = await readHiddenLine("Repeat new encryption password: ");
35062
+ if (first !== second) {
35063
+ throw new Error("The new encryption passwords do not match.");
35064
+ }
35065
+ return first;
35066
+ };
34363
35067
  var readUserEncryption = async (client) => {
34364
35068
  const preferences = await client.readUserPreferences();
34365
35069
  if (!preferences.encryption) {
34366
35070
  throw new Error(
34367
- "Encryption is not set up for this user. Set it up in the web app first."
35071
+ "Encryption is not set up for this user. Run `fm encryption setup` or set it up in the web app first."
34368
35072
  );
34369
35073
  }
34370
35074
  return {
@@ -34418,7 +35122,7 @@ var runDecryptCommand = async (rest, parsed, client) => {
34418
35122
  );
34419
35123
  };
34420
35124
  var runEditCommand = async (rest, parsed, client) => {
34421
- const filePath = parsed.inputFilePath ?? (rest[0] ? path24.resolve(rest[0]) : null);
35125
+ const filePath = parsed.inputFilePath ?? (rest[0] ? path27.resolve(rest[0]) : null);
34422
35126
  if (!filePath) {
34423
35127
  throw new Error(
34424
35128
  `Usage: ${commandNames} edit (<localPath>|--file|-f <localPath>) [--password <password>] [--token <jwt>]`
@@ -34430,7 +35134,7 @@ var runEditCommand = async (rest, parsed, client) => {
34430
35134
  readUserEncryption(client)
34431
35135
  ]);
34432
35136
  const result = await editEncryptedText({
34433
- edit: (currentPlaintext) => openInEditor(currentPlaintext, { extension: path24.extname(filePath) }),
35137
+ edit: (currentPlaintext) => openInEditor(currentPlaintext, { extension: path27.extname(filePath) }),
34434
35138
  encryptedText,
34435
35139
  password,
34436
35140
  userEncryption: userEncryption.userEncryption
@@ -34483,7 +35187,7 @@ var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
34483
35187
  userEncryption: userEncryption.userEncryption
34484
35188
  });
34485
35189
  if (parsed.inputFilePath) {
34486
- await writeFile7(parsed.inputFilePath, result.encryptedText, "utf8");
35190
+ await writeFile6(parsed.inputFilePath, result.encryptedText, "utf8");
34487
35191
  }
34488
35192
  if (parsed.json) {
34489
35193
  renderOutput({
@@ -34506,11 +35210,11 @@ var runEncryptAddRecipientCommand = async (rest, parsed, client) => {
34506
35210
  `);
34507
35211
  renderOutput(result.encryptedText);
34508
35212
  };
34509
- var defaultEncryptionMigrationBackupPath = () => path24.resolve(process.cwd(), "doctrine-encryption-migration.json");
35213
+ var defaultEncryptionMigrationBackupPath = () => path27.resolve(process.cwd(), "doctrine-encryption-migration.json");
34510
35214
  var readEncryptionMigrationBackup = async (backupPath) => JSON.parse(await readFile10(backupPath, "utf8"));
34511
35215
  var writeEncryptionMigrationBackup = async (backupPath, backup) => {
34512
- await mkdir7(path24.dirname(backupPath), { recursive: true });
34513
- await writeFile7(backupPath, `${JSON.stringify(backup, null, 2)}
35216
+ await mkdir7(path27.dirname(backupPath), { recursive: true });
35217
+ await writeFile6(backupPath, `${JSON.stringify(backup, null, 2)}
34514
35218
  `, "utf8");
34515
35219
  };
34516
35220
  var confirmEncryptionMigration = async ({
@@ -34692,7 +35396,11 @@ var migrateEncryptionBackupFile = async ({
34692
35396
  const encryptedFile = await createEncryptedPlainTextFile({
34693
35397
  label: backup.currentUserLabel,
34694
35398
  plaintext: legacyPlaintext,
34695
- userEncryption: backup.newUserEncryption
35399
+ userEncryption: backup.newUserEncryption,
35400
+ userKey: await unlockUserEncryption({
35401
+ metadata: backup.newUserEncryption,
35402
+ password
35403
+ })
34696
35404
  });
34697
35405
  const localVerification = await decryptTextForUser({
34698
35406
  encryptedText: encryptedFile.text,
@@ -34797,14 +35505,14 @@ var runEncryptionMigrateCommand = async (rest, parsed, client) => {
34797
35505
  `Usage: ${commandNames} encryption migrate [backup-file] [--store <storeId>] [--password <password>] [--dry-run] [--yes]`
34798
35506
  );
34799
35507
  }
34800
- const backupPath = path24.resolve(
35508
+ const backupPath = path27.resolve(
34801
35509
  rest[1] ?? defaultEncryptionMigrationBackupPath()
34802
35510
  );
34803
35511
  const password = await readEncryptionPassword(parsed);
34804
35512
  const preferences = await client.readUserPreferences();
34805
35513
  if (!preferences.encryption) {
34806
35514
  throw new Error(
34807
- "Encryption is not set up for this user. Set it up in the web app first."
35515
+ "Encryption is not set up for this user. Run `fm encryption setup` or set it up in the web app first."
34808
35516
  );
34809
35517
  }
34810
35518
  const accountIsLegacy = isLegacyUserEncryptionMetadata(
@@ -34859,8 +35567,14 @@ var runEncryptionMigrateCommand = async (rest, parsed, client) => {
34859
35567
  throw error51;
34860
35568
  }
34861
35569
  if (accountIsLegacy) {
34862
- await client.upsertUserPreferences({
34863
- patch: { encryption: backup.newUserEncryption }
35570
+ if (backup.newUserEncryption.version !== 3) {
35571
+ throw new Error(
35572
+ "This migration backup predates key binding. Delete it and re-run the migration to create a new backup."
35573
+ );
35574
+ }
35575
+ await client.setupEncryption({
35576
+ encryption: backup.newUserEncryption,
35577
+ expectedKeyId: backup.oldUserEncryption.keyId
34864
35578
  });
34865
35579
  }
34866
35580
  renderOutput(
@@ -34872,7 +35586,7 @@ var doesRemoteQueryMatchPath = (query, filePath) => {
34872
35586
  if (query.startsWith("/")) {
34873
35587
  return normalizedPath === query;
34874
35588
  }
34875
- const filename = path24.basename(filePath).toLowerCase();
35589
+ const filename = path27.basename(filePath).toLowerCase();
34876
35590
  return filename === query || normalizedPath === query || filename.includes(query) || normalizedPath.includes(query);
34877
35591
  };
34878
35592
  var queryRemoteFiles = async (query, storeFilters, client) => {
@@ -34944,7 +35658,7 @@ var printRemoteQueryMatches = (matches) => {
34944
35658
  });
34945
35659
  };
34946
35660
  var normalizeRemoteDirectoryPath = (input) => {
34947
- const normalized = path24.posix.normalize(`/${input.trim()}`);
35661
+ const normalized = path27.posix.normalize(`/${input.trim()}`);
34948
35662
  if (normalized.includes("\0")) {
34949
35663
  throw new Error("Path contains an invalid null byte.");
34950
35664
  }
@@ -35064,12 +35778,12 @@ var labelFromTreeDirectoryPath = (directoryPath) => {
35064
35778
  if (directoryPath === "/") {
35065
35779
  return "./";
35066
35780
  }
35067
- return `${path24.posix.basename(directoryPath)}/`;
35781
+ return `${path27.posix.basename(directoryPath)}/`;
35068
35782
  };
35069
35783
  var doesTreeFilterMatchDirectory = (filter, directoryPath) => {
35070
35784
  const normalizedFilter = filter.trim().toLowerCase();
35071
35785
  const normalizedPath = directoryPath.toLowerCase();
35072
- const basename3 = path24.posix.basename(directoryPath).toLowerCase();
35786
+ const basename3 = path27.posix.basename(directoryPath).toLowerCase();
35073
35787
  return basename3.includes(normalizedFilter) || normalizedPath.includes(normalizedFilter);
35074
35788
  };
35075
35789
  var resolveTreeDirectoryPath = async ({
@@ -35124,7 +35838,7 @@ var printRemoteTreeChildren = async ({
35124
35838
  const childPrefix = isLast ? " " : "\u2502 ";
35125
35839
  const suffix = entry.type === "directory" ? "/" : "";
35126
35840
  lines.push(
35127
- `${prefix}${connector}${path24.posix.basename(entry.path)}${suffix}`
35841
+ `${prefix}${connector}${path27.posix.basename(entry.path)}${suffix}`
35128
35842
  );
35129
35843
  if (entry.type === "directory") {
35130
35844
  await printRemoteTreeChildren({
@@ -35413,17 +36127,18 @@ var printConfigShow = async (parsed) => {
35413
36127
  var getConfigValue = async (parsed, key) => {
35414
36128
  const stored = await readConfig(parsed.stateDir);
35415
36129
  if (key === "token") {
35416
- return stored.token ?? "";
36130
+ if (parsed.reveal) {
36131
+ return stored.token ?? "";
36132
+ }
36133
+ return stored.token ? "(set)" : "(unset)";
35417
36134
  }
35418
36135
  return String(stored.pollIntervalMs);
35419
36136
  };
35420
36137
  var setConfigValue = async (parsed, key, value) => {
35421
36138
  const stored = await readConfig(parsed.stateDir);
35422
36139
  if (key === "token") {
35423
- await writeConfig(parsed.stateDir, {
35424
- ...stored,
35425
- token: value
35426
- });
36140
+ registerRedactedSecret(value);
36141
+ await writeStoredToken(parsed.stateDir, value);
35427
36142
  renderOutput("Stored token.");
35428
36143
  return;
35429
36144
  }
@@ -35440,10 +36155,7 @@ var setConfigValue = async (parsed, key, value) => {
35440
36155
  var unsetConfigValue = async (parsed, key) => {
35441
36156
  const stored = await readConfig(parsed.stateDir);
35442
36157
  if (key === "token") {
35443
- await writeConfig(parsed.stateDir, {
35444
- ...stored,
35445
- token: null
35446
- });
36158
+ await deleteStoredToken(parsed.stateDir);
35447
36159
  renderOutput("Unset token.");
35448
36160
  return;
35449
36161
  }
@@ -35736,9 +36448,9 @@ var shouldPrintCheckoutDetail = (detail, verbose) => {
35736
36448
  var formatCheckoutDetail = (detail, options2) => {
35737
36449
  const status = checkoutStatusLabel(detail, options2);
35738
36450
  const direction = checkoutDirectionLabel(detail);
35739
- const path25 = formatCheckoutDetailPath(detail, options2.syncRules);
36451
+ const path28 = formatCheckoutDetailPath(detail, options2.syncRules);
35740
36452
  const reason = styleText.dim(checkoutDetailMessage(detail));
35741
- return direction ? `${direction} ${status} ${path25} ${reason}` : `${status} ${path25} ${reason}`;
36453
+ return direction ? `${direction} ${status} ${path28} ${reason}` : `${status} ${path28} ${reason}`;
35742
36454
  };
35743
36455
  var formatCheckoutDetailPath = (detail, syncRules) => {
35744
36456
  const localPath = formatLocalCheckoutPath(detail.relativePath);
@@ -35950,9 +36662,9 @@ var checkoutReportGroups = (details, options2) => {
35950
36662
  );
35951
36663
  };
35952
36664
  var checkoutReportDetailLine = (detail, options2) => {
35953
- const path25 = formatCheckoutDetailPath(detail, options2.syncRules);
36665
+ const path28 = formatCheckoutDetailPath(detail, options2.syncRules);
35954
36666
  const message = detail.status === "failed" || detail.status === "skipped" || detail.status === "ignored" ? detail.message ?? checkoutDetailMessage(detail) : "";
35955
- return message ? ` ${path25} ${styleText.dim(message)}` : ` ${path25}`;
36667
+ return message ? ` ${path28} ${styleText.dim(message)}` : ` ${path28}`;
35956
36668
  };
35957
36669
  var checkoutReportGroupBlock = ({
35958
36670
  dryRun,
@@ -36079,13 +36791,13 @@ var statusChangeKind = (detail) => {
36079
36791
  var formatStatusChange = (detail, syncRules) => {
36080
36792
  const kind = statusChangeKind(detail);
36081
36793
  const tone = kind === "deleted" ? "error" : kind === "added" ? "ok" : "warn";
36082
- const path25 = formatCheckoutDetailPath(detail, syncRules);
36083
- return ` ${styleText.color(tone, kind.padEnd(8))} ${path25}`;
36794
+ const path28 = formatCheckoutDetailPath(detail, syncRules);
36795
+ return ` ${styleText.color(tone, kind.padEnd(8))} ${path28}`;
36084
36796
  };
36085
36797
  var formatStatusBlock = (detail, syncRules) => {
36086
36798
  const message = detail.message ? ` ${styleText.dim(detail.message)}` : "";
36087
- const path25 = formatCheckoutDetailPath(detail, syncRules);
36088
- return ` ${styleText.color("error", "blocked ".padEnd(8))} ${path25}${message}`;
36799
+ const path28 = formatCheckoutDetailPath(detail, syncRules);
36800
+ return ` ${styleText.color("error", "blocked ".padEnd(8))} ${path28}${message}`;
36089
36801
  };
36090
36802
  var actionableStatusDetails = (result) => result.details.filter(
36091
36803
  (detail) => detail.status === "succeeded" || detail.status === "deleted"
@@ -36744,15 +37456,15 @@ var runCheckoutStatus = async ({
36744
37456
  var isCheckoutStateGitPath = isCheckoutStateDirectoryPath;
36745
37457
  var checkoutFilesManifestPath2 = () => `${resolveCheckoutStateDirectoryName()}/files.json`;
36746
37458
  var isInsideOrEqual = (parentPath, childPath2) => {
36747
- const relativePath = path24.relative(parentPath, childPath2);
36748
- return relativePath === "" || !relativePath.startsWith("..") && !path24.isAbsolute(relativePath);
37459
+ const relativePath = path27.relative(parentPath, childPath2);
37460
+ return relativePath === "" || !relativePath.startsWith("..") && !path27.isAbsolute(relativePath);
36749
37461
  };
36750
37462
  var resolveSyncTargetPaths = (checkout) => checkout.syncRules.map(
36751
- (rule) => path24.resolve(checkout.rootDir, rule.target || ".")
37463
+ (rule) => path27.resolve(checkout.rootDir, rule.target || ".")
36752
37464
  );
36753
- var resolveCheckoutManifestGitPath = (checkout, gitRoot) => path24.relative(
37465
+ var resolveCheckoutManifestGitPath = (checkout, gitRoot) => path27.relative(
36754
37466
  gitRoot,
36755
- path24.join(checkout.rootDir, checkoutFilesManifestPath2())
37467
+ path27.join(checkout.rootDir, checkoutFilesManifestPath2())
36756
37468
  ) || checkoutFilesManifestPath2();
36757
37469
  var stageCheckoutManifest = async ({
36758
37470
  checkout,
@@ -36778,7 +37490,7 @@ var assertGitChangesStayInSyncTargets = async ({
36778
37490
  if (isCheckoutStateGitPath(entry.path)) {
36779
37491
  return false;
36780
37492
  }
36781
- const absolutePath = path24.resolve(gitRoot, entry.path);
37493
+ const absolutePath = path27.resolve(gitRoot, entry.path);
36782
37494
  return !allowedPaths.some(
36783
37495
  (allowedPath) => isInsideOrEqual(allowedPath, absolutePath)
36784
37496
  );
@@ -36800,7 +37512,7 @@ var stageGitSyncTargets = async ({
36800
37512
  }) => {
36801
37513
  const targetPaths = [];
36802
37514
  for (const targetPath of resolveSyncTargetPaths(checkout)) {
36803
- const relativePath = path24.relative(gitRoot, targetPath) || ".";
37515
+ const relativePath = path27.relative(gitRoot, targetPath) || ".";
36804
37516
  const tracked = await runGit(gitRoot, ["ls-files", "--", relativePath]);
36805
37517
  if (await pathExists3(targetPath) || tracked.stdout.trim()) {
36806
37518
  targetPaths.push(relativePath);
@@ -37100,7 +37812,7 @@ var writeCheckoutConfig = async (directoryPath, metadata, workspaceSlug, options
37100
37812
  );
37101
37813
  }
37102
37814
  await writeForumProjectConfig(
37103
- path24.join(directoryPath, defaultProjectConfigFilename),
37815
+ path27.join(directoryPath, defaultProjectConfigFilename),
37104
37816
  {
37105
37817
  syncRules: [
37106
37818
  {
@@ -37137,7 +37849,7 @@ var normalizeProjectConfigPath = (value, fieldName, allowCurrentDirectory = fals
37137
37849
  }
37138
37850
  throw new Error(`${fieldName} must be a non-empty relative path.`);
37139
37851
  }
37140
- if (path24.isAbsolute(value)) {
37852
+ if (path27.isAbsolute(value)) {
37141
37853
  throw new Error(`${fieldName} must be a relative path.`);
37142
37854
  }
37143
37855
  const segments2 = trimmed.split("/");
@@ -37319,7 +38031,7 @@ var defaultCloneDirectoryName = (storeId) => {
37319
38031
  var fsErrorCode = (error51) => error51 instanceof Error && "code" in error51 ? String(error51.code ?? "") : "";
37320
38032
  var ensureGitMetadataExists = async (directoryPath) => {
37321
38033
  try {
37322
- await lstat5(path24.join(directoryPath, ".git"));
38034
+ await lstat6(path27.join(directoryPath, ".git"));
37323
38035
  } catch (error51) {
37324
38036
  if (fsErrorCode(error51) === "ENOENT") {
37325
38037
  throw new Error(
@@ -37357,8 +38069,8 @@ var confirmGitMetadataDeletion = async (localPath, assumeYes) => {
37357
38069
  "Refusing to delete .git without interactive confirmation. Rerun with --yes to confirm in a non-interactive shell."
37358
38070
  );
37359
38071
  }
37360
- const gitPath = path24.join(localPath, ".git");
37361
- const gitignorePath = path24.join(localPath, ".gitignore");
38072
+ const gitPath = path27.join(localPath, ".git");
38073
+ const gitignorePath = path27.join(localPath, ".gitignore");
37362
38074
  const confirmationPhrase = "DELETE GIT";
37363
38075
  renderWarning("");
37364
38076
  renderWarning("DANGER: Forum is about to remove Git from this checkout.");
@@ -37404,7 +38116,7 @@ var runGitConvertCommand = async ({
37404
38116
  );
37405
38117
  }
37406
38118
  await writeForumProjectConfig(
37407
- path24.join(localPath, defaultProjectConfigFilename),
38119
+ path27.join(localPath, defaultProjectConfigFilename),
37408
38120
  {
37409
38121
  syncRules: [
37410
38122
  {
@@ -37466,8 +38178,8 @@ var runGitConvertCommand = async ({
37466
38178
  "Aborted before deleting Git metadata. The Forum push completed, but .git and .gitignore were left in place."
37467
38179
  );
37468
38180
  }
37469
- await rm6(path24.join(localPath, ".gitignore"), { force: true });
37470
- await rm6(path24.join(localPath, ".git"), { recursive: true, force: true });
38181
+ await rm8(path27.join(localPath, ".gitignore"), { force: true });
38182
+ await rm8(path27.join(localPath, ".git"), { recursive: true, force: true });
37471
38183
  renderOutput(
37472
38184
  `${created ? "Created" : "Using existing"} store ${metadata.slug}`
37473
38185
  );
@@ -37522,21 +38234,17 @@ var main = async (argv = process.argv.slice(2)) => {
37522
38234
  openBrowser: parsed.openBrowser
37523
38235
  })
37524
38236
  );
37525
- await writeConfig(parsed.stateDir, {
37526
- token,
37527
- pollIntervalMs: config3.pollIntervalMs,
37528
- forceWrites: config3.forceWrites
37529
- });
38237
+ registerRedactedSecret(token);
38238
+ await writeStoredToken(parsed.stateDir, token);
37530
38239
  renderOutput("Login successful. CLI token stored.");
37531
38240
  return;
37532
38241
  }
37533
38242
  if (subcommand === "logout") {
37534
- await writeConfig(parsed.stateDir, {
37535
- token: null,
37536
- pollIntervalMs: config3.pollIntervalMs,
37537
- forceWrites: config3.forceWrites
37538
- });
37539
- renderOutput("Logged out.");
38243
+ await deleteStoredToken(parsed.stateDir);
38244
+ renderOutput("Logged out. Local CLI credential removed.");
38245
+ if (process.env.DOCTRINE_TOKEN) {
38246
+ renderOutput("DOCTRINE_TOKEN is still set in this environment.");
38247
+ }
37540
38248
  return;
37541
38249
  }
37542
38250
  if (subcommand === "status") {
@@ -37594,7 +38302,7 @@ var main = async (argv = process.argv.slice(2)) => {
37594
38302
  }
37595
38303
  if (command === "hash" && parsed.local) {
37596
38304
  const filePath = rest[0];
37597
- renderOutput(await hashLocalFile(path24.resolve(filePath)));
38305
+ renderOutput(await hashLocalFile(path27.resolve(filePath)));
37598
38306
  return;
37599
38307
  }
37600
38308
  const config2 = await resolveConfig(parsed);
@@ -37641,6 +38349,21 @@ var main = async (argv = process.argv.slice(2)) => {
37641
38349
  await runEncryptionMigrateCommand(rest, parsed, client);
37642
38350
  return;
37643
38351
  }
38352
+ if (command === "encryption" && isEncryptionIdentitySubcommand(rest[0])) {
38353
+ await runEncryptionIdentityCommand({
38354
+ client,
38355
+ confirmReset: () => confirmYesNo({
38356
+ assumeYes: parsed.yes,
38357
+ nonInteractiveMessage: "Resetting your encryption identity needs confirmation. Re-run with --yes.",
38358
+ 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] "
38359
+ }),
38360
+ readCurrentPassword: () => readEncryptionPassword(parsed),
38361
+ readNewPassword: readNewEncryptionPassword,
38362
+ render: renderOutput,
38363
+ subcommand: rest[0]
38364
+ });
38365
+ return;
38366
+ }
37644
38367
  if (command === "inspect") {
37645
38368
  const filePath = rest[0] === "file" ? rest[1] : rest[0];
37646
38369
  if (!filePath) {
@@ -38081,8 +38804,8 @@ var main = async (argv = process.argv.slice(2)) => {
38081
38804
  `Usage: ${commandNames} clone <storeId> [localPath] [--readonly]`
38082
38805
  );
38083
38806
  }
38084
- const localPath = path24.resolve(
38085
- rest[1] ?? path24.join(process.cwd(), defaultCloneDirectoryName(remoteInput))
38807
+ const localPath = path27.resolve(
38808
+ rest[1] ?? path27.join(process.cwd(), defaultCloneDirectoryName(remoteInput))
38086
38809
  );
38087
38810
  const { metadata, workspaceSlug, storeRef } = await resolveReadableStore(
38088
38811
  remoteInput,
@@ -38110,7 +38833,7 @@ var main = async (argv = process.argv.slice(2)) => {
38110
38833
  storeRef,
38111
38834
  syncRules: checkout.syncRules
38112
38835
  });
38113
- renderOutput(`Cloned store ${metadata.slug} to ${path24.resolve(localPath)}`);
38836
+ renderOutput(`Cloned store ${metadata.slug} to ${path27.resolve(localPath)}`);
38114
38837
  formatCheckoutResult("Pulled", result, {
38115
38838
  detailsRendered: Boolean(progress),
38116
38839
  verbose: parsed.verbose
@@ -38160,7 +38883,7 @@ var main = async (argv = process.argv.slice(2)) => {
38160
38883
  });
38161
38884
  result.warnings.forEach((warning) => renderWarning(warning));
38162
38885
  if (parsed.outputFilePath) {
38163
- await writeFile7(parsed.outputFilePath, result.text, "utf8");
38886
+ await writeFile6(parsed.outputFilePath, result.text, "utf8");
38164
38887
  } else {
38165
38888
  renderOutput(result.text);
38166
38889
  }
@@ -38376,7 +39099,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar
38376
39099
  if (error51 instanceof RenderedCommandError) {
38377
39100
  process.exit(1);
38378
39101
  }
38379
- renderError(error51 instanceof Error ? error51 : String(error51));
39102
+ renderError(redactError(error51));
38380
39103
  process.exit(1);
38381
39104
  });
38382
39105
  }