@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.
Files changed (63) hide show
  1. package/README.md +8 -7
  2. package/SECURITY.md +55 -33
  3. package/dist/bridges/runtime/import-runner.js +4 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +243 -83
  6. package/dist/commands/agent.js +298 -72
  7. package/dist/commands/attention.js +2 -0
  8. package/dist/commands/bootstrap.js +2 -0
  9. package/dist/commands/bridge.js +10 -0
  10. package/dist/commands/doctor.js +87 -42
  11. package/dist/commands/export.js +141 -11
  12. package/dist/commands/import.js +36 -15
  13. package/dist/commands/init.js +373 -157
  14. package/dist/commands/keys.js +12 -8
  15. package/dist/commands/mcp.js +146 -62
  16. package/dist/commands/memory.js +5 -2
  17. package/dist/commands/migrate-harness-memory.js +9 -3
  18. package/dist/commands/principal.js +19 -14
  19. package/dist/commands/quality.js +23 -3
  20. package/dist/commands/reembed.js +468 -111
  21. package/dist/commands/search.js +2 -0
  22. package/dist/commands/service.js +25 -0
  23. package/dist/commands/status.js +130 -107
  24. package/dist/doctor-client.js +2 -23
  25. package/dist/federation/scheduler.js +148 -12
  26. package/dist/keystore.js +77 -10
  27. package/dist/lib/agent-key-file.js +509 -0
  28. package/dist/lib/agent-rotation-lock.js +249 -0
  29. package/dist/lib/atomic-write.js +2 -2
  30. package/dist/lib/auth-resolve.js +14 -14
  31. package/dist/lib/key-dir.js +203 -0
  32. package/dist/lib/launchd-management.js +7 -3
  33. package/dist/lib/local-instance-pair.js +8 -1
  34. package/dist/lib/node-alias-path.js +50 -2
  35. package/dist/lib/remote-admin-pass.js +157 -0
  36. package/dist/lib/scheduler-platform.js +13 -0
  37. package/dist/lib/service-repoint.js +13 -4
  38. package/dist/lib/skill-seed.js +35 -3
  39. package/dist/lib/terminal-text.js +32 -0
  40. package/dist/mcp-client-assertion.js +5 -4
  41. package/dist/resources/Memory.js +47 -3
  42. package/dist/resources/health.js +39 -22
  43. package/dist/resources/in-process-api.js +74 -11
  44. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  45. package/dist/resources/mcp-handler.js +40 -1
  46. package/dist/resources/mcp-oauth.js +17 -1
  47. package/dist/resources/mcp-tool-scopes.js +69 -0
  48. package/dist/resources/mcp-tools.js +10 -0
  49. package/dist/resources/skill-version-write.js +16 -0
  50. package/dist/src/keystore.js +77 -10
  51. package/dist/src/lib/atomic-write.js +2 -2
  52. package/dist/src/lib/key-dir.js +203 -0
  53. package/dist/src/lib/scheduler-platform.js +13 -0
  54. package/docs/access-control.md +21 -12
  55. package/docs/api-reference.md +35 -24
  56. package/docs/auth.md +31 -22
  57. package/docs/deploying-on-fabric.md +10 -2
  58. package/docs/embedding-in-a-harper-app.md +7 -7
  59. package/docs/entity-vocabulary.md +4 -5
  60. package/docs/hosted-on-fabric.md +1 -1
  61. package/docs/secrets-and-keys.md +8 -13
  62. package/docs/upgrade.md +15 -5
  63. package/package.json +1 -1
@@ -42,6 +42,7 @@
42
42
  * Kept free of any harper import (mirrors agentcard-fields.ts)
43
43
  * so the document shape is unit-testable without spinning up Harper.
44
44
  */
45
+ import { MCP_REQUESTED_SCOPES } from "./mcp-tool-scopes.js";
45
46
  /** The grant this agent's CIMD document targets — formalized by oauth#161, accepted by the published 2.2.0 validator. See module header. */
46
47
  export const CIMD_TARGET_GRANT_TYPES = ["client_credentials"];
47
48
  /** The auth method this agent's CIMD document targets — formalized by oauth#161, accepted by the published 2.2.0 validator. See module header. */
