@tpsdev-ai/flair 0.54.1 → 0.55.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.
Files changed (69) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +73 -2
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +80 -8
  10. package/dist/commands/upgrade.js +41 -5
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/engine-version.js +12 -4
  13. package/dist/fabric-upgrade.js +30 -15
  14. package/dist/hook-install.js +170 -16
  15. package/dist/lib/doctor-run.js +49 -3
  16. package/dist/lib/embed-gpu-doctor.js +30 -0
  17. package/dist/lib/federation-pair-access.js +118 -0
  18. package/dist/lib/harper-port-value.js +43 -0
  19. package/dist/lib/http-bind.js +227 -0
  20. package/dist/lib/init-admin-pass.js +316 -0
  21. package/dist/lib/launchd-management.js +16 -0
  22. package/dist/lib/launchd-repair.js +122 -1
  23. package/dist/lib/npm-registry.js +578 -0
  24. package/dist/lib/owned-pins.js +54 -1
  25. package/dist/lib/process-start-time.js +82 -0
  26. package/dist/lib/scratch-owner.js +124 -10
  27. package/dist/lib/stale-client-pin.js +26 -0
  28. package/dist/rem/runner.js +10 -1
  29. package/dist/resources/AdminInstance.js +8 -2
  30. package/dist/resources/Memory.js +36 -1
  31. package/dist/resources/MemoryBootstrap.js +23 -32
  32. package/dist/resources/MemoryFeed.js +4 -1
  33. package/dist/resources/MemoryReflect.js +121 -93
  34. package/dist/resources/SkillScan.js +13 -11
  35. package/dist/resources/Soul.js +15 -1
  36. package/dist/resources/XAA.js +16 -1
  37. package/dist/resources/a2a-url.js +5 -2
  38. package/dist/resources/client-version-gate.js +144 -0
  39. package/dist/resources/embed-gpu.js +241 -0
  40. package/dist/resources/embeddings-boot.js +34 -42
  41. package/dist/resources/federation-peer-liveness.js +7 -1
  42. package/dist/resources/health.js +12 -3
  43. package/dist/resources/mcp-tools.js +8 -3
  44. package/dist/resources/memory-reflect-lib.js +66 -0
  45. package/dist/resources/memory-reflect-models.js +9 -0
  46. package/dist/resources/migrations/embedding-stamp.js +32 -4
  47. package/dist/resources/oauth-discovery.js +3 -1
  48. package/dist/resources/record-type-kit.js +59 -0
  49. package/dist/resources/scan/skill-markdown.js +166 -0
  50. package/dist/resources/scan/skill-scanner.js +89 -68
  51. package/dist/resources/skill-provenance.js +273 -0
  52. package/dist/resources/skill-write.js +26 -7
  53. package/{node_modules/@tpsdev-ai/flair-tool-descriptors/dist → dist/resources/tool-descriptors}/index.js +4 -0
  54. package/dist/src/lib/harper-port-value.js +43 -0
  55. package/dist/version-check.js +29 -8
  56. package/docs/api-reference.md +35 -2
  57. package/docs/deployment.md +1 -1
  58. package/docs/federation.md +18 -7
  59. package/docs/mcp-clients.md +19 -6
  60. package/docs/releasing.md +96 -24
  61. package/docs/rem.md +1 -1
  62. package/docs/secrets-and-keys.md +1 -0
  63. package/docs/standalone-local.md +1 -1
  64. package/docs/troubleshooting.md +17 -0
  65. package/package.json +4 -9
  66. package/node_modules/@tpsdev-ai/flair-tool-descriptors/LICENSE +0 -19
  67. package/node_modules/@tpsdev-ai/flair-tool-descriptors/README.md +0 -22
  68. package/node_modules/@tpsdev-ai/flair-tool-descriptors/dist/index.d.ts +0 -70
  69. package/node_modules/@tpsdev-ai/flair-tool-descriptors/package.json +0 -46
