@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -9,7 +9,8 @@
9
9
  *
10
10
  * ── This handler's job ──────────────────────────────────────────────────────
11
11
  * 1. Parse the JSON-RPC request (initialize / tools/list / tools/call / ping).
12
- * 2. For tools/call: resolve `request.mcp.sub` → a flair `Agent` id via the
12
+ * 2. For tools/call: require the token's `scope` to grant the tool's scope
13
+ * (resources/mcp-tool-scopes.ts), then resolve `request.mcp.sub` → a flair `Agent` id via the
13
14
  * `Credential(kind:"idp", idpSubject=sub)` lookup, JIT-provisioning a
14
15
  * Principal+Credential the first time IF the trust anchor allows it.
15
16
  * 3. Establish the flair scoping context and invoke the tool, which delegates
@@ -27,12 +28,14 @@ import { databases } from "harper";
27
28
  import { randomBytes } from "node:crypto";
28
29
  import { TOOLS, listToolDefs } from "./mcp-tools.js";
29
30
  import { checkToolArguments, withoutNullArguments } from "./mcp-tool-arguments.js";
31
+ import { challengeScope, grantedScopes, requiredToolScope } from "./mcp-tool-scopes.js";
30
32
  import { agentRecordIsAdmin } from "./agent-admin.js";
31
33
  import { isPrincipalDeactivated } from "./agent-auth.js";
32
34
  import { stampOriginatorOnCreate } from "./originator-instance.js";
33
35
  import { invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
34
36
  import { credentialMapsPrincipal, credentialPrincipalId, credentialRefusal } from "../src/lib/credential-status-rule.js";
35
37
  import { resolveVersion } from "./version.js";
38
+ import { TEST_FAULT_INJECTION_ENV } from "./txn-pause-point.js";
36
39
  // The MCP protocol revision we implement (initialize handshake).
37
40
  const PROTOCOL_VERSION = "2025-06-18";
38
41
  // ─── Body size cap ───────────────────────────────────────────────────────────
@@ -130,6 +133,54 @@ function rpcError(id, code, message, httpStatus = 200) {
130
133
  };
131
134
  }
132
135
  // ─── sub → Agent resolution ─────────────────────────────────────────────────
136
+ // Test-only read failures (flair#2794): the `Credential(kind:"idp",
137
+ // idpSubject=sub)` lookup and the mapped principal's `Agent` read, each failing
138
+ // for a token subject that contains its setting's value. A setting is read only
139
+ // when FLAIR_ENABLE_TEST_FAULT_INJECTION=1 (resources/txn-pause-point.ts), and
140
+ // each matching subject fails once, so the request after the failing one is
141
+ // answered normally. Nothing in a request can arm either hook.
142
+ //
143
+ // flair#2799 — the fired-subject state is process-lifetime: it lives here for as
144
+ // long as the server process does and never resets between requests. It holds
145
+ // at most TEST_READ_FAILURE_FIRED_LIMIT (setting, subject) pairs so that a
146
+ // long-lived process driven with many distinct subjects stops arming new faults
147
+ // instead of growing without limit. Once the set is full, the hook answers false
148
+ // (no fault) for every further pair and logs that once. An empty setting value
149
+ // is inert: it matches nothing and is never added to the set.
150
+ const TEST_CREDENTIAL_READ_FAIL_SUB_ENV = "FLAIR_TEST_MCP_CREDENTIAL_READ_FAIL_SUB";
151
+ const TEST_PRINCIPAL_READ_FAIL_SUB_ENV = "FLAIR_TEST_MCP_PRINCIPAL_READ_FAIL_SUB";
152
+ export const TEST_READ_FAILURE_FIRED_LIMIT = 1024;
153
+ const testReadFailuresFired = new Set();
154
+ let testReadFailuresFullLogged = false;
155
+ /**
156
+ * Should this subject's read fail once? Test-only; false unless
157
+ * FLAIR_ENABLE_TEST_FAULT_INJECTION=1 and the setting names a non-empty value
158
+ * the subject contains. Exported for the fired-state bound's unit test.
159
+ */
160
+ export function testReadFailure(setting, sub) {
161
+ if (process.env[TEST_FAULT_INJECTION_ENV] !== "1")
162
+ return false;
163
+ const match = process.env[setting];
164
+ if (!match || !sub.includes(match))
165
+ return false;
166
+ const key = `${setting}\n${sub}`;
167
+ if (testReadFailuresFired.has(key))
168
+ return false;
169
+ if (testReadFailuresFired.size >= TEST_READ_FAILURE_FIRED_LIMIT) {
170
+ if (!testReadFailuresFullLogged) {
171
+ testReadFailuresFullLogged = true;
172
+ console.warn(`[flair] test-only read-failure hook fired state reached its ${TEST_READ_FAILURE_FIRED_LIMIT}-pair limit; ` +
173
+ "no further test read failures will be injected in this process.");
174
+ }
175
+ return false;
176
+ }
177
+ testReadFailuresFired.add(key);
178
+ return true;
179
+ }
180
+ /** The fired-subject set's current size. Exported for the bound's unit test. */
181
+ export function testReadFailureFiredCount() {
182
+ return testReadFailuresFired.size;
183
+ }
133
184
  /**
134
185
  * Should an unknown IdP subject be JIT-provisioned into a new Principal+
135
186
  * Credential? Gated by an explicit, auditable trust anchor — an OPEN JIT-provision
@@ -163,6 +214,10 @@ function jitProvisionEnabled() {
163
214
  * `undefined` — so existing callers/tests that don't pass one see the exact
164
215
  * same `{ agentId, isAdmin }` shape as before this field existed.
165
216
  *
217
+ * `allowJitProvision` (default true) is false for a read-only caller such as
218
+ * `tools/list`: a subject with no matching credential resolves to null instead
219
+ * of creating a principal.
220
+ *
166
221
  * When a Credential maps the sub, the mapped principal must exist and be
167
222
  * active — the rule the Ed25519 path applies (resources/agent-auth.ts,
168
223
  * `isPrincipalDeactivated`) — and its record is read on every resolution, so a
@@ -190,10 +245,10 @@ function jitProvisionEnabled() {
190
245
  * the mapped principal is deactivated or missing, or when the credential or
191
246
  * principal could not be read.
192
247
  */
