@phren/cli 0.3.73 → 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.
@@ -13,6 +13,7 @@ interface Row {
13
13
  checked?: boolean;
14
14
  answered: boolean;
15
15
  cursor: boolean;
16
+ wrapped?: boolean;
16
17
  }
17
18
  export interface ClaudeQuestionScreen {
18
19
  kind: "question";
@@ -32,15 +33,13 @@ export interface ClaudeReviewScreen {
32
33
  answers: {
33
34
  question: string;
34
35
  answer: string;
36
+ wrapped?: boolean;
35
37
  }[];
36
38
  }
37
39
  export type ClaudeDialogScreen = ClaudeQuestionScreen | ClaudeReviewScreen;
38
40
  /** Claude cuts a question at 2000 characters with "…" while the phone may send
39
41
  * more, so the pane's title matches when it is the question's own head. */
40
42
  export declare const sameTitle: (shown: string, asked: string) => boolean;
41
- /** Claude collapses runs of whitespace in a label, and the Hook reads only the
42
- * first line of one it wraps, so a long label matches by its head. */
43
- export declare const sameLabel: (shown: string, asked: string) => boolean;
44
43
  /** The question dialog the pane is drawing now, or undefined when the last
45
44
  * lines are not one: the last tab bar anchors it, and an active dialog ends
46
45
  * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
@@ -1,3 +1,5 @@
1
+ import { claudeFooterMode } from "./claude-footer-mode.js";
2
+ import { dialogHasClosed } from "./dialog-observation.js";
1
3
  import { joinDialogFooters } from "./terminal-dialog-text.js";
2
4
  import { BridgeError } from "./protocol.js";
3
5
  const TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
@@ -12,12 +14,6 @@ export const sameTitle = (shown, asked) => {
12
14
  return true;
13
15
  return shown.endsWith("…") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
14
16
  };
15
- /** Claude collapses runs of whitespace in a label, and the Hook reads only the
16
- * first line of one it wraps, so a long label matches by its head. */
17
- export const sameLabel = (shown, asked) => {
18
- const want = normalize(asked);
19
- return shown === want || (shown.length >= 30 && want.startsWith(shown));
20
- };
21
17
  /** Claude Code (2.1.284) draws a question that has a line break or is wider
22
18
  * than 80 columns inside a dimmed left border, "│ " before each line, on its
23
19
  * tab and in the review. The border is not part of the question. */
@@ -84,8 +80,10 @@ export function claudeQuestionDialog(text) {
84
80
  last.answer = answer[1];
85
81
  // A long question or answer wraps onto the next line.
86
82
  else if (last) {
87
- if (last.answer)
83
+ if (last.answer) {
88
84
  last.answer += " " + line;
85
+ last.wrapped = true;
86
+ }
89
87
  else
90
88
  last.question += " " + line;
91
89
  }
@@ -118,7 +116,7 @@ export function claudeQuestionDialog(text) {
118
116
  continue;
119
117
  }
120
118
  const answered = !match[3] && / ✔$/.test(match[4]);
121
- rows.push({ number, label: answered ? match[4].slice(0, -2).trim() : match[4], answered, cursor: !!match[1],
119
+ rows.push({ number, label: match[4], answered, cursor: !!match[1],
122
120
  ...(match[3] ? { checked: match[3] === "✔" } : {}) });
123
121
  }
124
122
  if (!title || !chat || cursor === undefined || rows.length < 2)
@@ -126,6 +124,18 @@ export function claudeQuestionDialog(text) {
126
124
  // The last row above "Chat about this" is the typed answer ("Type
127
125
  // something." until something is typed there).
128
126
  const other = rows.pop();
127
+ // Only option labels have a removable selection marker. Other is user
128
+ // input: preserving its raw value prevents "Teal ✔" reconciling as "Teal".
129
+ for (const row of rows)
130
+ if (row.answered)
131
+ row.label = row.label.slice(0, -2).trim();
132
+ const otherLine = body.findIndex(line => Number(ROW.exec(line)?.[2]) === other.number);
133
+ for (const line of body.slice(otherLine + 1)) {
134
+ if (NEXT.test(line) || ROW.test(line) || /^─+$/.test(line.trim()))
135
+ break;
136
+ if (line.trim())
137
+ other.wrapped = true;
138
+ }
129
139
  return { kind: "question", tabs, title, multiSelect: rows.some(row => row.checked !== undefined), options: rows, other, ...(cursor !== undefined ? { cursor } : {}) };
130
140
  }
131
141
  /** A 409 that says whether any key reached the terminal: `question-not-shown`
@@ -142,6 +152,9 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
142
152
  const from = options.from ?? 0, submit = options.submit ?? true;
143
153
  let sent = false;
144
154
  const changed = (message) => refusal(message, sent);
155
+ if (submit && (from !== 0 || answers.length !== questions.length)) {
156
+ throw changed("Cannot verify the full review from a partial answer set; send all answers together or finish in the terminal.");
157
+ }
145
158
  const realKeys = io.keys.bind(io);
146
159
  io = { ...io, keys: async (keys) => { sent = true; await realKeys(keys); } };
147
160
  const sleep = io.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
@@ -149,7 +162,12 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
149
162
  // Claude redraws a moment after a key; poll until the expected screen shows.
150
163
  const settle = async (check, ms = 2_000) => {
151
164
  for (let waited = 0;; waited += 120) {
152
- const value = check(claudeQuestionDialog(await io.read()));
165
+ const text = await io.read(), screen = claudeQuestionDialog(text);
166
+ // A bare cursor can itself be a partial question redraw. Closure must
167
+ // also have Claude's live footer or working hint, after the dialog cues.
168
+ const closed = !screen && dialogHasClosed(text)
169
+ && (claudeFooterMode(text) !== undefined || /\besc to interrupt\b/i.test(text));
170
+ const value = check(screen, closed);
153
171
  if (value !== undefined || waited >= ms)
154
172
  return value;
155
173
  await sleep(120);
@@ -166,6 +184,70 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
166
184
  // draws its own header. The tabs must be this set's, in this order.
167
185
  if (initial.tabs.length !== questions.length)
168
186
  throw changed("The terminal is asking a different set of questions.");
187
+ const moveCursor = async (index, screen, to) => {
188
+ const position = (value) => value === "next" ? screen.other.number + 1 : value;
189
+ while (screen.cursor !== to) {
190
+ const at = position(screen.cursor), target = position(to);
191
+ if (at === undefined || target === undefined)
192
+ throw changed("Could not locate the terminal cursor.");
193
+ const next = at + (target > at ? 1 : -1);
194
+ const expected = next === screen.other.number + 1 ? "next" : next;
195
+ await io.keys([target > at ? "down" : "up"]);
196
+ const moved = await settle(value => matches(value, index) && value.cursor === expected ? value : undefined);
197
+ if (!moved)
198
+ throw changed("Could not move and verify the terminal cursor.");
199
+ screen = moved;
200
+ }
201
+ return screen;
202
+ };
203
+ const commandCursor = async (index, screen) => {
204
+ if (screen.other && screen.cursor === screen.other.number)
205
+ screen = await moveCursor(index, screen, screen.other.number - 1);
206
+ if (!screen.options.some(row => row.number === screen.cursor) && !(screen.multiSelect && screen.cursor === "next")) {
207
+ throw changed("The terminal cursor is not on an option or Next row.");
208
+ }
209
+ return screen;
210
+ };
211
+ const enterText = async (index, screen, text) => {
212
+ screen = await moveCursor(index, screen, screen.other.number);
213
+ const existing = screen.other.label;
214
+ if (screen.other.answered)
215
+ throw changed("The existing typed answer ends with an ambiguous selection marker; edit it in the terminal.");
216
+ if (screen.other.wrapped)
217
+ throw changed("The existing typed answer is wrapped and cannot be verified; edit it in the terminal.");
218
+ const placeholder = existing === (screen.multiSelect ? "Type something" : "Type something.");
219
+ // The terminal capture cannot prove an editor shortcut cleared a field,
220
+ // or distinguish a literal placeholder answer from an empty field. Refuse
221
+ // those cases rather than append to a draft or submit an empty answer.
222
+ if ((placeholder && text === existing) || (!placeholder && existing !== text)) {
223
+ throw changed("The existing typed answer differs from the phone's answer or cannot be verified; clear it in the terminal first.");
224
+ }
225
+ const verifyText = async (expected) => {
226
+ const shown = await settle(value => matches(value, index) && value.cursor === screen.other.number
227
+ && !value.other?.wrapped && value.other?.label === expected && (!screen.multiSelect || value.other.checked) ? value : undefined);
228
+ if (!shown)
229
+ throw changed("The full typed answer did not appear exactly in the terminal.");
230
+ return shown;
231
+ };
232
+ if (placeholder) {
233
+ if (/^[0-9]/.test(text)) {
234
+ // Current Claude versions type digits into Other. Older versions may
235
+ // select (and immediately submit) an option if the field is empty,
236
+ // so establish text ownership without ever probing it with a digit.
237
+ await io.keys(["."]);
238
+ await verifyText(".");
239
+ await io.keys(typedKeys(text));
240
+ await verifyText("." + text);
241
+ // These editor keys cannot submit. If movement/deletion is unsupported
242
+ // or dropped, exact readback refuses before Enter can send the prefix.
243
+ await io.keys(["home", "right", "backspace"]);
244
+ }
245
+ else
246
+ await io.keys(typedKeys(text));
247
+ }
248
+ const shown = await verifyText(text);
249
+ return shown;
250
+ };
169
251
  const reach = async (index) => {
170
252
  const screen = await settle(value => value);
171
253
  if (screen?.kind === "question" && sameTitle(screen.title, questions[index].question))
@@ -175,15 +257,23 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
175
257
  if (at < 0)
176
258
  throw changed("The terminal is showing a different question.");
177
259
  // Arrow keys would edit a typed answer; step off that row first.
178
- if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number)
179
- await io.keys(["up"]);
260
+ if (screen?.kind === "question")
261
+ await commandCursor(at, screen);
180
262
  await io.keys(Array(Math.abs(index - at)).fill(index > at ? "right" : "left"));
181
263
  const moved = await settle(value => matches(value, index) ? value : undefined);
182
264
  if (!moved)
183
265
  throw changed("Could not move the terminal to the question being answered.");
184
266
  return moved;
185
267
  };
186
- const leaves = (index) => (value) => value === undefined ? "gone" : !matches(value, index) ? "moved" : undefined;
268
+ const leaves = (index, mayClose) => (value, closed) => {
269
+ if (mayClose && closed)
270
+ return "gone";
271
+ if (index + 1 < questions.length && matches(value, index + 1))
272
+ return "moved";
273
+ if (index + 1 === questions.length && value?.kind === "review")
274
+ return "moved";
275
+ return undefined;
276
+ };
187
277
  for (const [offset, answer] of answers.entries()) {
188
278
  const index = from + offset, question = questions[index];
189
279
  if (!question)
@@ -191,58 +281,42 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
191
281
  const typed = answer.text?.trim() ?? "";
192
282
  let screen = await reach(index);
193
283
  if (screen.multiSelect !== !!question.multiSelect || screen.options.length !== question.options.length
194
- || screen.options.some((row, position) => !sameLabel(row.label, question.options[position].label))) {
284
+ || screen.options.some((row, position) => row.label !== normalize(question.options[position].label))) {
195
285
  throw changed("The terminal's options differ from the question being answered.");
196
286
  }
197
287
  if (!screen.multiSelect) {
198
288
  if (typed) {
199
- const other = screen.other;
200
- await io.keys([String(other.number)]);
201
- const focused = await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined);
202
- if (!focused)
203
- throw changed("Could not open the typed answer.");
204
- await io.keys(typedKeys(typed));
205
- const shown = await settle(value => matches(value, index) && value.other && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
206
- if (!shown)
207
- throw changed("The typed answer did not appear in the terminal.");
289
+ await enterText(index, screen, typed);
208
290
  await io.keys(["enter"]);
209
291
  }
210
292
  else {
293
+ screen = await commandCursor(index, screen);
211
294
  await io.keys([String(screen.options[answer.options[0]].number)]);
212
295
  }
213
- if (!await settle(leaves(index), ANSWERED_MS))
214
- throw changed("The terminal did not take the answer.");
296
+ if (!await settle(leaves(index, questions.length === 1), ANSWERED_MS))
297
+ throw changed("The terminal did not confirm taking the answer.");
215
298
  continue;
216
299
  }
300
+ screen = await commandCursor(index, screen);
217
301
  // Multi-select: toggle only the boxes that differ, one key per write
218
302
  // (Ink reads "13" in one write as a single input and toggles nothing),
219
303
  // and check each box before the next.
220
304
  const rows = [...screen.options, ...(screen.other ? [screen.other] : [])];
221
305
  for (const [position, row] of rows.entries()) {
222
- const wanted = position < screen.options.length ? answer.options.includes(position) : !!row.checked && !!typed;
306
+ const wanted = position < screen.options.length ? answer.options.includes(position) : !!typed && row.label === typed;
223
307
  if (wanted === !!row.checked)
224
308
  continue;
225
309
  const box = (value) => matches(value, index)
226
310
  ? !!(position < value.options.length ? value.options[position] : value.other)?.checked : undefined;
227
- // A key that lands while the tab is still drawing can be dropped; the
228
- // box itself says whether one more press is needed.
229
- for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
230
- await io.keys([String(row.number)]);
231
- screen = await settle(value => box(value) === wanted ? value : undefined, 1_000) ?? screen;
232
- }
233
- if (box(screen) !== wanted)
311
+ screen = await commandCursor(index, screen);
312
+ await io.keys([String(row.number)]);
313
+ const toggled = await settle(value => box(value) === wanted ? value : undefined);
314
+ if (!toggled)
234
315
  throw changed("The terminal's checkboxes did not match the answer.");
316
+ screen = toggled;
235
317
  }
236
318
  if (typed) {
237
- const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
238
- if (cursor !== other.number)
239
- await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
240
- if (!await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined))
241
- throw changed("Could not reach the typed answer row.");
242
- await io.keys(typedKeys(typed));
243
- const shown = await settle(value => matches(value, index) && value.other?.checked && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
244
- if (!shown)
245
- throw changed("The typed answer did not appear in the terminal.");
319
+ screen = await enterText(index, screen, typed);
246
320
  // Tab moves from the typed row to Next; Enter there leaves the question.
247
321
  await io.keys(["tab"]);
248
322
  if (!await settle(value => matches(value, index) && value.cursor === "next" ? value : undefined))
@@ -251,23 +325,32 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
251
325
  }
252
326
  else {
253
327
  // Tab from the typed row would stop on Next instead of leaving.
254
- await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
328
+ screen = await commandCursor(index, screen);
329
+ await io.keys(["tab"]);
255
330
  }
256
- if (!await settle(leaves(index), ANSWERED_MS))
331
+ if (!await settle(leaves(index, false), ANSWERED_MS))
257
332
  throw changed("The terminal did not move past the question.");
258
333
  }
259
334
  if (!submit)
260
335
  return;
261
- const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined, ANSWERED_MS);
336
+ const review = await settle((value, closed) => value?.kind === "review" ? value
337
+ : questions.length === 1 && !questions[0].multiSelect && closed ? "gone" : undefined, ANSWERED_MS);
262
338
  // A lone single-select question submits on its digit.
263
339
  if (review === "gone")
264
340
  return;
265
341
  if (!review)
266
342
  throw changed("The terminal did not reach the review of the answers.");
267
343
  if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
268
- throw changed("Not every question has an answer in the terminal.");
344
+ throw changed("The terminal's review does not contain every expected question and answer.");
345
+ }
346
+ for (const [offset, answer] of answers.entries()) {
347
+ const index = from + offset, question = questions[index], text = answer.text?.trim() ?? "";
348
+ const labels = question.options.filter((_, position) => answer.options.includes(position)).map(option => normalize(option.label));
349
+ const expected = question.multiSelect ? [...labels, ...(text ? [text] : [])].join(", ") : text || labels[0];
350
+ if (review.answers[index]?.wrapped || review.answers[index]?.answer !== expected)
351
+ throw changed("The terminal's review does not exactly match the phone's answers.");
269
352
  }
270
353
  await io.keys(["1"]);
271
- if (await settle(value => value === undefined ? "gone" : undefined, ANSWERED_MS) !== "gone")
354
+ if (await settle((_value, closed) => closed ? "gone" : undefined, ANSWERED_MS) !== "gone")
272
355
  throw changed("The terminal did not submit the answers.");
273
356
  }
@@ -1,3 +1,4 @@
1
+ import type { IncomingMessage } from "node:http";
1
2
  import { type LinkResult, linkComputer } from "./link.js";
2
3
  import { type Json } from "./protocol.js";
3
4
  /** The Hook routes for linked computer sets (docs/conductor-sets.md). */
@@ -27,5 +28,5 @@ export declare function nameSet(data: Json): Promise<Json>;
27
28
  /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
28
29
  * on the computer whose set lists `name` as indirect or one-way, over this
29
30
  * computer's own ssh login, one link at a time. */
30
- export declare function linkSetMember(data: Json, link?: typeof linkComputer): Promise<LinkResult>;
31
+ export declare function linkSetMember(data: Json, request: Pick<IncomingMessage, "headers">, link?: typeof linkComputer): Promise<LinkResult>;
31
32
  export {};
@@ -7,6 +7,7 @@ import { listsCaller } from "./health.js";
7
7
  import { linkComputer } from "./link.js";
8
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
9
9
  import { BridgeError, object } from "./protocol.js";
10
+ import { ownerRequest } from "./request-origin.js";
10
11
  import { localConductor } from "./server-launch.js";
11
12
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
12
13
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -89,8 +90,8 @@ let linking;
89
90
  /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
90
91
  * on the computer whose set lists `name` as indirect or one-way, over this
91
92
  * computer's own ssh login, one link at a time. */
92
- export async function linkSetMember(data, link = linkComputer) {
93
- if (data && typeof data === "object" && "origin" in data)
93
+ export async function linkSetMember(data, request, link = linkComputer) {
94
+ if (!ownerRequest(request, data))
94
95
  throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
95
96
  const { name } = linkInput.parse(data);
96
97
  if (linking)
@@ -3,3 +3,7 @@
3
3
  export declare const DIALOG_READ_MS: number;
4
4
  export declare const DIALOG_CONFIRM_MS = 300;
5
5
  export declare function confirmDialogRead<T>(read: () => Promise<T>, current: () => boolean): Promise<T | undefined>;
6
+ /** A live composer or working hint after all dialog cues proves closure.
7
+ * Call only after ruling out a currently readable dialog. A failed parse alone
8
+ * says nothing: clipped and half-drawn screens remain unknown. */
9
+ export declare function dialogHasClosed(screen: string): boolean;
@@ -1,3 +1,5 @@
1
+ import { stripTerminal } from "../terminal-text.js";
2
+ import { claudeFooterMode } from "./claude-footer-mode.js";
1
3
  import { intervalFromEnv } from "./limits.js";
2
4
  /** Discovery is frequent by default; an owner can still cap polling explicitly.
3
5
  * Confirmation has its own small, fixed budget, independent of that cap. */
@@ -18,3 +20,25 @@ export async function confirmDialogRead(read, current) {
18
20
  clearTimeout(timer);
19
21
  }
20
22
  }
23
+ /** A live composer or working hint after all dialog cues proves closure.
24
+ * Call only after ruling out a currently readable dialog. A failed parse alone
25
+ * says nothing: clipped and half-drawn screens remain unknown. */
26
+ export function dialogHasClosed(screen) {
27
+ const lines = stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
28
+ const composer = (line) => /^[❯›](?!\s*\d+[.)])(?:\s|$)/.test(line);
29
+ const chrome = (line) => /^[─━═]+$/.test(line) || claudeFooterMode(line) !== undefined
30
+ || /^(?:[←→?].*(?:agents|shortcuts)|(?:gpt-|GPT-|claude-|Claude ).*)/i.test(line);
31
+ const liveTail = (index) => lines.slice(index + 1).every(line => composer(line) || chrome(line));
32
+ let cue = -1;
33
+ for (let index = 0; index < lines.length; index++) {
34
+ if (/^(?:[>❯›]?\s*\d+[.)]|Do you want|Would you like|Ready to code|Allow\b|Trust\b|Teach auto|△\s*Permission|[☐☒]|.*Esc to cancel)/i.test(lines[index]))
35
+ cue = index;
36
+ }
37
+ for (let index = lines.length - 1; index > cue; index--) {
38
+ if (/\besc to interrupt\b/i.test(lines[index]) && liveTail(index))
39
+ return true;
40
+ if (index >= lines.length - 3 && composer(lines[index]) && liveTail(index))
41
+ return true;
42
+ }
43
+ return false;
44
+ }
@@ -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>;