@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -13,10 +13,12 @@
13
13
  * Auth model: an agent presents `Authorization: TPS-Ed25519 <id>:<ts>:<nonce>:<sig>`.
14
14
  * The signature covers `<id>:<ts>:<nonce>:<METHOD>:<pathname><search>` and is
15
15
  * verified against the agent's stored Ed25519 public key. Replay is bounded by a
16
- * 30s timestamp window + a per-(agent,nonce) seen-set pruned to that window.
16
+ * 30s timestamp window + an instance-wide record of each (agent, nonce)
17
+ * (resources/replay-store.ts).
17
18
  */
18
19
  import { databases } from "harper";
19
- import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
20
+ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
21
+ import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
20
22
  import { ADMIN_ROLE, agentRecordIsAdmin } from "./agent-admin.js";
21
23
  /**
22
24
  * Shared Harper user that verified Ed25519 agents resolve to (least-privilege
@@ -53,11 +55,11 @@ export function isPrincipalDeactivated(agent) {
53
55
  return agent.status !== "active";
54
56
  }
55
57
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
56
- // WINDOW_MS, isNonceReplay/recordNonce (the ONE shared nonce store), and
57
- // importEd25519Key all live in ./ed25519-auth.ts — the single
58
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
59
- // Presence.ts so a nonce recorded via any one of the three call sites is
60
- // visible to the other two, and the crypto/decoder logic can't drift.
58
+ // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
59
+ // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
60
+ // auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
61
+ // any one of the three call sites, on any worker thread, is refused by all of
62
+ // them, and the crypto/decoder logic can't drift.
61
63
  // ─── Admin resolution ─────────────────────────────────────────────────────────
62
64
  // Admin agents come from FLAIR_ADMIN_AGENTS (comma-separated) OR Agent records
63
65
  // whose `role` is the admin sentinel. OR-combined, cached 60s. Distinct from
@@ -124,8 +126,9 @@ async function doVerify(request) {
124
126
  const now = Date.now();
125
127
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
126
128
  return null;
127
- // Reject replays within the window (isNonceReplay prunes expired entries first).
128
- if (isNonceReplay(agentId, nonce, now))
129
+ // A nonce this thread already saw recorded is refused before any lookup. A
130
+ // miss here proves nothing: claimAgentNonce below is the authoritative check.
131
+ if (isKnownAgentReplay(agentId, nonce, now))
129
132
  return null;
130
133
  const agent = await databases.flair.Agent.get(agentId).catch(() => null);
131
134
  if (!agent?.publicKey)
@@ -147,7 +150,10 @@ async function doVerify(request) {
147
150
  catch {
148
151
  return null;
149
152
  }
150
- recordNonce(agentId, nonce, ts);
153
+ // Record the nonce instance-wide now that the signature has verified, and
154
+ // before the request has any effect. A replay or an unusable store refuses.
155
+ if (!(await claimAgentNonce(agentId, nonce)).ok)
156
+ return null;
151
157
  return { agentId, isAdmin: await isAdmin(agentId) };
152
158
  }
153
159
  /**
@@ -0,0 +1,63 @@
1
+ /**
2
+ * agent-status-guard.ts — the `Agent.status` write rule for the Agent resource.
3
+ *
4
+ * `status` is the principal's LIFECYCLE state: any present value other than
5
+ * "active" means deactivated, and a missing or undefined `status` is treated as
6
+ * active (resources/agent-auth.ts's isPrincipalDeactivated). So a principal that
7
+ * may write its own `status` can deactivate itself. Liveness belongs on the
8
+ * Presence beacon, not on this column.
9
+ *
10
+ * resources/Agent.ts's PUT and PATCH admit a trusted internal call and an
11
+ * administrator, and refuse anonymous and any verdict kind the auth resolver
12
+ * does not define. A non-admin agent's PUT or PATCH whose body carries the
13
+ * `status` key is refused whole, on any row including its own, so the other
14
+ * fields in that request are not written either; without `status`, it goes on
15
+ * to Agent.ts's other per-record rules. A non-admin agent's POST (create) is
16
+ * refused earlier, at allowCreate(). (A federation peer's record is merged
17
+ * through the raw table, not this resource; resources/Federation.ts skips an
18
+ * inbound Agent record whose `status` differs from an existing local
19
+ * principal's stored value.)
20
+ *
21
+ * Deliberately dependency-free (no `harper`, no resource) so resources/Agent.ts
22
+ * and the unit lane decide this from one place.
23
+ */
24
+ /** The lifecycle field this module guards. */
25
+ export const AGENT_STATUS_FIELD = "status";
26
+ /**
27
+ * The feature's lifecycle rule applied to a value: a principal's effective
28
+ * `status` is its stored value, or "active" when it is missing or undefined
29
+ * (resources/agent-auth.ts's isPrincipalDeactivated applies the same rule to a
30
+ * principal). Federation's status comparison uses it on both sides
31
+ * (resources/federation-classify.ts).
32
+ */
33
+ export function effectiveAgentStatus(status) {
34
+ return status === undefined ? "active" : status;
35
+ }
36
+ /** The refusal text: names the field, the internal exception, and Presence. */
37
+ export const AGENT_STATUS_ADMIN_ONLY_ERROR = "forbidden: status is administrator-only (a trusted internal call is excepted); report liveness through Presence";
38
+ /** True iff a write body carries the `status` field. */
39
+ export function writeIncludesStatus(content) {
40
+ return content != null && typeof content === "object" && Object.hasOwn(content, AGENT_STATUS_FIELD);
41
+ }
42
+ export function admitPrincipalWrite(auth) {
43
+ if (auth == null || typeof auth !== "object")
44
+ return "deny";
45
+ if (auth.kind === "internal")
46
+ return "internal";
47
+ if (auth.kind === "agent")
48
+ return auth.isAdmin === true ? "admin" : "non-admin";
49
+ return "deny";
50
+ }
51
+ /**
52
+ * The 403 for a write whose body includes `status` from a caller who is not an
53
+ * administrator, or null when the caller is an administrator or the body has no
54
+ * `status`. resources/Agent.ts admits a trusted internal call without calling
55
+ * this helper.
56
+ */
57
+ export function statusWriteRefusal(content, callerIsAdmin) {
58
+ if (callerIsAdmin || !writeIncludesStatus(content))
59
+ return null;
60
+ return new Response(JSON.stringify({ error: AGENT_STATUS_ADMIN_ONLY_ERROR }), {
61
+ status: 403, headers: { "content-type": "application/json" },
62
+ });
63
+ }
@@ -2,11 +2,108 @@ import { patchRecord } from "./table-helpers.js";
2
2
  import { server, databases } from "harper";
