@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
@@ -15,6 +15,12 @@
15
15
  * - mise: `$MISE_DATA_DIR | ~/.local/share/mise` + `/installs/node/<major>/bin/node`.
16
16
  * mise keeps `installs/node/<major>` as a symlink to the newest installed
17
17
  * runtime of that major, so it resolves to the same binary and is written.
18
+ * - Homebrew: `<prefix>/Cellar/<formula>/<version>/bin/node` (a realpath into
19
+ * the Cellar) has the alias `<prefix>/opt/<formula>/bin/node`, where
20
+ * `<prefix>` is taken from the path (so /opt/homebrew and /usr/local both
21
+ * work) and `<formula>` is `node` or a versioned `node@NN`. `brew upgrade
22
+ * node` repoints `opt/node` at the new version, and upgrade cleanup can
23
+ * remove the old Cellar directory.
18
24
  * - Volta: `$VOLTA_HOME | ~/.volta` + `/bin/node`. Considered, but a standard
19
25
  * Volta install makes that path a link to `volta-shim`, whose realpath is
20
26
  * not a node binary, so the equality check rejects it and the exact path is
@@ -39,6 +45,44 @@
39
45
  import { existsSync, realpathSync } from "node:fs";
40
46
  import { join } from "node:path";
41
47
  import { resolveHome } from "./home.js";
