@tpsdev-ai/flair 0.55.2 → 0.57.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 +18 -19
- 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 +125 -26
- package/dist/commands/agent.js +22 -15
- package/dist/commands/attention.js +2 -2
- package/dist/commands/backup.js +2 -2
- package/dist/commands/bridge.js +40 -3
- package/dist/commands/doctor.js +91 -28
- package/dist/commands/export.js +2 -2
- package/dist/commands/federation.js +441 -68
- package/dist/commands/hook.js +4 -4
- package/dist/commands/init.js +59 -12
- package/dist/commands/mcp.js +2 -2
- package/dist/commands/migrate-harness-memory.js +8 -8
- package/dist/commands/rem.js +2 -2
- 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 +3 -3
- package/dist/doctor-client.js +5 -23
- package/dist/engine-version.js +2 -2
- package/dist/federation/scheduler.js +5 -5
- package/dist/install/clients.js +5 -10
- package/dist/keystore.js +10 -2
- package/dist/lib/auth-resolve.js +51 -5
- package/dist/lib/doctor-config-path.js +2 -2
- package/dist/lib/flair-paths.js +29 -0
- package/dist/lib/home.js +60 -0
- package/dist/lib/instance-identity-row.js +580 -0
- package/dist/lib/launchd-repair.js +6 -0
- package/dist/lib/mcp-enable.js +4 -4
- package/dist/lib/owned-pins.js +1 -13
- package/dist/lib/redact-token-id.js +197 -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/mcp-client-assertion.js +3 -3
- package/dist/rem/runner.js +3 -3
- package/dist/rem/scheduler.js +5 -5
- package/dist/rem/snapshot.js +2 -2
- package/dist/resources/AgentSeed.js +4 -1
- package/dist/resources/Asset.js +3 -11
- package/dist/resources/Credential.js +4 -10
- package/dist/resources/Federation.js +232 -78
- package/dist/resources/Integration.js +8 -32
- package/dist/resources/Memory.js +58 -16
- package/dist/resources/MemoryBootstrap.js +19 -12
- package/dist/resources/MemoryCandidate.js +3 -11
- package/dist/resources/MemoryDedupStats.js +1 -1
- package/dist/resources/MemoryFeed.js +10 -2
- package/dist/resources/MemoryGrant.js +19 -40
- package/dist/resources/MemoryUsage.js +7 -20
- package/dist/resources/OAuth.js +62 -11
- package/dist/resources/Presence.js +135 -47
- package/dist/resources/Relationship.js +3 -11
- package/dist/resources/SemanticSearch.js +25 -13
- package/dist/resources/admin-layout.js +7 -2
- package/dist/resources/auth-middleware.js +32 -5
- package/dist/resources/bm25.js +13 -14
- package/dist/resources/federation-cleanup.js +289 -51
- package/dist/resources/health.js +48 -8
- package/dist/resources/in-process-api.js +2 -1
- package/dist/resources/instance-create-lock.js +363 -0
- package/dist/resources/instance-identity-rows.js +43 -0
- package/dist/resources/instance-identity.js +94 -10
- package/dist/resources/mcp-handler.js +9 -1
- package/dist/resources/mcp-tool-arguments.js +83 -0
- package/dist/resources/mcp-tools.js +4 -5
- package/dist/resources/memory-reflect-lib.js +17 -1
- package/dist/resources/memory-visibility.js +10 -7
- package/dist/resources/rate-limit.js +6 -4
- package/dist/resources/record-type-kit.js +47 -23
- package/dist/resources/search-readiness.js +7 -1
- package/dist/resources/semantic-retrieval-core.js +98 -3
- package/dist/resources/table-helpers.js +33 -0
- package/dist/resources/tool-descriptors/index.js +2 -2
- package/dist/src/keystore.js +10 -2
- package/dist/src/lib/home.js +60 -0
- package/dist/src/lib/instance-identity-row.js +580 -0
- package/dist/src/lib/redact-token-id.js +197 -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 +32 -7
- package/docs/auth.md +19 -7
- package/docs/claude-code.md +5 -6
- package/docs/deploying-on-fabric.md +8 -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 +48 -21
- package/docs/hosted-on-fabric.md +7 -4
- package/docs/integrations.md +24 -15
- package/docs/mcp-clients.md +44 -23
- package/docs/n8n.md +8 -8
- package/docs/notes/mcp-oauth-model2.md +12 -17
- package/docs/openclaw.md +29 -28
- package/docs/spoke-bringup.md +44 -22
- package/docs/standalone-local.md +12 -16
- package/docs/supply-chain-policy.md +21 -8
- package/docs/system-requirements.md +1 -1
- package/docs/upgrade.md +2 -2
- package/package.json +1 -1
|
@@ -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
|
|
@@ -3,7 +3,7 @@ import { resolveAgentAuth } from "./agent-auth.js";
|
|
|
3
3
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
4
4
|
import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
|
|
5
5
|
import { localInstanceId } from "./instance-identity.js";
|
|
6
|
-
import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
6
|
+
import { buildProvenance, makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
7
7
|
import { RECORD_TYPES } from "./record-types.js";
|
|
8
8
|
// Parameterized from RECORD_TYPES.Relationship (record-types slice 2,
|
|
9
9
|
// flair#520) rather than a hand-typed "owner-only" literal — the registry is
|
|
@@ -13,6 +13,7 @@ import { RECORD_TYPES } from "./record-types.js";
|
|
|
13
13
|
// `.ownerField` against RECORD_TYPES.Relationship — not for any other
|
|
14
14
|
// runtime consumer.
|
|
15
15
|
export const relationshipReadScope = makeReadScope(RECORD_TYPES.Relationship.readScope, RECORD_TYPES.Relationship.ownerField);
|
|
16
|
+
const relationshipScopedSearch = makeScopedSearch(relationshipReadScope);
|
|
16
17
|
const relationshipByIdReadGate = makeByIdReadGate(relationshipReadScope);
|
|
17
18
|
// See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
|
|
18
19
|
// prototype method below, never a class-field assignment — Harper's
|
|
@@ -75,16 +76,7 @@ export class Relationship extends databases.flair.Relationship {
|
|
|
75
76
|
if (gate.kind === "unfiltered")
|
|
76
77
|
return super.search(query);
|
|
77
78
|
// Non-admin agent: scope to own relationships.
|
|
78
|
-
|
|
79
|
-
const agentCondition = scope.condition;
|
|
80
|
-
if (!query?.conditions) {
|
|
81
|
-
return super.search({ conditions: [agentCondition], ...(query || {}) });
|
|
82
|
-
}
|
|
83
|
-
return super.search({
|
|
84
|
-
...query,
|
|
85
|
-
conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
|
|
86
|
-
operator: "and",
|
|
87
|
-
});
|
|
79
|
+
return relationshipScopedSearch(gate.agentId, query, (q) => super.search(q));
|
|
88
80
|
}
|
|
89
81
|
/**
|
|
90
82
|
* ─── Auth reconcile (relationship-write-path, folded K&S refinement) ──────
|
|
@@ -11,7 +11,7 @@ import { resolveReadScope } from "./memory-read-scope.js";
|
|
|
11
11
|
// of 2026-07-08 (see ./bm25.ts's hybridEnabled() doc); set
|
|
12
12
|
// FLAIR_HYBRID_RETRIEVAL=false to revert to the legacy HNSW + +0.05
|
|
13
13
|
// keyword-bump path, byte-identical to the original pre-hybrid behavior.
|
|
14
|
-
import {
|
|
14
|
+
import { retrievalMode } from "./bm25.js";
|
|
15
15
|
// The actual HNSW/BM25 retrieval + post-retrieval filtering (temporal/
|
|
16
16
|
// supersede/isAllowed) now lives in the pure, side-effect-free
|
|
17
17
|
// retrieveCandidates() core (flair-bootstrap-scale-fix, Kern-approved
|
|
@@ -28,9 +28,9 @@ export class SemanticSearch extends Resource {
|
|
|
28
28
|
// Self-authorize via the Ed25519 agent verify instead of relying on the auth
|
|
29
29
|
// gate's admin super_user elevation (removed in the auth reshape). Any
|
|
30
30
|
// cryptographically-verified agent may search; per-agent RESULT scoping is
|
|
31
|
-
// enforced in post() below (an agent
|
|
32
|
-
//
|
|
33
|
-
//
|
|
31
|
+
// enforced in post() below (an agent sees its own records at any visibility
|
|
32
|
+
// plus every other agent's non-private records; grants are not consulted on
|
|
33
|
+
// reads — resolveReadScope()). Without this, Harper's default denies the POST for the
|
|
34
34
|
// least-privilege flair_agent role (AccessViolation 403).
|
|
35
35
|
async allowCreate() {
|
|
36
36
|
return allowVerified(this.getContext?.());
|
|
@@ -100,24 +100,33 @@ export class SemanticSearch extends Resource {
|
|
|
100
100
|
error: "forbidden: agentId must match authenticated agent",
|
|
101
101
|
}), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
102
102
|
}
|
|
103
|
-
// Scope: non-admin agent → own
|
|
104
|
-
//
|
|
103
|
+
// Scope: non-admin agent → its own records at any visibility plus every
|
|
104
|
+
// other agent's non-private records (grants are not consulted on reads —
|
|
105
|
+
// resolveReadScope()). Admin agent or trusted internal call (no request) →
|
|
106
|
+
// honor the body-supplied agentId.
|
|
105
107
|
const agentId = (authenticatedAgent && !callerIsAdmin)
|
|
106
108
|
? authenticatedAgent
|
|
107
109
|
: bodyAgentId;
|
|
108
|
-
// Read-scope: own
|
|
109
|
-
//
|
|
110
|
+
// Read-scope: own records at any visibility + every other agent's
|
|
111
|
+
// non-private records (grants are not consulted on reads). Centralized in
|
|
112
|
+
// resolveReadScope() — this used to be
|
|
110
113
|
// an inline grant-resolution loop here PLUS a `visibility === "office"`
|
|
111
114
|
// global OR-clause below that leaked ANY authenticated agent's read of
|
|
112
115
|
// ANY other agent's office-visible memories. Both are gone;
|
|
113
116
|
// this is the ONE scoping resolution for this endpoint now.
|
|
114
117
|
const scope = agentId ? await resolveReadScope(agentId) : null;
|
|
118
|
+
// Select the retrieval mode ONCE per request (bench-facing selector; see
|
|
119
|
+
// the flag doc in ./bm25.ts). Default (FLAIR_RETRIEVAL_MODE unset) follows
|
|
120
|
+
// the legacy FLAIR_HYBRID_RETRIEVAL boolean exactly.
|
|
121
|
+
const mode = retrievalMode();
|
|
115
122
|
// Generate query embedding
|
|
116
123
|
let qEmb = queryEmbedding;
|
|
117
|
-
if (!qEmb && q) {
|
|
124
|
+
if (!qEmb && q && mode !== "bm25-only") {
|
|
118
125
|
// Always attempt embedding generation — getEmbedding() handles init internally.
|
|
119
126
|
// Don't gate on getMode() which may return "none" before init completes in worker threads.
|
|
120
127
|
// flair#504 Phase 2: 'query' — this is a search query, not stored content.
|
|
128
|
+
// bm25-only: skipped — that arm ranks on the lexical leg alone and must
|
|
129
|
+
// perform NO embedding call (the core ignores any qEmb it is handed).
|
|
121
130
|
try {
|
|
122
131
|
qEmb = await getEmbedding(String(q).slice(0, 8000), "query");
|
|
123
132
|
}
|
|
@@ -171,8 +180,9 @@ export class SemanticSearch extends Resource {
|
|
|
171
180
|
}
|
|
172
181
|
// ─── Build conditions for Harper query ──────────────────────────────────
|
|
173
182
|
const conditions = [];
|
|
174
|
-
// Agent scoping: own
|
|
175
|
-
//
|
|
183
|
+
// Agent scoping: own records at any visibility OR every other agent's
|
|
184
|
+
// non-private records (grants are not consulted on reads — resolveReadScope())
|
|
185
|
+
// — the centralized read-scope condition. No agentId
|
|
176
186
|
// → no scoping condition pushed (trusted internal call / admin without a
|
|
177
187
|
// target agentId — matches the pre-existing unscoped fallback).
|
|
178
188
|
if (scope) {
|
|
@@ -228,7 +238,9 @@ export class SemanticSearch extends Resource {
|
|
|
228
238
|
scoring,
|
|
229
239
|
};
|
|
230
240
|
}
|
|
231
|
-
|
|
241
|
+
// (`mode` was resolved at the top of post(); the bm25-only arm has no
|
|
242
|
+
// embedding, so the HNSW-leg portion of the overfetch policy does not apply
|
|
243
|
+
// to it — the core ignores `queryEmbedding` on that branch.)
|
|
232
244
|
// The overfetch policy (how many raw candidates to pull from the
|
|
233
245
|
// HNSW/BM25 legs relative to what the caller ultimately wants) is THIS
|
|
234
246
|
// wrapper's decision — retrieveCandidates() never multiplies its `limit`
|
|
@@ -254,7 +266,7 @@ export class SemanticSearch extends Resource {
|
|
|
254
266
|
minScore,
|
|
255
267
|
agentId,
|
|
256
268
|
isAllowed: scope?.isAllowed,
|
|
257
|
-
|
|
269
|
+
mode,
|
|
258
270
|
ctx,
|
|
259
271
|
onLegs: includeLegs ? (l) => { legs = l; } : undefined,
|
|
260
272
|
// flair#744 slice 1: the trust block needs `provenance`, which the
|
|
@@ -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 = [
|
|
@@ -65,15 +65,41 @@ async function backfillEmbedding(memoryId) {
|
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
// ─── HTTP middleware ──────────────────────────────────────────────────────────
|
|
68
|
+
// Flair's clients use exactly these HTTP methods. Harper routes other methods
|
|
69
|
+
// to resource handlers as well; refusing them here, before any other branch of
|
|
70
|
+
// the default REST middleware, keeps the tables it serves to the methods their
|
|
71
|
+
// handlers are written and tested for. (Separately mounted routes such as /mcp
|
|
72
|
+
// and OAuth discovery have their own dispatch chains and method handling.)
|
|
73
|
+
const ALLOWED_HTTP_METHODS = new Set([
|
|
74
|
+
"GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE",
|
|
75
|
+
]);
|
|
68
76
|
server.http(async (request, nextLayer) => {
|
|
77
|
+
// ── HTTP method allowlist, FIRST ───────────────────────────────────────────
|
|
78
|
+
// Before the public-path passthrough and before any auth branch, so no path
|
|
79
|
+
// and no caller (anonymous, agent or admin) can reach a handler through any
|
|
80
|
+
// other method.
|
|
81
|
+
// Exact match: HTTP methods are case-sensitive, and these are the spellings
|
|
82
|
+
// Flair's clients send.
|
|
83
|
+
const httpMethod = String(request.method ?? "");
|
|
84
|
+
if (!ALLOWED_HTTP_METHODS.has(httpMethod)) {
|
|
85
|
+
return new Response(JSON.stringify({
|
|
86
|
+
error: "method_not_allowed",
|
|
87
|
+
detail: `Flair accepts ${[...ALLOWED_HTTP_METHODS].join(", ")}.`,
|
|
88
|
+
}), {
|
|
89
|
+
status: 405,
|
|
90
|
+
headers: { "content-type": "application/json", allow: [...ALLOWED_HTTP_METHODS].join(", ") },
|
|
91
|
+
});
|
|
92
|
+
}
|
|
69
93
|
const url = new URL(request.url, "http://" + (request.headers.get("host") || "localhost"));
|
|
70
|
-
// ── Rate limiting,
|
|
94
|
+
// ── Rate limiting, right after the method check ────────────────────────────
|
|
71
95
|
// Before the public-path passthrough below (the OAuth endpoints all sit on it,
|
|
72
96
|
// so a hook placed after it would never run for them), and before anything
|
|
73
|
-
// reads a credential.
|
|
97
|
+
// reads a credential. A request refused by the method check above never
|
|
98
|
+
// reaches the limiter, and consumes no budget.
|
|
74
99
|
//
|
|
75
100
|
// Ordering is a security property, not tidiness. The counter is consumed for
|
|
76
|
-
// every request to a throttled endpoint
|
|
101
|
+
// every request to a throttled endpoint that passes the method check, whether
|
|
102
|
+
// or not the credential that
|
|
77
103
|
// came with it was any good — if only failures were counted, "did this consume
|
|
78
104
|
// budget" would answer "was that credential valid", which is a cleaner
|
|
79
105
|
// enumeration oracle than the 400 the endpoint already returns. Because the
|
|
@@ -607,8 +633,9 @@ server.http(async (request, nextLayer) => {
|
|
|
607
633
|
if (memId) {
|
|
608
634
|
const record = await databases.flair.Memory.get(memId);
|
|
609
635
|
if (record && record.agentId && record.agentId !== agentId) {
|
|
610
|
-
// Centralized read-scope (Layer 1):
|
|
611
|
-
//
|
|
636
|
+
// Centralized read-scope (Layer 1): the owner's records at any
|
|
637
|
+
// visibility plus every other agent's non-private records; grants
|
|
638
|
+
// are not consulted on reads (resolveReadScope()). This
|
|
612
639
|
// used to be a `visibility === "office"` bypass (any authenticated
|
|
613
640
|
// agent, no grant needed) — that's gone; the private-exclusion is
|
|
614
641
|
// now enforced the same way every other read path enforces it.
|
package/dist/resources/bm25.js
CHANGED
|
@@ -8,21 +8,20 @@
|
|
|
8
8
|
// 5552320), which validated: BM25 alone recovers 5/6 severe misses into top-3;
|
|
9
9
|
// candidate-UNION RRF (NOT naive whole-corpus RRF) recovers 4/6 into top-10 with
|
|
10
10
|
// no regression on the within-cluster gate (p@3 holds 0.88).
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
11
|
+
const RETRIEVAL_MODES = ["hybrid", "vector-only", "bm25-only"];
|
|
12
|
+
export function retrievalMode() {
|
|
13
|
+
const raw = process.env.FLAIR_RETRIEVAL_MODE;
|
|
14
|
+
if (raw !== undefined) {
|
|
15
|
+
const v = raw.toLowerCase();
|
|
16
|
+
if (RETRIEVAL_MODES.includes(v))
|
|
17
|
+
return v;
|
|
18
|
+
throw new Error(`unknown FLAIR_RETRIEVAL_MODE value "${raw}" (accepted: ${RETRIEVAL_MODES.join(", ")})`);
|
|
19
|
+
}
|
|
20
|
+
const legacy = (process.env.FLAIR_HYBRID_RETRIEVAL ?? "true").toLowerCase();
|
|
21
|
+
return (legacy === "true" || legacy === "1" || legacy === "on") ? "hybrid" : "vector-only";
|
|
22
|
+
}
|
|
23
23
|
export function hybridEnabled() {
|
|
24
|
-
|
|
25
|
-
return v === "true" || v === "1" || v === "on";
|
|
24
|
+
return retrievalMode() === "hybrid";
|
|
26
25
|
}
|
|
27
26
|
// BM25 parameters (Kern-approved): k1≈1.2, b≈0.75; standard IDF + BM25.
|
|
28
27
|
export const BM25_K1 = 1.2;
|