3
3
  import { getEmbedding } from "./embeddings-provider.js";
4
4
  import { isAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME } from "./agent-auth.js";
5
- import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
6
- import { resolveReadScope } from "./memory-read-scope.js";
7
- import { NOT_FOUND } from "./record-type-kit.js";
8
- import { isForbiddenOwnerMutation, resolveGuardedRecord } from "./record-owner-guard.js";
5
+ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
6
+ import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
7
+ import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord } from "./record-owner-guard.js";
9
8
  import { checkHttpRateLimit } from "./rate-limit.js";
9
+ import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
10
+ import { stripUndeclaredMemoryAttributes, DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
11
+ // --- Non-admin Memory read: ignore the caller's selection --------------------
12
+ //
13
+ // flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
14
+ // pointer-projected row; a caller `select(...)` or `property` is dropped from the
15
+ // request URL before Harper parses it, while conditions, operator, sort, limit
16
+ // and offset are left exactly as sent. These helpers are the whole of that
17
+ // normalization.
18
+ const DECLARED_MEMORY_ATTRIBUTE_SET = new Set(DECLARED_MEMORY_ATTRIBUTES);
19
+ function isMemoryReadPath(pathname) {
20
+ return pathname === "/Memory" || pathname === "/Memory/" || pathname.startsWith("/Memory/");
21
+ }
22
+ // Drop a caller's `select(...)` and `property` from a Memory read URL, keeping
23
+ // conditions, operator, sort, limit and offset. Returns the input unchanged when
24
+ // the URL carries no selection.
25
+ function stripMemorySelection(rawUrl) {
26
+ const q = rawUrl.indexOf("?");
27
+ let pathPart = q === -1 ? rawUrl : rawUrl.slice(0, q);
28
+ let query = q === -1 ? "" : rawUrl.slice(q + 1);
29
+ // Path form: Harper reads a trailing `.<declared>` on the id as `property`.
30
+ // Harper decides on the DECODED path — RequestTarget decodes the path
31
+ // (`this.id = decodeURIComponent(path)`) and Resource.parsePath then splits at
32
+ // the first dot — so the middleware must decide on the decoded segment too, or
33
+ // it misses a percent-encoded dot: `%2E` (and `%2e`) IS a dot to Harper. Drop
34
+ // that suffix so the id addresses the full row; a suffix that is not a
35
+ // declared Memory attribute stays part of the id, exactly as Harper's own rule
36
+ // leaves it (a content-type extension such as `json` is not a declared
37
+ // attribute, so it is left for Harper to read as a content type).
38
+ const slash = pathPart.lastIndexOf("/");
39
+ const seg = pathPart.slice(slash + 1);
40
+ const decodedSeg = decodePathSegment(seg);
41
+ const dot = decodedSeg.indexOf(".");
42
+ if (dot > -1 && DECLARED_MEMORY_ATTRIBUTE_SET.has(decodedSeg.slice(dot + 1))) {
43
+ // Rebuild the id from its decoded form. Harper decodes the path it is handed,
44
+ // so this re-encoded segment addresses the SAME id, without the property.
45
+ pathPart = `${pathPart.slice(0, slash + 1)}${encodeURIComponent(decodedSeg.slice(0, dot))}`;
46
+ }
47
+ // Query form: drop every `select(...)` token and every `property` parameter.
48
+ for (const [start, end] of selectSpans(query).reverse()) {
49
+ query = query.slice(0, start) + query.slice(end);
50
+ }
51
+ query = query
52
+ .split("&")
53
+ .filter((p) => p !== "" && p !== "property" && !p.startsWith("property="))
54
+ .join("&");
55
+ // A run of separators left by removing `select(...)` tokens carries nothing.
56
+ if (/^[,;]*$/.test(query))
57
+ query = "";
58
+ if (q === -1)
59
+ return pathPart;
60
+ return query === "" ? pathPart : `${pathPart}?${query}`;
61
+ }
62
+ /** Decode a path segment the way Harper does before its property parse; fall
63
+ * back to the raw segment when it is not valid percent-encoding (Harper rejects
64
+ * the malformed request; the middleware must not crash on it). */
65
+ function decodePathSegment(raw) {
66
+ try {
67
+ return decodeURIComponent(raw);
68
+ }
69
+ catch {
70
+ return raw;
71
+ }
72
+ }
73
+ // [start, end) ranges of every `select(...)` call in a query string, accounting
74
+ // for Harper's nested-list form `select((a,b))`.
75
+ function selectSpans(query) {
76
+ const spans = [];
77
+ const marker = "select(";
78
+ let from = 0;
79
+ for (;;) {
80
+ const idx = query.indexOf(marker, from);
81
+ if (idx < 0)
82
+ break;
83
+ const before = idx > 0 ? query[idx - 1] : "";
84
+ if (before && /[A-Za-z0-9_$-]/.test(before)) {
85
+ from = idx + marker.length;
86
+ continue;
87
+ }
88
+ let depth = 1;
89
+ let i = idx + marker.length;
90
+ for (; i < query.length; i++) {
91
+ const ch = query[i];
92
+ if (ch === "(")
93
+ depth++;
94
+ else if (ch === ")") {
95
+ depth--;
96
+ if (depth === 0)
97
+ break;
98
+ }
99
+ }
100
+ if (i >= query.length)
101
+ break;
102
+ spans.push([idx, i + 1]);
103
+ from = i + 1;
104
+ }
105
+ return spans;
106
+ }
10
107
  // --- Admin credentials ---
11
108
  // Admin auth is sourced exclusively from Harper's own environment variables
12
109
  // (HDB_ADMIN_PASSWORD / FLAIR_ADMIN_PASSWORD). No filesystem token file.
@@ -40,11 +137,11 @@ function getAdminPass() {
40
137
  // auth reshape this gate and the per-resource allow* helpers must agree on who's
41
138
  // an admin — one implementation guarantees they can't diverge.
42
139
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
43
- // WINDOW_MS, isNonceReplay/recordNonce (the ONE shared nonce store), and
44
- // importEd25519Key all live in ./ed25519-auth.ts — the single
45
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
46
- // Presence.ts so a nonce recorded via any one of the three call sites is
47
- // visible to the other two, and the crypto/decoder logic can't drift.
140
+ // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
141
+ // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
142
+ // auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
143
+ // any one of the three call sites, on any worker thread, is refused by all of
144
+ // them, and the crypto/decoder logic can't drift.
48
145
  async function backfillEmbedding(memoryId) {
49
146
  try {
50
147
  const record = await databases.flair.Memory.get(memoryId);
@@ -57,7 +154,9 @@ async function backfillEmbedding(memoryId) {
57
154
  const embedding = await getEmbedding(record.content, "document");
58
155
  if (!embedding)
59
156
  return;
60
- await patchRecord(databases.flair.Memory, memoryId, { embedding });
157
+ const embedPatch = { embedding };
158
+ stripUndeclaredMemoryAttributes(embedPatch);
159
+ await patchRecord(databases.flair.Memory, memoryId, embedPatch);
61
160
  console.log(`[auto-embed] ${memoryId}: ${embedding.length}d`);
62
161
  }
63
162
  catch (err) {
@@ -343,7 +442,9 @@ server.http(async (request, nextLayer) => {
343
442
  const now = Date.now();
344
443
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
345
444
  return new Response(JSON.stringify({ error: "timestamp_out_of_window" }), { status: 401 });
346
- if (isNonceReplay(agentId, nonce, now))
445
+ // A nonce this thread already saw recorded is refused before any lookup. A
446
+ // miss here proves nothing: claimAgentNonce below is the authoritative check.
447
+ if (isKnownAgentReplay(agentId, nonce, now))
347
448
  return new Response(JSON.stringify({ error: "nonce_replay_detected" }), { status: 401 });
348
449
  const agent = await databases.flair.Agent.get(agentId);
349
450
  if (!agent)
@@ -365,7 +466,12 @@ server.http(async (request, nextLayer) => {
365
466
  catch (e) {
366
467
  return new Response(JSON.stringify({ error: "signature_verification_failed", detail: e?.message }), { status: 401 });
367
468
  }
368
- recordNonce(agentId, nonce, ts);
469
+ // Record the nonce instance-wide now that the signature has verified, and
470
+ // before the request reaches anything else. A replay (401) or an unusable
471
+ // replay store (503, named in the server log) refuses.
472
+ const claim = await claimAgentNonce(agentId, nonce);
473
+ if (!claim.ok)
474
+ return new Response(JSON.stringify({ error: claim.error }), { status: claim.status });
369
475
  request.tpsAgent = agentId;
370
476
  request._tpsAuthVerified = true;
371
477
  request.tpsAgentIsAdmin = await isAdmin(agentId);
@@ -456,9 +562,7 @@ server.http(async (request, nextLayer) => {
456
562
  try {
457
563
  const record = await databases.flair[guarded.table]?.get(guarded.id);
458
564
  if (isForbiddenOwnerMutation(record, guarded.ownerField, agentId)) {
459
- return new Response(JSON.stringify({
460
- error: `forbidden: cannot modify ${guarded.table} owned by another principal`,
461
- }), { status: 403, headers: { "Content-Type": "application/json" } });
565
+ return ownerMutationRefusal(guarded.table);
462
566
  }
463
567
  }
464
568
  catch { /* unreadable row → fall through to the resource's own rules */ }
@@ -624,39 +728,23 @@ server.http(async (request, nextLayer) => {
624
728
  // Instead, the resource-level check (e.g. BootstrapMemories line 58) handles
625
729
  // body-level enforcement since it receives the parsed data from Harper's REST
626
730
  // layer. The middleware's job is identity verification (done above).
627
- // ── Memory GET: non-admin can only read own memories (by ID) ────────────────
628
- if (!request.tpsAgentIsAdmin && method === "GET") {
629
- if (url.pathname.startsWith("/Memory/")) {
630
- try {
631
- const pathParts = url.pathname.split("/").filter(Boolean);
632
- const memId = pathParts[1] ? decodeURIComponent(pathParts[1]) : null;
633
- if (memId) {
634
- const record = await databases.flair.Memory.get(memId);
635
- if (record && record.agentId && record.agentId !== agentId) {
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
639
- // used to be a `visibility === "office"` bypass (any authenticated
640
- // agent, no grant needed) — that's gone; the private-exclusion is
641
- // now enforced the same way every other read path enforces it.
642
- //
643
- // Denial is the SAME 404 the resource layer returns (flair#1264):
644
- // Memory.get() deliberately answers NOT_FOUND for a cross-agent
645
- // private id so a denied caller can't distinguish "doesn't exist"
646
- // from "exists but not yours" — a 403 here, worse yet one naming
647
- // the owning agent, confirmed the id exists AND disclosed its
648
- // owner, defeating that anti-enumeration contract one layer up.
649
- // Reuses record-type-kit's NOT_FOUND so the two layers cannot
650
- // drift apart in shape.
651
- const scope = await resolveReadScope(agentId);
652
- if (!scope.isAllowed(record)) {
653
- return NOT_FOUND();
654
- }
655
- }
656
- }
657
- }
658
- catch { /* record not found or table error — let resource handle */ }
659
- }
731
+ // ── Memory read: a non-admin read ignores the caller's selection ─────────────
732
+ // flair#1940 round 17 (design ruling): a non-admin HTTP Memory read does NOT
733
+ // honour a caller `select(...)` or `property`. As soon as authentication has
734
+ // established that the caller is not an admin — and BEFORE anything reads a
735
+ // Memory row or hands the request to the next layer — the request URL is
736
+ // normalized to drop the caller's selection, keeping conditions, operator,
737
+ // sort, limit and offset exactly as sent. Harper builds its REST target from
738
+ // this URL AFTER this middleware, so the original selection cannot be
739
+ // reapplied. An admin read and a trusted internal read are unchanged, while a
740
+ // direct contextual non-admin read now ignores the selection too (the same
741
+ // contract, applied in `Memory.get`/`Memory.search`). The by-id
742
+ // read-scope denial is enforced by the resource layer (memoryByIdReadGate),
743
+ // which returns the same 404 this middleware used to return.
744
+ if (!request.tpsAgentIsAdmin && method === "GET" && isMemoryReadPath(url.pathname)) {
745
+ const stripped = stripMemorySelection(request.url);
746
+ if (stripped !== request.url)
747
+ request.url = stripped;
660
748
  }
661
749
  // ── Embedding backfill ─────────────────────────────────────────────────────
662
750
  const isMemoryWrite = isMutation && (url.pathname === "/Memory" || url.pathname.startsWith("/Memory/"));
@@ -670,4 +758,4 @@ server.http(async (request, nextLayer) => {
670
758
  backfillEmbedding(memoryId).catch(() => { });
671
759
  }
672
760
  return response;
673
- }, { runFirst: true });
761
+ }, { runFirst: true, name: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME });
@@ -107,10 +107,10 @@ export const DEFAULT_MAX_AUTO_PROMOTE_PER_CYCLE = 200;
107
107
  // describe it otherwise anywhere (comment, changelog, skip reason) — we amended
108
108
  // the 0.55.0 Metal entry for exactly this overclaim shape.
109
109
  //
110
- // The detection is ASCII-ONLY. It recognizes the ASCII backtick and the ASCII
111
- // pairs ( ) [ ] { }. Non-ASCII pairs — full-width ()/[]/{} and CJK lenticular
112
- // 【】/〔〕/〖〗 — are NOT covered, so a truncated claim written in those scripts
113
- // is judged balanced and is NOT refused. Do not assume Unicode coverage.
110
+ // Bracket coverage is the enumerated table in src/rem/promote-policy.ts,
111
+ // including its full-width/CJK pairs; unlisted bracket pairs are not checked.
112
+ // Backticks use parity, not Markdown span matching, so valid escape spans
113
+ // can be refused. This signal does not establish semantic completeness.
114
114
  //
115
115
  // The check counts delimiters WITHOUT interpreting context, so it is deliberately
116
116
  // over-broad: a COMPLETE claim that merely discusses an unmatched delimiter (an