@tpsdev-ai/flair 0.63.0 → 0.63.1
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 +8 -7
- package/SECURITY.md +55 -33
- package/dist/bridges/runtime/import-runner.js +4 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +243 -83
- package/dist/commands/agent.js +298 -72
- package/dist/commands/attention.js +2 -0
- package/dist/commands/bootstrap.js +2 -0
- package/dist/commands/bridge.js +10 -0
- package/dist/commands/doctor.js +87 -42
- package/dist/commands/export.js +141 -11
- package/dist/commands/import.js +36 -15
- package/dist/commands/init.js +373 -157
- package/dist/commands/keys.js +12 -8
- package/dist/commands/mcp.js +146 -62
- package/dist/commands/memory.js +5 -2
- package/dist/commands/migrate-harness-memory.js +9 -3
- package/dist/commands/principal.js +19 -14
- package/dist/commands/quality.js +23 -3
- package/dist/commands/reembed.js +468 -111
- package/dist/commands/search.js +2 -0
- package/dist/commands/service.js +25 -0
- package/dist/commands/status.js +130 -107
- package/dist/doctor-client.js +2 -23
- package/dist/federation/scheduler.js +148 -12
- package/dist/keystore.js +77 -10
- package/dist/lib/agent-key-file.js +509 -0
- package/dist/lib/agent-rotation-lock.js +249 -0
- package/dist/lib/atomic-write.js +2 -2
- package/dist/lib/auth-resolve.js +14 -14
- package/dist/lib/key-dir.js +203 -0
- package/dist/lib/launchd-management.js +7 -3
- package/dist/lib/local-instance-pair.js +8 -1
- package/dist/lib/node-alias-path.js +50 -2
- package/dist/lib/remote-admin-pass.js +157 -0
- package/dist/lib/scheduler-platform.js +13 -0
- package/dist/lib/service-repoint.js +13 -4
- package/dist/lib/skill-seed.js +35 -3
- package/dist/lib/terminal-text.js +32 -0
- package/dist/mcp-client-assertion.js +5 -4
- package/dist/resources/Memory.js +47 -3
- package/dist/resources/health.js +39 -22
- package/dist/resources/in-process-api.js +74 -11
- package/dist/resources/mcp-client-metadata-fields.js +4 -0
- package/dist/resources/mcp-handler.js +40 -1
- package/dist/resources/mcp-oauth.js +17 -1
- package/dist/resources/mcp-tool-scopes.js +69 -0
- package/dist/resources/mcp-tools.js +10 -0
- package/dist/resources/skill-version-write.js +16 -0
- package/dist/src/keystore.js +77 -10
- package/dist/src/lib/atomic-write.js +2 -2
- package/dist/src/lib/key-dir.js +203 -0
- package/dist/src/lib/scheduler-platform.js +13 -0
- package/docs/access-control.md +21 -12
- package/docs/api-reference.md +35 -24
- package/docs/auth.md +31 -22
- package/docs/deploying-on-fabric.md +10 -2
- package/docs/embedding-in-a-harper-app.md +7 -7
- package/docs/entity-vocabulary.md +4 -5
- package/docs/hosted-on-fabric.md +1 -1
- package/docs/secrets-and-keys.md +8 -13
- package/docs/upgrade.md +15 -5
- package/package.json +1 -1
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-rotation-lock.ts — a rotation lock for one agent in one keys directory,
|
|
3
|
+
* for `flair agent rotate-key` (flair#3151).
|
|
4
|
+
*
|
|
5
|
+
* Two rotations of one agent that use the same keys directory used to
|
|
6
|
+
* interleave: each read the current key, staged its own, sent the ops `update`,
|
|
7
|
+
* then renamed its staged key over the current one. The stored public key could
|
|
8
|
+
* end up matching neither private key on disk. The lock serializes rotations of
|
|
9
|
+
* one agent that use the same keys directory on a filesystem with reliable
|
|
10
|
+
* exclusive create; it is taken BEFORE the current key is read and held
|
|
11
|
+
* through the read-back check, the rename and the
|
|
12
|
+
* public-key write. Rotations that use different keys directories do not share
|
|
13
|
+
* it, and a server-side compare-and-set for the Agent row is out of scope.
|
|
14
|
+
*
|
|
15
|
+
* Conventions follow src/lib/config-critical-section.ts:
|
|
16
|
+
* - the lock is an `O_EXCL` create of a file in the keys dir named for the
|
|
17
|
+
* agent; its content is `<pid> <iso> <hostname>` for diagnosis only and is
|
|
18
|
+
* never an authorization input (a blank or partial record refuses).
|
|
19
|
+
* - acquisition retries a bounded number of times, then refuses, if the lock
|
|
20
|
+
* still exists after the retries, with a NAMED message that names the lock
|
|
21
|
+
* file and says to remove it only once no rotation of that agent is running.
|
|
22
|
+
* - a lock path that is not a regular file (a FIFO, a directory, a symlink)
|
|
23
|
+
* is refused at once, before it is read.
|
|
24
|
+
* - there is no reclaim, no age-out and no pid-liveness shortcut: a lock left
|
|
25
|
+
* by a killed run keeps refusing until an operator removes it.
|
|
26
|
+
* - release attempts to remove the lock file when that path still has the
|
|
27
|
+
* device and inode recorded at create. That is an lstat then unlink, not an
|
|
28
|
+
* atomic remove. A leaked lock refuses the next rotation; it never corrupts
|
|
29
|
+
* a key file.
|
|
30
|
+
*
|
|
31
|
+
* Release runs from an explicit `release()` and from a `process.once("exit")`
|
|
32
|
+
* listener registered with the lock. `flair agent rotate-key` exits with
|
|
33
|
+
* `process.exit(1)` on many failure paths, and `finally` does not run on
|
|
34
|
+
* `process.exit`.
|
|
35
|
+
*
|
|
36
|
+
* On filesystems where `O_EXCL` is unreliable (NFS/SMB) the lock may not
|
|
37
|
+
* serialize at all; that is the same residual config-critical-section.ts names.
|
|
38
|
+
*/
|
|
39
|
+
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
|
|
40
|
+
import { hostname } from "node:os";
|
|
41
|
+
import { join } from "node:path";
|
|
42
|
+
/** Lock acquisition: bounded retry (default 40 × 50 ms). */
|
|
43
|
+
export const AGENT_ROTATION_LOCK_RETRY = { attempts: 40, delayMs: 50 };
|
|
44
|
+
/**
|
|
45
|
+
* Test hook; production leaves it unset. It may return the open flags for the
|
|
46
|
+
* diagnostic holder read, so a test can present a platform that defines
|
|
47
|
+
* neither `O_NOFOLLOW` nor `O_NONBLOCK`.
|
|
48
|
+
*/
|
|
49
|
+
let beforeHolderOpen;
|
|
50
|
+
export function setAgentRotationLockTestHook(hook) {
|
|
51
|
+
beforeHolderOpen = hook;
|
|
52
|
+
}
|
|
53
|
+
/** The lock path for one agent in one keys directory. */
|
|
54
|
+
export function agentRotationLockPath(keysDir, id) {
|
|
55
|
+
return join(keysDir, `${id}.rotate-key.lock`);
|
|
56
|
+
}
|
|
57
|
+
/** Synchronous backoff without a sleep primitive that differs between bun and node. */
|
|
58
|
+
function sleepSync(ms) {
|
|
59
|
+
if (ms <= 0)
|
|
60
|
+
return;
|
|
61
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
62
|
+
}
|
|
63
|
+
function message(err) {
|
|
64
|
+
return err instanceof Error ? err.message : String(err);
|
|
65
|
+
}
|
|
66
|
+
function parseLockHolder(raw) {
|
|
67
|
+
if (!raw)
|
|
68
|
+
return null;
|
|
69
|
+
const m = raw.trim().match(/^(\d+)\s+(\S+)\s+(\S+)$/);
|
|
70
|
+
if (!m)
|
|
71
|
+
return null;
|
|
72
|
+
return { pid: m[1], timestamp: m[2], host: m[3] };
|
|
73
|
+
}
|
|
74
|
+
/** What an existing entry at the lock path is, by lstat alone (never a read). */
|
|
75
|
+
function lockPathKind(lockPath) {
|
|
76
|
+
try {
|
|
77
|
+
const st = lstatSync(lockPath);
|
|
78
|
+
if (st.isFile())
|
|
79
|
+
return "regular";
|
|
80
|
+
if (st.isDirectory())
|
|
81
|
+
return "a directory";
|
|
82
|
+
if (st.isSymbolicLink())
|
|
83
|
+
return "a symlink";
|
|
84
|
+
if (st.isFIFO())
|
|
85
|
+
return "a FIFO";
|
|
86
|
+
if (st.isSocket())
|
|
87
|
+
return "a socket";
|
|
88
|
+
if (st.isCharacterDevice())
|
|
89
|
+
return "a character device";
|
|
90
|
+
if (st.isBlockDevice())
|
|
91
|
+
return "a block device";
|
|
92
|
+
return "a non-regular file";
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
if (err.code === "ENOENT")
|
|
96
|
+
return "missing";
|
|
97
|
+
return `could not check the lock path (${err.code ?? "unknown"})`;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function nonRegularLockRefusal(lockPath, id, kind) {
|
|
101
|
+
return (`refusing to rotate agent '${id}': ${kind.startsWith("could not check") ? `${kind}: ${lockPath}` : `the rotation lock path ${lockPath} is not a regular file (lstat reports ${kind})`}. ` +
|
|
102
|
+
`Remove ${lockPath} only once no rotation of that agent is running.`);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Read the diagnostic holder record from a regular lock file only. Without
|
|
106
|
+
* `O_NOFOLLOW` the open could follow a symlink swapped in after the lstat;
|
|
107
|
+
* without `O_NONBLOCK` it could block on a FIFO swapped in the same way. When
|
|
108
|
+
* `O_RDONLY`, `O_NOFOLLOW` or `O_NONBLOCK` is not defined, there is no holder
|
|
109
|
+
* diagnostic.
|
|
110
|
+
*/
|
|
111
|
+
function readLockHolder(lockPath, flags = constants) {
|
|
112
|
+
if (typeof flags.O_RDONLY !== "number" ||
|
|
113
|
+
typeof flags.O_NOFOLLOW !== "number" ||
|
|
114
|
+
typeof flags.O_NONBLOCK !== "number") {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
let fd;
|
|
118
|
+
try {
|
|
119
|
+
fd = openSync(lockPath, flags.O_RDONLY | flags.O_NOFOLLOW | flags.O_NONBLOCK);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
if (!fstatSync(fd).isFile())
|
|
126
|
+
return null;
|
|
127
|
+
return readFileSync(fd, "utf-8");
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
try {
|
|
134
|
+
closeSync(fd);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// already closed
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function refusalLine(lockPath, id, holder) {
|
|
142
|
+
const parsed = parseLockHolder(holder);
|
|
143
|
+
const who = parsed
|
|
144
|
+
? `recorded holder pid ${parsed.pid} since ${parsed.timestamp} on host ${parsed.host}`
|
|
145
|
+
: "an unreadable or malformed lock record";
|
|
146
|
+
return (`an existing lock at ${lockPath} (${who}); refusing to rotate agent '${id}' without the lock. ` +
|
|
147
|
+
`Remove ${lockPath} only once no rotation of that agent is running.`);
|
|
148
|
+
}
|
|
149
|
+
function makeHandle(lockPath, identity) {
|
|
150
|
+
let released = false;
|
|
151
|
+
const release = () => {
|
|
152
|
+
if (released)
|
|
153
|
+
return;
|
|
154
|
+
released = true;
|
|
155
|
+
process.removeListener("exit", release);
|
|
156
|
+
try {
|
|
157
|
+
const st = lstatSync(lockPath, { bigint: true });
|
|
158
|
+
if (st.dev !== identity.dev || st.ino !== identity.ino)
|
|
159
|
+
return;
|
|
160
|
+
unlinkSync(lockPath);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
// ENOENT: the lock is already gone. Any other failure leaves a lock that
|
|
164
|
+
// refuses the next rotation; it never touches a key file.
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
process.once("exit", release);
|
|
168
|
+
return { path: lockPath, release };
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Take the per-agent rotation lock, or refuse by name. An existing lock
|
|
172
|
+
* is retried within the bound and then refused; the caller must exit without
|
|
173
|
+
* reading or writing any key file.
|
|
174
|
+
*/
|
|
175
|
+
export function acquireAgentRotationLock(opts) {
|
|
176
|
+
const lockPath = opts.lockPath ?? agentRotationLockPath(opts.keysDir, opts.id);
|
|
177
|
+
const retry = { ...AGENT_ROTATION_LOCK_RETRY, ...opts.retry };
|
|
178
|
+
for (let i = 0; i < retry.attempts; i++) {
|
|
179
|
+
let fd;
|
|
180
|
+
try {
|
|
181
|
+
fd = openSync(lockPath, "wx", 0o600);
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
if (err.code !== "EEXIST") {
|
|
185
|
+
return {
|
|
186
|
+
ok: false,
|
|
187
|
+
message: `could not create the rotation lock ${lockPath} (${message(err)}); no key file was changed`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const kind = lockPathKind(lockPath);
|
|
191
|
+
if (kind !== "regular" && kind !== "missing") {
|
|
192
|
+
return { ok: false, message: nonRegularLockRefusal(lockPath, opts.id, kind) };
|
|
193
|
+
}
|
|
194
|
+
if (i < retry.attempts - 1)
|
|
195
|
+
sleepSync(retry.delayMs);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
const st = fstatSync(fd, { bigint: true });
|
|
200
|
+
const identity = { dev: st.dev, ino: st.ino };
|
|
201
|
+
try {
|
|
202
|
+
// Diagnostic only: never an authorization input.
|
|
203
|
+
writeSync(fd, `${process.pid} ${new Date().toISOString()} ${hostname()}\n`);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// The lock exists (that is what protects us); a failed diagnostic
|
|
207
|
+
// write is not fatal.
|
|
208
|
+
}
|
|
209
|
+
return { ok: true, lock: makeHandle(lockPath, identity) };
|
|
210
|
+
}
|
|
211
|
+
finally {
|
|
212
|
+
try {
|
|
213
|
+
closeSync(fd);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
// already closed
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const kind = lockPathKind(lockPath);
|
|
221
|
+
if (kind !== "regular" && kind !== "missing") {
|
|
222
|
+
return { ok: false, message: nonRegularLockRefusal(lockPath, opts.id, kind) };
|
|
223
|
+
}
|
|
224
|
+
const hookResult = kind === "regular" ? beforeHolderOpen?.(lockPath) : undefined;
|
|
225
|
+
const hookFlags = typeof hookResult === "object" ? hookResult : undefined;
|
|
226
|
+
const holder = kind === "regular" ? readLockHolder(lockPath, hookFlags ?? constants) : null;
|
|
227
|
+
return { ok: false, message: refusalLine(lockPath, opts.id, holder) };
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* ENV-GATED test barrier for the real-server interleave test: after marking its
|
|
231
|
+
* own `.ready` file, a rotation waits (bounded) for the `.go` file the test
|
|
232
|
+
* drops. Inert unless `FLAIR_TEST_ROTATE_KEY_PAUSE` names a base path.
|
|
233
|
+
*
|
|
234
|
+
* TRUSTED-ENV ASSUMPTION: this path is only as privileged as the environment
|
|
235
|
+
* that starts the CLI; a caller who can set it can already set `FLAIR_*` and
|
|
236
|
+
* run the command itself. The polling loop is bounded.
|
|
237
|
+
*/
|
|
238
|
+
export async function agentRotationTestPause() {
|
|
239
|
+
const base = process.env.FLAIR_TEST_ROTATE_KEY_PAUSE;
|
|
240
|
+
if (!base)
|
|
241
|
+
return;
|
|
242
|
+
writeFileSync(`${base}.ready`, `${process.pid}\n`);
|
|
243
|
+
for (let i = 0; i < 1200; i++) {
|
|
244
|
+
if (existsSync(`${base}.go`))
|
|
245
|
+
return;
|
|
246
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
247
|
+
}
|
|
248
|
+
throw new Error(`rotation test pause at ${base} timed out waiting for ${base}.go`);
|
|
249
|
+
}
|
package/dist/lib/atomic-write.js
CHANGED
|
@@ -47,7 +47,7 @@ function resolveHooks(h) {
|
|
|
47
47
|
return {
|
|
48
48
|
open: h.open ?? ((p, flags, mode) => openSync(p, flags, mode)),
|
|
49
49
|
write: h.write ?? ((fd, data) => {
|
|
50
|
-
const buf = Buffer.from(data, "utf-8");
|
|
50
|
+
const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(data);
|
|
51
51
|
let off = 0;
|
|
52
52
|
while (off < buf.length)
|
|
53
53
|
off += writeSync(fd, buf, off, buf.length - off);
|
|
@@ -184,7 +184,7 @@ export function writeFilesAtomically(entries, hooks = {}) {
|
|
|
184
184
|
if (!fs.exists(e.path))
|
|
185
185
|
return { path: e.path, existed: false };
|
|
186
186
|
// A planned-from target is restored from the bytes it was re-checked to hold.
|
|
187
|
-
const content = e.expect ? e.expect.content : fs.
|
|
187
|
+
const content = e.expect ? Buffer.from(e.expect.content, "utf-8") : fs.readBytes(e.path);
|
|
188
188
|
return { path: e.path, existed: true, content, mode: fs.modeOf(e.path) };
|
|
189
189
|
});
|
|
190
190
|
// 2. Stage every new file. Nothing visible has changed yet.
|
package/dist/lib/auth-resolve.js
CHANGED
|
@@ -63,12 +63,14 @@
|
|
|
63
63
|
* conflict (`--admin-pass` + `--agent`) is never quiet either.
|
|
64
64
|
*/
|
|
65
65
|
import { existsSync, readFileSync, readdirSync, statSync, } from "node:fs";
|
|
66
|
-
import { join } from "node:path";
|
|
66
|
+
import { basename, join } from "node:path";
|
|
67
67
|
import { Option } from "commander";
|
|
68
68
|
import { createPrivateKey, randomUUID, sign as nodeCryptoSign } from "node:crypto";
|
|
69
69
|
import { resolveHome } from "./home.js";
|
|
70
|
+
import { agentKeyLocations, agentKeyPath, defaultKeysDir, keyPathIn } from "./key-dir.js";
|
|
70
71
|
import { isConnectPhaseFailure } from "./connect-phase.js";
|
|
71
72
|
export { isConnectPhaseFailure, REFUSED_CODES } from "./connect-phase.js";
|
|
73
|
+
export { defaultKeysDir };
|
|
72
74
|
// ─── Failure classification ─────────────────────────────────────────────────
|
|
73
75
|
/**
|
|
74
76
|
* Thrown by `sendJsonRequest` for an HTTP-level failure (as opposed to a
|
|
@@ -945,9 +947,6 @@ export const DEFAULT_ADMIN_USER = "admin";
|
|
|
945
947
|
export function resolveAdminUser(explicit) {
|
|
946
948
|
return explicit || process.env.FLAIR_ADMIN_USER || DEFAULT_ADMIN_USER;
|
|
947
949
|
}
|
|
948
|
-
export function defaultKeysDir() {
|
|
949
|
-
return join(resolveHome(), ".flair", "keys");
|
|
950
|
-
}
|
|
951
950
|
/**
|
|
952
951
|
* Resolve an admin password for LOCAL-only CLI convenience (`agent add`,
|
|
953
952
|
* `principal add`) without requiring `--admin-pass` on every call (#590).
|
|
@@ -1003,12 +1002,12 @@ export function resolveLocalAdminPass(explicit, isRemoteTarget = false, adminPas
|
|
|
1003
1002
|
// ─── Ed25519 agent-key signing ──────────────────────────────────────────────
|
|
1004
1003
|
/** Find the agent's private key file from standard locations. */
|
|
1005
1004
|
export function resolveKeyPath(agentId) {
|
|
1006
|
-
const
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
return
|
|
1005
|
+
for (const location of agentKeyLocations()) {
|
|
1006
|
+
const path = keyPathIn(location, agentId);
|
|
1007
|
+
if (existsSync(path))
|
|
1008
|
+
return path;
|
|
1009
|
+
}
|
|
1010
|
+
return null;
|
|
1012
1011
|
}
|
|
1013
1012
|
/**
|
|
1014
1013
|
* Load a signing key from disk: read the file, decode it (raw 32-byte seed,
|
|
@@ -1192,9 +1191,10 @@ export function isLocalBase(base) {
|
|
|
1192
1191
|
function noCredentialsHint(isLocal, signedOnly) {
|
|
1193
1192
|
if (signedOnly) {
|
|
1194
1193
|
// No admin password leaves a signedOnly request, so only an agent key helps.
|
|
1195
|
-
const
|
|
1196
|
-
|
|
1197
|
-
|
|
1194
|
+
const keyPath = signedOnly.agentId ? agentKeyPath(defaultKeysDir(), signedOnly.agentId) : null;
|
|
1195
|
+
const remedy = keyPath
|
|
1196
|
+
? `Provide the key of agent '${signedOnly.agentId}' at ${keyPath} ` +
|
|
1197
|
+
`(or set FLAIR_KEY_DIR to a directory containing ${basename(keyPath)}).`
|
|
1198
1198
|
: `Provide the key of an agent registered on the target instance at ${join(signedOnly.keysDir, "<agent-id>.key")}.`;
|
|
1199
1199
|
return `This request can send only an Ed25519 agent signature; the admin password is not sent on this path. ${remedy}`;
|
|
1200
1200
|
}
|
|
@@ -1547,7 +1547,7 @@ export async function authedRequest(method, path, body, opts) {
|
|
|
1547
1547
|
const keyPath = resolveKeyPath(opts.agentId);
|
|
1548
1548
|
if (!keyPath) {
|
|
1549
1549
|
throw new Error(`--agent '${opts.agentId}' has no signing key. Expected a key at ` +
|
|
1550
|
-
`${
|
|
1550
|
+
`${agentKeyPath(defaultKeysDir(), opts.agentId)} (or set FLAIR_KEY_DIR ` +
|
|
1551
1551
|
`to a directory containing it). Refusing to fall back to FLAIR_ADMIN_PASS ` +
|
|
1552
1552
|
`or the local admin-pass file.`);
|
|
1553
1553
|
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* key-dir.ts — the keys-directory walk shared by `flair keys prune`,
|
|
3
|
+
* `flair doctor` and `flair status` (flair#3077).
|
|
4
|
+
*
|
|
5
|
+
* Prune retains its entry classification; mode checks cover every file with a
|
|
6
|
+
* location's key suffix, because signing can read any such file.
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, lstatSync, readdirSync, realpathSync } from "node:fs";
|
|
9
|
+
import { join, resolve } from "node:path";
|
|
10
|
+
import { invalidAgentIdMessage, isValidAgentId } from "./agent-id-rule.js";
|
|
11
|
+
import { resolveHome } from "./home.js";
|
|
12
|
+
/** Read the keys directory, following a symlink at keysDir. The caller owns the
|
|
13
|
+
* "directory absent" decision; this reports only what readdir returned. */
|
|
14
|
+
export function scanKeyDir(keysDir) {
|
|
15
|
+
let dirents;
|
|
16
|
+
try {
|
|
17
|
+
dirents = readdirSync(keysDir, { withFileTypes: true });
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
return { state: "unreadable", error };
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
state: "ok",
|
|
24
|
+
entries: dirents.map((dirent) => {
|
|
25
|
+
if (dirent.isDirectory())
|
|
26
|
+
return { name: dirent.name, kind: "dir" };
|
|
27
|
+
if (!dirent.name.endsWith(".key"))
|
|
28
|
+
return { name: dirent.name, kind: "other" };
|
|
29
|
+
return { name: dirent.name, kind: "key" };
|
|
30
|
+
}),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** The ordered locations `resolveKeyPath` tries for an agent id. Read at CALL
|
|
34
|
+
* time, so `FLAIR_KEY_DIR` set later in the process is seen. */
|
|
35
|
+
export function agentKeyLocations() {
|
|
36
|
+
const home = resolveHome();
|
|
37
|
+
const locations = [];
|
|
38
|
+
if (process.env.FLAIR_KEY_DIR) {
|
|
39
|
+
locations.push({ dir: process.env.FLAIR_KEY_DIR, suffix: ".key" });
|
|
40
|
+
}
|
|
41
|
+
locations.push({ dir: join(home, ".flair", "keys"), suffix: ".key" });
|
|
42
|
+
locations.push({ dir: join(home, ".tps", "secrets", "flair"), suffix: "-priv.key" });
|
|
43
|
+
return locations;
|
|
44
|
+
}
|
|
45
|
+
/** A refusal for an agent id that cannot name a key file: the id is checked
|
|
46
|
+
* before it is joined into a path. Callers map it to their own error style. */
|
|
47
|
+
export class AgentKeyPathRefusal extends Error {
|
|
48
|
+
code = "invalid_agent_id";
|
|
49
|
+
/** The CLI prints the message alone and exits 1 when a command lets it propagate. */
|
|
50
|
+
flairFriendly = true;
|
|
51
|
+
constructor(message) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = "AgentKeyPathRefusal";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Apply the shared agent-ID rule to an id a command is about to sign as. */
|
|
57
|
+
export function requireAgentId(agentId) {
|
|
58
|
+
if (!isValidAgentId(agentId))
|
|
59
|
+
throw new AgentKeyPathRefusal(invalidAgentIdMessage(agentId));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The private-key path for `agentId`; the shared agent-ID rule runs before
|
|
63
|
+
* the join.
|
|
64
|
+
*/
|
|
65
|
+
export function agentKeyPath(keysDir, agentId) {
|
|
66
|
+
requireAgentId(agentId);
|
|
67
|
+
return join(keysDir, `${agentId}.key`);
|
|
68
|
+
}
|
|
69
|
+
/** The public-key path for `agentId`; the shared agent-ID rule runs before
|
|
70
|
+
* the join. */
|
|
71
|
+
export function agentPubKeyPath(keysDir, agentId) {
|
|
72
|
+
requireAgentId(agentId);
|
|
73
|
+
return join(keysDir, `${agentId}.pub`);
|
|
74
|
+
}
|
|
75
|
+
/** The path signing reads for `agentId` in `location`. */
|
|
76
|
+
export function keyPathIn(location, agentId) {
|
|
77
|
+
requireAgentId(agentId);
|
|
78
|
+
return join(location.dir, `${agentId}${location.suffix}`);
|
|
79
|
+
}
|
|
80
|
+
/** The legacy `~/.tps/secrets/flair/<id>-priv.key` signing key for `agentId`;
|
|
81
|
+
* the shared agent-ID rule runs before the join. */
|
|
82
|
+
export function legacyAgentKeyPath(agentId) {
|
|
83
|
+
requireAgentId(agentId);
|
|
84
|
+
return join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`);
|
|
85
|
+
}
|
|
86
|
+
function errorCode(error) {
|
|
87
|
+
const code = error?.code;
|
|
88
|
+
return typeof code === "string" ? code : "lstat failed";
|
|
89
|
+
}
|
|
90
|
+
/** lstat one key path and report a wide or uncheckable file. No content is read
|
|
91
|
+
* and no file is changed; entry symlinks are not followed. */
|
|
92
|
+
function keyModeFindingForPath(path) {
|
|
93
|
+
let stats;
|
|
94
|
+
try {
|
|
95
|
+
stats = lstatSync(path);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
return { kind: "not-checked", path, reason: errorCode(error) };
|
|
99
|
+
}
|
|
100
|
+
if (!stats.isFile()) {
|
|
101
|
+
return {
|
|
102
|
+
kind: "not-checked",
|
|
103
|
+
path,
|
|
104
|
+
reason: stats.isSymbolicLink() ? "symbolic link" : "not a regular file",
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (stats.mode & 0o077) {
|
|
108
|
+
return { kind: "wide", path, mode: (stats.mode & 0o777).toString(8).padStart(4, "0") };
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
function canonicalDir(dir) {
|
|
113
|
+
try {
|
|
114
|
+
return realpathSync(dir);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return resolve(dir);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Whether two key-location paths name the same directory entry after resolving symlinks. */
|
|
121
|
+
export function sameKeyDir(a, b) {
|
|
122
|
+
return canonicalDir(a) === canonicalDir(b);
|
|
123
|
+
}
|
|
124
|
+
/** The mode scan over the standard `resolveKeyPath` locations. A path reached
|
|
125
|
+
* through two locations (e.g. `FLAIR_KEY_DIR` pointing at the default
|
|
126
|
+
* directory) is reported once. */
|
|
127
|
+
export function scanAgentKeyModes(locations = agentKeyLocations()) {
|
|
128
|
+
const findings = [];
|
|
129
|
+
const unreadable = [];
|
|
130
|
+
const seenPaths = new Set();
|
|
131
|
+
const seenUnreadable = new Set();
|
|
132
|
+
for (const location of locations) {
|
|
133
|
+
const dirKey = canonicalDir(location.dir);
|
|
134
|
+
const scan = scanKeyDir(location.dir);
|
|
135
|
+
if (scan.state === "unreadable") {
|
|
136
|
+
const code = scan.error?.code;
|
|
137
|
+
if (code !== "ENOENT" && !seenUnreadable.has(dirKey)) {
|
|
138
|
+
seenUnreadable.add(dirKey);
|
|
139
|
+
unreadable.push({ dir: location.dir, code: code ?? "error" });
|
|
140
|
+
}
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const names = scan.entries.map((e) => e.name).filter((name) => name.endsWith(location.suffix)).sort();
|
|
144
|
+
for (const name of names) {
|
|
145
|
+
const path = join(location.dir, name);
|
|
146
|
+
const pathKey = join(dirKey, name);
|
|
147
|
+
if (seenPaths.has(pathKey))
|
|
148
|
+
continue;
|
|
149
|
+
seenPaths.add(pathKey);
|
|
150
|
+
const finding = keyModeFindingForPath(path);
|
|
151
|
+
if (finding)
|
|
152
|
+
findings.push(finding);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { findings, unreadable };
|
|
156
|
+
}
|
|
157
|
+
/** POSIX single-quoting for a path used in a command an operator will run. A
|
|
158
|
+
* relative path that starts with `-` is prefixed with `./`, so the command
|
|
159
|
+
* does not read it as an option. */
|
|
160
|
+
function shellQuotePath(path) {
|
|
161
|
+
const operand = path.startsWith("-") ? `./${path}` : path;
|
|
162
|
+
if (/^[A-Za-z0-9._\-/]+$/.test(operand))
|
|
163
|
+
return operand;
|
|
164
|
+
return `'${operand.replace(/'/g, `'\\''`)}'`;
|
|
165
|
+
}
|
|
166
|
+
/** The one rendering of a finding, so doctor and status cannot word it
|
|
167
|
+
* differently. The `chmod` remedy shell-quotes the path. */
|
|
168
|
+
export function formatKeyModeFinding(finding) {
|
|
169
|
+
if (finding.kind === "wide") {
|
|
170
|
+
return `agent key file ${finding.path} has mode ${finding.mode}, wider than owner-only — fix: chmod 600 ${shellQuotePath(finding.path)}`;
|
|
171
|
+
}
|
|
172
|
+
return `agent key file ${finding.path} not checked (${finding.reason})`;
|
|
173
|
+
}
|
|
174
|
+
/** Mode bits carry no owner-only meaning on Windows. */
|
|
175
|
+
export function keyModesUnsupported() {
|
|
176
|
+
return process.platform === "win32";
|
|
177
|
+
}
|
|
178
|
+
export const KEY_MODES_UNSUPPORTED_MESSAGE = "key file modes are not checked on Windows";
|
|
179
|
+
/** The keys directory `~/.flair/keys`, resolved at CALL time. */
|
|
180
|
+
export function defaultKeysDir() {
|
|
181
|
+
return join(resolveHome(), ".flair", "keys");
|
|
182
|
+
}
|
|
183
|
+
/** Node-shaped file ids. */
|
|
184
|
+
const NODE_KEY_ID_RE = /^flair_[0-9a-f]{8}$/;
|
|
185
|
+
/** Match node-shaped ids without a sibling .pub; file type is unproven. */
|
|
186
|
+
export function isNodeKeyId(id, keysDir) {
|
|
187
|
+
if (!NODE_KEY_ID_RE.test(id))
|
|
188
|
+
return false;
|
|
189
|
+
return !existsSync(agentPubKeyPath(keysDir, id));
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Partition `.key`-derived ids by file name: an id that `isNodeKeyId` matches
|
|
193
|
+
* (node-shaped, no sibling `.pub`) goes to `nodeKeyIds`, every other id to
|
|
194
|
+
* `agentKeyIds`. Key contents are not read.
|
|
195
|
+
*/
|
|
196
|
+
export function partitionKeyIds(ids, keysDir) {
|
|
197
|
+
const agentKeyIds = [];
|
|
198
|
+
const nodeKeyIds = [];
|
|
199
|
+
for (const id of ids) {
|
|
200
|
+
(isNodeKeyId(id, keysDir) ? nodeKeyIds : agentKeyIds).push(id);
|
|
201
|
+
}
|
|
202
|
+
return { agentKeyIds, nodeKeyIds };
|
|
203
|
+
}
|
|
@@ -249,11 +249,15 @@ export function classifyServiceNodePin(input, deps = {}) {
|
|
|
249
249
|
kind: "pinned",
|
|
250
250
|
unitNodeBin,
|
|
251
251
|
currentNodeBin,
|
|
252
|
-
//
|
|
253
|
-
//
|
|
252
|
+
// With valid targets and existing other runtime paths, `flair init`
|
|
253
|
+
// reports `pinned-node`, except for a plist's eligible Cellar-to-opt
|
|
254
|
+
// replacement (flair#3056). A plist can replace a missing runtime path
|
|
255
|
+
// and an eligible Cellar node together; systemd refuses missing paths.
|
|
256
|
+
// Moving the pin to this CLI's runtime is a hand edit.
|
|
254
257
|
message: `${unitDescription} pins node ${unitNodeBin} while this CLI runs ${currentNodeBin}, and it serves this ` +
|
|
255
258
|
`CLI's own install tree (${unitTree}). That is treated as a deliberate runtime pin and left as it is; ` +
|
|
256
|
-
"`flair init` does not change it
|
|
259
|
+
"`flair init` does not change it, except that it can replace a Homebrew Cellar node path in a launchd plist " +
|
|
260
|
+
"with its `opt` alias (the same binary). To move the service to this CLI's runtime, change that node path to " +
|
|
257
261
|
`${currentNodeBin} in the unit by hand, then run: flair restart`,
|
|
258
262
|
remedy: [],
|
|
259
263
|
};
|
|
@@ -64,6 +64,13 @@ import { readProcessBirth, readTcpListenerPids, LISTENER_VISIBILITY_REMEDY } fro
|
|
|
64
64
|
import { defaultReadProcessCmdline } from "./upgrade-exec-path.js";
|
|
65
65
|
/** The host halves of an `http.port` binding that bind on loopback or on all interfaces. */
|
|
66
66
|
const LOCAL_HTTP_BIND_HOSTS = ["127.0.0.1", "localhost", "0.0.0.0", "[::]", ""];
|
|
67
|
+
export class IncompleteInstancePairError extends Error {
|
|
68
|
+
reason;
|
|
69
|
+
constructor(message, supplied, missing) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.reason = { kind: "one-sided", supplied, missing };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
67
74
|
const DEFAULT_OS_READS = {
|
|
68
75
|
listeners: (port) => readTcpListenerPids(port),
|
|
69
76
|
birth: (pid) => readProcessBirth(pid),
|
|
@@ -227,7 +234,7 @@ function harperListenerRefusal(os, pid, label, port) {
|
|
|
227
234
|
/** The one process listening on `port`, or an `unproven` proof naming why not. */
|
|
228
235
|
function soleListener(read, label, port) {
|
|
229
236
|
if (read.kind === "unavailable") {
|
|
230
|
-
return { kind: "unproven", status: null, detail: `the listener table for ${label} port ${port} cannot be read: ${read.reason}`, remedy: read.remedy };
|
|
237
|
+
return { kind: "unproven", status: null, detail: `the listener table for ${label} port ${port} cannot be read: ${read.reason}`, remedy: read.remedy, reason: "listener-table-unavailable" };
|
|
231
238
|
}
|
|
232
239
|
if (read.pids.length === 0) {
|
|
233
240
|
return {
|
|
@@ -15,6 +15,12 @@
|
|
|
15
15
|
* - mise: `$MISE_DATA_DIR | ~/.local/share/mise` + `/installs/node/<major>/bin/node`.
|
|
16
16
|
* mise keeps `installs/node/<major>` as a symlink to the newest installed
|
|
17
17
|
* runtime of that major, so it resolves to the same binary and is written.
|
|
18
|
+
* - Homebrew: `<prefix>/Cellar/<formula>/<version>/bin/node` (a realpath into
|
|
19
|
+
* the Cellar) has the alias `<prefix>/opt/<formula>/bin/node`, where
|
|
20
|
+
* `<prefix>` is taken from the path (so /opt/homebrew and /usr/local both
|
|
21
|
+
* work) and `<formula>` is `node` or a versioned `node@NN`. `brew upgrade
|
|
22
|
+
* node` repoints `opt/node` at the new version, and upgrade cleanup can
|
|
23
|
+
* remove the old Cellar directory.
|
|
18
24
|
* - Volta: `$VOLTA_HOME | ~/.volta` + `/bin/node`. Considered, but a standard
|
|
19
25
|
* Volta install makes that path a link to `volta-shim`, whose realpath is
|
|
20
26
|
* not a node binary, so the equality check rejects it and the exact path is
|
|
@@ -39,6 +45,44 @@
|
|
|
39
45
|
import { existsSync, realpathSync } from "node:fs";
|
|
40
46
|
import { join } from "node:path";
|
|
41
47
|
import { resolveHome } from "./home.js";
|
|
48
|
+
const HOMEBREW_CELLAR_RE = /^(.*)\/Cellar\/([^/]+)\/[^/]+\/bin\/node$/;
|
|
49
|
+
const HOMEBREW_FORMULA_RE = /^node(?:@\d+)?$/;
|
|
50
|
+
/**
|
|
51
|
+
* `<prefix>/opt/<formula>/bin/node` for a `<prefix>/Cellar/<formula>/<version>/bin/node`
|
|
52
|
+
* path, else null. A Cellar path carries the version in a segment Homebrew may
|
|
53
|
+
* suffix with a revision (`26.10.0_1`), so this candidate is derived from the
|
|
54
|
+
* path alone.
|
|
55
|
+
*/
|
|
56
|
+
function homebrewAliasCandidate(nodeBin) {
|
|
57
|
+
const cellar = HOMEBREW_CELLAR_RE.exec(nodeBin);
|
|
58
|
+
const prefix = cellar?.[1];
|
|
59
|
+
const formula = cellar?.[2];
|
|
60
|
+
if (!prefix || !formula || !prefix.startsWith("/") || !HOMEBREW_FORMULA_RE.test(formula))
|
|
61
|
+
return null;
|
|
62
|
+
return join(prefix, "opt", formula, "bin", "node");
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The Homebrew `opt/<formula>/bin/node` alias to record IN PLACE OF an
|
|
66
|
+
* already-recorded `Cellar/<formula>/<version>/bin/node` path (flair#3056):
|
|
67
|
+
* returned only when that alias exists and its realpath equals the recorded
|
|
68
|
+
* path's realpath. null otherwise, including when either realpath cannot be
|
|
69
|
+
* read. mise and Volta candidates are not considered here.
|
|
70
|
+
*/
|
|
71
|
+
export function homebrewOptAlias(nodeBin, hooks = {}) {
|
|
72
|
+
const alias = homebrewAliasCandidate(nodeBin);
|
|
73
|
+
if (alias === null)
|
|
74
|
+
return null;
|
|
75
|
+
const exists = hooks.exists ?? existsSync;
|
|
76
|
+
const realpath = hooks.realpath ?? ((p) => realpathSync(p));
|
|
77
|
+
try {
|
|
78
|
+
if (!exists(alias))
|
|
79
|
+
return null;
|
|
80
|
+
return realpath(alias) === realpath(nodeBin) ? alias : null;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
42
86
|
/** `24.19.0` / `v24.19.0` → `24.19.0`; null when no version is present. */
|
|
43
87
|
export function parseNodeVersion(nodePath) {
|
|
44
88
|
const m = /(?:^|[/\\])v?(\d+\.\d+\.\d+)(?:[/\\]|$)/.exec(nodePath);
|
|
@@ -52,8 +96,11 @@ export function parseNodeVersion(nodePath) {
|
|
|
52
96
|
export function aliasCandidates(nodeBin, hooks = {}) {
|
|
53
97
|
const home = hooks.home ?? resolveHome();
|
|
54
98
|
const env = hooks.env ?? process.env;
|
|
55
|
-
const version = parseNodeVersion(nodeBin);
|
|
56
99
|
const out = [];
|
|
100
|
+
const brew = homebrewAliasCandidate(nodeBin);
|
|
101
|
+
if (brew)
|
|
102
|
+
out.push({ manager: "homebrew", path: brew });
|
|
103
|
+
const version = parseNodeVersion(nodeBin);
|
|
57
104
|
if (!version || !home)
|
|
58
105
|
return out;
|
|
59
106
|
const major = version.split(".")[0];
|
|
@@ -66,7 +113,8 @@ export function aliasCandidates(nodeBin, hooks = {}) {
|
|
|
66
113
|
/**
|
|
67
114
|
* The node path to WRITE into a generated unit: a floating alias whose realpath
|
|
68
115
|
* is the same binary as `nodeBin`, when one exists; otherwise `nodeBin`
|
|
69
|
-
* unchanged.
|
|
116
|
+
* unchanged. Candidates are tried in aliasCandidates order (Homebrew, then
|
|
117
|
+
* mise's major alias, then Volta's).
|
|
70
118
|
*/
|
|
71
119
|
export function preferVersionManagerAlias(nodeBin, hooks = {}) {
|
|
72
120
|
const exists = hooks.exists ?? existsSync;
|