@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,181 @@
1
+ /**
2
+ * skill-manifest.ts — the structured skills manifest in every successful
3
+ * bootstrap response (flair#2141 S1b, S1). No Harper imports.
4
+ *
5
+ * `resolveSkillManifest` turns an agent's `skill-assignment` Soul rows and the
6
+ * instance's org-scope assignments (OrgSkillAssignment) into two lists:
7
+ * - `skills`: the winners only — `{ name, skillId, scope, priority, source }`,
8
+ * where `skillId` is the skill-tagged Memory row to fetch with `skill_get`.
9
+ * - `diagnostics`: assignments refused (a non-durable source, an
10
+ * equal-priority tie or a non-boolean `optOut`) or superseded, and winners
11
+ * whose skill row does not resolve (unresolved or ambiguous).
12
+ * Candidates are the agent's own assignments (scope "own") plus the org
13
+ * assignments (scope "org") whose names the agent is not opted out of. The
14
+ * priority/tie rules (`resolveActiveSkills`, skill-provenance.ts) run on the
15
+ * candidates; then each winner's skill row is resolved: an own name to the
16
+ * agent's own skill row, an org assignment to its `skillRef`.
17
+ *
18
+ * The manifest strings (`name`, `source`) come from Soul `skill-assignment`
19
+ * rows, and an org entry's `name` from its OrgSkillAssignment row; they reach
20
+ * the agent's context without SkillScan. That is safe only because no agent
21
+ * key can write those rows; only operator credentials and Flair's own internal
22
+ * paths can (resources/soul-write-policy.ts, resources/OrgSkillAssignment.ts).
23
+ * Widening who may write them changes this render path.
24
+ */
25
+ import { formatBase, normalizePriority, parseSkillMetadata, resolveActiveSkills, skillSourceOf, } from "./skill-provenance.js";
26
+ import { isSkillWrite } from "./skill-write.js";
27
+ /** The Memory fields the bootstrap skill-row query selects. */
28
+ export const SKILL_ROW_SELECT = [
29
+ "id", "agentId", "visibility", "tags", "metadata", "archived", "validTo", "expiresAt",
30
+ ];
31
+ const NO_ORG = { assignments: [], rows: [], instanceId: null };
32
+ /**
33
+ * Whether a target receives org skills, from its Agent record: the record
34
+ * exists, `kind` is "agent" (absent counts as "agent") and `status` is
35
+ * "active" (absent counts as "active").
36
+ */
37
+ export function receivesOrgSkills(agent) {
38
+ if (!agent || typeof agent !== "object")
39
+ return false;
40
+ const { kind, status } = agent;
41
+ return (kind ?? "agent") === "agent" && (status ?? "active") === "active";
42
+ }
43
+ /** A skill row's name: `metadata.name` (skill_store folds it there). */
44
+ export function skillNameOf(row) {
45
+ const name = parseSkillMetadata(row.metadata).name;
46
+ return typeof name === "string" && name.length > 0 ? name : undefined;
47
+ }
48
+ function isPast(value, now) {
49
+ return typeof value === "string" && value.length > 0 && Date.parse(value) < now;
50
+ }
51
+ /**
52
+ * The rows passed to resolveSkillRef: skill-tagged, readable by the target agent
53
+ * (`isReadable`, the read-scope predicate `skill_get` applies), not archived,
54
+ * and not closed (`validTo`) or expired (`expiresAt`).
55
+ */
56
+ export function resolvableSkillRows(rows, isReadable, now = Date.now()) {
57
+ return rows.filter((row) => typeof row.id === "string"
58
+ && isSkillWrite(row)
59
+ && isReadable(row)
60
+ && row.archived !== true
61
+ && !isPast(row.expiresAt, now)
62
+ && !isPast(row.validTo, now));
63
+ }
64
+ /**
65
+ * flair#2141 S2 hook: the skill rows written by the reserved system writer
66
+ * (the operator seed), the only candidates besides the agent's own rows. None
67
+ * exist before S2, so this returns no rows.
68
+ */
69
+ export function seedSkillRows(_rows) {
70
+ return [];
71
+ }
72
+ /**
73
+ * Resolve a name-only assignment to one skill row: the target agent's own row
74
+ * with that name (then, from flair#2141 S2, a seed row; see seedSkillRows).
75
+ * More than one row at a step is ambiguous; no row is unresolved.
76
+ */
77
+ export function resolveSkillRef(name, rows, agentId) {
78
+ const named = rows.filter((row) => skillNameOf(row) === name);
79
+ const decide = (list, whose) => {
80
+ if (list.length === 1)
81
+ return { kind: "resolved", skillId: list[0].id };
82
+ if (list.length === 0)
83
+ return null;
84
+ return {
85
+ kind: "ambiguous",
86
+ reason: `${list.length} ${whose} skill rows have this name`,
87
+ candidates: list.map((row) => row.id).sort(),
88
+ };
89
+ };
90
+ return decide(named.filter((row) => row.agentId === agentId), "of the agent's own")
91
+ ?? decide(seedSkillRows(named), "seed")
92
+ ?? { kind: "unresolved", reason: "the agent has no live skill row with this name" };
93
+ }
94
+ /** An org assignment's `skillRef`, resolved against the rows it may name. */
95
+ function resolveOrgRef(skillRef, rows) {
96
+ if (typeof skillRef === "string" && rows.some((row) => row.id === skillRef)) {
97
+ return { kind: "resolved", skillId: skillRef };
98
+ }
99
+ return { kind: "unresolved", reason: "the skillRef is not a live skill row this agent can read" };
100
+ }
101
+ /** The "## Active Skills" prose line for a manifest entry. */
102
+ export function skillLine(entry) {
103
+ return formatBase(entry.name, entry.priority, entry.source ?? undefined);
104
+ }
105
+ function compareDiagnostics(a, b) {
106
+ return a.name.localeCompare(b.name)
107
+ || a.decision.localeCompare(b.decision)
108
+ || (a.source ?? "").localeCompare(b.source ?? "")
109
+ || a.priority.localeCompare(b.priority)
110
+ || a.reason.localeCompare(b.reason)
111
+ || a.scope.localeCompare(b.scope);
112
+ }
113
+ /**
114
+ * The manifest for one agent: `assignments` are its `skill-assignment` Soul
115
+ * rows, `rows` the skill rows its own names may resolve to (see
116
+ * resolvableSkillRows), `org` the org assignments it receives. A Soul row with
117
+ * `metadata.optOut: true` is an opt-out, never a candidate: it removes the org
118
+ * assignments with that name before the priority rules, when `org.instanceId`
119
+ * is a non-empty string and the row's `originatorInstanceId` equals it.
120
+ * `skills` is sorted by name; `diagnostics` by name, decision, source,
121
+ * priority, reason and scope.
122
+ */
123
+ export function resolveSkillManifest(assignments, rows, agentId, org = NO_ORG) {
124
+ const skills = [];
125
+ const diagnostics = [];
126
+ const candidates = [];
127
+ const optedOut = new Set();
128
+ for (const assignment of assignments) {
129
+ const optOut = parseSkillMetadata(assignment.metadata).optOut;
130
+ if (optOut === undefined || optOut === false) {
131
+ candidates.push({ input: assignment, scope: "own" });
132
+ continue;
133
+ }
134
+ if (typeof assignment.value !== "string" || assignment.value.length === 0)
135
+ continue;
136
+ if (optOut !== true) {
137
+ diagnostics.push({
138
+ name: assignment.value, scope: "own",
139
+ priority: normalizePriority(assignment.priority),
140
+ source: skillSourceOf(assignment) ?? null,
141
+ decision: "refused", reason: "metadata.optOut is not a boolean",
142
+ });
143
+ continue;
144
+ }
145
+ if (typeof org.instanceId === "string" && org.instanceId !== "" && assignment.originatorInstanceId === org.instanceId) {
146
+ optedOut.add(assignment.value);
147
+ }
148
+ }
149
+ for (const row of org.assignments) {
150
+ if (typeof row.skillName !== "string" || optedOut.has(row.skillName))
151
+ continue;
152
+ candidates.push({ input: { value: row.skillName, priority: row.priority }, scope: "org", skillRef: row.skillRef });
153
+ }
154
+ const byInput = new Map(candidates.map((candidate) => [candidate.input, candidate]));
155
+ for (const outcome of resolveActiveSkills(candidates.map((candidate) => candidate.input)).outcomes) {
156
+ const candidate = byInput.get(outcome.input);
157
+ const scope = candidate.scope;
158
+ const source = outcome.source ?? null;
159
+ if (!outcome.loaded) {
160
+ diagnostics.push({
161
+ name: outcome.name, scope, priority: outcome.priority, source,
162
+ decision: outcome.decision, reason: outcome.reason,
163
+ });
164
+ continue;
165
+ }
166
+ const ref = scope === "org"
167
+ ? resolveOrgRef(candidate.skillRef, org.rows)
168
+ : resolveSkillRef(outcome.name, rows, agentId);
169
+ if (ref.kind === "resolved") {
170
+ skills.push({ name: outcome.name, skillId: ref.skillId, scope, priority: outcome.priority, source });
171
+ continue;
172
+ }
173
+ diagnostics.push({
174
+ name: outcome.name, scope, priority: outcome.priority, source, decision: ref.kind, reason: ref.reason,
175
+ ...(ref.kind === "ambiguous" ? { candidates: ref.candidates } : {}),
176
+ });
177
+ }
178
+ skills.sort((a, b) => a.name.localeCompare(b.name));
179
+ diagnostics.sort(compareDiagnostics);
180
+ return { skills, diagnostics };
181
+ }
@@ -158,6 +158,11 @@ export function refuseSkillAssignmentWrite(content, existing) {
158
158
  if (assignmentKey(content, existing) !== SKILL_ASSIGNMENT_KEY)
159
159
  return null;
160
160
  const metadata = content?.metadata !== undefined ? content.metadata : existing?.metadata;
161
+ // flair#2141 S1: `metadata.optOut`, when present, is a boolean.
162
+ const parsed = parseSkillMetadata(metadata);
163
+ if (Object.hasOwn(parsed, "optOut") && typeof parsed.optOut !== "boolean") {
164
+ return new Response(JSON.stringify({ error: "skill_opt_out_not_boolean", message: "metadata.optOut must be true or false" }), { status: 400, headers: { "content-type": "application/json" } });
165
+ }
161
166
  const result = registerSkillAssignment({
162
167
  key: SKILL_ASSIGNMENT_KEY,
163
168
  value: content?.value ?? existing?.value,
@@ -172,7 +177,7 @@ export function refuseSkillAssignmentWrite(content, existing) {
172
177
  message: result.message,
173
178
  }), { status: 400, headers: { "content-type": "application/json" } });
174
179
  }
