@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.
- package/dist/bridge/browser-recordings.d.ts +19 -0
- package/dist/bridge/browser-recordings.js +75 -15
- package/dist/bridge/browser-registry.d.ts +2 -0
- package/dist/bridge/browser-registry.js +9 -0
- package/dist/bridge/computers.d.ts +6 -0
- package/dist/bridge/computers.js +38 -0
- package/dist/bridge/file-range.js +2 -1
- package/dist/bridge/file-resolve.js +2 -1
- package/dist/bridge/file-write.js +2 -1
- package/dist/bridge/files.js +3 -2
- package/dist/bridge/git-dir-name.d.ts +5 -0
- package/dist/bridge/git-dir-name.js +8 -0
- package/dist/bridge/memory-store.js +2 -1
- package/dist/bridge/pair.d.ts +21 -5
- package/dist/bridge/pair.js +53 -17
- package/dist/bridge/push.d.ts +9 -0
- package/dist/bridge/push.js +29 -5
- package/dist/bridge/server-routes.js +9 -0
- package/dist/bridge/unpair.d.ts +49 -0
- package/dist/bridge/unpair.js +185 -0
- package/dist/bridge-hook.mjs +148 -31
- package/dist/cli-registry.js +5 -0
- package/dist/governance/policy.d.ts +4 -0
- package/dist/governance/policy.js +14 -1
- package/dist/modules/registry.js +2 -2
- package/dist/session/artifacts.js +1 -1
- package/dist/session/utils.d.ts +4 -1
- package/dist/session/utils.js +13 -2
- package/dist/tools/session.js +4 -1
- package/package.json +1 -1
|
@@ -29,6 +29,21 @@ export interface RecordingMeta {
|
|
|
29
29
|
title: string;
|
|
30
30
|
}[];
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* What a watched page can make the Hook keep. Its URL, title and navigations
|
|
34
|
+
* are the page's to choose, so each is cut to a size and the lists to a length:
|
|
35
|
+
* the metadata file, rewritten whole on every change, stays under about 1 MB.
|
|
36
|
+
*/
|
|
37
|
+
export declare const RECORDING_LIMITS: {
|
|
38
|
+
readonly url: 1024;
|
|
39
|
+
readonly title: 200;
|
|
40
|
+
readonly reason: 1024;
|
|
41
|
+
readonly navigations: 500;
|
|
42
|
+
readonly navigationsPerSecond: 10;
|
|
43
|
+
readonly pages: 100;
|
|
44
|
+
readonly handoffs: 500;
|
|
45
|
+
readonly saveEveryMs: 1000;
|
|
46
|
+
};
|
|
32
47
|
interface IndexFrame {
|
|
33
48
|
t: number;
|
|
34
49
|
pageId: string;
|
|
@@ -44,6 +59,10 @@ export declare class BrowserRecordings {
|
|
|
44
59
|
constructor(root: string);
|
|
45
60
|
private dir;
|
|
46
61
|
private save;
|
|
62
|
+
/** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
|
|
63
|
+
private saveSoon;
|
|
64
|
+
private saveNow;
|
|
65
|
+
private forget;
|
|
47
66
|
start(hello: Hello, now?: number): void;
|
|
48
67
|
page(page: PageInfo, now?: number): void;
|
|
49
68
|
frame(info: FrameInfo, jpeg: Buffer): void;
|
|
@@ -2,6 +2,12 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { BridgeError } from "./protocol.js";
|
|
4
4
|
import { BROWSER_ID } from "./browser-protocol.js";
|
|
5
|
+
/**
|
|
6
|
+
* What a watched page can make the Hook keep. Its URL, title and navigations
|
|
7
|
+
* are the page's to choose, so each is cut to a size and the lists to a length:
|
|
8
|
+
* the metadata file, rewritten whole on every change, stays under about 1 MB.
|
|
9
|
+
*/
|
|
10
|
+
export const RECORDING_LIMITS = { url: 1024, title: 200, reason: 1024, navigations: 500, navigationsPerSecond: 10, pages: 100, handoffs: 500, saveEveryMs: 1000 };
|
|
5
11
|
export function browserId(value) {
|
|
6
12
|
if (!value || !BROWSER_ID.test(value))
|
|
7
13
|
throw new BridgeError(400, "Invalid browser identifier.");
|
|
@@ -20,6 +26,30 @@ export class BrowserRecordings {
|
|
|
20
26
|
fs.writeFileSync(path.join(dir, "meta.tmp"), JSON.stringify(meta), { mode: 0o600 });
|
|
21
27
|
fs.renameSync(path.join(dir, "meta.tmp"), path.join(dir, "meta.json"));
|
|
22
28
|
}
|
|
29
|
+
/** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
|
|
30
|
+
saveSoon(state) {
|
|
31
|
+
const wait = state.savedAt + RECORDING_LIMITS.saveEveryMs - Date.now();
|
|
32
|
+
if (wait <= 0) {
|
|
33
|
+
this.saveNow(state);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
state.timer ??= setTimeout(() => {
|
|
37
|
+
state.timer = undefined;
|
|
38
|
+
// Retention may have removed the recording meanwhile.
|
|
39
|
+
if (this.active.get(state.meta.id) === state)
|
|
40
|
+
try {
|
|
41
|
+
this.saveNow(state);
|
|
42
|
+
}
|
|
43
|
+
catch { /* the folder is gone */ }
|
|
44
|
+
}, wait).unref();
|
|
45
|
+
}
|
|
46
|
+
saveNow(state) {
|
|
47
|
+
clearTimeout(state.timer);
|
|
48
|
+
state.timer = undefined;
|
|
49
|
+
this.save(state.meta);
|
|
50
|
+
state.savedAt = Date.now();
|
|
51
|
+
}
|
|
52
|
+
forget(id) { clearTimeout(this.active.get(id)?.timer); this.active.delete(id); }
|
|
23
53
|
start(hello, now = Date.now()) {
|
|
24
54
|
const dir = this.dir(hello.browserId);
|
|
25
55
|
fs.mkdirSync(dir, { mode: 0o700 }); // never overwrite an earlier recording
|
|
@@ -27,28 +57,42 @@ export class BrowserRecordings {
|
|
|
27
57
|
fs.writeFileSync(path.join(dir, "index.jsonl"), "", { mode: 0o600 });
|
|
28
58
|
const meta = { 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: [] };
|
|
29
59
|
this.save(meta);
|
|
30
|
-
this.active.set(meta.id, { meta, last: new Map() });
|
|
60
|
+
this.active.set(meta.id, { meta, last: new Map(), savedAt: Date.now(), second: 0, inSecond: 0 });
|
|
31
61
|
}
|
|
32
62
|
page(page, now = Date.now()) {
|
|
33
63
|
const state = this.active.get(page.browserId);
|
|
34
64
|
if (!state)
|
|
35
65
|
return;
|
|
36
|
-
const nav = { t: now, pageId: page.pageId, url: page.url, title: page.title };
|
|
66
|
+
const nav = { t: now, pageId: page.pageId, url: page.url.slice(0, RECORDING_LIMITS.url), title: page.title.slice(0, RECORDING_LIMITS.title) };
|
|
37
67
|
const previous = state.meta.navigations.filter(n => n.pageId === page.pageId).at(-1);
|
|
38
|
-
if (previous?.url ===
|
|
68
|
+
if (previous?.url === nav.url && previous.title === nav.title)
|
|
39
69
|
return;
|
|
40
70
|
const existing = state.meta.pages.find(p => p.pageId === page.pageId);
|
|
41
71
|
// A copy: the page entry follows the latest navigation, the timeline keeps each one as it was.
|
|
42
72
|
if (existing)
|
|
43
73
|
Object.assign(existing, { url: nav.url, title: nav.title });
|
|
44
|
-
else
|
|
74
|
+
else if (state.meta.pages.length < RECORDING_LIMITS.pages)
|
|
45
75
|
state.meta.pages.push({ ...nav });
|
|
46
|
-
// The shim announces a navigation before its title loads; the title then completes that entry.
|
|
47
|
-
if (previous?.url === page.url && !previous.title)
|
|
48
|
-
previous.title = page.title;
|
|
49
76
|
else
|
|
77
|
+
return;
|
|
78
|
+
// The shim announces a navigation before its title loads; the title then completes that entry.
|
|
79
|
+
if (previous?.url === nav.url && !previous.title)
|
|
80
|
+
previous.title = nav.title;
|
|
81
|
+
else {
|
|
82
|
+
// A page that navigates in a loop fills neither the timeline nor the disk:
|
|
83
|
+
// past the limits the page entry still follows it, the timeline does not.
|
|
84
|
+
const second = Math.floor(now / 1000);
|
|
85
|
+
if (state.second !== second) {
|
|
86
|
+
state.second = second;
|
|
87
|
+
state.inSecond = 0;
|
|
88
|
+
}
|
|
89
|
+
if (state.meta.navigations.length >= RECORDING_LIMITS.navigations || ++state.inSecond > RECORDING_LIMITS.navigationsPerSecond) {
|
|
90
|
+
this.saveSoon(state);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
50
93
|
state.meta.navigations.push(nav);
|
|
51
|
-
|
|
94
|
+
}
|
|
95
|
+
this.saveNow(state);
|
|
52
96
|
}
|
|
53
97
|
frame(info, jpeg) {
|
|
54
98
|
const state = this.active.get(info.browserId);
|
|
@@ -67,22 +111,24 @@ export class BrowserRecordings {
|
|
|
67
111
|
state.meta.bytes += jpeg.length;
|
|
68
112
|
state.meta.frames++;
|
|
69
113
|
state.last.set(info.pageId, { t: info.t, jpeg });
|
|
70
|
-
this.
|
|
114
|
+
this.saveSoon(state);
|
|
71
115
|
}
|
|
72
116
|
handoff(id, kind, reason) {
|
|
73
117
|
const state = this.active.get(id);
|
|
74
118
|
if (!state)
|
|
75
119
|
return;
|
|
76
|
-
state.meta.handoffs.
|
|
77
|
-
|
|
120
|
+
if (state.meta.handoffs.length >= RECORDING_LIMITS.handoffs)
|
|
121
|
+
return;
|
|
122
|
+
state.meta.handoffs.push({ t: Date.now(), kind, ...(reason ? { reason: reason.slice(0, RECORDING_LIMITS.reason) } : {}) });
|
|
123
|
+
this.saveNow(state);
|
|
78
124
|
}
|
|
79
125
|
end(id, now = Date.now()) {
|
|
80
126
|
const state = this.active.get(id);
|
|
81
127
|
if (!state)
|
|
82
128
|
return;
|
|
83
129
|
state.meta.endedAt = now;
|
|
84
|
-
this.
|
|
85
|
-
this.
|
|
130
|
+
this.saveNow(state);
|
|
131
|
+
this.forget(id);
|
|
86
132
|
}
|
|
87
133
|
list() {
|
|
88
134
|
return fs.readdirSync(this.root).filter(id => BROWSER_ID.test(id)).flatMap(id => {
|
|
@@ -97,7 +143,14 @@ export class BrowserRecordings {
|
|
|
97
143
|
index(id) {
|
|
98
144
|
const dir = this.dir(id);
|
|
99
145
|
try {
|
|
100
|
-
return { meta: JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")),
|
|
146
|
+
return { meta: JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")),
|
|
147
|
+
// A crash during an append leaves a torn last line; the complete rows before it still play.
|
|
148
|
+
frames: fs.readFileSync(path.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).flatMap(line => { try {
|
|
149
|
+
return [JSON.parse(line)];
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return [];
|
|
153
|
+
} }) };
|
|
101
154
|
}
|
|
102
155
|
catch {
|
|
103
156
|
throw new BridgeError(404, "Recording not found.");
|
|
@@ -128,6 +181,13 @@ export class BrowserRecordings {
|
|
|
128
181
|
recover(now = Date.now()) {
|
|
129
182
|
for (const meta of this.list())
|
|
130
183
|
if (meta.endedAt === null && !this.active.has(meta.id)) {
|
|
184
|
+
// The counters in the file can trail the frames written in the last second before the crash.
|
|
185
|
+
try {
|
|
186
|
+
const frames = this.index(meta.id).frames, final = frames.at(-1);
|
|
187
|
+
meta.frames = frames.length;
|
|
188
|
+
meta.bytes = final ? final.offset + final.length : 0;
|
|
189
|
+
}
|
|
190
|
+
catch { /* keep what the file says */ }
|
|
131
191
|
meta.endedAt = now;
|
|
132
192
|
this.save(meta);
|
|
133
193
|
}
|
|
@@ -139,7 +199,7 @@ export class BrowserRecordings {
|
|
|
139
199
|
for (const meta of all.reverse()) {
|
|
140
200
|
if (now - meta.startedAt >= 86_400_000 || total > budget) {
|
|
141
201
|
// Retention includes live recordings. Capture continues live after its expired archive is removed.
|
|
142
|
-
this.
|
|
202
|
+
this.forget(meta.id);
|
|
143
203
|
this.remove(meta.id);
|
|
144
204
|
total -= sizes.get(meta.id) ?? 0;
|
|
145
205
|
}
|
|
@@ -5,6 +5,8 @@ import path from "node:path";
|
|
|
5
5
|
import { BrowserMessageReader, browserWire } from "./browser-protocol.js";
|
|
6
6
|
import { browserSocketPath } from "./browser-socket.js";
|
|
7
7
|
import { BrowserRecordings } from "./browser-recordings.js";
|
|
8
|
+
/** Pages one browser lists, open and closed. */
|
|
9
|
+
export const MAX_PAGES = 200;
|
|
8
10
|
const MAX_INPUT_BACKLOG = 1024 * 1024;
|
|
9
11
|
export class BrowserRegistry extends EventEmitter {
|
|
10
12
|
root;
|
|
@@ -49,6 +51,13 @@ export class BrowserRegistry extends EventEmitter {
|
|
|
49
51
|
if (page && !page.live)
|
|
50
52
|
throw new Error("Closed page");
|
|
51
53
|
if (!page) {
|
|
54
|
+
// A page that opens and closes popups in a loop must not grow this list: the oldest closed pages go first.
|
|
55
|
+
while (browser.pages.length >= MAX_PAGES) {
|
|
56
|
+
const closed = browser.pages.findIndex(page => !page.live);
|
|
57
|
+
if (closed < 0)
|
|
58
|
+
throw new Error("Too many pages");
|
|
59
|
+
browser.pages.splice(closed, 1);
|
|
60
|
+
}
|
|
52
61
|
page = { id: p.pageId, url: p.url, title: p.title, width: p.width, height: p.height, live: true };
|
|
53
62
|
browser.pages.push(page);
|
|
54
63
|
}
|
|
@@ -7,6 +7,12 @@ export declare function computerKeyLine(name: string, publicKey: string): string
|
|
|
7
7
|
export declare function enrollComputer(name: string, root?: string): Promise<string>;
|
|
8
8
|
/** Accept a public key, rebuilding the restrictions rather than trusting supplied options. */
|
|
9
9
|
export declare function acceptComputer(name: string, input: string, sshDirectory?: string): Promise<void>;
|
|
10
|
+
/**
|
|
11
|
+
* Remove every authorized_keys line `matches` picks, under the enrollment lock.
|
|
12
|
+
* Returns how many lines went. Every other line, comments and blank lines
|
|
13
|
+
* included, is written back as it was.
|
|
14
|
+
*/
|
|
15
|
+
export declare function removeAuthorizedKeys(matches: (line: string) => boolean, sshDirectory?: string): Promise<number>;
|
|
10
16
|
/**
|
|
11
17
|
* Append one authorized_keys line under a lock, refusing when `conflicts`
|
|
12
18
|
* matches an existing line and leaving an identical line in place.
|
package/dist/bridge/computers.js
CHANGED
|
@@ -79,6 +79,44 @@ export async function acceptComputer(name, input, sshDirectory = path.join(homed
|
|
|
79
79
|
const encoded = publicKey.split(" ")[1];
|
|
80
80
|
await appendAuthorizedKey(line, existing => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded), "This name or key is already enrolled differently. Revoke the old line explicitly first.", sshDirectory);
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Remove every authorized_keys line `matches` picks, under the enrollment lock.
|
|
84
|
+
* Returns how many lines went. Every other line, comments and blank lines
|
|
85
|
+
* included, is written back as it was.
|
|
86
|
+
*/
|
|
87
|
+
export async function removeAuthorizedKeys(matches, sshDirectory = path.join(homedir(), ".ssh")) {
|
|
88
|
+
const directory = await lstat(sshDirectory).catch(() => undefined);
|
|
89
|
+
if (!directory)
|
|
90
|
+
return 0;
|
|
91
|
+
if (!directory.isDirectory() || directory.isSymbolicLink())
|
|
92
|
+
throw new BridgeError(409, "Refusing an unexpected SSH directory.");
|
|
93
|
+
const lock = path.join(sshDirectory, ".phren-enroll.lock");
|
|
94
|
+
try {
|
|
95
|
+
await mkdir(lock, { mode: 0o700 });
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
|
|
99
|
+
}
|
|
100
|
+
const file = path.join(sshDirectory, "authorized_keys");
|
|
101
|
+
const temporary = path.join(lock, "authorized_keys");
|
|
102
|
+
try {
|
|
103
|
+
if (!await regularFile(file))
|
|
104
|
+
return 0;
|
|
105
|
+
const before = await readFile(file, "utf8");
|
|
106
|
+
const lines = before.split("\n");
|
|
107
|
+
const kept = lines.filter(line => !matches(line));
|
|
108
|
+
if (kept.length === lines.length)
|
|
109
|
+
return 0;
|
|
110
|
+
await writeFile(temporary, kept.join("\n"), { mode: 0o600, flag: "wx" });
|
|
111
|
+
if (await readFile(file, "utf8") !== before)
|
|
112
|
+
throw new BridgeError(409, "authorized_keys changed while removing the key. Try again.");
|
|
113
|
+
await rename(temporary, file);
|
|
114
|
+
return lines.length - kept.length;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
await rm(lock, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
82
120
|
/**
|
|
83
121
|
* Append one authorized_keys line under a lock, refusing when `conflicts`
|
|
84
122
|
* matches an existing line and leaving an identical line in place.
|
|
@@ -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
|
|
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("/").
|
|
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
|
|
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")
|
package/dist/bridge/files.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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);
|
package/dist/bridge/pair.d.ts
CHANGED
|
@@ -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;
|
|
@@ -45,7 +57,7 @@ export interface PairingApproval {
|
|
|
45
57
|
name?: string;
|
|
46
58
|
check: string | null;
|
|
47
59
|
}
|
|
48
|
-
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout
|
|
60
|
+
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout. */
|
|
49
61
|
export declare function startPairing(options: {
|
|
50
62
|
code: string;
|
|
51
63
|
user: string;
|
|
@@ -55,13 +67,17 @@ 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
|
|
60
|
-
* be cracked from a captured request, so the person at the computer
|
|
61
|
-
* the phone whose key check matches the one it shows. Without it,
|
|
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>;
|
|
79
|
+
/** Called once, when wrong codes have turned typed pairing off for this session. */
|
|
80
|
+
onTypedOff?: () => void;
|
|
65
81
|
}): Promise<PairingSession>;
|
|
66
82
|
export declare const PAIR_USAGE = "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|-> [--no-install]";
|
|
67
83
|
/** The authorized_keys line for a scoped key: no PTY, no forwarding, its own forced command. */
|
package/dist/bridge/pair.js
CHANGED
|
@@ -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
|
|
17
|
-
// phone makes its own key and posts the public half here
|
|
18
|
-
// by the code
|
|
19
|
-
//
|
|
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({
|
|
@@ -105,7 +122,7 @@ const request = z.object({
|
|
|
105
122
|
device: z.enum(["ios", "android"]).default("ios"), name: z.string().max(80).optional(),
|
|
106
123
|
typed: z.boolean().optional(),
|
|
107
124
|
});
|
|
108
|
-
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout
|
|
125
|
+
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout. */
|
|
109
126
|
export async function startPairing(options) {
|
|
110
127
|
let failures = 0, finished = false, claimed = false, timer;
|
|
111
128
|
let approvals = Promise.resolve();
|
|
@@ -133,6 +150,10 @@ export async function startPairing(options) {
|
|
|
133
150
|
throw new BridgeError(410, "Pairing is closed. Run phren pair again.");
|
|
134
151
|
if (incoming.method !== "POST" || incoming.url !== "/v1/pair")
|
|
135
152
|
throw new BridgeError(404, "Not found.");
|
|
153
|
+
// The phone apps send neither header; a web page's request always carries
|
|
154
|
+
// one. Refused before it can count as a wrong code.
|
|
155
|
+
if (incoming.headers.origin !== undefined || incoming.headers["sec-fetch-site"] !== undefined)
|
|
156
|
+
throw new BridgeError(403, "Pair from the Phren app.");
|
|
136
157
|
let size = 0;
|
|
137
158
|
const chunks = [];
|
|
138
159
|
for await (const chunk of incoming) {
|
|
@@ -143,13 +164,26 @@ export async function startPairing(options) {
|
|
|
143
164
|
}
|
|
144
165
|
const input = request.parse(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
|
|
145
166
|
const publicKey = publicComputerKey(input.publicKey);
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
167
|
+
const scanned = options.scanSecret !== undefined
|
|
168
|
+
&& sameProof(scanProof(options.code, options.scanSecret, "phone", publicKey), input.proof);
|
|
169
|
+
if (!scanned && !sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
|
|
170
|
+
// Wrong codes bound how often the short code can be guessed. They no
|
|
171
|
+
// longer close the session: anyone who could reach the port could
|
|
172
|
+
// cancel pairing with five requests. They turn typed pairing off, and a
|
|
173
|
+
// phone that scans still pairs, since the scan secret cannot be guessed.
|
|
174
|
+
if (++failures === MAX_FAILURES)
|
|
175
|
+
options.onTypedOff?.();
|
|
150
176
|
throw new BridgeError(403, "That pairing code doesn't match this computer.");
|
|
151
177
|
}
|
|
152
|
-
if (
|
|
178
|
+
if (!scanned) {
|
|
179
|
+
if (failures >= MAX_FAILURES)
|
|
180
|
+
throw new BridgeError(403, "Too many wrong codes were tried on this computer. Scan the pairing code, or run phren pair again.");
|
|
181
|
+
// The code alone never authorizes a key, whatever the request says
|
|
182
|
+
// about itself: `typed` only tells a phone that will wait for the
|
|
183
|
+
// answer from an app that scanned before the scan secret existed and
|
|
184
|
+
// gives up in seconds.
|
|
185
|
+
if (!input.typed)
|
|
186
|
+
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
187
|
// One question at a time, each bound to its own phone: a single answer
|
|
154
188
|
// never allows two keys.
|
|
155
189
|
const ask = approvals.then(() => finished || claimed || incoming.socket.destroyed ? false
|
|
@@ -180,7 +214,8 @@ export async function startPairing(options) {
|
|
|
180
214
|
}
|
|
181
215
|
reply(response, 200, {
|
|
182
216
|
v: 1, name: options.name, user: options.user, sshPort: options.sshPort, fingerprint: options.fingerprint ?? null,
|
|
183
|
-
proof:
|
|
217
|
+
proof: scanned ? scanProof(options.code, options.scanSecret, "computer", options.fingerprint ?? "", publicKey)
|
|
218
|
+
: pairingProof(options.code, "computer", options.fingerprint ?? "", publicKey),
|
|
184
219
|
});
|
|
185
220
|
setImmediate(() => finish(undefined, { device: input.device, name: input.name, publicKey }));
|
|
186
221
|
}
|
|
@@ -357,7 +392,7 @@ export async function runPair(args, version) {
|
|
|
357
392
|
const sshPort = 22;
|
|
358
393
|
if (!await sshListening(sshPort))
|
|
359
394
|
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();
|
|
395
|
+
const code = newPairingCode(), scanSecret = newScanSecret();
|
|
361
396
|
const name = await computerDisplayName(), user = userInfo().username, fingerprint = await hostFingerprint();
|
|
362
397
|
const hosts = await pairingHosts();
|
|
363
398
|
if (!hosts.length) {
|
|
@@ -365,10 +400,11 @@ export async function runPair(args, version) {
|
|
|
365
400
|
return 1;
|
|
366
401
|
}
|
|
367
402
|
let cancelPairing = () => { };
|
|
368
|
-
const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000,
|
|
369
|
-
approve: phone => askToAllow(phone, () => cancelPairing())
|
|
403
|
+
const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000, scanSecret,
|
|
404
|
+
approve: phone => askToAllow(phone, () => cancelPairing()),
|
|
405
|
+
onTypedOff: () => console.log("\n⚠ Five wrong codes were tried, so typing the code is off for this pairing. Scanning still works; run phren pair again to type a code.") });
|
|
370
406
|
cancelPairing = () => session.close();
|
|
371
|
-
const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name });
|
|
407
|
+
const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name, secret: scanSecret });
|
|
372
408
|
const { renderUnicodeCompact } = await import("uqr");
|
|
373
409
|
console.log(`\nConnect your phone to ${name}`);
|
|
374
410
|
console.log(" In the Phren app: Agents → Add computer → Scan pairing code\n");
|
|
@@ -388,7 +424,7 @@ export async function runPair(args, version) {
|
|
|
388
424
|
try {
|
|
389
425
|
const paired = await session.done;
|
|
390
426
|
console.log(`\n✓ Paired ${paired.name ?? "your phone"}. It can reach Phren Hook on ${name} as ${user}.`);
|
|
391
|
-
console.log(
|
|
427
|
+
console.log(" To remove it later, run: phren unpair");
|
|
392
428
|
return 0;
|
|
393
429
|
}
|
|
394
430
|
catch (error) {
|
package/dist/bridge/push.d.ts
CHANGED
|
@@ -112,6 +112,11 @@ export declare class ApprovalPushService {
|
|
|
112
112
|
private devices;
|
|
113
113
|
private sender?;
|
|
114
114
|
private readonly devicesFile;
|
|
115
|
+
/** Loading, registering, forgetting and dropping a gone phone each read or
|
|
116
|
+
* write the list and its file; one at a time, so an older write never lands
|
|
117
|
+
* over a newer one and a load never brings back what was just forgotten. */
|
|
118
|
+
private changes;
|
|
119
|
+
private change;
|
|
115
120
|
start(): Promise<void>;
|
|
116
121
|
/** Phones this Hook can reach: through the relay, or direct with its own key. */
|
|
117
122
|
private get reachable();
|
|
@@ -124,6 +129,10 @@ export declare class ApprovalPushService {
|
|
|
124
129
|
relay: number;
|
|
125
130
|
};
|
|
126
131
|
register(value: unknown): Promise<void>;
|
|
132
|
+
/** Drop every registration; returns how many went. Registrations carry no
|
|
133
|
+
* SSH key, so removing a phone cannot pick out its own: all go, and the
|
|
134
|
+
* phones still paired register again the next time Phren renews (hourly, on open). */
|
|
135
|
+
forgetAll(): Promise<number>;
|
|
127
136
|
/** One phone: the relay when it registered through one, otherwise direct. */
|
|
128
137
|
private send;
|
|
129
138
|
/** Until when the owner is at Phren desktop (ms epoch): approval pushes wait for the desk to go quiet. */
|