@tpsdev-ai/flair 0.59.0 → 0.62.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -1,13 +1,21 @@
1
- import { patchRecord } from "./table-helpers.js";
1
+ import { WRITE_BACK_ATTEMPTS, WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
2
+ import { txnPausePoint } from "./txn-pause-point.js";
2
3
  import { server, databases } from "harper";
3
- import { getEmbedding } from "./embeddings-provider.js";
4
- import { isAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME } from "./agent-auth.js";
4
+ import { getEmbedding, getModelId } from "./embeddings-provider.js";
5
+ import { noteWriteStamp } from "./embedding-space-guard.js";
6
+ import { hashEmbeddedText } from "./memory-embed-hash.js";
7
+ import { MEMORY_EMBEDDING_INPUT_FIELDS, skillEmbedText } from "./skill-write.js";
8
+ import { isAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME, readCredentialedPrincipal, AGENT_LOOKUP_FAILED } from "./agent-auth.js";
5
9
  import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
6
10
  import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
7
- import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord } from "./record-owner-guard.js";
11
+ import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord, resolveGuardedRecordById } from "./record-owner-guard.js";
12
+ import { routeWithHarper } from "./harper-routing.js";
8
13
  import { checkHttpRateLimit } from "./rate-limit.js";
9
14
  import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
