@tpsdev-ai/flair 0.55.2 → 0.56.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 (60) hide show
  1. package/README.md +3 -3
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +10 -12
  7. package/dist/commands/attention.js +2 -2
  8. package/dist/commands/backup.js +2 -2
  9. package/dist/commands/doctor.js +39 -28
  10. package/dist/commands/export.js +2 -2
  11. package/dist/commands/federation.js +185 -38
  12. package/dist/commands/hook.js +4 -4
  13. package/dist/commands/init.js +30 -8
  14. package/dist/commands/mcp.js +2 -2
  15. package/dist/commands/migrate-harness-memory.js +8 -8
  16. package/dist/commands/rem.js +2 -2
  17. package/dist/commands/service.js +25 -1
  18. package/dist/commands/session.js +2 -2
  19. package/dist/commands/uninstall.js +2 -2
  20. package/dist/commands/upgrade.js +3 -3
  21. package/dist/doctor-client.js +5 -23
  22. package/dist/engine-version.js +2 -2
  23. package/dist/federation/scheduler.js +5 -5
  24. package/dist/install/clients.js +5 -10
  25. package/dist/keystore.js +10 -2
  26. package/dist/lib/auth-resolve.js +5 -5
  27. package/dist/lib/doctor-config-path.js +2 -2
  28. package/dist/lib/flair-paths.js +29 -0
  29. package/dist/lib/home.js +60 -0
  30. package/dist/lib/launchd-repair.js +6 -0
  31. package/dist/lib/mcp-enable.js +4 -4
  32. package/dist/lib/owned-pins.js +1 -13
  33. package/dist/lib/socket-path-limit.js +120 -0
  34. package/dist/lib/uninstall-purge.js +2 -18
  35. package/dist/lib/upgrade-plain-tree.js +2 -2
  36. package/dist/mcp-client-assertion.js +3 -3
  37. package/dist/rem/runner.js +3 -3
  38. package/dist/rem/scheduler.js +5 -5
  39. package/dist/rem/snapshot.js +2 -2
  40. package/dist/resources/OAuth.js +62 -11
  41. package/dist/resources/Presence.js +135 -47
  42. package/dist/resources/admin-layout.js +7 -2
  43. package/dist/resources/memory-reflect-lib.js +17 -1
  44. package/dist/src/keystore.js +10 -2
  45. package/dist/src/lib/home.js +60 -0
  46. package/dist/src/rem/scheduler.js +5 -5
  47. package/dist/version-check.js +2 -2
  48. package/dist/version-handshake.js +2 -2
  49. package/docs/api-reference.md +31 -6
  50. package/docs/auth.md +14 -2
  51. package/docs/deploying-on-fabric.md +5 -4
  52. package/docs/deployment.md +26 -37
  53. package/docs/embedding-in-a-harper-app.md +4 -2
  54. package/docs/entity-vocabulary.md +5 -5
  55. package/docs/federation.md +39 -19
  56. package/docs/hosted-on-fabric.md +7 -5
  57. package/docs/mcp-clients.md +29 -12
  58. package/docs/spoke-bringup.md +41 -22
  59. package/docs/standalone-local.md +12 -16
  60. package/package.json +1 -1
@@ -18,10 +18,10 @@
18
18
  */
19
19
  import { mkdirSync, writeFileSync, statSync, chmodSync, rmSync, existsSync, readdirSync } from "node:fs";
20
20
  import { resolve } from "node:path";
21
- import { homedir } from "node:os";
22
21
  import { create as tarCreate, extract as tarExtract, list as tarList } from "tar";
23
22
  import { validateSnapshotArchive } from "../lib/safe-snapshot-extract.js";
24
- export const SNAPSHOT_ROOT = resolve(homedir(), ".flair", "snapshots");
23
+ import { resolveHome } from "../lib/home.js";
24
+ export const SNAPSHOT_ROOT = resolve(resolveHome(), ".flair", "snapshots");
25
25
  /** Validates the agent id and returns its snapshot directory. */
