@phren/cli 0.3.75 → 0.3.77
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/approval-summary.js +12 -1
- 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/changes.d.ts +7 -0
- package/dist/bridge/changes.js +15 -3
- package/dist/bridge/computers.d.ts +6 -0
- package/dist/bridge/computers.js +38 -0
- package/dist/bridge/pair.d.ts +3 -1
- package/dist/bridge/pair.js +16 -6
- 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 +190 -90
- package/dist/cli-registry.js +5 -0
- package/dist/modules/registry.js +2 -2
- package/package.json +1 -1
|
@@ -33,11 +33,22 @@ export function redactApproval(value) {
|
|
|
33
33
|
})
|
|
34
34
|
.replace(/\bAuthorization\s*:\s*Bearer\s+(\S+)/gi, (_whole, token) => `Authorization: Bearer …${/["']$/.test(token) ? token.slice(-1) : ""}`)
|
|
35
35
|
.replace(/(^|\s)(--(?:token|password|secret|api-key|access-token))(?:\s+|=)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1$2 …")
|
|
36
|
+
// HTTP basic auth: curl -u name:password, wget/http --user. The name goes too; it is half of the credential.
|
|
37
|
+
.replace(/(\b(?:curl|wget|https?|httpie|xh)\b[^\n]*?\s(?:-u|--user|--proxy-user)(?:=|\s+))(?:"[^"]*"|'[^']*'|\S+)/gi, "$1…")
|
|
38
|
+
// Other Authorization schemes, and the headers that carry a key, token or session, up to the closing quote.
|
|
39
|
+
.replace(/(Authorization:\s*(?!Bearer\s)[A-Za-z]+\s+)[^\s"']+/gi, "$1…")
|
|
40
|
+
.replace(/(\b(?:proxy-authorization|cookie|set-cookie|x-api-key|api-key|apikey|x-auth-token|x-[a-z-]*(?:token|key|secret)[a-z-]*):\s*)[^"'\n]+/gi, "$1…")
|
|
41
|
+
// sshpass -p and registry logins take the password as the next word.
|
|
42
|
+
.replace(/(\bsshpass\b[^\n]*?\s-p\s*)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1…")
|
|
43
|
+
.replace(/(\b(?:docker|podman|helm|npm)\s+login\b[^\n]*?\s-p(?:=|\s+))(?:"[^"]*"|'[^']*'|\S+)/gi, "$1…")
|
|
44
|
+
// Form and query fields inside a quoted body: -d 'user=a&password=b'.
|
|
45
|
+
.replace(/(\b(?:password|passwd|pwd|pass|secret|token|api[_-]?key|access[_-]?token|client[_-]?secret|auth)=)[^&\s"']+/gi, "$1…")
|
|
36
46
|
// -p is a password only for MySQL-style clients (-pSECRET); elsewhere it is
|
|
37
47
|
// mkdir -p, ssh -p 22, git log -p, claude -p.
|
|
38
48
|
.replace(/(\b(?:mysql|mysqldump|mysqladmin|mariadb)\b[^\n]*?\s-p)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1…")
|
|
39
49
|
// Environment assignments only: a word after a separator, not a --flag=value.
|
|
40
|
-
|
|
50
|
+
// An & counts when it follows a space or another &, not inside a=1&b=2.
|
|
51
|
+
.replace(/(^|[\s;|(]|(?<![^\s&])&)([A-Za-z_][A-Za-z0-9_]*)=(?:"[^"]*"|'[^']*'|[^\s;]+)/g, "$1$2=…")
|
|
41
52
|
.replace(/\b(?:gh[po]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[abp]-[A-Za-z0-9-]+|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Fa-f0-9]{32,}|[A-Za-z0-9_-]{32,})\b/g, "…");
|
|
42
53
|
}
|
|
43
54
|
export function shortApproval(value) {
|
|
@@ -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
|
}
|
package/dist/bridge/changes.d.ts
CHANGED
|
@@ -16,6 +16,13 @@ export declare const changedFileSchema: z.ZodObject<{
|
|
|
16
16
|
}, z.core.$strip>;
|
|
17
17
|
export type ChangedFile = z.infer<typeof changedFileSchema>;
|
|
18
18
|
export declare const secretName: (file: string) => boolean;
|
|
19
|
+
/** A patch that holds anything credential-shaped (a key block, a known token
|
|
20
|
+
* format, a password assignment) is withheld whole, as the Hook's logs are:
|
|
21
|
+
* the phone shows the file as redacted rather than a half-scrubbed diff. */
|
|
22
|
+
/** Lockfile integrity hashes and embedded data are long base64 by nature, so
|
|
23
|
+
* the detector's shape-only base64 rule would withhold every lockfile diff;
|
|
24
|
+
* the known formats and name-based rules still apply. */
|
|
25
|
+
export declare const secretPatch: (patch: string) => boolean;
|
|
19
26
|
/** Tools whose filesystem changes are captured around the lifecycle callback. */
|
|
20
27
|
export declare const SHELL_TOOLS: Set<string>;
|
|
21
28
|
export declare function capturesChanges(tool: string, input: Json): boolean;
|
package/dist/bridge/changes.js
CHANGED
|
@@ -10,6 +10,7 @@ import { z } from "zod";
|
|
|
10
10
|
import { ProcessPool } from "./limits.js";
|
|
11
11
|
import { phrenStoreRoot } from "./transcripts.js";
|
|
12
12
|
import { countGit, countTick } from "./metrics.js";
|
|
13
|
+
import { scanForSecrets } from "../content/secrets.js";
|
|
13
14
|
const exec = promisify(execFile);
|
|
14
15
|
/** One file a shell command changed, with the patch between the working
|
|
15
16
|
* tree before the call and after it. `root` is the repository; `path` is
|
|
@@ -17,7 +18,14 @@ const exec = promisify(execFile);
|
|
|
17
18
|
export const changedFileSchema = z.object({ root: z.string(), path: z.string(), status: z.string(), patch: z.string(),
|
|
18
19
|
added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional(), binary: z.boolean().optional(), truncated: z.boolean().optional() });
|
|
19
20
|
const changeRowSchema = z.object({ toolUseId: z.string(), files: z.array(changedFileSchema) });
|
|
20
|
-
export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|
|
|
21
|
+
export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.env|.*\.(?:pem|key|p8|p12|pfx|jks|keystore|keychain-db|tfstate|tfvars|ovpn)|id_(?:rsa|dsa|ecdsa|ed25519)(?:[_.].*)?|(?:.*\.)?credentials(?:\.json)?|\.credentials|\.git-credentials|\.netrc|\.npmrc|\.pypirc|\.pgpass|kubeconfig)$/i.test(path.basename(file));
|
|
22
|
+
/** A patch that holds anything credential-shaped (a key block, a known token
|
|
23
|
+
* format, a password assignment) is withheld whole, as the Hook's logs are:
|
|
24
|
+
* the phone shows the file as redacted rather than a half-scrubbed diff. */
|
|
25
|
+
/** Lockfile integrity hashes and embedded data are long base64 by nature, so
|
|
26
|
+
* the detector's shape-only base64 rule would withhold every lockfile diff;
|
|
27
|
+
* the known formats and name-based rules still apply. */
|
|
28
|
+
export const secretPatch = (patch) => scanForSecrets(patch.replace(/(?=[A-Za-z0-9+/]*[+/])[A-Za-z0-9+/]{40,}={0,2}/g, "")) !== null;
|
|
21
29
|
/** Two Git jobs at a time: one repository's tree read (shared by every call
|
|
22
30
|
* waiting for it), one call's diff, or a repository lookup. Each holds its slot
|
|
23
31
|
* for all of its Git processes, so under load jobs finish in turn rather than
|
|
@@ -219,7 +227,7 @@ async function treeDiff(root, before, after, env, signal) {
|
|
|
219
227
|
const specs = [...new Set([original, file])].map(name => `:(literal)${name}`);
|
|
220
228
|
const counts = (await git(root, [...NO_DIFF, "--numstat", before, after, "--", ...specs], env, signal)).split("\t");
|
|
221
229
|
const binary = counts[0] === "-" || counts[1] === "-";
|
|
222
|
-
|
|
230
|
+
let redacted = secretName(original) || secretName(file) || binary;
|
|
223
231
|
let overflowed = false;
|
|
224
232
|
let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", ...specs], env, signal).catch(error => {
|
|
225
233
|
// One patch past Git's output buffer is shown truncated, not as a failed capture.
|
|
@@ -229,6 +237,10 @@ async function treeDiff(root, before, after, env, signal) {
|
|
|
229
237
|
overflowed = true;
|
|
230
238
|
return String(failure.stdout ?? "");
|
|
231
239
|
});
|
|
240
|
+
if (patch && secretPatch(patch)) {
|
|
241
|
+
patch = "";
|
|
242
|
+
redacted = true;
|
|
243
|
+
}
|
|
232
244
|
const truncated = overflowed || patch.length > 200_000;
|
|
233
245
|
if (truncated)
|
|
234
246
|
patch = patch.slice(0, 200_000) + "\n… (truncated)\n";
|
|
@@ -647,7 +659,7 @@ export class ToolChanges {
|
|
|
647
659
|
try {
|
|
648
660
|
const row = changeRowSchema.parse(JSON.parse(line));
|
|
649
661
|
// Also sanitize old records made before patch redaction existed.
|
|
650
|
-
entry.files.set(row.toolUseId, row.files.map(file => secretName(file.path) || file.redacted || /^(?:Binary files |GIT binary patch)/m.test(file.patch)
|
|
662
|
+
entry.files.set(row.toolUseId, row.files.map(file => secretName(file.path) || file.redacted || /^(?:Binary files |GIT binary patch)/m.test(file.patch) || secretPatch(file.patch)
|
|
651
663
|
? { ...file, patch: "", redacted: true } : file));
|
|
652
664
|
}
|
|
653
665
|
catch { /* Torn or invalid rows are not transcript events. */ }
|
|
@@ -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.
|
package/dist/bridge/pair.d.ts
CHANGED
|
@@ -57,7 +57,7 @@ export interface PairingApproval {
|
|
|
57
57
|
name?: string;
|
|
58
58
|
check: string | null;
|
|
59
59
|
}
|
|
60
|
-
/** 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. */
|
|
61
61
|
export declare function startPairing(options: {
|
|
62
62
|
code: string;
|
|
63
63
|
user: string;
|
|
@@ -76,6 +76,8 @@ export declare function startPairing(options: {
|
|
|
76
76
|
* typed pairing is refused.
|
|
77
77
|
*/
|
|
78
78
|
approve?: (phone: PairingApproval) => Promise<boolean>;
|
|
79
|
+
/** Called once, when wrong codes have turned typed pairing off for this session. */
|
|
80
|
+
onTypedOff?: () => void;
|
|
79
81
|
}): Promise<PairingSession>;
|
|
80
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]";
|
|
81
83
|
/** The authorized_keys line for a scoped key: no PTY, no forwarding, its own forced command. */
|
package/dist/bridge/pair.js
CHANGED
|
@@ -122,7 +122,7 @@ const request = z.object({
|
|
|
122
122
|
device: z.enum(["ios", "android"]).default("ios"), name: z.string().max(80).optional(),
|
|
123
123
|
typed: z.boolean().optional(),
|
|
124
124
|
});
|
|
125
|
-
/** 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. */
|
|
126
126
|
export async function startPairing(options) {
|
|
127
127
|
let failures = 0, finished = false, claimed = false, timer;
|
|
128
128
|
let approvals = Promise.resolve();
|
|
@@ -150,6 +150,10 @@ export async function startPairing(options) {
|
|
|
150
150
|
throw new BridgeError(410, "Pairing is closed. Run phren pair again.");
|
|
151
151
|
if (incoming.method !== "POST" || incoming.url !== "/v1/pair")
|
|
152
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.");
|
|
153
157
|
let size = 0;
|
|
154
158
|
const chunks = [];
|
|
155
159
|
for await (const chunk of incoming) {
|
|
@@ -163,12 +167,17 @@ export async function startPairing(options) {
|
|
|
163
167
|
const scanned = options.scanSecret !== undefined
|
|
164
168
|
&& sameProof(scanProof(options.code, options.scanSecret, "phone", publicKey), input.proof);
|
|
165
169
|
if (!scanned && !sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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?.();
|
|
169
176
|
throw new BridgeError(403, "That pairing code doesn't match this computer.");
|
|
170
177
|
}
|
|
171
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.");
|
|
172
181
|
// The code alone never authorizes a key, whatever the request says
|
|
173
182
|
// about itself: `typed` only tells a phone that will wait for the
|
|
174
183
|
// answer from an app that scanned before the scan secret existed and
|
|
@@ -392,7 +401,8 @@ export async function runPair(args, version) {
|
|
|
392
401
|
}
|
|
393
402
|
let cancelPairing = () => { };
|
|
394
403
|
const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000, scanSecret,
|
|
395
|
-
approve: phone => askToAllow(phone, () => cancelPairing())
|
|
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.") });
|
|
396
406
|
cancelPairing = () => session.close();
|
|
397
407
|
const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name, secret: scanSecret });
|
|
398
408
|
const { renderUnicodeCompact } = await import("uqr");
|
|
@@ -414,7 +424,7 @@ export async function runPair(args, version) {
|
|
|
414
424
|
try {
|
|
415
425
|
const paired = await session.done;
|
|
416
426
|
console.log(`\n✓ Paired ${paired.name ?? "your phone"}. It can reach Phren Hook on ${name} as ${user}.`);
|
|
417
|
-
console.log(
|
|
427
|
+
console.log(" To remove it later, run: phren unpair");
|
|
418
428
|
return 0;
|
|
419
429
|
}
|
|
420
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. */
|
package/dist/bridge/push.js
CHANGED
|
@@ -214,8 +214,17 @@ export class ApprovalPushService {
|
|
|
214
214
|
devices = [];
|
|
215
215
|
sender;
|
|
216
216
|
devicesFile = path.join(bridgeRoot(), "push-devices.json");
|
|
217
|
+
/** Loading, registering, forgetting and dropping a gone phone each read or
|
|
218
|
+
* write the list and its file; one at a time, so an older write never lands
|
|
219
|
+
* over a newer one and a load never brings back what was just forgotten. */
|
|
220
|
+
changes = Promise.resolve();
|
|
221
|
+
change(work) {
|
|
222
|
+
const next = this.changes.then(work, work);
|
|
223
|
+
this.changes = next.catch(() => { });
|
|
224
|
+
return next;
|
|
225
|
+
}
|
|
217
226
|
async start() {
|
|
218
|
-
this.devices = await secureJSON(this.devicesFile, z.array(deviceSchema).max(16)) ?? [];
|
|
227
|
+
await this.change(async () => { this.devices = await secureJSON(this.devicesFile, z.array(deviceSchema).max(16)) ?? []; });
|
|
219
228
|
const configFile = process.env.PHREN_APNS_CONFIG || path.join(bridgeRoot(), "apns.json");
|
|
220
229
|
const config = await secureJSON(configFile, configSchema);
|
|
221
230
|
if (!config)
|
|
@@ -234,16 +243,31 @@ export class ApprovalPushService {
|
|
|
234
243
|
devices: this.devices.length, relay };
|
|
235
244
|
}
|
|
236
245
|
async register(value) {
|
|
237
|
-
this.
|
|
238
|
-
|
|
246
|
+
await this.change(async () => {
|
|
247
|
+
this.devices = upsertPushDevice(this.devices, value);
|
|
248
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
/** Drop every registration; returns how many went. Registrations carry no
|
|
252
|
+
* SSH key, so removing a phone cannot pick out its own: all go, and the
|
|
253
|
+
* phones still paired register again the next time Phren renews (hourly, on open). */
|
|
254
|
+
async forgetAll() {
|
|
255
|
+
return this.change(async () => {
|
|
256
|
+
const removed = this.devices.length;
|
|
257
|
+
this.devices = [];
|
|
258
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
259
|
+
return removed;
|
|
260
|
+
});
|
|
239
261
|
}
|
|
240
262
|
/** One phone: the relay when it registered through one, otherwise direct. */
|
|
241
263
|
async send(device, payload, headers) {
|
|
242
264
|
if (device.relay) {
|
|
243
265
|
const result = await sendThroughRelay(device.relay, payload, headers);
|
|
244
266
|
if (result === "gone") {
|
|
245
|
-
|
|
246
|
-
|
|
267
|
+
await this.change(async () => {
|
|
268
|
+
this.devices = this.devices.filter(item => item.deviceID !== device.deviceID);
|
|
269
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
270
|
+
}).catch(() => { });
|
|
247
271
|
}
|
|
248
272
|
return result === "sent";
|
|
249
273
|
}
|
|
@@ -1320,9 +1320,18 @@ export function createRouteHandler(ctx) {
|
|
|
1320
1320
|
}
|
|
1321
1321
|
else if (url.pathname === "/v1/push/register") {
|
|
1322
1322
|
// Registration is kept for when a key is added; the reply says whether push works now.
|
|
1323
|
+
// The owner's phone only: a linked computer or an agent must not add a destination for this computer's alerts.
|
|
1324
|
+
if (!ownerRequest(request, data))
|
|
1325
|
+
throw new BridgeError(403, "Only the owner's phone registers for notifications.");
|
|
1323
1326
|
await agentHooks.push.register(data);
|
|
1324
1327
|
result = { ok: true, configured: agentHooks.push.status.configured };
|
|
1325
1328
|
}
|
|
1329
|
+
else if (url.pathname === "/v1/push/forget") {
|
|
1330
|
+
// `phren unpair` ends a removed phone's notifications with this.
|
|
1331
|
+
if (!ownerRequest(request, data))
|
|
1332
|
+
throw new BridgeError(403, "Only the owner removes notification registrations.");
|
|
1333
|
+
result = { ok: true, removed: await agentHooks.push.forgetAll() };
|
|
1334
|
+
}
|
|
1326
1335
|
else if (url.pathname === "/v1/sudo/answer") {
|
|
1327
1336
|
// The owner answers from the phone; an agent's call names its pane and
|
|
1328
1337
|
// a peer computer's arrives through its key's scope.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export declare const UNPAIR_USAGE = "phren unpair [<number> | SHA256:<fingerprint> | --all | --notifications]";
|
|
2
|
+
export interface PhoneKey {
|
|
3
|
+
line: string;
|
|
4
|
+
device: "ios" | "android";
|
|
5
|
+
fingerprint: string;
|
|
6
|
+
}
|
|
7
|
+
/** The phone keys `phren pair` and the phone's password sign-in wrote, in file order. */
|
|
8
|
+
export declare function phoneKeys(authorizedKeys: string): PhoneKey[];
|
|
9
|
+
export interface ProcessRow {
|
|
10
|
+
pid: number;
|
|
11
|
+
ppid: number;
|
|
12
|
+
uid: number;
|
|
13
|
+
command: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function parseProcessRows(output: string): ProcessRow[];
|
|
16
|
+
/**
|
|
17
|
+
* The SSH connections to end after a key is removed. sshd does not say which
|
|
18
|
+
* key opened a connection, and one that is already open keeps working without
|
|
19
|
+
* its authorized_keys line: it can open the Hook pipe again at any time. So
|
|
20
|
+
* every connection of this user that runs nothing but the Phren gateway, or
|
|
21
|
+
* nothing at all, is ended; the phones and computers still enrolled reconnect.
|
|
22
|
+
* A connection running anything else (a login shell, an editor's server, this
|
|
23
|
+
* command itself) is left alone.
|
|
24
|
+
*/
|
|
25
|
+
export declare function gatewayConnections(rows: ProcessRow[], options: {
|
|
26
|
+
uid: number;
|
|
27
|
+
root: string;
|
|
28
|
+
self: number;
|
|
29
|
+
}): {
|
|
30
|
+
sessions: number[];
|
|
31
|
+
children: number[];
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* End them; returns how many connections were ended. A sign-in that was accepted
|
|
35
|
+
* just before the key went can still be finishing, so the scan runs again after
|
|
36
|
+
* a pause until one pass finds nothing.
|
|
37
|
+
*/
|
|
38
|
+
export declare function endGatewayConnections(root?: string, pauseMs?: number): Promise<number>;
|
|
39
|
+
/**
|
|
40
|
+
* Push registrations are not tied to an SSH key, so the removed phone's cannot
|
|
41
|
+
* be told from the others: the Hook drops them all. With no Hook running, the
|
|
42
|
+
* saved list goes and the next Hook starts without it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function forgetPushRegistrations(root?: string): Promise<number>;
|
|
45
|
+
export declare function runUnpair(args: string[], options?: {
|
|
46
|
+
sshDirectory?: string;
|
|
47
|
+
endConnections?: () => Promise<number>;
|
|
48
|
+
forgetPush?: () => Promise<number>;
|
|
49
|
+
}): Promise<number>;
|