48
+ const HOMEBREW_CELLAR_RE = /^(.*)\/Cellar\/([^/]+)\/[^/]+\/bin\/node$/;
49
+ const HOMEBREW_FORMULA_RE = /^node(?:@\d+)?$/;
50
+ /**
51
+ * `<prefix>/opt/<formula>/bin/node` for a `<prefix>/Cellar/<formula>/<version>/bin/node`
52
+ * path, else null. A Cellar path carries the version in a segment Homebrew may
53
+ * suffix with a revision (`26.10.0_1`), so this candidate is derived from the
54
+ * path alone.
55
+ */
56
+ function homebrewAliasCandidate(nodeBin) {
57
+ const cellar = HOMEBREW_CELLAR_RE.exec(nodeBin);
58
+ const prefix = cellar?.[1];
59
+ const formula = cellar?.[2];
60
+ if (!prefix || !formula || !prefix.startsWith("/") || !HOMEBREW_FORMULA_RE.test(formula))
61
+ return null;
62
+ return join(prefix, "opt", formula, "bin", "node");
63
+ }
64
+ /**
65
+ * The Homebrew `opt/<formula>/bin/node` alias to record IN PLACE OF an
66
+ * already-recorded `Cellar/<formula>/<version>/bin/node` path (flair#3056):
67
+ * returned only when that alias exists and its realpath equals the recorded
68
+ * path's realpath. null otherwise, including when either realpath cannot be
69
+ * read. mise and Volta candidates are not considered here.
70
+ */
71
+ export function homebrewOptAlias(nodeBin, hooks = {}) {
72
+ const alias = homebrewAliasCandidate(nodeBin);
73
+ if (alias === null)
74
+ return null;
75
+ const exists = hooks.exists ?? existsSync;
76
+ const realpath = hooks.realpath ?? ((p) => realpathSync(p));
77
+ try {
78
+ if (!exists(alias))
79
+ return null;
80
+ return realpath(alias) === realpath(nodeBin) ? alias : null;
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
42
86
  /** `24.19.0` / `v24.19.0` → `24.19.0`; null when no version is present. */
43
87
  export function parseNodeVersion(nodePath) {
44
88
  const m = /(?:^|[/\\])v?(\d+\.\d+\.\d+)(?:[/\\]|$)/.exec(nodePath);
@@ -52,8 +96,11 @@ export function parseNodeVersion(nodePath) {
52
96
  export function aliasCandidates(nodeBin, hooks = {}) {
53
97
  const home = hooks.home ?? resolveHome();
54
98
  const env = hooks.env ?? process.env;
55
- const version = parseNodeVersion(nodeBin);
56
99
  const out = [];
100
+ const brew = homebrewAliasCandidate(nodeBin);
101
+ if (brew)
102
+ out.push({ manager: "homebrew", path: brew });
103
+ const version = parseNodeVersion(nodeBin);
57
104
  if (!version || !home)
58
105
  return out;
59
106
  const major = version.split(".")[0];
@@ -66,7 +113,8 @@ export function aliasCandidates(nodeBin, hooks = {}) {
66
113
  /**
67
114
  * The node path to WRITE into a generated unit: a floating alias whose realpath
68
115
  * is the same binary as `nodeBin`, when one exists; otherwise `nodeBin`
69
- * unchanged. mise's major alias is preferred over Volta's when both match.
116
+ * unchanged. Candidates are tried in aliasCandidates order (Homebrew, then
117
+ * mise's major alias, then Volta's).
70
118
  */
71
119
  export function preferVersionManagerAlias(nodeBin, hooks = {}) {
72
120
  const exists = hooks.exists ?? existsSync;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * open-live-row.ts — the skill writer's "open live" Memory-row predicate
3
+ * (flair#2662), shared so `flair doctor` asks the same question the writer
4
+ * answers. It checks the row's fields and the current time (for `expiresAt`). Deliberately imports nothing (resources
5
+ * importing this compiled helper require it to be load-free).
6
+ *
7
+ * A row is open-live when it is not archived, is not expired (`expiresAt`
8
+ * absent, or a string later than now), and carries no `validTo`.
9
+ */
10
+ export function isOpenLiveRow(row) {
11
+ if (!row || typeof row !== "object")
12
+ return false;
13
+ if (row.archived === true)
14
+ return false;
15
+ if (row.expiresAt != null && (typeof row.expiresAt !== "string" || !(Date.parse(row.expiresAt) > Date.now())))
16
+ return false;
17
+ if (typeof row.validTo === "string" && row.validTo.length > 0)
18
+ return false;
19
+ return true;
20
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * ops-url.ts — derive a remote instance's operations API URL from its Flair
3
+ * base URL, the way every remote flair command does (resolveEffectiveOpsUrl in
4
+ * src/cli.ts, which also honours --ops-target / FLAIR_OPS_TARGET). Shared by
5
+ * src/cli.ts and the deploy channel (src/deploy.ts).
6
+ */
7
+ /** The default operations API port for a self-hosted instance on plain HTTP with no explicit port. */
8
+ export const DEFAULT_OPS_PORT = 19925;
9
+ /** The operations API port of a Harper Fabric cluster. */
10
+ export const FABRIC_OPS_PORT = 9925;
11
+ /** Derive the ops API URL from a Flair base URL.
12
+ * https with effective port 443 (no explicit port, or explicit :443): returns
13
+ * <host>:9925 (FABRIC_OPS_PORT) — the Fabric managed case where port-1/:442
14
+ * is a dead-end.
15
+ * All other cases unchanged:
16
+ * https with non-443 explicit port → port-1 (self-hosted TLS: 19926→19925, 8443→8442)
17
+ * http with explicit port → port-1 (19926→19925)
18
+ * http with no port → DEFAULT_OPS_PORT (19925)
19
+ * Bare hosts are normalised to https:// (effective-443 → Fabric path).
20
+ * Throws on unparseable URLs or out-of-range ports.
21
+ */
22
+ export function resolveOpsUrlFromTarget(targetUrl) {
23
+ // Normalise bare hosts: add https:// prefix so URL parser can handle them.
24
+ const normalised = targetUrl.includes("://") ? targetUrl : `https://${targetUrl}`;
25
+ const url = new URL(normalised);
26
+ // https target with effective port 443 (no explicit port, or explicit :443):
27
+ // this is the Fabric managed case — the ops API is on the well-known Fabric
28
+ // ops port, never REST-adjacent. The port-1 / :442 logic is a dead-end here.
29
+ if (url.protocol === "https:" && (url.port === "" || url.port === "443")) {
30
+ url.port = String(FABRIC_OPS_PORT);
31
+ return url.toString().replace(/\/$/, "");
32
+ }
33
+ // All other cases: unchanged port-1 convention.
34
+ // https with non-443 explicit port → port-1 (self-hosted TLS: 19926→19925, 8443→8442)
35
+ // http with explicit port → port-1 (19926→19925)
36
+ // http with no port → DEFAULT_OPS_PORT (19925)
37
+ const port = parseInt(url.port, 10);
38
+ if (!isNaN(port) && port > 0 && port <= 65535) {
39
+ const opsPort = port - 1;
40
+ if (opsPort < 1)
41
+ throw new Error(`Derived ops port ${opsPort} is out of range; target port must be > 1`);
42
+ url.port = String(opsPort);
43
+ return url.toString().replace(/\/$/, "");
44
+ }
45
+ // No valid explicit port — reject port 0 or out-of-range
46
+ if (url.port !== "" && url.port !== undefined) {
47
+ throw new Error(`Invalid target port: ${url.port} (must be 1-65535)`);
48
+ }
49
+ // No explicit port on http — use the default ops port.
50
+ url.port = String(DEFAULT_OPS_PORT);
51
+ return url.toString().replace(/\/$/, "");
52
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * promotion-content-hash.ts — the promotion content-binding hash (flair#2478)
3
+ * for `src/` callers: restore admission (src/lib/restore-archive.ts,
4
+ * flair#2664).
5
+ *
6
+ * The server computes the same binding in resources/promotion-binding.ts,
7
+ * which the read accessor and the trusted stamp use. The two are separate
8
+ * implementations of one algorithm, SHA-256 over the content as UTF-8, because
9
+ * neither side may import the other: `src/` must not import `resources/`
10
+ * (those imports do not survive npm packaging), and a resource may statically
11
+ * import only `src/` helpers that load no modules at all (flair#1775), while
12
+ * this one loads node:crypto. test/unit/restore-archive-2664.test.ts pins
13
+ * their parity and that no resource imports this module.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ /** SHA-256 of the supplied content as UTF-8 (non-string content is converted with String(); null and undefined hash as ""). */
17
+ export function promotionContentHash(content) {
18
+ const text = typeof content === "string" ? content : content == null ? "" : String(content);
19
+ return createHash("sha256").update(text, "utf8").digest("hex");
20
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * remote-admin-pass.ts — save the Flair administrator password chosen for a
3
+ * remote `flair init` provisioning run BEFORE the cluster change that applies
4
+ * it (flair#3130).
5
+ *
6
+ * Save before the cluster change so a failed save stops provisioning.
7
+ * An existing credential stays in place until the staged value is confirmed.
8
+ * After a password attempt, keep a direct write or remaining sibling.
9
+ */
10
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, } from "node:fs";
11
+ import { randomBytes } from "node:crypto";
12
+ import { basename, dirname, join } from "node:path";
13
+ /** A save/confirm refusal. The caller prints the message (which names the file). */
14
+ export class RemoteAdminPassError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "RemoteAdminPassError";
18
+ }
19
+ }
20
+ let beforeRenameForTests;
21
+ export function setRemoteAdminPassTestHooks(hooks) {
22
+ beforeRenameForTests = hooks?.beforeRename;
23
+ }
24
+ function errnoCode(error) {
25
+ const code = error?.code;
26
+ return typeof code === "string" ? code : undefined;
27
+ }
28
+ const NOFOLLOW = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
29
+ const O_NONBLOCK = process.platform === "win32" ? 0 : constants.O_NONBLOCK;
30
+ function currentUid() {
31
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
32
+ }
33
+ function modeText(mode) {
34
+ return (mode & 0o777).toString(8).padStart(3, "0");
35
+ }
36
+ function assertReplaceableTarget(path, st) {
37
+ if (st.isSymbolicLink()) {
38
+ throw new RemoteAdminPassError(`credential file ${path} is a symbolic link; replace it with a real regular file you own`);
39
+ }
40
+ if (!st.isFile()) {
41
+ throw new RemoteAdminPassError(`credential file ${path} is not a regular file; make it a writable regular file you own`);
42
+ }
43
+ const uid = currentUid();
44
+ if (uid !== undefined && st.uid !== uid) {
45
+ throw new RemoteAdminPassError(`credential file ${path} is owned by another user; move it aside so flair can write a file you own`);
46
+ }
47
+ }
48
+ /** Read the final path's current state, or null when it does not exist. */
49
+ function readTarget(path) {
50
+ try {
51
+ return lstatSync(path);
52
+ }
53
+ catch (error) {
54
+ if (errnoCode(error) === "ENOENT")
55
+ return null;
56
+ throw error;
57
+ }
58
+ }
59
+ function verifySaved(path, expected) {
60
+ // Open once; no-follow on POSIX, ordinary open on Windows. Stat and read
61
+ // through that descriptor.
62
+ let fd;
63
+ try {
64
+ fd = openSync(path, constants.O_RDONLY | NOFOLLOW | O_NONBLOCK);
65
+ }
66
+ catch (error) {
67
+ if (errnoCode(error) === "ELOOP") {
68
+ throw new RemoteAdminPassError(`credential file ${path} is a symbolic link after saving; replace it with a real regular file you own`);
69
+ }
70
+ throw error;
71
+ }
72
+ try {
73
+ const st = fstatSync(fd);
74
+ if (!st.isFile()) {
75
+ throw new RemoteAdminPassError(`credential file ${path} is not a regular file after saving`);
76
+ }
77
+ const uid = currentUid();
78
+ if (uid !== undefined && st.uid !== uid) {
79
+ throw new RemoteAdminPassError(`credential file ${path} is owned by another user after saving`);
80
+ }
81
+ if ((st.mode & 0o077) !== 0) {
82
+ throw new RemoteAdminPassError(`credential file ${path} is accessible to other users after saving (mode ${modeText(st.mode)}); run chmod 600 ${path}`);
83
+ }
84
+ const actual = readFileSync(fd, "utf8");
85
+ if (actual !== expected) {
86
+ throw new RemoteAdminPassError(`credential file ${path} does not hold the saved value after saving`);
87
+ }
88
+ }
89
+ finally {
90
+ closeSync(fd);
91
+ }
92
+ }
93
+ function passes(path, expected) {
94
+ try {
95
+ verifySaved(path, expected);
96
+ return true;
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ }
102
+ /**
103
+ * Save `password` to `path` before the cluster change. Returns a stage whose
104
+ * `confirm()` must run after the change succeeds.
105
+ *
106
+ * - No existing file: writes `path` now (0600); `abort()` is a no-op because
107
+ * the saved value is kept for a later run.
108
+ * - Existing file: writes a mode-0600 sibling and `confirm()` renames it over
109
+ * `path`; `abort()` attempts to remove the sibling and leaves `path` untouched.
110
+ */
111
+ export function stageRemoteAdminPassword(path, password, writeOwnerOnly) {
112
+ const content = password + "\n";
113
+ const current = readTarget(path);
114
+ if (current === null) {
115
+ writeOwnerOnly(path, content);
116
+ return {
117
+ path,
118
+ hadExistingFile: false,
119
+ stagedPath: null,
120
+ stagedFileVerified: false,
121
+ confirm: () => verifySaved(path, content),
122
+ stillValid: () => passes(path, content),
123
+ abort: () => {
124
+ /* the freshly saved value is kept for the next run */
125
+ },
126
+ };
127
+ }
128
+ assertReplaceableTarget(path, current);
129
+ const pending = join(dirname(path), `.${basename(path)}.pending-${process.pid}-${randomBytes(6).toString("hex")}`);
130
+ writeOwnerOnly(pending, content);
131
+ let stagedFileVerified = false;
132
+ return {
133
+ path,
134
+ hadExistingFile: true,
135
+ stagedPath: pending,
136
+ get stagedFileVerified() { return stagedFileVerified; },
137
+ confirm: () => {
138
+ // Check before publishing; leave a remaining sibling for recovery.
139
+ // Rename publishes the checked file unless the staged path is replaced in between.
140
+ stagedFileVerified = false;
141
+ verifySaved(pending, content);
142
+ stagedFileVerified = true;
143
+ beforeRenameForTests?.(pending);
144
+ renameSync(pending, path);
145
+ },
146
+ stillValid: () => passes(pending, content),
147
+ abort: () => {
148
+ try {
149
+ unlinkSync(pending);
150
+ }
151
+ catch (error) {
152
+ if (errnoCode(error) !== "ENOENT")
153
+ throw error;
154
+ }
155
+ },
156
+ };
157
+ }