@@ -0,0 +1,227 @@
1
+ /**
2
+ * http-bind.ts — the ONE constructor for a Harper HTTP bind value.
3
+ *
4
+ * Every place Flair hands Harper an HTTP listener address — `HTTP_PORT` in a
5
+ * spawn env or a launchd plist, and `http.port` inside a `HARPER_SET_CONFIG`
6
+ * payload — goes through `httpBind()`. It returns a SHAPE (`{ bindValue, host,
7
+ * port }`), not a string, because two different consumers need two different
8
+ * halves of the same answer:
9
+ *
10
+ * - the LISTENER wants the host-qualified `host:port` form (Harper's
11
+ * `listenOnPorts` splits a config port value on its LAST colon and binds
12
+ * that host; a bare number binds all interfaces), and
13
+ * - every CORS allow-list entry and every loopback URL builder wants the
14
+ * PORT half on its own.
15
+ *
16
+ * Returning only the qualified string would force every caller to re-split it —
17
+ * i.e. to re-implement the parser this module exists to be the single copy of.
18
+ *
19
+ * ## Why the constructor is not an exposure classifier
20
+ *
21
+ * There is already a predicate for "is this bind exposed?", `LOOPBACK_HOSTS` in
22
+ * `ops-api-bind.ts` (`{127.0.0.1, localhost, ::1}`). This module does NOT reuse
23
+ * it, and must not: that set answers a DIFFERENT question. It classifies
24
+ * whether a bind is narrowed; it does not guarantee that a client on IPv4
25
+ * loopback can reach the listener. The two disagree on exactly the hosts that
26
+ * matter here:
27
+ *
28
+ * - `::1` (IPv6 loopback) passes "is it exposed?" (it is not — it is
29
+ * loopback) but a client dialing `127.0.0.1` does NOT reach it. Harper
30
+ * passes the parsed host straight to `listen` with no loopback translation
31
+ * (`dist/server/threads/threadServer.js`, `listenOnPorts`), so `[::1]:PORT`
32
+ * would satisfy every exposure check, fail every self-call, and leave every
33
+ * bind assertion green.
34
+ * - `localhost` depends on name resolution and may resolve to `::1` on a
35
+ * v6-first host.
36
+ *
37
+ * So this constructor allows a host only when it GUARANTEES IPv4-loopback
38
+ * reachability: `127.0.0.1`, or a wildcard (which includes IPv4 loopback).
39
+ * Every other host — a specific non-loopback interface address, an IPv6-only
40
+ * loopback, a hostname, anything unparseable — is refused. That refusal is
41
+ * load-bearing: all of Flair's credentialed self-calls hardcode
42
+ * `http://127.0.0.1:<port>`, so a bind that excludes IPv4 loopback leaves them
43
+ * pointing at a dead port while every bind check still passes.
44
+ *
45
+ * Deliberate widening is still possible through the escape hatch
46
+ * (`--http-bind` / `FLAIR_HTTP_BIND` / persisted `httpBind`), but only to a
47
+ * WILDCARD — the hatch waives the exposure restriction, never the connectivity
48
+ * requirement.
49
+ */
50
+ import { harperPortValue } from "./harper-port-value.js";
51
+ /** The only non-wildcard host Flair will bind: it is IPv4 loopback by definition. */
52
+ export const DEFAULT_HTTP_BIND_HOST = "127.0.0.1";
53
+ /**
54
+ * Wildcard hosts. Binding one of these includes IPv4 loopback, so the
55
+ * hardcoded `http://127.0.0.1:<port>` self-calls still land — this is why a
56
+ * wildcard is the only widening the constructor will produce.
57
+ */
58
+ const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", "0:0:0:0:0:0:0:0"]);
59
+ /**
60
+ * Thrown when a requested bind host cannot be guaranteed reachable on IPv4
61
+ * loopback. Callers refuse BEFORE writing anything (plist, config, spawn env),
62
+ * so a bad host can never be persisted.
63
+ */
64
+ export class UnreachableHttpBindHostError extends Error {
65
+ host;
66
+ constructor(host) {
67
+ super(`refusing to bind Harper's HTTP listener to "${host}": every credentialed ` +
68
+ `self-call Flair makes hardcodes 127.0.0.1, so a bind that does not include ` +
69
+ `IPv4 loopback would leave them pointing at a dead port. Use 127.0.0.1 ` +
70
+ `(the default), or a wildcard (0.0.0.0 / ::) for deliberate widening.`);
71
+ this.host = host;
72
+ this.name = "UnreachableHttpBindHostError";
73
+ }
74
+ }
75
+ /** Strip a single pair of surrounding square brackets from an IPv6 literal. */
76
+ function stripBrackets(host) {
77
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
78
+ }
79
+ /**
80
+ * True when a bind host guarantees an IPv4-loopback client can reach the
81
+ * listener. `127.0.0.1` and a wildcard yes; everything else no. Exported so
82
+ * the escape-hatch validation and the tests name the same predicate.
83
+ */
84
+ export function guaranteesIpv4Loopback(host) {
85
+ const h = stripBrackets(host.trim());
86
+ return h === DEFAULT_HTTP_BIND_HOST || WILDCARD_HOSTS.has(h);
87
+ }
88
+ function isIpv6Literal(host) {
89
+ return host.includes(":");
90
+ }
91
+ /**
92
+ * Build the Harper HTTP bind value, refusing any host that does not guarantee
93
+ * IPv4-loopback reachability. An absent/empty host defaults to `127.0.0.1`.
94
+ *
95
+ * `port` must be an integer in 1..65535 (`resolveHttpPort` guarantees this for
96
+ * the production callers; the check is here so a stray value cannot reach a
97
+ * config payload that `new URL()` or Harper's `listen` would later reject).
98
+ */
99
+ export function httpBind(host, port) {
100
+ const rawHost = host === undefined || host === null ? "" : String(host).trim();
101
+ const resolvedHost = rawHost === "" ? DEFAULT_HTTP_BIND_HOST : rawHost;
102
+ const portNum = typeof port === "number" ? port : Number(String(port).trim());
103
+ if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
104
+ throw new RangeError(`refusing to build an HTTP bind for port "${String(port)}": must be an integer in 1..65535`);
105
+ }
106
+ if (!guaranteesIpv4Loopback(resolvedHost)) {
107
+ throw new UnreachableHttpBindHostError(resolvedHost);
108
+ }
109
+ const h = stripBrackets(resolvedHost);
110
+ const bindValue = isIpv6Literal(h) ? `[${h}]:${portNum}` : `${h}:${portNum}`;
111
+ return { bindValue, host: h, port: portNum };
112
+ }
113
+ /**
114
+ * The CORS allow-list entries for an HTTP bind. Uses the PORT half only:
115
+ * CORS is about the browser-facing origin, and every entry Flair writes is a
116
+ * loopback origin regardless of which interface the listener bound.
117
+ */
118
+ export function httpCorsAccessList(port) {
119
+ return [`http://127.0.0.1:${port}`, `http://localhost:${port}`];
120
+ }
121
+ // ─── repair: preserving an instance's recorded coordinates ─────────────────
122
+ //
123
+ // `doctor --fix` is the ONE bind emitter that does not go through `httpBind()`:
124
+ // it promises not to move the instance's coordinates, so it PRESERVES what the
125
+ // instance recorded (a bare legacy port stays bare; an already-qualified
126
+ // `host:port` keeps its host). The helpers below are shared between the CLI's
127
+ // plist writer and the pure repair PLANNER, so the planner can refuse an
128
+ // unsupported configuration BEFORE the executor stops anything.
129
+ /**
130
+ * Preserve an instance's recorded HTTP port value VERBATIM for a repair.
131
+ *
132
+ * Throws for a DISABLED value (absent, null or empty) and for an UNSUPPORTED
133
+ * value (a port that cannot be parsed). Callers refuse rather than substituting
134
+ * a default: a default here is a coordinate change that can enable a listener
135
+ * the instance never had.
136
+ */
137
+ export function preserveHttpPortValue(raw) {
138
+ if (raw === undefined || raw === null || (typeof raw === "string" && raw.trim() === "")) {
139
+ throw new Error("refusing to repair the launchd plist: the instance's harper-config.yaml records no http.port, " +
140
+ "so the HTTP listener is disabled. Repair preserves the instance's coordinates and will not " +
141
+ "substitute a default port, which would enable a listener the instance did not have.");
142
+ }
143
+ if (typeof raw === "number") {
144
+ if (Number.isInteger(raw) && raw >= 1 && raw <= 65535)
145
+ return String(raw);
146
+ throw new Error(`refusing to repair the launchd plist: http.port is ${raw}, which is not a usable port`);
147
+ }
148
+ const str = String(raw).trim();
149
+ if (harperPortValue(str) === null) {
150
+ throw new Error(`refusing to repair the launchd plist: http.port is "${str}", which is not a parseable bind value`);
151
+ }
152
+ return str;
153
+ }
154
+ /**
155
+ * A secure-listener port, reduced to its number. Returns undefined for a
156
+ * disabled value (so the key is omitted and a disabled listener STAYS
157
+ * disabled), and throws for an unparseable one (so a caller refuses rather than
158
+ * writing a value it cannot read).
159
+ */
160
+ export function preserveSecurePort(raw) {
161
+ if (raw === undefined || raw === null || (typeof raw === "string" && raw.trim() === ""))
162
+ return undefined;
163
+ const port = harperPortValue(raw);
164
+ if (port === null) {
165
+ throw new Error(`refusing to repair the launchd plist: secure port "${String(raw)}" is not a usable port`);
166
+ }
167
+ return port;
168
+ }
169
+ /**
170
+ * The host half of a preserved `host:port` bind value, or null when the value
171
+ * is bare (no host) or unparseable. Mirrors `ops-api-bind.ts`'s `parseBindHost`
172
+ * so both readers agree on what "the host half" is.
173
+ */
174
+ export function bindHostOf(value) {
175
+ const s = value.trim();
176
+ if (s.startsWith("[")) {
177
+ const close = s.indexOf("]");
178
+ return close === -1 ? null : s.slice(1, close);
179
+ }
180
+ const lastColon = s.lastIndexOf(":");
181
+ if (lastColon <= 0)
182
+ return null;
183
+ const tail = s.slice(lastColon + 1);
184
+ return /^\d+$/.test(tail) ? s.slice(0, lastColon) : null;
185
+ }
186
+ /**
187
+ * The host to qualify an ENABLED secure listener with, given the (preserved)
188
+ * plaintext bind host. A bare secure value binds ALL interfaces exactly like a
189
+ * bare plaintext port does — Harper feeds `http.securePort` through the same
190
+ * `listenOnPorts` path — so when the plaintext listener IS narrowed, a bare
191
+ * secure value is qualified with the same host, or TLS would stay wide while
192
+ * plaintext is narrowed. A plaintext host that cannot guarantee IPv4 loopback
193
+ * (e.g. a legacy `::1`) is not mirrored; the secure listener falls back to the
194
+ * loopback default instead of producing a bind Flair's self-calls cannot reach.
195
+ */
196
+ export function secureBindHostFor(plaintextHost) {
197
+ return plaintextHost !== null && guaranteesIpv4Loopback(plaintextHost) ? plaintextHost : DEFAULT_HTTP_BIND_HOST;
198
+ }
199
+ /**
200
+ * The secure-listener config value a repair should write, or undefined when the
201
+ * listener is disabled. Repair PRESERVES the instance's coordinates, and this
202
+ * rule is "both or neither" with respect to the plaintext bind:
203
+ *
204
+ * - the secure value already names a host -> preserve that value verbatim
205
+ * (repair never re-homes a listener the instance recorded with a host);
206
+ * - the secure value is BARE and the plaintext value is ALSO bare -> preserve
207
+ * it bare. Repair moves NEITHER listener; narrowing TLS here while leaving a
208
+ * bare (all-interfaces) plaintext port in place would move one coordinate
209
+ * and silently drop LAN TLS clients after a `doctor --fix` that promised to
210
+ * change nothing;
211
+ * - the secure value is BARE and the plaintext value is qualified -> qualify
212
+ * the secure host the same way as the plaintext bind (a bare secure port
213
+ * binds all interfaces exactly like a bare plaintext port, so leaving it
214
+ * bare would narrow plaintext and leave TLS wide).
215
+ */
216
+ export function qualifySecureBindValue(secureRaw, plaintextValue) {
217
+ const port = preserveSecurePort(secureRaw);
218
+ if (port === undefined)
219
+ return undefined;
220
+ const recorded = String(secureRaw).trim();
221
+ if (bindHostOf(recorded) !== null)
222
+ return recorded;
223
+ const plaintextHost = bindHostOf(plaintextValue);
224
+ if (plaintextHost === null)
225
+ return recorded;
226
+ return httpBind(secureBindHostFor(plaintextHost), port).bindValue;
227
+ }
@@ -0,0 +1,316 @@
1
+ /**
2
+ * init-admin-pass.ts — flair#837: the missing-file + persisted-Harper-user
3
+ * case that #827 could not close.
4
+ *
5
+ * #827 made `flair init` reuse `~/.flair/admin-pass` when the file is already
6
+ * present. The remaining footgun is the file MISSING while Harper's data dir
7
+ * already holds an admin user: `HDB_ADMIN_PASSWORD` only seeds a brand-new
8
+ * install, so generating a fresh file there desyncs from the stored hash and
9
+ * the next ops-API call 401s.
10
+ *
11
+ * This module is the single decision + the two exits that can actually be
12
+ * right: re-persist a supplied original credential, or rotate the stored
13
+ * hash through the ops-API domain socket (`alter_user`, no Authorization).
14
+ * Silent regeneration is never a decision here.
15
+ *
16
+ * Security property the rotate path relies on (flair#837 condition 2,
17
+ * #1704): the ops domain socket is a Harper `super_user` channel with no
18
+ * Authorization header (`bypassLocalAuth` is an else-if on "no header
19
+ * present"). That is safe ONLY because of the socket posture — parent dir
20
+ * 0700, socket 0600. The rotate path refuses if the socket is not
21
+ * owner-only. `--reset-admin-pass` is the only path that may rotate; it
22
+ * prints the user, socket, and destination file before doing it.
23
+ *
24
+ * Pure decision helpers are exported for unit tests. The socket POST is a
25
+ * thin `node:http` client against `dataDir/operations-server`.
26
+ */
27
+ import { request as httpRequest } from "node:http";
28
+ import { createConnection } from "node:net";
29
+ import { existsSync, statSync } from "node:fs";
30
+ import { dirname, join } from "node:path";
31
+ /** Copy-pasteable recovery commands. Tests assert these strings verbatim. */
32
+ export const INIT_RESET_ADMIN_PASS_COMMAND = "flair init --reset-admin-pass";
33
+ export const INIT_ADMIN_PASS_FILE_COMMAND = "flair init --admin-pass-file <path>";
34
+ export const INIT_STOP_FOREIGN_COMMAND = "flair stop";
35
+ /** Short doctor remedy — names the two exits as the fix (report-only). */
36
+ export const ADMIN_PASS_DESYNC_REMEDY = `Fix: ${INIT_ADMIN_PASS_FILE_COMMAND} (if you have the original) or ${INIT_RESET_ADMIN_PASS_COMMAND}`;
37
+ /**
38
+ * Decide the admin-password action for `flair init`.
39
+ *
40
+ * One-arg form (`adminPassFileExists`) is the #827 contract and must keep
41
+ * answering `reuse-existing` / `generate-new`. The optional second argument
42
+ * is the #837 persisted-user / foreign-instance / reset context. On a call
43
+ * that omits it, a missing file is still a fresh install.
44
+ */
45
+ export function resolveInitAdminPasswordSource(adminPassFileExists, ctx = {}) {
46
+ const persisted = !!ctx.persistedAdminUser;
47
+ const foreign = !!ctx.foreignInstanceOnPort;
48
+ const explicit = !!ctx.explicitCredential;
49
+ const reset = !!ctx.resetRequested;
50
+ const socketOk = ctx.opsSocketAvailable !== false;
51
+ if (foreign && !adminPassFileExists && !explicit) {
52
+ return "refuse";
53
+ }
54
+ if (adminPassFileExists && !reset) {
55
+ return "reuse-existing";
56
+ }
57
+ if (!adminPassFileExists && !persisted && !reset) {
58
+ return "generate-new";
59
+ }
60
+ if (persisted && explicit && !reset) {
61
+ return "re-persist";
62
+ }
63
+ // Rotate is production credential rotation. The ONLY way in is the
64
+ // explicit `--reset-admin-pass` flag — never a missing-file guess.
65
+ if (reset) {
66
+ return socketOk ? "rotate" : "refuse";
67
+ }
68
+ if (persisted && !adminPassFileExists) {
69
+ return "refuse";
70
+ }
71
+ return adminPassFileExists ? "reuse-existing" : "generate-new";
72
+ }
73
+ /** Why a `refuse` decision was reached — drives the exact recovery command. */
74
+ export function resolveInitAdminPasswordRefuseReason(adminPassFileExists, ctx = {}) {
75
+ if (resolveInitAdminPasswordSource(adminPassFileExists, ctx) !== "refuse")
76
+ return null;
77
+ if (ctx.foreignInstanceOnPort && !adminPassFileExists && !ctx.explicitCredential) {
78
+ return "foreign-instance";
79
+ }
80
+ if (ctx.resetRequested && ctx.opsSocketAvailable === false) {
81
+ return "reset-without-socket";
82
+ }
83
+ return "persisted-missing-file";
84
+ }
85
+ /**
86
+ * Harper's own install-validator signal that a rootPath already has a user
87
+ * record (`system/hdb_user/data.mdb` or the legacy `system/hdb_user.mdb`).
88
+ * Config presence alone is not enough — an interrupted install can write
89
+ * harper-config.yaml before the user hash lands.
90
+ */
91
+ export function detectPersistedAdminUser(dataDir) {
92
+ const dir = dataDir;
93
+ return (existsSync(join(dir, "system", "hdb_user", "data.mdb")) ||
94
+ existsSync(join(dir, "system", "hdb_user.mdb")));
95
+ }
96
+ export function initAdminPassRefusalMessage(reason, opts = {}) {
97
+ if (reason === "foreign-instance") {
98
+ const port = opts.httpPort ?? 19926;
99
+ return (`A Harper instance is already answering on port ${port} and this data directory has no persisted admin user. ` +
100
+ `Stop that process before initializing a new instance:\n ${INIT_STOP_FOREIGN_COMMAND}`);
101
+ }
102
+ if (reason === "reset-without-socket") {
103
+ return (`Cannot rotate the admin password: Harper is not running and --skip-start was set, so the operations socket is unreachable. ` +
104
+ `Start the instance, then run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
105
+ }
106
+ if (reason === "socket-not-owner-only") {
107
+ const socket = opts.socketPath ?? "<data-dir>/operations-server";
108
+ return (`Refusing to rotate the admin password: the operations socket at ${socket} is not owner-only ` +
109
+ `(required: parent dir 0700 / socket 0600, flair#1704). The socket is a super_user channel ` +
110
+ `with no Authorization header, so a group/world-accessible socket would expose credential rotation. ` +
111
+ `Fix the posture, then run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
112
+ }
113
+ if (reason === "socket-not-ready") {
114
+ const socket = opts.socketPath ?? "<data-dir>/operations-server";
115
+ return (`Cannot rotate the admin password: the operations socket at ${socket} never became ready ` +
116
+ `to accept a connection. Harper can answer HTTP health before it binds that socket, and a ` +
117
+ `leftover inode that does not accept connections is not ready. Refusing before any alter_user ` +
118
+ `or pass-file write. Wait until the instance has bound the socket, then run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
119
+ }
120
+ const dataDir = opts.dataDir ?? "<data-dir>";
121
+ const passPath = opts.adminPassPath ?? "~/.flair/admin-pass";
122
+ return (`Harper already has an admin user in ${dataDir}, but ${passPath} is missing. ` +
123
+ `HDB_ADMIN_PASSWORD only seeds a brand-new install and will not rotate the stored hash, ` +
124
+ `so generating a new file would 401 every later ops-API call.\n` +
125
+ `If you have the original password:\n ${INIT_ADMIN_PASS_FILE_COMMAND}\n` +
126
+ `If you do not:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
127
+ }
128
+ /**
129
+ * Doctor / status finding for the disk-visible half of #837: file gone,
130
+ * user record still in the data dir. Live 401 probes (file present but
131
+ * wrong) are a separate authenticated check the caller can layer on.
132
+ */
133
+ export function adminPassDesyncFinding(input) {
134
+ if (input.adminPassFileExists || !input.persistedAdminUser)
135
+ return null;
136
+ return {
137
+ flagged: true,
138
+ message: "admin-pass file missing; Harper still has a persisted admin user",
139
+ remedy: ADMIN_PASS_DESYNC_REMEDY,
140
+ };
141
+ }
142
+ /**
143
+ * `--reset-admin-pass` is production credential rotation. Print this
144
+ * exactly — user, socket, destination file — before any alter_user.
145
+ */
146
+ export function formatAdminPasswordRotatePreflight(opts) {
147
+ return (`About to rotate Harper admin user '${opts.username}' via operations socket ${opts.socketPath} ` +
148
+ `(super_user channel, no Authorization header; safe only because the socket is owner-only: ` +
149
+ `0700 dir / 0600 socket, flair#1704). After alter_user succeeds the new password will be written to ${opts.adminPassPath}.`);
150
+ }
151
+ /** Rotate is reachable only from `--reset-admin-pass`. */
152
+ export function assertExplicitAdminPasswordRotate(resetRequested) {
153
+ if (!resetRequested) {
154
+ throw new Error("Refusing to rotate the admin password: --reset-admin-pass was not given. " +
155
+ "Bare init never rotates a persisted hash.");
156
+ }
157
+ }
158
+ /** Owner-only ops-socket posture (flair#1704): dir 0700, socket 0600. */
159
+ export function isOwnerOnlyOpsSocketPosture(dirMode, socketMode) {
160
+ return (dirMode & 0o777) === 0o700 && (socketMode & 0o777) === 0o600;
161
+ }
162
+ /**
163
+ * Refuse rotation unless the socket and its parent directory are owner-only.
164
+ * The socket is a super_user channel with no Authorization header.
165
+ */
166
+ export function assertOwnerOnlyOpsSocket(socketPath, stat = (p) => statSync(p)) {
167
+ const socket = stat(socketPath);
168
+ const dir = stat(dirname(socketPath));
169
+ if (!isOwnerOnlyOpsSocketPosture(dir.mode, socket.mode)) {
170
+ throw new Error(initAdminPassRefusalMessage("socket-not-owner-only", { socketPath }));
171
+ }
172
+ }
173
+ /**
174
+ * POST an operations payload over the domain socket. Sends NO Authorization
175
+ * header: Harper's socket `bypassLocalAuth` is an else-if on "no header
176
+ * present", so attaching Basic/Bearer opts out of the local-admin channel
177
+ * and 401s (harper `bin/cliOperations.ts`).
178
+ */
179
+ export function callOpsSocket(socketPath, body, timeoutMs = 10_000) {
180
+ const payload = JSON.stringify(body);
181
+ return new Promise((resolve, reject) => {
182
+ const req = httpRequest({
183
+ socketPath,
184
+ path: "/",
185
+ method: "POST",
186
+ headers: {
187
+ "Content-Type": "application/json",
188
+ "Content-Length": Buffer.byteLength(payload),
189
+ },
190
+ timeout: timeoutMs,
191
+ }, (res) => {
192
+ const chunks = [];
193
+ res.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
194
+ res.on("end", () => {
195
+ resolve({
196
+ status: res.statusCode ?? 0,
197
+ body: Buffer.concat(chunks).toString("utf8"),
198
+ });
199
+ });
200
+ });
201
+ req.on("error", reject);
202
+ req.on("timeout", () => {
203
+ req.destroy();
204
+ reject(new Error(`ops socket timed out after ${timeoutMs}ms`));
205
+ });
206
+ req.write(payload);
207
+ req.end();
208
+ });
209
+ }
210
+ /**
211
+ * Gate the rotate path: explicit `--reset-admin-pass` AND owner-only socket.
212
+ * Returns the preflight line the caller MUST print before `alter_user`.
213
+ */
214
+ export function prepareAdminPasswordRotate(opts) {
215
+ assertExplicitAdminPasswordRotate(opts.resetRequested);
216
+ assertOwnerOnlyOpsSocket(opts.socketPath, opts.stat);
217
+ return formatAdminPasswordRotatePreflight({
218
+ username: opts.username,
219
+ socketPath: opts.socketPath,
220
+ adminPassPath: opts.adminPassPath,
221
+ });
222
+ }
223
+ export async function rotateAdminPasswordViaOpsSocket(socketPath, username, password) {
224
+ const result = await callOpsSocket(socketPath, {
225
+ operation: "alter_user",
226
+ username,
227
+ password,
228
+ role: "super_user",
229
+ active: true,
230
+ });
231
+ if (result.status >= 400) {
232
+ throw new Error(`Operations socket alter_user failed (${result.status}): ${result.body || "(empty)"}`);
233
+ }
234
+ }
235
+ /** How long rotate waits for Harper to bind and accept on operations-server. */
236
+ export const OPS_SOCKET_ROTATE_TIMEOUT_MS = 10_000;
237
+ const OPS_SOCKET_ROTATE_POLL_MS = 50;
238
+ const OPS_SOCKET_ROTATE_PROBE_TIMEOUT_MS = 250;
239
+ /**
240
+ * True when something is accepting on `path`. A leftover inode that exists
241
+ * but accepts no connection is dead — not ready. HTTP /Health is not a
242
+ * substitute: Harper can answer HTTP before it bind()s this socket.
243
+ */
244
+ export function probeOpsSocketAccepting(socketPath, timeoutMs = OPS_SOCKET_ROTATE_PROBE_TIMEOUT_MS) {
245
+ return new Promise((resolve) => {
246
+ let settled = false;
247
+ const finish = (ok) => {
248
+ if (settled)
249
+ return;
250
+ settled = true;
251
+ sock.removeAllListeners();
252
+ sock.destroy();
253
+ resolve(ok);
254
+ };
255
+ const sock = createConnection(socketPath);
256
+ sock.setTimeout(timeoutMs);
257
+ sock.once("connect", () => finish(true));
258
+ sock.once("error", () => finish(false));
259
+ sock.once("timeout", () => finish(false));
260
+ });
261
+ }
262
+ /**
263
+ * Bounded wait until the operations socket accepts a connection.
264
+ * A missing path or a stale/dead inode is not-ready; this never unlinks
265
+ * and never falls through to the HTTP ops path.
266
+ */
267
+ export async function waitForOpsSocketReady(socketPath, opts = {}) {
268
+ const timeoutMs = opts.timeoutMs ?? OPS_SOCKET_ROTATE_TIMEOUT_MS;
269
+ const pollMs = opts.pollMs ?? OPS_SOCKET_ROTATE_POLL_MS;
270
+ const isLive = opts.isLive ?? ((p) => probeOpsSocketAccepting(p));
271
+ const now = opts.now ?? Date.now;
272
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
273
+ const deadline = now() + timeoutMs;
274
+ while (now() < deadline) {
275
+ if (await isLive(socketPath))
276
+ return true;
277
+ const remaining = deadline - now();
278
+ if (remaining <= 0)
279
+ break;
280
+ await sleep(Math.min(pollMs, remaining));
281
+ }
282
+ return false;
283
+ }
284
+ /**
285
+ * Rotate entry used by `flair init --reset-admin-pass`.
286
+ *
287
+ * Readiness is the operations socket accepting a connection, not HTTP
288
+ * health. Wait (bounded, real timeout) first. A dead leftover inode is
289
+ * not-ready. If the socket never becomes ready, refuse before any
290
+ * alter_user and before any pass-file write — never fall through to HTTP.
291
+ * On success: owner-only check, preflight, alter_user, then write.
292
+ */
293
+ export async function executeAdminPasswordRotate(opts) {
294
+ assertExplicitAdminPasswordRotate(opts.resetRequested);
295
+ const ready = await waitForOpsSocketReady(opts.socketPath, {
296
+ timeoutMs: opts.timeoutMs,
297
+ pollMs: opts.pollMs,
298
+ isLive: opts.isLive,
299
+ now: opts.now,
300
+ sleep: opts.sleep,
301
+ });
302
+ if (!ready) {
303
+ throw new Error(initAdminPassRefusalMessage("socket-not-ready", { socketPath: opts.socketPath }));
304
+ }
305
+ const preflight = prepareAdminPasswordRotate({
306
+ resetRequested: opts.resetRequested,
307
+ username: opts.username,
308
+ socketPath: opts.socketPath,
309
+ adminPassPath: opts.adminPassPath,
310
+ stat: opts.stat,
311
+ });
312
+ opts.onPreflight?.(preflight);
313
+ const rotate = opts.rotate ?? rotateAdminPasswordViaOpsSocket;
314
+ await rotate(opts.socketPath, opts.username, opts.password);
315
+ opts.writeAdminPassFile(opts.adminPassPath, opts.password + "\n");
316
+ }
@@ -88,6 +88,22 @@ export function readPlistProgramRefs(plistPath, read = (p) => readFileSync(p, "u
88
88
  const wd = raw.match(/<key>WorkingDirectory<\/key>\s*<string>([^<]*)<\/string>/);
89
89
  return { programArguments, workingDirectory: wd ? unescapeXml(wd[1]) : null };
90
90
  }
91
+ /**
92
+ * Does this plist embed the admin password inline?
93
+ *
94
+ * The flair#1573 pass-file shape never contains this key: the launcher reads the
95
+ * password from a 0600 file at start time. A plist with the key
96
+ * `<key>HDB_ADMIN_PASSWORD</key>` is the pre-#1573 inline shape — a secret
97
+ * written into a config file (world-readable), and a downgrade of an adopted
98
+ * instance (flair#1693).
99
+ *
100
+ * Deliberately key-presence only: the pass-file launcher's argv names the file
101
+ * but never the key, so there is no legitimate plist shape this misfires on. It
102
+ * never returns plist contents — only the boolean.
103
+ */
104
+ export function plistCarriesInlineAdminPassword(raw) {
105
+ return /<key>HDB_ADMIN_PASSWORD<\/key>/.test(raw);
106
+ }
91
107
  /**
92
108
  * Does this plist still point at things that exist?
93
109
  *