@tpsdev-ai/flair 0.62.0 → 0.63.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. 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);
@@ -25,44 +25,376 @@ 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
27
  /**
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.
28
+ * Boot guard (flair#1021, flair#1322), after the flag and degraded-start checks.
34
29
  *
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.
30
+ * The `@harperfast/oauth` component must be declared, and its effective
31
+ * `mcp.enabled` must be true. Effective means the component's own read:
32
+ * whole-token `${VAR}` expansion, then `true`/`false` only. Any other string
33
+ * (`1`, `yes`, `on`, an unresolved placeholder, garbage) is deleted and the
34
+ * disabled default applies. Key presence is not that state — the block ships
35
+ * in config.yaml, so a pre-0.46 `FLAIR_MCP_OAUTH=1` used to mount `/mcp` while
36
+ * the authorization server stayed off.
37
+ *
38
+ * A config read that throws, or that returns an empty or unreadable body,
39
+ * refuses. That result is not a missing component and it is not success.
40
+ *
41
+ * When the two readers disagree, the error names `true` (the recommended
42
+ * setting, which both accept) and the remedy. It does not hardcode an issuer URL.
43
+ */
44
+ const OAUTH_COMPONENT_KEY = "@harperfast/oauth";
45
+ // Mirrors withMCPAuth denial CORS headers in @harperfast/oauth 2.9.0.
46
+ const MCP_DENIAL_CORS_HEADERS = {
47
+ "Access-Control-Allow-Origin": "*",
48
+ "Access-Control-Expose-Headers": "WWW-Authenticate",
49
+ };
50
+ /**
51
+ * A plain record in this realm or another. Harper runs this module in a VM,
52
+ * so `config` can be a host-realm object whose prototype is not this realm's
53
+ * `Object.prototype`.
54
+ */
55
+ function isRecord(value) {
56
+ try {
57
+ if (value == null || typeof value !== "object" || Array.isArray(value))
58
+ return false;
59
+ const proto = Object.getPrototypeOf(value);
60
+ if (proto === null)
61
+ return true;
62
+ // `Object.prototype` in any realm: its prototype is null, and it is that
63
+ // realm's `Object` constructor's prototype. Class instances sit one step
64
+ // further out and are not records.
65
+ if (Object.getPrototypeOf(proto) !== null)
66
+ return false;
67
+ const ctor = proto.constructor;
68
+ return typeof ctor === "function" && ctor.prototype === proto;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ /** `@harperfast/oauth` `expandEnvVar`: whole-token `${NAME}` only. */
75
+ function expandWholeTokenEnv(value) {
76
+ if (typeof value !== "string" || !value.startsWith("${") || !value.endsWith("}"))
77
+ return value;
78
+ const envValue = process.env[value.slice(2, -1)];
79
+ return envValue !== undefined ? envValue : value;
80
+ }
81
+ function readOAuthComponent(harperNs) {
82
+ let hc;
83
+ try {
84
+ const h = harperNs ?? harper;
85
+ hc = h?.app?.config ?? h?.config;
86
+ }
87
+ catch {
88
+ return { kind: "unreadable", detail: "config lookup failed" };
89
+ }
90
+ if (!isRecord(hc)) {
91
+ return { kind: "unreadable", detail: "application config is missing or unreadable" };
92
+ }
93
+ let keyCount = 0;
94
+ let readableGet = false;
95
+ try {
96
+ keyCount = Object.keys(hc).length;
97
+ readableGet = typeof hc.get === "function";
98
+ }
99
+ catch {
100
+ return { kind: "unreadable", detail: "application config is unreadable" };
101
+ }
102
+ // `{}` is unreadable: a missing document can arrive as an empty object.
103
+ // A get-backed config may have no enumerable keys and still hold the component.
104
+ if (keyCount === 0 && !readableGet) {
105
+ return { kind: "unreadable", detail: "application config is empty" };
106
+ }
107
+ let component;
108
+ try {
109
+ if (typeof hc.get === "function")
110
+ component = hc.get(OAUTH_COMPONENT_KEY);
111
+ }
112
+ catch {
113
+ return { kind: "unreadable", detail: "config lookup failed" };
114
+ }
115
+ if (component == null) {
116
+ try {
117
+ component = hc[OAUTH_COMPONENT_KEY];
118
+ }
119
+ catch {
120
+ return { kind: "unreadable", detail: "config lookup failed" };
121
+ }
122
+ }
123
+ if (component == null)
124
+ return { kind: "absent" };
125
+ if (!isRecord(component)) {
126
+ return { kind: "unreadable", detail: "component entry is not an object" };
127
+ }
128
+ return { kind: "present", component };
129
+ }
130
+ /**
131
+ * The component's effective `mcp.enabled` after `coerceConfigBoolean`.
132
+ * Omitted, null, or a deleted non-boolean string is the disabled default.
133
+ */
134
+ export function readEffectiveMcpEnabled(component) {
135
+ try {
136
+ if (!Object.prototype.hasOwnProperty.call(component, "mcp") || component.mcp == null) {
137
+ return { kind: "bool", enabled: false, configured: undefined };
138
+ }
139
+ if (!isRecord(component.mcp)) {
140
+ return { kind: "unreadable", detail: "mcp entry is not an object" };
141
+ }
142
+ if (!Object.prototype.hasOwnProperty.call(component.mcp, "enabled") || component.mcp.enabled === undefined) {
143
+ return { kind: "bool", enabled: false, configured: undefined };
144
+ }
145
+ const configured = component.mcp.enabled;
146
+ if (configured === null)
147
+ return { kind: "bool", enabled: false, configured };
148
+ const expanded = expandWholeTokenEnv(configured);
149
+ if (typeof expanded === "boolean")
150
+ return { kind: "bool", enabled: expanded, configured };
151
+ if (typeof expanded === "string") {
152
+ const v = expanded.trim().toLowerCase();
153
+ if (v === "true")
154
+ return { kind: "bool", enabled: true, configured };
155
+ if (v === "false")
156
+ return { kind: "bool", enabled: false, configured };
157
+ return { kind: "bool", enabled: false, configured };
158
+ }
159
+ return { kind: "unreadable", detail: "mcp.enabled is not a boolean or string" };
160
+ }
161
+ catch {
162
+ return { kind: "unreadable", detail: "mcp config lookup failed" };
163
+ }
164
+ }
165
+ function unreadableConfigError(detail) {
166
+ return new Error("FLAIR_MCP_OAUTH is enabled but the @harperfast/oauth configuration could not be read (" +
167
+ detail +
168
+ "). Refusing to mount /mcp. " +
169
+ 'Remedy: make config.yaml\'s "@harperfast/oauth" entry a readable object, ' +
170
+ "with mcp.enabled set to true or to ${FLAIR_MCP_OAUTH}, and set FLAIR_MCP_OAUTH=true.");
171
+ }
172
+ function componentAbsentError() {
173
+ return new Error("FLAIR_MCP_OAUTH is enabled but the @harperfast/oauth component is not declared in config.yaml. " +
174
+ "The authorization server cannot start without it — discovery, authorize, token, and JWKS endpoints will all 404.\n" +
175
+ 'Restore the complete "@harperfast/oauth" entry from the config.yaml that ships with this Flair version. ' +
176
+ "This is a PARTIAL declaration of that entry; it leaves out the providers block:\n" +
177
+ "\n" +
178
+ ' "@harperfast/oauth":\n' +
179
+ ' package: "@harperfast/oauth"\n' +
180
+ " mcp:\n" +
181
+ " enabled: ${FLAIR_MCP_OAUTH}\n" +
182
+ " issuer: ${FLAIR_MCP_ISSUER}\n" +
183
+ "\n" +
184
+ "This alone does not start the authorization server: the component also needs at least one provider " +
185
+ "with its client ID, client secret and redirect URI set (the shipped entry configures github through " +
186
+ "OAUTH_GITHUB_CLIENT_ID, OAUTH_GITHUB_CLIENT_SECRET and OAUTH_GITHUB_REDIRECT_URI). " +
187
+ "Then set FLAIR_MCP_OAUTH=true and set FLAIR_MCP_ISSUER to this instance's public origin.");
188
+ }
189
+ function boundedConfigValue(value) {
190
+ return JSON.stringify(value.length > 64 ? `${value.slice(0, 64)}…` : value);
191
+ }
192
+ function disagreementError(rawEnv, configured) {
193
+ const base = `FLAIR_MCP_OAUTH is ${boundedConfigValue(rawEnv)}, which Flair treats as enabled, ` +
194
+ "but the @harperfast/oauth component's effective mcp.enabled is not true. " +
195
+ "Use true, the recommended value; both readers accept it.";
196
+ const isEnvRef = configured === "${FLAIR_MCP_OAUTH}";
197
+ const remedy = isEnvRef ? "Set FLAIR_MCP_OAUTH=true." : "Set mcp.enabled to true.";
198
+ return new Error(`${base} ${remedy}`);
199
+ }
200
+ function issuerUnreadableError(phase = "mount") {
201
+ return new Error("mcp.issuer could not be read. Set FLAIR_MCP_ISSUER to an absolute http(s) origin " +
202
+ "and set mcp.issuer to ${FLAIR_MCP_ISSUER}. Refusing to " + phase + " /mcp.");
203
+ }
204
+ /**
205
+ * FLAIR_MCP_ISSUER is unset or blank at request time. That is its own fault,
206
+ * not an unreadable component value: withMCPAuth verifies tokens against this
207
+ * variable, so without it a request has nothing to check against, whether or
208
+ * not the live config is readable.
39
209
  */
210
+ function issuerEnvMissingError() {
211
+ return new Error("FLAIR_MCP_ISSUER is unset or blank, so a /mcp request cannot be checked against " +
212
+ "the authorization server's issuer. Refusing to serve /mcp. " +
213
+ "Set FLAIR_MCP_ISSUER to this instance's public origin.");
214
+ }
215
+ function liveMcpConfigUnreadableError() {
216
+ return new Error("The live @harperfast/oauth MCP configuration could not be verified. Refusing to serve /mcp. " +
217
+ "Inspect the registered @harperfast/oauth component and ensure its mcp settings are a plain mapping " +
218
+ "with enabled and issuer.");
219
+ }
220
+ /**
221
+ * The live @harperfast/oauth MCP config is absent, or present with
222
+ * `enabled !== true`: the authorization server cannot mint a token for this
223
+ * surface, and the per-request check refuses every /mcp request as
224
+ * unavailable (503) before withMCPAuth runs. Absent is also what a
225
+ * component with no valid provider leaves behind, so the remedy names one.
226
+ */
227
+ function mcpAuthUnavailableError() {
228
+ return new Error("The @harperfast/oauth component is not serving an MCP authorization configuration " +
229
+ "(its live mcpConfig is absent or disabled). Refusing to serve /mcp. " +
230
+ "Configure a valid OAuth provider for the component — its client ID, client secret " +
231
+ "and redirect URI — and set FLAIR_MCP_OAUTH=true and FLAIR_MCP_ISSUER to this " +
232
+ "instance's public origin, with mcp.enabled true and mcp.issuer set to " +
233
+ "${FLAIR_MCP_ISSUER}, then restart.");
234
+ }
235
+ /**
236
+ * The boot guard's issuer rule, over one candidate value: the failed rule, or
237
+ * undefined when the value is a canonical origin that also matches
238
+ * FLAIR_MCP_ISSUER after the trailing-slash trim. A valid origin returns
239
+ * undefined when FLAIR_MCP_ISSUER is unset — the rule cannot compare against an
240
+ * absent reference — so the request-time check refuses an unset issuer before
241
+ * calling this. flair#3032: the per-request check below holds this same rule
242
+ * against the authorization server's live issuer, so the two checks cannot
243
+ * drift apart.
244
+ */
245
+ function issuerFailedRule(issuer) {
246
+ let failedRule;
247
+ // new URL() removes ASCII tab, LF and CR anywhere and trims C0 controls
248
+ // and spaces at the ends; other embedded C0 controls or spaces in a host throw.
249
+ // Refuse whitespace and controls anyway: the component keeps the raw issuer.
250
+ if (typeof issuer !== "string")
251
+ return "not a string";
252
+ if (/[\u0000-\u0020\u007F]/.test(issuer))
253
+ return "has whitespace or control characters";
254
+ try {
255
+ const parsedIssuer = new URL(issuer);
256
+ const pathWithoutTrailingSlash = parsedIssuer.pathname.replace(/\/+$/, "");
257
+ if (parsedIssuer.protocol !== "http:" && parsedIssuer.protocol !== "https:")
258
+ failedRule = "not http/https";
259
+ else if (pathWithoutTrailingSlash !== "")
260
+ failedRule = "has a path";
261
+ // Stricter than @harperfast/oauth 2.9.0 on purpose: an empty `?` or `#` leaves
262
+ // URL.search/hash empty, so the component accepts it, then prefixes every endpoint
263
+ // with the raw value (`https://host?/oauth/mcp/token`). Refuse any raw delimiter.
264
+ else if (parsedIssuer.search !== "" || parsedIssuer.hash !== "" || /[?#]/.test(issuer))
265
+ failedRule = "has a query/hash";
266
+ else if (parsedIssuer.username !== "" || parsedIssuer.password !== "")
267
+ failedRule = "has userinfo";
268
+ else if (issuer.replace(/\/+$/, "") !== parsedIssuer.origin)
269
+ failedRule = "not in canonical origin form";
270
+ // flair#3032: the authorization server mints tokens for THIS value, while
271
+ // withMCPAuth verifies them against mcpIssuer(). A literal that disagrees
272
+ // with FLAIR_MCP_ISSUER mounts /mcp with tokens that cannot verify there.
273
+ else {
274
+ const envIssuer = mcpIssuer();
275
+ if (envIssuer !== undefined && issuer.replace(/\/+$/, "") !== envIssuer.replace(/\/+$/, "")) {
276
+ failedRule = "differs from FLAIR_MCP_ISSUER";
277
+ }
278
+ else
279
+ return undefined;
280
+ }
281
+ }
282
+ catch {
283
+ failedRule = "not absolute";
284
+ }
285
+ return failedRule;
286
+ }
287
+ function issuerRefusalError(configured, failedRule, phase = "mount") {
288
+ const envName = typeof configured === "string" && configured.startsWith("${") && configured.endsWith("}")
289
+ ? configured.slice(2, -1) : undefined;
290
+ const detail = envName === undefined ? ` (${failedRule})`
291
+ : process.env[envName] === undefined ? ` (environment variable ${JSON.stringify(envName)} is unset)`
292
+ : ` (environment variable ${JSON.stringify(envName)} value fails the rule: ${failedRule})`;
293
+ if (failedRule === "differs from FLAIR_MCP_ISSUER") {
294
+ return new Error("The @harperfast/oauth component's mcp.issuer is a valid absolute http(s) origin" + detail +
295
+ ", but withMCPAuth verifies tokens against FLAIR_MCP_ISSUER, so the tokens the component mints cannot verify here. " +
296
+ `Refusing to ${phase} /mcp. Set FLAIR_MCP_ISSUER and mcp.issuer to the same public origin, ` +
297
+ "or set mcp.issuer to ${FLAIR_MCP_ISSUER}.");
298
+ }
299
+ return new Error("The @harperfast/oauth component's mcp.issuer must be an absolute http(s) origin" + detail +
300
+ `. Refusing to ${phase} /mcp. Set FLAIR_MCP_ISSUER to an absolute http(s) origin ` +
301
+ "without a path, query, fragment or userinfo, written as scheme://host[:port] with a lowercase host, " +
302
+ "no default port, and at most a trailing slash, and set mcp.issuer to ${FLAIR_MCP_ISSUER}.");
303
+ }
304
+ function assertEffectiveMcpIssuer(component) {
305
+ let configured;
306
+ let issuer;
307
+ try {
308
+ configured = component.mcp.issuer;
309
+ issuer = expandWholeTokenEnv(configured);
310
+ }
311
+ catch {
312
+ throw issuerUnreadableError();
313
+ }
314
+ const failedRule = issuerFailedRule(issuer);
315
+ if (failedRule !== undefined)
316
+ throw issuerRefusalError(configured, failedRule);
317
+ }
318
+ function readLiveMcpConfig(harperNs) {
319
+ let config;
320
+ try {
321
+ config = (harperNs ?? harper).server?.resources?.get("oauth")?.Resource?.mcpConfig;
322
+ }
323
+ catch {
324
+ return { kind: "unreadable" };
325
+ }
326
+ // No live MCP config means the component is not serving an authorization
327
+ // server for this surface at all: the per-request check refuses it as
328
+ // unavailable (503), and getConfig returns undefined for it.
329
+ if (config == null)
330
+ return { kind: "absent" };
331
+ if (!isRecord(config))
332
+ return { kind: "unreadable" };
333
+ return { kind: "present", config };
334
+ }
335
+ function checkLiveMcpConfig(harperNs) {
336
+ const unavailable = (reason) => ({
337
+ kind: "refused",
338
+ code: "mcp_auth_unavailable",
339
+ status: "MCP auth unavailable",
340
+ reason,
341
+ });
342
+ // withMCPAuth verifies against FLAIR_MCP_ISSUER; without it at request time
343
+ // there is no comparison to hold, so this is a refusal, never a skip. It is
344
+ // not a component read failure, so it gets its own message.
345
+ if (mcpIssuer() === undefined)
346
+ return unavailable(issuerEnvMissingError().message);
347
+ const read = readLiveMcpConfig(harperNs);
348
+ if (read.kind === "unreadable")
349
+ return unavailable(liveMcpConfigUnreadableError().message);
350
+ // No live config, or a disabled one, cannot mint a token for this surface.
351
+ if (read.kind === "absent")
352
+ return unavailable(mcpAuthUnavailableError().message);
353
+ let enabled;
354
+ let issuer;
355
+ try {
356
+ enabled = read.config.enabled;
357
+ }
358
+ catch {
359
+ return unavailable(liveMcpConfigUnreadableError().message);
360
+ }
361
+ if (enabled !== true)
362
+ return unavailable(mcpAuthUnavailableError().message);
363
+ try {
364
+ issuer = read.config.issuer;
365
+ }
366
+ catch {
367
+ return unavailable(issuerUnreadableError("serve").message);
368
+ }
369
+ if (issuer === undefined || issuer === null)
370
+ return unavailable(issuerUnreadableError("serve").message);
371
+ const failedRule = issuerFailedRule(issuer);
372
+ if (failedRule === undefined)
373
+ return { kind: "served" };
374
+ return {
375
+ kind: "refused",
376
+ code: "mcp_issuer_refused",
377
+ status: "Issuer refused",
378
+ // No configured value: the live issuer never belongs in the response or
379
+ // the log, so the refusal names only the rule and the remedy.
380
+ reason: issuerRefusalError(undefined, failedRule, "serve").message,
381
+ };
382
+ }
40
383
  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.");
384
+ if (!mcpOAuthEnabled())
385
+ return;
386
+ const read = readOAuthComponent(harperNs);
387
+ if (read.kind === "unreadable")
388
+ throw unreadableConfigError(read.detail);
389
+ if (read.kind === "absent")
390
+ throw componentAbsentError();
391
+ const enabled = readEffectiveMcpEnabled(read.component);
392
+ if (enabled.kind === "unreadable")
393
+ throw unreadableConfigError(enabled.detail);
394
+ if (!enabled.enabled) {
395
+ throw disagreementError((process.env.FLAIR_MCP_OAUTH ?? "").trim(), enabled.configured);
65
396
  }
397
+ assertEffectiveMcpIssuer(read.component);
66
398
  }
67
399
  /**
68
400
  * Initial value: no route has been registered yet, which is literally true until
@@ -76,8 +408,24 @@ let routeState = {
76
408
  status: "Not mounted",
77
409
  reason: "MCP route registration has not run.",
78
410
  };
79
- /** Read the mount decision the router recorded. */
411
+ /**
412
+ * The namespace whose `/mcp` route is mounted, captured at mount time. A read
413
+ * of `mcpRouteState()` evaluates the same refusal helper against it, so the
414
+ * recorded answer tracks the live config instead of the last request.
415
+ */
416
+ let mountedNamespace;
417
+ /**
418
+ * Read the mount decision, derived from the live config when the route is
419
+ * mounted. A mounted route whose live config would now be refused reports the
420
+ * refusal, never "mounted".
421
+ */
80
422
  export function mcpRouteState() {
423
+ if (routeState.mounted && mountedNamespace !== undefined) {
424
+ const check = checkLiveMcpConfig(mountedNamespace);
425
+ if (check.kind === "refused") {
426
+ return { mounted: false, status: check.status, reason: check.reason };
427
+ }
428
+ }
81
429
  return routeState;
82
430
  }
83
431
  /**
@@ -87,6 +435,8 @@ export function mcpRouteState() {
87
435
  */
88
436
  function decide(state) {
89
437
  routeState = state;
438
+ if (!state.mounted)
439
+ mountedNamespace = undefined;
90
440
  return state.mounted;
91
441
  }
92
442
  async function defaultLoadWithMCPAuth() {
@@ -127,11 +477,9 @@ export async function registerMcpOAuthRoute(deps = {}) {
127
477
  return decide({
128
478
  mounted: false,
129
479
  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.
480
+ // "true" not "1": this reader accepts 1/true/yes/on, but the component
481
+ // maps only true/false strings (trimmed, any case) to a boolean, so
482
+ // 1/yes/on leave it disabled. This reason names true, which both accept.
135
483
  reason: "Set FLAIR_MCP_OAUTH=true (and an issuer) to serve MCP over HTTP.",
136
484
  });
137
485
  }
@@ -147,10 +495,8 @@ export async function registerMcpOAuthRoute(deps = {}) {
147
495
  reason: `${degraded.reason}. Set it (or re-run: flair mcp enable), then restart.`,
148
496
  });
149
497
  }
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.
498
+ // Boot guard (flair#1021, flair#1322): the component must be declared and its
499
+ // effective mcp.enabled must be true.
154
500
  if (!deps.skipComponentGuard) {
155
501
  assertHarperOAuthComponentDeclared(deps.harper);
156
502
  }
@@ -160,11 +506,11 @@ export async function registerMcpOAuthRoute(deps = {}) {
160
506
  // unconfigured guard (withMCPAuth would fail closed anyway, but not mounting
161
507
  // is the clearer signal). Log and bail — the operator must set FLAIR_MCP_ISSUER.
162
508
  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.");
509
+ "(set FLAIR_MCP_ISSUER) — /mcp NOT mounted.");
164
510
  return decide({
165
511
  mounted: false,
166
512
  status: "Not mounted",
167
- reason: "FLAIR_MCP_OAUTH is on but no issuer is configured — set FLAIR_MCP_ISSUER (or FLAIR_PUBLIC_URL).",
513
+ reason: "FLAIR_MCP_OAUTH is on but no issuer is configured — set FLAIR_MCP_ISSUER.",
168
514
  });
169
515
  }
170
516
  let withMCPAuth;
@@ -197,13 +543,44 @@ export async function registerMcpOAuthRoute(deps = {}) {
197
543
  // module, not a static named export) so this module links cleanly even where a
198
544
  // stub build of harper lacks the export.
199
545
  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 });
