@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
@@ -16,7 +16,7 @@
16
16
  * docs). The plugin serves DCR / authorize / token / JWKS / discovery.
17
17
  */
18
18
  import * as harper from "harper";
19
- import { mcpOAuthEnabled, mcpAuthConfig } from "./mcp-oauth-flag.js";
19
+ import { mcpOAuthEnabled, mcpAuthConfig, mcpIssuer } from "./mcp-oauth-flag.js";
20
20
  // flair#2270: run the degraded-start guard BEFORE the @harperfast/oauth
21
21
  // component resolves its config. Imported for its module-load side effect (this
22
22
  // module is itself loaded during jsResource boot, ahead of the component);
@@ -24,45 +24,378 @@ import { mcpOAuthEnabled, mcpAuthConfig } from "./mcp-oauth-flag.js";
24
24
  import { mcpOAuthDegraded } from "./mcp-oauth-env-guard.js";
25
25
  import { checkMcpRateLimit } from "./rate-limit.js";
26
26
  import { MULTI_WORKER_GUARD_HTTP_NAME } from "./multi-worker-guard.js";
27
+ import { MCP_REQUESTED_SCOPES } from "./mcp-tool-scopes.js";
27
28
  /**
28
- * Boot guard (flair#1021): when FLAIR_MCP_OAUTH is on, the @harperfast/oauth
29
- * component MUST be declared in config.yaml. Without it the authorization
30
- * server's routes never mount — discovery, authorize, token, JWKS all 404.
31
- * The /mcp route would still register, but every request fails closed against
32
- * a non-existent auth server. This guard fails loudly so the operator sees the
33
- * error at boot instead of a silently broken deployment.
29
+ * Boot guard (flair#1021, flair#1322), after the flag and degraded-start checks.
34
30
  *
35
- * The error names the actor (the operator who set the flag), the state
36
- * (component absent from config.yaml), and the remedy (add the declaration).
37
- * It does NOT suggest a concrete issuer — the issuer is derived at runtime
38
- * from FLAIR_MCP_ISSUER / FLAIR_PUBLIC_URL and must not be hardcoded.
31
+ * The `@harperfast/oauth` component must be declared, and its effective
32
+ * `mcp.enabled` must be true. Effective means the component's own read:
33
+ * whole-token `${VAR}` expansion, then `true`/`false` only. Any other string
34
+ * (`1`, `yes`, `on`, an unresolved placeholder, garbage) is deleted and the
35
+ * disabled default applies. Key presence is not that state — the block ships
36
+ * in config.yaml, so a pre-0.46 `FLAIR_MCP_OAUTH=1` used to mount `/mcp` while
37
+ * the authorization server stayed off.
38
+ *
39
+ * A config read that throws, or that returns an empty or unreadable body,
40
+ * refuses. That result is not a missing component and it is not success.
41
+ *
42
+ * When the two readers disagree, the error names `true` (the recommended
43
+ * setting, which both accept) and the remedy. It does not hardcode an issuer URL.
44
+ */
45
+ const OAUTH_COMPONENT_KEY = "@harperfast/oauth";
46
+ // Mirrors withMCPAuth denial CORS headers in @harperfast/oauth 2.9.0.
47
+ const MCP_DENIAL_CORS_HEADERS = {
48
+ "Access-Control-Allow-Origin": "*",
49
+ "Access-Control-Expose-Headers": "WWW-Authenticate",
50
+ };
51
+ /**
52
+ * A plain record in this realm or another. Harper runs this module in a VM,
53
+ * so `config` can be a host-realm object whose prototype is not this realm's
54
+ * `Object.prototype`.
55
+ */
56
+ function isRecord(value) {
57
+ try {
58
+ if (value == null || typeof value !== "object" || Array.isArray(value))
59
+ return false;
60
+ const proto = Object.getPrototypeOf(value);
61
+ if (proto === null)
62
+ return true;
63
+ // `Object.prototype` in any realm: its prototype is null, and it is that
64
+ // realm's `Object` constructor's prototype. Class instances sit one step
65
+ // further out and are not records.
66
+ if (Object.getPrototypeOf(proto) !== null)
67
+ return false;
68
+ const ctor = proto.constructor;
69
+ return typeof ctor === "function" && ctor.prototype === proto;
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ /** `@harperfast/oauth` `expandEnvVar`: whole-token `${NAME}` only. */
76
+ function expandWholeTokenEnv(value) {
77
+ if (typeof value !== "string" || !value.startsWith("${") || !value.endsWith("}"))
78
+ return value;
79
+ const envValue = process.env[value.slice(2, -1)];
80
+ return envValue !== undefined ? envValue : value;
81
+ }
82
+ function readOAuthComponent(harperNs) {
83
+ let hc;
84
+ try {
85
+ const h = harperNs ?? harper;
86
+ hc = h?.app?.config ?? h?.config;
87
+ }
88
+ catch {
89
+ return { kind: "unreadable", detail: "config lookup failed" };
90
+ }
91
+ if (!isRecord(hc)) {
92
+ return { kind: "unreadable", detail: "application config is missing or unreadable" };
93
+ }
94
+ let keyCount = 0;
95
+ let readableGet = false;
96
+ try {
97
+ keyCount = Object.keys(hc).length;
98
+ readableGet = typeof hc.get === "function";
99
+ }
100
+ catch {
101
+ return { kind: "unreadable", detail: "application config is unreadable" };
102
+ }
103
+ // `{}` is unreadable: a missing document can arrive as an empty object.
104
+ // A get-backed config may have no enumerable keys and still hold the component.
105
+ if (keyCount === 0 && !readableGet) {
106
+ return { kind: "unreadable", detail: "application config is empty" };
107
+ }
108
+ let component;
109
+ try {
110
+ if (typeof hc.get === "function")
111
+ component = hc.get(OAUTH_COMPONENT_KEY);
112
+ }
113
+ catch {
114
+ return { kind: "unreadable", detail: "config lookup failed" };
115
+ }
116
+ if (component == null) {
117
+ try {
118
+ component = hc[OAUTH_COMPONENT_KEY];
119
+ }
120
+ catch {
121
+ return { kind: "unreadable", detail: "config lookup failed" };
122
+ }
123
+ }
124
+ if (component == null)
125
+ return { kind: "absent" };
126
+ if (!isRecord(component)) {
127
+ return { kind: "unreadable", detail: "component entry is not an object" };
128
+ }
129
+ return { kind: "present", component };
130
+ }
131
+ /**
132
+ * The component's effective `mcp.enabled` after `coerceConfigBoolean`.
133
+ * Omitted, null, or a deleted non-boolean string is the disabled default.
134
+ */
135
+ export function readEffectiveMcpEnabled(component) {
136
+ try {
137
+ if (!Object.prototype.hasOwnProperty.call(component, "mcp") || component.mcp == null) {
138
+ return { kind: "bool", enabled: false, configured: undefined };
139
+ }
140
+ if (!isRecord(component.mcp)) {
141
+ return { kind: "unreadable", detail: "mcp entry is not an object" };
142
+ }
143
+ if (!Object.prototype.hasOwnProperty.call(component.mcp, "enabled") || component.mcp.enabled === undefined) {
144
+ return { kind: "bool", enabled: false, configured: undefined };
145
+ }
146
+ const configured = component.mcp.enabled;
147
+ if (configured === null)
148
+ return { kind: "bool", enabled: false, configured };
149
+ const expanded = expandWholeTokenEnv(configured);
150
+ if (typeof expanded === "boolean")
151
+ return { kind: "bool", enabled: expanded, configured };
152
+ if (typeof expanded === "string") {
153
+ const v = expanded.trim().toLowerCase();
154
+ if (v === "true")
155
+ return { kind: "bool", enabled: true, configured };
156
+ if (v === "false")
157
+ return { kind: "bool", enabled: false, configured };
158
+ return { kind: "bool", enabled: false, configured };
159
+ }
160
+ return { kind: "unreadable", detail: "mcp.enabled is not a boolean or string" };
161
+ }
162
+ catch {
163
+ return { kind: "unreadable", detail: "mcp config lookup failed" };
164
+ }
165
+ }
166
+ function unreadableConfigError(detail) {
167
+ return new Error("FLAIR_MCP_OAUTH is enabled but the @harperfast/oauth configuration could not be read (" +
168
+ detail +
169
+ "). Refusing to mount /mcp. " +
170
+ 'Remedy: make config.yaml\'s "@harperfast/oauth" entry a readable object, ' +
171
+ "with mcp.enabled set to true or to ${FLAIR_MCP_OAUTH}, and set FLAIR_MCP_OAUTH=true.");
172
+ }
173
+ function componentAbsentError() {
174
+ return new Error("FLAIR_MCP_OAUTH is enabled but the @harperfast/oauth component is not declared in config.yaml. " +
175
+ "The authorization server cannot start without it — discovery, authorize, token, and JWKS endpoints will all 404.\n" +
176
+ 'Restore the complete "@harperfast/oauth" entry from the config.yaml that ships with this Flair version. ' +
177
+ "This is a PARTIAL declaration of that entry; it leaves out the providers block:\n" +
178
+ "\n" +
179
+ ' "@harperfast/oauth":\n' +
180
+ ' package: "@harperfast/oauth"\n' +
181
+ " mcp:\n" +
182
+ " enabled: ${FLAIR_MCP_OAUTH}\n" +
183
+ " issuer: ${FLAIR_MCP_ISSUER}\n" +
184
+ "\n" +
185
+ "This alone does not start the authorization server: the component also needs at least one provider " +
186
+ "with its client ID, client secret and redirect URI set (the shipped entry configures github through " +
187
+ "OAUTH_GITHUB_CLIENT_ID, OAUTH_GITHUB_CLIENT_SECRET and OAUTH_GITHUB_REDIRECT_URI). " +
188
+ "Then set FLAIR_MCP_OAUTH=true and set FLAIR_MCP_ISSUER to this instance's public origin.");
189
+ }
190
+ function boundedConfigValue(value) {
191
+ return JSON.stringify(value.length > 64 ? `${value.slice(0, 64)}…` : value);
192
+ }
193
+ function disagreementError(rawEnv, configured) {
194
+ const base = `FLAIR_MCP_OAUTH is ${boundedConfigValue(rawEnv)}, which Flair treats as enabled, ` +
195
+ "but the @harperfast/oauth component's effective mcp.enabled is not true. " +
196
+ "Use true, the recommended value; both readers accept it.";
197
+ const isEnvRef = configured === "${FLAIR_MCP_OAUTH}";
198
+ const remedy = isEnvRef ? "Set FLAIR_MCP_OAUTH=true." : "Set mcp.enabled to true.";
199
+ return new Error(`${base} ${remedy}`);
200
+ }
201
+ function issuerUnreadableError(phase = "mount") {
202
+ return new Error("mcp.issuer could not be read. Set FLAIR_MCP_ISSUER to an absolute http(s) origin " +
203
+ "and set mcp.issuer to ${FLAIR_MCP_ISSUER}. Refusing to " + phase + " /mcp.");
204
+ }
205
+ /**
206
+ * FLAIR_MCP_ISSUER is unset or blank at request time. That is its own fault,
207
+ * not an unreadable component value: withMCPAuth verifies tokens against this
208
+ * variable, so without it a request has nothing to check against, whether or
209
+ * not the live config is readable.
210
+ */
211
+ function issuerEnvMissingError() {
212
+ return new Error("FLAIR_MCP_ISSUER is unset or blank, so a /mcp request cannot be checked against " +
213
+ "the authorization server's issuer. Refusing to serve /mcp. " +
214
+ "Set FLAIR_MCP_ISSUER to this instance's public origin.");
215
+ }
216
+ function liveMcpConfigUnreadableError() {
217
+ return new Error("The live @harperfast/oauth MCP configuration could not be verified. Refusing to serve /mcp. " +
218
+ "Inspect the registered @harperfast/oauth component and ensure its mcp settings are a plain mapping " +
219
+ "with enabled and issuer.");
220
+ }
221
+ /**
222
+ * The live @harperfast/oauth MCP config is absent, or present with
223
+ * `enabled !== true`: the authorization server cannot mint a token for this
224
+ * surface, and the per-request check refuses every /mcp request as
225
+ * unavailable (503) before withMCPAuth runs. Absent is also what a
226
+ * component with no valid provider leaves behind, so the remedy names one.
227
+ */
228
+ function mcpAuthUnavailableError() {
229
+ return new Error("The @harperfast/oauth component is not serving an MCP authorization configuration " +
230
+ "(its live mcpConfig is absent or disabled). Refusing to serve /mcp. " +
231
+ "Configure a valid OAuth provider for the component — its client ID, client secret " +
232
+ "and redirect URI — and set FLAIR_MCP_OAUTH=true and FLAIR_MCP_ISSUER to this " +
233
+ "instance's public origin, with mcp.enabled true and mcp.issuer set to " +
234
+ "${FLAIR_MCP_ISSUER}, then restart.");
235
+ }
236
+ /**
237
+ * The boot guard's issuer rule, over one candidate value: the failed rule, or
238
+ * undefined when the value is a canonical origin that also matches
239
+ * FLAIR_MCP_ISSUER after the trailing-slash trim. A valid origin returns
240
+ * undefined when FLAIR_MCP_ISSUER is unset — the rule cannot compare against an
241
+ * absent reference — so the request-time check refuses an unset issuer before
242
+ * calling this. flair#3032: the per-request check below holds this same rule
243
+ * against the authorization server's live issuer, so the two checks cannot
244
+ * drift apart.
39
245
  */
246
+ function issuerFailedRule(issuer) {
247
+ let failedRule;
248
+ // new URL() removes ASCII tab, LF and CR anywhere and trims C0 controls
249
+ // and spaces at the ends; other embedded C0 controls or spaces in a host throw.
250
+ // Refuse whitespace and controls anyway: the component keeps the raw issuer.
251
+ if (typeof issuer !== "string")
252
+ return "not a string";
253
+ if (/[\u0000-\u0020\u007F]/.test(issuer))
254
+ return "has whitespace or control characters";
255
+ try {
256
+ const parsedIssuer = new URL(issuer);
257
+ const pathWithoutTrailingSlash = parsedIssuer.pathname.replace(/\/+$/, "");
258
+ if (parsedIssuer.protocol !== "http:" && parsedIssuer.protocol !== "https:")
259
+ failedRule = "not http/https";
260
+ else if (pathWithoutTrailingSlash !== "")
261
+ failedRule = "has a path";
262
+ // Stricter than @harperfast/oauth 2.9.0 on purpose: an empty `?` or `#` leaves
263
+ // URL.search/hash empty, so the component accepts it, then prefixes every endpoint
264
+ // with the raw value (`https://host?/oauth/mcp/token`). Refuse any raw delimiter.
265
+ else if (parsedIssuer.search !== "" || parsedIssuer.hash !== "" || /[?#]/.test(issuer))
266
+ failedRule = "has a query/hash";
267
+ else if (parsedIssuer.username !== "" || parsedIssuer.password !== "")
268
+ failedRule = "has userinfo";
269
+ else if (issuer.replace(/\/+$/, "") !== parsedIssuer.origin)
270
+ failedRule = "not in canonical origin form";
271
+ // flair#3032: the authorization server mints tokens for THIS value, while
272
+ // withMCPAuth verifies them against mcpIssuer(). A literal that disagrees
273
+ // with FLAIR_MCP_ISSUER mounts /mcp with tokens that cannot verify there.
274
+ else {
275
+ const envIssuer = mcpIssuer();
276
+ if (envIssuer !== undefined && issuer.replace(/\/+$/, "") !== envIssuer.replace(/\/+$/, "")) {
277
+ failedRule = "differs from FLAIR_MCP_ISSUER";
278
+ }
279
+ else
280
+ return undefined;
281
+ }
282
+ }
283
+ catch {
284
+ failedRule = "not absolute";
285
+ }
286
+ return failedRule;
287
+ }
288
+ function issuerRefusalError(configured, failedRule, phase = "mount") {
289
+ const envName = typeof configured === "string" && configured.startsWith("${") && configured.endsWith("}")
290
+ ? configured.slice(2, -1) : undefined;
291
+ const detail = envName === undefined ? ` (${failedRule})`
292
+ : process.env[envName] === undefined ? ` (environment variable ${JSON.stringify(envName)} is unset)`
293
+ : ` (environment variable ${JSON.stringify(envName)} value fails the rule: ${failedRule})`;
294
+ if (failedRule === "differs from FLAIR_MCP_ISSUER") {
295
+ return new Error("The @harperfast/oauth component's mcp.issuer is a valid absolute http(s) origin" + detail +
296
+ ", but withMCPAuth verifies tokens against FLAIR_MCP_ISSUER, so the tokens the component mints cannot verify here. " +
297
+ `Refusing to ${phase} /mcp. Set FLAIR_MCP_ISSUER and mcp.issuer to the same public origin, ` +
298
+ "or set mcp.issuer to ${FLAIR_MCP_ISSUER}.");
299
+ }
300
+ return new Error("The @harperfast/oauth component's mcp.issuer must be an absolute http(s) origin" + detail +
301
+ `. Refusing to ${phase} /mcp. Set FLAIR_MCP_ISSUER to an absolute http(s) origin ` +
302
+ "without a path, query, fragment or userinfo, written as scheme://host[:port] with a lowercase host, " +
303
+ "no default port, and at most a trailing slash, and set mcp.issuer to ${FLAIR_MCP_ISSUER}.");
304
+ }
305
+ function assertEffectiveMcpIssuer(component) {
306
+ let configured;
307
+ let issuer;
308
+ try {
309
+ configured = component.mcp.issuer;
310
+ issuer = expandWholeTokenEnv(configured);
311
+ }
312
+ catch {
313
+ throw issuerUnreadableError();
314
+ }
315
+ const failedRule = issuerFailedRule(issuer);
316
+ if (failedRule !== undefined)
317
+ throw issuerRefusalError(configured, failedRule);
318
+ }
319
+ function readLiveMcpConfig(harperNs) {
320
+ let config;
321
+ try {
322
+ config = (harperNs ?? harper).server?.resources?.get("oauth")?.Resource?.mcpConfig;
323
+ }
324
+ catch {
325
+ return { kind: "unreadable" };
326
+ }
327
+ // No live MCP config means the component is not serving an authorization
328
+ // server for this surface at all: the per-request check refuses it as
329
+ // unavailable (503), and getConfig returns undefined for it.
330
+ if (config == null)
331
+ return { kind: "absent" };
332
+ if (!isRecord(config))
333
+ return { kind: "unreadable" };
334
+ return { kind: "present", config };
335
+ }
336
+ function checkLiveMcpConfig(harperNs) {
337
+ const unavailable = (reason) => ({
338
+ kind: "refused",
339
+ code: "mcp_auth_unavailable",
340
+ status: "MCP auth unavailable",
341
+ reason,
342
+ });
343
+ // withMCPAuth verifies against FLAIR_MCP_ISSUER; without it at request time
344
+ // there is no comparison to hold, so this is a refusal, never a skip. It is
345
+ // not a component read failure, so it gets its own message.
346
+ if (mcpIssuer() === undefined)
347
+ return unavailable(issuerEnvMissingError().message);
348
+ const read = readLiveMcpConfig(harperNs);
349
+ if (read.kind === "unreadable")
350
+ return unavailable(liveMcpConfigUnreadableError().message);
351
+ // No live config, or a disabled one, cannot mint a token for this surface.
352
+ if (read.kind === "absent")
353
+ return unavailable(mcpAuthUnavailableError().message);
354
+ let enabled;
355
+ let issuer;
356
+ try {
357
+ enabled = read.config.enabled;
358
+ }
359
+ catch {
360
+ return unavailable(liveMcpConfigUnreadableError().message);
361
+ }
362
+ if (enabled !== true)
363
+ return unavailable(mcpAuthUnavailableError().message);
364
+ try {
365
+ issuer = read.config.issuer;
366
+ }
367
+ catch {
368
+ return unavailable(issuerUnreadableError("serve").message);
369
+ }
370
+ if (issuer === undefined || issuer === null)
371
+ return unavailable(issuerUnreadableError("serve").message);
372
+ const failedRule = issuerFailedRule(issuer);
373
+ if (failedRule === undefined)
374
+ return { kind: "served" };
375
+ return {
376
+ kind: "refused",
377
+ code: "mcp_issuer_refused",
378
+ status: "Issuer refused",
379
+ // No configured value: the live issuer never belongs in the response or
380
+ // the log, so the refusal names only the rule and the remedy.
381
+ reason: issuerRefusalError(undefined, failedRule, "serve").message,
382
+ };
383
+ }
40
384
  export function assertHarperOAuthComponentDeclared(harperNs) {
41
- // Harper exposes parsed config via its runtime namespace. We check for the
42
- // @harperfast/oauth key; absence means the component's routes were never
43
- // registered.
44
- const h = harperNs ?? harper;
45
- const hc = h.app?.config ?? h.config;
46
- const component = hc?.get?.("@harperfast/oauth") ?? hc?.["@harperfast/oauth"];
47
- if (!component) {
48
- throw new Error("FLAIR_MCP_OAUTH is enabled but the @harperfast/oauth component is not declared in config.yaml. " +
49
- "The authorization server cannot start without it — discovery, authorize, token, and JWKS endpoints will all 404, " +
50
- "and /mcp will reject every request.\n" +
51
- "Add this entry to your config.yaml:\n" +
52
- "\n" +
53
- ' "@harperfast/oauth":\n' +
54
- " providers:\n" +
55
- ' default:\n' +
56
- ' authorizationEndpoint: "/OAuthAuthorize"\n' +
57
- ' tokenEndpoint: "/OAuthToken"\n' +
58
- ' revocationEndpoint: "/OAuthRevoke"\n' +
59
- ' registrationEndpoint: "/OAuthRegister"\n' +
60
- ' jwksUri: "/.well-known/jwks.json"\n' +
61
- ' discoveryEndpoint: "/.well-known/oauth-authorization-server"\n' +
62
- "\n" +
63
- "Then set FLAIR_MCP_ISSUER (or FLAIR_PUBLIC_URL) to your instance's public origin " +
64
- "and add the corresponding mcp.* block to the component config.");
385
+ if (!mcpOAuthEnabled())
386
+ return;
387
+ const read = readOAuthComponent(harperNs);
388
+ if (read.kind === "unreadable")
389
+ throw unreadableConfigError(read.detail);
390
+ if (read.kind === "absent")
391
+ throw componentAbsentError();
392
+ const enabled = readEffectiveMcpEnabled(read.component);
393
+ if (enabled.kind === "unreadable")
394
+ throw unreadableConfigError(enabled.detail);
395
+ if (!enabled.enabled) {
396
+ throw disagreementError((process.env.FLAIR_MCP_OAUTH ?? "").trim(), enabled.configured);
65
397
  }
398
+ assertEffectiveMcpIssuer(read.component);
66
399
  }
67
400
  /**
68
401
  * Initial value: no route has been registered yet, which is literally true until
@@ -76,8 +409,24 @@ let routeState = {
76
409
  status: "Not mounted",
77
410
  reason: "MCP route registration has not run.",
78
411
  };
79
- /** Read the mount decision the router recorded. */
412
+ /**
413
+ * The namespace whose `/mcp` route is mounted, captured at mount time. A read
414
+ * of `mcpRouteState()` evaluates the same refusal helper against it, so the
415
+ * recorded answer tracks the live config instead of the last request.
416
+ */
417
+ let mountedNamespace;
418
+ /**
419
+ * Read the mount decision, derived from the live config when the route is
420
+ * mounted. A mounted route whose live config would now be refused reports the
421
+ * refusal, never "mounted".
422
+ */
80
423
  export function mcpRouteState() {
424
+ if (routeState.mounted && mountedNamespace !== undefined) {
425
+ const check = checkLiveMcpConfig(mountedNamespace);
426
+ if (check.kind === "refused") {
427
+ return { mounted: false, status: check.status, reason: check.reason };
428
+ }
429
+ }
81
430
  return routeState;
82
431
  }
83
432
  /**
@@ -87,6 +436,8 @@ export function mcpRouteState() {
87
436
  */
88
437
  function decide(state) {
89
438
  routeState = state;
439
+ if (!state.mounted)
440
+ mountedNamespace = undefined;
90
441
  return state.mounted;
91
442
  }
92
443
  async function defaultLoadWithMCPAuth() {
@@ -121,17 +472,30 @@ export function rateLimitedMcpHandler(handler) {
121
472
  return handler(request);
122
473
  };
123
474
  }
475
+ /**
476
+ * flair#3076: add `scope="<MCP_REQUESTED_SCOPES>"` (the scope of each /mcp tool
477
+ * except soul_set) to a 401 Bearer challenge that names no scope. Any other
478
+ * response is returned as it is.
479
+ */
480
+ export function withRequestedScope(res) {
481
+ const challenge = res?.headers?.["WWW-Authenticate"];
482
+ if (res?.status !== 401 || typeof challenge !== "string" || !/^Bearer\s/.test(challenge) || /\bscope=/.test(challenge)) {
483
+ return res;
484
+ }
485
+ return {
486
+ ...res,
487
+ headers: { ...res.headers, "WWW-Authenticate": `${challenge}, scope="${MCP_REQUESTED_SCOPES.join(" ")}"` },
488
+ };
489
+ }
124
490
  export async function registerMcpOAuthRoute(deps = {}) {
125
491
  if (!mcpOAuthEnabled()) {
126
492
  // OFF → no route, no import, no side effects.
127
493
  return decide({
128
494
  mounted: false,
129
495
  status: "Not enabled",
130
- // "true" not "1": flair's flag accepts either, but the component's
131
- // config-side read of the same var (config.yaml `mcp.enabled:
132
- // ${FLAIR_MCP_OAUTH}`, flair#1152) accepts ONLY "true"/"false" — with
133
- // "1" the /mcp route registers and every request 401s against a
134
- // component that never mounted its AS.
496
+ // "true" not "1": this reader accepts 1/true/yes/on, but the component
497
+ // maps only true/false strings (trimmed, any case) to a boolean, so
498
+ // 1/yes/on leave it disabled. This reason names true, which both accept.
135
499
  reason: "Set FLAIR_MCP_OAUTH=true (and an issuer) to serve MCP over HTTP.",
136
500
  });
137
501
  }
@@ -147,10 +511,8 @@ export async function registerMcpOAuthRoute(deps = {}) {
147
511
  reason: `${degraded.reason}. Set it (or re-run: flair mcp enable), then restart.`,
148
512
  });
149
513
  }
150
- // Boot guard (flair#1021): fail loudly if the operator enabled the flag but
151
- // the @harperfast/oauth component is absent from config.yaml. Without it the
152
- // authorization server's routes never mount — discovery, authorize, token,
153
- // JWKS all 404 — and the /mcp guard has nothing to validate against.
514
+ // Boot guard (flair#1021, flair#1322): the component must be declared and its
515
+ // effective mcp.enabled must be true.
154
516
  if (!deps.skipComponentGuard) {
155
517
  assertHarperOAuthComponentDeclared(deps.harper);
156
518
  }
@@ -160,11 +522,11 @@ export async function registerMcpOAuthRoute(deps = {}) {
160
522
  // unconfigured guard (withMCPAuth would fail closed anyway, but not mounting
161
523
  // is the clearer signal). Log and bail — the operator must set FLAIR_MCP_ISSUER.
162
524
  console.error("[mcp-oauth] FLAIR_MCP_OAUTH is on but no issuer configured " +
163
- "(set FLAIR_MCP_ISSUER or FLAIR_PUBLIC_URL) — /mcp NOT mounted.");
525
+ "(set FLAIR_MCP_ISSUER) — /mcp NOT mounted.");
164
526
  return decide({
165
527
  mounted: false,
166
528
  status: "Not mounted",
167
- reason: "FLAIR_MCP_OAUTH is on but no issuer is configured — set FLAIR_MCP_ISSUER (or FLAIR_PUBLIC_URL).",
529
+ reason: "FLAIR_MCP_OAUTH is on but no issuer is configured — set FLAIR_MCP_ISSUER.",
168
530
  });
169
531
  }
170
532
  let withMCPAuth;
@@ -197,13 +559,44 @@ export async function registerMcpOAuthRoute(deps = {}) {
197
559
  // module, not a static named export) so this module links cleanly even where a
198
560
  // stub build of harper lacks the export.
199
561
  const srv = deps.server ?? (harper.server);
200
- // Mount /mcp after the guard.
201
- srv.http(withMCPAuth(rateLimitedMcpHandler(handler), {
202
- getConfig: () => (deps.harper ?? harper).server?.resources?.get("oauth")?.Resource?.mcpConfig?.enabled === true
203
- ? mcpAuthConfig()
204
- : undefined,
205
- }), { urlPath: "/mcp", after: MULTI_WORKER_GUARD_HTTP_NAME });
562
+ // Mount /mcp after the guard. The listener below holds the issuer rule on
563
+ // every request before the wrapper runs (flair#3032), so a live issuer
564
+ // change is answered with the boot guard's named refusal instead of the
565
+ // wrapper's generic invalid_token.
566
+ const harperNs = deps.harper ?? harper;
567
+ const guardedMcp = withMCPAuth(rateLimitedMcpHandler(handler), {
568
+ getConfig: () => {
569
+ try {
570
+ const live = readLiveMcpConfig(harperNs);
571
+ if (live.kind !== "present" || live.config.enabled !== true)
572
+ return undefined;
573
+ if (issuerFailedRule(live.config.issuer) !== undefined)
574
+ return undefined;
575
+ return mcpAuthConfig();
576
+ }
577
+ catch {
578
+ return undefined;
579
+ }
580
+ },
581
+ });
582
+ srv.http(async (request, next) => {
583
+ const check = checkLiveMcpConfig(harperNs);
584
+ if (check.kind === "refused") {
585
+ // The body carries the named refusal, which names the rule and the
586
+ // remedy but no resolved issuer value.
587
+ return {
588
+ status: 503,
589
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...MCP_DENIAL_CORS_HEADERS },
590
+ body: JSON.stringify({ error: check.code, error_description: check.reason }),
591
+ };
592
+ }
593
+ // Reaching the wrapper means the live config is present, enabled, and
594
+ // its issuer passed the rule; mounted state is derived on read, never
595
+ // recorded for a request that may then be denied.
596
+ return withRequestedScope(await guardedMcp(request, next));
597
+ }, { urlPath: "/mcp", after: MULTI_WORKER_GUARD_HTTP_NAME });
206
598
  console.error(`[mcp-oauth] /mcp mounted (OAuth-guarded); issuer=${config.issuer}`);
599
+ mountedNamespace = harperNs;
207
600
  return decide({ mounted: true });
208
601
  }
209
602
  // Fire-and-forget at module load. Any failure is contained inside
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The OAuth scope each native `/mcp` tool requires (flair#3076).
3
+ *
4
+ * `withMCPAuth` passes the access token's verified `scope` claim (a
5
+ * space-separated string) to the handler as `request.mcp.scope`. A tools/call
6
+ * runs only when that claim grants the scope this table lists for the tool. A
7
+ * token with no `scope` claim grants no scope. The tool runs as the token's
8
+ * mapped principal, with that principal's authority.
9
+ *
10
+ * resources/mcp-tools.ts refuses to load when a tool has no entry here, or an
11
+ * entry names a tool it does not serve.
12
+ */
13
+ export const MCP_TOOL_SCOPES = Object.freeze({
14
+ // Reads and searches of memories and the caller's own context.
15
+ memory_search: "memory:read",
16
+ memory_get: "memory:read",
17
+ skill_search: "memory:read",
18
+ skill_get: "memory:read",
19
+ bootstrap: "memory:read",
20
+ soul_get: "memory:read",
21
+ attention: "memory:read",
22
+ // Writes, updates, archive changes and deletes.
23
+ memory_store: "memory:write",
24
+ memory_update: "memory:write",
25
+ memory_delete: "memory:write",
26
+ memory_basement: "memory:write",
27
+ memory_restore: "memory:write",
28
+ skill_store: "memory:write",
29
+ flair_workspace_set: "memory:write",
30
+ flair_orgevent: "memory:write",
31
+ record_usage: "memory:write",
32
+ // The principal list.
33
+ team_directory: "principal:read",
34
+ // A Soul write is an operator action; with this scope soul_set still refuses
35
+ // the write (soul_write_requires_operator).
36
+ soul_set: "principal:admin",
37
+ });
38
+ /**
39
+ * The scopes the /mcp 401 challenge names and Flair's client metadata documents
40
+ * declare: the scope of each tool except `soul_set`.
41
+ */
42
+ export const MCP_REQUESTED_SCOPES = Object.freeze([
43
+ "memory:read",
44
+ "memory:write",
45
+ "principal:read",
46
+ ]);
47
+ /** The scope `tool` requires, or undefined for a name the table does not list. */
48
+ export function requiredToolScope(tool) {
49
+ return Object.prototype.hasOwnProperty.call(MCP_TOOL_SCOPES, tool) ? MCP_TOOL_SCOPES[tool] : undefined;
50
+ }
51
+ /** The scopes a token's `scope` claim grants. An absent claim grants none. */
52
+ export function grantedScopes(claim) {
53
+ return typeof claim === "string" ? claim.split(/\s+/).filter(Boolean) : [];
54
+ }
55
+ // RFC 6749 section 3.3 scope-token characters. A granted value outside them is
56
+ // left out of a challenge header rather than quoted into it.
57
+ const SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
58
+ /**
59
+ * The `scope` an insufficient_scope challenge names: the granted values that are
60
+ * RFC 6749 scope tokens, MCP_REQUESTED_SCOPES, and the scope the tool requires.
61
+ */
62
+ export function challengeScope(granted, required) {
63
+ const scopes = new Set();
64
+ for (const scope of [...granted, ...MCP_REQUESTED_SCOPES, required]) {
65
+ if (SCOPE_TOKEN.test(scope))
66
+ scopes.add(scope);
67
+ }
68
+ return [...scopes].join(" ");
69
+ }