@tpsdev-ai/flair 0.58.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/SECURITY.md +36 -0
- package/config.yaml +15 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1030 -343
- package/dist/commands/agent.js +384 -45
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +601 -163
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +146 -53
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +81 -8
- package/dist/lib/doctor-run.js +140 -35
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +120 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +27 -2
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1775 -338
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +103 -7
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +348 -8
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +19 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +752 -132
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +227 -64
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/OrgSkillAssignment.js +209 -0
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +212 -65
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/agent-status-guard.js +63 -0
- package/dist/resources/auth-middleware.js +402 -162
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +94 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/flair-agent-role-boot.js +26 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +130 -20
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +31 -0
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +26 -12
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +150 -23
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/multi-worker-guard.js +121 -0
- package/dist/resources/oauth-discovery.js +1 -0
- package/dist/resources/oauth-wellknown.js +8 -4
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +17 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +145 -21
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +190 -0
- package/dist/resources/skill-provenance.js +15 -10
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +120 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +768 -0
- package/docs/api-reference.md +52 -13
- package/docs/auth.md +10 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deepseek-harness.md +1 -1
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +6 -6
- package/docs/mcp-clients.md +10 -5
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +34 -28
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +12 -6
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +115 -5
- package/schemas/oauth.graphql +27 -4
- package/schemas/schema.graphql +2 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
|
@@ -135,6 +135,8 @@
|
|
|
135
135
|
*/
|
|
136
136
|
import { databases } from "harper";
|
|
137
137
|
import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
|
|
138
|
+
import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
|
|
139
|
+
import { txnPausePoint } from "../txn-pause-point.js";
|
|
138
140
|
function defaultMemoryTable() {
|
|
139
141
|
return databases.flair.Memory;
|
|
140
142
|
}
|
|
@@ -170,7 +172,7 @@ function pendingCondition() {
|
|
|
170
172
|
* `embedding-stamp`, there is no separate HTTP mechanism to inject: the
|
|
171
173
|
* write IS the table's own `.put()`, already covered by the same fake.
|
|
172
174
|
*/
|
|
173
|
-
export function createVisibilityBackfillMigration(getTable = defaultMemoryTable) {
|
|
175
|
+
export function createVisibilityBackfillMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl) {
|
|
174
176
|
return {
|
|
175
177
|
id: VISIBILITY_BACKFILL_ID,
|
|
176
178
|
riskClass: "derived-only",
|
|
@@ -200,34 +202,32 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable)
|
|
|
200
202
|
const id = String(row.id ?? "");
|
|
201
203
|
if (!id)
|
|
202
204
|
continue;
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
await table.put(backfillRow);
|
|
230
|
-
touchedIds.push(id);
|
|
205
|
+
const outcome = await writeBackCommittedRow(table, id, (existing) => {
|
|
206
|
+
if (!existing)
|
|
207
|
+
return { skip: true }; // deleted since the search above — nothing to fix
|
|
208
|
+
// The write-gate: this is what actually enforces "never overwrite an
|
|
209
|
+
// existing visibility value", independent of how precisely the
|
|
210
|
+
// candidate query above narrowed things (see module doc — a
|
|
211
|
+
// garbage third value would still be pulled in as a candidate).
|
|
212
|
+
if (existing.visibility !== undefined && existing.visibility !== null)
|
|
213
|
+
return { skip: true };
|
|
214
|
+
const derived = deriveVisibilityFromDurability(existing.durability);
|
|
215
|
+
// Never-widen invariant, asserted, not just tested: the only two
|
|
216
|
+
// values `deriveVisibilityFromDurability` can ever produce are
|
|
217
|
+
// "private"/"shared" (see its own doc), so this can never fire
|
|
218
|
+
// today — it exists to fail loudly (halting this migration via the
|
|
219
|
+
// runner's mid-batch-throw path, never a silent bad write) if a
|
|
220
|
+
// future edit to that function ever widens its return type or is
|
|
221
|
+
// bypassed via a type-unsafe call.
|
|
222
|
+
if (derived !== "private" && derived !== "shared") {
|
|
223
|
+
throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
|
|
224
|
+
}
|
|
225
|
+
const backfillRow = { ...existing, visibility: derived };
|
|
226
|
+
stripUndeclaredMemoryAttributes(backfillRow);
|
|
227
|
+
return { write: backfillRow };
|
|
228
|
+
}, { label: "visibility-backfill", pausePre: () => txnPausePoint("visibility-backfill-pre"), pausePoint: () => txnPausePoint("visibility-backfill"), expectedRow: row });
|
|
229
|
+
if ("write" in outcome)
|
|
230
|
+
touchedIds.push(id);
|
|
231
231
|
}
|
|
232
232
|
return { processed: touchedIds.length, touchedIds };
|
|
233
233
|
},
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { server } from "harper";
|
|
2
|
+
import * as harper from "harper";
|
|
3
|
+
export const MULTI_WORKER_REFUSED_STATE = "multi-worker-unsupported";
|
|
4
|
+
export const MULTI_WORKER_ERROR_NAME = "multi_worker_unsupported";
|
|
5
|
+
export const MULTI_WORKER_REMEDY = "THREADS_COUNT=1";
|
|
6
|
+
export const MULTI_WORKER_UNSAFE_ENV = "FLAIR_MULTI_WORKER_UNSAFE";
|
|
7
|
+
export const MULTI_WORKER_GUARD_HTTP_NAME = "flair-multi-worker-guard";
|
|
8
|
+
export const FLAIR_AUTH_MIDDLEWARE_HTTP_NAME = "flair-auth-middleware";
|
|
9
|
+
export function decideMultiWorkerState(workerCount, optIn) {
|
|
10
|
+
if (workerCount === null)
|
|
11
|
+
return "refused";
|
|
12
|
+
if (!(workerCount > 1))
|
|
13
|
+
return "single-worker";
|
|
14
|
+
return optIn ? "unsafe-opt-in" : "refused";
|
|
15
|
+
}
|
|
16
|
+
export function multiWorkerUnsafeOptIn(env = process.env) {
|
|
17
|
+
return env[MULTI_WORKER_UNSAFE_ENV] === "1";
|
|
18
|
+
}
|
|
19
|
+
function workerCountLabel(condition) {
|
|
20
|
+
return condition.workerCount === null
|
|
21
|
+
? "the worker count is unreadable"
|
|
22
|
+
: `worker count=${condition.workerCount}`;
|
|
23
|
+
}
|
|
24
|
+
export function multiWorkerHealthField(condition) {
|
|
25
|
+
if (condition.state === "single-worker")
|
|
26
|
+
return null;
|
|
27
|
+
return {
|
|
28
|
+
state: condition.state,
|
|
29
|
+
workerCount: condition.workerCount,
|
|
30
|
+
remedy: condition.state === "refused" ? MULTI_WORKER_REMEDY : `${MULTI_WORKER_UNSAFE_ENV}=1`,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export function multiWorkerBootLine(condition) {
|
|
34
|
+
if (condition.state === "single-worker")
|
|
35
|
+
return null;
|
|
36
|
+
const reason = "the multi-worker readiness work (flair#2052) is not complete — a per-worker embedding " +
|
|
37
|
+
"engine and BM25 index";
|
|
38
|
+
if (condition.state === "refused") {
|
|
39
|
+
return (`[multi-worker] refused: ${workerCountLabel(condition)}; flair does not serve on more than one ` +
|
|
40
|
+
`Harper worker thread because ${reason}. Set ${MULTI_WORKER_REMEDY} and restart.`);
|
|
41
|
+
}
|
|
42
|
+
return (`[multi-worker] ${MULTI_WORKER_UNSAFE_ENV}=1 with ${workerCountLabel(condition)}: serving with ` +
|
|
43
|
+
`the multi-worker readiness work outstanding — ${reason}. Set ${MULTI_WORKER_REMEDY} and unset ` +
|
|
44
|
+
`${MULTI_WORKER_UNSAFE_ENV}.`);
|
|
45
|
+
}
|
|
46
|
+
export function multiWorkerRefusalBody(condition) {
|
|
47
|
+
return {
|
|
48
|
+
error: MULTI_WORKER_ERROR_NAME,
|
|
49
|
+
workerCount: condition.workerCount,
|
|
50
|
+
remedy: MULTI_WORKER_REMEDY,
|
|
51
|
+
detail: "flair does not serve on more than one Harper worker thread until the multi-worker readiness work lands.",
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export function isMultiWorkerExemptPath(pathname) {
|
|
55
|
+
return pathname === "/Health" || pathname === "/health";
|
|
56
|
+
}
|
|
57
|
+
export function multiWorkerRefusalResponse(condition, pathname) {
|
|
58
|
+
if (condition.state !== "refused" || isMultiWorkerExemptPath(pathname))
|
|
59
|
+
return null;
|
|
60
|
+
return new Response(JSON.stringify(multiWorkerRefusalBody(condition)), {
|
|
61
|
+
status: 503,
|
|
62
|
+
headers: { "content-type": "application/json" },
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
let cached = null;
|
|
66
|
+
function readPositiveInteger(read) {
|
|
67
|
+
let raw;
|
|
68
|
+
try {
|
|
69
|
+
raw = read();
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1)
|
|
75
|
+
return null;
|
|
76
|
+
return raw;
|
|
77
|
+
}
|
|
78
|
+
export function readWorkerCount() {
|
|
79
|
+
const perThread = readPositiveInteger(() => server?.workerCount);
|
|
80
|
+
if (perThread !== null)
|
|
81
|
+
return perThread;
|
|
82
|
+
return readPositiveInteger(() => (server?.config)?.threads?.count);
|
|
83
|
+
}
|
|
84
|
+
export function resolveMultiWorkerCondition() {
|
|
85
|
+
if (cached)
|
|
86
|
+
return cached;
|
|
87
|
+
const workerCount = readWorkerCount();
|
|
88
|
+
cached = { state: decideMultiWorkerState(workerCount, multiWorkerUnsafeOptIn()), workerCount };
|
|
89
|
+
return cached;
|
|
90
|
+
}
|
|
91
|
+
export function multiWorkerCondition() {
|
|
92
|
+
return resolveMultiWorkerCondition();
|
|
93
|
+
}
|
|
94
|
+
export function announceMultiWorkerCondition(condition = resolveMultiWorkerCondition()) {
|
|
95
|
+
const line = multiWorkerBootLine(condition);
|
|
96
|
+
if (!line)
|
|
97
|
+
return;
|
|
98
|
+
const l = harper.logger;
|
|
99
|
+
if (typeof l?.error === "function")
|
|
100
|
+
l.error(line);
|
|
101
|
+
else
|
|
102
|
+
console.error(line);
|
|
103
|
+
}
|
|
104
|
+
export async function multiWorkerRequestGuard(request, nextLayer) {
|
|
105
|
+
const pathname = typeof request?.pathname === "string" ? request.pathname : "/";
|
|
106
|
+
const refusal = multiWorkerRefusalResponse(multiWorkerCondition(), pathname);
|
|
107
|
+
if (refusal)
|
|
108
|
+
return refusal;
|
|
109
|
+
return nextLayer(request);
|
|
110
|
+
}
|
|
111
|
+
export function _resetMultiWorkerGuardForTests() {
|
|
112
|
+
cached = null;
|
|
113
|
+
}
|
|
114
|
+
if (typeof server?.http === "function") {
|
|
115
|
+
server.http(multiWorkerRequestGuard, {
|
|
116
|
+
runFirst: true,
|
|
117
|
+
name: MULTI_WORKER_GUARD_HTTP_NAME,
|
|
118
|
+
before: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
announceMultiWorkerCondition();
|
|
@@ -34,6 +34,7 @@ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
|
|
|
34
34
|
export const PRM_PATH = "/.well-known/oauth-protected-resource";
|
|
35
35
|
/** RFC 8414 §3 — Authorization Server Metadata well-known path. */
|
|
36
36
|
export const AS_METADATA_PATH = "/.well-known/oauth-authorization-server";
|
|
37
|
+
export const JWKS_PATH = "/.well-known/jwks.json";
|
|
37
38
|
/**
|
|
38
39
|
* The public origin every URL in every discovery document derives from.
|
|
39
40
|
*
|
|
@@ -88,8 +88,9 @@
|
|
|
88
88
|
* and the plugin is declared), so the discovery loop closes.
|
|
89
89
|
*/
|
|
90
90
|
import { server } from "harper";
|
|
91
|
-
import { AS_METADATA_PATH, PRM_PATH, asMetadataPathMatches, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, makeWellKnownHandler, prmPathMatches, } from "./oauth-discovery.js";
|
|
91
|
+
import { AS_METADATA_PATH, JWKS_PATH, PRM_PATH, asMetadataPathMatches, buildAuthorizationServerMetadata, buildProtectedResourceMetadata, makeWellKnownHandler, prmPathMatches, } from "./oauth-discovery.js";
|
|
92
92
|
import { mcpOAuthEnabled } from "./mcp-oauth-flag.js";
|
|
93
|
+
import { MULTI_WORKER_GUARD_HTTP_NAME, multiWorkerRequestGuard } from "./multi-worker-guard.js";
|
|
93
94
|
/**
|
|
94
95
|
* Mount both documents. Called once at module load, and directly from tests.
|
|
95
96
|
* Returns the urlPaths mounted so a caller can assert on them.
|
|
@@ -99,9 +100,12 @@ export function registerOAuthWellKnownRoutes(deps = {}) {
|
|
|
99
100
|
if (typeof srv?.http !== "function")
|
|
100
101
|
return [];
|
|
101
102
|
const enabled = deps.isMcpOAuthEnabled ?? mcpOAuthEnabled;
|
|
102
|
-
srv.http(makeWellKnownHandler(prmPathMatches, buildProtectedResourceMetadata, enabled), { urlPath: PRM_PATH });
|
|
103
|
-
srv.http(makeWellKnownHandler(asMetadataPathMatches, buildAuthorizationServerMetadata, enabled), { urlPath: AS_METADATA_PATH });
|
|
104
|
-
|
|
103
|
+
srv.http(makeWellKnownHandler(prmPathMatches, buildProtectedResourceMetadata, enabled), { urlPath: PRM_PATH, after: MULTI_WORKER_GUARD_HTTP_NAME });
|
|
104
|
+
srv.http(makeWellKnownHandler(asMetadataPathMatches, buildAuthorizationServerMetadata, enabled), { urlPath: AS_METADATA_PATH, after: MULTI_WORKER_GUARD_HTTP_NAME });
|
|
105
|
+
for (const path of [PRM_PATH, AS_METADATA_PATH, JWKS_PATH]) {
|
|
106
|
+
srv.http(multiWorkerRequestGuard, { urlPath: path, runFirst: true, name: MULTI_WORKER_GUARD_HTTP_NAME });
|
|
107
|
+
}
|
|
108
|
+
return [PRM_PATH, AS_METADATA_PATH, JWKS_PATH];
|
|
105
109
|
}
|
|
106
110
|
// Registered at module load, like resources/auth-middleware.ts. The opt-out
|
|
107
111
|
// exists only so a unit test can import this module under a partial `harper`
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* object-body-guard.ts — the shared write-body shape check.
|
|
3
|
+
*
|
|
4
|
+
* `content` must be a non-null, non-array object. Arrays of records are admitted
|
|
5
|
+
* when `allowArrayObjects` is enabled. Anything else reaching this guard is
|
|
6
|
+
* refused with `body_must_be_object` (400).
|
|
7
|
+
*/
|
|
8
|
+
export const BODY_MUST_BE_OBJECT_ERROR = "body_must_be_object";
|
|
9
|
+
/** True for a write body that is one record: a non-null object that is not an array. */
|
|
10
|
+
function isObjectRecord(value) {
|
|
11
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
/** 400 for a write body that is neither a JSON object nor an allowed array of them. Echoes nothing. */
|
|
14
|
+
export function bodyMustBeObject() {
|
|
15
|
+
return new Response(JSON.stringify({
|
|
16
|
+
error: BODY_MUST_BE_OBJECT_ERROR,
|
|
17
|
+
message: "the write body must be a JSON object, or an array of them for a collection write",
|
|
18
|
+
}), { status: 400, headers: { "Content-Type": "application/json" } });
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Refuse a write body that is neither an object nor an allowed array of records.
|
|
22
|
+
*
|
|
23
|
+
* @param content the parsed request body
|
|
24
|
+
* @param opts `allowArrayObjects: true` admits arrays of records
|
|
25
|
+
* @returns the 400 `Response` to send, or null to proceed
|
|
26
|
+
*/
|
|
27
|
+
export function guardObjectBody(content, opts = {}) {
|
|
28
|
+
if (isObjectRecord(content))
|
|
29
|
+
return null;
|
|
30
|
+
if (opts.allowArrayObjects && Array.isArray(content) && content.every(isObjectRecord))
|
|
31
|
+
return null;
|
|
32
|
+
return bodyMustBeObject();
|
|
33
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* org-event-created-at.ts — the createdAt check for OrgEvent writes: the server
|
|
3
|
+
* assigns an event's createdAt on create, and a write that reaches this check
|
|
4
|
+
* cannot change a stored row's createdAt.
|
|
5
|
+
*
|
|
6
|
+
* The check runs after the resource's earlier checks (authentication,
|
|
7
|
+
* ownership, attribution, entity validation), which answer first with their own
|
|
8
|
+
* responses, as Harper's own validation does for input it refuses before the
|
|
9
|
+
* resource runs. For each record that reaches it:
|
|
10
|
+
*
|
|
11
|
+
* - a record that is not an object, or whose id is not a non-empty string or
|
|
12
|
+
* a non-empty array of strings, is not read: it is refused with
|
|
13
|
+
* `invalid_event_id` (400) before any write. Before validation, an
|
|
14
|
+
* addressed POST binds a missing or null body id to the addressed id, and
|
|
15
|
+
* a string or number body id when its text matches the address; any other
|
|
16
|
+
* id type is left unchanged by this step. At the root collection, POST
|
|
17
|
+
* generates an id when the body's id is missing, null or empty. At the
|
|
18
|
+
* root collection, or an addressed path whose body id was not bound, a
|
|
19
|
+
* remaining id outside those shapes receives the same 400 before the
|
|
20
|
+
* ownership lookup;
|
|
21
|
+
* - otherwise the check reads the stored row under that id. With no stored
|
|
22
|
+
* row (a create), createdAt is the server's time, whatever the body says;
|
|
23
|
+
* - with a stored row, its createdAt is authoritative whatever its value, an
|
|
24
|
+
* empty string included. A body that omits createdAt keeps the stored
|
|
25
|
+
* value; a body whose createdAt differs from it is refused with
|
|
26
|
+
* `created_at_immutable` (409), and nothing is written.
|
|
27
|
+
*
|
|
28
|
+
* resources/OrgEvent.ts runs this check for writes from verified agents and
|
|
29
|
+
* administrators on POST, single-record PUT and PATCH, and for administrators
|
|
30
|
+
* on each element of a collection PUT. A non-admin agent's collection PUT or
|
|
31
|
+
* PATCH is refused before this check by the owner-scoped write guard
|
|
32
|
+
* (resources/owner-scoped-write-policy.ts), and a non-admin addressed
|
|
33
|
+
* array-body PUT that reaches the resource is refused before it by attribution. Trusted in-process
|
|
34
|
+
* writers that supply their own createdAt (the migration ledger, the graph-heal migration) write
|
|
35
|
+
* through the raw `databases.flair.OrgEvent` table, not the resource's verbs,
|
|
36
|
+
* and an `internal` verdict on the resource passes through unchanged.
|
|
37
|
+
*
|
|
38
|
+
* The stored row is read before the write and the two are not atomic: a row
|
|
39
|
+
* first written between the read and the write is treated as a create, so its
|
|
40
|
+
* createdAt becomes this write's server time.
|
|
41
|
+
*
|
|
42
|
+
* The decision is pure and has no Harper import, so it is unit-tested directly.
|
|
43
|
+
*/
|
|
44
|
+
export const CREATED_AT_IMMUTABLE_ERROR = "created_at_immutable";
|
|
45
|
+
export const CREATED_AT_CHECK_UNAVAILABLE_ERROR = "created_at_check_unavailable";
|
|
46
|
+
export const INVALID_EVENT_ID_ERROR = "invalid_event_id";
|
|
47
|
+
/** 409 for a write that reaches the check and would change a stored event's createdAt. Echoes nothing. */
|
|
48
|
+
export function createdAtImmutable() {
|
|
49
|
+
return new Response(JSON.stringify({
|
|
50
|
+
error: CREATED_AT_IMMUTABLE_ERROR,
|
|
51
|
+
message: "this write would change the stored event's createdAt, which the server assigns on create",
|
|
52
|
+
}), { status: 409, headers: { "Content-Type": "application/json" } });
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 503 when this check's own stored-event read fails, so the write was refused.
|
|
56
|
+
* Read failures in earlier checks keep their own responses.
|
|
57
|
+
*/
|
|
58
|
+
export function createdAtCheckUnavailable(err) {
|
|
59
|
+
console.error("org-event-created-at: the stored event could not be read, so the write was refused", { err });
|
|
60
|
+
return new Response(JSON.stringify({
|
|
61
|
+
error: CREATED_AT_CHECK_UNAVAILABLE_ERROR,
|
|
62
|
+
message: "the stored event could not be read; the write was refused",
|
|
63
|
+
}), { status: 503, headers: { "Content-Type": "application/json" } });
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* 400 for a record the check does not read: one that is not an object, or whose
|
|
67
|
+
* id is not a key the check reads (see isReadableEventId). Echoes nothing.
|
|
68
|
+
*/
|
|
69
|
+
export function invalidEventId() {
|
|
70
|
+
return new Response(JSON.stringify({
|
|
71
|
+
error: INVALID_EVENT_ID_ERROR,
|
|
72
|
+
message: "each OrgEvent a write stores must be an object whose id is a non-empty string or a non-empty array of strings",
|
|
73
|
+
}), { status: 400, headers: { "Content-Type": "application/json" } });
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Whether the check reads the stored row under `id`: a non-empty string, or a
|
|
77
|
+
* non-empty array of strings (a composite key). The check refuses every other
|
|
78
|
+
* id with `invalid_event_id` before any write. Harper accepts some of those ids
|
|
79
|
+
* as keys (the empty string is one), so the refusal is this check's own rule,
|
|
80
|
+
* not something left to Harper's validation.
|
|
81
|
+
*/
|
|
82
|
+
export function isReadableEventId(id) {
|
|
83
|
+
if (typeof id === "string")
|
|
84
|
+
return id !== "";
|
|
85
|
+
return Array.isArray(id) && id.length > 0 && id.every((part) => typeof part === "string");
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Returns invalid_event_id (400) for anything but a non-empty string or a
|
|
89
|
+
* non-empty array of strings, or null. The refusal echoes no submitted value.
|
|
90
|
+
*/
|
|
91
|
+
export function unreadableEventIdRefusal(id) {
|
|
92
|
+
return isReadableEventId(id) ? null : invalidEventId();
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The same rule applied to a collection PUT's array body: the refusal for the
|
|
96
|
+
* first record element whose id it does not read, or null.
|
|
97
|
+
* The scan skips non-record elements.
|
|
98
|
+
*/
|
|
99
|
+
export function collectionElementIdRefusal(body) {
|
|
100
|
+
if (!Array.isArray(body))
|
|
101
|
+
return null;
|
|
102
|
+
for (const element of body) {
|
|
103
|
+
if (element == null || typeof element !== "object" || Array.isArray(element))
|
|
104
|
+
continue;
|
|
105
|
+
const denial = unreadableEventIdRefusal(element.id);
|
|
106
|
+
if (denial)
|
|
107
|
+
return denial;
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Assign or keep `content.createdAt` for one write, given the stored row the
|
|
113
|
+
* write lands on (`stored` null/undefined = no stored row, a create). Mutates
|
|
114
|
+
* `content`. Returns null to proceed, or the refusal to send.
|
|
115
|
+
*
|
|
116
|
+
* For a stored row, the stored createdAt is authoritative whatever its value,
|
|
117
|
+
* an empty string included: a body that names a different value is refused,
|
|
118
|
+
* and a body that omits it keeps the stored value.
|
|
119
|
+
*/
|
|
120
|
+
export function applyServerCreatedAt(content, stored, mode, now = new Date()) {
|
|
121
|
+
if (stored == null) {
|
|
122
|
+
// No stored row: a create, so the server assigns createdAt.
|
|
123
|
+
content.createdAt = now.toISOString();
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
const storedAt = stored.createdAt;
|
|
127
|
+
if (Object.prototype.hasOwnProperty.call(content, "createdAt") && content.createdAt !== storedAt) {
|
|
128
|
+
return createdAtImmutable();
|
|
129
|
+
}
|
|
130
|
+
if (mode === "replace")
|
|
131
|
+
content.createdAt = storedAt;
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
@@ -56,12 +56,25 @@ function isStoredRow(value) {
|
|
|
56
56
|
/**
|
|
57
57
|
* CREATE path — stamp this instance's own federation id, ignoring any value the
|
|
58
58
|
* request body carried. Used by `post()` (always a create) and by a
|
|
59
|
-
* `put()`/`patch()` whose target id has no stored row yet.
|
|
59
|
+
* `put()`/`patch()` whose target id has no stored row yet. The id is this
|
|
60
|
+
* module's process-cached {@link localInstanceId}.
|
|
60
61
|
*/
|
|
61
62
|
export async function stampOriginatorOnCreate(content) {
|
|
63
|
+
applyOriginatorInstanceIdWith(content, null, await localInstanceId());
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* CREATE path with a CALLER-RESOLVED local id: the same stamp as
|
|
67
|
+
* {@link stampOriginatorOnCreate}, but the id is one the caller read from the
|
|
68
|
+
* CURRENT `Instance` table (a fresh read), never this module's process cache. A
|
|
69
|
+
* caller that must agree with a second decision on the same write — the
|
|
70
|
+
* Presence local home guard (resources/Presence.ts) compares an agent's home
|
|
71
|
+
* against the same id — resolves it once and passes it here, so both use ONE
|
|
72
|
+
* read and cannot disagree. A null id stamps null (the local-origin state).
|
|
73
|
+
*/
|
|
74
|
+
export function stampOriginatorOnCreateWith(content, localInstanceId) {
|
|
62
75
|
if (!isPlainObject(content))
|
|
63
76
|
return;
|
|
64
|
-
content.originatorInstanceId =
|
|
77
|
+
content.originatorInstanceId = localInstanceId;
|
|
65
78
|
}
|
|
66
79
|
/**
|
|
67
80
|
* UPDATE path — the STORED value stands. A body value is dropped (neither
|
|
@@ -87,7 +100,8 @@ export function keepStoredOriginator(content, stored) {
|
|
|
87
100
|
/**
|
|
88
101
|
* Apply the full create/update rule: `stored` is the row this write is over
|
|
89
102
|
* (null/undefined ⇒ a create). This is the one call a `put()` or `patch()` needs
|
|
90
|
-
* after it has resolved the pre-existing row.
|
|
103
|
+
* after it has resolved the pre-existing row. The create id is this module's
|
|
104
|
+
* process-cached {@link localInstanceId}.
|
|
91
105
|
*/
|
|
92
106
|
export async function applyOriginatorInstanceId(content, stored) {
|
|
93
107
|
if (isStoredRow(stored)) {
|
|
@@ -97,6 +111,22 @@ export async function applyOriginatorInstanceId(content, stored) {
|
|
|
97
111
|
await stampOriginatorOnCreate(content);
|
|
98
112
|
}
|
|
99
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Apply the full create/update rule with an explicitly resolved local id:
|
|
116
|
+
* `stored` is the row this write is over (null/undefined ⇒ a create, stamped
|
|
117
|
+
* with `localInstanceId`). The id is the caller's fresh read of the CURRENT
|
|
118
|
+
* `Instance` table, not this module's cache — used where a caller also decides
|
|
119
|
+
* the write by the current instance id (the Presence local home guard,
|
|
120
|
+
* resources/Presence.ts) so the two share ONE read.
|
|
121
|
+
*/
|
|
122
|
+
export function applyOriginatorInstanceIdWith(content, stored, localInstanceId) {
|
|
123
|
+
if (isStoredRow(stored)) {
|
|
124
|
+
keepStoredOriginator(content, stored);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
stampOriginatorOnCreateWith(content, localInstanceId);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
100
130
|
/**
|
|
101
131
|
* PATCH path — a patch MERGES into the stored row (Harper partial update), so a
|
|
102
132
|
* body value can be dropped and the stored value stands untouched.
|
|
@@ -200,7 +230,8 @@ function storedRowLookupFailure(tableName, err) {
|
|
|
200
230
|
* force a "create" that re-stamped an existing row.
|
|
201
231
|
*
|
|
202
232
|
* Rules:
|
|
203
|
-
* - a body `id` that
|
|
233
|
+
* - with a URL target id, a non-null body `id` that is not a string or
|
|
234
|
+
* number, or that disagrees with it, is REFUSED;
|
|
204
235
|
* - the stored row is read by the URL target id (via the raw table reader,
|
|
205
236
|
* falling back to the resource's own bound-record read when the table
|
|
206
237
|
* exposes no static reader — an in-process harness);
|
|
@@ -209,10 +240,11 @@ function storedRowLookupFailure(tableName, err) {
|
|
|
209
240
|
* An in-process call with no URL-bound id (a direct `new Resource().put(body)`)
|
|
210
241
|
* falls back to the body `id`, which IS the write key on that path.
|
|
211
242
|
*/
|
|
212
|
-
export async function resolveStoredRow(resource, tableName, content, getUrlBound) {
|
|
243
|
+
export async function resolveStoredRow(resource, tableName, content, getUrlBound, context) {
|
|
213
244
|
const targetId = urlTargetId(resource);
|
|
214
245
|
const bodyId = isPlainObject(content) && content.id != null ? content.id : undefined;
|
|
215
|
-
if (targetId != null && bodyId !== undefined &&
|
|
246
|
+
if (targetId != null && bodyId !== undefined &&
|
|
247
|
+
((typeof bodyId !== "string" && typeof bodyId !== "number") || String(bodyId) !== String(targetId))) {
|
|
216
248
|
return { row: null, denial: idTargetMismatchDenial(bodyId, targetId) };
|
|
217
249
|
}
|
|
218
250
|
const id = targetId ?? bodyId;
|
|
@@ -221,7 +253,7 @@ export async function resolveStoredRow(resource, tableName, content, getUrlBound
|
|
|
221
253
|
try {
|
|
222
254
|
const table = databases.flair?.[tableName];
|
|
223
255
|
if (table && typeof table.get === "function") {
|
|
224
|
-
const row = await table.get(id);
|
|
256
|
+
const row = await table.get(id, context ?? resource?.getContext?.());
|
|
225
257
|
return { row: isStoredRow(row) ? row : null };
|
|
226
258
|
}
|
|
227
259
|
// No static table reader (an in-process harness): read the resource's own
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* owner-delete-recheck.ts — the confirmation a non-admin owner-scoped delete
|
|
3
|
+
* runs before it removes a row (flair#2355).
|
|
4
|
+
*
|
|
5
|
+
* A non-admin delete reads the stored row, decides the caller owns it, then
|
|
6
|
+
* deletes it. Harper 5.2.8 has no compare-and-set on a table write: a
|
|
7
|
+
* transaction does not fail when a row it read is changed by another write
|
|
8
|
+
* before it commits; Harper applies both writes, ordered by transaction
|
|
9
|
+
* timestamp. So an owner change committed between that read and the
|
|
10
|
+
* confirmation read below — an admin/internal write, or a raw table write, as
|
|
11
|
+
* an operator or a migration would make — would let the delete remove a row
|
|
12
|
+
* that is no longer the caller's.
|
|
13
|
+
*
|
|
14
|
+
* This helper runs the read and the delete in ONE transaction the call OWNS
|
|
15
|
+
* (withOwnedTransaction), re-reads the row there, and, for a non-admin caller,
|
|
16
|
+
* pauses (a test-only point) between that read and the delete and re-reads the
|
|
17
|
+
* COMMITTED row before the delete is staged. A row whose owner had changed by
|
|
18
|
+
* that confirmation read is refused (`owner_changed`) and not deleted; a row
|
|
19
|
+
* absent at the first read is reported absent. A change committed after the
|
|
20
|
+
* confirmation read is not caught.
|
|
21
|
+
*
|
|
22
|
+
* The owner field is immutable to a non-admin's own writes
|
|
23
|
+
* (guardOwnerFieldImmutable, resources/owner-field-guard.ts), so the change this
|
|
24
|
+
* confirmation catches comes from an admin or internal write, or a raw table
|
|
25
|
+
* write — the writers that can re-point a stored row's owner.
|
|
26
|
+
*
|
|
27
|
+
* The confirmation read runs while the owned transaction is open, in an
|
|
28
|
+
* EXPLICIT fresh context (`{}`), never contextless: a contextless read joins the
|
|
29
|
+
* request's ambient operation transaction and reads that transaction's pinned
|
|
30
|
+
* read snapshot (flair#2147), and a by-id read on the request Resource
|
|
31
|
+
* instance reads that instance's request-time entry.
|
|
32
|
+
*/
|
|
33
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
34
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
35
|
+
/** The named error for a delete refused because the row's owner changed (flair#2355). */
|
|
36
|
+
export const OWNER_CHANGED_ERROR = "owner_changed";
|
|
37
|
+
/** The named 409 for a delete refused because an owner confirmation failed. */
|
|
38
|
+
export function ownerChangedRefusal(tableName) {
|
|
39
|
+
return new Response(JSON.stringify({
|
|
40
|
+
error: OWNER_CHANGED_ERROR,
|
|
41
|
+
message: `${tableName} owner confirmation failed; not deleted`,
|
|
42
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Delete `spec.id` in a transaction this call owns, refusing when the row read
|
|
46
|
+
* at the re-read or at the confirmation read has an owner other than
|
|
47
|
+
* `spec.callerId` (flair#2355).
|
|
48
|
+
*
|
|
49
|
+
* Returns `deleted` with the table delete's result, `absent` when the first
|
|
50
|
+
* read finds no row (the caller decides the no-op), or `refused` with the
|
|
51
|
+
* named 409 when the stored or confirmed row's owner is not the caller. A
|
|
52
|
+
* delete whose row exists but reports no success throws rather than a silent
|
|
53
|
+
* partial.
|
|
54
|
+
*/
|
|
55
|
+
export async function deleteOwnedRow(ctx, spec) {
|
|
56
|
+
return withOwnedTransaction(ctx, async (c) => {
|
|
57
|
+
const stored = await spec.table.get(spec.id, c);
|
|
58
|
+
if (!stored)
|
|
59
|
+
return { kind: "absent" };
|
|
60
|
+
if (stored[spec.ownerField] !== spec.callerId) {
|
|
61
|
+
return { kind: "refused", response: ownerChangedRefusal(spec.tableName) };
|
|
62
|
+
}
|
|
63
|
+
// Test-only: valid names are inert unless fault injection is enabled and armed.
|
|
64
|
+
const pause = txnPausePoint(spec.point);
|
|
65
|
+
if (pause)
|
|
66
|
+
await pause;
|
|
67
|
+
// Confirmation read: the committed row in an explicit fresh context (see
|
|
68
|
+
// this module's header — never contextless).
|
|
69
|
+
const confirmed = await spec.table.get(spec.id, {});
|
|
70
|
+
if (confirmed && confirmed[spec.ownerField] !== spec.callerId) {
|
|
71
|
+
return { kind: "refused", response: ownerChangedRefusal(spec.tableName) };
|
|
72
|
+
}
|
|
73
|
+
const result = await spec.table.delete(spec.id, c);
|
|
74
|
+
if (result !== true)
|
|
75
|
+
throw new Error(`${spec.tableName} row delete was not confirmed`);
|
|
76
|
+
return { kind: "deleted", result };
|
|
77
|
+
});
|
|
78
|
+
}
|
|
@@ -27,18 +27,43 @@
|
|
|
27
27
|
* not this rule's business — no-forge attribution on creation is each resource's
|
|
28
28
|
* own job. The decision itself is the pure `isForbiddenOwnerFieldChange`
|
|
29
29
|
* (record-owner-guard.ts), so it is unit-tested without a Harper instance.
|
|
30
|
+
*
|
|
31
|
+
* ─── Read-failure scope ─────────────────────────────────────────────────────
|
|
32
|
+
*
|
|
33
|
+
* For addressed single-record HTTP PUT/PATCH, Harper loads the row through
|
|
34
|
+
* `Table.getResource` → `resource._loadRecord` before the resource method runs;
|
|
35
|
+
* a no-argument `super.get()` then returns the cached row. If reached before
|
|
36
|
+
* that load, the non-admin write guard checks string or number body ids before stored ownership.
|
|
37
|
+
* Its stored-row read failure returns `owner_check_unavailable`. The
|
|
38
|
+
* real-Harper test injects an initial load failure: a non-admin agent gets that
|
|
39
|
+
* named refusal, and an administrator gets Harper's own 500. It does not cover
|
|
40
|
+
* collection paths.
|
|
41
|
+
*
|
|
42
|
+
* This guard returns `owner_check_unavailable` only when a non-admin agent's
|
|
43
|
+
* `getExisting` thunk throws or rejects. Admin/internal callers return before
|
|
44
|
+
* the thunk; unauthenticated callers receive 401 before it.
|
|
45
|
+
*
|
|
46
|
+
* Soul first reads through `resolveStoredRow` and passes an already-resolved row
|
|
47
|
+
* to this guard. That resolver's `stored_row_lookup_failed` (500) is a separate
|
|
48
|
+
* refusal for a read this guard does not backstop.
|
|
30
49
|
*/
|
|
31
50
|
import { resolveAgentAuth } from "./agent-auth.js";
|
|
32
|
-
import { isForbiddenOwnerFieldChange } from "./record-owner-guard.js";
|
|
51
|
+
import { isForbiddenOwnerFieldChange, ownerCheckUnavailable } from "./record-owner-guard.js";
|
|
52
|
+
// The named refusal and its constant live in record-owner-guard.ts, which has
|
|
53
|
+
// no authentication-module dependency, so the owner-scoped write guard can use
|
|
54
|
+
// them without importing this module;
|
|
55
|
+
// re-exported here for this module's existing importers.
|
|
56
|
+
export { OWNER_CHECK_UNAVAILABLE_ERROR, ownerCheckUnavailable } from "./record-owner-guard.js";
|
|
33
57
|
/**
|
|
34
58
|
* Enforce owner-field immutability for one write.
|
|
35
59
|
*
|
|
36
60
|
* @param self the resource instance (`this`)
|
|
37
|
-
* @param getExisting a thunk
|
|
38
|
-
*
|
|
61
|
+
* @param getExisting a thunk returning stored state, e.g. `() => super.get()`
|
|
62
|
+
* or Soul's already-resolved row
|
|
39
63
|
* @param content the write content (the caller's claim)
|
|
40
64
|
* @param ownerField the column naming the owning principal for this table
|
|
41
|
-
* @returns a
|
|
65
|
+
* @returns a Response to send (401 unauthenticated, 403 owner-field change,
|
|
66
|
+
* 400/503 non-admin agent's guard-thunk failure), or null to proceed
|
|
42
67
|
*/
|
|
43
68
|
export async function guardOwnerFieldImmutable(self, getExisting, content, ownerField) {
|
|
44
69
|
const auth = await resolveAgentAuth(self.getContext?.());
|
|
@@ -54,7 +79,16 @@ export async function guardOwnerFieldImmutable(self, getExisting, content, owner
|
|
|
54
79
|
if (auth.kind !== "agent") {
|
|
55
80
|
return new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "content-type": "application/json" } });
|
|
56
81
|
}
|
|
57
|
-
|
|
82
|
+
// A read that RESOLVED to null/undefined is "no stored row" (a create, which
|
|
83
|
+
// this rule leaves to each resource). A read that THREW or rejected is a
|
|
84
|
+
// FAILURE, and the guard refuses it rather than reading it as "no stored row".
|
|
85
|
+
let existing;
|
|
86
|
+
try {
|
|
87
|
+
existing = ((await Promise.resolve(getExisting())) ?? null);
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
return ownerCheckUnavailable(err);
|
|
91
|
+
}
|
|
58
92
|
if (isForbiddenOwnerFieldChange(existing, content, ownerField, auth.agentId)) {
|
|
59
93
|
return new Response(JSON.stringify({ error: "forbidden: the owner of a record cannot be changed" }), { status: 403, headers: { "content-type": "application/json" } });
|
|
60
94
|
}
|