@tpsdev-ai/flair 0.59.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 +4 -4
- package/SECURITY.md +36 -0
- package/config.yaml +12 -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 +991 -248
- package/dist/commands/agent.js +224 -43
- 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 +592 -146
- 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 +97 -35
- 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 +41 -10
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +4 -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 +24 -0
- 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 +1168 -326
- 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 +76 -12
- 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 +321 -1
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +10 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +751 -143
- 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 +110 -39
- 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/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 +181 -63
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/auth-middleware.js +400 -161
- 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 +72 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +120 -18
- 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 +3 -3
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +23 -6
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +128 -19
- 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/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 +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- 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 +20 -11
- 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 +4 -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 +146 -45
- package/docs/api-reference.md +46 -11
- package/docs/auth.md +6 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- 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 +5 -5
- package/docs/mcp-clients.md +5 -2
- 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 +12 -6
- 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 +10 -5
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +84 -5
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
|
@@ -75,6 +75,7 @@
|
|
|
75
75
|
* nor exempted with a stated reason. A table added later enters that test's
|
|
76
76
|
* scope the moment it declares the column — nobody has to know this file exists.
|
|
77
77
|
*/
|
|
78
|
+
import { routedRecordId } from "./request-target.js";
|
|
78
79
|
/**
|
|
79
80
|
* Table → the attribute naming the principal that owns a row.
|
|
80
81
|
*
|
|
@@ -121,6 +122,15 @@ export const OWNER_GUARD_EXEMPT = Object.freeze({
|
|
|
121
122
|
// writes stamp `authorId` from the authenticated principal; direct resource
|
|
122
123
|
// reads permit admins and trusted internal callers.
|
|
123
124
|
MemoryHostSource: "REST writes refused; application writes stamp authorId; direct reads limited to admins and trusted internal callers",
|
|
125
|
+
// Application append-only history; REST writes are refused.
|
|
126
|
+
InstructionVersion: "application append-only; REST writes refused",
|
|
127
|
+
// flair#2266: the private audit log of key registrations. Its `agentId` names
|
|
128
|
+
// the row whose key was registered (the AUDIT TARGET), not the caller — the
|
|
129
|
+
// caller is the admin in `actorId`. Its only application writer is
|
|
130
|
+
// resources/AgentKeyRegister.ts; the Flair resource route
|
|
131
|
+
// (resources/AgentKeyRegistration.ts) admits admin reads and refuses every
|
|
132
|
+
// write. The Harper operations API is a separate raw-table trust root.
|
|
133
|
+
AgentKeyRegistration: "admin-read-only audit log; Flair resource-route writes refused; the registration operation is its only application writer",
|
|
124
134
|
});
|
|
125
135
|
/** The verbs that can mutate a record, and therefore need the rule applied. */
|
|
126
136
|
export const MUTATING_METHODS = Object.freeze(["POST", "PUT", "PATCH", "DELETE"]);
|
|
@@ -128,33 +138,41 @@ export function isMutatingMethod(method) {
|
|
|
128
138
|
return MUTATING_METHODS.includes(method.toUpperCase());
|
|
129
139
|
}
|
|
130
140
|
/**
|
|
131
|
-
* Resolve a request
|
|
132
|
-
* null when the
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
141
|
+
* Resolve a raw request target to the guarded table and record id it
|
|
142
|
+
* addresses, or null when the target is not one this early check decides.
|
|
143
|
+
*
|
|
144
|
+
* `pathname` is the RAW request path (the target before its `?`). The id is the
|
|
145
|
+
* FULL decoded remainder after the table segment, so an id that itself contains
|
|
146
|
+
* `/`, raw or as `%2F`, resolves to the whole id rather than a shorter prefix.
|
|
147
|
+
*
|
|
148
|
+
* Matches `/<Table>/<id>` ONLY. A bare resource path has no record id; a
|
|
149
|
+
* trailing-slash path is a collection. The table segment is matched EXACTLY so
|
|
150
|
+
* `/SoulFeed/x` can never be read as a `Soul` route.
|
|
139
151
|
*/
|
|
140
152
|
export function resolveGuardedRecord(pathname) {
|
|
141
|
-
const
|
|
142
|
-
if (
|
|
153
|
+
const routed = routedRecordId(pathname);
|
|
154
|
+
if (!routed)
|
|
155
|
+
return null; // no record id, or malformed percent-encoding
|
|
156
|
+
return resolveGuardedRecordById(routed.resource, routed.id);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The guarded record for a resource and record id already resolved by Harper's
|
|
160
|
+
* own routing (resources/harper-routing.ts). Null when the resource is not a
|
|
161
|
+
* guarded table, or there is no record id. This is the form
|
|
162
|
+
* the middleware uses at request time, where the id has had Harper's
|
|
163
|
+
* content-type-suffix and property rules applied.
|
|
164
|
+
*/
|
|
165
|
+
export function resolveGuardedRecordById(resource, id) {
|
|
166
|
+
if (id == null || id === "")
|
|
143
167
|
return null;
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
if (!
|
|
168
|
+
// Own property only: an inherited name (`constructor`, `__proto__`, …) is not
|
|
169
|
+
// a table with an owner field.
|
|
170
|
+
if (!Object.prototype.hasOwnProperty.call(OWNER_FIELDS, resource))
|
|
147
171
|
return null;
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
id = decodeURIComponent(parts[1]);
|
|
151
|
-
}
|
|
152
|
-
catch {
|
|
153
|
-
return null; // malformed percent-encoding addresses no record we can resolve
|
|
154
|
-
}
|
|
155
|
-
if (!id)
|
|
172
|
+
const ownerField = OWNER_FIELDS[resource];
|
|
173
|
+
if (!ownerField)
|
|
156
174
|
return null;
|
|
157
|
-
return { table, ownerField, id };
|
|
175
|
+
return { table: resource, ownerField, id };
|
|
158
176
|
}
|
|
159
177
|
/**
|
|
160
178
|
* Decide whether a caller may mutate an already-stored record.
|
|
@@ -184,16 +202,46 @@ export function isForbiddenOwnerMutation(record, ownerField, callerAgentId) {
|
|
|
184
202
|
* principal: 403 with a body that names only the table.
|
|
185
203
|
*
|
|
186
204
|
* One constructor for every place the rule is enforced — the auth middleware
|
|
187
|
-
* for `/<Table>/<id>` routes,
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
* row.
|
|
205
|
+
* for `/<Table>/<id>` routes, resources/owner-scoped-write-policy.ts for a
|
|
206
|
+
* non-admin addressed write (POST/PUT/PATCH/DELETE to `/<Table>/<id>`) to an
|
|
207
|
+
* owner-scoped table, and resources/relay-ops.ts for a Message POST to the
|
|
208
|
+
* collection that reuses an existing message id. Carries no stored-row content.
|
|
191
209
|
*/
|
|
192
210
|
export function ownerMutationRefusal(table) {
|
|
193
211
|
return new Response(JSON.stringify({
|
|
194
212
|
error: `forbidden: cannot modify ${table} owned by another principal`,
|
|
195
213
|
}), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
196
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* The refusal for a non-admin PUT, PATCH or DELETE that addresses an
|
|
217
|
+
* owner-scoped table's collection rather than one record: 403 with a body that
|
|
218
|
+
* names only the table (resources/owner-scoped-write-policy.ts).
|
|
219
|
+
*/
|
|
220
|
+
export function collectionWriteRefusal(table) {
|
|
221
|
+
return new Response(JSON.stringify({
|
|
222
|
+
error: `forbidden: a non-admin write to ${table} must address one record by its id`,
|
|
223
|
+
}), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
224
|
+
}
|
|
225
|
+
/** The named refusal when a non-admin agent's stored-record read for an owner check fails. */
|
|
226
|
+
export const OWNER_CHECK_UNAVAILABLE_ERROR = "owner_check_unavailable";
|
|
227
|
+
/**
|
|
228
|
+
* Refuse a non-admin agent's write when the stored record its owner check
|
|
229
|
+
* needs cannot be read (resources/owner-field-guard.ts's guard thunk, and the
|
|
230
|
+
* owner-scoped write guard's stored-record read). A numeric 4xx `statusCode`
|
|
231
|
+
* maps to 400; anything else maps to 503. It logs the failure and has no
|
|
232
|
+
* authentication-module dependency, so the owner-scoped write guard can use it
|
|
233
|
+
* without importing that module graph; re-exported by
|
|
234
|
+
* resources/owner-field-guard.ts.
|
|
235
|
+
*/
|
|
236
|
+
export function ownerCheckUnavailable(err) {
|
|
237
|
+
console.error("owner-field-guard: the stored record could not be read, so the write was refused", { err });
|
|
238
|
+
const code = err?.statusCode;
|
|
239
|
+
const status = typeof code === "number" && code >= 400 && code < 500 ? 400 : 503;
|
|
240
|
+
return new Response(JSON.stringify({
|
|
241
|
+
error: OWNER_CHECK_UNAVAILABLE_ERROR,
|
|
242
|
+
message: "the stored record could not be read; the write was refused",
|
|
243
|
+
}), { status, headers: { "content-type": "application/json" } });
|
|
244
|
+
}
|
|
197
245
|
/**
|
|
198
246
|
* Decide whether a caller may CHANGE the owner field of an already-stored record.
|
|
199
247
|
*
|
|
@@ -403,7 +403,7 @@ export const RECORD_TYPES = {
|
|
|
403
403
|
// skill_search — skill-tagged Memory recall (flair#1546), rides SemanticSearch
|
|
404
404
|
// skill_get — full skill read by id (flair#1546), rides Memory.get
|
|
405
405
|
//
|
|
406
|
-
export const COMPOSITE_MCP_TOOLS = ["bootstrap", "attention", "record_usage", "memory_basement", "memory_restore", "skill_store", "skill_search", "skill_get"];
|
|
406
|
+
export const COMPOSITE_MCP_TOOLS = ["bootstrap", "attention", "record_usage", "memory_basement", "memory_restore", "skill_store", "skill_search", "skill_get", "team_directory"];
|
|
407
407
|
// ─── Runtime immutability ───────────────────────────────────────────────────
|
|
408
408
|
// Belt-and-suspenders backstop for the "static, compiled" invariant (see
|
|
409
409
|
// header doc). TypeScript's `as const satisfies` already gives compile-time
|
|
@@ -9,7 +9,10 @@
|
|
|
9
9
|
* All authorization decisions are made here against an already-resolved auth
|
|
10
10
|
* verdict; the resource layer only resolves the verdict and forwards the call.
|
|
11
11
|
*/
|
|
12
|
+
import { withKeyLock } from "./key-lock.js";
|
|
13
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
12
14
|
import { isForbiddenOwnerMutation, ownerMutationRefusal, OWNER_FIELDS } from "./record-owner-guard.js";
|
|
15
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
13
16
|
import { capDecision, computeContentHash, isUnconsumed, LOCAL_ORG_SENTINEL, reconcileState, sweepDecision, verifyMessageSignature, } from "./relay-lib.js";
|
|
14
17
|
// ─── HTTP responses (Response is a web global, not a Harper import) ──────────
|
|
15
18
|
const json = (status, obj) => new Response(JSON.stringify(obj), { status, headers: { "Content-Type": "application/json" } });
|
|
@@ -22,6 +25,37 @@ const BAD_REQUEST = (error) => json(400, { error });
|
|
|
22
25
|
const CONFLICT = (error) => json(409, { error, reason: "seq_conflict" });
|
|
23
26
|
/** Over-cap: a synchronous 4xx that names the reason — backpressure that fails loud. */
|
|
24
27
|
const INBOX_FULL = (scope) => json(429, { error: "inbox full", reason: "inbox_full", scope });
|
|
28
|
+
/** The message-id or sender lock could not be acquired: the send is refused. */
|
|
29
|
+
const SEND_BUSY = () => json(409, { error: "send in progress", reason: "send_contended" });
|
|
30
|
+
/** Without a per-key lock, serialization within one Harper process is
|
|
31
|
+
* unavailable: the send is refused. */
|
|
32
|
+
const SEND_LOCK_UNAVAILABLE = () => json(503, { error: "send lock unavailable", message: "the Message store has no per-key lock; the send was refused" });
|
|
33
|
+
// ─── send-time serialization ────────────────────────────────────────────────
|
|
34
|
+
/** First element of every relay-send lock key (resources/key-lock.ts), so a send
|
|
35
|
+
* lock never collides with another lock on the database. */
|
|
36
|
+
const SEND_LOCK_NAMESPACE = "flair-relay-send";
|
|
37
|
+
/** Per-lock retry schedule: SEND_LOCK_ATTEMPTS attempts, SEND_LOCK_WAIT_MS apart. */
|
|
38
|
+
const SEND_LOCK_ATTEMPTS = 200;
|
|
39
|
+
const SEND_LOCK_WAIT_MS = 10;
|
|
40
|
+
/**
|
|
41
|
+
* Run `fn` while holding every key in `keys`, acquired in the array's order
|
|
42
|
+
* (resources/key-lock.ts). A send holds its locks in ONE fixed order — message
|
|
43
|
+
* id, then recipient, then sender — and only ever waits for a lock later in
|
|
44
|
+
* that order than every lock it already holds, so no wait-for cycle (deadlock)
|
|
45
|
+
* is possible. Returns the innermost outcome: `{kind:"done", value}` when every
|
|
46
|
+
* lock was held and `fn` ran, `{kind:"busy"}` if any lock stayed held, or
|
|
47
|
+
* `{kind:"unavailable"}` if the store has no lock — in the last two cases `fn`
|
|
48
|
+
* never runs.
|
|
49
|
+
*/
|
|
50
|
+
async function withKeyLocks(store, keys, fn, attempts, waitMs) {
|
|
51
|
+
const run = async (i) => {
|
|
52
|
+
if (i >= keys.length)
|
|
53
|
+
return { kind: "done", value: await fn() };
|
|
54
|
+
const held = await withKeyLock(store, keys[i], () => run(i + 1), attempts, waitMs);
|
|
55
|
+
return held.kind === "done" ? held.value : held;
|
|
56
|
+
};
|
|
57
|
+
return run(0);
|
|
58
|
+
}
|
|
25
59
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
26
60
|
/**
|
|
27
61
|
* Materialize a table.search() result (async iterable | iterable | promise) to
|
|
@@ -32,11 +66,11 @@ const INBOX_FULL = (scope) => json(429, { error: "inbox full", reason: "inbox_fu
|
|
|
32
66
|
* call site remain the correctness guarantee (the unit-test table double ignores
|
|
33
67
|
* the query and returns every row); the conditions are the production index hint.
|
|
34
68
|
*/
|
|
35
|
-
async function queryRows(table, conditions = []) {
|
|
69
|
+
async function queryRows(table, conditions = [], ctx) {
|
|
36
70
|
const query = conditions.length > 0
|
|
37
71
|
? { operator: "and", conditions: conditions.map((c) => ({ attribute: c.attribute, comparator: "equals", value: c.value })) }
|
|
38
72
|
: undefined;
|
|
39
|
-
const res = table.search(query);
|
|
73
|
+
const res = table.search(query, ctx);
|
|
40
74
|
const iter = res && typeof res.then === "function" ? await res : res;
|
|
41
75
|
const out = [];
|
|
42
76
|
for await (const row of iter)
|
|
@@ -122,6 +156,40 @@ export async function relaySend(deps, auth, content) {
|
|
|
122
156
|
return BAD_REQUEST(`signature: ${verdict.reason}`);
|
|
123
157
|
// Store the server-recomputed canonical hash (verified equal above).
|
|
124
158
|
content.contentHash = computeContentHash(content);
|
|
159
|
+
// Within one Harper process, three per-key locks serialize a send's
|
|
160
|
+
// check-and-write, and are always acquired in ONE fixed order — message id,
|
|
161
|
+
// then recipient, then sender — so two sends can never deadlock: a send only
|
|
162
|
+
// ever waits for a lock that comes AFTER every lock it already holds, so no
|
|
163
|
+
// wait-for cycle exists. The id lock serializes id ownership; the recipient
|
|
164
|
+
// lock serializes the recipient-wide inbox cap; the sender lock serializes
|
|
165
|
+
// content dedup, thread sequence and the per-sender sub-cap. Cross-process
|
|
166
|
+
// coordination is out of scope: the lock is ONE Harper process's
|
|
167
|
+
// primary-store lock (flair#2333/#2461/#2462).
|
|
168
|
+
const store = deps.messages?.primaryStore;
|
|
169
|
+
const outcome = await withKeyLocks(store, [
|
|
170
|
+
[SEND_LOCK_NAMESPACE, "id", String(content.id)],
|
|
171
|
+
[SEND_LOCK_NAMESPACE, "recipient", String(content.to)],
|
|
172
|
+
[SEND_LOCK_NAMESPACE, "from", String(content.from)],
|
|
173
|
+
], () => withOwnedTransaction(deps.ctx, (owned) => storeAndDeliver(deps, content, owned)), SEND_LOCK_ATTEMPTS, SEND_LOCK_WAIT_MS);
|
|
174
|
+
if (outcome.kind === "busy")
|
|
175
|
+
return SEND_BUSY();
|
|
176
|
+
if (outcome.kind === "unavailable")
|
|
177
|
+
return SEND_LOCK_UNAVAILABLE();
|
|
178
|
+
// Test-only: pause after the send locks release and the owned transaction
|
|
179
|
+
// commits, before this request's transaction commits (flair#2333).
|
|
180
|
+
const committed = txnPausePoint("relay-send-lock-released");
|
|
181
|
+
if (committed)
|
|
182
|
+
await committed;
|
|
183
|
+
return outcome.value;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The delivery half of relaySend, run while holding the send locks (the
|
|
187
|
+
* message id's, the recipient's and the sender's): the id-ownership answer, the
|
|
188
|
+
* content dedup, the per-thread seq check, the recipient-wide cap check and the
|
|
189
|
+
* store. Extracted so the whole check-and-write runs under those locks; it is
|
|
190
|
+
* never called outside them.
|
|
191
|
+
*/
|
|
192
|
+
async function storeAndDeliver(deps, content, ctx) {
|
|
125
193
|
// Retry-dedup: an identical resend — same primary id, or the same content
|
|
126
194
|
// hash from this sender to this recipient — returns the already-accepted
|
|
127
195
|
// envelope. No second row, and (critically) no second charge against the cap.
|
|
@@ -137,7 +205,7 @@ export async function relaySend(deps, auth, content) {
|
|
|
137
205
|
// cannot be read, the send is refused the same way, never written over it.
|
|
138
206
|
let existingById;
|
|
139
207
|
try {
|
|
140
|
-
existingById = (await Promise.resolve(deps.messages.get(String(content.id)))) ?? null;
|
|
208
|
+
existingById = (await Promise.resolve(deps.messages.get(String(content.id), ctx))) ?? null;
|
|
141
209
|
}
|
|
142
210
|
catch {
|
|
143
211
|
return ownerMutationRefusal("Message");
|
|
@@ -150,7 +218,7 @@ export async function relaySend(deps, auth, content) {
|
|
|
150
218
|
}
|
|
151
219
|
// The recipient's inbox — queried by the @indexed `to`, never the whole table
|
|
152
220
|
// (Sherlock P0). Serves both dedup (same content from this sender) and the cap.
|
|
153
|
-
const recipientRows = await queryRows(deps.messages, [{ attribute: "to", value: content.to }]);
|
|
221
|
+
const recipientRows = await queryRows(deps.messages, [{ attribute: "to", value: content.to }], ctx);
|
|
154
222
|
const dup = recipientRows.find((r) => r.from === content.from && r.to === content.to && r.contentHash === content.contentHash);
|
|
155
223
|
if (dup)
|
|
156
224
|
return acceptedView(dup);
|
|
@@ -158,7 +226,7 @@ export async function relaySend(deps, auth, content) {
|
|
|
158
226
|
// STRICTLY ahead of the thread's last seq (Sherlock P1). Checked AFTER dedup so
|
|
159
227
|
// a legitimate retry (same content, caught above) is never rejected. Queried by
|
|
160
228
|
// the @indexed `threadId`, then filtered to this sender in-code.
|
|
161
|
-
const threadRows = await queryRows(deps.messages, [{ attribute: "threadId", value: content.threadId }]);
|
|
229
|
+
const threadRows = await queryRows(deps.messages, [{ attribute: "threadId", value: content.threadId }], ctx);
|
|
162
230
|
let prevMaxSeq = -1;
|
|
163
231
|
for (const r of threadRows) {
|
|
164
232
|
if (r.from !== content.from || r.threadId !== content.threadId)
|
|
@@ -194,7 +262,11 @@ export async function relaySend(deps, auth, content) {
|
|
|
194
262
|
state: "delivered",
|
|
195
263
|
deliveredAt: now,
|
|
196
264
|
};
|
|
197
|
-
|
|
265
|
+
// Test-only: pause between the checks above and the store below.
|
|
266
|
+
const pause = txnPausePoint("relay-send-write");
|
|
267
|
+
if (pause)
|
|
268
|
+
await pause;
|
|
269
|
+
await deps.messages.put(row, ctx);
|
|
198
270
|
return acceptedView(row);
|
|
199
271
|
}
|
|
200
272
|
// ─── inbox ──────────────────────────────────────────────────────────────────
|
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
* FederationSync (Federation.ts, via verifyFederationRequestBody).
|
|
10
10
|
*
|
|
11
11
|
* The XAA ID-JAG `jti` record (flair#2073) uses the same `recordOnce` on its
|
|
12
|
-
* own table; see `claimIdJagJti` below.
|
|
12
|
+
* own table; see `claimIdJagJti` below. The OAuth single-use record (flair#2145)
|
|
13
|
+
* uses it on one more, for claims to redeem an authorization code (`c:<sha256>`)
|
|
14
|
+
* or rotate a refresh token (`r:<sha256>`); see `claimOAuthSingleUse` below.
|
|
13
15
|
*
|
|
14
16
|
* The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
|
|
15
17
|
* `replicate: false`, `expiration: 120`). Every Harper thread of this instance
|
|
@@ -154,6 +156,7 @@ const REFUSED = {
|
|
|
154
156
|
a: "TPS-Ed25519 signed request",
|
|
155
157
|
f: "federation signed request",
|
|
156
158
|
x: "XAA jwt-bearer grant whose assertion carries a jti",
|
|
159
|
+
o: "OAuth request that redeems an authorization code or rotates a refresh token",
|
|
157
160
|
};
|
|
158
161
|
function noteUnavailable(scope, err, table = REPLAY_TABLE) {
|
|
159
162
|
const reason = err instanceof ReplayStoreUnavailable
|
|
@@ -276,7 +279,7 @@ export function verifyFederationRequestBody(body, publicKeyB64url) {
|
|
|
276
279
|
export const ID_JAG_REPLAY_TABLE = "IdJagReplay";
|
|
277
280
|
/** First element of every jti lock key, so a jti never shares a lock key with a nonce. */
|
|
278
281
|
export const ID_JAG_LOCK_NAMESPACE = "flair-replay-id-jag";
|
|
279
|
-
function idJagReplayDeps() {
|
|
282
|
+
export function idJagReplayDeps() {
|
|
280
283
|
return {
|
|
281
284
|
table: databases?.flair?.[ID_JAG_REPLAY_TABLE],
|
|
282
285
|
transaction: globalThis.transaction,
|
|
@@ -284,6 +287,20 @@ function idJagReplayDeps() {
|
|
|
284
287
|
lockNamespace: ID_JAG_LOCK_NAMESPACE,
|
|
285
288
|
};
|
|
286
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* The reason `deps`' table cannot remember a key for `minRetentionMs`, or null.
|
|
292
|
+
* `basis` completes the sentence that says what the minimum covers.
|
|
293
|
+
*/
|
|
294
|
+
export function storeRetentionGap(deps, minRetentionMs, basis) {
|
|
295
|
+
const gap = replayStoreContractGap(deps);
|
|
296
|
+
if (gap)
|
|
297
|
+
return gap;
|
|
298
|
+
const expirationMs = deps.table.expirationMS;
|
|
299
|
+
if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
|
|
300
|
+
return `flair.${deps.name ?? REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms ${basis}`;
|
|
301
|
+
}
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
287
304
|
/**
|
|
288
305
|
* Claim an ID-JAG's `jti` once per instance, through `recordOnce`. Call it after
|
|
289
306
|
* the assertion has validated and before the grant has any effect; refuse on
|
|
@@ -294,13 +311,9 @@ function idJagReplayDeps() {
|
|
|
294
311
|
export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
|
|
295
312
|
try {
|
|
296
313
|
const deps = idJagReplayDeps();
|
|
297
|
-
const gap =
|
|
314
|
+
const gap = storeRetentionGap(deps, minRetentionMs, "an assertion can stay acceptable");
|
|
298
315
|
if (gap)
|
|
299
316
|
throw new ReplayStoreUnavailable(gap);
|
|
300
|
-
const expirationMs = deps.table.expirationMS;
|
|
301
|
-
if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
|
|
302
|
-
throw new ReplayStoreUnavailable(`flair.${ID_JAG_REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms an assertion can stay acceptable`);
|
|
303
|
-
}
|
|
304
317
|
// A lock miss ("contended") is refused like a stored row.
|
|
305
318
|
return (await recordOnce(jti, now, deps)) === "recorded" ? "recorded" : "replay";
|
|
306
319
|
}
|
|
@@ -309,6 +322,43 @@ export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
|
|
|
309
322
|
return "unavailable";
|
|
310
323
|
}
|
|
311
324
|
}
|
|
325
|
+
// ─── OAuth single-use records (flair#2145) ─────────────────────────────────
|
|
326
|
+
/** One row per claim to redeem a code or rotate a refresh token (schemas/oauth.graphql). */
|
|
327
|
+
export const OAUTH_SINGLE_USE_TABLE = "OAuthSingleUse";
|
|
328
|
+
/** First element of every single-use lock key, so it never collides with a nonce or a jti lock. */
|
|
329
|
+
export const OAUTH_SINGLE_USE_LOCK_NAMESPACE = "flair-replay-oauth";
|
|
330
|
+
export function oauthSingleUseDeps() {
|
|
331
|
+
return {
|
|
332
|
+
table: databases?.flair?.[OAUTH_SINGLE_USE_TABLE],
|
|
333
|
+
transaction: globalThis.transaction,
|
|
334
|
+
name: OAUTH_SINGLE_USE_TABLE,
|
|
335
|
+
lockNamespace: OAUTH_SINGLE_USE_LOCK_NAMESPACE,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Claim an authorization code presented for redemption (`c:<sha256>`) or a
|
|
340
|
+
* refresh token presented for rotation (`r:<sha256>`) once per instance,
|
|
341
|
+
* through `recordOnce`. Call it after the request has been validated and before
|
|
342
|
+
* the handler attempts its later write or token issuance; refuse on anything
|
|
343
|
+
* but "recorded". `sha256Hex` is the SHA-256 of the code or token, so the
|
|
344
|
+
* record holds no redeemable secret. `minRetentionMs` is the longest the code
|
|
345
|
+
* or token can be presented after its row is recorded: a table whose rows do
|
|
346
|
+
* not outlive it is unavailable.
|
|
347
|
+
*/
|
|
348
|
+
export async function claimOAuthSingleUse(kind, sha256Hex, minRetentionMs, now = Date.now()) {
|
|
349
|
+
try {
|
|
350
|
+
const deps = oauthSingleUseDeps();
|
|
351
|
+
const gap = storeRetentionGap(deps, minRetentionMs, "a redeemed authorization code or refresh token can be presented");
|
|
352
|
+
if (gap)
|
|
353
|
+
throw new ReplayStoreUnavailable(gap);
|
|
354
|
+
// A lock miss ("contended") is refused like a stored row.
|
|
355
|
+
return (await recordOnce(`${kind === "refresh" ? "r" : "c"}:${sha256Hex}`, now, deps)) === "recorded" ? "recorded" : "replay";
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
noteUnavailable("o", err, OAUTH_SINGLE_USE_TABLE);
|
|
359
|
+
return "unavailable";
|
|
360
|
+
}
|
|
361
|
+
}
|
|
312
362
|
// ─── Boot report ───────────────────────────────────────────────────────────
|
|
313
363
|
/** Every gap that would refuse requests on this thread, or an empty list. */
|
|
314
364
|
export function replayStoreBootGaps(deps = harperReplayDeps()) {
|
|
@@ -320,17 +370,44 @@ export function replayStoreBootGaps(deps = harperReplayDeps()) {
|
|
|
320
370
|
}
|
|
321
371
|
return gaps;
|
|
322
372
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
373
|
+
/** Run during the awaited resource-module import, after graphqlSchema loads. */
|
|
374
|
+
function reportAtBoot(fn) {
|
|
375
|
+
// Harper defines `server.workerCount` on worker threads; unit tests and the
|
|
376
|
+
// CLI never reach this. The jsResource initial load awaits module imports,
|
|
377
|
+
// and the worker waits for that load before it starts listening.
|
|
378
|
+
if (typeof globalThis.server?.workerCount !== "number")
|
|
379
|
+
return;
|
|
380
|
+
try {
|
|
381
|
+
fn();
|
|
382
|
+
}
|
|
383
|
+
catch (err) {
|
|
384
|
+
console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
// Once per worker thread, after the schema's tables are bound.
|
|
388
|
+
reportAtBoot(() => {
|
|
389
|
+
for (const gap of replayStoreBootGaps()) {
|
|
390
|
+
console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
/**
|
|
394
|
+
* Every gap that would refuse a request through `store` on this thread, each
|
|
395
|
+
* labelled with the store's name, or an empty list.
|
|
396
|
+
*/
|
|
397
|
+
export function replayStoreStoreGaps(store) {
|
|
398
|
+
const gap = storeRetentionGap(store.deps(), store.minRetentionMs, store.retentionBasis);
|
|
399
|
+
return gap ? [`${store.label}: ${gap}`] : [];
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Print `store`'s gaps once per worker thread at boot, beside the replay
|
|
403
|
+
* guards' (`replayStoreBootGaps`): a misconfigured table is named before the
|
|
404
|
+
* first request instead of on the first claim. Call it at module load, from the
|
|
405
|
+
* module that owns the store, while Harper awaits that resource import.
|
|
406
|
+
*/
|
|
407
|
+
export function reportReplayStoreGapsAtBoot(store) {
|
|
408
|
+
reportAtBoot(() => {
|
|
409
|
+
for (const gap of replayStoreStoreGaps(store)) {
|
|
410
|
+
console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Requests through that store are refused until it is usable (see resources/replay-store.ts).`);
|
|
334
411
|
}
|
|
335
|
-
}
|
|
412
|
+
});
|
|
336
413
|
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* request-target.ts — the raw request target the auth middleware decides on.
|
|
3
|
+
*
|
|
4
|
+
* Before any other request processing, the middleware answers a target that is not in
|
|
5
|
+
* canonical form with a named 400 (`non_canonical_request_target`). A raw
|
|
6
|
+
* target is canonical unless its path (the part before the first `?`) has:
|
|
7
|
+
*
|
|
8
|
+
* - a `.` or `..` segment, raw or percent-encoded as a whole segment
|
|
9
|
+
* (`%2e`, `%2E%2e`, `.%2e`, …);
|
|
10
|
+
* - repeated slashes (`//`) anywhere in the path;
|
|
11
|
+
* - a raw backslash.
|
|
12
|
+
*
|
|
13
|
+
* Everything else is canonical, including `%2F` and `%5C` inside a segment, a
|
|
14
|
+
* dot inside a segment (`a.b`), and any query string.
|
|
15
|
+
*
|
|
16
|
+
* PURE: string logic only, imports nothing.
|
|
17
|
+
*/
|
|
18
|
+
/** The named error a non-canonical request target is refused with. */
|
|
19
|
+
export const NON_CANONICAL_REQUEST_TARGET_ERROR = "non_canonical_request_target";
|
|
20
|
+
/** A whole segment that is `.` or `..`, each dot raw or percent-encoded. */
|
|
21
|
+
const DOT_SEGMENT = /^(?:\.|%2e){1,2}$/i;
|
|
22
|
+
/**
|
|
23
|
+
* The path part of a raw request target: everything before the first `?`.
|
|
24
|
+
*/
|
|
25
|
+
export function requestPath(rawTarget) {
|
|
26
|
+
const q = rawTarget.indexOf("?");
|
|
27
|
+
return q === -1 ? rawTarget : rawTarget.slice(0, q);
|
|
28
|
+
}
|
|
29
|
+
/** True when a raw request target is in canonical form (see the module header). */
|
|
30
|
+
export function isCanonicalRequestTarget(rawTarget) {
|
|
31
|
+
const path = requestPath(rawTarget);
|
|
32
|
+
if (path.includes("\\"))
|
|
33
|
+
return false;
|
|
34
|
+
if (path.includes("//"))
|
|
35
|
+
return false;
|
|
36
|
+
return !path.split("/").some((segment) => DOT_SEGMENT.test(segment));
|
|
37
|
+
}
|
|
38
|
+
/** The named 400 for a non-canonical request target. HEAD gets no body. */
|
|
39
|
+
export function nonCanonicalRequestTargetRefusal(method) {
|
|
40
|
+
const body = JSON.stringify({
|
|
41
|
+
error: NON_CANONICAL_REQUEST_TARGET_ERROR,
|
|
42
|
+
message: "the request target must be in canonical form: no '.' or '..' path segment, no repeated slashes (`//`), and no backslash",
|
|
43
|
+
});
|
|
44
|
+
return new Response(method === "HEAD" ? null : body, {
|
|
45
|
+
status: 400,
|
|
46
|
+
headers: { "content-type": "application/json" },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The raw path's segments, split on `/` FIRST and still percent-encoded.
|
|
51
|
+
* Empty segments are dropped.
|
|
52
|
+
*/
|
|
53
|
+
export function rawPathSegments(path) {
|
|
54
|
+
return path.split("/").filter(Boolean);
|
|
55
|
+
}
|
|
56
|
+
/** The last raw segment of a path (still percent-encoded). */
|
|
57
|
+
export function lastRawPathSegment(path) {
|
|
58
|
+
return path.slice(path.lastIndexOf("/") + 1);
|
|
59
|
+
}
|
|
60
|
+
/** Decode one raw path segment; null when it is not valid percent-encoding. */
|
|
61
|
+
export function decodePathSegment(segment) {
|
|
62
|
+
try {
|
|
63
|
+
return decodeURIComponent(segment);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* For a plain one-level resource path, return the first segment and the
|
|
71
|
+
* still-encoded remainder after it, removing one leading slash.
|
|
72
|
+
*/
|
|
73
|
+
export function routedResourceAndRemainder(path) {
|
|
74
|
+
const p = path.startsWith("/") ? path.slice(1) : path;
|
|
75
|
+
const slash = p.indexOf("/");
|
|
76
|
+
if (slash === -1)
|
|
77
|
+
return { resource: p, remainder: "" };
|
|
78
|
+
return { resource: p.slice(0, slash), remainder: p.slice(slash + 1) };
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Return the resource segment and fully decoded remainder (the initial
|
|
82
|
+
* RequestTarget id for a plain one-level resource path). `parsePath` can change
|
|
83
|
+
* the final row id. Null for an empty, trailing-slash or malformed remainder.
|
|
84
|
+
*/
|
|
85
|
+
export function routedRecordId(path) {
|
|
86
|
+
const { resource, remainder } = routedResourceAndRemainder(path);
|
|
87
|
+
if (remainder === "" || remainder.endsWith("/"))
|
|
88
|
+
return null;
|
|
89
|
+
let id;
|
|
90
|
+
try {
|
|
91
|
+
id = decodeURIComponent(remainder);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
if (id === "")
|
|
97
|
+
return null;
|
|
98
|
+
return { resource, id };
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Return the prefix before the first dot when its suffix is in
|
|
102
|
+
* `declaredAttributes`; otherwise return the id unchanged.
|
|
103
|
+
*/
|
|
104
|
+
export function routedIdAfterPropertyRule(id, declaredAttributes) {
|
|
105
|
+
const dot = id.indexOf(".");
|
|
106
|
+
if (dot > -1 && declaredAttributes.has(id.slice(dot + 1)))
|
|
107
|
+
return id.slice(0, dot);
|
|
108
|
+
return id;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Return the first nonempty segment if `isKnown` accepts it, otherwise its
|
|
112
|
+
* prefix before the first dot if accepted, otherwise the segment unchanged.
|
|
113
|
+
*/
|
|
114
|
+
export function routedFirstResourceName(path, isKnown) {
|
|
115
|
+
const seg = rawPathSegments(path)[0] ?? "";
|
|
116
|
+
if (isKnown(seg))
|
|
117
|
+
return seg;
|
|
118
|
+
const dot = seg.indexOf(".");
|
|
119
|
+
if (dot > -1 && isKnown(seg.slice(0, dot)))
|
|
120
|
+
return seg.slice(0, dot);
|
|
121
|
+
return seg;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* For a path with one leading slash, return it with the first segment replaced
|
|
125
|
+
* by `routedFirstResourceName`; unchanged when that name does not change.
|
|
126
|
+
*/
|
|
127
|
+
export function routedResourcePath(path, known) {
|
|
128
|
+
const segs = rawPathSegments(path);
|
|
129
|
+
const first = segs[0];
|
|
130
|
+
if (first === undefined)
|
|
131
|
+
return path;
|
|
132
|
+
const name = routedFirstResourceName(path, (n) => known.has(n));
|
|
133
|
+
if (name === first)
|
|
134
|
+
return path;
|
|
135
|
+
return `/${name}${path.slice(1 + first.length)}`;
|
|
136
|
+
}
|
|
@@ -76,3 +76,38 @@ export async function withOwnedTransaction(ctx, fn) {
|
|
|
76
76
|
ctx.transaction = saved;
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
|
+
/** Marks a context whose OPEN write transaction belongs to an in-process
|
|
80
|
+
* caller that composes a Memory write into it. A Symbol, so no request body
|
|
81
|
+
* or header can set it. */
|
|
82
|
+
const COMPOSED_WRITE = Symbol("flair.composedMemoryWrite");
|
|
83
|
+
/**
|
|
84
|
+
* Run `fn` in a shared write transaction ({@link withSharedWriteTransaction})
|
|
85
|
+
* and mark `shared` for the duration, so `Memory.put()` JOINS this transaction
|
|
86
|
+
* instead of owning one (flair#2478 slice 1, part 1). The caller owns the
|
|
87
|
+
* commit: its own writes in `fn` commit or abort with the Memory row. Manual
|
|
88
|
+
* promotion uses it, so its Memory write and verdict stamp stay one
|
|
89
|
+
* transaction (flair#2354). The per-id write lock orders the put's read and
|
|
90
|
+
* decision against other owner PUT/PATCH writers of that id, but this
|
|
91
|
+
* transaction commits after the lock is released, so its commit is not
|
|
92
|
+
* serialized with theirs; writers that take no lock are not serialized at all.
|
|
93
|
+
*/
|
|
94
|
+
export async function withComposedWriteTransaction(ctx, fn) {
|
|
95
|
+
return withSharedWriteTransaction(ctx, async (shared) => {
|
|
96
|
+
const had = Object.prototype.hasOwnProperty.call(shared, COMPOSED_WRITE);
|
|
97
|
+
const prior = shared[COMPOSED_WRITE];
|
|
98
|
+
shared[COMPOSED_WRITE] = true;
|
|
99
|
+
try {
|
|
100
|
+
return await fn(shared);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
if (had)
|
|
104
|
+
shared[COMPOSED_WRITE] = prior;
|
|
105
|
+
else
|
|
106
|
+
delete shared[COMPOSED_WRITE];
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/** Is `ctx` inside {@link withComposedWriteTransaction} with its transaction still open? */
|
|
111
|
+
export function composesCallerWrite(ctx) {
|
|
112
|
+
return !!ctx && ctx[COMPOSED_WRITE] === true && isJoinableTransaction(ctx);
|
|
113
|
+
}
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
* search) is what clears `empty`.
|
|
29
29
|
*/
|
|
30
30
|
import { bm25SearchLagReason } from "./bm25-status.js";
|
|
31
|
+
import { MEMORY_REEMBED_PATCH_CAPABILITY } from "../src/lib/reembed-server-support.js";
|
|
31
32
|
/**
|
|
32
33
|
* How a ready result was verified. Constant strings — no interpolation
|
|
33
34
|
* (flair#1411). Public /Health still omits this field when searchReady is
|
|
@@ -117,8 +118,10 @@ export function buildPublicHealthBody(readiness, identity) {
|
|
|
117
118
|
version: identity.version,
|
|
118
119
|
buildCommit: identity.buildCommit,
|
|
119
120
|
searchReady: readiness.searchReady,
|
|
121
|
+
// flair#2337: this build advertises the re-embed PATCH token.
|
|
122
|
+
// The shared constant aligns this build's CLI and server literals.
|
|
123
|
+
capabilities: [MEMORY_REEMBED_PATCH_CAPABILITY],
|
|
120
124
|
};
|
|
121
|
-
// Public shape is unchanged: searchReadyReason is still present iff !searchReady.
|
|
122
125
|
// Ready-path verification constants stay on the decision object (flair#1411).
|
|
123
126
|
if (!readiness.searchReady && readiness.searchReadyReason) {
|
|
124
127
|
body.searchReadyReason = readiness.searchReadyReason;
|