175
- function normalizePriority(p) {
180
+ export function normalizePriority(p) {
176
181
  if (typeof p === "string" && Object.hasOwn(PRIORITY_RANK, p))
177
182
  return p;
178
183
  return "standard";
@@ -180,7 +185,7 @@ function normalizePriority(p) {
180
185
  function priorityRank(p) {
181
186
  return PRIORITY_RANK[p] ?? PRIORITY_RANK.standard;
182
187
  }
183
- function formatBase(name, priority, source) {
188
+ export function formatBase(name, priority, source) {
184
189
  const src = source ? `, source: ${source}` : "";
185
190
  return `- ${name} (${priority} priority${src})`;
186
191
  }
@@ -196,7 +201,7 @@ function compareOutcomes(a, b) {
196
201
  return byPri;
197
202
  return a.reason.localeCompare(b.reason);
198
203
  }
199
- function outcomeOf(name, priority, source, decision, reason, loaded) {
204
+ function outcomeOf(input, name, priority, source, decision, reason, loaded) {
200
205
  let line = formatBase(name, priority, source);
201
206
  if (decision === "superseded") {
202
207
  line += ` [SKILL_CONFLICT superseded: ${reason}]`;
@@ -206,7 +211,7 @@ function outcomeOf(name, priority, source, decision, reason, loaded) {
206
211
  ? ` [refused: ${reason}]`
207
212
  : ` [SKILL_CONFLICT refused: ${reason}]`;
208
213
  }
209
- return { name, priority, source, decision, reason, loaded, line };
214
+ return { name, priority, source, decision, reason, loaded, line, input };
210
215
  }
211
216
  /**
212
217
  * Stated, deterministic Active Skills outcome.
@@ -231,10 +236,10 @@ export function resolveActiveSkills(assignments) {
231
236
  const priority = normalizePriority(raw.priority);
232
237
  const source = skillSourceOf(raw);
233
238
  if (source && !isDurableSkillSource(source)) {
234
- outcomes.push(outcomeOf(name, priority, source, "refused", `non-durable source ${source}`, false));
239
+ outcomes.push(outcomeOf(raw, name, priority, source, "refused", `non-durable source ${source}`, false));
235
240
  continue;
236
241
  }
237
- prepared.push({ name, priority, source });
242
+ prepared.push({ input: raw, name, priority, source });
238
243
  }
239
244
  const byName = new Map();
240
245
  for (const row of prepared) {
@@ -247,25 +252,25 @@ export function resolveActiveSkills(assignments) {
247
252
  for (const group of byName.values()) {
248
253
  if (group.length === 1) {
249
254
  const only = group[0];
250
- outcomes.push(outcomeOf(only.name, only.priority, only.source, "loaded", "sole", true));
255
+ outcomes.push(outcomeOf(only.input, only.name, only.priority, only.source, "loaded", "sole", true));
251
256
  continue;
252
257
  }
253
258
  const best = Math.min(...group.map((g) => priorityRank(g.priority)));
254
259
  const top = group.filter((g) => priorityRank(g.priority) === best);
255
260
  if (top.length === 1) {
256
261
  const winner = top[0];
257
- outcomes.push(outcomeOf(winner.name, winner.priority, winner.source, "loaded", `unique_priority ${winner.priority}`, true));
262
+ outcomes.push(outcomeOf(winner.input, winner.name, winner.priority, winner.source, "loaded", `unique_priority ${winner.priority}`, true));
258
263
  for (const loser of group) {
259
264
  if (loser === winner)
260
265
  continue;
261
- outcomes.push(outcomeOf(loser.name, loser.priority, loser.source, "superseded", `${winner.priority} priority is stated precedence over ${loser.priority}`, false));
266
+ outcomes.push(outcomeOf(loser.input, loser.name, loser.priority, loser.source, "superseded", `${winner.priority} priority is stated precedence over ${loser.priority}`, false));
262
267
  }
263
268
  continue;
264
269
  }
265
270
  const sources = [...new Set(top.map((t) => t.source ?? "(none)"))].sort((a, b) => a.localeCompare(b));
266
271
  const reason = `equal-priority tie at ${top[0].priority}; load refused (sources: ${sources.join(", ")})`;
267
272
  for (const member of group) {
268
- outcomes.push(outcomeOf(member.name, member.priority, member.source, "refused", reason, false));
273
+ outcomes.push(outcomeOf(member.input, member.name, member.priority, member.source, "refused", reason, false));
269
274
  }
270
275
  }
271
276
  outcomes.sort(compareOutcomes);
@@ -0,0 +1,109 @@
1
+ /**
2
+ * PATCH updates an existing row. For a caller that is not an administrator or a
3
+ * trusted internal call, a PATCH never creates one; where a resource permits
4
+ * creation, rows are created with POST or PUT under the resource's own create
5
+ * rules.
6
+ *
7
+ * Harper's PATCH writes to the row its URL names and, when that row does not
8
+ * exist, would create it from the request body alone. So each guarded table's
9
+ * own `patch()` refuses a PATCH whose target row does not exist unless the
10
+ * caller is an administrator or a trusted internal call: the caller gets 404.
11
+ * A resource or authorization check that refuses the request before the
12
+ * table's `patch()` runs answers with its own status instead. A PATCH to an
13
+ * existing row is unchanged — the resources' own rules (ownership, the
14
+ * immutable owner field, validation) still decide it.
15
+ *
16
+ * ── The seam ────────────────────────────────────────────────────────────────
17
+ * `guardTablePatches` gives every table class in the flair database's table
18
+ * registry its own instance `patch()`, read from that registry at load
19
+ * (resources/table-patches.ts), not from a list someone maintains:
20
+ * - a table added to the schema is in that registry, so its class gets the
21
+ * guard without anyone naming it;
22
+ * - Harper has already resolved the target id and loaded the row when the
23
+ * instance `patch()` runs, so the guard decides on the row Harper will
24
+ * write (`doesExist()`), never on a re-parse of the URL;
25
+ * - a resource class without a `patch()` override inherits the guarded
26
+ * method, and an override reaches it only through `super.patch()`. Every
27
+ * flair override today either ends in `super.patch()` for the callers it
28
+ * admits or refuses the request itself: MemoryHostSource refuses every REST
29
+ * write, and MemoryUsage refuses a non-admin PATCH. A future override must
30
+ * do one or the other; an override that writes the row another way would
31
+ * not be covered by this guard.
32
+ * test/integration/patch-updates-existing-rows.test.ts enumerates every table in
33
+ * the database at runtime and fails if a non-admin PATCH creates a row in any.
34
+ *
35
+ * This module has no imports, so it is unit-tested directly
36
+ * (test/unit/table-patch-policy.test.ts); the dependencies it needs are passed
37
+ * in by resources/table-patches.ts.
38
+ */
39
+ /** Marks a table class whose `patch()` has been guarded. */
40
+ export const TABLE_PATCH_GUARD = Symbol.for("flair.tablePatchGuard");
41
+ /**
42
+ * Whether the row a resource instance addresses exists: true or false as the
43
+ * instance reports it, or undefined when the instance cannot say (the guard
44
+ * then treats the PATCH as a create).
45
+ */
46
+ export function rowExists(resource) {
47
+ const doesExist = resource?.doesExist;
48
+ if (typeof doesExist !== "function")
49
+ return undefined;
50
+ const answer = doesExist.call(resource);
51
+ return typeof answer === "boolean" ? answer : undefined;
52
+ }
53
+ /** The refusal for a PATCH whose target row does not exist; null for an administrator or a trusted internal call. */
54
+ export function patchCreateRefusal(table, caller) {
55
+ if (caller.kind === "internal")
56
+ return null;
57
+ if (caller.kind === "agent" && caller.isAdmin === true)
58
+ return null;
59
+ return Object.assign(new Error(`not found: PATCH updates an existing ${table} row and does not create one; where ${table} permits creation, use POST or PUT`), { statusCode: 404 });
60
+ }
61
+ /** The refusal when the caller of a PATCH that would create a row cannot be resolved. */
62
+ export function unverifiedPatchCallerRefusal(table) {
63
+ return Object.assign(new Error(`the caller of this ${table} PATCH could not be verified, so it was refused; retry`), { statusCode: 500 });
64
+ }
65
+ /**
66
+ * Give every table class in `tables` its own instance `patch()` that refuses to
67
+ * create a row for a caller who is not an administrator or a trusted internal
68
+ * call, then delegates to the inherited `patch()` unchanged. A PATCH to an
69
+ * existing row goes straight through. Idempotent. Returns the names of the
70
+ * guarded tables.
71
+ */
72
+ export function guardTablePatches(tables, deps) {
73
+ const guarded = [];
74
+ for (const name of Object.keys(tables ?? {})) {
75
+ const table = tables[name];
76
+ if (typeof table !== "function" || table.prototype == null)
77
+ continue;
78
+ if (Object.prototype.hasOwnProperty.call(table, TABLE_PATCH_GUARD)) {
79
+ guarded.push(name);
80
+ continue;
81
+ }
82
+ const inherited = table.prototype.patch;
83
+ if (typeof inherited !== "function")
84
+ continue; // no PATCH to guard
85
+ Object.defineProperty(table.prototype, "patch", {
86
+ configurable: true,
87
+ writable: true,
88
+ enumerable: false,
89
+ value: async function patch(...args) {
90
+ if (rowExists(this) !== true) {
91
+ let caller;
92
+ try {
93
+ caller = await deps.resolveAuth(this.getContext?.());
94
+ }
95
+ catch {
96
+ throw unverifiedPatchCallerRefusal(name);
97
+ }
98
+ const refusal = patchCreateRefusal(name, caller);
99
+ if (refusal)
100
+ throw refusal;
101
+ }
102
+ return inherited.apply(this, args);
103
+ },
104
+ });
105
+ Object.defineProperty(table, TABLE_PATCH_GUARD, { value: true });
106
+ guarded.push(name);
107
+ }
108
+ return guarded;
109
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Installs the PATCH guard (resources/table-patch-policy.ts) on every table
3
+ * class in the flair database's table registry when the component loads: a
4
+ * PATCH whose target row does not exist does not create or modify its target
5
+ * row unless the caller is an administrator or a trusted internal call. The
6
+ * tables are read from the registry, so the class of a table added to the
7
+ * schema gets the guard without being named here. A resource that overrides
8
+ * `patch()` reaches the guard only by ending in `super.patch()`; an override
9
+ * that does not must enforce the no-create rule itself by refusing.
10
+ *
11
+ * This module deliberately exports nothing: Harper registers exported values of
12
+ * a resource module as routes.
13
+ */
14
+ import { databases } from "harper";
15
+ import { resolveAgentAuth } from "./agent-auth.js";
16
+ import { guardTablePatches } from "./table-patch-policy.js";
17
+ guardTablePatches(databases.flair, { resolveAuth: resolveAgentAuth });
@@ -0,0 +1,138 @@
1
+ /**
2
+ * A non-admin HTTP collection POST is served only by a resource's own `post()`,
3
+ * which applies that resource's own write rules. On a table whose resource
4
+ * defines no `post()` of its own, a collection POST is refused unless the
5
+ * caller is an administrator or a trusted internal call. Harper runs the
6
+ * resource's `allowCreate()` check before `post()`, and that check can refuse
7
+ * the POST first; a POST that reaches the guard is answered 403 for a verified
8
+ * non-admin agent and 401 for a caller without a valid credential, and is
9
+ * refused when the caller cannot be resolved.
10
+ *
11
+ * ── The seam ────────────────────────────────────────────────────────────────
12
+ * `guardInheritedPosts` gives every table class in the flair database's table
13
+ * registry that has a `post()` its own instance `post()`, read from that
14
+ * registry at load
15
+ * (resources/table-posts.ts), not from a list someone maintains:
16
+ * - a table added to the schema is in that registry, so its class gets the
17
+ * guard without anyone naming it;
18
+ * - a resource class that defines `post()` keeps it: Harper calls the most
19
+ * derived `post()`, and when that override ends in `super.post()` the guard
20
+ * sees that the resource defines one and lets the call through;
21
+ * - on a resource class without a `post()` of its own, a POST that passes the
22
+ * resource's `allowCreate()` check reaches the guard, which refuses a
23
+ * non-admin caller before Harper's `create()` runs;
24
+ * - resources/table-posts.ts logs an error at load when the registry is
25
+ * missing or empty, or an entry could not be guarded (`tablePostGuardGaps`).
26
+ * test/integration/collection-post-attribution.test.ts reads every table in the
27
+ * database at runtime, sends a collection POST built from the table's declared
28
+ * attributes (plus a value a table's own validation requires) as a verified
29
+ * non-admin agent, and checks each candidate stored row of that POST (a new or
30
+ * changed row, or a row under the body id or a key the response names, found
31
+ * under the table's primary key): the table's registered owner field, if it
32
+ * has one, must be the caller. The body carries an `originatorInstanceId` and a
33
+ * `provenance` only where the table declares them, and only those declared
34
+ * fields are checked: `originatorInstanceId` must be this instance's id on a
35
+ * new row and the previous value on an existing one, and `provenance` must
36
+ * not contain the body's sentinel timestamp. The guard's non-admin refusals
37
+ * are unit-tested (test/unit/table-post-policy.test.ts,
38
+ * test/unit/table-posts.test.ts); the integration test covers an
39
+ * administrator's POST through the guard (Peer).
40
+ *
41
+ * This module has no imports, so it is unit-tested directly
42
+ * (test/unit/table-post-policy.test.ts); the dependencies it needs are passed in
43
+ * by resources/table-posts.ts.
44
+ */
45
+ /** Marks a table class whose `post()` has been guarded. */
46
+ export const TABLE_POST_GUARD = Symbol.for("flair.tablePostGuard");
47
+ /**
48
+ * Whether the resource class an instance belongs to defines its own `post()`
49
+ * below the table class (`tablePrototype`): true when any prototype between the
50
+ * instance's own and the table's carries a `post` of its own.
51
+ */
52
+ export function resourceDefinesPost(instance, tablePrototype) {
53
+ let proto = instance == null ? null : Object.getPrototypeOf(instance);
54
+ while (proto && proto !== tablePrototype) {
55
+ if (Object.prototype.hasOwnProperty.call(proto, "post"))
56
+ return true;
57
+ proto = Object.getPrototypeOf(proto);
58
+ }
59
+ return false;
60
+ }
61
+ /**
62
+ * The refusal for a collection POST on a table whose resource defines no
63
+ * `post()`; null for an administrator or a trusted internal call.
64
+ */
65
+ export function inheritedPostRefusal(table, caller) {
66
+ if (caller.kind === "internal")
67
+ return null;
68
+ if (caller.kind === "agent" && caller.isAdmin === true)
69
+ return null;
70
+ if (caller.kind === "agent") {
71
+ return Object.assign(new Error(`forbidden: a ${table} row is created through POST only by an administrator; where ${table} permits it, use PUT /${table}/<id>`), { statusCode: 403 });
72
+ }
73
+ return Object.assign(new Error(`creating a ${table} row through POST needs an administrator's credential`), { statusCode: 401 });
74
+ }
75
+ /** The refusal when the caller of such a POST cannot be resolved. */
76
+ export function unverifiedPostCallerRefusal(table) {
77
+ return Object.assign(new Error(`the caller of this ${table} POST could not be verified, so it was refused; retry`), { statusCode: 500 });
78
+ }
79
+ /**
80
+ * Give every table class in `tables` that has a `post()` its own instance
81
+ * `post()`. When the resource defines no `post()` of its own, that `post()`
82
+ * refuses a caller who is not an administrator or a trusted internal call; an
83
+ * admitted caller, and every call on a resource with its own `post()`, is
84
+ * delegated to the inherited `post()` unchanged. Idempotent. Returns the names
85
+ * of the guarded tables.
86
+ */
87
+ export function guardInheritedPosts(tables, deps) {
88
+ const guarded = [];
89
+ for (const name of Object.keys(tables ?? {})) {
90
+ const table = tables[name];
91
+ if (typeof table !== "function" || table.prototype == null)
92
+ continue;
93
+ if (Object.prototype.hasOwnProperty.call(table, TABLE_POST_GUARD)) {
94
+ guarded.push(name);
95
+ continue;
96
+ }
97
+ const tablePrototype = table.prototype;
98
+ const inherited = tablePrototype.post;
99
+ if (typeof inherited !== "function")
100
+ continue; // no POST to guard
101
+ Object.defineProperty(tablePrototype, "post", {
102
+ configurable: true,
103
+ writable: true,
104
+ enumerable: false,
105
+ value: async function post(...args) {
106
+ if (!resourceDefinesPost(this, tablePrototype)) {
107
+ let caller;
108
+ try {
109
+ caller = await deps.resolveAuth(this.getContext?.());
110
+ }
111
+ catch {
112
+ throw unverifiedPostCallerRefusal(name);
113
+ }
114
+ const refusal = inheritedPostRefusal(name, caller);
115
+ if (refusal)
116
+ throw refusal;
117
+ }
118
+ return inherited.apply(this, args);
119
+ },
120
+ });
121
+ Object.defineProperty(table, TABLE_POST_GUARD, { value: true });
122
+ guarded.push(name);
123
+ }
124
+ return guarded;
125
+ }
126
+ /**
127
+ * What an installation left unguarded, given the registry and the names
128
+ * `guardInheritedPosts` returned: a missing or empty registry, or each entry
129
+ * that is not a table class with a `post()` to guard. Empty when every entry
130
+ * is guarded.
131
+ */
132
+ export function tablePostGuardGaps(tables, guarded) {
133
+ const names = Object.keys(tables ?? {});
134
+ if (names.length === 0)
135
+ return ["the flair table registry is missing or empty"];
136
+ const done = new Set(guarded);
137
+ return names.filter((name) => !done.has(name)).map((name) => `${name} is not a table class with a post() to guard`);
138
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Installs the collection-POST guard (resources/table-post-policy.ts) on every
3
+ * table class in the flair database's table registry that has a `post()`, when
4
+ * the component loads:
5
+ * on a table whose resource defines no `post()` of its own, a collection POST
6
+ * creates a row only for an administrator or a trusted internal call. The
7
+ * tables are read from the registry, so the class of a table added to the
8
+ * schema gets the guard without being named here. An incomplete installation
9
+ * (a missing or empty registry, or an entry that could not be guarded) is
10
+ * logged as an error at load.
11
+ *
12
+ * This module deliberately exports nothing: Harper registers exported values of
13
+ * a resource module as routes.
14
+ */
15
+ import { databases } from "harper";
16
+ import { resolveAgentAuth } from "./agent-auth.js";
17
+ import { guardInheritedPosts, tablePostGuardGaps } from "./table-post-policy.js";
18
+ const registry = databases.flair;
19
+ const gaps = tablePostGuardGaps(registry, guardInheritedPosts(registry, { resolveAuth: resolveAgentAuth }));
20
+ if (gaps.length > 0) {
21
+ console.error(`[flair] the collection POST guard is incomplete: ${gaps.join("; ")}`);
22
+ }