193
- export async function resolveAgentFromSub(sub, clientId) {
194
- return (await resolveMapping(sub, clientId))?.agent ?? null;
248
+ export async function resolveAgentFromSub(sub, clientId, allowJitProvision = true) {
249
+ return (await resolveMapping(sub, clientId, allowJitProvision))?.agent ?? null;
195
250
  }
196
- async function resolveMapping(sub, clientId) {
251
+ async function resolveMapping(sub, clientId, allowJitProvision = true) {
197
252
  if (!sub)
198
253
  return null;
199
254
  // 1. Existing IdP credential → its principalId is the Agent id.
@@ -208,6 +263,9 @@ async function resolveMapping(sub, clientId) {
208
263
  let mapped = null;
209
264
  let refused = null;
210
265
  try {
266
+ if (testReadFailure(TEST_CREDENTIAL_READ_FAIL_SUB_ENV, sub)) {
267
+ throw new Error("test-only fault: the IdP credential read failed");
268
+ }
211
269
  for await (const cred of databases.flair.Credential.search({
212
270
  conditions: [
213
271
  { attribute: "kind", comparator: "equals", value: "idp" },
@@ -228,7 +286,7 @@ async function resolveMapping(sub, clientId) {
228
286
  }
229
287
  if (mapped) {
230
288
  const principalId = credentialPrincipalId(mapped);
231
- const principal = await requireActivePrincipal(principalId);
289
+ const principal = await requireActivePrincipal(principalId, sub);
232
290
  const resolved = { agentId: principalId, isAdmin: agentRecordIsAdmin(principal) };
233
291
  if (clientId)
234
292
  resolved.clientId = clientId;
@@ -238,8 +296,10 @@ async function resolveMapping(sub, clientId) {
238
296
  throw new PrincipalRefusedError(-32001, credentialRefusal(`the IdP credential for this token's subject (id '${refused.id}')`, refused));
239
297
  }
240
298
  // 2. No matching Credential(kind:"idp", idpSubject:sub) row. JIT-provision
241
- // only behind the explicit trust anchor.
242
- if (!jitProvisionEnabled())
299
+ // only behind the explicit trust anchor, and only for a caller that may
300
+ // create a principal — `tools/list` passes allowJitProvision:false, since
301
+ // a listing must not write.
302
+ if (!allowJitProvision || !jitProvisionEnabled())
243
303
  return null;
244
304
  try {
245
305
  const { principalId, credential } = await jitProvisionPrincipal(sub);
@@ -328,9 +388,12 @@ export class PrincipalRefusedError extends Error {
328
388
  * never elevates on its own. This surface is gated behind FLAIR_MCP_OAUTH and is
329
389
  * default-OFF.
330
390
  */
331
- async function requireActivePrincipal(principalId) {
391
+ async function requireActivePrincipal(principalId, sub = "") {
332
392
  let principal;
333
393
  try {
394
+ if (testReadFailure(TEST_PRINCIPAL_READ_FAIL_SUB_ENV, sub)) {
395
+ throw new Error("test-only fault: the principal read failed");
396
+ }
334
397
  principal = await databases.flair.Agent.get(principalId);
335
398
  }
336
399
  catch {
@@ -395,13 +458,49 @@ export async function mcpHandler(request) {
395
458
  case "ping":
396
459
  return rpcResult(id, {});
397
460
  case "tools/list":
398
- return rpcResult(id, { tools: listToolDefs() });
461
+ return handleToolsList(request, id);
399
462
  case "tools/call":
400
463
  return handleToolCall(request, id, params);
401
464
  default:
402
465
  return rpcError(id, -32601, `method not found: ${rpcMethod}`);
403
466
  }
404
467
  }
468
+ /**
469
+ * tools/list: the tools advertised to this request's caller. The caller is
470
+ * resolved the way handleToolCall resolves it (same sub lookup, same
471
+ * active-principal rule), except that listing never JIT-provisions: for a
472
+ * mapped subject each tool's `tools/list` gate is decided for the agent the
473
+ * call would run as, while an unmapped subject lists with no principal even
474
+ * when JIT provisioning is on (a call by it may provision one), and gets no
475
+ * gated tool. A resolution that fails or is refused is answered with the
476
+ * JSON-RPC error a tools/call of a known tool by the same caller gets, and no
477
+ * list (flair#2760).
478
+ *
479
+ * JIT provisioning is off here: a listing is a read and must not create a
480
+ * principal.
481
+ */
482
+ async function handleToolsList(request, id) {
483
+ const clientId = typeof request?.mcp?.client_id === "string" ? request.mcp.client_id : undefined;
484
+ let agent;
485
+ try {
486
+ agent = await resolveAgentFromSub(String(request?.mcp?.sub ?? ""), clientId, false);
487
+ }
488
+ catch (err) {
489
+ return resolutionFailure(id, err);
490
+ }
491
+ return rpcResult(id, { tools: await listToolDefs(agent) });
492
+ }
493
+ /**
494
+ * The JSON-RPC error for a caller whose token subject could not be resolved to
495
+ * a principal: a refusal's own code and message, otherwise a generic
496
+ * `unavailable` error. tools/list and tools/call both answer with it.
497
+ */
498
+ function resolutionFailure(id, err) {
499
+ if (err instanceof PrincipalRefusedError)
500
+ return rpcError(id, err.rpcCode, err.message);
501
+ return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
502
+ "Retry; if this persists, an operator should check the flair server log.");
503
+ }
405
504
  /**
406
505
  * tools/call: resolve the token sub → flair Agent, then dispatch to the curated
407
506
  * tool. An unresolvable sub is DENIED (not silently run as anonymous or admin).
@@ -419,6 +518,17 @@ async function handleToolCall(request, id, params) {
419
518
  if (!sub) {
420
519
  return rpcError(id, -32001, "unauthorized: no verified token subject");
421
520
  }
521
+ // flair#3076: the token's granted scope must include the scope this tool
522
+ // requires. Checked before the subject is resolved, so a refused call reads
523
+ // no credential and provisions no principal.
524
+ const required = requiredToolScope(toolName);
525
+ if (required === undefined) {
526
+ return rpcError(id, -32602, `unknown tool: ${toolName}`);
527
+ }
528
+ const granted = grantedScopes(request?.mcp?.scope);
529
+ if (!granted.includes(required)) {
530
+ return insufficientScope(id, toolName, required, granted);
531
+ }
422
532
  // flair#718 authorship-provenance, Sherlock's binding refinement: source
423
533
  // the authorship stamp from `client_id` (the server-generated
424
534
  // `flair_cl_...` machine id — resources/OAuth.ts, an RS256-verified JWT
@@ -437,10 +547,7 @@ async function handleToolCall(request, id, params) {
437
547
  mapping = await resolveMapping(String(sub), clientId);
438
548
  }
439
549
  catch (err) {
440
- if (err instanceof PrincipalRefusedError)
441
- return rpcError(id, err.rpcCode, err.message);
442
- return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
443
- "Retry; if this persists, an operator should check the flair server log.");
550
+ return resolutionFailure(id, err);
444
551
  }
445
552
  if (!mapping) {
446
553
  // Sub verified by the AS but not mapped to a flair Agent (and JIT disabled /
@@ -481,6 +588,32 @@ async function handleToolCall(request, id, params) {
481
588
  isError,
482
589
  });
483
590
  }
591
+ /**
592
+ * flair#3076: the answer to a tools/call whose token does not grant the tool's
593
+ * scope. HTTP 403 with a Bearer `insufficient_scope` challenge whose `scope` is
594
+ * challengeScope(), and a JSON-RPC error naming the tool and the scope it
595
+ * requires.
596
+ */
597
+ function insufficientScope(id, tool, required, granted) {
598
+ return {
599
+ status: 403,
600
+ headers: {
601
+ ...JSON_HEADERS,
602
+ "WWW-Authenticate": `Bearer error="insufficient_scope", scope="${challengeScope(granted, required)}"`,
603
+ "Access-Control-Allow-Origin": "*",
604
+ "Access-Control-Expose-Headers": "WWW-Authenticate",
605
+ },
606
+ body: JSON.stringify({
607
+ jsonrpc: "2.0",
608
+ id: id ?? null,
609
+ error: {
610
+ code: -32001,
611
+ message: `insufficient_scope: ${tool} requires the '${required}' scope, which this access token does not grant. ` +
612
+ "Obtain a token that grants it; the WWW-Authenticate header names the scopes to request.",
613
+ },
614
+ }),
615
+ };
616
+ }
484
617
  /**
485
618
  * Mark the mapping credential used, once a tool has run (best-effort). The
486
619
  * update writes `lastUsedAt` alone, as a field-level patch from an internal
@@ -29,17 +29,17 @@
29
29
  * Read from `FLAIR_MCP_OAUTH` — truthy values: "1", "true", "yes", "on"
30
30
  * (case-insensitive). Anything else (incl. unset / empty) → OFF.
31
31
  *
32
- * ASYMMETRY (load-bearing, flair#1152, measured on oauth 2.5.0): config.yaml's
33
- * `mcp.enabled: ${FLAIR_MCP_OAUTH}` hands the SAME env var to
32
+ * ASYMMETRY (load-bearing, flair#1152, measured on @harperfast/oauth 2.9.0):
33
+ * config.yaml's `mcp.enabled: ${FLAIR_MCP_OAUTH}` hands the SAME env var to
34
34
  * @harperfast/oauth, but the two readers accept DIFFERENT vocabularies. The
35
- * component's coerceConfigBoolean takes ONLY "true"/"false" and DELETES any
36
- * other string (unresolved placeholder, "1", "yes", garbage) so its disabled
37
- * default applies; this function takes 1/true/yes/on. Consequences:
38
- * - "true" is the ONE value that enables both sides (`flair mcp enable`
39
- * stages exactly that).
40
- * - "1"/"yes"/"on" turn flair's /mcp handler ON while the component AS
41
- * stays OFF — fail-closed broken-on (every request 401s, no AS
42
- * advertised).
35
+ * component's coerceConfigBoolean trims and lowercases, mapping "true"/"false"
36
+ * to a boolean, and normalizeBooleanField deletes strings it cannot coerce
37
+ * (unresolved placeholder, "1", "yes", garbage), so its disabled default
38
+ * applies (dist/lib/config.js); this function takes 1/true/yes/on.
39
+ * Consequences:
40
+ * - "true" is accepted by both readers.
41
+ * - "1"/"yes"/"on" make this reader true while the component deletes the
42
+ * value and stays off; /mcp is not mounted.
43
43
  * - garbage (e.g. "maybe") disables BOTH: the component deletes it, this
44
44
  * stays false, no /mcp handler exists — no data path (flair's own
45
45
  * discovery documents still serve whenever this flag is off, by design).
@@ -60,12 +60,10 @@ export function mcpOAuthEnabled() {
60
60
  * the client-controlled Host header) is the audience-confusion defense called
61
61
  * out in the plugin's production checklist.
62
62
  *
63
- * Configurable via `FLAIR_MCP_ISSUER` (fall back to `FLAIR_PUBLIC_URL`, which the
64
- * XAA token path already uses as the canonical public base). No hardcoded
65
- * default — an operator turning the flag on MUST set the public origin.
63
+ * Configured via `FLAIR_MCP_ISSUER`.
66
64
  */
67
65
  export function mcpIssuer() {
68
- const raw = (process.env.FLAIR_MCP_ISSUER ?? process.env.FLAIR_PUBLIC_URL ?? "").trim();
66
+ const raw = (process.env.FLAIR_MCP_ISSUER ?? "").trim();
69
67
  return raw || undefined;
70
68
  }
71
69
  /**