26
26
  export function remSnapshotDir(agent) {
27
27
  if (!/^[a-zA-Z0-9_-]+$/.test(agent)) {
@@ -4,6 +4,7 @@ import { handleJwtBearerGrant } from "./XAA.js";
4
4
  import { resolveAgentAuth } from "./agent-auth.js";
5
5
  import { decideRegistration } from "./dcr-gate.js";
6
6
  import { buildAuthorizationServerMetadata } from "./oauth-discovery.js";
7
+ import { esc } from "./admin-layout.js";
7
8
  /**
8
9
  * OAuth 2.1 Authorization Server for Flair.
9
10
  *
@@ -22,9 +23,32 @@ import { buildAuthorizationServerMetadata } from "./oauth-discovery.js";
22
23
  * - No "remember this decision" — each authorize is explicit
23
24
  */
24
25
  const ALLOWED_REDIRECT_URI = "https://claude.com/api/mcp/auth_callback";
26
+ // The callback's ORIGIN, derived from the SAME constant the redirect_uri check
27
+ // uses — never a second literal. The consent form's POST answers with a 302 to
28
+ // this origin, and `form-action` is enforced across redirects, so it must be an
29
+ // allowed form-action target.
30
+ const ALLOWED_REDIRECT_ORIGIN = new URL(ALLOWED_REDIRECT_URI).origin;
25
31
  const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
26
32
  const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
27
33
  const AUTH_CODE_TTL_MS = 600_000; // 10 minutes
34
+ /**
35
+ * The scopes this server can issue, straight from the authorization-server
36
+ * metadata — ONE source of truth, so the consent page can never render a scope
37
+ * the token endpoint would later refuse.
38
+ */
39
+ const SUPPORTED_SCOPES = new Set(buildAuthorizationServerMetadata().scopes_supported);
40
+ /** `state` is an opaque passthrough: printable ASCII, bounded (RFC 6749 §4.1.2). */
41
+ const STATE_MAX_LENGTH = 512;
42
+ function isOpaqueState(value) {
43
+ if (value.length > STATE_MAX_LENGTH)
44
+ return false;
45
+ for (let i = 0; i < value.length; i++) {
46
+ const c = value.charCodeAt(i);
47
+ if (c < 0x20 || c > 0x7e)
48
+ return false;
49
+ }
50
+ return true;
51
+ }
28
52
  function sha256(input) {
29
53
  return createHash("sha256").update(input).digest("hex");
30
54
  }
@@ -169,7 +193,7 @@ export class OAuthAuthorize extends Resource {
169
193
  const clientId = url.searchParams.get("client_id") ?? "";
170
194
  const redirectUri = url.searchParams.get("redirect_uri") ?? "";
171
195
  const responseType = url.searchParams.get("response_type") ?? "";
172
- const scope = url.searchParams.get("scope") ?? "memory:read";
196
+ const scope = (url.searchParams.get("scope") ?? "").trim() || "memory:read";
173
197
  const state = url.searchParams.get("state") ?? "";
174
198
  const codeChallenge = url.searchParams.get("code_challenge") ?? "";
175
199
  const codeChallengeMethod = url.searchParams.get("code_challenge_method") ?? "";
@@ -183,6 +207,23 @@ export class OAuthAuthorize extends Resource {
183
207
  status: 400, headers: { "content-type": "application/json" },
184
208
  });
185
209
  }
210
+ // `state` is an opaque passthrough: printable ASCII, bounded. Anything else
211
+ // is refused (400) BEFORE rendering, so it can never reach the page.
212
+ if (!isOpaqueState(state)) {
213
+ return new Response(JSON.stringify({
214
+ error: "invalid_request",
215
+ error_description: `state must be printable ASCII of at most ${STATE_MAX_LENGTH} characters`,
216
+ }), { status: 400, headers: { "content-type": "application/json" } });
217
+ }
218
+ // Every requested scope must be one the server advertises (RFC 6749
219
+ // §4.1.2.1: invalid_scope).
220
+ const scopeTokens = scope.split(/\s+/).filter(Boolean);
221
+ if (scopeTokens.some((s) => !SUPPORTED_SCOPES.has(s))) {
222
+ return new Response(JSON.stringify({
223
+ error: "invalid_scope",
224
+ error_description: "one or more requested scopes are not supported by this server",
225
+ }), { status: 400, headers: { "content-type": "application/json" } });
226
+ }
186
227
  // Verify client exists
187
228
  const client = await databases.flair.OAuthClient.get(clientId);
188
229
  if (!client) {
@@ -190,7 +231,9 @@ export class OAuthAuthorize extends Resource {
190
231
  status: 400, headers: { "content-type": "application/json" },
191
232
  });
192
233
  }
193
- // Server-rendered consent page (minimal HTML, no JS frameworks)
234
+ // Server-rendered consent page (minimal HTML, no JS frameworks). EVERY
235
+ // interpolated value passes through `esc` — correct for element text and
236
+ // for the double-quoted attribute values below.
194
237
  const html = `<!DOCTYPE html>
195
238
  <html><head><title>Flair — Authorize</title>
196
239
  <style>body{font-family:system-ui;max-width:480px;margin:60px auto;padding:0 20px}
@@ -198,22 +241,30 @@ h1{font-size:1.4em}button{padding:10px 24px;font-size:1em;border:none;border-rad
198
241
  .approve{background:#2563eb;color:#fff}.deny{background:#e5e7eb;color:#333}
199
242
  .scope{background:#f3f4f6;padding:8px 12px;border-radius:4px;margin:4px 0;font-family:monospace}</style></head>
200
243
  <body>
201
- <h1>Authorize ${client.name || clientId}</h1>
244
+ <h1>Authorize ${esc(client.name || clientId)}</h1>
202
245
  <p>This application wants to access your Flair memories:</p>
203
- ${scope.split(" ").map((s) => `<div class="scope">${s}</div>`).join("")}
246
+ ${scopeTokens.map((s) => `<div class="scope">${esc(s)}</div>`).join("")}
204
247
  <form method="POST" action="/OAuthAuthorize" style="margin-top:24px">
205
- <input type="hidden" name="client_id" value="${clientId}">
206
- <input type="hidden" name="redirect_uri" value="${redirectUri || ALLOWED_REDIRECT_URI}">
207
- <input type="hidden" name="scope" value="${scope}">
208
- <input type="hidden" name="state" value="${state}">
209
- <input type="hidden" name="code_challenge" value="${codeChallenge}">
210
- <input type="hidden" name="code_challenge_method" value="${codeChallengeMethod}">
248
+ <input type="hidden" name="client_id" value="${esc(clientId)}">
249
+ <input type="hidden" name="redirect_uri" value="${esc(redirectUri || ALLOWED_REDIRECT_URI)}">
250
+ <input type="hidden" name="scope" value="${esc(scope)}">
251
+ <input type="hidden" name="state" value="${esc(state)}">
252
+ <input type="hidden" name="code_challenge" value="${esc(codeChallenge)}">
253
+ <input type="hidden" name="code_challenge_method" value="${esc(codeChallengeMethod)}">
211
254
  <button type="submit" name="action" value="approve" class="approve">Approve</button>
212
255
  <button type="submit" name="action" value="deny" class="deny">Deny</button>
213
256
  </form></body></html>`;
214
257
  return new Response(html, {
215
258
  status: 200,
216
- headers: { "content-type": "text/html; charset=utf-8" },
259
+ headers: {
260
+ "content-type": "text/html; charset=utf-8",
261
+ // No script is needed by this page; an inline <style> is the only
262
+ // non-default allowance. The form posts back here and the POST answers
263
+ // with a 302 to the pinned callback, so that origin must be allowed too.
264
+ // Nothing may frame the consent page.
265
+ "content-security-policy": `default-src 'none'; frame-ancestors 'none'; style-src 'unsafe-inline'; form-action 'self' ${ALLOWED_REDIRECT_ORIGIN}`,
266
+ "x-content-type-options": "nosniff",
267
+ },
217
268
  });
218
269
  }
219
270
  async post(data) {
@@ -1,37 +1,43 @@
1
1
  /**
2
2
  * POST /Presence — agent heartbeat writes its own presence.
3
- * GET /Presence — public-safe presence roster for The Office Space.
3
+ * GET /Presence — verified-reader roster for The Office Space (public roster
4
+ * is an explicit opt-in, flair#1880).
4
5
  *
5
6
  * Extends the auto-generated Presence table resource (from schema.graphql).
6
7
  * Overrides get() for public-safe roster and post() for Ed25519-authed
7
8
  * heartbeat writes.
8
9
  *
9
10
  * Auth:
10
- * GET — public (returns only allowlisted fields; safe for public renderer).
11
- * currentTask is additionally content-gated to verified agents only
12
- * (#592) — anonymous callers get the roster with currentTask=null.
11
+ * GET — requires a VERIFIED reader by default (flair#1880): a valid
12
+ * TPS-Ed25519 signature from an agent registered on this instance, or
13
+ * the admin credential. An anonymous caller gets 401. Set
14
+ * `PRESENCE_PUBLIC_ROSTER=true` (publicRosterEnabled()) to opt in to
15
+ * the pre-#1880 anonymous, field-allowlisted roster. For a verified
16
+ * reader, currentTask/flairVersion/harperVersion stay content-gated
17
+ * to a valid TPS-Ed25519 signature (#592/#639).
13
18
  * POST — Ed25519 agent credential (TPS-Ed25519 header). Agent writes only its
14
19
  * own record; cross-agent writes are rejected (403).
15
20
  *
16
21
  * Security (Sherlock):
17
22
  * - Write: per-agent Ed25519 auth. Cross-agent → 403.
18
- * - Read: field-allowlisted to public-safe set. No secrets, no admin data.
23
+ * - Read: verified reader by default (401 for anonymous); when the
24
+ * publicRoster opt-in is on, the roster is field-allowlisted to a
25
+ * public-safe set. No secrets, no admin data.
19
26
  * - currentTask is agent-authored free text → cap length, escape on render.
20
- * - currentTask CONTENT gate (#592): the roster (id/displayName/role/
21
- * runtime/activity/presenceStatus/lastHeartbeatAt) is genuinely
22
- * public-safe and stays world-readable, but currentTask is free text that
23
- * the coordination convention (`presence set --task "investigating
24
- * <host>: <symptom>"`) has put customer names and preprod hostnames in.
25
- * sanitizeCurrentTask() only trims/caps length — it does not redact
26
- * content. get() additionally gates currentTask itself to verified
27
- * in-org agents only; see get()'s inline comment.
27
+ * - currentTask CONTENT gate (#592): for a verified reader the roster
28
+ * (id/displayName/role/runtime/activity/presenceStatus/lastHeartbeatAt) is
29
+ * public-safe, but currentTask is free text that the coordination
30
+ * convention (`presence set --task "investigating <host>: <symptom>"`) has
31
+ * put customer names and preprod hostnames in. sanitizeCurrentTask() only
32
+ * trims/caps length — it does not redact content. get() gates currentTask
33
+ * (and the versions) to a valid signature; see get()'s inline comment.
28
34
  */
29
35
  import { databases } from "harper";
30
36
  import { existsSync, readFileSync } from "node:fs";
31
37
  import { dirname, join } from "node:path";
32
38
  import { fileURLToPath } from "node:url";
33
39
  import { createRequire } from "node:module";
34
- import { resolveAgentAuth, verifyAgentRequest, isPrincipalDeactivated } from "./agent-auth.js";
40
+ import { resolveAgentAuth, isPrincipalDeactivated } from "./agent-auth.js";
35
41
  import { agentRecordIsAdmin } from "./agent-admin.js";
36
42
  import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
37
43
  // ─── Constants ────────────────────────────────────────────────────────────────
@@ -45,6 +51,66 @@ function offlineThresholdMs() {
45
51
  const env = process.env.PRESENCE_OFFLINE_THRESHOLD_MS;
46
52
  return env ? Number(env) || 600_000 : 600_000;
47
53
  }
54
+ /**
55
+ * Is the PUBLIC roster opt-in enabled? (flair#1880) Default OFF.
56
+ *
57
+ * Read from `PRESENCE_PUBLIC_ROSTER` — the same env-var channel the two
58
+ * presence config keys above use (`PRESENCE_IDLE_THRESHOLD_MS` /
59
+ * `PRESENCE_OFFLINE_THRESHOLD_MS`); this is the file where presence config is
60
+ * read. Truthy: `1` / `true` / `yes` / `on` (case-insensitive), matching the
61
+ * repo-wide boolean-env vocabulary (mcp-oauth-flag.ts, mcp-handler.ts,
62
+ * rate-limit.ts). Anything else — unset, empty, `false`, `0`, garbage — is OFF,
63
+ * so the DEFAULT is a verified reader.
64
+ *
65
+ * OFF → GET /Presence requires a verified reader (a valid TPS-Ed25519
66
+ * signature from a registered agent, or the admin credential); an
67
+ * anonymous caller gets 401 (see get()).
68
+ * ON → today's behaviour exactly: an anonymous caller gets the
69
+ * field-allowlisted roster with currentTask / flairVersion /
70
+ * harperVersion null.
71
+ *
72
+ * Documented as "publishes your roster to the internet".
73
+ */
74
+ export function publicRosterEnabled() {
75
+ const raw = (process.env.PRESENCE_PUBLIC_ROSTER ?? "").trim().toLowerCase();
76
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
77
+ }
78
+ /**
79
+ /**
80
+ * Resolve the GET /Presence read verdict from the verdict the AUTH MIDDLEWARE
81
+ * already established, rather than re-verifying the request here (flair#1880
82
+ * F2; exactly the collision resources/AttentionQuery.ts documents).
83
+ *
84
+ * GET /Presence/<id> is NOT on auth-middleware.ts's short-circuit list (only
85
+ * the exact "/Presence" collection GET is). The middleware verifies the
86
+ * TPS-Ed25519 signature and records the nonce in the ONE shared nonce store,
87
+ * annotating request.tpsAgent but NOT verifyAgentRequest's per-request memo.
88
+ * Calling verifyAgentRequest() again would re-consume that same nonce, read as
89
+ * a replay (isNonceReplay) and deny a legitimate agent. resolveAgentAuth()
90
+ * consults the middleware's tpsAgent/tpsAnonymous annotations FIRST, and only
91
+ * falls back to a header verify when the middleware never ran (the
92
+ * short-circuited collection GET) — so it reuses the established verdict
93
+ * instead of re-running a doomed second signature check. It is the repo's ONE
94
+ * resolver, not a second verifier.
95
+ *
96
+ * verifiedReader — kind !== "anonymous": a signature-verified agent,
97
+ * the admin credential, or a trusted in-process call
98
+ * (kind "internal").
99
+ * includeVerifiedFields — the #592/#639 content gate, UNCHANGED: only a
100
+ * request presenting a TPS-Ed25519 SIGNATURE sees
101
+ * currentTask/flairVersion/harperVersion. The admin
102
+ * credential authorizes the read but is not a
103
+ * signature, so it stays redacted. An in-process
104
+ * caller's seeded `_flairAgentAuth` memo counts.
105
+ */
106
+ async function presenceReaderVerdict(ctx) {
107
+ const auth = await resolveAgentAuth(ctx);
108
+ const verifiedReader = auth.kind !== "anonymous";
109
+ const request = ctx?.request ?? ctx;
110
+ const header = request?.headers?.get?.("authorization") ?? request?.headers?.asObject?.authorization ?? "";
111
+ const includeVerifiedFields = verifiedReader && (parseTpsEd25519Header(header) !== null || request?._flairAgentAuth != null);
112
+ return { verifiedReader, includeVerifiedFields };
113
+ }
48
114
  // ─── Version stamping (flair#639) ──────────────────────────────────────────────
49
115
  //
50
116
  // Auto-presence (packages/flair-mcp/src/presence.ts, flair#608) gives agents a
@@ -253,7 +319,19 @@ function pickAllowlisted(record) {
253
319
  * public-safe roster view and post() for Ed25519-authed heartbeat writes.
254
320
  */
255
321
  export class Presence extends databases.flair.Presence {
256
- /** Bypass Harper's role gate for GET (public-safe data only). */
322
+ /**
323
+ * GET /Presence read authorization is enforced in get(), NOT here (flair#1880).
324
+ *
325
+ * Returning `false` from allowRead() makes Harper throw AccessViolation and
326
+ * reply **403** — MEASURED on the harness Harper: with allowRead() → false, an
327
+ * anonymous GET /Presence returned 403 (context.user is truthy, so
328
+ * AccessViolation picks its 403 branch). The issue requires **401** for an
329
+ * anonymous reader, and a resource can only choose a status by returning a
330
+ * Response from get(). So the verified-reader gate lives in get(), and
331
+ * allowRead() stays `true` so the request reaches it and gets the correct 401
332
+ * instead of a 403. (The currentTask content gate has likewise always lived in
333
+ * get(), never here.)
334
+ */
257
335
  allowRead() {
258
336
  return true;
259
337
  }
@@ -262,7 +340,7 @@ export class Presence extends databases.flair.Presence {
262
340
  return true;
263
341
  }
264
342
  /**
265
- * GET /Presence — public-safe presence roster.
343
+ * GET /Presence — verified-reader roster (see presenceReaderVerdict()).
266
344
  *
267
345
  * Joins Presence records with Agent metadata and derives presenceStatus.
268
346
  * Only allowlisted fields are returned (no secrets, no admin data).
@@ -274,43 +352,53 @@ export class Presence extends databases.flair.Presence {
274
352
  * array), so gating once here, before the loop, covers every read path with
275
353
  * no separate return site to miss.
276
354
  *
277
- * The gate keys off a valid TPS-Ed25519 SIGNATURE (verifyAgentRequest),
278
- * NOT resolveAgentAuth()/allowVerified — and that distinction is the whole
279
- * fix. /Presence is a public-passthrough in auth-middleware.ts: the
280
- * middleware early-returns WITHOUT annotating tpsAgent/tpsAnonymous, so a
281
- * resource-level resolver never sees a gate annotation for this path. Worse,
282
- * Harper's `authorizeLocal` (config default true) auto-authorizes any
283
- * *credential-less* loopback request as super_user — it injects request.user
284
- * ONLY "when there is no Authorization header" (node .../server/http.js). So a
285
- * bare, unauthenticated `GET /Presence` from loopback (exactly the anonymous
286
- * caller the issue is about, and what the integration test exercises against
287
- * a real spawned Harper) arrives with request.user = super_user and NO
288
- * signature. resolveAgentAuth() would classify that as `kind:"agent"` (its
289
- * super_user branch) and leak currentTask — which it did, against real
290
- * Harper, even though mocked unit tests using tpsAgent annotations passed.
291
- * A TPS-Ed25519 signature, by contrast, cannot be manufactured by
292
- * authorizeLocal (it requires the Authorization header, which suppresses the
293
- * super_user injection), so verifyAgentRequest() cleanly separates a real
294
- * in-org agent from an anonymous/loopback/Basic-admin caller. Only a valid
295
- * agent signature gets currentTask; everything else (anonymous, loopback
296
- * super_user, Basic-admin, internal in-process) gets currentTask=null.
297
- * allowRead() is UNCHANGED (still `true`) — the roster itself stays public;
298
- * only the free-text field is gated, per the issue's field-level option.
355
+ * The CONTENT gate (#592/#639) keys off whether the request presents a
356
+ * TPS-Ed25519 SIGNATURE (`includeVerifiedFields`, see presenceReaderVerdict()):
357
+ * only a signature-verified agent sees currentTask/flairVersion/harperVersion.
358
+ * An admin credential verifies the READER but is not a signature, so it still
359
+ * gets those three as null, exactly as before; anonymous/loopback/internal
360
+ * without that signal likewise.
361
+ *
362
+ * The READER decision is resolved from the auth MIDDLEWARE's already-
363
+ * established verdict via resolveAgentAuth() — NOT by re-verifying the header
364
+ * here (flair#1880 F2). /Presence is a public-passthrough in
365
+ * auth-middleware.ts, and GET /Presence/<id> is not: on a by-id read the
366
+ * middleware has ALREADY verified the signature and consumed its nonce in the
367
+ * one shared nonce store, so a second verifyAgentRequest() would read as a
368
+ * replay and deny a legitimate agent. resolveAgentAuth() checks the
369
+ * middleware's tpsAgent/tpsAnonymous annotations first and only falls back to
370
+ * a header verify for the short-circuited collection GET. The old
371
+ * authorizeLocal-forged-super_user vector (#610) stays closed: the middleware
372
+ * marks a credential-less request tpsAnonymous (checked first), and
373
+ * resolveAgentAuth never trusts a `context.user` without a credential header.
374
+ * allowRead() is UNCHANGED (still `true`): the read gate lives in get() so it
375
+ * can return 401 (allowRead()=false would return 403 — see that method).
299
376
  *
300
377
  * flairVersion/harperVersion (flair#639) ride the SAME gate, renamed to
301
378
  * includeVerifiedFields since it now covers more than currentTask — see the
302
379
  * ROSTER_ALLOWLIST comment above for why version numbers are gated too.
380
+ *
381
+ * READ gate (flair#1880): the roster ITSELF now requires a verified reader by
382
+ * default — a valid TPS-Ed25519 signature from an agent registered on this
383
+ * instance, or the admin credential. An anonymous/unverified caller gets 401
384
+ * (the same method emits it, so the status is ours to choose; see allowRead()).
385
+ * `PRESENCE_PUBLIC_ROSTER` (publicRosterEnabled(), default false) is the
386
+ * explicit opt-in that restores the pre-#1880 anonymous, field-allowlisted
387
+ * roster (gated fields null). The gate runs BEFORE the loop, so `GET /Presence`
388
+ * and `GET /Presence/<id>` are both covered by the one return site. The
389
+ * allowlist and the includeVerifiedFields content gate are UNCHANGED for
390
+ * verified readers.
303
391
  */
304
392
  async get() {
305
393
  // Extract the raw request the same way post() does (getContext().request
306
- // is populated for GET; fall back to the context itself). verifyAgentRequest
307
- // returns the agent for a valid TPS-Ed25519 signature, else null — see the
308
- // gate rationale above. Memoized per-request, so this is a no-op if any
309
- // other path already verified the same request.
394
+ // is populated for GET; fall back to the context itself).
310
395
  const ctx = this.getContext?.();
311
- const request = ctx?.request ?? ctx;
312
- const agentAuth = request ? await verifyAgentRequest(request) : null;
313
- const includeVerifiedFields = agentAuth !== null;
396
+ // READ GATE (flair#1880) + content gate, both resolved from the verdict the
397
+ // auth middleware already established — see presenceReaderVerdict().
398
+ const { verifiedReader, includeVerifiedFields } = await presenceReaderVerdict(ctx);
399
+ if (!verifiedReader && !publicRosterEnabled()) {
400
+ return new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
401
+ }
314
402
  const now = Date.now();
315
403
  const idleThreshold = idleThresholdMs();
316
404
  const offlineThreshold = offlineThresholdMs();
@@ -349,8 +437,8 @@ export class Presence extends databases.flair.Presence {
349
437
  const entry = {
350
438
  id: agentId,
351
439
  displayName: agent?.displayName ?? agent?.name ?? agentId,
352
- // `role` is a human label on a PUBLIC roster (allowRead() is `true`),
353
- // and it is also the field that decides administrator status
440
+ // `role` is a human label on a PUBLIC roster (the publicRoster
441
+ // opt-in serves it anonymously), and it is also the field that decides administrator status
354
442
  // (resources/agent-admin.ts). Publishing the admin sentinel would
355
443
  // hand an unauthenticated reader the list of privileged principals —
356
444
  // so the roster reports admins as ordinary agents. It is a display
@@ -27,7 +27,11 @@ function resolveVersion() {
27
27
  return process.env.npm_package_version ?? "dev";
28
28
  }
29
29
  const VERSION = resolveVersion();
30
- /** Escape HTML special characters to prevent stored XSS. */
30
+ /**
31
+ * Escape HTML special characters. Correct for BOTH element text and
32
+ * double-quoted attribute values, so every interpolation can use it:
33
+ * `&`, `<`, `>`, `"`, `'` and backtick.
34
+ */
31
35
  export function esc(str) {
32
36
  if (!str)
33
37
  return "";
@@ -36,7 +40,8 @@ export function esc(str) {
36
40
  .replace(/</g, "&lt;")
37
41
  .replace(/>/g, "&gt;")
38
42
  .replace(/"/g, "&quot;")
39
- .replace(/'/g, "&#39;");
43
+ .replace(/'/g, "&#39;")
44
+ .replace(/`/g, "&#96;");
40
45
  }
41
46
  export function layout(title, content, activePage) {
42
47
  const nav = [
@@ -400,9 +400,25 @@ function sourceMemoryElement(m) {
400
400
  // until its escaped form fits the room the marker leaves.
401
401
  const limit = Math.max(0, SOURCE_EXCERPT_BUDGET - SOURCE_EXCERPT_MARKER.length);
402
402
  let kept = content.slice(0, limit);
403
+ // The initial budget cut can land between the two code units of an astral
404
+ // character, leaving kept ending in a lone high surrogate (flair#1772). Drop
405
+ // any trailing lone high surrogate so this cut lands on a code-point boundary.
406
+ while (kept.length >= 1 &&
407
+ kept.charCodeAt(kept.length - 1) >= 0xd800 &&
408
+ kept.charCodeAt(kept.length - 1) <= 0xdbff) {
409
+ kept = kept.slice(0, kept.length - 1);
410
+ }
403
411
  let keptEscaped = escapeElementText(kept);
404
412
  while (keptEscaped.length > limit && kept.length > 0) {
405
- kept = kept.slice(0, -1);
413
+ // Drop one whole code point: a complete surrogate pair (two code units) when
414
+ // the tail is a pair, otherwise a single BMP code unit (flair#1772).
415
+ const n = kept.length;
416
+ const tailIsPair = n >= 2 &&
417
+ kept.charCodeAt(n - 1) >= 0xdc00 &&
418
+ kept.charCodeAt(n - 1) <= 0xdfff &&
419
+ kept.charCodeAt(n - 2) >= 0xd800 &&
420
+ kept.charCodeAt(n - 2) <= 0xdbff;
421
+ kept = kept.slice(0, n - (tailIsPair ? 2 : 1));
406
422
  keptEscaped = escapeElementText(kept);
407
423
  }
408
424
  return `<memory id="${id}" date="${date}" excerpt="true">${keptEscaped}${SOURCE_EXCERPT_MARKER}</memory>`;
@@ -10,11 +10,19 @@
10
10
  */
11
11
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
12
  import { join } from "node:path";
13
- import { homedir } from "node:os";
13
+ import { resolveHome } from "./lib/home.js";
14
14
  import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
15
15
  // ─── Helpers ────────────────────────────────────────────────────────────────
16
+ /**
17
+ * The keystore's home comes from the ONE shared resolver (src/lib/home.ts,
18
+ * flair#1853 round 3): resolved at CALL time, with the platform rule (Windows
19
+ * uses USERPROFILE, everywhere else HOME). The runtime caches `os.homedir()` at
20
+ * process start, so a HOME set after start — the test harness in
21
+ * test/helpers/sandbox-home.ts — would otherwise be invisible and the keystore
22
+ * would reach the REAL ~/.flair/keys.
23
+ */
16
24
  function keysDir() {
17
- return join(homedir(), ".flair", "keys");
25
+ return join(resolveHome(), ".flair", "keys");
18
26
  }
19
27
  function keyPath(instanceId) {
20
28
  // Sanitize instanceId to prevent directory traversal
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The user's home directory, resolved at CALL time (flair#1853).
3
+ *
4
+ * `os.homedir()` is cached at process start, so a HOME set later in the same
5
+ * process is invisible to it. Every Flair surface that resolves `~` — the
6
+ * keystore and the client config writers — must land on the SAME home, and it
7
+ * must be the one the calling shell actually uses.
8
+ *
9
+ * Which environment variable names that home differs by platform:
10
+ *
11
+ * - **Windows** — `USERPROFILE` is authoritative. Node's `os.homedir()` reads
12
+ * it, but a POSIX-style shell (Git Bash, MSYS, Cygwin) may set `HOME` to a
13
+ * different path. Preferring `HOME` there would move `~/.flair/keys` away
14
+ * from where the keys actually live, so an existing key would read as
15
+ * missing (and a new one would be written somewhere nothing looks).
16
+ * - **Everywhere else** — `HOME` is authoritative (and is how the test harness
17
+ * redirects a process), with `os.homedir()` as the fallback.
18
+ */
19
+ import { homedir } from "node:os";
20
+ /** The home directory for this invocation, resolved at call time. */
21
+ export function resolveHome() {
22
+ return process.platform === "win32"
23
+ ? process.env.USERPROFILE || homedir()
24
+ : process.env.HOME || homedir();
25
+ }
26
+ /**
27
+ * Run `fn` with BOTH `HOME` and `USERPROFILE` pointed at `homeDir`, then restore
28
+ * both to exactly what they were — including the previously-UNSET case, and even
29
+ * when `fn` throws. Returns `fn`'s value.
30
+ *
31
+ * `resolveHome()` reads `USERPROFILE` on win32 and `HOME` elsewhere, so setting
32
+ * only `HOME` silently ignored the override on Windows: doctor, the pin refresh
33
+ * and uninstall's `unwire()` then acted on the real profile instead of the
34
+ * directory the caller named. Both are set here, so the override holds on every
35
+ * platform.
36
+ *
37
+ * `fn` MUST be synchronous. The parameter type REJECTS a Promise-returning
38
+ * callback at compile time (a Promise is not assignable to the `never` branch),
39
+ * because a sync save/restore around async work would restore the environment
40
+ * before the work runs.
41
+ */
42
+ export function withHome(homeDir, fn) {
43
+ const prevHome = process.env.HOME;
44
+ const prevProfile = process.env.USERPROFILE;
45
+ process.env.HOME = homeDir;
46
+ process.env.USERPROFILE = homeDir;
47
+ try {
48
+ return fn();
49
+ }
50
+ finally {
51
+ if (prevHome === undefined)
52
+ delete process.env.HOME;
53
+ else
54
+ process.env.HOME = prevHome;
55
+ if (prevProfile === undefined)
56
+ delete process.env.USERPROFILE;
57
+ else
58
+ process.env.USERPROFILE = prevProfile;
59
+ }
60
+ }
@@ -15,25 +15,25 @@
15
15
  */
16
16
  import { existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
17
17
  import { resolve, dirname } from "node:path";
18
- import { homedir } from "node:os";
19
18
  import { spawn } from "node:child_process";
20
19
  import { fileURLToPath } from "node:url";
21
20
  import { escapeXml } from "../lib/xml-escape.js";
22
21
  import { detectPlatform as detectPlatformFor, spawnReport, readTemplate as readTemplateFrom, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, describeExitCode, resolveNodeBin, resolveFlairBin, formatFlairBinWarning, verifyFirstRun, probeUserLingerEnabled, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
22
+ import { resolveHome } from "../lib/home.js";
23
23
  // Re-exported so this module's public surface is unchanged by the extraction
24
24
  // into src/lib/scheduler-platform.ts (a second scheduler — `flair federation
25
25
  // sync enable` — needs the identical launchctl/systemctl interpretation, and
26
26
  // flair#850's lesson must have exactly one implementation).
27
27
  export { interpretActiveResult };
28
- export const SHIM_PATH_DEFAULT = resolve(homedir(), ".flair", "bin", "flair-rem-nightly");
28
+ export const SHIM_PATH_DEFAULT = resolve(resolveHome(), ".flair", "bin", "flair-rem-nightly");
29
29
  // Unit names, exported (flair#1278) so `flair doctor`'s scheduled-drivers
30
30
  // section addresses the same job this module installs — same single-source
31
31
  // rule as the federation scheduler's LAUNCHD_LABEL/SYSTEMD_*_UNIT constants.
32
32
  export const LAUNCHD_LABEL = "dev.flair.rem.nightly";
33
33
  export const SYSTEMD_TIMER_UNIT = "flair-rem-nightly.timer";
34
34
  export const SYSTEMD_SERVICE_UNIT = "flair-rem-nightly.service";
35
- export const LAUNCHD_PLIST_PATH = resolve(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
36
- export const SYSTEMD_USER_DIR = resolve(homedir(), ".config", "systemd", "user");
35
+ export const LAUNCHD_PLIST_PATH = resolve(resolveHome(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
36
+ export const SYSTEMD_USER_DIR = resolve(resolveHome(), ".config", "systemd", "user");
37
37
  export const SYSTEMD_TIMER_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_TIMER_UNIT);
38
38
  export const SYSTEMD_SERVICE_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_SERVICE_UNIT);
39
39
  function detectPlatform(override) {
@@ -102,7 +102,7 @@ function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
102
102
  FLAIR_BIN: flairBin,
103
103
  NODE_BIN: nodeBin,
104
104
  SHIM_PATH: shimPath,
105
- HOME: opts.homeOverride ?? homedir(),
105
+ HOME: opts.homeOverride ?? resolveHome(),
106
106
  AGENT_ID: opts.agentId,
107
107
  FLAIR_URL: opts.flairUrl,
108
108
  HOUR: String(opts.hour),
@@ -29,12 +29,12 @@
29
29
  * current fact.
30
30
  */
31
31
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
32
- import { homedir } from "node:os";
33
32
  import { dirname, join } from "node:path";
34
33
  import { parseSemverCore } from "./fabric-upgrade.js";
35
34
  import { fetchLatestVersion } from "./lib/npm-registry.js";
35
+ import { resolveHome } from "./lib/home.js";
36
36
  export const FLAIR_PKG_NAME = "@tpsdev-ai/flair";
37
- export const DEFAULT_CACHE_PATH = join(homedir(), ".flair", ".version-check-cache.json");
37
+ export const DEFAULT_CACHE_PATH = join(resolveHome(), ".flair", ".version-check-cache.json");
38
38
  /** How long a cached "latest" answer is trusted before we re-hit the registry. */
39
39
  export const DEFAULT_TTL_MS = 12 * 60 * 60 * 1000; // 12h
40
40
  /** Registry fetch timeout — this runs on every status/doctor call, so it must stay short. */
@@ -17,10 +17,10 @@
17
17
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
18
18
  import { createHash } from "node:crypto";
19
19
  import { dirname, join } from "node:path";
20
- import { homedir } from "node:os";
20
+ import { resolveHome } from "./lib/home.js";
21
21
  export const DEFAULT_HANDSHAKE_TTL_MS = 60_000;
22
22
  export const DEFAULT_HANDSHAKE_TIMEOUT_MS = 1500; // within the spec's 1-2s budget
23
- export const DEFAULT_HANDSHAKE_CACHE_DIR = join(homedir(), ".flair", ".version-handshake-cache");
23
+ export const DEFAULT_HANDSHAKE_CACHE_DIR = join(resolveHome(), ".flair", ".version-handshake-cache");
24
24
  export function defaultHandshakeDeps() {
25
25
  return {
26
26
  fetchImpl: fetch,