@@ -78,6 +79,9 @@ export function buildCimdDocument(params) {
78
79
  // pending oauth#161 — rejected by today's open-draft #167 validator; see module header.
79
80
  token_endpoint_auth_method: CIMD_TARGET_AUTH_METHOD,
80
81
  grant_types: [...CIMD_TARGET_GRANT_TYPES],
82
+ // flair#3076: @harperfast/oauth 2.9.0 mints a client_credentials token with
83
+ // this document's `scope` (test/unit-isolated/mcp-machine-token-scope-3076.test.ts).
84
+ scope: MCP_REQUESTED_SCOPES.join(" "),
81
85
  // redirect_uris AND response_types are both deliberately omitted — #161
82
86
  // blesses this explicitly for client_credentials-only CIMD clients (no
83
87
  // redirect-based flow is ever possible for a headless agent). Neither
@@ -9,7 +9,8 @@
9
9
  *
10
10
  * ── This handler's job ──────────────────────────────────────────────────────
11
11
  * 1. Parse the JSON-RPC request (initialize / tools/list / tools/call / ping).
12
- * 2. For tools/call: resolve `request.mcp.sub` → a flair `Agent` id via the
12
+ * 2. For tools/call: require the token's `scope` to grant the tool's scope
13
+ * (resources/mcp-tool-scopes.ts), then resolve `request.mcp.sub` → a flair `Agent` id via the
13
14
  * `Credential(kind:"idp", idpSubject=sub)` lookup, JIT-provisioning a
14
15
  * Principal+Credential the first time IF the trust anchor allows it.
15
16
  * 3. Establish the flair scoping context and invoke the tool, which delegates
@@ -27,6 +28,7 @@ import { databases } from "harper";
27
28
  import { randomBytes } from "node:crypto";
28
29
  import { TOOLS, listToolDefs } from "./mcp-tools.js";
29
30
  import { checkToolArguments, withoutNullArguments } from "./mcp-tool-arguments.js";
31
+ import { challengeScope, grantedScopes, requiredToolScope } from "./mcp-tool-scopes.js";
30
32
  import { agentRecordIsAdmin } from "./agent-admin.js";
31
33
  import { isPrincipalDeactivated } from "./agent-auth.js";
32
34
  import { stampOriginatorOnCreate } from "./originator-instance.js";
@@ -516,6 +518,17 @@ async function handleToolCall(request, id, params) {
516
518
  if (!sub) {
517
519
  return rpcError(id, -32001, "unauthorized: no verified token subject");
518
520
  }
521
+ // flair#3076: the token's granted scope must include the scope this tool
522
+ // requires. Checked before the subject is resolved, so a refused call reads
523
+ // no credential and provisions no principal.
524
+ const required = requiredToolScope(toolName);
525
+ if (required === undefined) {
526
+ return rpcError(id, -32602, `unknown tool: ${toolName}`);
527
+ }
528
+ const granted = grantedScopes(request?.mcp?.scope);
529
+ if (!granted.includes(required)) {
530
+ return insufficientScope(id, toolName, required, granted);
531
+ }
519
532
  // flair#718 authorship-provenance, Sherlock's binding refinement: source
520
533
  // the authorship stamp from `client_id` (the server-generated
521
534
  // `flair_cl_...` machine id — resources/OAuth.ts, an RS256-verified JWT
@@ -575,6 +588,32 @@ async function handleToolCall(request, id, params) {
575
588
  isError,
576
589
  });
577
590
  }
