@phren/cli 0.3.74 → 0.3.75

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.
@@ -1,6 +1,7 @@
1
1
  import { constants } from "node:fs";
2
2
  import { lstat, open, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { isGitDirName } from "./git-dir-name.js";
4
5
  import { BridgeError } from "./protocol.js";
5
6
  export const MAX_FILE_RANGE = 4 * 1024 * 1024;
6
7
  const types = {
@@ -32,7 +33,7 @@ export function rangeInteger(value, fallback) {
32
33
  * Reject every symlink component, matching the repository browser policy. */
33
34
  export async function readFileRange(root, requested, offset, length, expectedVersion) {
34
35
  if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested)
35
- || requested.split("/").some(part => part === ".." || part === ".git"))
36
+ || requested.split("/").some(part => part === ".." || isGitDirName(part)))
36
37
  throw new BridgeError(400, "Invalid file path.");
37
38
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > MAX_FILE_RANGE) {
38
39
  throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
@@ -1,6 +1,7 @@
1
1
  import { lstat, realpath } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { readFileRange } from "./file-range.js";
4
+ import { isGitDirName } from "./git-dir-name.js";
4
5
  import { BridgeError } from "./protocol.js";
5
6
  function beneath(root, file) {
6
7
  const relative = path.relative(root, file);
@@ -17,7 +18,7 @@ export async function resolveFilePath(root, cwd, requested) {
17
18
  requested = requested.replaceAll("\\", "/");
18
19
  if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested)
19
20
  || /^[A-Za-z]:[^/]/.test(requested)
20
- || requested.split("/").includes(".git") || path.win32.isAbsolute(requested) && !path.isAbsolute(requested)) {
21
+ || requested.split("/").some(isGitDirName) || path.win32.isAbsolute(requested) && !path.isAbsolute(requested)) {
21
22
  throw new BridgeError(400, "Invalid file path.");
22
23
  }
23
24
  const base = await realpath(root), folder = await realpath(cwd);
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
3
3
  import { lstat, open, realpath, rename, rm } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { fileVersion, MAX_FILE_RANGE } from "./file-range.js";
6
+ import { isGitDirName } from "./git-dir-name.js";
6
7
  import { BridgeError } from "./protocol.js";
7
8
  /**
8
9
  * Write one text file inside a repository root the server chose (a pane's
@@ -37,7 +38,7 @@ export async function writeRepoFile(root, requested, content, expectedVersion) {
37
38
  }
38
39
  async function writeRepoFileNow(root, requested, content, expectedVersion) {
39
40
  if (typeof requested !== "string" || !requested || requested.length > 4096 || path.isAbsolute(requested)
40
- || /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some(part => part === ".." || part.toLowerCase() === ".git" || part === "")) {
41
+ || /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some(part => part === ".." || isGitDirName(part) || part === "")) {
41
42
  throw new BridgeError(400, "Invalid file path.");
42
43
  }
43
44
  if (typeof content !== "string")
@@ -1,12 +1,13 @@
1
1
  import { constants } from "node:fs";
2
2
  import { lstat, open, readdir, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { isGitDirName } from "./git-dir-name.js";
4
5
  import { BridgeError } from "./protocol.js";
5
6
  const MAX_BYTES = 2_097_152;
6
7
  /** Read-only browsing beneath a root selected and verified by the server. */
7
8
  export async function browseFiles(root, relative) {
8
9
  if (relative.length > 4096 || relative.includes("\0") || relative.includes("\\") || path.isAbsolute(relative)
9
- || relative.split("/").some(part => part === ".." || part === ".git")) {
10
+ || relative.split("/").some(part => part === ".." || isGitDirName(part))) {
10
11
  throw new BridgeError(400, "Invalid repository path.");
11
12
  }
12
13
  const base = await realpath(root);
@@ -22,7 +23,7 @@ export async function browseFiles(root, relative) {
22
23
  const metadata = await lstat(resolved);
23
24
  if (metadata.isDirectory()) {
24
25
  const entries = (await readdir(resolved, { withFileTypes: true }))
25
- .filter(entry => entry.name !== ".git" && (entry.isDirectory() || entry.isFile()))
26
+ .filter(entry => !isGitDirName(entry.name) && (entry.isDirectory() || entry.isFile()))
26
27
  .sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
27
28
  return { path: relative, kind: "directory", truncated: entries.length > 500,
28
29
  entries: entries.slice(0, 500).map(entry => ({ name: entry.name, path: path.posix.join(relative, entry.name), kind: entry.isDirectory() ? "directory" : "file" })) };
@@ -0,0 +1,5 @@
1
+ /** A path part that names a repository's `.git` folder on some volume, not
2
+ * only on this one: any letter case, the NTFS short name, the trailing dots
3
+ * and spaces Windows drops, and the code points HFS+ ignores. Git refuses the
4
+ * same spellings in a tree for the same reason. */
5
+ export declare function isGitDirName(part: string): boolean;
@@ -0,0 +1,8 @@
1
+ /** A path part that names a repository's `.git` folder on some volume, not
2
+ * only on this one: any letter case, the NTFS short name, the trailing dots
3
+ * and spaces Windows drops, and the code points HFS+ ignores. Git refuses the
4
+ * same spellings in a tree for the same reason. */
5
+ export function isGitDirName(part) {
6
+ const name = part.replace(/[‌-‏‪-‮-]/g, "").replace(/[. ]+$/, "").toLowerCase();
7
+ return name === ".git" || name === "git~1";
8
+ }
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
  import { promisify } from "node:util";
7
7
  import { z } from "zod";
8
8
  import { withFileLock } from "../governance/locks.js";
9
+ import { isGitDirName } from "./git-dir-name.js";
9
10
  import { BridgeError, bridgeRoot } from "./protocol.js";
10
11
  // The phone reads memory from a paired computer through these routes, in the
11
12
  // same git terms its sync engine uses with GitHub: a head, a recursive tree,
@@ -198,7 +199,7 @@ function catFile(store, mode, shas) {
198
199
  export async function storeFile(store, relative) {
199
200
  const normalized = path.posix.normalize(relative);
200
201
  if (!relative || relative !== normalized || normalized.startsWith("../") || normalized === ".." || path.posix.isAbsolute(normalized)
201
- || normalized.split("/").some(part => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
202
+ || normalized.split("/").some(part => isGitDirName(part) || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
202
203
  throw new BridgeError(400, "Invalid store path.");
203
204
  }
204
205
  const root = await realpath(store);
@@ -4,6 +4,16 @@ export declare function newPairingCode(): string;
4
4
  /** Codes are typed as ABC-234 or abc234; both mean the same code. */
5
5
  export declare function normalizeCode(code: string): string;
6
6
  export declare function pairingProof(code: string, label: "phone" | "computer", ...parts: string[]): string;
7
+ /**
8
+ * The secret only the QR code and the phren://pair link carry: 128 random
9
+ * bits, never typed and never sent. The six-character code can be recovered
10
+ * from one captured request (about 30 bits, checked offline against its
11
+ * proof), so a proof made with the code alone always needs the person at the
12
+ * computer; a proof made with this secret shows the phone read the screen.
13
+ */
14
+ export declare function newScanSecret(): string;
15
+ /** The proof of a phone that scanned: keyed by the code and the scan secret together. */
16
+ export declare function scanProof(code: string, secret: string, label: "phone" | "computer", ...parts: string[]): string;
7
17
  /**
8
18
  * The short check a phone that typed the code shows to confirm: the first
9
19
  * eight characters of the host key fingerprint, as "abcd efgh". A typed code
@@ -26,6 +36,8 @@ export interface PairingOffer {
26
36
  fingerprint?: string;
27
37
  code: string;
28
38
  name: string;
39
+ /** The scan secret (`k`); see `newScanSecret`. */
40
+ secret?: string;
29
41
  }
30
42
  /** The QR payload; the phone opens phren://pair links from the camera too. */
31
43
  export declare function pairingURL(offer: PairingOffer): string;
@@ -55,11 +67,13 @@ export declare function startPairing(options: {
55
67
  port?: number;
56
68
  timeoutMs?: number;
57
69
  sshDirectory?: string;
70
+ /** The secret in the QR code. A phone that proves it is authorized at once; without one, no phone is. */
71
+ scanSecret?: string;
58
72
  /**
59
- * Asked before a phone that typed the code is authorized: a typed code can
60
- * be cracked from a captured request, so the person at the computer allows
61
- * the phone whose key check matches the one it shows. Without it, typed
62
- * pairing is refused.
73
+ * Asked before a phone that proved only the code is authorized: the code
74
+ * can be cracked from a captured request, so the person at the computer
75
+ * allows the phone whose key check matches the one it shows. Without it,
76
+ * typed pairing is refused.
63
77
  */
64
78
  approve?: (phone: PairingApproval) => Promise<boolean>;
65
79
  }): Promise<PairingSession>;
@@ -1,5 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
- import { createHash, createHmac, randomInt, timingSafeEqual } from "node:crypto";
2
+ import { createHash, createHmac, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
3
3
  import { lstat, readFile } from "node:fs/promises";
4
4
  import { createServer } from "node:http";
5
5
  import { connect } from "node:net";
@@ -13,10 +13,11 @@ import { forcedCommand, install, scopedForcedCommand, scopedGatewayPath } from "
13
13
  import { isGatewayScope, SCOPE_KEY_COMMENT } from "./scoped-gateway.js";
14
14
  import { BridgeError, bridgeRoot } from "./protocol.js";
15
15
  // `phren pair` connects a phone in one scan. The QR code carries where to
16
- // reach this computer, its SSH host key fingerprint and a one-time code. The
17
- // phone makes its own key and posts the public half here with an HMAC keyed
18
- // by the code, so the code itself never crosses the network; this computer
19
- // answers with an HMAC over its fingerprint, which lets a phone that typed
16
+ // reach this computer, its SSH host key fingerprint, a one-time code and a
17
+ // scan secret. The phone makes its own key and posts the public half here
18
+ // with an HMAC keyed by the code and the secret (a phone that typed the code
19
+ // has only the code, and waits to be allowed at the computer), so neither
20
+ // crosses the network; this computer answers with an HMAC over its fingerprint, which lets a phone that typed
20
21
  // the code by hand trust the host key too. One success, five bad proofs or
21
22
  // the time limit closes the listener.
22
23
  const exec = promisify(execFile);
@@ -33,6 +34,20 @@ export function normalizeCode(code) {
33
34
  export function pairingProof(code, label, ...parts) {
34
35
  return createHmac("sha256", `phren-pair-v1:${normalizeCode(code)}`).update([label, ...parts].join("\n")).digest("base64url");
35
36
  }
37
+ /**
38
+ * The secret only the QR code and the phren://pair link carry: 128 random
39
+ * bits, never typed and never sent. The six-character code can be recovered
40
+ * from one captured request (about 30 bits, checked offline against its
41
+ * proof), so a proof made with the code alone always needs the person at the
42
+ * computer; a proof made with this secret shows the phone read the screen.
43
+ */
44
+ export function newScanSecret() {
45
+ return randomBytes(16).toString("base64url");
46
+ }
47
+ /** The proof of a phone that scanned: keyed by the code and the scan secret together. */
48
+ export function scanProof(code, secret, label, ...parts) {
49
+ return createHmac("sha256", `phren-pair-v2:${normalizeCode(code)}:${secret}`).update([label, ...parts].join("\n")).digest("base64url");
50
+ }
36
51
  function sameProof(expected, received) {
37
52
  const a = Buffer.from(expected), b = Buffer.from(received);
38
53
  return a.length === b.length && timingSafeEqual(a, b);
@@ -98,6 +113,8 @@ export function pairingURL(offer) {
98
113
  s: String(offer.sshPort), c: offer.code, n: offer.name });
99
114
  if (offer.fingerprint)
100
115
  query.set("fp", offer.fingerprint);
116
+ if (offer.secret)
117
+ query.set("k", offer.secret);
101
118
  return `phren://pair?${query.toString()}`;
102
119
  }
103
120
  const request = z.object({
@@ -143,13 +160,21 @@ export async function startPairing(options) {
143
160
  }
144
161
  const input = request.parse(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
145
162
  const publicKey = publicComputerKey(input.publicKey);
146
- if (!sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
163
+ const scanned = options.scanSecret !== undefined
164
+ && sameProof(scanProof(options.code, options.scanSecret, "phone", publicKey), input.proof);
165
+ if (!scanned && !sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
147
166
  failures++;
148
167
  if (failures >= MAX_FAILURES)
149
168
  setImmediate(() => finish(new Error("Too many wrong pairing codes; pairing closed. Run phren pair again.")));
150
169
  throw new BridgeError(403, "That pairing code doesn't match this computer.");
151
170
  }
152
- if (input.typed) {
171
+ if (!scanned) {
172
+ // The code alone never authorizes a key, whatever the request says
173
+ // about itself: `typed` only tells a phone that will wait for the
174
+ // answer from an app that scanned before the scan secret existed and
175
+ // gives up in seconds.
176
+ if (!input.typed)
177
+ throw new BridgeError(403, "This version of the Phren app can't pair by scanning with this computer. Update the app, or choose Enter code and type the code.");
153
178
  // One question at a time, each bound to its own phone: a single answer
154
179
  // never allows two keys.
155
180
  const ask = approvals.then(() => finished || claimed || incoming.socket.destroyed ? false
@@ -180,7 +205,8 @@ export async function startPairing(options) {
180
205
  }
181
206
  reply(response, 200, {
182
207
  v: 1, name: options.name, user: options.user, sshPort: options.sshPort, fingerprint: options.fingerprint ?? null,
183
- proof: pairingProof(options.code, "computer", options.fingerprint ?? "", publicKey),
208
+ proof: scanned ? scanProof(options.code, options.scanSecret, "computer", options.fingerprint ?? "", publicKey)
209
+ : pairingProof(options.code, "computer", options.fingerprint ?? "", publicKey),
184
210
  });
185
211
  setImmediate(() => finish(undefined, { device: input.device, name: input.name, publicKey }));
186
212
  }
@@ -357,7 +383,7 @@ export async function runPair(args, version) {
357
383
  const sshPort = 22;
358
384
  if (!await sshListening(sshPort))
359
385
  console.log(`\n⚠ SSH isn't answering on this computer. ${sshHint()}\n Pairing can finish now; the phone connects once SSH is on.`);
360
- const code = newPairingCode();
386
+ const code = newPairingCode(), scanSecret = newScanSecret();
361
387
  const name = await computerDisplayName(), user = userInfo().username, fingerprint = await hostFingerprint();
362
388
  const hosts = await pairingHosts();
363
389
  if (!hosts.length) {
@@ -365,10 +391,10 @@ export async function runPair(args, version) {
365
391
  return 1;
366
392
  }
367
393
  let cancelPairing = () => { };
368
- const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000,
394
+ const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000, scanSecret,
369
395
  approve: phone => askToAllow(phone, () => cancelPairing()) });
370
396
  cancelPairing = () => session.close();
371
- const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name });
397
+ const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name, secret: scanSecret });
372
398
  const { renderUnicodeCompact } = await import("uqr");
373
399
  console.log(`\nConnect your phone to ${name}`);
374
400
  console.log(" In the Phren app: Agents → Add computer → Scan pairing code\n");
@@ -39521,7 +39521,7 @@ var init_package_metadata = __esm({
39521
39521
  __dirname = path41.dirname(fileURLToPath3(import.meta.url));
39522
39522
  ROOT = path41.join(__dirname, "..");
39523
39523
  PACKAGE_JSON_PATH = path41.join(ROOT, "package.json");
39524
- BUNDLED_VERSION = true ? "0.3.74" : "0.0.0";
39524
+ BUNDLED_VERSION = true ? "0.3.75" : "0.0.0";
39525
39525
  PACKAGE_JSON = readPackageJson();
39526
39526
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
39527
39527
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -42584,6 +42584,17 @@ var init_runtime = __esm({
42584
42584
  }
42585
42585
  });
42586
42586
 
42587
+ // src/bridge/git-dir-name.ts
42588
+ function isGitDirName(part) {
42589
+ const name2 = part.replace(/[‌-‏‪-‮-]/g, "").replace(/[. ]+$/, "").toLowerCase();
42590
+ return name2 === ".git" || name2 === "git~1";
42591
+ }
42592
+ var init_git_dir_name = __esm({
42593
+ "src/bridge/git-dir-name.ts"() {
42594
+ "use strict";
42595
+ }
42596
+ });
42597
+
42587
42598
  // src/bridge/memory-store.ts
42588
42599
  import { execFile as execFile6, spawn as spawn3 } from "node:child_process";
42589
42600
  import { createHash as createHash15 } from "node:crypto";
@@ -42747,7 +42758,7 @@ function catFile(store, mode, shas) {
42747
42758
  }
42748
42759
  async function storeFile(store, relative6) {
42749
42760
  const normalized = path51.posix.normalize(relative6);
42750
- if (!relative6 || relative6 !== normalized || normalized.startsWith("../") || normalized === ".." || path51.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
42761
+ if (!relative6 || relative6 !== normalized || normalized.startsWith("../") || normalized === ".." || path51.posix.isAbsolute(normalized) || normalized.split("/").some((part) => isGitDirName(part) || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
42751
42762
  throw new BridgeError(400, "Invalid store path.");
42752
42763
  }
42753
42764
  const root = await realpath7(store);
@@ -42823,6 +42834,7 @@ var init_memory_store = __esm({
42823
42834
  "use strict";
42824
42835
  init_zod();
42825
42836
  init_locks();
42837
+ init_git_dir_name();
42826
42838
  init_protocol();
42827
42839
  exec5 = promisify5(execFile6);
42828
42840
  SHA = /^[0-9a-f]{40}$/;
@@ -43666,8 +43678,12 @@ function runtimeSessionsDir(phrenPath) {
43666
43678
  fs30.mkdirSync(dir, { recursive: true });
43667
43679
  return dir;
43668
43680
  }
43669
- function sessionFileForId(phrenPath, sessionId2) {
43670
- return path56.join(runtimeSessionsDir(phrenPath), `session-${sessionId2}.json`);
43681
+ function isSessionId(value2) {
43682
+ return typeof value2 === "string" && SESSION_ID.test(value2);
43683
+ }
43684
+ function sessionFileForId(phrenPath, sessionId2, suffix = "") {
43685
+ if (!isSessionId(sessionId2)) throw new Error("That is not a session id.");
43686
+ return path56.join(runtimeSessionsDir(phrenPath), `session-${sessionId2}${suffix}.json`);
43671
43687
  }
43672
43688
  function readSessionStateFile(file5) {
43673
43689
  try {
@@ -43690,12 +43706,14 @@ function debugError(scope, err) {
43690
43706
  );
43691
43707
  }
43692
43708
  }
43709
+ var SESSION_ID;
43693
43710
  var init_utils2 = __esm({
43694
43711
  "src/session/utils.ts"() {
43695
43712
  "use strict";
43696
43713
  init_utils();
43697
43714
  init_phren_paths();
43698
43715
  init_phren_paths();
43716
+ SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
43699
43717
  }
43700
43718
  });
43701
43719
 
@@ -76952,7 +76970,7 @@ function rangeInteger(value2, fallback2) {
76952
76970
  return Number(value2);
76953
76971
  }
76954
76972
  async function readFileRange(root, requested, offset, length, expectedVersion) {
76955
- if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some((part) => part === ".." || part === ".git")) throw new BridgeError(400, "Invalid file path.");
76973
+ if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some((part) => part === ".." || isGitDirName(part))) throw new BridgeError(400, "Invalid file path.");
76956
76974
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > MAX_FILE_RANGE) {
76957
76975
  throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
76958
76976
  }
@@ -77008,6 +77026,7 @@ var MAX_FILE_RANGE, types;
77008
77026
  var init_file_range = __esm({
77009
77027
  "src/bridge/file-range.ts"() {
77010
77028
  "use strict";
77029
+ init_git_dir_name();
77011
77030
  init_protocol();
77012
77031
  MAX_FILE_RANGE = 4 * 1024 * 1024;
77013
77032
  types = {
@@ -77068,7 +77087,7 @@ async function writeRepoFile(root, requested, content, expectedVersion) {
77068
77087
  return serialized3(key4, () => writeRepoFileNow(root, requested, content, expectedVersion));
77069
77088
  }
77070
77089
  async function writeRepoFileNow(root, requested, content, expectedVersion) {
77071
- if (typeof requested !== "string" || !requested || requested.length > 4096 || path132.isAbsolute(requested) || /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some((part) => part === ".." || part.toLowerCase() === ".git" || part === "")) {
77090
+ if (typeof requested !== "string" || !requested || requested.length > 4096 || path132.isAbsolute(requested) || /[\x00-\x1f\x7f\\]/.test(requested) || requested.split("/").some((part) => part === ".." || isGitDirName(part) || part === "")) {
77072
77091
  throw new BridgeError(400, "Invalid file path.");
77073
77092
  }
77074
77093
  if (typeof content !== "string") throw new BridgeError(400, "Supply the file's text.");
@@ -77136,6 +77155,7 @@ var init_file_write = __esm({
77136
77155
  "src/bridge/file-write.ts"() {
77137
77156
  "use strict";
77138
77157
  init_file_range();
77158
+ init_git_dir_name();
77139
77159
  init_protocol();
77140
77160
  fileLocks = /* @__PURE__ */ new Map();
77141
77161
  }
@@ -85318,7 +85338,7 @@ import { constants as constants7 } from "node:fs";
85318
85338
  import { lstat as lstat40, open as open30, readdir as readdir26, realpath as realpath27 } from "node:fs/promises";
85319
85339
  import path160 from "node:path";
85320
85340
  async function browseFiles(root, relative6) {
85321
- if (relative6.length > 4096 || relative6.includes("\0") || relative6.includes("\\") || path160.isAbsolute(relative6) || relative6.split("/").some((part) => part === ".." || part === ".git")) {
85341
+ if (relative6.length > 4096 || relative6.includes("\0") || relative6.includes("\\") || path160.isAbsolute(relative6) || relative6.split("/").some((part) => part === ".." || isGitDirName(part))) {
85322
85342
  throw new BridgeError(400, "Invalid repository path.");
85323
85343
  }
85324
85344
  const base2 = await realpath27(root);
@@ -85331,7 +85351,7 @@ async function browseFiles(root, relative6) {
85331
85351
  if (resolved !== base2 && !resolved.startsWith(base2 + path160.sep)) throw new BridgeError(403, "The path is outside this repository.");
85332
85352
  const metadata = await lstat40(resolved);
85333
85353
  if (metadata.isDirectory()) {
85334
- const entries2 = (await readdir26(resolved, { withFileTypes: true })).filter((entry2) => entry2.name !== ".git" && (entry2.isDirectory() || entry2.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
85354
+ const entries2 = (await readdir26(resolved, { withFileTypes: true })).filter((entry2) => !isGitDirName(entry2.name) && (entry2.isDirectory() || entry2.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
85335
85355
  return {
85336
85356
  path: relative6,
85337
85357
  kind: "directory",
@@ -85362,6 +85382,7 @@ var MAX_BYTES;
85362
85382
  var init_files = __esm({
85363
85383
  "src/bridge/files.ts"() {
85364
85384
  "use strict";
85385
+ init_git_dir_name();
85365
85386
  init_protocol();
85366
85387
  MAX_BYTES = 2097152;
85367
85388
  }
@@ -85376,7 +85397,7 @@ function beneath(root, file5) {
85376
85397
  }
85377
85398
  async function resolveFilePath(root, cwd, requested) {
85378
85399
  if (process.platform === "win32") requested = requested.replaceAll("\\", "/");
85379
- if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || /^[A-Za-z]:[^/]/.test(requested) || requested.split("/").includes(".git") || path161.win32.isAbsolute(requested) && !path161.isAbsolute(requested)) {
85400
+ if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || /^[A-Za-z]:[^/]/.test(requested) || requested.split("/").some(isGitDirName) || path161.win32.isAbsolute(requested) && !path161.isAbsolute(requested)) {
85380
85401
  throw new BridgeError(400, "Invalid file path.");
85381
85402
  }
85382
85403
  const base2 = await realpath28(root), folder = await realpath28(cwd);
@@ -85409,6 +85430,7 @@ var init_file_resolve = __esm({
85409
85430
  "src/bridge/file-resolve.ts"() {
85410
85431
  "use strict";
85411
85432
  init_file_range();
85433
+ init_git_dir_name();
85412
85434
  init_protocol();
85413
85435
  }
85414
85436
  });
@@ -86015,6 +86037,7 @@ var init_artifacts = __esm({
86015
86037
  function resolveSessionFile(phrenPath, sessionId2, connectionId) {
86016
86038
  const effectiveId = sessionId2 ?? (connectionId ? _sessionMap.get(connectionId) : void 0);
86017
86039
  if (effectiveId) {
86040
+ if (!isSessionId(effectiveId)) return null;
86018
86041
  const file5 = sessionFileForId(phrenPath, effectiveId);
86019
86042
  const state = readSessionStateFile(file5);
86020
86043
  if (!state) return null;
@@ -92841,7 +92864,7 @@ async function main() {
92841
92864
  return askpass2(args[1]);
92842
92865
  }
92843
92866
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
92844
- return runBridge2(args, "0.3.74");
92867
+ return runBridge2(args, "0.3.75");
92845
92868
  }
92846
92869
  main().then((code) => {
92847
92870
  process.exitCode = code;
@@ -149,6 +149,10 @@ export declare function getRetentionPolicy(phrenPath: string, projectName?: stri
149
149
  export declare function updateRetentionPolicy(phrenPath: string, patch: RetentionPolicyPatch): PhrenResult<RetentionPolicy>;
150
150
  export declare function getWorkflowPolicy(phrenPath: string, projectName?: string): WorkflowPolicy;
151
151
  export declare function updateWorkflowPolicy(phrenPath: string, patch: Partial<WorkflowPolicy>): PhrenResult<WorkflowPolicy>;
152
+ /** An index glob is matched from each project's folder and stays inside it:
153
+ * relative, with no `..` and no backslash (an escape in a glob, a separator
154
+ * on Windows). Blank entries are not globs. */
155
+ export declare function isProjectGlob(glob: unknown): glob is string;
152
156
  export declare function getIndexPolicy(phrenPath: string): IndexPolicy;
153
157
  export declare function updateIndexPolicy(phrenPath: string, patch: Partial<IndexPolicy>): PhrenResult<IndexPolicy>;
154
158
  export declare function getRuntimeHealth(phrenPath: string): RuntimeHealth;
@@ -584,10 +584,18 @@ function patchedWorkflowPolicy(current, patch) {
584
584
  };
585
585
  return next;
586
586
  }
587
+ /** An index glob is matched from each project's folder and stays inside it:
588
+ * relative, with no `..` and no backslash (an escape in a glob, a separator
589
+ * on Windows). Blank entries are not globs. */
590
+ export function isProjectGlob(glob) {
591
+ return typeof glob === "string" && glob.trim().length > 0
592
+ && !/^([/~]|[A-Za-z]:)/.test(glob.trim()) && !glob.includes("..") && !glob.includes("\\");
593
+ }
587
594
  export function getIndexPolicy(phrenPath) {
588
595
  const parsed = readJsonFile(govFile(phrenPath, "index-policy"), {});
589
596
  const merged = withDefaults(parsed, DEFAULT_INDEX_POLICY);
590
- merged.includeGlobs = merged.includeGlobs.filter((glob) => typeof glob === "string" && glob.trim().length > 0);
597
+ // The file syncs with the store, so what it holds is checked on every read.
598
+ merged.includeGlobs = merged.includeGlobs.filter(isProjectGlob);
591
599
  merged.excludeGlobs = merged.excludeGlobs.filter((glob) => typeof glob === "string" && glob.trim().length > 0);
592
600
  if (!merged.includeGlobs.length)
593
601
  merged.includeGlobs = DEFAULT_INDEX_POLICY.includeGlobs;
@@ -596,6 +604,11 @@ export function getIndexPolicy(phrenPath) {
596
604
  return merged;
597
605
  }
598
606
  export function updateIndexPolicy(phrenPath, patch) {
607
+ const outside = Array.isArray(patch.includeGlobs)
608
+ ? patch.includeGlobs.filter(glob => typeof glob === "string" && glob.trim().length > 0 && !isProjectGlob(glob)) : [];
609
+ if (outside.length) {
610
+ return phrenErr(`Index globs are matched inside each project folder: use a relative pattern with no ".." or backslash. Not accepted: ${outside.join(", ")}`, PhrenError.VALIDATION_ERROR);
611
+ }
599
612
  const file = govFile(phrenPath, "index-policy");
600
613
  const next = withFileLock(file, () => {
601
614
  const merged = patchedIndexPolicy(getIndexPolicy(phrenPath), patch);
@@ -8,7 +8,7 @@ function normalizeSummary(summary) {
8
8
  return trimmed ? trimmed : undefined;
9
9
  }
10
10
  function sessionMessagesFileForId(phrenPath, sessionId) {
11
- return path.join(runtimeSessionsDir(phrenPath), `session-${sessionId}-messages.json`);
11
+ return sessionFileForId(phrenPath, sessionId, "-messages");
12
12
  }
13
13
  function inferProjectForSession(phrenPath, sessionId) {
14
14
  return readSessionState(phrenPath, sessionId)?.project;
@@ -19,7 +19,10 @@ export interface SessionState {
19
19
  agentCreated?: boolean;
20
20
  }
21
21
  export declare function runtimeSessionsDir(phrenPath: string): string;
22
- export declare function sessionFileForId(phrenPath: string, sessionId: string): string;
22
+ export declare function isSessionId(value: unknown): value is string;
23
+ /** `session-<id><suffix>.json` in the sessions folder. Throws for anything
24
+ * that is not a session id; callers taking an id from outside check first. */
25
+ export declare function sessionFileForId(phrenPath: string, sessionId: string, suffix?: string): string;
23
26
  export declare function isSessionStateFileName(name: string): boolean;
24
27
  export declare function readSessionStateFile(file: string): SessionState | null;
25
28
  export declare function writeSessionStateFile(file: string, state: SessionState): void;
@@ -16,8 +16,19 @@ export function runtimeSessionsDir(phrenPath) {
16
16
  fs.mkdirSync(dir, { recursive: true });
17
17
  return dir;
18
18
  }
19
- export function sessionFileForId(phrenPath, sessionId) {
20
- return path.join(runtimeSessionsDir(phrenPath), `session-${sessionId}.json`);
19
+ /** A session id is one plain name. phren's own are UUIDs; one handed in by a
20
+ * tool call is used only in this shape, so the file it names is always
21
+ * inside the sessions folder. */
22
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
23
+ export function isSessionId(value) {
24
+ return typeof value === "string" && SESSION_ID.test(value);
25
+ }
26
+ /** `session-<id><suffix>.json` in the sessions folder. Throws for anything
27
+ * that is not a session id; callers taking an id from outside check first. */
28
+ export function sessionFileForId(phrenPath, sessionId, suffix = "") {
29
+ if (!isSessionId(sessionId))
30
+ throw new Error("That is not a session id.");
31
+ return path.join(runtimeSessionsDir(phrenPath), `session-${sessionId}${suffix}.json`);
21
32
  }
22
33
  export function isSessionStateFileName(name) {
23
34
  return name.startsWith("session-") &&
@@ -18,7 +18,7 @@ import { getActiveTaskForSession } from "../task/lifecycle.js";
18
18
  import { listTaskCheckpoints, writeTaskCheckpoint } from "../session/checkpoints.js";
19
19
  import { findMostRecentSummaryWithProject as findMostRecentSummaryRecord, writeLastSummary, } from "../session/artifacts.js";
20
20
  import { markImpactEntriesCompletedForSession } from "../finding/impact.js";
21
- import { debugError, scanSessionFiles, runtimeSessionsDir, sessionFileForId, readSessionStateFile, writeSessionStateFile, } from "../session/utils.js";
21
+ import { debugError, scanSessionFiles, runtimeSessionsDir, isSessionId, sessionFileForId, readSessionStateFile, writeSessionStateFile, } from "../session/utils.js";
22
22
  import { getRuntimeHealth } from "../governance/policy.js";
23
23
  import { getProjectSourcePath, readProjectConfig } from "../project-config.js";
24
24
  const STALE_SESSION_MS = 24 * 60 * 60 * 1000; // 24 hours
@@ -148,6 +148,9 @@ function findMostRecentSummaryWithProject(phrenPath) {
148
148
  function resolveSessionFile(phrenPath, sessionId, connectionId) {
149
149
  const effectiveId = sessionId ?? (connectionId ? _sessionMap.get(connectionId) : undefined);
150
150
  if (effectiveId) {
151
+ // An id that is not one of ours names no session.
152
+ if (!isSessionId(effectiveId))
153
+ return null;
151
154
  const file = sessionFileForId(phrenPath, effectiveId);
152
155
  const state = readSessionStateFile(file);
153
156
  if (!state)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.74",
3
+ "version": "0.3.75",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {