@phren/cli 0.3.74 → 0.3.76

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.
@@ -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.76" : "0.0.0";
39525
39525
  PACKAGE_JSON = readPackageJson();
39526
39526
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
39527
39527
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -42184,6 +42184,7 @@ var init_registry = __esm({
42184
42184
  "bridge serve",
42185
42185
  "bridge ssh",
42186
42186
  "pair",
42187
+ "unpair",
42187
42188
  "bridge fanouts archive",
42188
42189
  "bridge accounts",
42189
42190
  "bridge askpass",
@@ -42253,6 +42254,7 @@ var init_registry = __esm({
42253
42254
  ]),
42254
42255
  ...routes("POST", [
42255
42256
  "/v1/push/register",
42257
+ "/v1/push/forget",
42256
42258
  "/v1/push/answer",
42257
42259
  "/v1/push/target",
42258
42260
  "/v1/push/presence",
@@ -42584,6 +42586,17 @@ var init_runtime = __esm({
42584
42586
  }
42585
42587
  });
42586
42588
 
42589
+ // src/bridge/git-dir-name.ts
42590
+ function isGitDirName(part) {
42591
+ const name2 = part.replace(/[‌-‏‪-‮-]/g, "").replace(/[. ]+$/, "").toLowerCase();
42592
+ return name2 === ".git" || name2 === "git~1";
42593
+ }
42594
+ var init_git_dir_name = __esm({
42595
+ "src/bridge/git-dir-name.ts"() {
42596
+ "use strict";
42597
+ }
42598
+ });
42599
+
42587
42600
  // src/bridge/memory-store.ts
42588
42601
  import { execFile as execFile6, spawn as spawn3 } from "node:child_process";
42589
42602
  import { createHash as createHash15 } from "node:crypto";
@@ -42747,7 +42760,7 @@ function catFile(store, mode, shas) {
42747
42760
  }
42748
42761
  async function storeFile(store, relative6) {
42749
42762
  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)) {
42763
+ 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
42764
  throw new BridgeError(400, "Invalid store path.");
42752
42765
  }
42753
42766
  const root = await realpath7(store);
@@ -42823,6 +42836,7 @@ var init_memory_store = __esm({
42823
42836
  "use strict";
42824
42837
  init_zod();
42825
42838
  init_locks();
42839
+ init_git_dir_name();
42826
42840
  init_protocol();
42827
42841
  exec5 = promisify5(execFile6);
42828
42842
  SHA = /^[0-9a-f]{40}$/;
@@ -43666,8 +43680,12 @@ function runtimeSessionsDir(phrenPath) {
43666
43680
  fs30.mkdirSync(dir, { recursive: true });
43667
43681
  return dir;
43668
43682
  }
43669
- function sessionFileForId(phrenPath, sessionId2) {
43670
- return path56.join(runtimeSessionsDir(phrenPath), `session-${sessionId2}.json`);
43683
+ function isSessionId(value2) {
43684
+ return typeof value2 === "string" && SESSION_ID.test(value2);
43685
+ }
43686
+ function sessionFileForId(phrenPath, sessionId2, suffix = "") {
43687
+ if (!isSessionId(sessionId2)) throw new Error("That is not a session id.");
43688
+ return path56.join(runtimeSessionsDir(phrenPath), `session-${sessionId2}${suffix}.json`);
43671
43689
  }
43672
43690
  function readSessionStateFile(file5) {
43673
43691
  try {
@@ -43690,12 +43708,14 @@ function debugError(scope, err) {
43690
43708
  );
43691
43709
  }
43692
43710
  }
43711
+ var SESSION_ID;
43693
43712
  var init_utils2 = __esm({
43694
43713
  "src/session/utils.ts"() {
43695
43714
  "use strict";
43696
43715
  init_utils();
43697
43716
  init_phren_paths();
43698
43717
  init_phren_paths();
43718
+ SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
43699
43719
  }
43700
43720
  });
43701
43721
 
@@ -67020,12 +67040,13 @@ function browserId(value2) {
67020
67040
  if (!value2 || !BROWSER_ID.test(value2)) throw new BridgeError(400, "Invalid browser identifier.");
67021
67041
  return value2;
67022
67042
  }
67023
- var BrowserRecordings;
67043
+ var RECORDING_LIMITS, BrowserRecordings;
67024
67044
  var init_browser_recordings = __esm({
67025
67045
  "src/bridge/browser-recordings.ts"() {
67026
67046
  "use strict";
67027
67047
  init_protocol();
67028
67048
  init_browser_protocol();
67049
+ RECORDING_LIMITS = { url: 1024, title: 200, reason: 1024, navigations: 500, navigationsPerSecond: 10, pages: 100, handoffs: 500, saveEveryMs: 1e3 };
67029
67050
  BrowserRecordings = class {
67030
67051
  constructor(root) {
67031
67052
  this.root = root;
@@ -67041,6 +67062,31 @@ var init_browser_recordings = __esm({
67041
67062
  fs47.writeFileSync(path109.join(dir, "meta.tmp"), JSON.stringify(meta3), { mode: 384 });
67042
67063
  fs47.renameSync(path109.join(dir, "meta.tmp"), path109.join(dir, "meta.json"));
67043
67064
  }
67065
+ /** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
67066
+ saveSoon(state) {
67067
+ const wait = state.savedAt + RECORDING_LIMITS.saveEveryMs - Date.now();
67068
+ if (wait <= 0) {
67069
+ this.saveNow(state);
67070
+ return;
67071
+ }
67072
+ state.timer ??= setTimeout(() => {
67073
+ state.timer = void 0;
67074
+ if (this.active.get(state.meta.id) === state) try {
67075
+ this.saveNow(state);
67076
+ } catch {
67077
+ }
67078
+ }, wait).unref();
67079
+ }
67080
+ saveNow(state) {
67081
+ clearTimeout(state.timer);
67082
+ state.timer = void 0;
67083
+ this.save(state.meta);
67084
+ state.savedAt = Date.now();
67085
+ }
67086
+ forget(id3) {
67087
+ clearTimeout(this.active.get(id3)?.timer);
67088
+ this.active.delete(id3);
67089
+ }
67044
67090
  start(hello, now = Date.now()) {
67045
67091
  const dir = this.dir(hello.browserId);
67046
67092
  fs47.mkdirSync(dir, { mode: 448 });
@@ -67048,20 +67094,32 @@ var init_browser_recordings = __esm({
67048
67094
  fs47.writeFileSync(path109.join(dir, "index.jsonl"), "", { mode: 384 });
67049
67095
  const meta3 = { id: hello.browserId, browserId: hello.browserId, session: hello.session, cwd: hello.cwd, engine: hello.engine, headless: hello.headless, startedAt: now, endedAt: null, frames: 0, bytes: 0, pages: [], navigations: [], handoffs: [] };
67050
67096
  this.save(meta3);
67051
- this.active.set(meta3.id, { meta: meta3, last: /* @__PURE__ */ new Map() });
67097
+ this.active.set(meta3.id, { meta: meta3, last: /* @__PURE__ */ new Map(), savedAt: Date.now(), second: 0, inSecond: 0 });
67052
67098
  }
67053
67099
  page(page, now = Date.now()) {
67054
67100
  const state = this.active.get(page.browserId);
67055
67101
  if (!state) return;
67056
- const nav = { t: now, pageId: page.pageId, url: page.url, title: page.title };
67102
+ const nav = { t: now, pageId: page.pageId, url: page.url.slice(0, RECORDING_LIMITS.url), title: page.title.slice(0, RECORDING_LIMITS.title) };
67057
67103
  const previous = state.meta.navigations.filter((n) => n.pageId === page.pageId).at(-1);
67058
- if (previous?.url === page.url && previous.title === page.title) return;
67104
+ if (previous?.url === nav.url && previous.title === nav.title) return;
67059
67105
  const existing = state.meta.pages.find((p) => p.pageId === page.pageId);
67060
67106
  if (existing) Object.assign(existing, { url: nav.url, title: nav.title });
67061
- else state.meta.pages.push({ ...nav });
67062
- if (previous?.url === page.url && !previous.title) previous.title = page.title;
67063
- else state.meta.navigations.push(nav);
67064
- this.save(state.meta);
67107
+ else if (state.meta.pages.length < RECORDING_LIMITS.pages) state.meta.pages.push({ ...nav });
67108
+ else return;
67109
+ if (previous?.url === nav.url && !previous.title) previous.title = nav.title;
67110
+ else {
67111
+ const second = Math.floor(now / 1e3);
67112
+ if (state.second !== second) {
67113
+ state.second = second;
67114
+ state.inSecond = 0;
67115
+ }
67116
+ if (state.meta.navigations.length >= RECORDING_LIMITS.navigations || ++state.inSecond > RECORDING_LIMITS.navigationsPerSecond) {
67117
+ this.saveSoon(state);
67118
+ return;
67119
+ }
67120
+ state.meta.navigations.push(nav);
67121
+ }
67122
+ this.saveNow(state);
67065
67123
  }
67066
67124
  frame(info, jpeg) {
67067
67125
  const state = this.active.get(info.browserId);
@@ -67076,20 +67134,21 @@ var init_browser_recordings = __esm({
67076
67134
  state.meta.bytes += jpeg.length;
67077
67135
  state.meta.frames++;
67078
67136
  state.last.set(info.pageId, { t: info.t, jpeg });
67079
- this.save(state.meta);
67137
+ this.saveSoon(state);
67080
67138
  }
67081
67139
  handoff(id3, kind, reason3) {
67082
67140
  const state = this.active.get(id3);
67083
67141
  if (!state) return;
67084
- state.meta.handoffs.push({ t: Date.now(), kind, ...reason3 ? { reason: reason3 } : {} });
67085
- this.save(state.meta);
67142
+ if (state.meta.handoffs.length >= RECORDING_LIMITS.handoffs) return;
67143
+ state.meta.handoffs.push({ t: Date.now(), kind, ...reason3 ? { reason: reason3.slice(0, RECORDING_LIMITS.reason) } : {} });
67144
+ this.saveNow(state);
67086
67145
  }
67087
67146
  end(id3, now = Date.now()) {
67088
67147
  const state = this.active.get(id3);
67089
67148
  if (!state) return;
67090
67149
  state.meta.endedAt = now;
67091
- this.save(state.meta);
67092
- this.active.delete(id3);
67150
+ this.saveNow(state);
67151
+ this.forget(id3);
67093
67152
  }
67094
67153
  list() {
67095
67154
  return fs47.readdirSync(this.root).filter((id3) => BROWSER_ID.test(id3)).flatMap((id3) => {
@@ -67103,7 +67162,17 @@ var init_browser_recordings = __esm({
67103
67162
  index(id3) {
67104
67163
  const dir = this.dir(id3);
67105
67164
  try {
67106
- return { meta: JSON.parse(fs47.readFileSync(path109.join(dir, "meta.json"), "utf8")), frames: fs47.readFileSync(path109.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) };
67165
+ return {
67166
+ meta: JSON.parse(fs47.readFileSync(path109.join(dir, "meta.json"), "utf8")),
67167
+ // A crash during an append leaves a torn last line; the complete rows before it still play.
67168
+ frames: fs47.readFileSync(path109.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).flatMap((line) => {
67169
+ try {
67170
+ return [JSON.parse(line)];
67171
+ } catch {
67172
+ return [];
67173
+ }
67174
+ })
67175
+ };
67107
67176
  } catch {
67108
67177
  throw new BridgeError(404, "Recording not found.");
67109
67178
  }
@@ -67128,6 +67197,12 @@ var init_browser_recordings = __esm({
67128
67197
  /** Recover archives left open by a Hook crash before accepting new producers. */
67129
67198
  recover(now = Date.now()) {
67130
67199
  for (const meta3 of this.list()) if (meta3.endedAt === null && !this.active.has(meta3.id)) {
67200
+ try {
67201
+ const frames = this.index(meta3.id).frames, final = frames.at(-1);
67202
+ meta3.frames = frames.length;
67203
+ meta3.bytes = final ? final.offset + final.length : 0;
67204
+ } catch {
67205
+ }
67131
67206
  meta3.endedAt = now;
67132
67207
  this.save(meta3);
67133
67208
  }
@@ -67138,7 +67213,7 @@ var init_browser_recordings = __esm({
67138
67213
  let total = [...sizes.values()].reduce((a, b) => a + b, 0);
67139
67214
  for (const meta3 of all.reverse()) {
67140
67215
  if (now - meta3.startedAt >= 864e5 || total > budget) {
67141
- this.active.delete(meta3.id);
67216
+ this.forget(meta3.id);
67142
67217
  this.remove(meta3.id);
67143
67218
  total -= sizes.get(meta3.id) ?? 0;
67144
67219
  }
@@ -67153,13 +67228,14 @@ import { EventEmitter as EventEmitter2 } from "node:events";
67153
67228
  import * as fs48 from "node:fs/promises";
67154
67229
  import { createServer as createServer2, connect as connect3 } from "node:net";
67155
67230
  import path110 from "node:path";
67156
- var MAX_INPUT_BACKLOG, BrowserRegistry;
67231
+ var MAX_PAGES, MAX_INPUT_BACKLOG, BrowserRegistry;
67157
67232
  var init_browser_registry = __esm({
67158
67233
  "src/bridge/browser-registry.ts"() {
67159
67234
  "use strict";
67160
67235
  init_browser_protocol();
67161
67236
  init_browser_socket();
67162
67237
  init_browser_recordings();
67238
+ MAX_PAGES = 200;
67163
67239
  MAX_INPUT_BACKLOG = 1024 * 1024;
67164
67240
  BrowserRegistry = class extends EventEmitter2 {
67165
67241
  constructor(root) {
@@ -67202,6 +67278,11 @@ var init_browser_registry = __esm({
67202
67278
  let page = browser.pages.find((page2) => page2.id === p.pageId);
67203
67279
  if (page && !page.live) throw new Error("Closed page");
67204
67280
  if (!page) {
67281
+ while (browser.pages.length >= MAX_PAGES) {
67282
+ const closed = browser.pages.findIndex((page2) => !page2.live);
67283
+ if (closed < 0) throw new Error("Too many pages");
67284
+ browser.pages.splice(closed, 1);
67285
+ }
67205
67286
  page = { id: p.pageId, url: p.url, title: p.title, width: p.width, height: p.height, live: true };
67206
67287
  browser.pages.push(page);
67207
67288
  }
@@ -72475,8 +72556,20 @@ var init_push = __esm({
72475
72556
  devices = [];
72476
72557
  sender;
72477
72558
  devicesFile = path122.join(bridgeRoot(), "push-devices.json");
72559
+ /** Loading, registering, forgetting and dropping a gone phone each read or
72560
+ * write the list and its file; one at a time, so an older write never lands
72561
+ * over a newer one and a load never brings back what was just forgotten. */
72562
+ changes = Promise.resolve();
72563
+ change(work) {
72564
+ const next = this.changes.then(work, work);
72565
+ this.changes = next.catch(() => {
72566
+ });
72567
+ return next;
72568
+ }
72478
72569
  async start() {
72479
- this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
72570
+ await this.change(async () => {
72571
+ this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
72572
+ });
72480
72573
  const configFile = process.env.PHREN_APNS_CONFIG || path122.join(bridgeRoot(), "apns.json");
72481
72574
  const config4 = await secureJSON(configFile, configSchema3);
72482
72575
  if (!config4) return;
@@ -72502,16 +72595,31 @@ var init_push = __esm({
72502
72595
  };
72503
72596
  }
72504
72597
  async register(value2) {
72505
- this.devices = upsertPushDevice(this.devices, value2);
72506
- await atomic(this.devicesFile, JSON.stringify(this.devices));
72598
+ await this.change(async () => {
72599
+ this.devices = upsertPushDevice(this.devices, value2);
72600
+ await atomic(this.devicesFile, JSON.stringify(this.devices));
72601
+ });
72602
+ }
72603
+ /** Drop every registration; returns how many went. Registrations carry no
72604
+ * SSH key, so removing a phone cannot pick out its own: all go, and the
72605
+ * phones still paired register again the next time Phren renews (hourly, on open). */
72606
+ async forgetAll() {
72607
+ return this.change(async () => {
72608
+ const removed = this.devices.length;
72609
+ this.devices = [];
72610
+ await atomic(this.devicesFile, JSON.stringify(this.devices));
72611
+ return removed;
72612
+ });
72507
72613
  }
72508
72614
  /** One phone: the relay when it registered through one, otherwise direct. */
72509
72615
  async send(device, payload, headers) {
72510
72616
  if (device.relay) {
72511
72617
  const result = await sendThroughRelay(device.relay, payload, headers);
72512
72618
  if (result === "gone") {
72513
- this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
72514
- await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => {
72619
+ await this.change(async () => {
72620
+ this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
72621
+ await atomic(this.devicesFile, JSON.stringify(this.devices));
72622
+ }).catch(() => {
72515
72623
  });
72516
72624
  }
72517
72625
  return result === "sent";
@@ -76952,7 +77060,7 @@ function rangeInteger(value2, fallback2) {
76952
77060
  return Number(value2);
76953
77061
  }
76954
77062
  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.");
77063
+ 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
77064
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > MAX_FILE_RANGE) {
76957
77065
  throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
76958
77066
  }
@@ -77008,6 +77116,7 @@ var MAX_FILE_RANGE, types;
77008
77116
  var init_file_range = __esm({
77009
77117
  "src/bridge/file-range.ts"() {
77010
77118
  "use strict";
77119
+ init_git_dir_name();
77011
77120
  init_protocol();
77012
77121
  MAX_FILE_RANGE = 4 * 1024 * 1024;
77013
77122
  types = {
@@ -77068,7 +77177,7 @@ async function writeRepoFile(root, requested, content, expectedVersion) {
77068
77177
  return serialized3(key4, () => writeRepoFileNow(root, requested, content, expectedVersion));
77069
77178
  }
77070
77179
  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 === "")) {
77180
+ 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
77181
  throw new BridgeError(400, "Invalid file path.");
77073
77182
  }
77074
77183
  if (typeof content !== "string") throw new BridgeError(400, "Supply the file's text.");
@@ -77136,6 +77245,7 @@ var init_file_write = __esm({
77136
77245
  "src/bridge/file-write.ts"() {
77137
77246
  "use strict";
77138
77247
  init_file_range();
77248
+ init_git_dir_name();
77139
77249
  init_protocol();
77140
77250
  fileLocks = /* @__PURE__ */ new Map();
77141
77251
  }
@@ -85318,7 +85428,7 @@ import { constants as constants7 } from "node:fs";
85318
85428
  import { lstat as lstat40, open as open30, readdir as readdir26, realpath as realpath27 } from "node:fs/promises";
85319
85429
  import path160 from "node:path";
85320
85430
  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")) {
85431
+ if (relative6.length > 4096 || relative6.includes("\0") || relative6.includes("\\") || path160.isAbsolute(relative6) || relative6.split("/").some((part) => part === ".." || isGitDirName(part))) {
85322
85432
  throw new BridgeError(400, "Invalid repository path.");
85323
85433
  }
85324
85434
  const base2 = await realpath27(root);
@@ -85331,7 +85441,7 @@ async function browseFiles(root, relative6) {
85331
85441
  if (resolved !== base2 && !resolved.startsWith(base2 + path160.sep)) throw new BridgeError(403, "The path is outside this repository.");
85332
85442
  const metadata = await lstat40(resolved);
85333
85443
  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));
85444
+ 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
85445
  return {
85336
85446
  path: relative6,
85337
85447
  kind: "directory",
@@ -85362,6 +85472,7 @@ var MAX_BYTES;
85362
85472
  var init_files = __esm({
85363
85473
  "src/bridge/files.ts"() {
85364
85474
  "use strict";
85475
+ init_git_dir_name();
85365
85476
  init_protocol();
85366
85477
  MAX_BYTES = 2097152;
85367
85478
  }
@@ -85376,7 +85487,7 @@ function beneath(root, file5) {
85376
85487
  }
85377
85488
  async function resolveFilePath(root, cwd, requested) {
85378
85489
  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)) {
85490
+ 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
85491
  throw new BridgeError(400, "Invalid file path.");
85381
85492
  }
85382
85493
  const base2 = await realpath28(root), folder = await realpath28(cwd);
@@ -85409,6 +85520,7 @@ var init_file_resolve = __esm({
85409
85520
  "src/bridge/file-resolve.ts"() {
85410
85521
  "use strict";
85411
85522
  init_file_range();
85523
+ init_git_dir_name();
85412
85524
  init_protocol();
85413
85525
  }
85414
85526
  });
@@ -86015,6 +86127,7 @@ var init_artifacts = __esm({
86015
86127
  function resolveSessionFile(phrenPath, sessionId2, connectionId) {
86016
86128
  const effectiveId = sessionId2 ?? (connectionId ? _sessionMap.get(connectionId) : void 0);
86017
86129
  if (effectiveId) {
86130
+ if (!isSessionId(effectiveId)) return null;
86018
86131
  const file5 = sessionFileForId(phrenPath, effectiveId);
86019
86132
  const state = readSessionStateFile(file5);
86020
86133
  if (!state) return null;
@@ -90087,8 +90200,12 @@ function createRouteHandler(ctx) {
90087
90200
  } else if (url2.pathname === "/v1/sets/link") {
90088
90201
  result = await linkSetMember(data, request10);
90089
90202
  } else if (url2.pathname === "/v1/push/register") {
90203
+ if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner's phone registers for notifications.");
90090
90204
  await agentHooks.push.register(data);
90091
90205
  result = { ok: true, configured: agentHooks.push.status.configured };
90206
+ } else if (url2.pathname === "/v1/push/forget") {
90207
+ if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner removes notification registrations.");
90208
+ result = { ok: true, removed: await agentHooks.push.forgetAll() };
90092
90209
  } else if (url2.pathname === "/v1/sudo/answer") {
90093
90210
  if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
90094
90211
  let parsed;
@@ -92841,7 +92958,7 @@ async function main() {
92841
92958
  return askpass2(args[1]);
92842
92959
  }
92843
92960
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
92844
- return runBridge2(args, "0.3.74");
92961
+ return runBridge2(args, "0.3.76");
92845
92962
  }
92846
92963
  main().then((code) => {
92847
92964
  process.exitCode = code;
@@ -145,6 +145,11 @@ export const REGISTRY = [
145
145
  { name: "ask", usage: 'phren browser ask "<reason>" [--browser <id>] [--timeout <s>]', summary: "Wait for owner help (900 s default); Ctrl-C cancels" },
146
146
  ],
147
147
  run: async (args) => { const { runBrowser } = await import("./bridge/browser-env.js"); return runBrowser(args); } },
148
+ {
149
+ name: "unpair", topic: "setup", usage: "phren unpair [<number> | SHA256:<fingerprint> | --all | --notifications]",
150
+ summary: "List the phones paired with this computer, or remove one, end its open connections and stop its notifications",
151
+ run: async (args) => { const { runUnpair } = await import("./bridge/unpair.js"); return runUnpair(args); },
152
+ },
148
153
  {
149
154
  name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|->",
150
155
  summary: "Connect your phone with a pairing QR code, or authorize a scoped key for gitboy (gitboy-read: project memory; gitboy-write: save findings)",
@@ -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);
@@ -69,7 +69,7 @@ export const BUILTIN_MODULES = [
69
69
  tools: [],
70
70
  cliCommands: [
71
71
  "bridge", "bridge install", "bridge update", "bridge uninstall", "bridge rollback", "bridge status",
72
- "browser", "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair",
72
+ "browser", "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair", "unpair",
73
73
  "bridge fanouts archive", "bridge accounts", "bridge askpass", "canary", "computers", "computers mcp", "usage", "sudo",
74
74
  ],
75
75
  agentHooks: [
@@ -90,7 +90,7 @@ export const BUILTIN_MODULES = [
90
90
  "/v1/subagents", "/v1/subagents/transcript", "/v1/subagents/messages", "/v1/sessions/move", "/v1/sessions/moves", "/v1/sessions/move/computers", "/v1/sessions/move/availability", "/v1/sessions/move/intent", "/v1/sessions/move/launch", "/v1/dispatch/relocation", "/v1/dispatch/arrival",
91
91
  ]),
92
92
  ...routes("POST", [
93
- "/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
93
+ "/v1/push/register", "/v1/push/forget", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
94
94
  "/v1/workspaces/launch", "/v1/workspaces/create", "/v1/workspaces/focus", "/v1/workspaces/rename",
95
95
  "/v1/workspaces/close", "/v1/sessions/rename", "/v1/sessions/seen", "/v1/sessions/move", "/v1/accounts/claude/add", "/v1/accounts/claude/settings", "/v1/accounts/allowed-pools", "/v1/sessions/move/abort", "/v1/sessions/move/launch", "/v1/prompt", "/v1/prompt/status", "/v1/prompt/after-turn", "/v1/prompt/after-turn/list", "/v1/prompt/after-turn/edit", "/v1/prompt/after-turn/cancel", "/v1/prompt/queue", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
96
96
  "/v1/approvals/answer", "/v1/questions/answer", "/v1/subagents/resume", "/v1/subagents/archive-finished", "/v1/canary",
@@ -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.76",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {