@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
@@ -0,0 +1,612 @@
1
+ /**
2
+ * backup-approval-store.ts — the target host's local store of approved backup
3
+ * archives (flair#2664 slice 1c).
4
+ *
5
+ * The operator approves exact archive bytes on the host that will restore
6
+ * them. The store is plain files under the operator's home, never a Harper
7
+ * table, and nothing on the server's REST surface reads or writes it:
8
+ *
9
+ * ~/.flair/approved-archives/ 0700, owned by the current user
10
+ * archives/ 0700
11
+ * <sha256>.json 0600, the archive's exact bytes
12
+ * approvals/ 0700
13
+ * <sha256>.json 0600, the approval record
14
+ *
15
+ * Every store operation checks the root, both directories and every entry in
16
+ * them before it creates anything in the store or reads a store file
17
+ * (openStore); approval also checks this digest's existing record and stored
18
+ * copy before it creates a missing directory. (The CLI reads the operator's
19
+ * import file before it opens the store.) Each directory must be a real
20
+ * directory (not a symbolic link) owned by the current user with mode exactly
21
+ * 0700. In the root only `archives` and `approvals` may appear. In those, a
22
+ * managed record or archive file (`<sha256>.json`) must be a regular file
23
+ * owned by the current user with mode exactly 0600. The one exception is a
24
+ * temp file an interrupted approval left (`.<sha256>.<pid>.<random>.tmp`),
25
+ * which must be a regular file owned by the current user with no group or
26
+ * other permission and is otherwise ignored. Any other entry refuses. A
27
+ * refusal of the existing state names the path and creates or changes
28
+ * nothing. A failure while writing (a full disk, say) can leave a directory
29
+ * the approval created and a temp file, never a record for bytes the store
30
+ * does not hold. The store creates what is missing with exact modes, whatever
31
+ * the umask, and never loosens or repairs an existing entry.
32
+ *
33
+ * Stored archives are content-addressed, no-clobber copies whose bytes are
34
+ * rechecked on use: an archive is published under the SHA-256 of its bytes
35
+ * with a link that never replaces an existing file, and a copy already there
36
+ * is reused only when its bytes still hash to its name. Nothing prevents
37
+ * another writer with the operator's file access from changing a stored file,
38
+ * which is why use rechecks it. A record names the digest, how it was
39
+ * admitted (`sidecar`: the archive matched its detached digest; `legacy`: an
40
+ * archive with no sidecar, whose digest the operator confirmed), the approval
41
+ * time and operator, and, once revoked, the revocation time and operator.
42
+ *
43
+ * Approval writes a record only after the archive copy is published and read
44
+ * back to the approved digest. So a fresh approval that fails or is
45
+ * interrupted before the record is published leaves no new record (once the
46
+ * record rename succeeds, a process killed before reporting success leaves a
47
+ * valid approval without a success message), and a failed re-approval does not publish
48
+ * a new one: a record that was already there stays as it was (and use still
49
+ * rechecks its stored copy).
50
+ *
51
+ * Using an approval (loadApprovedArchive) rechecks it: the record must be
52
+ * well formed and unrevoked, and the stored copy is read once, hashed and
53
+ * parsed from that one buffer, and must hash to the approved digest.
54
+ *
55
+ * Imports refuse a path whose last component is a symbolic link, anything but
56
+ * a regular file, and a file inside the store. Files are opened with
57
+ * O_NOFOLLOW where the platform has it, and checked through the open
58
+ * descriptor.
59
+ *
60
+ * An approval admits those bytes to `flair restore` on this host until it is
61
+ * revoked; restoring the promotion verdicts in an archive is not part of it
62
+ * yet (the server refuses an absent Memory row that carries one). It does not
63
+ * establish where the archive came
64
+ * from, that a past promotion decision was right, or that an archive without
65
+ * a sidecar is unchanged since it was written.
66
+ */
67
+ import { createHash, randomBytes } from "node:crypto";
68
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeSync, chmodSync, } from "node:fs";
69
+ import { dirname, join, resolve, sep } from "node:path";
70
+ import { fsyncDir } from "./atomic-write.js";
71
+ import { resolveHome } from "./home.js";
72
+ import { parseRestoreArchive, parseStrictJson } from "./restore-archive.js";
73
+ /** The store's directory name under `~/.flair`. */
74
+ export const APPROVAL_STORE_DIRNAME = "approved-archives";
75
+ /** `~/.flair/approved-archives`, resolved at call time. */
76
+ export function defaultApprovalStoreRoot(home = resolveHome()) {
77
+ return join(home, ".flair", APPROVAL_STORE_DIRNAME);
78
+ }
79
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
80
+ const RECORD_VERSION = 1;
81
+ const RECORD_KEYS = ["version", "sha256", "admission", "approvedAt", "approvedBy", "archiveName", "size", "revokedAt", "revokedBy"];
82
+ /** A refusal from the store, with a message naming the path and what did not hold. */
83
+ export class ApprovalStoreError extends Error {
84
+ code;
85
+ constructor(code, message) {
86
+ super(message);
87
+ this.name = "ApprovalStoreError";
88
+ this.code = code;
89
+ }
90
+ }
91
+ /** The approval publication steps, in order. */
92
+ export const APPROVAL_PUBLISH_STEPS = Object.freeze([
93
+ "open-store",
94
+ "stage-archive",
95
+ "publish-archive",
96
+ "verify-archive",
97
+ "stage-record",
98
+ "publish-record",
99
+ ]);
100
+ // ─── File-system checks ──────────────────────────────────────────────────────
101
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
102
+ const NONBLOCK = constants.O_NONBLOCK ?? 0;
103
+ function currentUid(options) {
104
+ if (options.uid !== undefined)
105
+ return options.uid;
106
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
107
+ }
108
+ function storeUnsafe(message) {
109
+ return new ApprovalStoreError("store-unsafe", message);
110
+ }
111
+ function errnoCode(error) {
112
+ const code = error?.code;
113
+ return typeof code === "string" ? code : undefined;
114
+ }
115
+ function modeText(mode) {
116
+ return (mode & 0o777).toString(8).padStart(3, "0");
117
+ }
118
+ /** Refuse unless `st` (from lstat) is a real directory owned by `uid` with mode 0700. */
119
+ function checkPrivateDirectory(path, st, uid) {
120
+ if (st.isSymbolicLink())
121
+ throw storeUnsafe(`approval store directory ${path} is a symbolic link; the store refuses it`);
122
+ if (!st.isDirectory())
123
+ throw storeUnsafe(`approval store path ${path} is not a directory; the store refuses it`);
124
+ if (uid !== undefined && st.uid !== uid) {
125
+ throw storeUnsafe(`approval store directory ${path} is owned by uid ${st.uid}, not the current user (uid ${uid}); the store refuses it`);
126
+ }
127
+ if ((st.mode & 0o777) !== 0o700) {
128
+ throw storeUnsafe(`approval store directory ${path} has mode ${modeText(st.mode)}, not 700; the store refuses it. ` +
129
+ "If nothing else could have written to it, run chmod 700 on it and check its contents");
130
+ }
131
+ }
132
+ /** Refuse unless `st` (from fstat of an open file) is a regular file owned by `uid` with mode 0600. */
133
+ function checkPrivateFile(path, st, uid) {
134
+ if (!st.isFile())
135
+ throw storeUnsafe(`approval store file ${path} is not a regular file; the store refuses it`);
136
+ if (uid !== undefined && st.uid !== uid) {
137
+ throw storeUnsafe(`approval store file ${path} is owned by uid ${st.uid}, not the current user (uid ${uid}); the store refuses it`);
138
+ }
139
+ if ((st.mode & 0o777) !== 0o600) {
140
+ throw storeUnsafe(`approval store file ${path} has mode ${modeText(st.mode)}, not 600; the store refuses it`);
141
+ }
142
+ }
143
+ /**
144
+ * Read a whole regular file without following a symbolic link in its last
145
+ * component. `check` runs on the open descriptor's stat. Throws the
146
+ * underlying error for a missing file (ENOENT) so callers can tell absence
147
+ * from refusal.
148
+ */
149
+ function readNoFollow(path, describe, check, unsafe) {
150
+ if (NOFOLLOW === 0) {
151
+ // No O_NOFOLLOW on this platform: check the last component before opening.
152
+ const st = lstatSync(path);
153
+ if (st.isSymbolicLink())
154
+ throw unsafe(`${describe} ${path} is a symbolic link`);
155
+ }
156
+ let fd;
157
+ try {
158
+ fd = openSync(path, constants.O_RDONLY | NOFOLLOW | NONBLOCK);
159
+ }
160
+ catch (error) {
161
+ if (errnoCode(error) === "ELOOP")
162
+ throw unsafe(`${describe} ${path} is a symbolic link`);
163
+ throw error;
164
+ }
165
+ try {
166
+ const st = fstatSync(fd);
167
+ check(st);
168
+ return readFileSync(fd);
169
+ }
170
+ finally {
171
+ closeSync(fd);
172
+ }
173
+ }
174
+ /** Write `bytes` to a new file (no-clobber), with exactly mode 0600, and fsync it. */
175
+ function writeNewPrivateFile(path, bytes) {
176
+ const fd = openSync(path, "wx", 0o600);
177
+ try {
178
+ let offset = 0;
179
+ while (offset < bytes.length)
180
+ offset += writeSync(fd, bytes, offset, bytes.length - offset);
181
+ fchmodSync(fd, 0o600);
182
+ fsyncSync(fd);
183
+ }
184
+ finally {
185
+ closeSync(fd);
186
+ }
187
+ }
188
+ function tempPath(dir, name) {
189
+ return join(dir, `.${name}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
190
+ }
191
+ function removeQuietly(path) {
192
+ try {
193
+ unlinkSync(path);
194
+ }
195
+ catch { /* best effort: it may never have been created */ }
196
+ }
197
+ function storePaths(options) {
198
+ const root = resolve(options.root ?? defaultApprovalStoreRoot());
199
+ return { root, archives: join(root, "archives"), approvals: join(root, "approvals") };
200
+ }
201
+ /** lstat `path`, or undefined when it does not exist. */
202
+ function lstatOrUndefined(path) {
203
+ try {
204
+ return lstatSync(path);
205
+ }
206
+ catch (error) {
207
+ if (errnoCode(error) === "ENOENT")
208
+ return undefined;
209
+ throw error;
210
+ }
211
+ }
212
+ /** Create `path` with mode exactly 0700 when it is missing; then require it to be a private directory. */
213
+ function ensurePrivateDirectory(path, uid) {
214
+ if (lstatOrUndefined(path) === undefined) {
215
+ try {
216
+ mkdirSync(path, { mode: 0o700 });
217
+ // mkdir's mode is narrowed by the umask; set it exactly. The directory
218
+ // was created by this call, so nothing else has had it at a wider mode.
219
+ chmodSync(path, 0o700);
220
+ }
221
+ catch (error) {
222
+ if (errnoCode(error) !== "EEXIST")
223
+ throw error;
224
+ }
225
+ }
226
+ checkPrivateDirectory(path, lstatSync(path), uid);
227
+ }
228
+ const MANAGED_FILE = /^[0-9a-f]{64}\.json$/;
229
+ const TEMP_FILE = /^\.[0-9a-f]{64}\.\d+\.[0-9a-f]{8}\.tmp$/;
230
+ const ROOT_ENTRIES = new Set(["archives", "approvals"]);
231
+ /**
232
+ * Check every entry of an existing store directory. In the root only
233
+ * `archives` and `approvals` may appear. In those two, a managed file
234
+ * (`<sha256>.json`) must be a regular file owned by `uid` with mode exactly
235
+ * 0600; a temp file an interrupted approval left (`.<sha256>.<pid>.<random>.tmp`)
236
+ * must be a regular file owned by `uid` with no group or other permission,
237
+ * and is otherwise ignored. Any other entry refuses.
238
+ */
239
+ function checkEntries(dir, isRoot, uid) {
240
+ for (const name of readdirSync(dir)) {
241
+ const path = join(dir, name);
242
+ if (isRoot) {
243
+ if (!ROOT_ENTRIES.has(name))
244
+ throw storeUnsafe(`approval store entry ${path} is not archives or approvals; the store refuses it`);
245
+ continue;
246
+ }
247
+ const managed = MANAGED_FILE.test(name);
248
+ if (!managed && !TEMP_FILE.test(name)) {
249
+ throw storeUnsafe(`approval store entry ${path} is not <sha256>.json or an approval's temp file; the store refuses it`);
250
+ }
251
+ const st = lstatSync(path);
252
+ if (st.isSymbolicLink())
253
+ throw storeUnsafe(`approval store file ${path} is a symbolic link; the store refuses it`);
254
+ if (managed) {
255
+ checkPrivateFile(path, st, uid);
256
+ }
257
+ else {
258
+ if (!st.isFile())
259
+ throw storeUnsafe(`approval store file ${path} is not a regular file; the store refuses it`);
260
+ if (uid !== undefined && st.uid !== uid) {
261
+ throw storeUnsafe(`approval store file ${path} is owned by uid ${st.uid}, not the current user (uid ${uid}); the store refuses it`);
262
+ }
263
+ if ((st.mode & 0o077) !== 0)
264
+ throw storeUnsafe(`approval store file ${path} has mode ${modeText(st.mode)}, readable by others; the store refuses it`);
265
+ }
266
+ }
267
+ }
268
+ /**
269
+ * Open the store. Every directory that already exists is checked, and so is
270
+ * every entry in it (checkEntries), before anything is created; with
271
+ * `create`, the missing directories are then created (the parent of the
272
+ * root with mode 0700 when it is missing too). Returns undefined when the
273
+ * store does not exist and `create` is false.
274
+ */
275
+ function openStore(options, create) {
276
+ const paths = storePaths(options);
277
+ const uid = currentUid(options);
278
+ const rootStat = lstatOrUndefined(paths.root);
279
+ if (rootStat === undefined && !create)
280
+ return undefined;
281
+ const existing = [];
282
+ if (rootStat !== undefined) {
283
+ checkPrivateDirectory(paths.root, rootStat, uid);
284
+ existing.push([paths.root, true]);
285
+ for (const dir of [paths.archives, paths.approvals]) {
286
+ const sub = lstatOrUndefined(dir);
287
+ if (sub === undefined)
288
+ continue;
289
+ checkPrivateDirectory(dir, sub, uid);
290
+ existing.push([dir, false]);
291
+ }
292
+ }
293
+ for (const [dir, isRoot] of existing)
294
+ checkEntries(dir, isRoot, uid);
295
+ if (!create)
296
+ return paths;
297
+ const parent = dirname(paths.root);
298
+ if (lstatOrUndefined(parent) === undefined)
299
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
300
+ ensurePrivateDirectory(paths.root, uid);
301
+ ensurePrivateDirectory(paths.archives, uid);
302
+ ensurePrivateDirectory(paths.approvals, uid);
303
+ return paths;
304
+ }
305
+ // ─── Records ─────────────────────────────────────────────────────────────────
306
+ function isRecord(value) {
307
+ return value !== null && typeof value === "object" && !Array.isArray(value);
308
+ }
309
+ function nonEmptyString(value) {
310
+ return typeof value === "string" && value.length > 0;
311
+ }
312
+ /** Parse an approval record file's bytes; `sha256` is the digest its file name claims. */
313
+ export function parseApprovalRecord(bytes, sha256) {
314
+ let text;
315
+ try {
316
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
317
+ }
318
+ catch {
319
+ return { ok: false, reason: "the record is not UTF-8" };
320
+ }
321
+ const parsed = parseStrictJson(text);
322
+ if (parsed.ok === false)
323
+ return { ok: false, reason: `the record is not valid JSON (${parsed.reason})` };
324
+ const value = parsed.value;
325
+ if (!isRecord(value))
326
+ return { ok: false, reason: "the record is not a JSON object" };
327
+ const keys = Object.keys(value).sort();
328
+ const expected = [...RECORD_KEYS].sort();
329
+ if (keys.length !== expected.length || keys.some((key, index) => key !== expected[index])) {
330
+ return { ok: false, reason: `the record's fields are not exactly ${RECORD_KEYS.join(", ")}` };
331
+ }
332
+ if (value.version !== RECORD_VERSION)
333
+ return { ok: false, reason: `the record version is not ${RECORD_VERSION}` };
334
+ if (value.sha256 !== sha256)
335
+ return { ok: false, reason: "the record's sha256 does not match its file name" };
336
+ if (value.admission !== "sidecar" && value.admission !== "legacy")
337
+ return { ok: false, reason: "the record's admission is not sidecar or legacy" };
338
+ if (!nonEmptyString(value.approvedAt) || !nonEmptyString(value.approvedBy)) {
339
+ return { ok: false, reason: "the record has no approval time or operator" };
340
+ }
341
+ if (typeof value.archiveName !== "string")
342
+ return { ok: false, reason: "the record's archiveName is not a string" };
343
+ if (typeof value.size !== "number" || !Number.isSafeInteger(value.size) || value.size < 0) {
344
+ return { ok: false, reason: "the record's size is not a non-negative integer" };
345
+ }
346
+ const revokedAt = value.revokedAt;
347
+ const revokedBy = value.revokedBy;
348
+ const bothNull = revokedAt === null && revokedBy === null;
349
+ if (!bothNull && !(nonEmptyString(revokedAt) && nonEmptyString(revokedBy))) {
350
+ return { ok: false, reason: "the record's revokedAt and revokedBy are not both null or both set" };
351
+ }
352
+ return { ok: true, record: value };
353
+ }
354
+ function serializeRecord(record) {
355
+ const ordered = Object.fromEntries(RECORD_KEYS.map((key) => [key, record[key]]));
356
+ return Buffer.from(JSON.stringify(ordered, null, 2) + "\n", "utf-8");
357
+ }
358
+ function requireDigest(sha256) {
359
+ if (!SHA256_HEX.test(sha256))
360
+ throw new ApprovalStoreError("invalid-digest", `${JSON.stringify(sha256)} is not a lowercase hex SHA-256 digest`);
361
+ }
362
+ /** Read and check a record; undefined when it does not exist. */
363
+ function readRecord(paths, sha256, uid) {
364
+ const path = join(paths.approvals, `${sha256}.json`);
365
+ let bytes;
366
+ try {
367
+ bytes = readNoFollow(path, "approval record", (st) => checkPrivateFile(path, st, uid), storeUnsafe);
368
+ }
369
+ catch (error) {
370
+ if (errnoCode(error) === "ENOENT")
371
+ return undefined;
372
+ throw error;
373
+ }
374
+ const parsed = parseApprovalRecord(bytes, sha256);
375
+ if (parsed.ok === false) {
376
+ throw new ApprovalStoreError("record-invalid", `approval record ${path} is invalid (${parsed.reason}); the store refuses it`);
377
+ }
378
+ return parsed.record;
379
+ }
380
+ /** Atomically replace (or create) a record: stage, fsync, rename, fsync the directory. */
381
+ function writeRecord(paths, record, step) {
382
+ const final = join(paths.approvals, `${record.sha256}.json`);
383
+ step("stage-record");
384
+ const staged = tempPath(paths.approvals, record.sha256);
385
+ try {
386
+ writeNewPrivateFile(staged, serializeRecord(record));
387
+ step("publish-record");
388
+ renameSync(staged, final);
389
+ }
390
+ catch (error) {
391
+ removeQuietly(staged);
392
+ throw error;
393
+ }
394
+ fsyncDir(paths.approvals);
395
+ }
396
+ // ─── Stored archives ─────────────────────────────────────────────────────────
397
+ /** Read the stored copy of `sha256` once; undefined when it does not exist. */
398
+ function readStoredArchive(paths, sha256, uid) {
399
+ const path = join(paths.archives, `${sha256}.json`);
400
+ try {
401
+ return readNoFollow(path, "stored archive", (st) => checkPrivateFile(path, st, uid), storeUnsafe);
402
+ }
403
+ catch (error) {
404
+ if (errnoCode(error) === "ENOENT")
405
+ return undefined;
406
+ throw error;
407
+ }
408
+ }
409
+ const sha256Of = (bytes) => createHash("sha256").update(bytes).digest("hex");
410
+ // ─── Import ──────────────────────────────────────────────────────────────────
411
+ /**
412
+ * Read a file the operator names for import, once. Refuses a symbolic link in
413
+ * the last path component, anything but a regular file, and a file inside the
414
+ * store. Throws the underlying error (ENOENT included) for an unreadable path.
415
+ */
416
+ export function readImportFile(path, describe, options = {}) {
417
+ const importUnsafe = (message) => new ApprovalStoreError("import-unsafe", `refusing to import ${message}`);
418
+ const bytes = readNoFollow(path, describe, (st) => {
419
+ if (!st.isFile())
420
+ throw importUnsafe(`${describe} ${path}: it is not a regular file`);
421
+ }, (message) => importUnsafe(message));
422
+ const root = storePaths(options).root;
423
+ let real;
424
+ let realRoot;
425
+ try {
426
+ real = realpathSync(path);
427
+ realRoot = lstatOrUndefined(root) === undefined ? undefined : realpathSync(root);
428
+ }
429
+ catch (error) {
430
+ throw new ApprovalStoreError("import-unreadable", `cannot resolve ${describe} ${path} (${errnoCode(error) ?? "error"})`);
431
+ }
432
+ if (realRoot !== undefined && (real === realRoot || real.startsWith(realRoot + sep))) {
433
+ throw importUnsafe(`${describe} ${path}: it is inside the approval store`);
434
+ }
435
+ return bytes;
436
+ }
437
+ // ─── Approval ────────────────────────────────────────────────────────────────
438
+ function changedStoredCopy(paths, sha256) {
439
+ return new ApprovalStoreError("stored-mismatch", `stored archive ${join(paths.archives, `${sha256}.json`)} no longer hashes to ${sha256}; the store refuses to reuse it. ` +
440
+ "Move it out of the store and approve the archive again");
441
+ }
442
+ /**
443
+ * Record an approval: check the store as it stands, create any missing
444
+ * directory, publish the archive bytes under their digest (reusing a stored
445
+ * copy that still hashes to it), read them back, then publish the record.
446
+ * Replaces an existing record for the digest, revoked or not. Throws an
447
+ * ApprovalStoreError (or the underlying I/O error) when approval does not
448
+ * complete. A refusal of the existing state (an unsafe directory or entry,
449
+ * an invalid record, a stored copy that no longer hashes to its name) comes
450
+ * before anything is created. No record is written or changed before the
451
+ * stored copy is verified, so a failure leaves any existing record as it was.
452
+ */
453
+ export function approveArchive(input, options = {}, hooks = {}) {
454
+ const step = hooks.beforeStep ?? (() => { });
455
+ requireDigest(input.sha256);
456
+ if (sha256Of(input.bytes) !== input.sha256) {
457
+ throw new ApprovalStoreError("stored-mismatch", "the archive bytes do not hash to the digest being approved; nothing was stored");
458
+ }
459
+ if (!nonEmptyString(input.operator))
460
+ throw new ApprovalStoreError("record-invalid", "an approval needs a non-empty operator name");
461
+ const uid = currentUid(options);
462
+ step("open-store");
463
+ // Check the store as it stands (its directories, every entry, this
464
+ // digest's record and its stored copy) before creating any missing
465
+ // directory, so a refusal of existing state creates nothing.
466
+ const found = openStore(options, false);
467
+ if (found !== undefined) {
468
+ readRecord(found, input.sha256, uid);
469
+ const prior = readStoredArchive(found, input.sha256, uid);
470
+ if (prior !== undefined && sha256Of(prior) !== input.sha256)
471
+ throw changedStoredCopy(found, input.sha256);
472
+ }
473
+ const paths = openStore(options, true);
474
+ const final = join(paths.archives, `${input.sha256}.json`);
475
+ const existing = readStoredArchive(paths, input.sha256, uid);
476
+ if (existing !== undefined && sha256Of(existing) !== input.sha256)
477
+ throw changedStoredCopy(paths, input.sha256);
478
+ if (existing === undefined) {
479
+ step("stage-archive");
480
+ const staged = tempPath(paths.archives, input.sha256);
481
+ try {
482
+ writeNewPrivateFile(staged, input.bytes);
483
+ step("publish-archive");
484
+ // No-clobber: a stored archive is never replaced.
485
+ linkSync(staged, final);
486
+ }
487
+ catch (error) {
488
+ removeQuietly(staged);
489
+ if (errnoCode(error) === "EEXIST") {
490
+ throw new ApprovalStoreError("stored-mismatch", `stored archive ${final} appeared while approving; run the approval again`);
491
+ }
492
+ throw error;
493
+ }
494
+ removeQuietly(staged);
495
+ fsyncDir(paths.archives);
496
+ }
497
+ step("verify-archive");
498
+ const stored = readStoredArchive(paths, input.sha256, uid);
499
+ if (stored === undefined || sha256Of(stored) !== input.sha256) {
500
+ throw new ApprovalStoreError("stored-mismatch", `stored archive ${final} does not read back to ${input.sha256}; no approval was recorded`);
501
+ }
502
+ const record = {
503
+ version: RECORD_VERSION,
504
+ sha256: input.sha256,
505
+ admission: input.admission,
506
+ approvedAt: input.now ?? new Date().toISOString(),
507
+ approvedBy: input.operator,
508
+ archiveName: input.archiveName,
509
+ size: stored.length,
510
+ revokedAt: null,
511
+ revokedBy: null,
512
+ };
513
+ writeRecord(paths, record, step);
514
+ return record;
515
+ }
516
+ /** Revoke the approval of `sha256`. Throws when there is none or it is already revoked. */
517
+ export function revokeApproval(sha256, operator, options = {}, now) {
518
+ requireDigest(sha256);
519
+ if (!nonEmptyString(operator))
520
+ throw new ApprovalStoreError("record-invalid", "a revocation needs a non-empty operator name");
521
+ const uid = currentUid(options);
522
+ const paths = openStore(options, false);
523
+ const record = paths === undefined ? undefined : readRecord(paths, sha256, uid);
524
+ if (paths === undefined || record === undefined) {
525
+ throw new ApprovalStoreError("not-approved", `no approval of ${sha256} exists on this host`);
526
+ }
527
+ if (record.revokedAt !== null) {
528
+ throw new ApprovalStoreError("already-revoked", `the approval of ${sha256} was already revoked at ${record.revokedAt} by ${record.revokedBy}`);
529
+ }
530
+ const revoked = { ...record, revokedAt: now ?? new Date().toISOString(), revokedBy: operator };
531
+ writeRecord(paths, revoked, () => { });
532
+ return revoked;
533
+ }
534
+ /** Every approval record, sorted by approval time, each with its stored copy checked. */
535
+ export function listApprovals(options = {}) {
536
+ const uid = currentUid(options);
537
+ const paths = openStore(options, false);
538
+ if (paths === undefined || lstatOrUndefined(paths.approvals) === undefined)
539
+ return [];
540
+ const listed = [];
541
+ for (const name of readdirSync(paths.approvals).sort()) {
542
+ // A temp file an interrupted approval left; openStore already checked it.
543
+ if (TEMP_FILE.test(name))
544
+ continue;
545
+ const sha256 = name.endsWith(".json") ? name.slice(0, -".json".length) : "";
546
+ if (!SHA256_HEX.test(sha256)) {
547
+ throw storeUnsafe(`approval store entry ${join(paths.approvals, name)} is not <sha256>.json; the store refuses it`);
548
+ }
549
+ const record = readRecord(paths, sha256, uid);
550
+ let stored;
551
+ try {
552
+ const bytes = readStoredArchive(paths, sha256, uid);
553
+ stored = bytes === undefined ? "missing" : sha256Of(bytes) === sha256 ? "intact" : "does-not-match";
554
+ }
555
+ catch (error) {
556
+ if (!(error instanceof ApprovalStoreError))
557
+ throw error;
558
+ stored = "unsafe";
559
+ }
560
+ listed.push({ record, stored });
561
+ }
562
+ return listed.sort((a, b) => a.record.approvedAt.localeCompare(b.record.approvedAt) || a.record.sha256.localeCompare(b.record.sha256));
563
+ }
564
+ /**
565
+ * Load the approved bytes for `sha256` and recheck them: the record must
566
+ * exist, be well formed and be unrevoked; the stored copy is read once, and
567
+ * that one buffer must hash to `sha256` and parse as a restorable archive.
568
+ * Never creates or changes anything.
569
+ */
570
+ export function loadApprovedArchive(sha256, options = {}) {
571
+ if (!SHA256_HEX.test(sha256))
572
+ return { ok: false, code: "not-approved", reason: `${sha256} is not a SHA-256 digest` };
573
+ const uid = currentUid(options);
574
+ let paths;
575
+ let record;
576
+ try {
577
+ paths = openStore(options, false);
578
+ record = paths === undefined ? undefined : readRecord(paths, sha256, uid);
579
+ }
580
+ catch (error) {
581
+ if (!(error instanceof ApprovalStoreError))
582
+ throw error;
583
+ return { ok: false, code: error.code === "record-invalid" ? "record-invalid" : "store-unsafe", reason: error.message };
584
+ }
585
+ if (paths === undefined || record === undefined) {
586
+ return { ok: false, code: "not-approved", reason: `no approval of ${sha256} exists on this host` };
587
+ }
588
+ if (record.revokedAt !== null) {
589
+ return { ok: false, code: "revoked", record, reason: `the approval of ${sha256} on this host was revoked at ${record.revokedAt} by ${record.revokedBy}` };
590
+ }
591
+ const path = join(paths.archives, `${sha256}.json`);
592
+ let bytes;
593
+ try {
594
+ bytes = readStoredArchive(paths, sha256, uid);
595
+ }
596
+ catch (error) {
597
+ if (!(error instanceof ApprovalStoreError))
598
+ throw error;
599
+ return { ok: false, code: "store-unsafe", record, reason: error.message };
600
+ }
601
+ if (bytes === undefined) {
602
+ return { ok: false, code: "stored-missing", record, reason: `the approved copy ${path} is missing` };
603
+ }
604
+ const parsed = parseRestoreArchive(bytes);
605
+ if (parsed.sha256 !== sha256) {
606
+ return { ok: false, code: "stored-mismatch", record, reason: `the approved copy ${path} no longer hashes to ${sha256} (it hashes to ${parsed.sha256})` };
607
+ }
608
+ if (parsed.ok === false) {
609
+ return { ok: false, code: "archive-refused", record, reason: `the approved copy ${path} is not a restorable archive (${parsed.reason})` };
610
+ }
611
+ return { ok: true, record, archive: parsed.archive, sha256 };
612
+ }