591
+ /**
592
+ * flair#3076: the answer to a tools/call whose token does not grant the tool's
593
+ * scope. HTTP 403 with a Bearer `insufficient_scope` challenge whose `scope` is
594
+ * challengeScope(), and a JSON-RPC error naming the tool and the scope it
595
+ * requires.
596
+ */
597
+ function insufficientScope(id, tool, required, granted) {
598
+ return {
599
+ status: 403,
600
+ headers: {
601
+ ...JSON_HEADERS,
602
+ "WWW-Authenticate": `Bearer error="insufficient_scope", scope="${challengeScope(granted, required)}"`,
603
+ "Access-Control-Allow-Origin": "*",
604
+ "Access-Control-Expose-Headers": "WWW-Authenticate",
605
+ },
606
+ body: JSON.stringify({
607
+ jsonrpc: "2.0",
608
+ id: id ?? null,
609
+ error: {
610
+ code: -32001,
611
+ message: `insufficient_scope: ${tool} requires the '${required}' scope, which this access token does not grant. ` +
612
+ "Obtain a token that grants it; the WWW-Authenticate header names the scopes to request.",
613
+ },
614
+ }),
615
+ };
616
+ }
578
617
  /**
579
618
  * Mark the mapping credential used, once a tool has run (best-effort). The
580
619
  * update writes `lastUsedAt` alone, as a field-level patch from an internal
@@ -24,6 +24,7 @@ import { mcpOAuthEnabled, mcpAuthConfig, mcpIssuer } from "./mcp-oauth-flag.js";
24
24
  import { mcpOAuthDegraded } from "./mcp-oauth-env-guard.js";
25
25
  import { checkMcpRateLimit } from "./rate-limit.js";
26
26
  import { MULTI_WORKER_GUARD_HTTP_NAME } from "./multi-worker-guard.js";
27
+ import { MCP_REQUESTED_SCOPES } from "./mcp-tool-scopes.js";
27
28
  /**
28
29
  * Boot guard (flair#1021, flair#1322), after the flag and degraded-start checks.
29
30
  *
@@ -471,6 +472,21 @@ export function rateLimitedMcpHandler(handler) {
471
472
  return handler(request);
472
473
  };
473
474
  }
475
+ /**
476
+ * flair#3076: add `scope="<MCP_REQUESTED_SCOPES>"` (the scope of each /mcp tool
477
+ * except soul_set) to a 401 Bearer challenge that names no scope. Any other
478
+ * response is returned as it is.
479
+ */
480
+ export function withRequestedScope(res) {
481
+ const challenge = res?.headers?.["WWW-Authenticate"];
482
+ if (res?.status !== 401 || typeof challenge !== "string" || !/^Bearer\s/.test(challenge) || /\bscope=/.test(challenge)) {
483
+ return res;
484
+ }
485
+ return {
486
+ ...res,
487
+ headers: { ...res.headers, "WWW-Authenticate": `${challenge}, scope="${MCP_REQUESTED_SCOPES.join(" ")}"` },
488
+ };
489
+ }
474
490
  export async function registerMcpOAuthRoute(deps = {}) {
475
491
  if (!mcpOAuthEnabled()) {
476
492
  // OFF → no route, no import, no side effects.
@@ -577,7 +593,7 @@ export async function registerMcpOAuthRoute(deps = {}) {
577
593
  // Reaching the wrapper means the live config is present, enabled, and
578
594
  // its issuer passed the rule; mounted state is derived on read, never
579
595
  // recorded for a request that may then be denied.
580
- return guardedMcp(request, next);
596
+ return withRequestedScope(await guardedMcp(request, next));
581
597
  }, { urlPath: "/mcp", after: MULTI_WORKER_GUARD_HTTP_NAME });
582
598
  console.error(`[mcp-oauth] /mcp mounted (OAuth-guarded); issuer=${config.issuer}`);
583
599
  mountedNamespace = harperNs;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The OAuth scope each native `/mcp` tool requires (flair#3076).
3
+ *
4
+ * `withMCPAuth` passes the access token's verified `scope` claim (a
5
+ * space-separated string) to the handler as `request.mcp.scope`. A tools/call
6
+ * runs only when that claim grants the scope this table lists for the tool. A
7
+ * token with no `scope` claim grants no scope. The tool runs as the token's
8
+ * mapped principal, with that principal's authority.
9
+ *
10
+ * resources/mcp-tools.ts refuses to load when a tool has no entry here, or an
11
+ * entry names a tool it does not serve.
12
+ */
13
+ export const MCP_TOOL_SCOPES = Object.freeze({
14
+ // Reads and searches of memories and the caller's own context.
15
+ memory_search: "memory:read",
16
+ memory_get: "memory:read",
17
+ skill_search: "memory:read",
18
+ skill_get: "memory:read",
19
+ bootstrap: "memory:read",
20
+ soul_get: "memory:read",
21
+ attention: "memory:read",
22
+ // Writes, updates, archive changes and deletes.
23
+ memory_store: "memory:write",
24
+ memory_update: "memory:write",
25
+ memory_delete: "memory:write",
26
+ memory_basement: "memory:write",
27
+ memory_restore: "memory:write",
28
+ skill_store: "memory:write",
29
+ flair_workspace_set: "memory:write",
30
+ flair_orgevent: "memory:write",
31
+ record_usage: "memory:write",
32
+ // The principal list.
33
+ team_directory: "principal:read",
34
+ // A Soul write is an operator action; with this scope soul_set still refuses
35
+ // the write (soul_write_requires_operator).
36
+ soul_set: "principal:admin",
37
+ });
38
+ /**
39
+ * The scopes the /mcp 401 challenge names and Flair's client metadata documents
40
+ * declare: the scope of each tool except `soul_set`.
41
+ */
42
+ export const MCP_REQUESTED_SCOPES = Object.freeze([
43
+ "memory:read",
44
+ "memory:write",
45
+ "principal:read",
46
+ ]);
47
+ /** The scope `tool` requires, or undefined for a name the table does not list. */
48
+ export function requiredToolScope(tool) {
49
+ return Object.prototype.hasOwnProperty.call(MCP_TOOL_SCOPES, tool) ? MCP_TOOL_SCOPES[tool] : undefined;
50
+ }
51
+ /** The scopes a token's `scope` claim grants. An absent claim grants none. */
52
+ export function grantedScopes(claim) {
53
+ return typeof claim === "string" ? claim.split(/\s+/).filter(Boolean) : [];
54
+ }
55
+ // RFC 6749 section 3.3 scope-token characters. A granted value outside them is
56
+ // left out of a challenge header rather than quoted into it.
57
+ const SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
58
+ /**
59
+ * The `scope` an insufficient_scope challenge names: the granted values that are
60
+ * RFC 6749 scope tokens, MCP_REQUESTED_SCOPES, and the scope the tool requires.
61
+ */
62
+ export function challengeScope(granted, required) {
63
+ const scopes = new Set();
64
+ for (const scope of [...granted, ...MCP_REQUESTED_SCOPES, required]) {
65
+ if (SCOPE_TOKEN.test(scope))
66
+ scopes.add(scope);
67
+ }
68
+ return [...scopes].join(" ");
69
+ }
@@ -57,6 +57,7 @@ import { resolveVersion } from "./version.js";
57
57
  import { agentContext, adminContext, collectionResource } from "./in-process.js";
58
58
  import { unionUsageMemoryIds } from "./usage-ids.js";
59
59
  import { SKILL_TAG, isSkillWrite } from "./skill-write.js";
60
+ import { MCP_TOOL_SCOPES } from "./mcp-tool-scopes.js";
60
61
  import { NATIVE_TOOL_DESCRIPTORS, toMcpToolDef, } from "./tool-descriptors/index.js";
61
62
  const H = {};
62
63
  const LOADERS = {
@@ -1323,6 +1324,15 @@ for (const name of Object.keys(LIST_GATES)) {
1323
1324
  throw new Error(`tools/list gate names a tool that is not in TOOLS: ${name}`);
1324
1325
  }
1325
1326
  }
1327
+ // flair#3076: each tool requires the scope MCP_TOOL_SCOPES lists for it, so the
1328
+ // table and TOOLS must name the same tools.
1329
+ {
1330
+ const unscoped = Object.keys(TOOLS).filter((name) => !Object.prototype.hasOwnProperty.call(MCP_TOOL_SCOPES, name));
1331
+ const unserved = Object.keys(MCP_TOOL_SCOPES).filter((name) => !Object.prototype.hasOwnProperty.call(TOOLS, name));
1332
+ if (unscoped.length > 0 || unserved.length > 0) {
1333
+ throw new Error(`MCP_TOOL_SCOPES does not match TOOLS: no scope for [${unscoped.join(", ")}]; not in TOOLS [${unserved.join(", ")}]`);
1334
+ }
1335
+ }
1326
1336
  /**
1327
1337
  * The tool defs `tools/list` returns for `agent`: every `TOOLS` entry whose gate
1328
1338
  * (if any) admits this caller. `agent` is null for a caller whose token subject
@@ -251,6 +251,22 @@ export function grantedSkillClose(closed, ctx, auth) {
251
251
  return null;
252
252
  return { granteeId: auth.agentId, ownerId: closed.agentId };
253
253
  }
254
+ /** The fields the embedding backfill's incremental update stages
255
+ * (resources/auth-middleware.ts); a committed target read may differ from the
256
+ * request snapshot by these without refusing the POST (flair#3170). */
257
+ const BACKFILL_WRITTEN_FIELDS = new Set(["embedding", "embeddingModel", "embeddedContentHash"]);
258
+ /** Does a committed target row differ from the request snapshot outside the
259
+ * embedding backfill's fields? Such a change refuses the POST with 409
260
+ * skill_target_changed (flair#3170). */
261
+ export function skillTargetSnapshotChanged(snapshot, committed) {
262
+ for (const field of new Set([...Object.keys(snapshot), ...Object.keys(committed)])) {
263
+ if (BACKFILL_WRITTEN_FIELDS.has(field))
264
+ continue;
265
+ if (!isDeepStrictEqual(snapshot[field], committed[field]))
266
+ return true;
267
+ }
268
+ return false;
269
+ }
254
270
  export async function validateSkillSnapshots(stored, predecessor, targetId, shared) {
255
271
  for (const [id, expected] of [[targetId, stored], [predecessor?.id, predecessor]]) {
256
272
  if (!id)
@@ -8,9 +8,10 @@
8
8
  * or an auto-generated random passphrase stored at ~/.flair/keys/.passphrase
9
9
  * (mode 0600). Never falls back to guessable data.
10
10
  */
11
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { closeSync, constants, existsSync, fstatSync, linkSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
12
12
  import { join } from "node:path";
13
13
  import { resolveHome } from "./lib/home.js";
14
+ import { agentKeyPath } from "./lib/key-dir.js";
14
15
  import { writeFilesAtomically } from "./lib/atomic-write.js";
15
16
  import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
16
17
  // ─── Helpers ────────────────────────────────────────────────────────────────
@@ -28,7 +29,7 @@ function keysDir() {
28
29
  function keyPath(instanceId) {
29
30
  // Sanitize instanceId to prevent directory traversal
30
31
  const safe = instanceId.replace(/[^a-zA-Z0-9_-]/g, "_");
31
- return join(keysDir(), `${safe}.key`);
32
+ return agentKeyPath(keysDir(), safe);
32
33
  }
33
34
  /**
34
35
  * Path to the auto-generated passphrase file.
@@ -37,20 +38,54 @@ function keyPath(instanceId) {
37
38
  function passphrasePath() {
38
39
  return join(keysDir(), ".passphrase");
39
40
  }
41
+ /**
42
+ * Read the auto-generated passphrase through one no-follow descriptor, after
43
+ * refusing a file wider than owner-only. On Windows the mode check is skipped
44
+ * and the file is read by path.
45
+ */
46
+ function readPassphraseFile(pp, hooks) {
47
+ const read = hooks.read ?? ((source) => readFileSync(source, "utf-8"));
48
+ const checked = (source) => {
49
+ const passphrase = read(source).trim();
50
+ if (!passphrase)
51
+ throw new Error(`passphrase file ${pp} is empty`);
52
+ return passphrase;
53
+ };
54
+ if ((hooks.platform ?? process.platform) === "win32") {
55
+ return checked(pp);
56
+ }
57
+ const fd = openSync(pp, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
58
+ try {
59
+ const st = (hooks.fstat ?? fstatSync)(fd);
60
+ if ((st.mode & 0o077) !== 0) {
61
+ throw new Error(`passphrase file ${pp} is accessible to other users (mode ${(st.mode & 0o777).toString(8).padStart(3, "0")}); ` +
62
+ `run chmod 600 ${pp} to make it owner-only`);
63
+ }
64
+ return checked(fd);
65
+ }
66
+ finally {
67
+ closeSync(fd);
68
+ }
69
+ }
40
70
  /**
41
71
  * Get or create the keystore passphrase.
42
72
  * Priority: FLAIR_KEY_PASSPHRASE env var > auto-generated file.
43
73
  * Never falls back to guessable data (hostname, username, etc.).
44
74
  */
45
- function getPassphrase() {
75
+ function getPassphrase(hooks = {}) {
46
76
  // Explicit env var takes priority
47
77
  if (process.env.FLAIR_KEY_PASSPHRASE) {
48
78
  return process.env.FLAIR_KEY_PASSPHRASE;
49
79
  }
50
80
  const pp = passphrasePath();
51
- // Read existing auto-generated passphrase
52
- if (existsSync(pp)) {
53
- return readFileSync(pp, "utf-8").trim();
81
+ // Read existing auto-generated passphrase; a missing file falls through to
82
+ // generation, and any other open/read failure propagates.
83
+ try {
84
+ return readPassphraseFile(pp, hooks);
85
+ }
86
+ catch (error) {
87
+ if (error?.code !== "ENOENT")
88
+ throw error;
54
89
  }
55
90
  // Generate a cryptographically random passphrase and persist it
56
91
  const dir = keysDir();
@@ -58,8 +93,40 @@ function getPassphrase() {
58
93
  mkdirSync(dir, { recursive: true, mode: 0o700 });
59
94
  }
60
95
  const generated = randomBytes(32).toString("base64url");
61
- writeFileSync(pp, generated, { mode: 0o600 });
62
- return generated;
96
+ const staged = join(dir, `.passphrase.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
97
+ writeFilesAtomically([{ path: staged, content: generated, mode: 0o600 }]);
98
+ let passphrase = generated;
99
+ let failure;
100
+ try {
101
+ hooks.beforePublish?.();
102
+ // Link the complete file without replacing a competing passphrase; reread on conflict.
103
+ try {
104
+ (hooks.link ?? linkSync)(staged, pp);
105
+ }
106
+ catch (error) {
107
+ const code = error?.code;
108
+ if (code !== "EEXIST") {
109
+ throw new Error(`could not publish the generated passphrase at ${pp} (${code}: ${error.message}); ` +
110
+ "if the keys dir's volume does not support hard links, set FLAIR_KEY_PASSPHRASE or use a keys dir on a volume that does");
111
+ }
112
+ passphrase = readPassphraseFile(pp, hooks);
113
+ }
114
+ }
115
+ catch (error) {
116
+ failure = { error };
117
+ }
118
+ try {
119
+ unlinkSync(staged);
120
+ }
121
+ catch (error) {
122
+ if (error?.code !== "ENOENT") {
123
+ const cleanup = `could not remove staged passphrase ${staged} (${error?.code}: ${error.message})`;
124
+ throw new Error(`${failure ? failure.error.message : `passphrase at ${pp}`}; ${cleanup}`, { cause: failure ? failure.error : error });
125
+ }
126
+ }
127
+ if (failure)
128
+ throw failure.error;
129
+ return passphrase;
63
130
  }
64
131
  /**
65
132
  * Derive a 256-bit encryption key using HKDF.
@@ -116,7 +183,7 @@ class FileKeyStore {
116
183
  }
117
184
  const p = keyPath(instanceId);
118
185
  const encrypted = encryptSeed(seed);
119
- writeFileSync(p, encrypted, { mode: 0o600 });
186
+ writeFilesAtomically([{ path: p, content: encrypted, mode: 0o600 }]);
120
187
  }
121
188
  }
122
189
  /** Singleton keystore instance. */
@@ -193,4 +260,4 @@ export function recordSeedOwner(instanceId, dataDir) {
193
260
  ]);
194
261
  }
195
262
  // Export helpers for testing
196
- export { encryptSeed, decryptSeed, deriveKey, keyPath, keysDir };
263
+ export { encryptSeed, decryptSeed, deriveKey, getPassphrase, keyPath, keysDir };
@@ -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.read(e.path);
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.
@@ -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
+ }
@@ -477,6 +477,19 @@ export function describeScheduledDriverFinding(f) {
477
477
  };
478
478
  }
479
479
  // Loaded from here down.
480
+ if (f.shimMissingNode) {
481
+ const m = f.shimMissingNode;
482
+ return {
483
+ state: "degraded",
484
+ icon: "error",
485
+ isIssue: true,
486
+ message: `${f.label} DEGRADED — the shim its unit file names execs a node binary that does not exist (${m.nodeBin})`,
487
+ detail: [
488
+ `${m.unitPath} names ${m.shimPath} as its program; the shim's exec line names ${m.nodeBin}, which does not exist.`,
489
+ `Fix: flair init # then check: ${f.statusCommand}`,
490
+ ],
491
+ };
492
+ }
480
493
  const le = f.lastExit;
481
494
  if (!le || le.state === "unavailable") {
482
495
  return {