@builtbynauroz/passforth 1.14.1 → 1.15.0
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/README.md +7 -5
- package/package.json +6 -3
- package/passforth.mjs +876 -221
package/passforth.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Passforth: end-to-end encrypted messages between Claude Code and Codex sessions (docs/backend/adr/0009, 0014). One
|
|
3
3
|
// file, Node 18+ or Bun 1.1+ and their built-ins only, MIT licence. A port of passforth.py (client 1.13.0), so either
|
|
4
|
-
// client reads what the other writes under ~/.passforth
|
|
5
|
-
// passforth connect does that from npm's cache)
|
|
4
|
+
// client reads what the other writes under ~/.passforth; unlike it, this one runs on Windows too (ADR-0017). Connect
|
|
5
|
+
// installs it as ~/.passforth/passforth.mjs (npx @builtbynauroz/passforth connect does that from npm's cache):
|
|
6
6
|
// node passforth.mjs connect [--url URL] set up this machine: asks for its secret and your passphrase
|
|
7
7
|
// node passforth.mjs unlock unlock your key again after you reset it on another machine
|
|
8
8
|
// node passforth.mjs reset-key forgot your passphrase: a new key (messages sealed to the old one are lost)
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// Message text and refs are sealed on this machine and opened only on the receiver's. The relay keeps routing data
|
|
15
15
|
// (who, to whom, kind, size, times, state) and the sealed bytes; it never sees your passphrase or your private key.
|
|
16
16
|
|
|
17
|
-
import { spawnSync } from "node:child_process";
|
|
17
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
18
18
|
import {
|
|
19
19
|
createCipheriv,
|
|
20
20
|
createDecipheriv,
|
|
@@ -49,12 +49,29 @@ import {
|
|
|
49
49
|
writeSync,
|
|
50
50
|
} from "node:fs";
|
|
51
51
|
import { homedir, hostname } from "node:os";
|
|
52
|
-
import {
|
|
52
|
+
import {
|
|
53
|
+
basename,
|
|
54
|
+
delimiter,
|
|
55
|
+
dirname,
|
|
56
|
+
isAbsolute,
|
|
57
|
+
join,
|
|
58
|
+
relative,
|
|
59
|
+
resolve,
|
|
60
|
+
sep,
|
|
61
|
+
} from "node:path";
|
|
62
|
+
import { createInterface } from "node:readline";
|
|
53
63
|
import { isatty } from "node:tty";
|
|
54
64
|
import { fileURLToPath } from "node:url";
|
|
55
65
|
import { deflateRawSync } from "node:zlib";
|
|
56
66
|
|
|
57
|
-
export const VERSION = "1.
|
|
67
|
+
export const VERSION = "1.15.0";
|
|
68
|
+
// Windows' own behaviour (ADR-0017): exec-form hooks, no POSIX tools, double-quoted commands. PASSFORTH_PLATFORM is
|
|
69
|
+
// there only so tests can drive those paths on macOS and Linux.
|
|
70
|
+
export const WINDOWS =
|
|
71
|
+
(process.env.PASSFORTH_PLATFORM || process.platform) === "win32";
|
|
72
|
+
// Paths follow the real file system, which no variable changes: "\\" separates them on Windows, where node:path's
|
|
73
|
+
// win32 functions do the work; elsewhere Python's posixpath, so both clients agree byte for byte.
|
|
74
|
+
const NATIVE = sep === "\\";
|
|
58
75
|
const HOME = process.env.PASSFORTH_HOME || pjoin(homedir(), ".passforth");
|
|
59
76
|
const PBKDF2_ITERATIONS = 600_000;
|
|
60
77
|
const MAX_TEXT_BYTES = 16_384;
|
|
@@ -290,11 +307,13 @@ const shq = (text) =>
|
|
|
290
307
|
function pjoin(first, ...rest) {
|
|
291
308
|
let out = first;
|
|
292
309
|
for (const part of rest) {
|
|
293
|
-
out = part
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
?
|
|
297
|
-
:
|
|
310
|
+
if (NATIVE) out = isAbsolute(part) ? resolve(out, part) : join(out, part);
|
|
311
|
+
else
|
|
312
|
+
out = part.startsWith("/")
|
|
313
|
+
? part
|
|
314
|
+
: !out || out.endsWith("/")
|
|
315
|
+
? out + part
|
|
316
|
+
: `${out}/${part}`;
|
|
298
317
|
}
|
|
299
318
|
return out;
|
|
300
319
|
}
|
|
@@ -304,16 +323,19 @@ function psplit(p) {
|
|
|
304
323
|
if (head && head !== "/".repeat(head.length)) head = head.replace(/\/+$/, "");
|
|
305
324
|
return [head, p.slice(i)];
|
|
306
325
|
}
|
|
307
|
-
const pbase = (p) => p.slice(p.lastIndexOf("/") + 1);
|
|
308
|
-
const pdir = (p) => psplit(p)[0];
|
|
326
|
+
const pbase = (p) => (NATIVE ? basename(p) : p.slice(p.lastIndexOf("/") + 1));
|
|
327
|
+
const pdir = (p) => (NATIVE ? dirname(p) : psplit(p)[0]);
|
|
328
|
+
const samePath = (a, b) =>
|
|
329
|
+
NATIVE ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
309
330
|
const expanduser = (p) =>
|
|
310
|
-
p === "~" || p.startsWith("~/")
|
|
311
|
-
? homedir().replace(/\/+$/, "") + p.slice(1)
|
|
331
|
+
p === "~" || p.startsWith("~/") || (NATIVE && p.startsWith("~\\"))
|
|
332
|
+
? homedir().replace(NATIVE ? /[\\/]+$/ : /\/+$/, "") + p.slice(1)
|
|
312
333
|
: p;
|
|
313
334
|
|
|
314
335
|
// os.path.realpath: symlinks resolved as far as the path exists, the rest kept as written, ".." after a link taken
|
|
315
336
|
// from where the link points (node:fs resolves ".." first, which can land elsewhere).
|
|
316
337
|
function realpath(p) {
|
|
338
|
+
if (NATIVE) return realpathNative(p);
|
|
317
339
|
const seen = new Map();
|
|
318
340
|
const walk = (start, rest) => {
|
|
319
341
|
let current = start;
|
|
@@ -364,6 +386,23 @@ function realpath(p) {
|
|
|
364
386
|
return resolve(walk("", p)[0]);
|
|
365
387
|
}
|
|
366
388
|
|
|
389
|
+
function realpathNative(p) {
|
|
390
|
+
// Windows takes ".." before any link, so resolve() first; then the longest part that exists, as the system names it
|
|
391
|
+
// (links and junctions followed), and the rest as written.
|
|
392
|
+
let head = resolve(p);
|
|
393
|
+
const tail = [];
|
|
394
|
+
for (;;) {
|
|
395
|
+
try {
|
|
396
|
+
return join(realpathSync.native(head), ...tail);
|
|
397
|
+
} catch {
|
|
398
|
+
const parent = dirname(head);
|
|
399
|
+
if (parent === head) return resolve(p);
|
|
400
|
+
tail.unshift(basename(head));
|
|
401
|
+
head = parent;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
367
406
|
// os.path.commonpath of two absolute paths.
|
|
368
407
|
function commonpath(a, b) {
|
|
369
408
|
const x = a.split("/").filter((c) => c && c !== ".");
|
|
@@ -373,6 +412,15 @@ function commonpath(a, b) {
|
|
|
373
412
|
return `/${x.slice(0, i).join("/")}`;
|
|
374
413
|
}
|
|
375
414
|
|
|
415
|
+
// commonpath([root, p]) == root: p is root or inside it. Windows compares as its file system does, ignoring case.
|
|
416
|
+
function within(root, p) {
|
|
417
|
+
if (!NATIVE) return commonpath(root, p) === root;
|
|
418
|
+
const rel = relative(root, p);
|
|
419
|
+
return (
|
|
420
|
+
!rel || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
|
|
376
424
|
const stat = (p, follow = true) => {
|
|
377
425
|
try {
|
|
378
426
|
return follow ? statSync(p) : lstatSync(p);
|
|
@@ -405,17 +453,26 @@ function removeTree(p) {
|
|
|
405
453
|
}
|
|
406
454
|
}
|
|
407
455
|
|
|
408
|
-
// shutil.which.
|
|
456
|
+
// shutil.which, with PATHEXT's extensions on Windows.
|
|
409
457
|
function which(command) {
|
|
410
|
-
const found = process.env.PATH ?? "/usr/bin:/bin";
|
|
458
|
+
const found = process.env.PATH ?? (NATIVE ? "" : "/usr/bin:/bin");
|
|
411
459
|
if (!found) return null;
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
460
|
+
const names =
|
|
461
|
+
NATIVE && !/\.[^.\\/]+$/.test(command)
|
|
462
|
+
? (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD")
|
|
463
|
+
.split(";")
|
|
464
|
+
.filter(Boolean)
|
|
465
|
+
.map((ext) => command + ext.toLowerCase())
|
|
466
|
+
: [command];
|
|
467
|
+
for (const dir of new Set(found.split(delimiter))) {
|
|
468
|
+
for (const name of names) {
|
|
469
|
+
const full = pjoin(dir, name);
|
|
470
|
+
try {
|
|
471
|
+
accessSync(full, constants.X_OK);
|
|
472
|
+
if (!statSync(full).isDirectory()) return full;
|
|
473
|
+
} catch {
|
|
474
|
+
// not here
|
|
475
|
+
}
|
|
419
476
|
}
|
|
420
477
|
}
|
|
421
478
|
return null;
|
|
@@ -871,8 +928,12 @@ const path = (...parts) => pjoin(HOME, ...parts);
|
|
|
871
928
|
// This client, wherever it runs from: ~/.passforth/passforth.mjs after connect, an npx cache, or a plugin's own folder,
|
|
872
929
|
// so a command it tells someone to type points at a file that exists. Connect points it at the copy it installs.
|
|
873
930
|
const THIS = realpathSync(fileURLToPath(import.meta.url));
|
|
874
|
-
|
|
931
|
+
// Windows' shells (CMD, PowerShell) take a path in double quotes; elsewhere it's shell-quoted.
|
|
932
|
+
const quoteHere = (p) => (WINDOWS ? `"${p}"` : shq(p));
|
|
933
|
+
let HERE = quoteHere(THIS);
|
|
875
934
|
const RUNTIME = process.versions.bun ? "bun" : "node";
|
|
935
|
+
// A command to type in a terminal: how to run this client, then what to run.
|
|
936
|
+
export const hereCommand = (args) => `${RUNTIME} ${HERE} ${args}`;
|
|
876
937
|
|
|
877
938
|
function readJson(name, fallback = null) {
|
|
878
939
|
try {
|
|
@@ -891,7 +952,26 @@ function writePrivate(name, content) {
|
|
|
891
952
|
const tmp = `${target}.tmp`;
|
|
892
953
|
writeFileSync(tmp, content, { mode: 0o600 });
|
|
893
954
|
chmodSync(tmp, 0o600);
|
|
894
|
-
|
|
955
|
+
replaceFile(tmp, target);
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// os.replace. On Windows a file another process holds (an editor, a scanner) can refuse it for a moment: up to 10 more
|
|
959
|
+
// tries, 50 ms apart.
|
|
960
|
+
function replaceFile(tmp, target) {
|
|
961
|
+
for (let tries = 0; ; tries++) {
|
|
962
|
+
try {
|
|
963
|
+
renameSync(tmp, target);
|
|
964
|
+
return;
|
|
965
|
+
} catch (error) {
|
|
966
|
+
if (
|
|
967
|
+
!WINDOWS ||
|
|
968
|
+
tries === 10 ||
|
|
969
|
+
!["EPERM", "EBUSY", "EACCES"].includes(error.code)
|
|
970
|
+
)
|
|
971
|
+
throw error;
|
|
972
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
895
975
|
}
|
|
896
976
|
|
|
897
977
|
const writeJson = (name, value) =>
|
|
@@ -1035,7 +1115,7 @@ function peerKey(userId, handle, version, publicB64) {
|
|
|
1035
1115
|
409,
|
|
1036
1116
|
"key_changed",
|
|
1037
1117
|
`@${handle}'s key changed (now ${fingerprint(publicRaw)}). If they reset their passphrase, check the ` +
|
|
1038
|
-
`fingerprint with them, then run in your own terminal: ${
|
|
1118
|
+
`fingerprint with them, then run in your own terminal: ${hereCommand(`trust @${handle}`)}`,
|
|
1039
1119
|
);
|
|
1040
1120
|
}
|
|
1041
1121
|
if (
|
|
@@ -1066,7 +1146,7 @@ function requireKey() {
|
|
|
1066
1146
|
throw new RelayError(
|
|
1067
1147
|
0,
|
|
1068
1148
|
"no_key",
|
|
1069
|
-
`This machine has no Passforth key; in a terminal, run: ${
|
|
1149
|
+
`This machine has no Passforth key; in a terminal, run: ${hereCommand("unlock")}`,
|
|
1070
1150
|
);
|
|
1071
1151
|
}
|
|
1072
1152
|
return key;
|
|
@@ -1096,6 +1176,11 @@ function parentOf(pid) {
|
|
|
1096
1176
|
}
|
|
1097
1177
|
|
|
1098
1178
|
function rememberSession(sid, shortId) {
|
|
1179
|
+
// On Windows connect's hooks run with no shell, so a hook's parent is Claude Code itself, and there's no ps to ask.
|
|
1180
|
+
if (WINDOWS) {
|
|
1181
|
+
writeJson(pjoin("state", `pid-${process.ppid}.json`), { sid, shortId });
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1099
1184
|
let pid = process.ppid;
|
|
1100
1185
|
for (let seen = 0; pid > 1 && seen < 4; seen++) {
|
|
1101
1186
|
writeJson(pjoin("state", `pid-${pid}.json`), { sid, shortId });
|
|
@@ -1412,7 +1497,7 @@ function pickFiles(paths, root) {
|
|
|
1412
1497
|
let total = 0;
|
|
1413
1498
|
for (const given of paths) {
|
|
1414
1499
|
const full = realpath(pjoin(root, given));
|
|
1415
|
-
if (full === root ||
|
|
1500
|
+
if (full === root || !within(root, full)) {
|
|
1416
1501
|
throw new RelayError(
|
|
1417
1502
|
422,
|
|
1418
1503
|
"outside_project",
|
|
@@ -1573,7 +1658,7 @@ export function zipFolder(folderPath, given) {
|
|
|
1573
1658
|
if (entry.name.startsWith(".")) continue;
|
|
1574
1659
|
const inner = pjoin(dir, entry.name);
|
|
1575
1660
|
if (entry.isDirectory()) walk(inner);
|
|
1576
|
-
else listed.push(relative(full, inner));
|
|
1661
|
+
else listed.push(relative(full, inner).replaceAll(sep, "/"));
|
|
1577
1662
|
}
|
|
1578
1663
|
};
|
|
1579
1664
|
walk(full);
|
|
@@ -1583,11 +1668,7 @@ export function zipFolder(folderPath, given) {
|
|
|
1583
1668
|
let raw = 0;
|
|
1584
1669
|
for (const name of [...new Set(listed)].sort(byCodePoint)) {
|
|
1585
1670
|
const inner = pjoin(full, name);
|
|
1586
|
-
if (
|
|
1587
|
-
isLink(inner) ||
|
|
1588
|
-
!isFile(inner) ||
|
|
1589
|
-
commonpath(full, realpath(inner)) !== full
|
|
1590
|
-
)
|
|
1671
|
+
if (isLink(inner) || !isFile(inner) || !within(full, realpath(inner)))
|
|
1591
1672
|
continue;
|
|
1592
1673
|
const info = statSync(inner);
|
|
1593
1674
|
raw += info.size;
|
|
@@ -2272,7 +2353,8 @@ function wakeCodex(sid, text, notices) {
|
|
|
2272
2353
|
"This line is Passforth's, not your user's.",
|
|
2273
2354
|
);
|
|
2274
2355
|
}
|
|
2275
|
-
|
|
2356
|
+
// No codex queue on Windows, where connect doesn't set Codex up (ADR-0017).
|
|
2357
|
+
const codex = WINDOWS ? null : which("codex");
|
|
2276
2358
|
if (codex && lines.length) {
|
|
2277
2359
|
spawnSync(
|
|
2278
2360
|
codex,
|
|
@@ -3011,8 +3093,9 @@ async function toolLogin() {
|
|
|
3011
3093
|
if (key && key.userId === answer.userId)
|
|
3012
3094
|
return `Linked as @${answer.handle}, ready to send and receive.`;
|
|
3013
3095
|
return (
|
|
3014
|
-
`Linked as @${answer.handle}. One step left
|
|
3015
|
-
"
|
|
3096
|
+
`Linked as @${answer.handle}. One step left: ${hereCommand("unlock")} puts your key on this machine. ` +
|
|
3097
|
+
"It can run from this session: with no terminal it asks for your passphrase in a window on your " +
|
|
3098
|
+
"screen, never in this chat."
|
|
3016
3099
|
);
|
|
3017
3100
|
}
|
|
3018
3101
|
const grant = await deviceStart(url);
|
|
@@ -3049,12 +3132,21 @@ async function toolStatus() {
|
|
|
3049
3132
|
);
|
|
3050
3133
|
} else {
|
|
3051
3134
|
lines.push(
|
|
3052
|
-
`No key on this machine yet:
|
|
3135
|
+
`No key on this machine yet: ${hereCommand("unlock")} puts it here. It can run from this session: with no ` +
|
|
3136
|
+
"terminal it asks for your passphrase in a window on your screen, never in this chat.",
|
|
3053
3137
|
);
|
|
3054
3138
|
}
|
|
3055
3139
|
return lines.join("\n");
|
|
3056
3140
|
}
|
|
3057
3141
|
|
|
3142
|
+
// Windows reads some names as devices (CON, NUL, COM1) and "a:b" as a stream: a sender's name it can save as a file.
|
|
3143
|
+
function windowsName(name) {
|
|
3144
|
+
const clean = name.replace(/[<>:"|?*]/g, "_").replace(/[. ]+$/, "") || "file";
|
|
3145
|
+
return /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(clean)
|
|
3146
|
+
? `_${clean}`
|
|
3147
|
+
: clean;
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3058
3150
|
async function toolFiles(args) {
|
|
3059
3151
|
// Saves what a message that reached this developer carries: each file fetched sealed, opened with its own key from
|
|
3060
3152
|
// the message's sealed body, checked and written once. A second call skips what's already saved.
|
|
@@ -3070,11 +3162,12 @@ async function toolFiles(args) {
|
|
|
3070
3162
|
const lines = [];
|
|
3071
3163
|
const names = new Set();
|
|
3072
3164
|
for (const f of files) {
|
|
3073
|
-
|
|
3165
|
+
const given = WINDOWS ? windowsName(f.name) : f.name;
|
|
3166
|
+
let name = given;
|
|
3074
3167
|
let n = 2;
|
|
3075
|
-
const [stem, dot, ext] = rpartition(
|
|
3168
|
+
const [stem, dot, ext] = rpartition(given, ".");
|
|
3076
3169
|
while (names.has(name)) {
|
|
3077
|
-
name = dot && stem ? `${stem} (${n})${dot}${ext}` : `${
|
|
3170
|
+
name = dot && stem ? `${stem} (${n})${dot}${ext}` : `${given} (${n})`;
|
|
3078
3171
|
n += 1;
|
|
3079
3172
|
}
|
|
3080
3173
|
names.add(name);
|
|
@@ -3153,7 +3246,7 @@ async function toolSearch(args) {
|
|
|
3153
3246
|
throw new RelayError(422, "validation", "query is 1 to 200 characters.");
|
|
3154
3247
|
}
|
|
3155
3248
|
if (!archiveOn())
|
|
3156
|
-
return `Search is off on this machine; ${
|
|
3249
|
+
return `Search is off on this machine; ${hereCommand("archive on")} turns it on.`;
|
|
3157
3250
|
const terms = query.split(" ");
|
|
3158
3251
|
const found = new Map();
|
|
3159
3252
|
let content;
|
|
@@ -3552,6 +3645,231 @@ const replyJson = (value) => out(`${dumps(value)}\n`);
|
|
|
3552
3645
|
// ---------------------------------------------------------------------------------------------------------------------
|
|
3553
3646
|
// Commands a person runs in their own terminal.
|
|
3554
3647
|
|
|
3648
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
3649
|
+
// The terminal (ADR-0018; design/DECISIONS.md, "Numbered steps"). A command prints numbered steps, every line under a step
|
|
3650
|
+
// carries one mark, and color and the spinner show only on a terminal that wants them. With no terminal to ask at, as in
|
|
3651
|
+
// Claude Code's and Codex's shells, a command takes the agent's path: nothing waits on a prompt, a passphrase is asked in a
|
|
3652
|
+
// window on the developer's screen and never passes through the agent, and a step that waits on its developer stops the
|
|
3653
|
+
// run with "Not finished", exit status 75, naming what to do before the same command runs again.
|
|
3654
|
+
|
|
3655
|
+
class NotFinished extends Error {}
|
|
3656
|
+
class NoScreen extends Error {}
|
|
3657
|
+
|
|
3658
|
+
const NOT_FINISHED = 75;
|
|
3659
|
+
const SPIN = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
|
|
3660
|
+
const AGENT_WAIT_S = 90;
|
|
3661
|
+
const WINDOW_WAIT_S = 120;
|
|
3662
|
+
let indent = " ";
|
|
3663
|
+
|
|
3664
|
+
const styled = (fd = 1) =>
|
|
3665
|
+
isatty(fd) && !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
|
3666
|
+
|
|
3667
|
+
const paint = (text, code, fd = 1) =>
|
|
3668
|
+
styled(fd) ? `\x1b[${code}m${text}\x1b[0m` : text;
|
|
3669
|
+
|
|
3670
|
+
// The Linux console's font has no ✓, ✗ or braille; on Windows, only the consoles below draw them.
|
|
3671
|
+
function drawsUnicode() {
|
|
3672
|
+
const env = process.env;
|
|
3673
|
+
if (!WINDOWS) return env.TERM !== "linux";
|
|
3674
|
+
return (
|
|
3675
|
+
Boolean(env.WT_SESSION) ||
|
|
3676
|
+
env.TERM_PROGRAM === "vscode" ||
|
|
3677
|
+
env.ConEmuANSI === "ON" ||
|
|
3678
|
+
["xterm-256color", "alacritty"].includes(env.TERM)
|
|
3679
|
+
);
|
|
3680
|
+
}
|
|
3681
|
+
|
|
3682
|
+
// Each mark, what stands in for it where the console can't draw it, and its color.
|
|
3683
|
+
const MARKS = {
|
|
3684
|
+
ok: ["✓", WINDOWS ? "√" : "+", "32"],
|
|
3685
|
+
note: ["!", "!", "33"],
|
|
3686
|
+
fail: ["✗", WINDOWS ? "×" : "x", "31"],
|
|
3687
|
+
};
|
|
3688
|
+
|
|
3689
|
+
function mark(kind, fd = 1) {
|
|
3690
|
+
const [symbol, plain, code] = MARKS[kind];
|
|
3691
|
+
return paint(drawsUnicode() ? symbol : plain, code, fd);
|
|
3692
|
+
}
|
|
3693
|
+
|
|
3694
|
+
function header(action) {
|
|
3695
|
+
indent = " ";
|
|
3696
|
+
print(`${paint(`Passforth ${VERSION}`, "1")} · ${action}`);
|
|
3697
|
+
print(paint(`client sha256 ${clientDigest()}`, "2"));
|
|
3698
|
+
print("");
|
|
3699
|
+
}
|
|
3700
|
+
|
|
3701
|
+
function step(number, title, total = 3) {
|
|
3702
|
+
indent = " ".repeat(5);
|
|
3703
|
+
if (number > 1) print("");
|
|
3704
|
+
print(`${paint(`${number}/${total}`, "1;32")} ${paint(title, "1")}`);
|
|
3705
|
+
}
|
|
3706
|
+
|
|
3707
|
+
const say = (text, kind = "") =>
|
|
3708
|
+
print(`${indent}${kind ? `${mark(kind)} ` : ""}${text}`);
|
|
3709
|
+
|
|
3710
|
+
function finish(text, kind = "ok") {
|
|
3711
|
+
indent = " ";
|
|
3712
|
+
print(`\n${mark(kind)} ${text}`);
|
|
3713
|
+
}
|
|
3714
|
+
|
|
3715
|
+
// Red with its mark on a terminal; elsewhere the plain "passforth: …" line that scripts and agents read.
|
|
3716
|
+
const fail = (text) =>
|
|
3717
|
+
eprint(styled(2) ? `${mark("fail", 2)} ${text}` : `passforth: ${text}`);
|
|
3718
|
+
|
|
3719
|
+
function tilde(where) {
|
|
3720
|
+
const home = expanduser("~");
|
|
3721
|
+
return where === home || where.startsWith(home + sep)
|
|
3722
|
+
? `~${where.slice(home.length)}`
|
|
3723
|
+
: where;
|
|
3724
|
+
}
|
|
3725
|
+
|
|
3726
|
+
const toolLine = (name, where) => `${name.padEnd(11)} ${tilde(where)}`;
|
|
3727
|
+
|
|
3728
|
+
function hasTerminal() {
|
|
3729
|
+
// Windows has no /dev/tty: its console is stdin, as getpass reads it.
|
|
3730
|
+
if (WINDOWS) return Boolean(process.stdin.isTTY);
|
|
3731
|
+
try {
|
|
3732
|
+
closeSync(openSync("/dev/tty", "r+"));
|
|
3733
|
+
return true;
|
|
3734
|
+
} catch {
|
|
3735
|
+
return false;
|
|
3736
|
+
}
|
|
3737
|
+
}
|
|
3738
|
+
|
|
3739
|
+
function openBrowser(page) {
|
|
3740
|
+
// On this machine's screen, for its developer; never without a screen, or with $PASSFORTH_NO_BROWSER set.
|
|
3741
|
+
if (process.env.PASSFORTH_NO_BROWSER) return false;
|
|
3742
|
+
const command = WINDOWS
|
|
3743
|
+
? ["rundll32.exe", "url.dll,FileProtocolHandler", page]
|
|
3744
|
+
: process.platform === "darwin"
|
|
3745
|
+
? ["open", page]
|
|
3746
|
+
: process.env.DISPLAY || process.env.WAYLAND_DISPLAY
|
|
3747
|
+
? ["xdg-open", page]
|
|
3748
|
+
: null;
|
|
3749
|
+
// Python's Popen fails at once on a missing program; spawn only says so later, as an event.
|
|
3750
|
+
if (!command || !which(command[0])) return false;
|
|
3751
|
+
try {
|
|
3752
|
+
spawn(command[0], command.slice(1), { stdio: "ignore", detached: true })
|
|
3753
|
+
.on("error", () => {})
|
|
3754
|
+
.unref();
|
|
3755
|
+
} catch {
|
|
3756
|
+
return false;
|
|
3757
|
+
}
|
|
3758
|
+
return true;
|
|
3759
|
+
}
|
|
3760
|
+
|
|
3761
|
+
// macOS's own dialog with its answer hidden. It gives up after WINDOW_WAIT_S, so no run waits on a window nobody answers.
|
|
3762
|
+
const WINDOW_SCRIPT = `on run argv
|
|
3763
|
+
set answer to display dialog (item 1 of argv) default answer "" with hidden answer with title "Passforth" buttons {"Cancel", "OK"} default button "OK" giving up after ((item 2 of argv) as integer)
|
|
3764
|
+
if gave up of answer then error number -128
|
|
3765
|
+
return text returned of answer
|
|
3766
|
+
end run`;
|
|
3767
|
+
|
|
3768
|
+
// Windows' own: a WinForms password box in PowerShell, on top and centred, that closes itself after WINDOW_WAIT_S. Its
|
|
3769
|
+
// text comes in $env:PASSFORTH_WINDOW_TEXT, never written into the script, and its answer goes out as UTF-8.
|
|
3770
|
+
const POWERSHELL_WINDOW = [
|
|
3771
|
+
"$ErrorActionPreference = 'Stop'",
|
|
3772
|
+
"Add-Type -AssemblyName System.Windows.Forms, System.Drawing",
|
|
3773
|
+
"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false",
|
|
3774
|
+
"[System.Windows.Forms.Application]::EnableVisualStyles()",
|
|
3775
|
+
"$form = New-Object System.Windows.Forms.Form",
|
|
3776
|
+
"$form.Text = 'Passforth'",
|
|
3777
|
+
"$form.TopMost = $true",
|
|
3778
|
+
"$form.StartPosition = 'CenterScreen'",
|
|
3779
|
+
"$form.FormBorderStyle = 'FixedDialog'",
|
|
3780
|
+
"$form.MaximizeBox = $false",
|
|
3781
|
+
"$form.MinimizeBox = $false",
|
|
3782
|
+
"$label = New-Object System.Windows.Forms.Label",
|
|
3783
|
+
"$label.Text = $env:PASSFORTH_WINDOW_TEXT",
|
|
3784
|
+
"$label.Location = New-Object System.Drawing.Point 12, 12",
|
|
3785
|
+
"$label.Size = $label.GetPreferredSize((New-Object System.Drawing.Size 360, 0))",
|
|
3786
|
+
"$box = New-Object System.Windows.Forms.TextBox",
|
|
3787
|
+
"$box.UseSystemPasswordChar = $true",
|
|
3788
|
+
"$box.SetBounds(12, $label.Bottom + 10, 360, 24)",
|
|
3789
|
+
"$ok = New-Object System.Windows.Forms.Button",
|
|
3790
|
+
"$ok.Text = 'OK'",
|
|
3791
|
+
"$ok.DialogResult = 'OK'",
|
|
3792
|
+
"$ok.SetBounds(216, $box.Bottom + 12, 75, 26)",
|
|
3793
|
+
"$cancel = New-Object System.Windows.Forms.Button",
|
|
3794
|
+
"$cancel.Text = 'Cancel'",
|
|
3795
|
+
"$cancel.DialogResult = 'Cancel'",
|
|
3796
|
+
"$cancel.SetBounds(297, $box.Bottom + 12, 75, 26)",
|
|
3797
|
+
"$form.AcceptButton = $ok",
|
|
3798
|
+
"$form.CancelButton = $cancel",
|
|
3799
|
+
"$form.ClientSize = New-Object System.Drawing.Size 384, ($ok.Bottom + 12)",
|
|
3800
|
+
"$form.Controls.AddRange(@($label, $box, $ok, $cancel))",
|
|
3801
|
+
"$timer = New-Object System.Windows.Forms.Timer",
|
|
3802
|
+
`$timer.Interval = ${WINDOW_WAIT_S * 1000}`,
|
|
3803
|
+
"$timer.add_Tick({ $form.Close() })",
|
|
3804
|
+
"$form.add_Shown({ $form.Activate(); [void]$box.Focus(); $timer.Start() })",
|
|
3805
|
+
"if ($form.ShowDialog() -ne 'OK') { exit 1 }",
|
|
3806
|
+
"[Console]::Out.Write($box.Text)",
|
|
3807
|
+
"exit 0",
|
|
3808
|
+
].join("\n");
|
|
3809
|
+
|
|
3810
|
+
// The window that asks, as [program, args, spawn options]; null where there's no screen to show one on.
|
|
3811
|
+
export function windowCommand(text) {
|
|
3812
|
+
const program = process.env.PASSFORTH_ASKPASS;
|
|
3813
|
+
const screen = process.env.DISPLAY || process.env.WAYLAND_DISPLAY;
|
|
3814
|
+
if (program) return viaCmd(program, [text]);
|
|
3815
|
+
if (WINDOWS) {
|
|
3816
|
+
// No windowsHide: its SW_HIDE would apply to the box, the first window PowerShell shows.
|
|
3817
|
+
const script = Buffer.from(POWERSHELL_WINDOW, "utf16le").toString("base64");
|
|
3818
|
+
return [
|
|
3819
|
+
"powershell.exe",
|
|
3820
|
+
["-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand", script],
|
|
3821
|
+
{ env: { ...process.env, PASSFORTH_WINDOW_TEXT: text } },
|
|
3822
|
+
];
|
|
3823
|
+
}
|
|
3824
|
+
if (process.platform === "darwin")
|
|
3825
|
+
return [
|
|
3826
|
+
"osascript",
|
|
3827
|
+
["-e", WINDOW_SCRIPT, text, String(WINDOW_WAIT_S)],
|
|
3828
|
+
{},
|
|
3829
|
+
];
|
|
3830
|
+
if (screen && which("zenity"))
|
|
3831
|
+
return [
|
|
3832
|
+
"zenity",
|
|
3833
|
+
[
|
|
3834
|
+
"--entry",
|
|
3835
|
+
"--hide-text",
|
|
3836
|
+
"--title=Passforth",
|
|
3837
|
+
`--text=${text}`,
|
|
3838
|
+
`--timeout=${WINDOW_WAIT_S}`,
|
|
3839
|
+
],
|
|
3840
|
+
{},
|
|
3841
|
+
];
|
|
3842
|
+
if (screen && which("kdialog"))
|
|
3843
|
+
return ["kdialog", ["--title", "Passforth", "--password", text], {}];
|
|
3844
|
+
return null;
|
|
3845
|
+
}
|
|
3846
|
+
|
|
3847
|
+
function askWindow(text) {
|
|
3848
|
+
// A passphrase typed into a window on the developer's screen, never through the agent that ran the command: macOS's
|
|
3849
|
+
// dialog, Windows' WinForms box, or zenity or kdialog on a Linux desktop. $PASSFORTH_ASKPASS names another program
|
|
3850
|
+
// that prints the answer, as $SSH_ASKPASS does for ssh.
|
|
3851
|
+
const command = windowCommand(text);
|
|
3852
|
+
if (!command) throw new NoScreen();
|
|
3853
|
+
const [program, args, options] = command;
|
|
3854
|
+
const ran = spawnSync(program, args, {
|
|
3855
|
+
...options,
|
|
3856
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3857
|
+
encoding: "utf8",
|
|
3858
|
+
timeout: (WINDOW_WAIT_S + 15) * 1000,
|
|
3859
|
+
});
|
|
3860
|
+
if (ran.error && ran.error.code !== "ETIMEDOUT") throw new NoScreen();
|
|
3861
|
+
if (ran.error || ran.status !== 0) {
|
|
3862
|
+
throw new NotFinished(
|
|
3863
|
+
"the passphrase window closed without an answer. Run the same command again to open it again.",
|
|
3864
|
+
);
|
|
3865
|
+
}
|
|
3866
|
+
// Read as Python's text mode reads it, without the one newline it ends with.
|
|
3867
|
+
return ran.stdout.replace(/\r\n?/g, "\n").replace(/\n$/, "");
|
|
3868
|
+
}
|
|
3869
|
+
|
|
3870
|
+
const askPassphrase = (prompt, window, terminal) =>
|
|
3871
|
+
terminal ? getpass(`${indent}${prompt}`) : askWindow(window);
|
|
3872
|
+
|
|
3555
3873
|
// A line typed at a file descriptor, without its newline; null at its end.
|
|
3556
3874
|
function fdLine(fd) {
|
|
3557
3875
|
const got = [];
|
|
@@ -3571,11 +3889,60 @@ function fdLine(fd) {
|
|
|
3571
3889
|
}
|
|
3572
3890
|
}
|
|
3573
3891
|
|
|
3574
|
-
// input(): a line from stdin, or EOFError.
|
|
3892
|
+
// input(): a line from stdin, or EOFError. Windows ends one with "\r\n", which Python's text mode reads as "\n".
|
|
3575
3893
|
function stdinLine() {
|
|
3576
3894
|
const line = fdLine(0);
|
|
3577
3895
|
if (line === null) throw new EOFError("EOF when reading a line");
|
|
3578
|
-
return line;
|
|
3896
|
+
return WINDOWS ? line.replace(/\r$/, "") : line;
|
|
3897
|
+
}
|
|
3898
|
+
|
|
3899
|
+
// Windows' console has no /dev/tty or stty: a hidden line is read in raw mode, as Python's win_getpass reads it (Enter
|
|
3900
|
+
// ends it, Backspace takes a character back, Ctrl+C leaves with 130), and the console's mode is put back.
|
|
3901
|
+
function consoleHidden(prompt) {
|
|
3902
|
+
return new Promise((done) => {
|
|
3903
|
+
const stdin = process.stdin;
|
|
3904
|
+
let line = "";
|
|
3905
|
+
const onData = (chunk) => {
|
|
3906
|
+
for (const ch of chunk) {
|
|
3907
|
+
if (ch === "\u0003") {
|
|
3908
|
+
stdin.setRawMode(false);
|
|
3909
|
+
process.exit(130);
|
|
3910
|
+
}
|
|
3911
|
+
if (ch === "\r" || ch === "\n") {
|
|
3912
|
+
stdin.removeListener("data", onData);
|
|
3913
|
+
stdin.setRawMode(false);
|
|
3914
|
+
stdin.pause();
|
|
3915
|
+
process.stderr.write("\n");
|
|
3916
|
+
done(line);
|
|
3917
|
+
return;
|
|
3918
|
+
}
|
|
3919
|
+
line =
|
|
3920
|
+
ch === "\b" || ch === "\u007f"
|
|
3921
|
+
? Array.from(line).slice(0, -1).join("")
|
|
3922
|
+
: line + ch;
|
|
3923
|
+
}
|
|
3924
|
+
};
|
|
3925
|
+
process.stderr.write(prompt);
|
|
3926
|
+
stdin.setEncoding("utf8");
|
|
3927
|
+
stdin.setRawMode(true);
|
|
3928
|
+
stdin.on("data", onData);
|
|
3929
|
+
stdin.resume();
|
|
3930
|
+
});
|
|
3931
|
+
}
|
|
3932
|
+
|
|
3933
|
+
// A visible line typed at Windows' console, readline doing the echo and the editing.
|
|
3934
|
+
function consoleLine(prompt) {
|
|
3935
|
+
return new Promise((done) => {
|
|
3936
|
+
const reader = createInterface({
|
|
3937
|
+
input: process.stdin,
|
|
3938
|
+
output: process.stderr,
|
|
3939
|
+
});
|
|
3940
|
+
reader.on("SIGINT", () => process.exit(130));
|
|
3941
|
+
reader.question(prompt, (answer) => {
|
|
3942
|
+
reader.close();
|
|
3943
|
+
done(answer);
|
|
3944
|
+
});
|
|
3945
|
+
});
|
|
3579
3946
|
}
|
|
3580
3947
|
|
|
3581
3948
|
// The terminal's echo goes off for the line, and comes back on even after a Ctrl-C.
|
|
@@ -3586,6 +3953,7 @@ const HIDDEN_READ =
|
|
|
3586
3953
|
function getpass(prompt) {
|
|
3587
3954
|
// getpass.getpass: read at the terminal with its echo off, never from stdin, which send may use for the message.
|
|
3588
3955
|
// With no terminal at all, Python falls back to stdin with a warning, and so does this.
|
|
3956
|
+
if (WINDOWS && process.stdin.isTTY) return consoleHidden(prompt);
|
|
3589
3957
|
let tty;
|
|
3590
3958
|
try {
|
|
3591
3959
|
tty = openSync("/dev/tty", "r+");
|
|
@@ -3611,12 +3979,20 @@ function getpass(prompt) {
|
|
|
3611
3979
|
}
|
|
3612
3980
|
|
|
3613
3981
|
function ttyInput(prompt) {
|
|
3982
|
+
if (WINDOWS && process.stdin.isTTY) return consoleLine(prompt).then(strip);
|
|
3614
3983
|
let tty;
|
|
3615
3984
|
try {
|
|
3616
3985
|
tty = openSync("/dev/tty", "r");
|
|
3617
3986
|
} catch {
|
|
3618
3987
|
writeSync(1, prompt);
|
|
3619
|
-
|
|
3988
|
+
try {
|
|
3989
|
+
return stdinLine();
|
|
3990
|
+
} catch (error) {
|
|
3991
|
+
if (!(error instanceof EOFError)) throw error;
|
|
3992
|
+
throw new SystemExit(
|
|
3993
|
+
"passforth: this asks you to type an answer, so run it in a terminal.",
|
|
3994
|
+
);
|
|
3995
|
+
}
|
|
3620
3996
|
}
|
|
3621
3997
|
try {
|
|
3622
3998
|
writeSync(2, prompt);
|
|
@@ -3636,7 +4012,7 @@ function claudeDirs() {
|
|
|
3636
4012
|
if (
|
|
3637
4013
|
(name === ".claude" || name.startsWith(".claude-")) &&
|
|
3638
4014
|
isDir(full) &&
|
|
3639
|
-
!found.
|
|
4015
|
+
!found.some((other) => samePath(other, full))
|
|
3640
4016
|
)
|
|
3641
4017
|
found.push(full);
|
|
3642
4018
|
}
|
|
@@ -3658,17 +4034,80 @@ const runner = () => (process.versions.bun && !which("node") ? "bun" : "node");
|
|
|
3658
4034
|
const hookCommand = (event) =>
|
|
3659
4035
|
`${runner()} ${shq(path("passforth.mjs"))} hook ${event}`;
|
|
3660
4036
|
|
|
3661
|
-
|
|
3662
|
-
|
|
4037
|
+
// Claude Code accounts whose MCP server connect couldn't add itself (no claude on PATH, or its add failed): connect
|
|
4038
|
+
// prints mcpHint for each.
|
|
4039
|
+
const MCP_BY_HAND = [];
|
|
4040
|
+
|
|
4041
|
+
export function mcpHint(directory) {
|
|
4042
|
+
const label = accountLabel(directory);
|
|
4043
|
+
return WINDOWS
|
|
4044
|
+
? `Add the MCP server yourself: $env:CLAUDE_CONFIG_DIR="${directory}"; claude mcp add -s user passforth ` +
|
|
4045
|
+
`-e PASSFORTH_ACCOUNT=${label} -- ${runner()} "${path("passforth.mjs")}" mcp`
|
|
4046
|
+
: `Add the MCP server yourself: CLAUDE_CONFIG_DIR=${directory} claude mcp add -s user passforth ` +
|
|
4047
|
+
`-e PASSFORTH_ACCOUNT=${label} -- ${runner()} ${path("passforth.mjs")} mcp`;
|
|
4048
|
+
}
|
|
4049
|
+
|
|
4050
|
+
export function ours(group) {
|
|
4051
|
+
// Passforth's entries from either client (passforth.py or passforth.mjs), as one line or in exec form, whose command
|
|
4052
|
+
// and args read as one line: each connect replaces the other's, and disconnect finds them all.
|
|
3663
4053
|
return (get(group, "hooks", []) ?? []).some((h) => {
|
|
3664
4054
|
const command = str(get(h, "command", ""));
|
|
4055
|
+
const args = orElse(get(h, "args", null), []);
|
|
4056
|
+
const line = [command, ...(Array.isArray(args) ? args.map(str) : [])].join(
|
|
4057
|
+
" ",
|
|
4058
|
+
);
|
|
3665
4059
|
return (
|
|
3666
4060
|
command.includes("/huddle/hook.sh") ||
|
|
3667
|
-
/passforth\.(py|mjs)\b.* hook /.test(
|
|
4061
|
+
/passforth\.(py|mjs)\b.* hook /.test(`${line} `)
|
|
3668
4062
|
);
|
|
3669
4063
|
});
|
|
3670
4064
|
}
|
|
3671
4065
|
|
|
4066
|
+
// The six hooks connect writes into a Claude Code account, as [event, group]. On Windows each is in exec form, which
|
|
4067
|
+
// Claude Code spawns with no shell (Git Bash is optional there); elsewhere it's the one line every Claude Code reads.
|
|
4068
|
+
export function hookEntries() {
|
|
4069
|
+
const entry = (event, extra) =>
|
|
4070
|
+
WINDOWS
|
|
4071
|
+
? {
|
|
4072
|
+
type: "command",
|
|
4073
|
+
command: runner(),
|
|
4074
|
+
args: [path("passforth.mjs"), "hook", event],
|
|
4075
|
+
...extra,
|
|
4076
|
+
}
|
|
4077
|
+
: { type: "command", command: hookCommand(event), ...extra };
|
|
4078
|
+
return [
|
|
4079
|
+
["SessionStart", { hooks: [entry("SessionStart", { timeout: 10 })] }],
|
|
4080
|
+
[
|
|
4081
|
+
"UserPromptSubmit",
|
|
4082
|
+
{ hooks: [entry("UserPromptSubmit", { timeout: 10 })] },
|
|
4083
|
+
],
|
|
4084
|
+
[
|
|
4085
|
+
"PostToolUse",
|
|
4086
|
+
{ matcher: "*", hooks: [entry("PostToolUse", { timeout: 10 })] },
|
|
4087
|
+
],
|
|
4088
|
+
[
|
|
4089
|
+
"PreToolUse",
|
|
4090
|
+
{
|
|
4091
|
+
matcher: "mcp__passforth__(open|send|reply)",
|
|
4092
|
+
hooks: [entry("PreToolUse", { timeout: 20 })],
|
|
4093
|
+
},
|
|
4094
|
+
],
|
|
4095
|
+
[
|
|
4096
|
+
"Stop",
|
|
4097
|
+
{
|
|
4098
|
+
hooks: [
|
|
4099
|
+
entry("Stop", {
|
|
4100
|
+
timeout: WAIT_TOTAL_S + 60,
|
|
4101
|
+
async: true,
|
|
4102
|
+
asyncRewake: true,
|
|
4103
|
+
}),
|
|
4104
|
+
],
|
|
4105
|
+
},
|
|
4106
|
+
],
|
|
4107
|
+
["SessionEnd", { hooks: [entry("SessionEnd", { timeout: 5 })] }],
|
|
4108
|
+
];
|
|
4109
|
+
}
|
|
4110
|
+
|
|
3672
4111
|
function pluginEnabled(settings) {
|
|
3673
4112
|
// Claude Code loads Passforth's hooks and server from its plugin in this folder.
|
|
3674
4113
|
const enabled = settings.enabledPlugins;
|
|
@@ -3709,37 +4148,10 @@ export function configure(directory, addHooks) {
|
|
|
3709
4148
|
for (const name of ["PASSFORTH_SECRET", "PASSFORTH_URL", "PASSFORTH_ACCOUNT"])
|
|
3710
4149
|
delete env[name];
|
|
3711
4150
|
if (add) {
|
|
3712
|
-
const
|
|
3713
|
-
type: "command",
|
|
3714
|
-
command: hookCommand(event),
|
|
3715
|
-
...extra,
|
|
3716
|
-
});
|
|
3717
|
-
const append = (event, group) => {
|
|
4151
|
+
for (const [event, group] of hookEntries()) {
|
|
3718
4152
|
hooks[event] ??= [];
|
|
3719
4153
|
hooks[event].push(group);
|
|
3720
|
-
}
|
|
3721
|
-
append("SessionStart", { hooks: [entry("SessionStart", { timeout: 10 })] });
|
|
3722
|
-
append("UserPromptSubmit", {
|
|
3723
|
-
hooks: [entry("UserPromptSubmit", { timeout: 10 })],
|
|
3724
|
-
});
|
|
3725
|
-
append("PostToolUse", {
|
|
3726
|
-
matcher: "*",
|
|
3727
|
-
hooks: [entry("PostToolUse", { timeout: 10 })],
|
|
3728
|
-
});
|
|
3729
|
-
append("PreToolUse", {
|
|
3730
|
-
matcher: "mcp__passforth__(open|send|reply)",
|
|
3731
|
-
hooks: [entry("PreToolUse", { timeout: 20 })],
|
|
3732
|
-
});
|
|
3733
|
-
append("Stop", {
|
|
3734
|
-
hooks: [
|
|
3735
|
-
entry("Stop", {
|
|
3736
|
-
timeout: WAIT_TOTAL_S + 60,
|
|
3737
|
-
async: true,
|
|
3738
|
-
asyncRewake: true,
|
|
3739
|
-
}),
|
|
3740
|
-
],
|
|
3741
|
-
});
|
|
3742
|
-
append("SessionEnd", { hooks: [entry("SessionEnd", { timeout: 5 })] });
|
|
4154
|
+
}
|
|
3743
4155
|
env.PASSFORTH_ACCOUNT = accountLabel(directory);
|
|
3744
4156
|
}
|
|
3745
4157
|
for (const [name, value] of [
|
|
@@ -3753,42 +4165,66 @@ export function configure(directory, addHooks) {
|
|
|
3753
4165
|
saveWithBackup(settingsPath, `${dumps(settings, { indent: 2 })}\n`);
|
|
3754
4166
|
// The legacy curl hook and its folder, from before end-to-end encryption.
|
|
3755
4167
|
removeTree(pjoin(directory, "huddle"));
|
|
3756
|
-
const claude =
|
|
3757
|
-
const server = [runner(), path("passforth.mjs"), "mcp"];
|
|
4168
|
+
const claude = claudeCommand();
|
|
3758
4169
|
if (!claude) {
|
|
3759
|
-
if (add)
|
|
3760
|
-
eprint(
|
|
3761
|
-
` add the MCP server yourself: CLAUDE_CONFIG_DIR=${directory} claude mcp add -s user passforth ` +
|
|
3762
|
-
`-e PASSFORTH_ACCOUNT=${accountLabel(directory)} -- ${server.join(" ")}`,
|
|
3763
|
-
);
|
|
3764
|
-
}
|
|
4170
|
+
if (add) MCP_BY_HAND.push(directory);
|
|
3765
4171
|
return add;
|
|
3766
4172
|
}
|
|
4173
|
+
const server = [runner(), path("passforth.mjs"), "mcp"];
|
|
3767
4174
|
const envVars = { ...process.env, CLAUDE_CONFIG_DIR: directory };
|
|
3768
|
-
|
|
3769
|
-
env: envVars,
|
|
3770
|
-
stdio: "ignore",
|
|
3771
|
-
});
|
|
4175
|
+
runClaude(claude, ["mcp", "remove", "passforth", "-s", "user"], envVars);
|
|
3772
4176
|
if (add) {
|
|
3773
|
-
|
|
4177
|
+
// The name before -e, which takes every value up to the next option: after it, the name was taken for one.
|
|
4178
|
+
const added = runClaude(
|
|
3774
4179
|
claude,
|
|
3775
4180
|
[
|
|
3776
4181
|
"mcp",
|
|
3777
4182
|
"add",
|
|
3778
4183
|
"-s",
|
|
3779
4184
|
"user",
|
|
4185
|
+
"passforth",
|
|
3780
4186
|
"-e",
|
|
3781
4187
|
`PASSFORTH_ACCOUNT=${accountLabel(directory)}`,
|
|
3782
|
-
"passforth",
|
|
3783
4188
|
"--",
|
|
3784
4189
|
...server,
|
|
3785
4190
|
],
|
|
3786
|
-
|
|
4191
|
+
envVars,
|
|
3787
4192
|
);
|
|
4193
|
+
if (added.status !== 0) MCP_BY_HAND.push(directory);
|
|
3788
4194
|
}
|
|
3789
4195
|
return add;
|
|
3790
4196
|
}
|
|
3791
4197
|
|
|
4198
|
+
// Claude Code on Windows: the native installer's claude.exe, else a claude.exe on PATH, else npm's claude.cmd.
|
|
4199
|
+
function windowsClaude() {
|
|
4200
|
+
const native = pjoin(
|
|
4201
|
+
process.env.USERPROFILE || homedir(),
|
|
4202
|
+
".local",
|
|
4203
|
+
"bin",
|
|
4204
|
+
"claude.exe",
|
|
4205
|
+
);
|
|
4206
|
+
return isFile(native) ? native : (which("claude.exe") ?? which("claude.cmd"));
|
|
4207
|
+
}
|
|
4208
|
+
|
|
4209
|
+
const claudeCommand = () => (WINDOWS ? windowsClaude() : which("claude"));
|
|
4210
|
+
|
|
4211
|
+
// A .cmd or .bat runs only through cmd.exe, which Node won't do itself: every argument quoted, and the whole line quoted
|
|
4212
|
+
// once more, since /s takes the first and last quote off it (as Node's own shell option does).
|
|
4213
|
+
function viaCmd(program, args) {
|
|
4214
|
+
if (!WINDOWS || !/\.(cmd|bat)$/i.test(program)) return [program, args, {}];
|
|
4215
|
+
const line = [program, ...args].map((arg) => `"${arg}"`).join(" ");
|
|
4216
|
+
return [
|
|
4217
|
+
process.env.ComSpec || "cmd.exe",
|
|
4218
|
+
["/d", "/s", "/c", `"${line}"`],
|
|
4219
|
+
{ windowsVerbatimArguments: true },
|
|
4220
|
+
];
|
|
4221
|
+
}
|
|
4222
|
+
|
|
4223
|
+
function runClaude(claude, args, env) {
|
|
4224
|
+
const [program, argv, options] = viaCmd(claude, args);
|
|
4225
|
+
return spawnSync(program, argv, { env, stdio: "ignore", ...options });
|
|
4226
|
+
}
|
|
4227
|
+
|
|
3792
4228
|
function saveWithBackup(target, content) {
|
|
3793
4229
|
// The file as it was goes beside it as <name>.before-passforth; the new one replaces it in one step. A symlink (a
|
|
3794
4230
|
// dotfiles checkout) is written through, so it stays a link to the user's own copy.
|
|
@@ -3797,7 +4233,7 @@ function saveWithBackup(target, content) {
|
|
|
3797
4233
|
writeFileSync(`${real}.before-passforth`, readText(real), { mode: 0o600 });
|
|
3798
4234
|
const tmp = `${real}.passforth-tmp`;
|
|
3799
4235
|
writeFileSync(tmp, content, { mode: 0o600 });
|
|
3800
|
-
|
|
4236
|
+
replaceFile(tmp, real);
|
|
3801
4237
|
}
|
|
3802
4238
|
|
|
3803
4239
|
// Codex (ADR-0014): one home per account, $CODEX_HOME or ~/.codex, each with its config.toml and hooks.json. Passforth
|
|
@@ -3819,7 +4255,8 @@ function codexHomes() {
|
|
|
3819
4255
|
pjoin(homedir(), ".codex"),
|
|
3820
4256
|
]) {
|
|
3821
4257
|
const full = candidate ? resolve(expanduser(candidate)) : "";
|
|
3822
|
-
if (full && isDir(full) && !found.
|
|
4258
|
+
if (full && isDir(full) && !found.some((other) => samePath(other, full)))
|
|
4259
|
+
found.push(full);
|
|
3823
4260
|
}
|
|
3824
4261
|
return found;
|
|
3825
4262
|
}
|
|
@@ -3870,6 +4307,13 @@ function tomlParses(text) {
|
|
|
3870
4307
|
}
|
|
3871
4308
|
|
|
3872
4309
|
export function configureCodex(home, add) {
|
|
4310
|
+
if (WINDOWS && add) {
|
|
4311
|
+
// Codex's hooks here are POSIX lines with env prefixes; on Windows it gets Passforth through WSL (ADR-0017).
|
|
4312
|
+
eprint(
|
|
4313
|
+
"passforth: Codex on Windows isn't supported yet; run Passforth inside WSL for Codex.",
|
|
4314
|
+
);
|
|
4315
|
+
return false;
|
|
4316
|
+
}
|
|
3873
4317
|
const hooksPath = pjoin(home, "hooks.json");
|
|
3874
4318
|
const configPath = pjoin(home, "config.toml");
|
|
3875
4319
|
let current;
|
|
@@ -3975,30 +4419,100 @@ async function deviceCollect(url, deviceCode) {
|
|
|
3975
4419
|
return answer;
|
|
3976
4420
|
}
|
|
3977
4421
|
|
|
3978
|
-
async function linkByCode(url) {
|
|
3979
|
-
// The
|
|
3980
|
-
|
|
3981
|
-
|
|
3982
|
-
|
|
3983
|
-
|
|
3984
|
-
|
|
3985
|
-
`It runs out in ${Math.floor(pyInt(grant.expiresIn) / 60)} minutes. Waiting…`,
|
|
4422
|
+
async function linkByCode(url, terminal) {
|
|
4423
|
+
// The code waits in device.json (shared with /passforth:login), so a run that stops for its developer's approval
|
|
4424
|
+
// carries on with the same code next time. A terminal's run waits for the approval at once; an agent's run stops
|
|
4425
|
+
// first, so the agent can tell its developer, and its next run waits.
|
|
4426
|
+
let pending = readJson("device.json");
|
|
4427
|
+
const fresh = !(
|
|
4428
|
+
truthy(pending) && Number(pending.expiresAt ?? 0) > now() + 30
|
|
3986
4429
|
);
|
|
3987
|
-
|
|
3988
|
-
|
|
3989
|
-
|
|
3990
|
-
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
|
|
3995
|
-
|
|
3996
|
-
|
|
4430
|
+
if (fresh) {
|
|
4431
|
+
const grant = await deviceStart(url);
|
|
4432
|
+
pending = {
|
|
4433
|
+
deviceCode: grant.deviceCode,
|
|
4434
|
+
userCode: grant.userCode,
|
|
4435
|
+
uri: grant.verificationUri,
|
|
4436
|
+
expiresAt: now() + pyInt(grant.expiresIn),
|
|
4437
|
+
interval: pyInt(orElse(grant.interval, 5)),
|
|
4438
|
+
};
|
|
4439
|
+
writeJson("device.json", pending);
|
|
4440
|
+
}
|
|
4441
|
+
const page = `${pending.uri}?code=${pending.userCode}`;
|
|
4442
|
+
say(`${paint("Open", "2")} ${paint(page, "1")}`);
|
|
4443
|
+
say(`${paint("Code", "2")} ${paint(str(pending.userCode), "1")}`);
|
|
4444
|
+
if (fresh && openBrowser(page)) say(paint("Opened it in your browser.", "2"));
|
|
4445
|
+
if (fresh && !terminal) {
|
|
4446
|
+
throw new NotFinished(
|
|
4447
|
+
"ask the user to approve this machine at that page, signing in if asked, then run the same command again.",
|
|
4448
|
+
);
|
|
4449
|
+
}
|
|
4450
|
+
return waitForApproval(url, pending, page, terminal);
|
|
4451
|
+
}
|
|
4452
|
+
|
|
4453
|
+
async function waitForApproval(url, pending, page, terminal) {
|
|
4454
|
+
// A terminal waits the code's whole life, a spinner turning; an agent's run waits AGENT_WAIT_S, then stops again.
|
|
4455
|
+
// Each wait between frames and each poll is awaited, so a Ctrl+C is heard mid-spin, and the cursor comes back first.
|
|
4456
|
+
const expires = Number(pending.expiresAt);
|
|
4457
|
+
const deadline = terminal ? expires : Math.min(expires, now() + AGENT_WAIT_S);
|
|
4458
|
+
const interval = Math.max(1, pyInt(orElse(pending.interval, 5)));
|
|
4459
|
+
const who = terminal ? "you" : "the user";
|
|
4460
|
+
const spinning = styled();
|
|
4461
|
+
const frames = drawsUnicode() ? SPIN : "|/-\\";
|
|
4462
|
+
const interrupted = () =>
|
|
4463
|
+
process.stdout.write("\r\x1b[2K\x1b[?25h", () => process.exit(130));
|
|
4464
|
+
if (!spinning) say(`Waiting for ${who} to approve it…`);
|
|
4465
|
+
let polled = 0;
|
|
4466
|
+
let turn = 0;
|
|
4467
|
+
try {
|
|
4468
|
+
if (spinning) {
|
|
4469
|
+
process.on("SIGINT", interrupted);
|
|
4470
|
+
out("\x1b[?25l");
|
|
3997
4471
|
}
|
|
3998
|
-
|
|
4472
|
+
while (now() < deadline) {
|
|
4473
|
+
if (spinning) {
|
|
4474
|
+
const left = Math.max(0, Math.trunc(expires - now()));
|
|
4475
|
+
const time = `· ${Math.floor(left / 60)}:${String(left % 60).padStart(2, "0")} left`;
|
|
4476
|
+
out(
|
|
4477
|
+
`\r\x1b[2K${indent}${paint(frames[turn % frames.length], "32")} Waiting for ${who} to approve it ${paint(time, "2")}`,
|
|
4478
|
+
);
|
|
4479
|
+
turn += 1;
|
|
4480
|
+
}
|
|
4481
|
+
if (now() - polled >= interval) {
|
|
4482
|
+
polled = now();
|
|
4483
|
+
let answer;
|
|
4484
|
+
try {
|
|
4485
|
+
answer = await deviceCollect(url, str(pending.deviceCode));
|
|
4486
|
+
} catch (error) {
|
|
4487
|
+
if (!(error instanceof RelayError)) throw error;
|
|
4488
|
+
if (error.status !== 0) {
|
|
4489
|
+
// Denied, expired or used: the code is dead, so the next run starts a new one.
|
|
4490
|
+
remove(path("device.json"));
|
|
4491
|
+
throw new SystemExit(`passforth: ${error.message}`);
|
|
4492
|
+
}
|
|
4493
|
+
answer = {};
|
|
4494
|
+
}
|
|
4495
|
+
if (get(answer, "status") === "approved") {
|
|
4496
|
+
unlinkSync(path("device.json"));
|
|
4497
|
+
return str(answer.secret);
|
|
4498
|
+
}
|
|
4499
|
+
}
|
|
4500
|
+
await sleep(spinning ? 80 : 500);
|
|
4501
|
+
}
|
|
4502
|
+
} finally {
|
|
4503
|
+
if (spinning) {
|
|
4504
|
+
process.removeListener("SIGINT", interrupted);
|
|
4505
|
+
out("\r\x1b[2K\x1b[?25h");
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
4508
|
+
if (now() >= expires) {
|
|
4509
|
+
remove(path("device.json"));
|
|
4510
|
+
throw new SystemExit(
|
|
4511
|
+
"passforth: the code ran out before it was approved; run connect again.",
|
|
4512
|
+
);
|
|
3999
4513
|
}
|
|
4000
|
-
throw new
|
|
4001
|
-
|
|
4514
|
+
throw new NotFinished(
|
|
4515
|
+
`the user hasn't approved it yet. Ask them to open ${page}, then run the same command again.`,
|
|
4002
4516
|
);
|
|
4003
4517
|
}
|
|
4004
4518
|
|
|
@@ -4022,7 +4536,7 @@ async function logoutNow() {
|
|
|
4022
4536
|
for (const name of ["secret", "key.json", "device.json"]) remove(path(name));
|
|
4023
4537
|
return (
|
|
4024
4538
|
"Logged out: this machine's secret is revoked, and its key is gone from it. /passforth:login, or " +
|
|
4025
|
-
`${
|
|
4539
|
+
`${hereCommand("login")} in a terminal, links it again.`
|
|
4026
4540
|
);
|
|
4027
4541
|
}
|
|
4028
4542
|
|
|
@@ -4044,6 +4558,12 @@ function commandArchive(argv) {
|
|
|
4044
4558
|
|
|
4045
4559
|
export function terminalYes(question) {
|
|
4046
4560
|
// A yes typed at this terminal, never read from stdin, which may be the message itself. No terminal: no.
|
|
4561
|
+
if (WINDOWS) {
|
|
4562
|
+
if (!process.stdin.isTTY) return false;
|
|
4563
|
+
return consoleLine(question).then((answer) =>
|
|
4564
|
+
["y", "yes"].includes(strip(answer).toLowerCase()),
|
|
4565
|
+
);
|
|
4566
|
+
}
|
|
4047
4567
|
let tty;
|
|
4048
4568
|
try {
|
|
4049
4569
|
tty = openSync("/dev/tty", "r+");
|
|
@@ -4187,9 +4707,10 @@ async function commandSend(argv) {
|
|
|
4187
4707
|
const opts = parseSend(argv);
|
|
4188
4708
|
if (!opts.text.length && isatty(0))
|
|
4189
4709
|
throw sendError("give the message as TEXT, or pipe it in");
|
|
4710
|
+
const piped = opts.text.length ? "" : await readStdin();
|
|
4190
4711
|
const text = opts.text.length
|
|
4191
4712
|
? opts.text.join(" ")
|
|
4192
|
-
: (
|
|
4713
|
+
: (WINDOWS ? piped.replace(/\r\n?/g, "\n") : piped).replace(/\n+$/, "");
|
|
4193
4714
|
const args = {
|
|
4194
4715
|
to: opts.to,
|
|
4195
4716
|
kind: opts.kind,
|
|
@@ -4210,9 +4731,9 @@ async function commandSend(argv) {
|
|
|
4210
4731
|
if (to !== null && !opts.yes) {
|
|
4211
4732
|
const listing = fileListing(picked);
|
|
4212
4733
|
if (
|
|
4213
|
-
!terminalYes(
|
|
4734
|
+
!(await terminalYes(
|
|
4214
4735
|
`Send ${filesLine(picked)} to ${to}, sealed end to end? ${listing} [y/N] `,
|
|
4215
|
-
)
|
|
4736
|
+
))
|
|
4216
4737
|
) {
|
|
4217
4738
|
throw new RelayError(
|
|
4218
4739
|
0,
|
|
@@ -4245,9 +4766,9 @@ function commandShareBranch(argv) {
|
|
|
4245
4766
|
function install() {
|
|
4246
4767
|
// npx, bunx and their kind run this file from a cache that comes and goes: the hooks run a copy that stays.
|
|
4247
4768
|
const target = path("passforth.mjs");
|
|
4248
|
-
if (realpath(target)
|
|
4769
|
+
if (!samePath(realpath(target), THIS))
|
|
4249
4770
|
writePrivate("passforth.mjs", readFileSync(THIS));
|
|
4250
|
-
HERE =
|
|
4771
|
+
HERE = quoteHere(target);
|
|
4251
4772
|
}
|
|
4252
4773
|
|
|
4253
4774
|
async function commandConnect(argv) {
|
|
@@ -4272,101 +4793,181 @@ async function commandConnect(argv) {
|
|
|
4272
4793
|
) {
|
|
4273
4794
|
throw new SystemExit("passforth: connect needs --url https://…");
|
|
4274
4795
|
}
|
|
4275
|
-
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
);
|
|
4284
|
-
if (!token) token = await linkByCode(url);
|
|
4285
|
-
if (!token.startsWith("hk_live_")) {
|
|
4286
|
-
throw new SystemExit(
|
|
4287
|
-
"passforth: that isn't a machine secret; make one on the dashboard's Machines page.",
|
|
4796
|
+
const terminal = hasTerminal();
|
|
4797
|
+
header("connect this machine");
|
|
4798
|
+
step(1, "Link this machine");
|
|
4799
|
+
let [token, me] = await linkedAlready(url);
|
|
4800
|
+
if (truthy(me)) {
|
|
4801
|
+
say(
|
|
4802
|
+
`Already linked as ${paint(`@${me.handle}`, "1")} (${me.machineLabel})`,
|
|
4803
|
+
"ok",
|
|
4288
4804
|
);
|
|
4805
|
+
} else {
|
|
4806
|
+
token =
|
|
4807
|
+
argv.includes("--code") || !terminal
|
|
4808
|
+
? ""
|
|
4809
|
+
: strip(
|
|
4810
|
+
await getpass(
|
|
4811
|
+
`${indent}Paste this machine's secret, or press Enter for a code (it won't show): `,
|
|
4812
|
+
),
|
|
4813
|
+
);
|
|
4814
|
+
if (!token) token = await linkByCode(url, terminal);
|
|
4815
|
+
if (!token.startsWith("hk_live_")) {
|
|
4816
|
+
throw new SystemExit(
|
|
4817
|
+
"passforth: that isn't a machine secret; make one on the dashboard's Machines page.",
|
|
4818
|
+
);
|
|
4819
|
+
}
|
|
4820
|
+
// Kept the moment it arrives: a code's secret is handed over once, so a run that stops after the approval (a
|
|
4821
|
+
// slow /me, say) carries on with this link next time instead of asking for another.
|
|
4822
|
+
writePrivate("secret", `${token}\n`);
|
|
4823
|
+
writeJson("config.json", { url, accounts: [] });
|
|
4824
|
+
[, me] = await relay("GET", "me", { token, url });
|
|
4825
|
+
writeJson("config.json", {
|
|
4826
|
+
url,
|
|
4827
|
+
userId: me.userId,
|
|
4828
|
+
handle: me.handle,
|
|
4829
|
+
accounts: [],
|
|
4830
|
+
});
|
|
4831
|
+
say(`Linked as ${paint(`@${me.handle}`, "1")} (${me.machineLabel})`, "ok");
|
|
4289
4832
|
}
|
|
4290
|
-
const [, me] = await relay("GET", "me", { token, url });
|
|
4291
|
-
print(`Connecting this machine as @${me.handle} (${me.machineLabel}).`);
|
|
4292
|
-
writePrivate("secret", `${token}\n`);
|
|
4293
|
-
writeJson("config.json", {
|
|
4294
|
-
url,
|
|
4295
|
-
userId: me.userId,
|
|
4296
|
-
handle: me.handle,
|
|
4297
|
-
accounts: [],
|
|
4298
|
-
});
|
|
4299
4833
|
install();
|
|
4300
|
-
await
|
|
4834
|
+
const stored = await storedKey(token, url);
|
|
4835
|
+
step(2, stored ? "Unlock your key" : "Choose your passphrase");
|
|
4836
|
+
const unlocked = await unlockOrCreate(token, url, me, terminal, stored);
|
|
4837
|
+
step(3, "Connect your AI tools");
|
|
4301
4838
|
const accounts = [];
|
|
4302
4839
|
for (const directory of claudeDirs()) {
|
|
4303
4840
|
if (configure(directory, true)) {
|
|
4304
4841
|
accounts.push(directory);
|
|
4305
|
-
|
|
4306
|
-
|
|
4842
|
+
say(
|
|
4843
|
+
`${toolLine("Claude Code", directory)} (${accountLabel(directory)})`,
|
|
4844
|
+
"ok",
|
|
4307
4845
|
);
|
|
4846
|
+
if (MCP_BY_HAND.includes(directory)) say(mcpHint(directory), "note");
|
|
4308
4847
|
} else {
|
|
4309
|
-
|
|
4310
|
-
|
|
4848
|
+
say(
|
|
4849
|
+
`${toolLine("Claude Code", directory)} (${accountLabel(directory)}), through its Passforth plugin`,
|
|
4850
|
+
"ok",
|
|
4311
4851
|
);
|
|
4312
4852
|
}
|
|
4313
4853
|
}
|
|
4314
4854
|
const homes = codexHomes().filter((home) => configureCodex(home, true));
|
|
4315
4855
|
for (const home of homes)
|
|
4316
|
-
|
|
4856
|
+
say(`${toolLine("Codex", home)} (${codexLabel(home)})`, "ok");
|
|
4317
4857
|
const cfg = config();
|
|
4318
4858
|
cfg.accounts = accounts;
|
|
4319
4859
|
cfg.codexHomes = homes;
|
|
4320
4860
|
writeJson("config.json", cfg);
|
|
4321
|
-
const key = ownKey();
|
|
4322
|
-
print(`Your key's fingerprint: ${fingerprint(key.publicBytes)}`);
|
|
4323
4861
|
if (homes.length)
|
|
4324
|
-
|
|
4862
|
+
say(
|
|
4325
4863
|
"In Codex, open /hooks once and trust Passforth's hooks: Codex runs them only after that.",
|
|
4864
|
+
"note",
|
|
4326
4865
|
);
|
|
4327
|
-
|
|
4328
|
-
|
|
4866
|
+
if (!unlocked) {
|
|
4867
|
+
finish(
|
|
4868
|
+
"Connected, but the key is still locked: run the unlock command above in a terminal on this machine, " +
|
|
4869
|
+
"then restart Claude Code or Codex.",
|
|
4870
|
+
"note",
|
|
4871
|
+
);
|
|
4872
|
+
return NOT_FINISHED;
|
|
4873
|
+
}
|
|
4874
|
+
finish(
|
|
4875
|
+
`Connected. ${terminal ? "Restart Claude Code or Codex to join." : "Ask the user to restart Claude Code or Codex to join."}`,
|
|
4329
4876
|
);
|
|
4330
|
-
|
|
4877
|
+
say(paint(`Remove it: ${hereCommand("disconnect")}`, "2"));
|
|
4331
4878
|
return 0;
|
|
4332
4879
|
}
|
|
4333
4880
|
|
|
4334
|
-
async function
|
|
4881
|
+
async function linkedAlready(url) {
|
|
4882
|
+
// A machine this relay already knows keeps its link, so connect runs again (an agent's next run, or after an
|
|
4883
|
+
// update) without linking a second machine.
|
|
4884
|
+
if (config().url !== url || !exists(path("secret"))) return ["", null];
|
|
4885
|
+
let me;
|
|
4886
|
+
try {
|
|
4887
|
+
[, me] = await relay("GET", "me", { timeout: 10 });
|
|
4888
|
+
} catch (error) {
|
|
4889
|
+
if (error instanceof RelayError && error.status === 401) return ["", null];
|
|
4890
|
+
throw error;
|
|
4891
|
+
}
|
|
4892
|
+
return [secret(), me];
|
|
4893
|
+
}
|
|
4894
|
+
|
|
4895
|
+
async function storedKey(token, url) {
|
|
4335
4896
|
let stored;
|
|
4336
4897
|
try {
|
|
4337
4898
|
[, stored] = await relay("GET", "keys/me", { token, url });
|
|
4338
4899
|
} catch (error) {
|
|
4339
4900
|
if (!(error instanceof RelayError) || error.status !== 404) throw error;
|
|
4340
|
-
|
|
4901
|
+
return null;
|
|
4341
4902
|
}
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4903
|
+
return truthy(stored) ? stored : null;
|
|
4904
|
+
}
|
|
4905
|
+
|
|
4906
|
+
async function unlockOrCreate(token, url, me, terminal, stored) {
|
|
4907
|
+
// True once the key is on this machine. False when there's neither a terminal nor a screen to ask on: its developer
|
|
4908
|
+
// runs unlock in a terminal later.
|
|
4909
|
+
const key = ownKey();
|
|
4910
|
+
if (
|
|
4911
|
+
stored &&
|
|
4912
|
+
key &&
|
|
4913
|
+
key.userId === me.userId &&
|
|
4914
|
+
key.public === stored.publicKey
|
|
4915
|
+
) {
|
|
4916
|
+
say(
|
|
4917
|
+
`Your key is already on this machine · ${fingerprint(key.publicBytes)}`,
|
|
4918
|
+
"ok",
|
|
4919
|
+
);
|
|
4920
|
+
return true;
|
|
4921
|
+
}
|
|
4922
|
+
if (!stored)
|
|
4923
|
+
say("It locks your key. Passforth never sees it and can't recover it.");
|
|
4924
|
+
if (!terminal)
|
|
4925
|
+
say(
|
|
4926
|
+
"Asking the user in a window on their screen: the passphrase never passes through here.",
|
|
4927
|
+
);
|
|
4928
|
+
let privateRaw;
|
|
4929
|
+
let passphrase;
|
|
4930
|
+
try {
|
|
4931
|
+
if (stored) {
|
|
4932
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
4933
|
+
const typed = await askPassphrase(
|
|
4934
|
+
"Your Passforth passphrase: ",
|
|
4935
|
+
`${attempt ? "That passphrase doesn't open your key. " : ""}Type your Passforth passphrase to unlock your key ` +
|
|
4936
|
+
"on this machine.",
|
|
4937
|
+
terminal,
|
|
4356
4938
|
);
|
|
4939
|
+
let opened;
|
|
4940
|
+
try {
|
|
4941
|
+
opened = unwrapPrivate(stored.wrap, typed, me.userId);
|
|
4942
|
+
} catch (error) {
|
|
4943
|
+
if (!valueish(error)) throw error;
|
|
4944
|
+
say("That passphrase doesn't open your key. Try again.", "note");
|
|
4945
|
+
continue;
|
|
4946
|
+
}
|
|
4947
|
+
if (b64(x25519Public(opened)) !== stored.publicKey) {
|
|
4948
|
+
throw new SystemExit(
|
|
4949
|
+
"passforth: the stored key doesn't match its public half; contact support.",
|
|
4950
|
+
);
|
|
4951
|
+
}
|
|
4952
|
+
saveKey(me, pyInt(stored.version), opened);
|
|
4953
|
+
say(`Key unlocked · ${fingerprint(x25519Public(opened))}`, "ok");
|
|
4954
|
+
return true;
|
|
4357
4955
|
}
|
|
4358
|
-
|
|
4359
|
-
|
|
4956
|
+
throw new SystemExit(
|
|
4957
|
+
`passforth: forgot it? ${hereCommand("reset-key")} makes a new one.`,
|
|
4958
|
+
);
|
|
4360
4959
|
}
|
|
4361
|
-
|
|
4362
|
-
|
|
4960
|
+
privateRaw = randomBytes(32);
|
|
4961
|
+
passphrase = await newPassphrase(terminal);
|
|
4962
|
+
} catch (error) {
|
|
4963
|
+
if (!(error instanceof NoScreen)) throw error;
|
|
4964
|
+
say(
|
|
4965
|
+
"No screen here to ask for the passphrase. Run this in a terminal on this machine:",
|
|
4966
|
+
"note",
|
|
4363
4967
|
);
|
|
4968
|
+
say(` ${hereCommand("unlock")}`);
|
|
4969
|
+
return false;
|
|
4364
4970
|
}
|
|
4365
|
-
print(
|
|
4366
|
-
"Choose a Passforth passphrase. It locks your key: Passforth never sees it and can't recover it.",
|
|
4367
|
-
);
|
|
4368
|
-
const privateRaw = randomBytes(32);
|
|
4369
|
-
const passphrase = newPassphrase();
|
|
4370
4971
|
const [, saved] = await relay("PUT", "keys/me", {
|
|
4371
4972
|
body: {
|
|
4372
4973
|
publicKey: b64(x25519Public(privateRaw)),
|
|
@@ -4377,17 +4978,30 @@ async function unlockOrCreate(token, url, me) {
|
|
|
4377
4978
|
url,
|
|
4378
4979
|
});
|
|
4379
4980
|
saveKey(me, pyInt(saved.version), privateRaw);
|
|
4981
|
+
say(`Key locked · ${fingerprint(x25519Public(privateRaw))}`, "ok");
|
|
4982
|
+
return true;
|
|
4380
4983
|
}
|
|
4381
4984
|
|
|
4382
|
-
function newPassphrase() {
|
|
4985
|
+
async function newPassphrase(terminal) {
|
|
4986
|
+
let warning = "";
|
|
4383
4987
|
for (;;) {
|
|
4384
|
-
const first =
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
4988
|
+
const first = await askPassphrase(
|
|
4989
|
+
"Passphrase (12 characters or more): ",
|
|
4990
|
+
`${warning}Choose a Passforth passphrase of 12 characters or more. It locks your key: Passforth never sees ` +
|
|
4991
|
+
"it and can't recover it.",
|
|
4992
|
+
terminal,
|
|
4993
|
+
);
|
|
4994
|
+
if (cpLen(first) < 12) warning = "Use 12 characters or more. ";
|
|
4995
|
+
else if (
|
|
4996
|
+
(await askPassphrase(
|
|
4997
|
+
"Again: ",
|
|
4998
|
+
"Type the same passphrase again.",
|
|
4999
|
+
terminal,
|
|
5000
|
+
)) === first
|
|
5001
|
+
)
|
|
5002
|
+
return first;
|
|
5003
|
+
else warning = "They didn't match. ";
|
|
5004
|
+
say(strip(warning), "note");
|
|
4391
5005
|
}
|
|
4392
5006
|
}
|
|
4393
5007
|
|
|
@@ -4402,20 +5016,32 @@ function saveKey(me, version, privateRaw) {
|
|
|
4402
5016
|
}
|
|
4403
5017
|
|
|
4404
5018
|
async function commandUnlock() {
|
|
5019
|
+
header("unlock your key");
|
|
4405
5020
|
const [, me] = await relay("GET", "me");
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
return
|
|
5021
|
+
const token = secret();
|
|
5022
|
+
const url = config().url;
|
|
5023
|
+
return (await unlockOrCreate(
|
|
5024
|
+
token,
|
|
5025
|
+
url,
|
|
5026
|
+
me,
|
|
5027
|
+
hasTerminal(),
|
|
5028
|
+
await storedKey(token, url),
|
|
5029
|
+
))
|
|
5030
|
+
? 0
|
|
5031
|
+
: NOT_FINISHED;
|
|
4409
5032
|
}
|
|
4410
5033
|
|
|
4411
5034
|
async function commandResetKey() {
|
|
4412
|
-
|
|
4413
|
-
|
|
5035
|
+
header("make a new key");
|
|
5036
|
+
say(
|
|
5037
|
+
"This makes a new key. Messages sealed to your old one can't be opened again; your contacts are told your key " +
|
|
5038
|
+
"changed.",
|
|
5039
|
+
"note",
|
|
4414
5040
|
);
|
|
4415
|
-
if (ttyInput(
|
|
5041
|
+
if ((await ttyInput(`${indent}Type reset to go on: `)) !== "reset") return 1;
|
|
4416
5042
|
const [, me] = await relay("GET", "me");
|
|
4417
5043
|
const privateRaw = randomBytes(32);
|
|
4418
|
-
const passphrase = newPassphrase();
|
|
5044
|
+
const passphrase = await newPassphrase(true);
|
|
4419
5045
|
const [, saved] = await relay("PUT", "keys/me", {
|
|
4420
5046
|
body: {
|
|
4421
5047
|
publicKey: b64(x25519Public(privateRaw)),
|
|
@@ -4424,8 +5050,9 @@ async function commandResetKey() {
|
|
|
4424
5050
|
},
|
|
4425
5051
|
});
|
|
4426
5052
|
saveKey(me, pyInt(saved.version), privateRaw);
|
|
4427
|
-
|
|
4428
|
-
`New key
|
|
5053
|
+
say(
|
|
5054
|
+
`New key · ${fingerprint(x25519Public(privateRaw))}. Run unlock on your other machines.`,
|
|
5055
|
+
"ok",
|
|
4429
5056
|
);
|
|
4430
5057
|
return 0;
|
|
4431
5058
|
}
|
|
@@ -4433,11 +5060,16 @@ async function commandResetKey() {
|
|
|
4433
5060
|
async function commandTrust(argv) {
|
|
4434
5061
|
if (!argv.length) throw new SystemExit("passforth: trust @handle");
|
|
4435
5062
|
const handle = argv[0].replace(/^@+/, "").toLowerCase();
|
|
5063
|
+
header("trust a key");
|
|
4436
5064
|
const [, found] = await relay("GET", `keys/${quote(handle)}`);
|
|
4437
5065
|
const publicRaw = unb64(found.publicKey, 32);
|
|
4438
|
-
|
|
4439
|
-
|
|
4440
|
-
|
|
5066
|
+
say(`@${handle}'s key fingerprint: ${paint(fingerprint(publicRaw), "1")}`);
|
|
5067
|
+
say(
|
|
5068
|
+
"Check it with them over a channel you trust before you accept it.",
|
|
5069
|
+
"note",
|
|
5070
|
+
);
|
|
5071
|
+
if ((await ttyInput(`${indent}Trust this key? Type yes: `)) !== "yes")
|
|
5072
|
+
return 1;
|
|
4441
5073
|
const peers = orDict(readJson("peers.json", {}));
|
|
4442
5074
|
peers[found.userId] = {
|
|
4443
5075
|
handle: found.handle,
|
|
@@ -4445,34 +5077,37 @@ async function commandTrust(argv) {
|
|
|
4445
5077
|
public: found.publicKey,
|
|
4446
5078
|
};
|
|
4447
5079
|
writeJson("peers.json", peers);
|
|
4448
|
-
|
|
5080
|
+
say("Trusted.", "ok");
|
|
4449
5081
|
return 0;
|
|
4450
5082
|
}
|
|
4451
5083
|
|
|
4452
5084
|
async function commandDisconnect() {
|
|
5085
|
+
header("disconnect this machine");
|
|
4453
5086
|
try {
|
|
4454
5087
|
await relay("POST", "machine/revoke", { body: {} });
|
|
4455
|
-
|
|
5088
|
+
say("This machine's secret is revoked.", "ok");
|
|
4456
5089
|
} catch (error) {
|
|
4457
5090
|
if (!(error instanceof RelayError)) throw error;
|
|
4458
|
-
|
|
4459
|
-
`
|
|
5091
|
+
say(
|
|
5092
|
+
`Couldn't revoke the secret (${error.message}); revoke it on the dashboard's Machines page.`,
|
|
5093
|
+
"note",
|
|
4460
5094
|
);
|
|
4461
5095
|
}
|
|
4462
5096
|
const accounts = config().accounts;
|
|
4463
5097
|
for (const directory of truthy(accounts) ? accounts : claudeDirs()) {
|
|
4464
5098
|
configure(directory, false);
|
|
4465
|
-
|
|
5099
|
+
say(`Removed from Claude Code at ${tilde(directory)}`, "ok");
|
|
4466
5100
|
}
|
|
4467
5101
|
const homes = config().codexHomes;
|
|
4468
5102
|
for (const home of truthy(homes) ? homes : codexHomes()) {
|
|
4469
|
-
if (configureCodex(home, false))
|
|
5103
|
+
if (configureCodex(home, false))
|
|
5104
|
+
say(`Removed from Codex at ${tilde(home)}`, "ok");
|
|
4470
5105
|
}
|
|
4471
5106
|
for (const name of ["secret", "key.json", "peers.json", "config.json"])
|
|
4472
5107
|
remove(path(name));
|
|
4473
5108
|
removeTree(path("state"));
|
|
4474
|
-
|
|
4475
|
-
"Passforth is removed from this machine.
|
|
5109
|
+
finish(
|
|
5110
|
+
"Passforth is removed from this machine. Your previous settings are in settings.json.before-passforth.",
|
|
4476
5111
|
);
|
|
4477
5112
|
return 0;
|
|
4478
5113
|
}
|
|
@@ -4480,15 +5115,23 @@ async function commandDisconnect() {
|
|
|
4480
5115
|
function commandStatus() {
|
|
4481
5116
|
const cfg = config();
|
|
4482
5117
|
const key = ownKey();
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
5118
|
+
header("status");
|
|
5119
|
+
const rows = [
|
|
5120
|
+
["You", truthy(cfg.handle) ? `@${cfg.handle}` : "not connected"],
|
|
5121
|
+
["Relay", orElse(cfg.url, "not connected")],
|
|
5122
|
+
[
|
|
5123
|
+
"Key",
|
|
5124
|
+
key
|
|
5125
|
+
? fingerprint(key.publicBytes)
|
|
5126
|
+
: `none on this machine yet: ${hereCommand("unlock")}`,
|
|
5127
|
+
],
|
|
5128
|
+
];
|
|
4488
5129
|
for (const directory of orElse(cfg.accounts, []))
|
|
4489
|
-
|
|
5130
|
+
rows.push(["Claude Code", tilde(directory)]);
|
|
4490
5131
|
for (const home of orElse(cfg.codexHomes, []))
|
|
4491
|
-
|
|
5132
|
+
rows.push(["Codex", tilde(home)]);
|
|
5133
|
+
for (const [label, value] of rows)
|
|
5134
|
+
say(`${paint(label.padEnd(11), "2")} ${value}`);
|
|
4492
5135
|
return 0;
|
|
4493
5136
|
}
|
|
4494
5137
|
|
|
@@ -4508,7 +5151,8 @@ const COMMANDS = {
|
|
|
4508
5151
|
connect: commandConnect,
|
|
4509
5152
|
login: (argv) => commandConnect([...argv, "--code"]),
|
|
4510
5153
|
logout: async () => {
|
|
4511
|
-
|
|
5154
|
+
header("log out");
|
|
5155
|
+
say(await logoutNow(), "ok");
|
|
4512
5156
|
return 0;
|
|
4513
5157
|
},
|
|
4514
5158
|
archive: commandArchive,
|
|
@@ -4538,9 +5182,20 @@ export async function main(argv) {
|
|
|
4538
5182
|
try {
|
|
4539
5183
|
return await command(argv.slice(1));
|
|
4540
5184
|
} catch (error) {
|
|
4541
|
-
if (
|
|
4542
|
-
|
|
4543
|
-
|
|
5185
|
+
if (error instanceof NotFinished) {
|
|
5186
|
+
say(`Not finished: ${error.message}`, "note");
|
|
5187
|
+
return NOT_FINISHED;
|
|
5188
|
+
}
|
|
5189
|
+
if (error instanceof RelayError) {
|
|
5190
|
+
fail(error.message);
|
|
5191
|
+
return 1;
|
|
5192
|
+
}
|
|
5193
|
+
// A SystemExit with text is one failure line; SystemExit(2), as argparse leaves, goes on out quietly.
|
|
5194
|
+
if (error instanceof SystemExit && error.message) {
|
|
5195
|
+
fail(error.message.replace(/^passforth: /, ""));
|
|
5196
|
+
return 1;
|
|
5197
|
+
}
|
|
5198
|
+
throw error;
|
|
4544
5199
|
}
|
|
4545
5200
|
}
|
|
4546
5201
|
|
|
@@ -4555,7 +5210,7 @@ function leave(code) {
|
|
|
4555
5210
|
|
|
4556
5211
|
function isEntry() {
|
|
4557
5212
|
try {
|
|
4558
|
-
return realpathSync(process.argv[1])
|
|
5213
|
+
return samePath(realpathSync(process.argv[1]), THIS);
|
|
4559
5214
|
} catch {
|
|
4560
5215
|
return false;
|
|
4561
5216
|
}
|