10
- import { stripUndeclaredMemoryAttributes, DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
15
+ import { DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
16
+ import { idSegmentHasEncodedSlash, decodeMemoryIdSegment, MEMORY_CONTENT_SELECTOR_SUFFIX } from "../src/lib/memory-id-policy.js";
17
+ import { contentSuffixIdDenial } from "./memory-id-guard.js";
18
+ import { isCanonicalRequestTarget, nonCanonicalRequestTargetRefusal, requestPath, lastRawPathSegment, routedRecordId, routedResourceAndRemainder, routedIdAfterPropertyRule, routedResourcePath, } from "./request-target.js";
11
19
  // --- Non-admin Memory read: ignore the caller's selection --------------------
12
20
  //
13
21
  // flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
@@ -19,30 +27,38 @@ const DECLARED_MEMORY_ATTRIBUTE_SET = new Set(DECLARED_MEMORY_ATTRIBUTES);
19
27
  function isMemoryReadPath(pathname) {
20
28
  return pathname === "/Memory" || pathname === "/Memory/" || pathname.startsWith("/Memory/");
21
29
  }
30
+ /** True when a path segment is valid percent-encoding. */
31
+ function isValidPercentEncoding(segment) {
32
+ try {
33
+ decodeURIComponent(segment);
34
+ return true;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
22
40
  // Drop a caller's `select(...)` and `property` from a Memory read URL, keeping
23
41
  // conditions, operator, sort, limit and offset. Returns the input unchanged when
24
42
  // the URL carries no selection.
25
- function stripMemorySelection(rawUrl) {
43
+ //
44
+ // The path rewrite runs ONLY when Harper routed this target to a Memory RECORD
45
+ // (`routedToMemoryRecord`): the raw path alone is not enough, because a target
46
+ // Harper resolved with no record id — e.g. `/Memory.json/<id>.content`, whose
47
+ // suffixed first segment routes to the Memory COLLECTION with an empty remainder
48
+ // — must not be turned into a by-id read of a row the target does not address.
49
+ function stripMemorySelection(rawUrl, routedToMemoryRecord) {
26
50
  const q = rawUrl.indexOf("?");
27
51
  let pathPart = q === -1 ? rawUrl : rawUrl.slice(0, q);
28
52
  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))}`;
53
+ // Strip a declared-attribute suffix after the first dot in the decoded remainder.
54
+ const { remainder } = routedResourceAndRemainder(pathPart);
55
+ const decodedId = decodeMemoryIdSegment(remainder);
56
+ const stripped = routedIdAfterPropertyRule(decodedId, DECLARED_MEMORY_ATTRIBUTE_SET);
57
+ // An encoded `/` in the id makes the suffix ambiguous (the caller is refused
58
+ // upstream in the middleware), so only rewrite when there is no encoded slash
59
+ // and the first-dot rule actually dropped a declared-attribute suffix.
60
+ if (routedToMemoryRecord && !idSegmentHasEncodedSlash(remainder) && stripped !== decodedId) {
61
+ pathPart = `/Memory/${encodeURIComponent(stripped)}`;
46
62
  }
47
63
  // Query form: drop every `select(...)` token and every `property` parameter.
48
64
  for (const [start, end] of selectSpans(query).reverse()) {
@@ -59,16 +75,19 @@ function stripMemorySelection(rawUrl) {
59
75
  return pathPart;
60
76
  return query === "" ? pathPart : `${pathPart}?${query}`;
61
77
  }
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
- }
78
+ /**
79
+ * True when a Memory by-id read path names an id that carries an encoded `/`
80
+ * (`%2F`/`%2f`) AND would otherwise be given the property-suffix rewrite in
81
+ * stripMemorySelection. Such an id is ambiguous — the trailing
82
+ * `.<declared attribute>` could be part of the id or a selector on an id that
83
+ * contains a slash (flair#2199).
84
+ */
85
+ function isAmbiguousEncodedSlashSelector(rawUrl) {
86
+ const { remainder } = routedResourceAndRemainder(requestPath(rawUrl));
87
+ if (!idSegmentHasEncodedSlash(remainder))
88
+ return false;
89
+ const decodedId = decodeMemoryIdSegment(remainder);
90
+ return routedIdAfterPropertyRule(decodedId, DECLARED_MEMORY_ATTRIBUTE_SET) !== decodedId;
72
91
  }
73
92
  // [start, end) ranges of every `select(...)` call in a query string, accounting
74
93
  // for Harper's nested-list form `select((a,b))`.
@@ -144,26 +163,149 @@ function getAdminPass() {
144
163
  // them, and the crypto/decoder logic can't drift.
145
164
  async function backfillEmbedding(memoryId) {
146
165
  try {
147
- const record = await databases.flair.Memory.get(memoryId);
148
- if (!record?.content)
149
- return;
150
- if (record.embedding?.length > 100)
151
- return;
152
- // flair#504 Phase 2: 'document' — a backfilled embedding IS a stored
153
- // document vector, same as the three Memory.ts sites; must match.
154
- const embedding = await getEmbedding(record.content, "document");
155
- if (!embedding)
156
- return;
157
- const embedPatch = { embedding };
158
- stripUndeclaredMemoryAttributes(embedPatch);
159
- await patchRecord(databases.flair.Memory, memoryId, embedPatch);
160
- console.log(`[auto-embed] ${memoryId}: ${embedding.length}d`);
166
+ const table = databases.flair.Memory;
167
+ // flair#2484: compute the vector before the owned write transaction opens.
168
+ // The text embedded is the one Memory's own writers embed (flair#2465,
169
+ // `skillEmbedText`: a skill-tagged row's non-empty `trigger`, else
170
+ // `content`). Rows without that text or with an embedding longer than 100
171
+ // entries skip before the text comparison. For eligible rows, `matchFields`
172
+ // compares every field that selects the text (`content`, `trigger`, `tags`)
173
+ // before staging; the helper confirms the committed row afterward. Drift
174
+ // observed by either check aborts the attempt; remaining outer attempts
175
+ // re-read and may recompute. Changes after confirmation and before commit
176
+ // are not detected by these checks.
177
+ //
178
+ // flair#2573: the vector is stamped with the current model id, the space it
179
+ // was computed in, and the embedding-space guard is notified after the write
180
+ // commits with that stamp and the row it replaced, as for any other notified
181
+ // vector write.
182
+ for (let attempt = 1; attempt <= WRITE_BACK_ATTEMPTS; attempt++) {
183
+ const record = await table.get(memoryId, {});
184
+ const text = record ? skillEmbedText(record) : undefined;
185
+ if (typeof text !== "string" || text.length === 0)
186
+ return;
187
+ if (record.embedding?.length > 100)
188
+ return;
189
+ const embedding = await getEmbedding(text, "document");
190
+ if (!Array.isArray(embedding) || embedding.length === 0)
191
+ return;
192
+ const model = getModelId();
193
+ // The vector fields of the committed row the update replaces, for the
194
+ // guard notification.
195
+ let replaced = null;
196
+ try {
197
+ const outcome = await writeBackCommittedRow(table, memoryId, (row) => {
198
+ const rowText = row ? skillEmbedText(row) : undefined;
199
+ if (typeof rowText !== "string" || rowText.length === 0)
200
+ return { skip: true };
201
+ if (row.embedding?.length > 100)
202
+ return { skip: true };
203
+ replaced = { embedding: row.embedding, embeddingModel: row.embeddingModel };
204
+ // Only `embedding`, its model stamp and its text hash: an incremental
205
+ // update, never a full-row put of the row read above (flair#2470,
206
+ // flair#2465). The newly computed hash is of `text`, the text this
207
+ // vector was computed from (null for an empty owner).
208
+ return { update: { embedding, embeddingModel: model, embeddedContentHash: hashEmbeddedText(row.agentId, text) ?? null } };
209
+ }, {
210
+ label: "backfillEmbedding",
211
+ expectedRow: record,
212
+ // Compare the text-selecting fields before staging, after the plan's skip checks.
213
+ matchFields: [...MEMORY_EMBEDDING_INPUT_FIELDS, "tags"],
214
+ pausePre: () => txnPausePoint("backfill-embedding-pre"),
215
+ pausePoint: () => txnPausePoint("backfill-embedding"),
216
+ });
217
+ if ("update" in outcome) {
218
+ // After the commit: the stamp the update stored (an absent one reads as
219
+ // untrusted and closes the guard) and the row it replaced.
220
+ noteWriteStamp(outcome.update.embeddingModel, replaced);
221
+ console.log(`[auto-embed] ${memoryId}: ${outcome.update.embedding.length}d`);
222
+ }
223
+ return;
224
+ }
225
+ catch (err) {
226
+ if (err instanceof WriteBackConflictError && attempt < WRITE_BACK_ATTEMPTS)
227
+ continue;
228
+ throw err;
229
+ }
230
+ }
161
231
  }
162
232
  catch (err) {
163
233
  console.error(`[auto-embed] Failed for ${memoryId}: ${err.message}`);
164
234
  }
165
235
  }
166
236
  // ─── HTTP middleware ──────────────────────────────────────────────────────────
237
+ /**
238
+ * Refuse a credentialed Basic-auth request whose Agent row could not be READ:
239
+ * log the named error and return it. A read that FAILED is never an absent
240
+ * principal (flair#2403); the same rule resources/AgentSeed.ts applies as
241
+ * `agent_lookup_failed`.
242
+ */
243
+ function credentialedLookupRefusal(username, error) {
244
+ console.error("auth-middleware: the credentialed principal lookup failed, so the request was refused", { username, error });
245
+ return new Response(JSON.stringify({
246
+ error: AGENT_LOOKUP_FAILED,
247
+ message: "the principal record could not be read, so the request was refused",
248
+ }), { status: 500, headers: { "content-type": "application/json" } });
249
+ }
250
+ /**
251
+ * A guarded mutation whose stored-owner read FAILED is refused, not allowed
252
+ * through. The ownership read is the authorization input; a failed read is not
253
+ * "no owner", so it must fail closed. 503 because a retry can succeed.
254
+ */
255
+ function ownerReadFailedRefusal(table) {
256
+ console.error("auth-middleware: the stored-owner read failed, so the mutation was refused", { table });
257
+ return new Response(JSON.stringify({
258
+ error: "owner_lookup_failed",
259
+ message: "the record's owner could not be read, so the write was refused",
260
+ }), { status: 503, headers: { "content-type": "application/json" } });
261
+ }
262
+ /**
263
+ * A signed non-admin agent's mutation that reaches the owner checks is refused
264
+ * when Harper's route lookup threw: the owner decisions need Harper's route, and
265
+ * the pure fallback does not stand in for it. 503 because a retry can succeed. The message is fixed and
266
+ * names no part of the target.
267
+ */
268
+ function routeLookupFailedRefusal() {
269
+ console.error("auth-middleware: the route lookup failed, so the mutation was refused");
270
+ return new Response(JSON.stringify({
271
+ error: "route_lookup_failed",
272
+ message: "the request could not be routed, so the write was refused",
273
+ }), { status: 503, headers: { "content-type": "application/json" } });
274
+ }
275
+ /**
276
+ * A signed non-admin agent's mutation that reaches the owner checks, whose target
277
+ * Harper matched but whose record id Harper's request-target parsing or path
278
+ * parsing could not resolve, is refused before any owner decision: those
279
+ * decisions need the id. 400: the target cannot be parsed into a record id. The
280
+ * message is fixed and names no part of the target.
281
+ */
282
+ function unresolvedTargetRefusal() {
283
+ return new Response(JSON.stringify({
284
+ error: "unresolved_request_target",
285
+ message: "the request target could not be resolved to a record id, so the write was refused",
286
+ }), { status: 400, headers: { "content-type": "application/json" } });
287
+ }
288
+ /**
289
+ * The id a Memory write COMMITTED, read from the writer's own response result
290
+ * (its `id` field) — the trustworthy source, since a by-id write can commit a
291
+ * successor with a different id. Returns null when the result names no id as a
292
+ * plain string body (a 204, a streamed or compressed body); the caller then
293
+ * falls back to the routed id for a PUT or PATCH, and otherwise skips. Reads
294
+ * only the already-serialized string body; never consumes a stream.
295
+ */
296
+ function committedMemoryIdFromResult(response) {
297
+ const body = response?.body;
298
+ if (typeof body !== "string" || body.length === 0)
299
+ return null;
300
+ try {
301
+ const parsed = JSON.parse(body);
302
+ const id = parsed?.id;
303
+ return typeof id === "string" && id.length > 0 ? id : null;
304
+ }
305
+ catch {
306
+ return null;
307
+ }
308
+ }
167
309
  // Flair's clients use exactly these HTTP methods. Harper routes other methods
168
310
  // to resource handlers as well; refusing them here, before any other branch of
169
311
  // the default REST middleware, keeps the tables it serves to the methods their
@@ -172,11 +314,48 @@ async function backfillEmbedding(memoryId) {
172
314
  const ALLOWED_HTTP_METHODS = new Set([
173
315
  "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE",
174
316
  ]);
317
+ // The resources the middleware makes a by-NAME decision on: the public-path
318
+ // allowance and the OAuth rate-limit policy.
319
+ const NAME_ROUTED_RESOURCES = new Set([
320
+ "health", "Health", "a2a", "A2AAdapter", "AgentCard",
321
+ "FederationSync", "FederationPair",
322
+ "OAuthRegister", "OAuthAuthorize", "OAuthToken", "OAuthRevoke", "OAuthMetadata",
323
+ "Admin",
324
+ ]);
325
+ const RAW_QUERY_RESOURCES = new Set(["sql", "graphql"]);
175
326
  server.http(async (request, nextLayer) => {
176
- // ── HTTP method allowlist, FIRST ───────────────────────────────────────────
177
- // Before the public-path passthrough and before any auth branch, so no path
178
- // and no caller (anonymous, agent or admin) can reach a handler through any
179
- // other method.
327
+ // ── Canonical request target, FIRST ────────────────────────────────────────
328
+ // This check reads the RAW request target, the string Harper routes. A target
329
+ // that is not in canonical form (a `.`/`..` segment, raw or percent-encoded;
330
+ // repeated slashes; a raw backslash) is answered with the named 400 here,
331
+ // before any other request processing: no method check, no rate-limit budget,
332
+ // no credential read, no next layer. See resources/request-target.ts.
333
+ const rawTarget = typeof request.url === "string" ? request.url : String(request.url ?? "");
334
+ if (!isCanonicalRequestTarget(rawTarget)) {
335
+ return nonCanonicalRequestTargetRefusal(String(request.method ?? ""));
336
+ }
337
+ const targetPath = requestPath(rawTarget);
338
+ // ── Resolve the target through Harper's OWN routing, FIRST ──────────────────
339
+ // Synchronous and before any await (getMatch mutates its entry in place; see
340
+ // harper-routing.ts). The helpers in request-target.ts are the fallback when
341
+ // no route is returned: the live registry or Harper's `RequestTarget` is absent
342
+ // (a unit test mocking `harper`), the target matches no route, or the matcher
343
+ // throws. When the matcher throws, a signed non-admin agent's mutation that
344
+ // reaches the owner checks is refused instead (below), before any owner
345
+ // decision; the checks that run earlier (e.g. the rate limit and the raw-query
346
+ // refusal) still answer first.
347
+ let routed = null;
348
+ let routeLookupFailed = false;
349
+ try {
350
+ routed = routeWithHarper(rawTarget, request.headers);
351
+ }
352
+ catch {
353
+ routeLookupFailed = true;
354
+ }
355
+ // ── HTTP method allowlist ──────────────────────────────────────────────────
356
+ // After the canonical check and route resolution: before the public-path passthrough
357
+ // and before any auth branch, so no path and no caller (anonymous, agent or
358
+ // admin) can reach a handler through any other method.
180
359
  // Exact match: HTTP methods are case-sensitive, and these are the spellings
181
360
  // Flair's clients send.
182
361
  const httpMethod = String(request.method ?? "");
@@ -189,6 +368,9 @@ server.http(async (request, nextLayer) => {
189
368
  headers: { "content-type": "application/json", allow: [...ALLOWED_HTTP_METHODS].join(", ") },
190
369
  });
191
370
  }
371
+ // The parsed URL is read for the signed payload (the client signs the
372
+ // pathname and search of the URL it built) and for query parameters only.
373
+ // A path decision is never made on its parsed pathname.
192
374
  const url = new URL(request.url, "http://" + (request.headers.get("host") || "localhost"));
193
375
  // ── Rate limiting, right after the method check ────────────────────────────
194
376
  // Before the public-path passthrough below (the OAuth endpoints all sit on it,
@@ -209,9 +391,25 @@ server.http(async (request, nextLayer) => {
209
391
  // Only the OAuth endpoints named in rate-limit.ts's PATH_POLICY are affected.
210
392
  // Every other path — /Memory, /Presence, /FederationSync, everything agents
211
393
  // actually use — returns null here and is untouched.
212
- const limited = checkHttpRateLimit(request, url.pathname);
394
+ //
395
+ const routedDecisionPath = routed?.decisionPath ?? routedResourcePath(targetPath, NAME_ROUTED_RESOURCES);
396
+ const limited = checkHttpRateLimit(request, routedDecisionPath);
213
397
  if (limited)
214
398
  return limited;
399
+ // ── Malformed `.content` Memory path: the named 400, for every caller ────────
400
+ // flair#2307 item 2: Harper's OWN path decode answers a 500 for invalid
401
+ // percent-encoding, before any resource by-id guard can run. A Memory path
402
+ // whose last segment is invalid percent-encoding AND ends in the `.content`
403
+ // property suffix is refused here with the guard's named 400 instead. Placed
404
+ // before every auth branch (the public-path passthrough, the Basic-admin and
405
+ // anonymous early returns, the signed-agent path), so the refusal does not
406
+ // depend on the request's credential, and no row is read or written for it.
407
+ if (isMemoryReadPath(targetPath)) {
408
+ const seg = lastRawPathSegment(targetPath);
409
+ if (seg.endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX) && !isValidPercentEncoding(seg)) {
410
+ return contentSuffixIdDenial(seg);
411
+ }
412
+ }
215
413
  // A2A discovery endpoints: GET returns public agent-card metadata (per
216
414
  // A2A spec, cards are intentionally public). POST invokes JSON-RPC
217
415
  // actions (message/send writes OrgEvents on behalf of agents,
@@ -219,60 +417,47 @@ server.http(async (request, nextLayer) => {
219
417
  // OrgEvents) — those must be authenticated. Narrowing to GET-only
220
418
  // closes the P0 where any caller could forge OrgEvents as any agent
221
419
  // and read all internal Beads issues unauthenticated.
222
- const isA2APath = url.pathname === "/a2a" || url.pathname === "/A2AAdapter" || url.pathname.startsWith("/A2AAdapter/");
223
- if (url.pathname === "/health" ||
224
- url.pathname === "/Health" ||
420
+ const header = request.headers.get("authorization") || request.headers?.asObject?.authorization || "";
421
+ const isTpsEd25519 = /^TPS-Ed25519(?:\s|$)/i.test(header);
422
+ // Scheme names are case-insensitive (RFC 9110): "basic"/"BASIC"/"Basic" all
423
+ // select the Basic branch below, exactly as "Basic" does. Used for both the
424
+ // /FederationPair public-bypass test and the Basic branch itself.
425
+ const isBasic = /^Basic /i.test(header);
426
+ const isA2APath = routedDecisionPath === "/a2a" || routedDecisionPath === "/A2AAdapter" || routedDecisionPath.startsWith("/A2AAdapter/");
427
+ if (!isTpsEd25519 && (routedDecisionPath === "/health" ||
428
+ routedDecisionPath === "/Health" ||
225
429
  (request.method === "GET" && isA2APath) ||
226
- url.pathname === "/AgentCard" ||
227
- url.pathname.startsWith("/AgentCard/") ||
430
+ routedDecisionPath === "/AgentCard" ||
431
+ routedDecisionPath.startsWith("/AgentCard/") ||
228
432
  // FederationSync uses Ed25519 body-signature auth with anti-replay, validated
229
433
  // by the resource handler (allowCreate=true, same pattern as FederationPair).
230
- url.pathname === "/FederationSync" ||
434
+ routedDecisionPath === "/FederationSync" ||
231
435
  // FederationPair uses one-time PairingToken in the request body, validated
232
436
  // by the resource itself (allowCreate=true on the Resource lets anonymous
233
437
  // POST through Harper's role gate). Bearer can't be used here because
234
438
  // Harper's auth layer claims any "Bearer X" Authorization header for itself.
235
- url.pathname === "/FederationPair" ||
439
+ //
440
+ // A Basic-credentialled pair request is NOT passed through here. The Basic
441
+ // block below is what authenticates the token's bootstrap user
442
+ // (pair-bootstrap-<id>, Path 3) and annotates `tpsAgent`; passing straight
443
+ // through skipped that annotation, so the resource's bootstrap-user binding
444
+ // (PR-4, resources/Federation.ts) could never see a caller and never
445
+ // refused a mismatch. An anonymous pair request (no Authorization header)
446
+ // still passes through.
447
+ (routedDecisionPath === "/FederationPair" && !isBasic) ||
236
448
  // OAuth 2.1 public endpoints (spec requires no pre-auth)
237
- url.pathname === "/OAuthRegister" ||
238
- url.pathname === "/OAuthAuthorize" ||
239
- url.pathname === "/OAuthToken" ||
240
- url.pathname === "/OAuthRevoke" ||
449
+ routedDecisionPath === "/OAuthRegister" ||
450
+ routedDecisionPath === "/OAuthAuthorize" ||
451
+ routedDecisionPath === "/OAuthToken" ||
452
+ routedDecisionPath === "/OAuthRevoke" ||
241
453
  // Belt-and-braces since flair#1000: `/.well-known/oauth-authorization-server`
242
454
  // is served from its OWN urlPath mount (resources/oauth-wellknown.ts), which
243
455
  // gets its own dispatch chain — this middleware never sees a request for it.
244
456
  // The entry stays so the path is still public if that mount ever moves back
245
457
  // onto the default chain.
246
- url.pathname === "/.well-known/oauth-authorization-server" ||
247
- url.pathname === "/OAuthMetadata" ||
248
- // Presence roster is public-safe (field-allowlisted); GET serves the
249
- // Office Space renderer without auth. Scoped to GET only (#604): the
250
- // exact-path match used to match ANY method, so a bare `PUT /Presence`
251
- // (collection-level, no id — Harper routes it to the same .put() as
252
- // by-id PUT) early-returned here too, skipping this middleware entirely.
253
- // A credential-less loopback PUT then reached Presence.put()'s
254
- // resolveAgentAuth() call with NO tpsAnonymous/tpsAgent annotation, which
255
- // fell through to raw `context.user` — populated by Harper's
256
- // `authorizeLocal` (config true) ambient super_user injection for ANY
257
- // credential-less loopback request — so the ownership check saw an
258
- // "admin" caller (isAdmin=true) and let the write through unauthenticated
259
- // (`super.put()`, no signature, no password). Mirrors the A2A GET-only
260
- // pattern above: POST/PUT/DELETE now always transit the general
261
- // middleware path below, which marks a genuinely headerless request
262
- // tpsAnonymous BEFORE Harper's ambient elevation lands (resolveAgentAuth
263
- // checks tpsAnonymous first — see agent-auth.ts's resolution order), so
264
- // the ownership check in Presence.put()/delete() correctly denies it.
265
- // POST (the heartbeat) is unaffected in practice: it already prefers
266
- // request.tpsAgent when the middleware set it, and falls back to its own
267
- // Ed25519 header parse otherwise — transiting the general path now just
268
- // means a genuinely headerless POST gets marked anonymous (still 401)
269
- // instead of skipping straight to that fallback parse.
270
- (request.method === "GET" && url.pathname === "/Presence"))
458
+ routedDecisionPath === "/.well-known/oauth-authorization-server" ||
459
+ routedDecisionPath === "/OAuthMetadata"))
271
460
  return nextLayer(request);
272
- // Read the Authorization header ONCE, up front — the super_user branch below
273
- // needs it too (hoisted from its former position just after the branch as part
274
- // of the flair#610 belt-and-suspenders check).
275
- const header = request.headers.get("authorization") || request.headers?.asObject?.authorization || "";
276
461
  // If Harper has already authorized this request (e.g. Basic admin, or
277
462
  // authorizeLocal=true on localhost), trust Harper's auth decision and pass
278
463
  // through. Annotate the admin identity so resources' resolveAgentAuth recognizes
@@ -288,13 +473,15 @@ server.http(async (request, nextLayer) => {
288
473
  // live vector today — but it keeps the trust decision from ever hinging on
289
474
  // ambient elevation alone. (The root-cause gate lives in resolveAgentAuth; see
290
475
  // agent-auth.ts hasCredentialEvidence.)
291
- if (header && request.user?.role?.permission?.super_user === true) {
476
+ if (!isTpsEd25519 && header && request.user?.role?.permission?.super_user === true) {
292
477
  const username = request.user.username ?? "admin";
293
478
  // Deactivation guard — same predicate as the Ed25519 path.
294
479
  // A deactivated principal must not receive a tpsAgent annotation, even
295
480
  // when Harper's ambient auth already verified the credential.
296
- const agentRecord = await databases.flair.Agent.get(username).catch(() => null);
297
- if (!isPrincipalDeactivated(agentRecord)) {
481
+ const read = await readCredentialedPrincipal(username);
482
+ if (!read.ok)
483
+ return credentialedLookupRefusal(username, read.error);
484
+ if (!isPrincipalDeactivated(read.agent)) {
298
485
  request.tpsAgent = username;
299
486
  request.tpsAgentIsAdmin = true;
300
487
  try {
@@ -316,7 +503,7 @@ server.http(async (request, nextLayer) => {
316
503
  // 1. HDB_ADMIN_PASSWORD env-var fast-path (user must be "admin" with exact pass)
317
504
  // 2. Harper super_user check — any user with super_user:true permission accepted
318
505
  // Checked BEFORE Ed25519 so admin tools can use simple auth.
319
- if (header.startsWith("Basic ")) {
506
+ if (isBasic) {
320
507
  try {
321
508
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf-8");
322
509
  const colonIdx = decoded.indexOf(":");
@@ -327,8 +514,10 @@ server.http(async (request, nextLayer) => {
327
514
  const adminPass = getAdminPass();
328
515
  if (adminPass !== null && user === "admin" && pass === adminPass) {
329
516
  // Deactivation guard — same predicate, called before tpsAgent is stamped.
330
- const agentRecord = await databases.flair.Agent.get("admin").catch(() => null);
331
- if (!isPrincipalDeactivated(agentRecord)) {
517
+ const read = await readCredentialedPrincipal("admin");
518
+ if (!read.ok)
519
+ return credentialedLookupRefusal("admin", read.error);
520
+ if (!isPrincipalDeactivated(read.agent)) {
332
521
  // Mark as verified and set Harper user directly
333
522
  request._tpsAuthVerified = true;
334
523
  try {
@@ -352,8 +541,10 @@ server.http(async (request, nextLayer) => {
352
541
  catch { /* fall through — invalid creds, non-existent user, etc. */ }
353
542
  if (harperUser?.role?.permission?.super_user === true) {
354
543
  // Deactivation guard — same predicate, called before tpsAgent is stamped.
355
- const agentRecord = await databases.flair.Agent.get(user).catch(() => null);
356
- if (!isPrincipalDeactivated(agentRecord)) {
544
+ const read = await readCredentialedPrincipal(user);
545
+ if (!read.ok)
546
+ return credentialedLookupRefusal(user, read.error);
547
+ if (!isPrincipalDeactivated(read.agent)) {
357
548
  request._tpsAuthVerified = true;
358
549
  request.user = harperUser;
359
550
  request.headers.set("x-tps-agent", user);
@@ -368,7 +559,7 @@ server.http(async (request, nextLayer) => {
368
559
  // Path 3: flair_pair_initiator — restricted to /FederationPair only.
369
560
  // Bootstrap credentials (pair-bootstrap-<id>) may only be used on this
370
561
  // one endpoint. Any other path must fall through to 401.
371
- if (url.pathname === "/FederationPair" && user.startsWith("pair-bootstrap-")) {
562
+ if (routedDecisionPath === "/FederationPair" && user.startsWith("pair-bootstrap-")) {
372
563
  let pairUser = null;
373
564
  try {
374
565
  pairUser = await server.getUser(user, pass, request);
@@ -377,8 +568,10 @@ server.http(async (request, nextLayer) => {
377
568
  if (pairUser?.role?.role === "flair_pair_initiator" &&
378
569
  pairUser?.active === true) {
379
570
  // Deactivation guard — same predicate, called before tpsAgent is stamped.
380
- const agentRecord = await databases.flair.Agent.get(user).catch(() => null);
381
- if (!isPrincipalDeactivated(agentRecord)) {
571
+ const read = await readCredentialedPrincipal(user);
572
+ if (!read.ok)
573
+ return credentialedLookupRefusal(user, read.error);
574
+ if (!isPrincipalDeactivated(read.agent)) {
382
575
  request._tpsAuthVerified = true;
383
576
  request.user = pairUser;
384
577
  request.headers.set("x-tps-agent", user);
@@ -409,11 +602,13 @@ server.http(async (request, nextLayer) => {
409
602
  // ── Ed25519 agent auth ────────────────────────────────────────────────────
410
603
  const parsed = parseTpsEd25519Header(header);
411
604
  if (!parsed) {
605
+ if (isTpsEd25519)
606
+ return new Response(JSON.stringify({ error: "invalid_authorization_header" }), { status: 401 });
412
607
  // For browser-accessible admin pages, emit `WWW-Authenticate: Basic` so
413
608
  // the browser shows a native auth dialog instead of a bare 401 page.
414
609
  // JSON API endpoints don't get this — they should keep the structured
415
610
  // 401 body so the client can parse the error.
416
- const isAdminPage = url.pathname === "/Admin" || url.pathname.startsWith("/Admin");
611
+ const isAdminPage = routedDecisionPath === "/Admin" || routedDecisionPath.startsWith("/Admin");
417
612
  if (isAdminPage) {
418
613
  return new Response("Authentication required.", {
419
614
  status: 401,
@@ -475,15 +670,6 @@ server.http(async (request, nextLayer) => {
475
670
  request.tpsAgent = agentId;
476
671
  request._tpsAuthVerified = true;
477
672
  request.tpsAgentIsAdmin = await isAdmin(agentId);
478
- // Grant Harper-level permissions for the cryptographically-verified agent by
479
- // setting request.user directly. Setting request.user is the supported
480
- // extension path (and the only one that works post-5.0.9: Harper resolves
481
- // request.user from the Authorization header BEFORE this middleware runs, and
482
- // a TPS-Ed25519 header matches no Basic/Bearer strategy, so request.user
483
- // arrives null — see #456). getUser(name, null) looks up the record WITHOUT
484
- // password validation, safe here because the Ed25519 signature already proved
485
- // identity cryptographically.
486
- //
487
673
  // RESHAPE (auth-rbac) — THE FLIP: per-agent DE-ELEVATION. A cryptographically-
488
674
  // verified NON-admin agent resolves to the least-privilege `flair-agent` user,
489
675
  // NOT admin super_user. The flair_agent role grants exactly the table CRUD agents
@@ -530,15 +716,26 @@ server.http(async (request, nextLayer) => {
530
716
  // SQL and GraphQL endpoints bypass all resource-level scoping — block them
531
717
  // for non-admin agents. Admins (bootstrap, consolidation scripts) still pass.
532
718
  if (!request.tpsAgentIsAdmin) {
533
- const rawPath = url.pathname.toLowerCase();
534
- if (rawPath === "/sql" || rawPath.startsWith("/sql/") ||
535
- rawPath === "/graphql" || rawPath.startsWith("/graphql/")) {
719
+ const lowerPath = (routed ? routedDecisionPath : routedResourcePath(targetPath, RAW_QUERY_RESOURCES)).toLowerCase();
720
+ if (lowerPath === "/sql" || lowerPath.startsWith("/sql/") ||
721
+ lowerPath === "/graphql" || lowerPath.startsWith("/graphql/")) {
536
722
  return new Response(JSON.stringify({ error: "forbidden: raw query endpoints require admin access" }), { status: 403, headers: { "Content-Type": "application/json" } });
537
723
  }
538
724
  }
539
725
  // ── Server-side permission guards ──────────────────────────────────────────
540
726
  const method = request.method.toUpperCase();
541
727
  const isMutation = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
728
+ // A signed non-admin agent's mutation that reaches this point (the earlier
729
+ // checks, e.g. the rate limit and the raw-query refusal, answer first) is
730
+ // refused before the owner decisions below when Harper's route lookup threw, or
731
+ // when Harper matched the target but its request-target parsing or path parsing
732
+ // could not resolve the record id.
733
+ if (isMutation && !request.tpsAgentIsAdmin && routeLookupFailed) {
734
+ return routeLookupFailedRefusal();
735
+ }
736
+ if (isMutation && !request.tpsAgentIsAdmin && routed?.recordIdUnresolved) {
737
+ return unresolvedTargetRefusal();
738
+ }
542
739
  // ── THE record-ownership rule, for every table, on every mutating verb ─────
543
740
  //
544
741
  // One enforcement point rather than one per resource. See
@@ -556,21 +753,38 @@ server.http(async (request, nextLayer) => {
556
753
  // resource's own no-forge attribution. That keeps this incapable of breaking a
557
754
  // create, a self-write, or a legitimate cross-agent field like MemoryGrant's
558
755
  // granteeId — it can only narrow mutation of another agent's stored row.
559
- if (isMutation && !request.tpsAgentIsAdmin) {
560
- const guarded = resolveGuardedRecord(url.pathname);
756
+ // A Memory mutation whose raw id ends in the reserved `.content` suffix is a
757
+ // request the resource layer refuses by SHAPE (flair#2199, 400
758
+ // memory_id_content_suffix) and commits no row — Harper mutates nothing, so
759
+ // the ownership guard below must not pre-empt that with a 403 on the base row
760
+ // the `.content` property parse happens to name. Skip the guard for it and let
761
+ // the resource's named 400 answer, as it did before the routed-id resolution.
762
+ const isReservedContentMutation = isMutation &&
763
+ (routedDecisionPath === "/Memory" || routedDecisionPath.startsWith("/Memory/")) &&
764
+ decodeMemoryIdSegment(lastRawPathSegment(targetPath)).endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX);
765
+ if (isMutation && !request.tpsAgentIsAdmin && !isReservedContentMutation) {
766
+ const guarded = routed
767
+ ? resolveGuardedRecordById(routed.resource, routed.recordId)
768
+ : resolveGuardedRecord(targetPath);
561
769
  if (guarded) {
770
+ let record;
562
771
  try {
563
- const record = await databases.flair[guarded.table]?.get(guarded.id);
564
- if (isForbiddenOwnerMutation(record, guarded.ownerField, agentId)) {
565
- return ownerMutationRefusal(guarded.table);
566
- }
772
+ record = await databases.flair[guarded.table]?.get(guarded.id);
773
+ }
774
+ catch {
775
+ // The ownership read is the authorization input. A read that FAILED is
776
+ // not "no owner" and must not fall through to the resource's allow* as
777
+ // though the check passed — fail closed with a named, retryable refusal.
778
+ return ownerReadFailedRefusal(guarded.table);
779
+ }
780
+ if (isForbiddenOwnerMutation(record, guarded.ownerField, agentId)) {
781
+ return ownerMutationRefusal(guarded.table);
567
782
  }
568
- catch { /* unreadable row → fall through to the resource's own rules */ }
569
783
  }
570
784
  }
571
785
  if (isMutation) {
572
786
  // OrgEvent: authorId must match authenticated agent
573
- if ((url.pathname === "/OrgEvent" || url.pathname.startsWith("/OrgEvent/")) &&
787
+ if ((routedDecisionPath === "/OrgEvent" || routedDecisionPath.startsWith("/OrgEvent/")) &&
574
788
  (method === "POST" || method === "PUT" || method === "PATCH")) {
575
789
  if (!request.tpsAgentIsAdmin) {
576
790
  try {
@@ -591,25 +805,28 @@ server.http(async (request, nextLayer) => {
591
805
  }
592
806
  }
593
807
  // OrgEvent DELETE: ownership check
594
- if (url.pathname.startsWith("/OrgEvent/") && method === "DELETE") {
808
+ if (routedDecisionPath.startsWith("/OrgEvent/") && method === "DELETE") {
595
809
  if (!request.tpsAgentIsAdmin) {
596
- try {
597
- const pathParts = url.pathname.split("/").filter(Boolean);
598
- const eventId = pathParts[1] ? decodeURIComponent(pathParts[1]) : null;
599
- if (eventId) {
600
- const record = await databases.flair.OrgEvent.get(eventId);
601
- if (record && record.authorId && record.authorId !== agentId) {
602
- return new Response(JSON.stringify({
603
- error: "forbidden: cannot delete events authored by another agent"
604
- }), { status: 403 });
605
- }
810
+ const eventId = routed ? routed.recordId : (routedRecordId(targetPath)?.id ?? null);
811
+ if (eventId) {
812
+ let record;
813
+ try {
814
+ record = await databases.flair.OrgEvent.get(eventId);
815
+ }
816
+ catch {
817
+ // A failed read is not "no author": refuse, as the shared owner rule does.
818
+ return ownerReadFailedRefusal("OrgEvent");
819
+ }
820
+ if (record && record.authorId && record.authorId !== agentId) {
821
+ return new Response(JSON.stringify({
822
+ error: "forbidden: cannot delete events authored by another agent"
823
+ }), { status: 403 });
606
824
  }
607
825
  }
608
- catch { }
609
826
  }
610
827
  }
611
828
  // WorkspaceState: agent-scoped mutations (non-admin can only write own records)
612
- if ((url.pathname === "/WorkspaceState" || url.pathname.startsWith("/WorkspaceState/")) &&
829
+ if ((routedDecisionPath === "/WorkspaceState" || routedDecisionPath.startsWith("/WorkspaceState/")) &&
613
830
  (method === "POST" || method === "PUT" || method === "PATCH")) {
614
831
  if (!request.tpsAgentIsAdmin) {
615
832
  try {
@@ -630,21 +847,24 @@ server.http(async (request, nextLayer) => {
630
847
  }
631
848
  }
632
849
  // WorkspaceState DELETE: ownership check
633
- if ((url.pathname.startsWith("/WorkspaceState/")) && method === "DELETE") {
850
+ if ((routedDecisionPath.startsWith("/WorkspaceState/")) && method === "DELETE") {
634
851
  if (!request.tpsAgentIsAdmin) {
635
- try {
636
- const pathParts = url.pathname.split("/").filter(Boolean);
637
- const wsId = pathParts[1] ? decodeURIComponent(pathParts[1]) : null;
638
- if (wsId) {
639
- const record = await databases.flair.WorkspaceState.get(wsId);
640
- if (record && record.agentId && record.agentId !== agentId) {
641
- return new Response(JSON.stringify({
642
- error: "forbidden: cannot delete workspace state for another agent"
643
- }), { status: 403 });
644
- }
852
+ const wsId = routed ? routed.recordId : (routedRecordId(targetPath)?.id ?? null);
853
+ if (wsId) {
854
+ let record;
855
+ try {
856
+ record = await databases.flair.WorkspaceState.get(wsId);
857
+ }
858
+ catch {
859
+ // A failed read is not "no owner": refuse, as the shared owner rule does.
860
+ return ownerReadFailedRefusal("WorkspaceState");
861
+ }
862
+ if (record && record.agentId && record.agentId !== agentId) {
863
+ return new Response(JSON.stringify({
864
+ error: "forbidden: cannot delete workspace state for another agent"
865
+ }), { status: 403 });
645
866
  }
646
867
  }
647
- catch { }
648
868
  }
649
869
  }
650
870
  // Soul mutations: only the owner or an admin may write a soul entry.
@@ -679,7 +899,7 @@ server.http(async (request, nextLayer) => {
679
899
  // The path test stays `startsWith("/Soul")` so sibling routes keep the
680
900
  // body check they already had; the record lookup is scoped to the real
681
901
  // `/Soul/<id>` collection so it never resolves an unrelated id.
682
- if (url.pathname.startsWith("/Soul") &&
902
+ if (routedDecisionPath.startsWith("/Soul") &&
683
903
  (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE")) {
684
904
  if (!request.tpsAgentIsAdmin) {
685
905
  // (a) A PRESENT, mismatched body agentId is a forged attribution.
@@ -712,7 +932,7 @@ server.http(async (request, nextLayer) => {
712
932
  }
713
933
  // ── WorkspaceState read guard: agent-scoped reads ───────────────────────────
714
934
  if (method === "GET" && !request.tpsAgentIsAdmin) {
715
- if (url.pathname === "/WorkspaceState" || url.pathname === "/WorkspaceState/") {
935
+ if (routedDecisionPath === "/WorkspaceState" || routedDecisionPath === "/WorkspaceState/") {
716
936
  const queryAgent = url.searchParams.get("agentId");
717
937
  if (queryAgent && queryAgent !== agentId) {
718
938
  return new Response(JSON.stringify({
@@ -741,21 +961,40 @@ server.http(async (request, nextLayer) => {
741
961
  // contract, applied in `Memory.get`/`Memory.search`). The by-id
742
962
  // read-scope denial is enforced by the resource layer (memoryByIdReadGate),
743
963
  // 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);
964
+ // (A malformed `.content` segment was refused before any auth branch, above.)
965
+ if (!request.tpsAgentIsAdmin && (method === "GET" || method === "HEAD") && isMemoryReadPath(routedDecisionPath)) {
966
+ // flair#2199: an id segment carrying an encoded `/` before a declared
967
+ // property suffix is ambiguous — the suffix could be part of the id or a
968
+ // selector on a slash-containing id. This branch runs for a signed
969
+ // non-admin agent: Basic-admin and anonymous requests returned to the next
970
+ // layer before it.
971
+ if (isAmbiguousEncodedSlashSelector(request.url)) {
972
+ return new Response(method === "HEAD" ? null : JSON.stringify({
973
+ error: "ambiguous_memory_id",
974
+ message: `a Memory request whose id segment contains an encoded '/' before a "${MEMORY_CONTENT_SELECTOR_SUFFIX}" (or other property) suffix is refused: the suffix cannot be told from part of the id`,
975
+ }), { status: 400, headers: { "content-type": "application/json" } });
976
+ }
977
+ // The path rewrite inside stripMemorySelection runs only when Harper's own
978
+ // routing returned a Memory route with a record id. With no route (e.g. no
979
+ // live registry, no match, or a matcher error) or no record id, the path is
980
+ // left as sent; the query-selection removal does not depend on this.
981
+ const routedToMemoryRecord = routed !== null && routed.resource === "Memory" && routed.recordId !== null;
982
+ const stripped = stripMemorySelection(request.url, routedToMemoryRecord);
746
983
  if (stripped !== request.url)
747
984
  request.url = stripped;
748
985
  }
749
986
  // ── Embedding backfill ─────────────────────────────────────────────────────
750
- const isMemoryWrite = isMutation && (url.pathname === "/Memory" || url.pathname.startsWith("/Memory/"));
751
- let memoryId = null;
752
- if (isMemoryWrite) {
753
- const pathParts = url.pathname.split("/").filter(Boolean);
754
- memoryId = pathParts.length >= 2 ? decodeURIComponent(pathParts[1]) : (request.headers.get("x-memory-id") ?? null);
755
- }
987
+ const isMemoryWrite = isMutation && method !== "DELETE" &&
988
+ (routedDecisionPath === "/Memory" || routedDecisionPath.startsWith("/Memory/"));
989
+ const routedMemoryWrite = routed
990
+ ? (routed.resource === "Memory" ? routed.recordId : null)
991
+ : (() => { const r = routedRecordId(targetPath); return r?.resource === "Memory" ? r.id : null; })();
992
+ const routedCommittedId = (method === "PUT" || method === "PATCH") ? routedMemoryWrite : null;
756
993
  const response = await nextLayer(request);
757
- if (isMemoryWrite && memoryId && response.status >= 200 && response.status < 300) {
758
- backfillEmbedding(memoryId).catch(() => { });
994
+ if (isMemoryWrite && response.status >= 200 && response.status < 300) {
995
+ const committedId = committedMemoryIdFromResult(response) ?? routedCommittedId;
996
+ if (committedId)
997
+ backfillEmbedding(committedId).catch(() => { });
759
998
  }
760
999
  return response;
761
1000
  }, { runFirst: true, name: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME });