@tpsdev-ai/flair 0.55.1 → 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.
- package/README.md +3 -3
- package/dist/bridges/builtins/markdown.js +2 -2
- package/dist/bridges/discover.js +2 -2
- package/dist/bridges/runtime/allow-list.js +2 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +201 -95
- package/dist/commands/attention.js +2 -2
- package/dist/commands/backup.js +2 -2
- package/dist/commands/doctor.js +168 -37
- package/dist/commands/export.js +2 -2
- package/dist/commands/federation.js +229 -95
- package/dist/commands/hook.js +4 -4
- package/dist/commands/init.js +94 -70
- package/dist/commands/mcp.js +2 -2
- package/dist/commands/migrate-harness-memory.js +8 -8
- package/dist/commands/rem.js +31 -4
- package/dist/commands/service.js +25 -1
- package/dist/commands/session.js +2 -2
- package/dist/commands/uninstall.js +2 -2
- package/dist/commands/upgrade.js +88 -69
- package/dist/doctor-client.js +341 -161
- package/dist/engine-version.js +2 -2
- package/dist/federation/scheduler.js +5 -5
- package/dist/hook-install.js +359 -176
- package/dist/install/clients.js +908 -214
- package/dist/keystore.js +10 -2
- package/dist/lib/auth-resolve.js +5 -5
- package/dist/lib/config-critical-section.js +557 -0
- package/dist/lib/doctor-config-path.js +2 -2
- package/dist/lib/doctor-run.js +107 -27
- package/dist/lib/flair-paths.js +29 -0
- package/dist/lib/home.js +60 -0
- package/dist/lib/launchd-repair.js +109 -0
- package/dist/lib/mcp-enable.js +4 -4
- package/dist/lib/owned-pins.js +256 -94
- package/dist/lib/pin-write-guard.js +87 -0
- package/dist/lib/settings-bytes.js +85 -0
- package/dist/lib/socket-path-limit.js +120 -0
- package/dist/lib/uninstall-purge.js +2 -18
- package/dist/lib/upgrade-plain-tree.js +2 -2
- package/dist/lib/upgrade-status.js +164 -0
- package/dist/lib/wiring-spec.js +238 -0
- package/dist/mcp-client-assertion.js +3 -3
- package/dist/rem/promote-policy.js +102 -0
- package/dist/rem/runner.js +3 -3
- package/dist/rem/scheduler.js +5 -5
- package/dist/rem/snapshot.js +2 -2
- package/dist/resources/MemoryReflect.js +10 -0
- package/dist/resources/OAuth.js +62 -11
- package/dist/resources/Presence.js +135 -47
- package/dist/resources/admin-layout.js +7 -2
- package/dist/resources/auto-promote-lib.js +56 -0
- package/dist/resources/health.js +26 -0
- package/dist/resources/memory-reflect-lib.js +215 -6
- package/dist/resources/migrations/progress.js +17 -0
- package/dist/resources/migrations/runner.js +46 -27
- package/dist/resources/migrations/status.js +2 -1
- package/dist/src/keystore.js +10 -2
- package/dist/src/lib/home.js +60 -0
- package/dist/src/rem/promote-policy.js +102 -0
- package/dist/src/rem/scheduler.js +5 -5
- package/dist/version-check.js +2 -2
- package/dist/version-handshake.js +2 -2
- package/docs/api-reference.md +31 -6
- package/docs/auth.md +14 -2
- package/docs/deploying-on-fabric.md +5 -4
- package/docs/deployment.md +26 -37
- package/docs/embedding-in-a-harper-app.md +4 -2
- package/docs/entity-vocabulary.md +5 -5
- package/docs/federation.md +58 -19
- package/docs/hosted-on-fabric.md +7 -5
- package/docs/mcp-clients.md +29 -12
- package/docs/releasing.md +66 -22
- package/docs/spoke-bringup.md +41 -22
- package/docs/standalone-local.md +12 -16
- package/package.json +3 -1
|
@@ -202,3 +202,105 @@ export function validateHumanReviewerId(reviewerId) {
|
|
|
202
202
|
}
|
|
203
203
|
return null;
|
|
204
204
|
}
|
|
205
|
+
// ─── Structural-truncation signal (flair#1756 slice 2, #1776 slice 3) ────────
|
|
206
|
+
// The SINGLE definition of the structural-truncation signal. The GATE for it
|
|
207
|
+
// lives server-side in resources/auto-promote-lib.ts (decideAutoPromote — the
|
|
208
|
+
// UNATTENDED path), which IMPORTS these from here. The direction is deliberate
|
|
209
|
+
// and established in this repo: a server file may import a PURE helper from src/
|
|
210
|
+
// (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts already
|
|
211
|
+
// import this very module); it is a CLI file importing FROM resources/ that does
|
|
212
|
+
// not survive npm packaging. Defining it here lets the CLI side
|
|
213
|
+
// (src/commands/rem.ts, `flair rem candidates`) and the server gate share ONE
|
|
214
|
+
// implementation rather than a hand-kept pair.
|
|
215
|
+
//
|
|
216
|
+
// Detects STRUCTURAL imbalance (unclosed/unmatched backtick, bracket, paren,
|
|
217
|
+
// brace) — NOT semantic completeness. A balanced claim can still be a fragment.
|
|
218
|
+
//
|
|
219
|
+
// The delimiter set is an ENUMERATED table (STRUCTURAL_PAIRS, below): the ASCII
|
|
220
|
+
// pairs `( )`, `[ ]`, `{ }` AND the full-width/CJK pairs
|
|
221
|
+
// `()[]{}【】〔〕〖〗「」『』《》〈〉〘〙〚〛`. Both the opener set and the closer
|
|
222
|
+
// map are DERIVED from that one list, so a pair cannot be added to one side and
|
|
223
|
+
// missed on the other. The table IS the boundary: mathematical and ornamental
|
|
224
|
+
// brackets (`⟨⟩ ⟦⟧ ⌈⌉ ⌊⌋ ⁅⁆ ⦅⦆ ❨❩ ༺༻`) are deliberately EXCLUDED — they are used
|
|
225
|
+
// standalone in real text, so counting them by category would over-refuse. The
|
|
226
|
+
// set is deliberately NOT derived from Unicode general categories
|
|
227
|
+
// (`\p{Ps}` / `\p{Pe}`) and is NOT described as "Unicode-aware": category
|
|
228
|
+
// membership does not establish paired usage (Ogham `᚛` and bare `༺`/`༻`,
|
|
229
|
+
// `⸢`/`⸣`, `⌈`/`⌉` are permitted standalone by the core spec), and a category
|
|
230
|
+
// counter refuses ordinary COMPLETE prose — see the quotation-mark note
|
|
231
|
+
// immediately below. There is no vendored Unicode data and no codegen here.
|
|
232
|
+
//
|
|
233
|
+
// QUOTATION MARKS OF EVERY SCRIPT ARE OUT OF SCOPE. `“ ” ‘ ’ „ “ ‚ ‘ « »` are
|
|
234
|
+
// NOT counted, so a claim truncated mid-quotation is judged balanced. The reason
|
|
235
|
+
// is concrete, not a preference: U+201E `„` (and U+201A `‚`) is category Ps
|
|
236
|
+
// while its closing mark U+201C (U+2018) is Pi, so ANY category-based counter
|
|
237
|
+
// reports positive depth on the ordinary COMPLETE German quotation `„Fertig.“`
|
|
238
|
+
// and refuses it; and U+2019 `’` is the standard English apostrophe (category
|
|
239
|
+
// Pf), so a quote-counting leg refuses every English contraction (e.g. `isn’t`).
|
|
240
|
+
// Enumerating matched bracket pairs avoids both false positives. That is why
|
|
241
|
+
// categories were rejected in favour of this table.
|
|
242
|
+
//
|
|
243
|
+
// The check counts delimiters without interpreting context, so a complete claim
|
|
244
|
+
// that merely DISCUSSES an unmatched delimiter is also flagged/refused
|
|
245
|
+
// (fail-closed; nothing is lost — the candidate stays pending for the human
|
|
246
|
+
// `rem promote` path).
|
|
247
|
+
//
|
|
248
|
+
// Runtimes this signal was exercised against (2026-09-21): Node v22.22.1
|
|
249
|
+
// (process.versions.unicode = 17.0) and Bun 1.3.10 (process.versions.unicode =
|
|
250
|
+
// 15.1). Passing the check means NO DETECTED IMBALANCE for the enumerated
|
|
251
|
+
// pairs — never completeness, and never coverage of an unenumerated script.
|
|
252
|
+
// The one source of truth: [opener, closer]. The two lookups below are DERIVED,
|
|
253
|
+
// so there is no second hand-kept list that can drift out of step. All three are
|
|
254
|
+
// exported so the pair-table invariant can be pinned by a test without
|
|
255
|
+
// duplicating the list here.
|
|
256
|
+
export const STRUCTURAL_PAIRS = [
|
|
257
|
+
["(", ")"], ["[", "]"], ["{", "}"],
|
|
258
|
+
["(", ")"], ["[", "]"], ["{", "}"],
|
|
259
|
+
["【", "】"], ["〔", "〕"], ["〖", "〗"],
|
|
260
|
+
["「", "」"], ["『", "』"],
|
|
261
|
+
["《", "》"], ["〈", "〉"], ["〘", "〙"], ["〚", "〛"],
|
|
262
|
+
];
|
|
263
|
+
export const STRUCTURAL_OPENERS = new Map(STRUCTURAL_PAIRS);
|
|
264
|
+
export const STRUCTURAL_CLOSERS = new Map(STRUCTURAL_PAIRS.map(([opener, closer]) => [closer, opener]));
|
|
265
|
+
/**
|
|
266
|
+
* Return a description of the STRUCTURAL imbalance in `claim` (an unmatched or
|
|
267
|
+
* closing-first bracket, an unclosed opener, or an odd number of backticks), or
|
|
268
|
+
* null if it is balanced. The delimiter set is the ENUMERATED table above
|
|
269
|
+
* (ASCII + full-width/CJK pairs); a delimiter outside that set — in particular a
|
|
270
|
+
* quotation mark of any script — is not examined and does not make this
|
|
271
|
+
* non-null. Pure. The description is for diagnostics only — it is NOT surfaced
|
|
272
|
+
* as a claim about completeness.
|
|
273
|
+
*/
|
|
274
|
+
export function structuralImbalance(claim) {
|
|
275
|
+
const stack = [];
|
|
276
|
+
for (const ch of claim) {
|
|
277
|
+
if (STRUCTURAL_OPENERS.has(ch)) {
|
|
278
|
+
stack.push(ch);
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
const opener = STRUCTURAL_CLOSERS.get(ch);
|
|
282
|
+
if (opener !== undefined && stack.pop() !== opener)
|
|
283
|
+
return `unmatched '${ch}'`;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (stack.length > 0)
|
|
287
|
+
return `unclosed '${stack[stack.length - 1]}'`;
|
|
288
|
+
if (((claim.match(/`/g) ?? []).length) % 2 !== 0)
|
|
289
|
+
return "unbalanced backtick";
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* True iff `claim` ends with terminal punctuation (optionally followed by a
|
|
294
|
+
* closing quote/bracket). This is a FLAG INPUT ONLY, never a refusal: plenty of
|
|
295
|
+
* legitimate claims end without a full stop, and on the UNATTENDED path a false
|
|
296
|
+
* refusal is silent. `flair rem candidates` surfaces it for the human reviewer.
|
|
297
|
+
*
|
|
298
|
+
* Terminators: ASCII `.` `!` `?` plus the full-width/CJK `。` (U+3002), `!`
|
|
299
|
+
* (U+FF01), `?` (U+FF1F). The trailing-suffix class accepts the quote/bracket
|
|
300
|
+
* closers it always did plus the enumerated bracket closers
|
|
301
|
+
* `」』)]}】〕〗》〉〙〛`. The single-dot leaders `…` `‥` `․` are deliberately NOT
|
|
302
|
+
* terminators — they are not interchangeable with a full stop.
|
|
303
|
+
*/
|
|
304
|
+
export function hasTerminalPunctuation(claim) {
|
|
305
|
+
return /[.!?。!?]["')\]}»”’」』)]}】〕〗》〉〙〛]*$/.test(claim.trimEnd());
|
|
306
|
+
}
|
package/dist/rem/runner.js
CHANGED
|
@@ -56,11 +56,11 @@
|
|
|
56
56
|
*/
|
|
57
57
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
58
58
|
import { dirname, resolve } from "node:path";
|
|
59
|
-
import { homedir } from "node:os";
|
|
60
59
|
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
|
|
61
60
|
import { createSnapshot } from "./snapshot.js";
|
|
62
|
-
|
|
63
|
-
export const
|
|
61
|
+
import { resolveHome } from "../lib/home.js";
|
|
62
|
+
export const REM_PAUSE_FLAG = resolve(resolveHome(), ".flair", "rem.paused");
|
|
63
|
+
export const REM_NIGHTLY_LOG = resolve(resolveHome(), ".flair", "logs", "rem-nightly.jsonl");
|
|
64
64
|
// ─── ADK per-tag distillation (#1205b-1) ─────────────────────────────────────
|
|
65
65
|
// adk-flair collapses (app_name, user_id) → ONE Flair agentId, distinguishing
|
|
66
66
|
// users ONLY by a per-user tag `adk:<app>:<user>` (see the adk-flair
|
package/dist/rem/scheduler.js
CHANGED
|
@@ -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(
|
|
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(
|
|
36
|
-
export const SYSTEMD_USER_DIR = resolve(
|
|
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 ??
|
|
105
|
+
HOME: opts.homeOverride ?? resolveHome(),
|
|
106
106
|
AGENT_ID: opts.agentId,
|
|
107
107
|
FLAIR_URL: opts.flairUrl,
|
|
108
108
|
HOUR: String(opts.hour),
|
package/dist/rem/snapshot.js
CHANGED
|
@@ -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
|
-
|
|
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)) {
|
|
@@ -308,6 +308,16 @@ export class ReflectMemories extends Resource {
|
|
|
308
308
|
// Static body (K&S) — never echo Harper version, backend lists, or endpoints.
|
|
309
309
|
return new Response(JSON.stringify({ error: "No generative backend configured. See the models configuration docs." }), { status: 503 });
|
|
310
310
|
}
|
|
311
|
+
if (distill.outcome.reason === "incomplete_generation") {
|
|
312
|
+
// The backend PROVED the generation was cut short (finishReason
|
|
313
|
+
// `length` or `content_filter`). Valid-looking JSON from an incomplete
|
|
314
|
+
// response must not stage as a finished thought (flair#1756). Static
|
|
315
|
+
// body — never echo backend detail.
|
|
316
|
+
return new Response(JSON.stringify({
|
|
317
|
+
error: "distillation_failed",
|
|
318
|
+
detail: "model output was incomplete — the backend reported the generation was cut short",
|
|
319
|
+
}), { status: 502 });
|
|
320
|
+
}
|
|
311
321
|
return new Response(JSON.stringify({ error: "distillation_failed", detail: "model output did not validate after one retry" }), { status: 502 });
|
|
312
322
|
}
|
|
313
323
|
// Response omits rationalePrompt (spec §3A item 5: "no prompt field") —
|
package/dist/resources/OAuth.js
CHANGED
|
@@ -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
|
-
${
|
|
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: {
|
|
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 —
|
|
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 —
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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:
|
|
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
|
|
21
|
-
* runtime/activity/presenceStatus/lastHeartbeatAt) is
|
|
22
|
-
* public-safe
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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,
|
|
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
|
-
/**
|
|
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 —
|
|
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
|
|
278
|
-
*
|
|
279
|
-
*
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
* super_user
|
|
294
|
-
*
|
|
295
|
-
*
|
|
296
|
-
*
|
|
297
|
-
* allowRead()
|
|
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).
|
|
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
|
-
|
|
312
|
-
|
|
313
|
-
const includeVerifiedFields =
|
|
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 (
|
|
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
|
-
/**
|
|
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, "<")
|
|
37
41
|
.replace(/>/g, ">")
|
|
38
42
|
.replace(/"/g, """)
|
|
39
|
-
.replace(/'/g, "'")
|
|
43
|
+
.replace(/'/g, "'")
|
|
44
|
+
.replace(/`/g, "`");
|
|
40
45
|
}
|
|
41
46
|
export function layout(title, content, activePage) {
|
|
42
47
|
const nav = [
|