@tpsdev-ai/flair 0.58.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -0,0 +1,132 @@
1
+ /**
2
+ * agent-home-fields.ts — the home-instance field predicates and the stamp
3
+ * control field, shared by the CLI (src/lib/agent-home.ts) and the Agent
4
+ * resource (resources/Agent.ts, flair#2472).
5
+ *
6
+ * Kept in its OWN module, with no imports: a static resource import must reach a
7
+ * dependency-free compiled helper (test/unit/resource-src-purity-1775.test.ts).
8
+ * agent-home.ts itself pulls in the ops-API readers, so the resource imports
9
+ * this file, never that one.
10
+ */
11
+ /** The `originatorInstanceId` value the Agent resource's create and the CLI's
12
+ * seed stamp as a new row's home. */
13
+ export const AGENT_HOME_FIELD = "originatorInstanceId";
14
+ /**
15
+ * The request-body control field the remedy sends to the Agent resource
16
+ * (flair#2472): a guarded home stamp. The resource reads it, applies the stamp
17
+ * inside a FRESH OWNED transaction — the request's own transaction is detached
18
+ * for that scope (resources/request-transaction.ts's withOwnedTransaction) — and
19
+ * drops the field before the write. It is a control field, not a stored column.
20
+ */
21
+ export const AGENT_HOME_STAMP_FIELD = "flairStampHome";
22
+ /**
23
+ * The named pause point the home-stamp test arms (flair#2472), inside the
24
+ * stamp's OWNED transaction, after the resource's first read of the row and
25
+ * before its confirmation read. Inert unless the fault-injection env opt-in is
26
+ * set and armed (resources/txn-pause-point.ts).
27
+ *
28
+ * The resource names this point as a DIRECT string literal at its call site
29
+ * (`txnPausePoint("agent-home-stamp")` in resources/Agent.ts), not through this
30
+ * constant: flair#2382's checker scans resources/ and src/ and resolves only
31
+ * direct literals or `spec.point`. This export is the single source the
32
+ * integration test arms (test/integration/agent-home-2433.test.ts), and it must
33
+ * stay equal to the literal.
34
+ */
35
+ export const AGENT_HOME_STAMP_PAUSE_POINT = "agent-home-stamp";
36
+ /**
37
+ * The request-body control field `flair principal add`'s write-back sends to the
38
+ * Agent resource (flair#2473). The write-back runs when the command's create-only
39
+ * `insert` is SKIPPED because the row already exists: the resource then writes
40
+ * back only the allow-listed fields (never the home) in a fresh owned
41
+ * transaction, refusing `originator_instance_immutable` when its owned read or
42
+ * its confirmation read sees a non-empty stored home differing from the resolved
43
+ * local ID, and
44
+ * `agent_principal_write_back_no_row` when either read finds the row absent. The
45
+ * resource reads the field and drops it before the write — it is a control
46
+ * field, not a stored column.
47
+ */
48
+ export const AGENT_PRINCIPAL_WRITE_BACK_FIELD = "flairPrincipalWriteBack";
49
+ /**
50
+ * The named refusal the Agent resource answers for a guarded principal write-back
51
+ * (flair#2473) whose row is ABSENT at the owned read before the staging or at the
52
+ * confirmation read (HTTP 404). Harper's `table.update` would re-create a missing
53
+ * row, so a deletion either read sees leaves the row deleted rather than bringing
54
+ * it back home-less. A deletion committed after the confirmation read and before
55
+ * the commit is not seen (the residual window, flair#2478).
56
+ */
57
+ export const AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR = "agent_principal_write_back_no_row";
58
+ /**
59
+ * The fields `flair principal add`'s write-back may set on an EXISTING Agent row
60
+ * (flair#2473). An EXPLICIT allow-list, not a deny-list: a field a future caller
61
+ * adds to the request body is NOT carried by this path until it is named here.
62
+ *
63
+ * `originatorInstanceId` is deliberately ABSENT — this path never takes a home
64
+ * from the request body (a create stamps it; an update keeps the stored value).
65
+ * `publicKey` and `createdAt` are absent too: the Agent resource treats both as
66
+ * immutable after create (a key changes through key rotation, not this write).
67
+ * The receiver-side federation stamps (`_syncedFrom`, `_originatorInstanceId`,
68
+ * `_syncedAt`) are absent as well — the Agent resource's write paths do not take
69
+ * them from a request body.
70
+ */
71
+ export const AGENT_PRINCIPAL_WRITE_BACK_FIELDS = [
72
+ "name",
73
+ "displayName",
74
+ "kind",
75
+ "type",
76
+ "status",
77
+ "defaultTrustTier",
78
+ "role",
79
+ "admin",
80
+ "runtime",
81
+ "updatedAt",
82
+ ];
83
+ /**
84
+ * The allow-listed subset of a write-back body: exactly the fields
85
+ * {@link AGENT_PRINCIPAL_WRITE_BACK_FIELDS} names, copied as-is. Never a home
86
+ * and never a federation stamp, because neither is on the list. PURE; a
87
+ * non-object body yields an empty object.
88
+ */
89
+ export function pickPrincipalWriteBackFields(content) {
90
+ const out = {};
91
+ if (content == null || typeof content !== "object")
92
+ return out;
93
+ const src = content;
94
+ for (const field of AGENT_PRINCIPAL_WRITE_BACK_FIELDS) {
95
+ if (field in src)
96
+ out[field] = src[field];
97
+ }
98
+ return out;
99
+ }
100
+ /**
101
+ * The named pause point the write-back test arms (flair#2473), inside the
102
+ * write-back's OWNED transaction, between the staged update and its confirmation
103
+ * read. Named as a DIRECT string literal at the call site in resources/Agent.ts
104
+ * (flair#2382's checker resolves only literals or `spec.point`); this export is
105
+ * the single source the integration test arms, and it must stay equal.
106
+ */
107
+ export const AGENT_PRINCIPAL_WRITE_BACK_PAUSE_POINT = "agent-principal-write-back";
108
+ /**
109
+ * Whether a non-empty string stored home differs from the resolved local ID
110
+ * (which may be null). Used by the guarded principal write-back (flair#2473).
111
+ */
112
+ export function isForeignAgentHome(row, localId) {
113
+ if (!row || typeof row !== "object")
114
+ return false;
115
+ const home = row[AGENT_HOME_FIELD];
116
+ return typeof home === "string" && home.length > 0 && home !== localId;
117
+ }
118
+ /** A row is home-less when `originatorInstanceId` is null, absent or empty. */
119
+ export function isHomeLessAgentRow(row) {
120
+ const home = row[AGENT_HOME_FIELD];
121
+ return home === null || home === undefined || home === "";
122
+ }
123
+ /**
124
+ * Whether the row carries a non-empty string `_syncedFrom` or
125
+ * `_originatorInstanceId` (receiver-side federation bookkeeping).
126
+ */
127
+ export function isSyncOriginatedAgentRow(row) {
128
+ if (!row)
129
+ return false;
130
+ return ((typeof row._syncedFrom === "string" && row._syncedFrom.length > 0) ||
131
+ (typeof row._originatorInstanceId === "string" && row._originatorInstanceId.length > 0));
132
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * agent-id-rule.ts — the ONE agent-ID rule, shared by the CLI (src/) and the
3
+ * server (resources/).
4
+ *
5
+ * An agent ID is the key of an Agent row and is used in URLs, shell hooks and
6
+ * federation payloads, so Flair's paths that create an Agent reject ids outside
7
+ * this rule (`flair mcp grant` also applies a narrower naming policy: a leading
8
+ * letter or digit). Before this module the rule lived inline in
9
+ * resources/AgentSeed.ts only: the Agent resource's REST writes,
10
+ * `flair agent add` and the federation merge each accepted an id AgentSeed
11
+ * would have refused, and the JIT-principal writers (XAA / MCP) built an id
12
+ * from a token subject without checking it.
13
+ *
14
+ * This module is deliberately dependency-free (it imports nothing): the
15
+ * resource/CLI boundary guard (test/unit/resource-src-purity-1775.test.ts)
16
+ * requires every src/ module a resources/ file imports to emit no module
17
+ * loads, and src/ must never import harper.
18
+ *
19
+ * The rule: `^[a-zA-Z0-9_-]{1,64}$` — 1..64 characters of A-Z, a-z, 0-9, `_`
20
+ * or `-`.
21
+ */
22
+ /** The rule as text, for messages and docs. */
23
+ export const AGENT_ID_RULE = "^[a-zA-Z0-9_-]{1,64}$";
24
+ /** The maximum length of an agent ID. */
25
+ export const AGENT_ID_MAX_LENGTH = 64;
26
+ /** The rule as a matcher. */
27
+ export const AGENT_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
28
+ /** The named error the Agent resource's write paths and the federation merge
29
+ * refuse with. The CLI and JIT-principal writers refuse with the same message
30
+ * text but not this code. */
31
+ export const AGENT_ID_ERROR = "invalid_agent_id";
32
+ /**
33
+ * Is `id` an agent ID this rule accepts? A non-string, non-number value —
34
+ * including `null` — is never valid. A write path must distinguish an OMITTED
35
+ * id (nothing to check; Harper may generate one) from a SUPPLIED `null`, which
36
+ * this returns false for.
37
+ */
38
+ export function isValidAgentId(id) {
39
+ if (typeof id !== "string" && typeof id !== "number")
40
+ return false;
41
+ return AGENT_ID_PATTERN.test(String(id));
42
+ }
43
+ /** A human-readable refusal message naming the rule and the offending value. */
44
+ export function invalidAgentIdMessage(id) {
45
+ return `invalid agent id ${JSON.stringify(id)}: an agent id must match ${AGENT_ID_RULE} (1-64 characters: A-Z, a-z, 0-9, _ or -)`;
46
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * agent-key-register.ts — the pure helpers for the admin-only key-registration
3
+ * operation (POST /AgentKeyRegister, flair#2266). The federation rule that ships
4
+ * with it has its predicate in resources/federation-classify.ts, applied by
5
+ * FederationSync in resources/Federation.ts.
6
+ *
7
+ * Kept out of the resource so the key-format rule and the fingerprint are
8
+ * unit-tested without Harper (test/unit/agent-key-register-2266.test.ts). The
9
+ * registration-specific refusal constants live here too; the authentication
10
+ * refusals (`authentication required`, `forbidden`) are literals in the
11
+ * resource. The integration tests assert the registration error names, and the
12
+ * authentication denials by HTTP status, against real Harper. Imports
13
+ * NOTHING (a static resource import must reach a dependency-free compiled
14
+ * helper — test/unit/resource-src-purity-1775.test.ts); the fingerprint uses the
15
+ * ambient WebCrypto, which the auth paths already use.
16
+ */
17
+ /** The stored `publicKey` value of an Agent row seeded but not yet registered. */
18
+ export const PENDING_PUBLIC_KEY = "pending";
19
+ /**
20
+ * The test-only pause point the concurrency/rollback test arms (flair#2266),
21
+ * inside the registration's OWNED transaction, after the fresh read and before
22
+ * the staging. Named as a DIRECT string literal at the resource call site
23
+ * (flair#2382's checker resolves only literals or `spec.point`); this export is
24
+ * the single source the integration test arms and must stay equal to the
25
+ * literal.
26
+ */
27
+ export const AGENT_KEY_REGISTER_PAUSE_POINT = "agent-key-register";
28
+ /**
29
+ * The test-only pause point after the registration's commit and before its
30
+ * read-back (flair#2266), so a test can commit a competing key change in
31
+ * between. A DIRECT string literal at the resource call site (flair#2382); this
32
+ * export must stay equal to it.
33
+ */
34
+ export const AGENT_KEY_REGISTER_READ_BACK_PAUSE_POINT = "agent-key-register-read-back";
35
+ /** 400: the request body is missing or malformed (invalid agentId / publicKey). */
36
+ export const REGISTRATION_REQUEST_INVALID = "registration_request_invalid";
37
+ /** 404: no Agent row with that id. */
38
+ export const AGENT_NOT_FOUND = "agent_not_found";
39
+ /** 403: the row did not originate on this instance (a foreign home or sync provenance). */
40
+ export const AGENT_NOT_LOCAL = "agent_not_local";
41
+ /** 403: the row is deactivated. */
42
+ export const AGENT_INACTIVE = "agent_inactive";
43
+ /** 409: the stored key is not exactly `pending`. */
44
+ export const AGENT_KEY_NOT_PENDING = "agent_key_not_pending";
45
+ /** 409: another registration is in progress, or the row changed under this one. */
46
+ export const REGISTRATION_CONFLICT = "registration_conflict";
47
+ /** 503: the registration store is unavailable, or committed state could not be confirmed. */
48
+ export const REGISTRATION_UNAVAILABLE = "registration_unavailable";
49
+ /** The OrgEvent kind a committed registration writes (its detail carries the fingerprint, not the key). */
50
+ export const AGENT_KEY_REGISTERED_EVENT = "agent_key_registered";
51
+ const CANONICAL_B64URL_43 = /^[A-Za-z0-9_-]{43}$/;
52
+ /**
53
+ * True iff `value` is a canonical base64url encoding of 32 bytes.
54
+ * This does not establish a valid Ed25519 point or possession of the private key.
55
+ * A key that is not a valid point never verifies a signature.
56
+ */
57
+ export function isCanonicalEd25519Base64url(value) {
58
+ if (typeof value !== "string" || !CANONICAL_B64URL_43.test(value))
59
+ return false;
60
+ try {
61
+ const buf = Buffer.from(value, "base64url");
62
+ return buf.length === 32 && buf.toString("base64url") === value;
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ /**
69
+ * The audit fingerprint of a registered key: the hex sha256 of its canonical
70
+ * base64url string. The audit `keyFingerprint` and the OrgEvent `detail` carry
71
+ * this in place of the key; the audit `agentId` and the event `refId` carry the
72
+ * target agent's id, which the event `summary` also names in text. The key
73
+ * itself is stored on the Agent row. Uses the ambient WebCrypto
74
+ * (the same primitive the auth paths digest/verify with), so this module
75
+ * imports nothing.
76
+ */
77
+ export async function keyFingerprint(canonicalKey) {
78
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalKey));
79
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
80
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * atomic-write.ts — replace a set of files all together, or not at all
3
+ * (flair#2034 §2).
4
+ *
5
+ * The service re-pointing paths (`flair init`, `flair doctor --fix`) rewrite
6
+ * files an operator's service manager reads: a launchd plist, a systemd unit,
7
+ * the federation-sync shim. A write that truncates the file in place and then
8
+ * fails leaves a half-written unit; a two-file update that fails between the
9
+ * files leaves a pair that disagree. Either is worse than not writing at all.
10
+ *
11
+ * `writeFilesAtomically` stages every new file as a temp file in the target's
12
+ * own directory (same filesystem, so the final rename is atomic), fsyncs each
13
+ * one, and only then renames them over their targets. When a rename fails
14
+ * part-way, every target already replaced is restored from the bytes and mode
15
+ * it had before the call, and the remaining temp files are removed. The caller
16
+ * sees either the complete new set or the complete old set.
17
+ *
18
+ * PLANNED FROM THESE BYTES (flair#2034 §2, round 3). A caller that computed
19
+ * the new content FROM the file's current content passes the snapshot it
20
+ * planned from as `expect` (see snapshotRegularFile). Immediately before the
21
+ * rename, the target is lstat'ed and read again: it must still be a regular
22
+ * file (never a symlink — rename would replace the link itself, not the file
23
+ * it points to), the SAME file (device + inode), and hold exactly the planned
24
+ * bytes. Anything else — an operator's edit saved while flair was planning, a
25
+ * file swapped for a symlink — refuses the write and changes nothing. This is a
26
+ * re-check, not a lock: the window between the re-check and the rename is the
27
+ * one syscall apart, and a second flair writer planning from the same bytes
28
+ * computes the same content.
29
+ *
30
+ * BYTES, NOT DECODED TEXT (round 4). A snapshot is taken only of a file whose
31
+ * bytes survive a UTF-8 decode and re-encode unchanged; any other file is
32
+ * refused before anything is planned from it (two different invalid byte
33
+ * sequences decode to the same U+FFFD, so a rewrite would change bytes flair
34
+ * does not own). The re-check compares the file's BYTES with the encoding of
35
+ * the planned content, which is exact for such a file, and the new content is
36
+ * written as its UTF-8 encoding, so every byte outside the replaced values is
37
+ * the byte that was read.
38
+ *
39
+ * The filesystem primitives are injectable so a test can fail any step (a
40
+ * write, an fsync, the Nth rename) and prove the recovery, without a real
41
+ * failing disk.
42
+ */
43
+ import { closeSync, existsSync, fchmodSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync, } from "node:fs";
44
+ import { randomBytes } from "node:crypto";
45
+ import { basename, dirname, join } from "node:path";
46
+ function resolveHooks(h) {
47
+ return {
48
+ open: h.open ?? ((p, flags, mode) => openSync(p, flags, mode)),
49
+ write: h.write ?? ((fd, data) => {
50
+ const buf = Buffer.from(data, "utf-8");
51
+ let off = 0;
52
+ while (off < buf.length)
53
+ off += writeSync(fd, buf, off, buf.length - off);
54
+ }),
55
+ fchmod: h.fchmod ?? ((fd, mode) => fchmodSync(fd, mode)),
56
+ fsync: h.fsync ?? ((fd) => fsyncSync(fd)),
57
+ close: h.close ?? ((fd) => closeSync(fd)),
58
+ rename: h.rename ?? ((from, to) => renameSync(from, to)),
59
+ unlink: h.unlink ?? ((p) => unlinkSync(p)),
60
+ exists: h.exists ?? ((p) => existsSync(p)),
61
+ read: h.read ?? ((p) => readFileSync(p, "utf-8")),
62
+ readBytes: h.readBytes ?? ((p) => readFileSync(p)),
63
+ modeOf: h.modeOf ?? ((p) => statSync(p).mode & 0o7777),
64
+ lstat: h.lstat ?? ((p) => lstatSync(p)),
65
+ };
66
+ }
67
+ /** Why `st` is not a plain regular file, or null. */
68
+ function notRegular(path, st) {
69
+ if (st.isSymbolicLink())
70
+ return `${path} is a symbolic link`;
71
+ if (!st.isFile())
72
+ return `${path} is not a regular file`;
73
+ return null;
74
+ }
75
+ /**
76
+ * Read `path` for planning: it must be a regular file (lstat — a symlink is
77
+ * refused, never followed), it must be the same file before and after the
78
+ * read, and its bytes must be valid UTF-8 that re-encodes to exactly those
79
+ * bytes. Throws an Error naming the path and what did not hold.
80
+ */
81
+ export function snapshotRegularFile(path, hooks = {}) {
82
+ const lstat = hooks.lstat ?? ((p) => lstatSync(p));
83
+ const readBytes = hooks.readBytes ?? ((p) => readFileSync(p));
84
+ const before = lstat(path);
85
+ const bad = notRegular(path, before);
86
+ if (bad)
87
+ throw new Error(bad);
88
+ const bytes = readBytes(path);
89
+ const content = bytes.toString("utf-8");
90
+ if (!Buffer.from(content, "utf-8").equals(bytes)) {
91
+ throw new Error(`${path} is not valid UTF-8, so flair cannot rewrite it without changing bytes it does not own`);
92
+ }
93
+ const after = lstat(path);
94
+ if (notRegular(path, after) || after.dev !== before.dev || after.ino !== before.ino) {
95
+ throw new Error(`${path} was replaced while it was being read`);
96
+ }
97
+ return { path, content, dev: before.dev, ino: before.ino, mode: before.mode & 0o7777 };
98
+ }
99
+ /** The re-check before a rename: null when `path` is still the planned file with the planned bytes. */
100
+ function plannedFileProblem(fs, path, expect) {
101
+ let st;
102
+ try {
103
+ st = fs.lstat(path);
104
+ }
105
+ catch (err) {
106
+ return `${path} could not be checked again before replacing it (${err?.message ?? err})`;
107
+ }
108
+ const bad = notRegular(path, st);
109
+ if (bad)
110
+ return bad;
111
+ if (st.dev !== expect.dev || st.ino !== expect.ino)
112
+ return `${path} was replaced by another file since flair read it`;
113
+ let now;
114
+ try {
115
+ now = fs.readBytes(path);
116
+ }
117
+ catch (err) {
118
+ return `${path} could not be read again before replacing it (${err?.message ?? err})`;
119
+ }
120
+ if (!now.equals(Buffer.from(expect.content, "utf-8")))
121
+ return `${path} was changed since flair read it`;
122
+ return null;
123
+ }
124
+ function tempPathFor(target) {
125
+ return join(dirname(target), `.${basename(target)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
126
+ }
127
+ /** Write `content` to a NEW temp file next to `target`, fsynced and closed. */
128
+ function stage(fs, target, content, mode) {
129
+ const tmp = tempPathFor(target);
130
+ const fd = fs.open(tmp, "wx", mode);
131
+ try {
132
+ fs.write(fd, content);
133
+ fs.fchmod(fd, mode);
134
+ fs.fsync(fd);
135
+ }
136
+ catch (err) {
137
+ try {
138
+ fs.close(fd);
139
+ }
140
+ catch { /* already failing */ }
141
+ try {
142
+ fs.unlink(tmp);
143
+ }
144
+ catch { /* best effort */ }
145
+ throw err;
146
+ }
147
+ fs.close(fd);
148
+ return tmp;
149
+ }
150
+ /** Best-effort directory fsync so the renames themselves are durable. */
151
+ function fsyncDir(dir) {
152
+ try {
153
+ const fd = openSync(dir, "r");
154
+ try {
155
+ fsyncSync(fd);
156
+ }
157
+ finally {
158
+ closeSync(fd);
159
+ }
160
+ }
161
+ catch {
162
+ /* not every platform allows fsync on a directory; the renames are still atomic */
163
+ }
164
+ }
165
+ /**
166
+ * Replace every file in `entries`, or none of them.
167
+ *
168
+ * Throws when the set could not be written. The error message says whether the
169
+ * originals were restored; in the (double-failure) case where a restore itself
170
+ * failed, it names every path that may now hold new content.
171
+ */
172
+ export function writeFilesAtomically(entries, hooks = {}) {
173
+ const fs = resolveHooks(hooks);
174
+ // 1. Remember what each target held, so a failed commit can put it back.
175
+ // A planned-from target must already be exactly what was planned from.
176
+ for (const e of entries) {
177
+ if (!e.expect)
178
+ continue;
179
+ const problem = plannedFileProblem(fs, e.path, e.expect);
180
+ if (problem)
181
+ throw new Error(`refusing to replace ${e.path}: ${problem}; nothing was changed`);
182
+ }
183
+ const originals = entries.map((e) => {
184
+ if (!fs.exists(e.path))
185
+ return { path: e.path, existed: false };
186
+ // A planned-from target is restored from the bytes it was re-checked to hold.
187
+ const content = e.expect ? e.expect.content : fs.read(e.path);
188
+ return { path: e.path, existed: true, content, mode: fs.modeOf(e.path) };
189
+ });
190
+ // 2. Stage every new file. Nothing visible has changed yet.
191
+ const staged = [];
192
+ try {
193
+ for (const e of entries)
194
+ staged.push(stage(fs, e.path, e.content, e.mode));
195
+ }
196
+ catch (err) {
197
+ for (const tmp of staged) {
198
+ try {
199
+ fs.unlink(tmp);
200
+ }
201
+ catch { /* best effort */ }
202
+ }
203
+ throw new Error(`could not stage the new ${entries.length === 1 ? "file" : "files"} (${err?.message ?? err}); ` +
204
+ `nothing was changed: ${entries.map((e) => e.path).join(", ")}`);
205
+ }
206
+ // 3. Commit: rename each staged file over its target.
207
+ const committed = [];
208
+ for (let i = 0; i < entries.length; i++) {
209
+ try {
210
+ // Re-check the planned-from target immediately before replacing it.
211
+ const expect = entries[i].expect;
212
+ const problem = expect ? plannedFileProblem(fs, entries[i].path, expect) : null;
213
+ if (problem)
214
+ throw new Error(`refusing to replace it: ${problem}`);
215
+ fs.rename(staged[i], entries[i].path);
216
+ committed.push(i);
217
+ }
218
+ catch (err) {
219
+ // Remove the temps not yet committed, then put back what was replaced.
220
+ for (let j = i; j < staged.length; j++) {
221
+ try {
222
+ fs.unlink(staged[j]);
223
+ }
224
+ catch { /* best effort */ }
225
+ }
226
+ const unrestored = [];
227
+ for (const k of committed.reverse()) {
228
+ const o = originals[k];
229
+ try {
230
+ if (o.existed) {
231
+ const tmp = stage(fs, o.path, o.content, o.mode);
232
+ fs.rename(tmp, o.path);
233
+ }
234
+ else {
235
+ fs.unlink(o.path);
236
+ }
237
+ }
238
+ catch {
239
+ unrestored.push(o.path);
240
+ }
241
+ }
242
+ const cause = err?.message ?? String(err);
243
+ if (unrestored.length > 0) {
244
+ throw new Error(`could not replace ${entries[i].path} (${cause}), and restoring the files already replaced failed for: ` +
245
+ `${unrestored.join(", ")} — those now hold the NEW content while the rest hold the old.`);
246
+ }
247
+ if (committed.length === 0) {
248
+ throw new Error(`could not replace ${entries[i].path} (${cause}); nothing was changed`);
249
+ }
250
+ throw new Error(`could not replace ${entries[i].path} (${cause}); every file was restored to its previous content: ` +
251
+ `${entries.map((e) => e.path).join(", ")}`);
252
+ }
253
+ }
254
+ for (const dir of new Set(entries.map((e) => dirname(e.path))))
255
+ fsyncDir(dir);
256
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * credential-status-rule.ts — the Credential-usability rule shared by the MCP
3
+ * credential resolver, the principal linker and the XAA jwt-bearer grant, from
4
+ * both the CLI (src/) and the server (resources/).
5
+ *
6
+ * A `Credential(kind:"idp")` is the mapping that turns an IdP subject into a
7
+ * flair principal. `resolveAgentFromSub` (resources/mcp-handler.ts) resolves a
8
+ * token subject through it at request time, `provisionIdpIdentityMapping`
9
+ * (src/lib/mcp-enable.ts) is the operator-facing layer that writes and
10
+ * maintains it (the MCP and XAA JIT provisioners also create one when their
11
+ * lookup finds none), and the XAA jwt-bearer grant (resources/XAA.ts,
12
+ * `resolveOrCreatePrincipalLocked`) resolves an ID-JAG subject through it.
13
+ * Before this module the resolver and the linker accepted every status except
14
+ * `"revoked"`, so a principal-bearing row with a missing, empty or unknown
15
+ * status was served as a live mapping; on the resolver's path a revoked row was
16
+ * also skipped, so it could re-create a principal when JIT provisioning was
17
+ * enabled. XAA already accepted only `"active"` (flair#2501). All three sites
18
+ * now use this module's shared rule for row usability.
19
+ *
20
+ * The rule is an ALLOWLIST: a credential is usable only when its `status` is
21
+ * exactly `"active"`. Missing, empty, `"revoked"` and any other value are not
22
+ * usable. All three sites apply `credentialMapsPrincipal`: the row must also
23
+ * name a principal, a non-empty string `principalId`. The schema requires
24
+ * `principalId` and Harper refuses a write that omits it, but it stores an
25
+ * empty string, and no site relies on the schema to exclude a row without one.
26
+ *
27
+ * Deliberately dependency-free (it imports nothing): the resource/CLI boundary
28
+ * guard (test/unit/resource-src-purity-1775.test.ts) requires every src/ module
29
+ * a resources/ file imports to emit no module loads, and src/ must never import
30
+ * harper.
31
+ */
32
+ /** The only `status` value a Credential is usable with. */
33
+ export const CREDENTIAL_STATUS_ACTIVE = "active";
34
+ /**
35
+ * Is `cred` a credential this rule accepts as usable? Exactly
36
+ * `status === "active"`. A null/undefined credential, a missing status, an
37
+ * empty string, `"revoked"` and any other value are all not usable.
38
+ */
39
+ export function isUsableCredential(cred) {
40
+ return cred?.status === CREDENTIAL_STATUS_ACTIVE;
41
+ }
42
+ /**
43
+ * The principal `cred` names: its `principalId` when that is a non-empty
44
+ * string, otherwise null. The resolver, the linker and XAA all decide "names
45
+ * no principal" with this one test.
46
+ */
47
+ export function credentialPrincipalId(cred) {
48
+ const principalId = cred?.principalId;
49
+ return typeof principalId === "string" && principalId !== "" ? principalId : null;
50
+ }
51
+ /**
52
+ * Does `cred` map a principal? It must be usable (`status === "active"`) and
53
+ * name a principal. Anything else maps nothing.
54
+ */
55
+ export function credentialMapsPrincipal(cred) {
56
+ return isUsableCredential(cred) && credentialPrincipalId(cred) !== null;
57
+ }
58
+ /** How a refusal names the status it found: the stored value, or that none was there. */
59
+ function credentialStatusPhrase(status) {
60
+ return status === undefined || status === null ? "no status" : `status ${JSON.stringify(status)}`;
61
+ }
62
+ /**
63
+ * The named refusal for a Credential that maps no principal: it names the
64
+ * actor (the named credential — pass the surrounding subject too when the
65
+ * caller has one), the state (the stored status, or that there is none, and,
66
+ * when applicable, that it names no principal) and the remedy (an operator
67
+ * re-links the subject, which writes an active mapping that names its
68
+ * principal). The resolver builds its JSON-RPC refusal from this, so that
69
+ * wording has one home.
70
+ */
71
+ export function credentialRefusal(actor, cred) {
72
+ const state = credentialPrincipalId(cred) === null
73
+ ? `${credentialStatusPhrase(cred?.status)} and names no principal`
74
+ : credentialStatusPhrase(cred?.status);
75
+ return (`forbidden: ${actor} has ${state}; a Credential is usable only when its status is "active" and it names a ` +
76
+ "principal, so it was not used and nothing was written. An operator must re-link the credential " +
77
+ "(`flair mcp enable`, or `flair principal link`) to write an active mapping.");
78
+ }
@@ -0,0 +1,37 @@
1
+ /** Named agents in the warning before the remainder is folded into a count. */
2
+ export const EXPIRED_BY_AGENT_NAMED_MAX = 5;
3
+ export function summarizeExpiredByAgent(counts, driver, max = EXPIRED_BY_AGENT_NAMED_MAX) {
4
+ const positive = [...counts].filter(([, n]) => n > 0);
5
+ const entries = positive.filter(([id]) => id !== "");
6
+ entries.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
7
+ const keep = Math.max(0, max);
8
+ const named = entries.slice(0, keep);
9
+ const rest = entries.slice(keep);
10
+ const installedFor = (agentId) => driver.installed !== true ? driver.installed : driver.agentKnown ? agentId === driver.agent : null;
11
+ return {
12
+ agents: named.map(([agentId, count]) => ({ agentId, count, nightlyDriverInstalled: installedFor(agentId) })),
13
+ agentCount: entries.length,
14
+ total: positive.reduce((sum, [, n]) => sum + n, 0),
15
+ remainderCount: rest.reduce((sum, [, n]) => sum + n, 0),
16
+ unownedCount: positive.filter(([id]) => id === "").reduce((sum, [, n]) => sum + n, 0),
17
+ };
18
+ }
19
+ export function expiredByAgentWarningLines(b) {
20
+ if (b.total === 0)
21
+ return "";
22
+ const lines = [" grouped by agent:\n"];
23
+ for (const a of b.agents) {
24
+ const state = a.nightlyDriverInstalled === true
25
+ ? "installed nightly scheduler names this agent"
26
+ : a.nightlyDriverInstalled === false
27
+ ? "NO matching installed nightly scheduler"
28
+ : "nightly driver state unknown";
29
+ lines.push(` ${a.agentId}: ${a.count} — ${state}\n`);
30
+ }
31
+ const remaining = b.agentCount - b.agents.length;
32
+ if (remaining > 0)
33
+ lines.push(` and ${remaining} more agent(s) (${b.remainderCount} expired rows)\n`);
34
+ if (b.unownedCount > 0)
35
+ lines.push(` ${b.unownedCount} expired row(s) with no agent id\n`);
36
+ return lines.join("");
37
+ }