546
+ // Mount /mcp after the guard. The listener below holds the issuer rule on
547
+ // every request before the wrapper runs (flair#3032), so a live issuer
548
+ // change is answered with the boot guard's named refusal instead of the
549
+ // wrapper's generic invalid_token.
550
+ const harperNs = deps.harper ?? harper;
551
+ const guardedMcp = withMCPAuth(rateLimitedMcpHandler(handler), {
552
+ getConfig: () => {
553
+ try {
554
+ const live = readLiveMcpConfig(harperNs);
555
+ if (live.kind !== "present" || live.config.enabled !== true)
556
+ return undefined;
557
+ if (issuerFailedRule(live.config.issuer) !== undefined)
558
+ return undefined;
559
+ return mcpAuthConfig();
560
+ }
561
+ catch {
562
+ return undefined;
563
+ }
564
+ },
565
+ });
566
+ srv.http(async (request, next) => {
567
+ const check = checkLiveMcpConfig(harperNs);
568
+ if (check.kind === "refused") {
569
+ // The body carries the named refusal, which names the rule and the
570
+ // remedy but no resolved issuer value.
571
+ return {
572
+ status: 503,
573
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...MCP_DENIAL_CORS_HEADERS },
574
+ body: JSON.stringify({ error: check.code, error_description: check.reason }),
575
+ };
576
+ }
577
+ // Reaching the wrapper means the live config is present, enabled, and
578
+ // its issuer passed the rule; mounted state is derived on read, never
579
+ // recorded for a request that may then be denied.
580
+ return guardedMcp(request, next);
581
+ }, { urlPath: "/mcp", after: MULTI_WORKER_GUARD_HTTP_NAME });
206
582
  console.error(`[mcp-oauth] /mcp mounted (OAuth-guarded); issuer=${config.issuer}`);
583
+ mountedNamespace = harperNs;
207
584
  return decide({ mounted: true });
208
585
  }
209
586
  // Fire-and-forget at module load. Any failure is contained inside