@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
|
@@ -1,13 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { WRITE_BACK_ATTEMPTS, WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
|
|
2
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
2
3
|
import { server, databases } from "harper";
|
|
3
|
-
import { getEmbedding } from "./embeddings-provider.js";
|
|
4
|
-
import {
|
|
4
|
+
import { getEmbedding, getModelId } from "./embeddings-provider.js";
|
|
5
|
+
import { noteWriteStamp } from "./embedding-space-guard.js";
|
|
6
|
+
import { hashEmbeddedText } from "./memory-embed-hash.js";
|
|
7
|
+
import { MEMORY_EMBEDDING_INPUT_FIELDS, skillEmbedText } from "./skill-write.js";
|
|
8
|
+
import { isAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME, readCredentialedPrincipal, AGENT_LOOKUP_FAILED } from "./agent-auth.js";
|
|
5
9
|
import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
|
|
6
10
|
import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
|
|
7
|
-
import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord } from "./record-owner-guard.js";
|
|
11
|
+
import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord, resolveGuardedRecordById } from "./record-owner-guard.js";
|
|
12
|
+
import { routeWithHarper } from "./harper-routing.js";
|
|
8
13
|
import { checkHttpRateLimit } from "./rate-limit.js";
|
|
9
14
|
import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
|
|
10
|
-
import {
|
|
15
|
+
import { DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
|
|
16
|
+
import { idSegmentHasEncodedSlash, decodeMemoryIdSegment, MEMORY_CONTENT_SELECTOR_SUFFIX } from "../src/lib/memory-id-policy.js";
|
|
17
|
+
import { contentSuffixIdDenial } from "./memory-id-guard.js";
|
|
18
|
+
import { isCanonicalRequestTarget, nonCanonicalRequestTargetRefusal, requestPath, lastRawPathSegment, routedRecordId, routedResourceAndRemainder, routedIdAfterPropertyRule, routedResourcePath, } from "./request-target.js";
|
|
11
19
|
// --- Non-admin Memory read: ignore the caller's selection --------------------
|
|
12
20
|
//
|
|
13
21
|
// flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
|
|
@@ -19,30 +27,38 @@ const DECLARED_MEMORY_ATTRIBUTE_SET = new Set(DECLARED_MEMORY_ATTRIBUTES);
|
|
|
19
27
|
function isMemoryReadPath(pathname) {
|
|
20
28
|
return pathname === "/Memory" || pathname === "/Memory/" || pathname.startsWith("/Memory/");
|
|
21
29
|
}
|
|
30
|
+
/** True when a path segment is valid percent-encoding. */
|
|
31
|
+
function isValidPercentEncoding(segment) {
|
|
32
|
+
try {
|
|
33
|
+
decodeURIComponent(segment);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
22
40
|
// Drop a caller's `select(...)` and `property` from a Memory read URL, keeping
|
|
23
41
|
// conditions, operator, sort, limit and offset. Returns the input unchanged when
|
|
24
42
|
// the URL carries no selection.
|
|
25
|
-
|
|
43
|
+
//
|
|
44
|
+
// The path rewrite runs ONLY when Harper routed this target to a Memory RECORD
|
|
45
|
+
// (`routedToMemoryRecord`): the raw path alone is not enough, because a target
|
|
46
|
+
// Harper resolved with no record id — e.g. `/Memory.json/<id>.content`, whose
|
|
47
|
+
// suffixed first segment routes to the Memory COLLECTION with an empty remainder
|
|
48
|
+
// — must not be turned into a by-id read of a row the target does not address.
|
|
49
|
+
function stripMemorySelection(rawUrl, routedToMemoryRecord) {
|
|
26
50
|
const q = rawUrl.indexOf("?");
|
|
27
51
|
let pathPart = q === -1 ? rawUrl : rawUrl.slice(0, q);
|
|
28
52
|
let query = q === -1 ? "" : rawUrl.slice(q + 1);
|
|
29
|
-
//
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const slash = pathPart.lastIndexOf("/");
|
|
39
|
-
const seg = pathPart.slice(slash + 1);
|
|
40
|
-
const decodedSeg = decodePathSegment(seg);
|
|
41
|
-
const dot = decodedSeg.indexOf(".");
|
|
42
|
-
if (dot > -1 && DECLARED_MEMORY_ATTRIBUTE_SET.has(decodedSeg.slice(dot + 1))) {
|
|
43
|
-
// Rebuild the id from its decoded form. Harper decodes the path it is handed,
|
|
44
|
-
// so this re-encoded segment addresses the SAME id, without the property.
|
|
45
|
-
pathPart = `${pathPart.slice(0, slash + 1)}${encodeURIComponent(decodedSeg.slice(0, dot))}`;
|
|
53
|
+
// Strip a declared-attribute suffix after the first dot in the decoded remainder.
|
|
54
|
+
const { remainder } = routedResourceAndRemainder(pathPart);
|
|
55
|
+
const decodedId = decodeMemoryIdSegment(remainder);
|
|
56
|
+
const stripped = routedIdAfterPropertyRule(decodedId, DECLARED_MEMORY_ATTRIBUTE_SET);
|
|
57
|
+
// An encoded `/` in the id makes the suffix ambiguous (the caller is refused
|
|
58
|
+
// upstream in the middleware), so only rewrite when there is no encoded slash
|
|
59
|
+
// and the first-dot rule actually dropped a declared-attribute suffix.
|
|
60
|
+
if (routedToMemoryRecord && !idSegmentHasEncodedSlash(remainder) && stripped !== decodedId) {
|
|
61
|
+
pathPart = `/Memory/${encodeURIComponent(stripped)}`;
|
|
46
62
|
}
|
|
47
63
|
// Query form: drop every `select(...)` token and every `property` parameter.
|
|
48
64
|
for (const [start, end] of selectSpans(query).reverse()) {
|
|
@@ -59,16 +75,19 @@ function stripMemorySelection(rawUrl) {
|
|
|
59
75
|
return pathPart;
|
|
60
76
|
return query === "" ? pathPart : `${pathPart}?${query}`;
|
|
61
77
|
}
|
|
62
|
-
/**
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
78
|
+
/**
|
|
79
|
+
* True when a Memory by-id read path names an id that carries an encoded `/`
|
|
80
|
+
* (`%2F`/`%2f`) AND would otherwise be given the property-suffix rewrite in
|
|
81
|
+
* stripMemorySelection. Such an id is ambiguous — the trailing
|
|
82
|
+
* `.<declared attribute>` could be part of the id or a selector on an id that
|
|
83
|
+
* contains a slash (flair#2199).
|
|
84
|
+
*/
|
|
85
|
+
function isAmbiguousEncodedSlashSelector(rawUrl) {
|
|
86
|
+
const { remainder } = routedResourceAndRemainder(requestPath(rawUrl));
|
|
87
|
+
if (!idSegmentHasEncodedSlash(remainder))
|
|
88
|
+
return false;
|
|
89
|
+
const decodedId = decodeMemoryIdSegment(remainder);
|
|
90
|
+
return routedIdAfterPropertyRule(decodedId, DECLARED_MEMORY_ATTRIBUTE_SET) !== decodedId;
|
|
72
91
|
}
|
|
73
92
|
// [start, end) ranges of every `select(...)` call in a query string, accounting
|
|
74
93
|
// for Harper's nested-list form `select((a,b))`.
|
|
@@ -144,26 +163,149 @@ function getAdminPass() {
|
|
|
144
163
|
// them, and the crypto/decoder logic can't drift.
|
|
145
164
|
async function backfillEmbedding(memoryId) {
|
|
146
165
|
try {
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
166
|
+
const table = databases.flair.Memory;
|
|
167
|
+
// flair#2484: compute the vector before the owned write transaction opens.
|
|
168
|
+
// The text embedded is the one Memory's own writers embed (flair#2465,
|
|
169
|
+
// `skillEmbedText`: a skill-tagged row's non-empty `trigger`, else
|
|
170
|
+
// `content`). Rows without that text or with an embedding longer than 100
|
|
171
|
+
// entries skip before the text comparison. For eligible rows, `matchFields`
|
|
172
|
+
// compares every field that selects the text (`content`, `trigger`, `tags`)
|
|
173
|
+
// before staging; the helper confirms the committed row afterward. Drift
|
|
174
|
+
// observed by either check aborts the attempt; remaining outer attempts
|
|
175
|
+
// re-read and may recompute. Changes after confirmation and before commit
|
|
176
|
+
// are not detected by these checks.
|
|
177
|
+
//
|
|
178
|
+
// flair#2573: the vector is stamped with the current model id, the space it
|
|
179
|
+
// was computed in, and the embedding-space guard is notified after the write
|
|
180
|
+
// commits with that stamp and the row it replaced, as for any other notified
|
|
181
|
+
// vector write.
|
|
182
|
+
for (let attempt = 1; attempt <= WRITE_BACK_ATTEMPTS; attempt++) {
|
|
183
|
+
const record = await table.get(memoryId, {});
|
|
184
|
+
const text = record ? skillEmbedText(record) : undefined;
|
|
185
|
+
if (typeof text !== "string" || text.length === 0)
|
|
186
|
+
return;
|
|
187
|
+
if (record.embedding?.length > 100)
|
|
188
|
+
return;
|
|
189
|
+
const embedding = await getEmbedding(text, "document");
|
|
190
|
+
if (!Array.isArray(embedding) || embedding.length === 0)
|
|
191
|
+
return;
|
|
192
|
+
const model = getModelId();
|
|
193
|
+
// The vector fields of the committed row the update replaces, for the
|
|
194
|
+
// guard notification.
|
|
195
|
+
let replaced = null;
|
|
196
|
+
try {
|
|
197
|
+
const outcome = await writeBackCommittedRow(table, memoryId, (row) => {
|
|
198
|
+
const rowText = row ? skillEmbedText(row) : undefined;
|
|
199
|
+
if (typeof rowText !== "string" || rowText.length === 0)
|
|
200
|
+
return { skip: true };
|
|
201
|
+
if (row.embedding?.length > 100)
|
|
202
|
+
return { skip: true };
|
|
203
|
+
replaced = { embedding: row.embedding, embeddingModel: row.embeddingModel };
|
|
204
|
+
// Only `embedding`, its model stamp and its text hash: an incremental
|
|
205
|
+
// update, never a full-row put of the row read above (flair#2470,
|
|
206
|
+
// flair#2465). The newly computed hash is of `text`, the text this
|
|
207
|
+
// vector was computed from (null for an empty owner).
|
|
208
|
+
return { update: { embedding, embeddingModel: model, embeddedContentHash: hashEmbeddedText(row.agentId, text) ?? null } };
|
|
209
|
+
}, {
|
|
210
|
+
label: "backfillEmbedding",
|
|
211
|
+
expectedRow: record,
|
|
212
|
+
// Compare the text-selecting fields before staging, after the plan's skip checks.
|
|
213
|
+
matchFields: [...MEMORY_EMBEDDING_INPUT_FIELDS, "tags"],
|
|
214
|
+
pausePre: () => txnPausePoint("backfill-embedding-pre"),
|
|
215
|
+
pausePoint: () => txnPausePoint("backfill-embedding"),
|
|
216
|
+
});
|
|
217
|
+
if ("update" in outcome) {
|
|
218
|
+
// After the commit: the stamp the update stored (an absent one reads as
|
|
219
|
+
// untrusted and closes the guard) and the row it replaced.
|
|
220
|
+
noteWriteStamp(outcome.update.embeddingModel, replaced);
|
|
221
|
+
console.log(`[auto-embed] ${memoryId}: ${outcome.update.embedding.length}d`);
|
|
222
|
+
}
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
catch (err) {
|
|
226
|
+
if (err instanceof WriteBackConflictError && attempt < WRITE_BACK_ATTEMPTS)
|
|
227
|
+
continue;
|
|
228
|
+
throw err;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
161
231
|
}
|
|
162
232
|
catch (err) {
|
|
163
233
|
console.error(`[auto-embed] Failed for ${memoryId}: ${err.message}`);
|
|
164
234
|
}
|
|
165
235
|
}
|
|
166
236
|
// ─── HTTP middleware ──────────────────────────────────────────────────────────
|
|
237
|
+
/**
|
|
238
|
+
* Refuse a credentialed Basic-auth request whose Agent row could not be READ:
|
|
239
|
+
* log the named error and return it. A read that FAILED is never an absent
|
|
240
|
+
* principal (flair#2403); the same rule resources/AgentSeed.ts applies as
|
|
241
|
+
* `agent_lookup_failed`.
|
|
242
|
+
*/
|
|
243
|
+
function credentialedLookupRefusal(username, error) {
|
|
244
|
+
console.error("auth-middleware: the credentialed principal lookup failed, so the request was refused", { username, error });
|
|
245
|
+
return new Response(JSON.stringify({
|
|
246
|
+
error: AGENT_LOOKUP_FAILED,
|
|
247
|
+
message: "the principal record could not be read, so the request was refused",
|
|
248
|
+
}), { status: 500, headers: { "content-type": "application/json" } });
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* A guarded mutation whose stored-owner read FAILED is refused, not allowed
|
|
252
|
+
* through. The ownership read is the authorization input; a failed read is not
|
|
253
|
+
* "no owner", so it must fail closed. 503 because a retry can succeed.
|
|
254
|
+
*/
|
|
255
|
+
function ownerReadFailedRefusal(table) {
|
|
256
|
+
console.error("auth-middleware: the stored-owner read failed, so the mutation was refused", { table });
|
|
257
|
+
return new Response(JSON.stringify({
|
|
258
|
+
error: "owner_lookup_failed",
|
|
259
|
+
message: "the record's owner could not be read, so the write was refused",
|
|
260
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* A signed non-admin agent's mutation that reaches the owner checks is refused
|
|
264
|
+
* when Harper's route lookup threw: the owner decisions need Harper's route, and
|
|
265
|
+
* the pure fallback does not stand in for it. 503 because a retry can succeed. The message is fixed and
|
|
266
|
+
* names no part of the target.
|
|
267
|
+
*/
|
|
268
|
+
function routeLookupFailedRefusal() {
|
|
269
|
+
console.error("auth-middleware: the route lookup failed, so the mutation was refused");
|
|
270
|
+
return new Response(JSON.stringify({
|
|
271
|
+
error: "route_lookup_failed",
|
|
272
|
+
message: "the request could not be routed, so the write was refused",
|
|
273
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* A signed non-admin agent's mutation that reaches the owner checks, whose target
|
|
277
|
+
* Harper matched but whose record id Harper's request-target parsing or path
|
|
278
|
+
* parsing could not resolve, is refused before any owner decision: those
|
|
279
|
+
* decisions need the id. 400: the target cannot be parsed into a record id. The
|
|
280
|
+
* message is fixed and names no part of the target.
|
|
281
|
+
*/
|
|
282
|
+
function unresolvedTargetRefusal() {
|
|
283
|
+
return new Response(JSON.stringify({
|
|
284
|
+
error: "unresolved_request_target",
|
|
285
|
+
message: "the request target could not be resolved to a record id, so the write was refused",
|
|
286
|
+
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* The id a Memory write COMMITTED, read from the writer's own response result
|
|
290
|
+
* (its `id` field) — the trustworthy source, since a by-id write can commit a
|
|
291
|
+
* successor with a different id. Returns null when the result names no id as a
|
|
292
|
+
* plain string body (a 204, a streamed or compressed body); the caller then
|
|
293
|
+
* falls back to the routed id for a PUT or PATCH, and otherwise skips. Reads
|
|
294
|
+
* only the already-serialized string body; never consumes a stream.
|
|
295
|
+
*/
|
|
296
|
+
function committedMemoryIdFromResult(response) {
|
|
297
|
+
const body = response?.body;
|
|
298
|
+
if (typeof body !== "string" || body.length === 0)
|
|
299
|
+
return null;
|
|
300
|
+
try {
|
|
301
|
+
const parsed = JSON.parse(body);
|
|
302
|
+
const id = parsed?.id;
|
|
303
|
+
return typeof id === "string" && id.length > 0 ? id : null;
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
167
309
|
// Flair's clients use exactly these HTTP methods. Harper routes other methods
|
|
168
310
|
// to resource handlers as well; refusing them here, before any other branch of
|
|
169
311
|
// the default REST middleware, keeps the tables it serves to the methods their
|
|
@@ -172,11 +314,48 @@ async function backfillEmbedding(memoryId) {
|
|
|
172
314
|
const ALLOWED_HTTP_METHODS = new Set([
|
|
173
315
|
"GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE",
|
|
174
316
|
]);
|
|
317
|
+
// The resources the middleware makes a by-NAME decision on: the public-path
|
|
318
|
+
// allowance and the OAuth rate-limit policy.
|
|
319
|
+
const NAME_ROUTED_RESOURCES = new Set([
|
|
320
|
+
"health", "Health", "a2a", "A2AAdapter", "AgentCard",
|
|
321
|
+
"FederationSync", "FederationPair",
|
|
322
|
+
"OAuthRegister", "OAuthAuthorize", "OAuthToken", "OAuthRevoke", "OAuthMetadata",
|
|
323
|
+
"Admin",
|
|
324
|
+
]);
|
|
325
|
+
const RAW_QUERY_RESOURCES = new Set(["sql", "graphql"]);
|
|
175
326
|
server.http(async (request, nextLayer) => {
|
|
176
|
-
// ──
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
//
|
|
327
|
+
// ── Canonical request target, FIRST ────────────────────────────────────────
|
|
328
|
+
// This check reads the RAW request target, the string Harper routes. A target
|
|
329
|
+
// that is not in canonical form (a `.`/`..` segment, raw or percent-encoded;
|
|
330
|
+
// repeated slashes; a raw backslash) is answered with the named 400 here,
|
|
331
|
+
// before any other request processing: no method check, no rate-limit budget,
|
|
332
|
+
// no credential read, no next layer. See resources/request-target.ts.
|
|
333
|
+
const rawTarget = typeof request.url === "string" ? request.url : String(request.url ?? "");
|
|
334
|
+
if (!isCanonicalRequestTarget(rawTarget)) {
|
|
335
|
+
return nonCanonicalRequestTargetRefusal(String(request.method ?? ""));
|
|
336
|
+
}
|
|
337
|
+
const targetPath = requestPath(rawTarget);
|
|
338
|
+
// ── Resolve the target through Harper's OWN routing, FIRST ──────────────────
|
|
339
|
+
// Synchronous and before any await (getMatch mutates its entry in place; see
|
|
340
|
+
// harper-routing.ts). The helpers in request-target.ts are the fallback when
|
|
341
|
+
// no route is returned: the live registry or Harper's `RequestTarget` is absent
|
|
342
|
+
// (a unit test mocking `harper`), the target matches no route, or the matcher
|
|
343
|
+
// throws. When the matcher throws, a signed non-admin agent's mutation that
|
|
344
|
+
// reaches the owner checks is refused instead (below), before any owner
|
|
345
|
+
// decision; the checks that run earlier (e.g. the rate limit and the raw-query
|
|
346
|
+
// refusal) still answer first.
|
|
347
|
+
let routed = null;
|
|
348
|
+
let routeLookupFailed = false;
|
|
349
|
+
try {
|
|
350
|
+
routed = routeWithHarper(rawTarget, request.headers);
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
routeLookupFailed = true;
|
|
354
|
+
}
|
|
355
|
+
// ── HTTP method allowlist ──────────────────────────────────────────────────
|
|
356
|
+
// After the canonical check and route resolution: before the public-path passthrough
|
|
357
|
+
// and before any auth branch, so no path and no caller (anonymous, agent or
|
|
358
|
+
// admin) can reach a handler through any other method.
|
|
180
359
|
// Exact match: HTTP methods are case-sensitive, and these are the spellings
|
|
181
360
|
// Flair's clients send.
|
|
182
361
|
const httpMethod = String(request.method ?? "");
|
|
@@ -189,6 +368,9 @@ server.http(async (request, nextLayer) => {
|
|
|
189
368
|
headers: { "content-type": "application/json", allow: [...ALLOWED_HTTP_METHODS].join(", ") },
|
|
190
369
|
});
|
|
191
370
|
}
|
|
371
|
+
// The parsed URL is read for the signed payload (the client signs the
|
|
372
|
+
// pathname and search of the URL it built) and for query parameters only.
|
|
373
|
+
// A path decision is never made on its parsed pathname.
|
|
192
374
|
const url = new URL(request.url, "http://" + (request.headers.get("host") || "localhost"));
|
|
193
375
|
// ── Rate limiting, right after the method check ────────────────────────────
|
|
194
376
|
// Before the public-path passthrough below (the OAuth endpoints all sit on it,
|
|
@@ -209,9 +391,25 @@ server.http(async (request, nextLayer) => {
|
|
|
209
391
|
// Only the OAuth endpoints named in rate-limit.ts's PATH_POLICY are affected.
|
|
210
392
|
// Every other path — /Memory, /Presence, /FederationSync, everything agents
|
|
211
393
|
// actually use — returns null here and is untouched.
|
|
212
|
-
|
|
394
|
+
//
|
|
395
|
+
const routedDecisionPath = routed?.decisionPath ?? routedResourcePath(targetPath, NAME_ROUTED_RESOURCES);
|
|
396
|
+
const limited = checkHttpRateLimit(request, routedDecisionPath);
|
|
213
397
|
if (limited)
|
|
214
398
|
return limited;
|
|
399
|
+
// ── Malformed `.content` Memory path: the named 400, for every caller ────────
|
|
400
|
+
// flair#2307 item 2: Harper's OWN path decode answers a 500 for invalid
|
|
401
|
+
// percent-encoding, before any resource by-id guard can run. A Memory path
|
|
402
|
+
// whose last segment is invalid percent-encoding AND ends in the `.content`
|
|
403
|
+
// property suffix is refused here with the guard's named 400 instead. Placed
|
|
404
|
+
// before every auth branch (the public-path passthrough, the Basic-admin and
|
|
405
|
+
// anonymous early returns, the signed-agent path), so the refusal does not
|
|
406
|
+
// depend on the request's credential, and no row is read or written for it.
|
|
407
|
+
if (isMemoryReadPath(targetPath)) {
|
|
408
|
+
const seg = lastRawPathSegment(targetPath);
|
|
409
|
+
if (seg.endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX) && !isValidPercentEncoding(seg)) {
|
|
410
|
+
return contentSuffixIdDenial(seg);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
215
413
|
// A2A discovery endpoints: GET returns public agent-card metadata (per
|
|
216
414
|
// A2A spec, cards are intentionally public). POST invokes JSON-RPC
|
|
217
415
|
// actions (message/send writes OrgEvents on behalf of agents,
|
|
@@ -219,60 +417,47 @@ server.http(async (request, nextLayer) => {
|
|
|
219
417
|
// OrgEvents) — those must be authenticated. Narrowing to GET-only
|
|
220
418
|
// closes the P0 where any caller could forge OrgEvents as any agent
|
|
221
419
|
// and read all internal Beads issues unauthenticated.
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
420
|
+
const header = request.headers.get("authorization") || request.headers?.asObject?.authorization || "";
|
|
421
|
+
const isTpsEd25519 = /^TPS-Ed25519(?:\s|$)/i.test(header);
|
|
422
|
+
// Scheme names are case-insensitive (RFC 9110): "basic"/"BASIC"/"Basic" all
|
|
423
|
+
// select the Basic branch below, exactly as "Basic" does. Used for both the
|
|
424
|
+
// /FederationPair public-bypass test and the Basic branch itself.
|
|
425
|
+
const isBasic = /^Basic /i.test(header);
|
|
426
|
+
const isA2APath = routedDecisionPath === "/a2a" || routedDecisionPath === "/A2AAdapter" || routedDecisionPath.startsWith("/A2AAdapter/");
|
|
427
|
+
if (!isTpsEd25519 && (routedDecisionPath === "/health" ||
|
|
428
|
+
routedDecisionPath === "/Health" ||
|
|
225
429
|
(request.method === "GET" && isA2APath) ||
|
|
226
|
-
|
|
227
|
-
|
|
430
|
+
routedDecisionPath === "/AgentCard" ||
|
|
431
|
+
routedDecisionPath.startsWith("/AgentCard/") ||
|
|
228
432
|
// FederationSync uses Ed25519 body-signature auth with anti-replay, validated
|
|
229
433
|
// by the resource handler (allowCreate=true, same pattern as FederationPair).
|
|
230
|
-
|
|
434
|
+
routedDecisionPath === "/FederationSync" ||
|
|
231
435
|
// FederationPair uses one-time PairingToken in the request body, validated
|
|
232
436
|
// by the resource itself (allowCreate=true on the Resource lets anonymous
|
|
233
437
|
// POST through Harper's role gate). Bearer can't be used here because
|
|
234
438
|
// Harper's auth layer claims any "Bearer X" Authorization header for itself.
|
|
235
|
-
|
|
439
|
+
//
|
|
440
|
+
// A Basic-credentialled pair request is NOT passed through here. The Basic
|
|
441
|
+
// block below is what authenticates the token's bootstrap user
|
|
442
|
+
// (pair-bootstrap-<id>, Path 3) and annotates `tpsAgent`; passing straight
|
|
443
|
+
// through skipped that annotation, so the resource's bootstrap-user binding
|
|
444
|
+
// (PR-4, resources/Federation.ts) could never see a caller and never
|
|
445
|
+
// refused a mismatch. An anonymous pair request (no Authorization header)
|
|
446
|
+
// still passes through.
|
|
447
|
+
(routedDecisionPath === "/FederationPair" && !isBasic) ||
|
|
236
448
|
// OAuth 2.1 public endpoints (spec requires no pre-auth)
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
449
|
+
routedDecisionPath === "/OAuthRegister" ||
|
|
450
|
+
routedDecisionPath === "/OAuthAuthorize" ||
|
|
451
|
+
routedDecisionPath === "/OAuthToken" ||
|
|
452
|
+
routedDecisionPath === "/OAuthRevoke" ||
|
|
241
453
|
// Belt-and-braces since flair#1000: `/.well-known/oauth-authorization-server`
|
|
242
454
|
// is served from its OWN urlPath mount (resources/oauth-wellknown.ts), which
|
|
243
455
|
// gets its own dispatch chain — this middleware never sees a request for it.
|
|
244
456
|
// The entry stays so the path is still public if that mount ever moves back
|
|
245
457
|
// onto the default chain.
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
// Presence roster is public-safe (field-allowlisted); GET serves the
|
|
249
|
-
// Office Space renderer without auth. Scoped to GET only (#604): the
|
|
250
|
-
// exact-path match used to match ANY method, so a bare `PUT /Presence`
|
|
251
|
-
// (collection-level, no id — Harper routes it to the same .put() as
|
|
252
|
-
// by-id PUT) early-returned here too, skipping this middleware entirely.
|
|
253
|
-
// A credential-less loopback PUT then reached Presence.put()'s
|
|
254
|
-
// resolveAgentAuth() call with NO tpsAnonymous/tpsAgent annotation, which
|
|
255
|
-
// fell through to raw `context.user` — populated by Harper's
|
|
256
|
-
// `authorizeLocal` (config true) ambient super_user injection for ANY
|
|
257
|
-
// credential-less loopback request — so the ownership check saw an
|
|
258
|
-
// "admin" caller (isAdmin=true) and let the write through unauthenticated
|
|
259
|
-
// (`super.put()`, no signature, no password). Mirrors the A2A GET-only
|
|
260
|
-
// pattern above: POST/PUT/DELETE now always transit the general
|
|
261
|
-
// middleware path below, which marks a genuinely headerless request
|
|
262
|
-
// tpsAnonymous BEFORE Harper's ambient elevation lands (resolveAgentAuth
|
|
263
|
-
// checks tpsAnonymous first — see agent-auth.ts's resolution order), so
|
|
264
|
-
// the ownership check in Presence.put()/delete() correctly denies it.
|
|
265
|
-
// POST (the heartbeat) is unaffected in practice: it already prefers
|
|
266
|
-
// request.tpsAgent when the middleware set it, and falls back to its own
|
|
267
|
-
// Ed25519 header parse otherwise — transiting the general path now just
|
|
268
|
-
// means a genuinely headerless POST gets marked anonymous (still 401)
|
|
269
|
-
// instead of skipping straight to that fallback parse.
|
|
270
|
-
(request.method === "GET" && url.pathname === "/Presence"))
|
|
458
|
+
routedDecisionPath === "/.well-known/oauth-authorization-server" ||
|
|
459
|
+
routedDecisionPath === "/OAuthMetadata"))
|
|
271
460
|
return nextLayer(request);
|
|
272
|
-
// Read the Authorization header ONCE, up front — the super_user branch below
|
|
273
|
-
// needs it too (hoisted from its former position just after the branch as part
|
|
274
|
-
// of the flair#610 belt-and-suspenders check).
|
|
275
|
-
const header = request.headers.get("authorization") || request.headers?.asObject?.authorization || "";
|
|
276
461
|
// If Harper has already authorized this request (e.g. Basic admin, or
|
|
277
462
|
// authorizeLocal=true on localhost), trust Harper's auth decision and pass
|
|
278
463
|
// through. Annotate the admin identity so resources' resolveAgentAuth recognizes
|
|
@@ -288,13 +473,15 @@ server.http(async (request, nextLayer) => {
|
|
|
288
473
|
// live vector today — but it keeps the trust decision from ever hinging on
|
|
289
474
|
// ambient elevation alone. (The root-cause gate lives in resolveAgentAuth; see
|
|
290
475
|
// agent-auth.ts hasCredentialEvidence.)
|
|
291
|
-
if (header && request.user?.role?.permission?.super_user === true) {
|
|
476
|
+
if (!isTpsEd25519 && header && request.user?.role?.permission?.super_user === true) {
|
|
292
477
|
const username = request.user.username ?? "admin";
|
|
293
478
|
// Deactivation guard — same predicate as the Ed25519 path.
|
|
294
479
|
// A deactivated principal must not receive a tpsAgent annotation, even
|
|
295
480
|
// when Harper's ambient auth already verified the credential.
|
|
296
|
-
const
|
|
297
|
-
if (!
|
|
481
|
+
const read = await readCredentialedPrincipal(username);
|
|
482
|
+
if (!read.ok)
|
|
483
|
+
return credentialedLookupRefusal(username, read.error);
|
|
484
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
298
485
|
request.tpsAgent = username;
|
|
299
486
|
request.tpsAgentIsAdmin = true;
|
|
300
487
|
try {
|
|
@@ -316,7 +503,7 @@ server.http(async (request, nextLayer) => {
|
|
|
316
503
|
// 1. HDB_ADMIN_PASSWORD env-var fast-path (user must be "admin" with exact pass)
|
|
317
504
|
// 2. Harper super_user check — any user with super_user:true permission accepted
|
|
318
505
|
// Checked BEFORE Ed25519 so admin tools can use simple auth.
|
|
319
|
-
if (
|
|
506
|
+
if (isBasic) {
|
|
320
507
|
try {
|
|
321
508
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf-8");
|
|
322
509
|
const colonIdx = decoded.indexOf(":");
|
|
@@ -327,8 +514,10 @@ server.http(async (request, nextLayer) => {
|
|
|
327
514
|
const adminPass = getAdminPass();
|
|
328
515
|
if (adminPass !== null && user === "admin" && pass === adminPass) {
|
|
329
516
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
330
|
-
const
|
|
331
|
-
if (!
|
|
517
|
+
const read = await readCredentialedPrincipal("admin");
|
|
518
|
+
if (!read.ok)
|
|
519
|
+
return credentialedLookupRefusal("admin", read.error);
|
|
520
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
332
521
|
// Mark as verified and set Harper user directly
|
|
333
522
|
request._tpsAuthVerified = true;
|
|
334
523
|
try {
|
|
@@ -352,8 +541,10 @@ server.http(async (request, nextLayer) => {
|
|
|
352
541
|
catch { /* fall through — invalid creds, non-existent user, etc. */ }
|
|
353
542
|
if (harperUser?.role?.permission?.super_user === true) {
|
|
354
543
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
355
|
-
const
|
|
356
|
-
if (!
|
|
544
|
+
const read = await readCredentialedPrincipal(user);
|
|
545
|
+
if (!read.ok)
|
|
546
|
+
return credentialedLookupRefusal(user, read.error);
|
|
547
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
357
548
|
request._tpsAuthVerified = true;
|
|
358
549
|
request.user = harperUser;
|
|
359
550
|
request.headers.set("x-tps-agent", user);
|
|
@@ -368,7 +559,7 @@ server.http(async (request, nextLayer) => {
|
|
|
368
559
|
// Path 3: flair_pair_initiator — restricted to /FederationPair only.
|
|
369
560
|
// Bootstrap credentials (pair-bootstrap-<id>) may only be used on this
|
|
370
561
|
// one endpoint. Any other path must fall through to 401.
|
|
371
|
-
if (
|
|
562
|
+
if (routedDecisionPath === "/FederationPair" && user.startsWith("pair-bootstrap-")) {
|
|
372
563
|
let pairUser = null;
|
|
373
564
|
try {
|
|
374
565
|
pairUser = await server.getUser(user, pass, request);
|
|
@@ -377,8 +568,10 @@ server.http(async (request, nextLayer) => {
|
|
|
377
568
|
if (pairUser?.role?.role === "flair_pair_initiator" &&
|
|
378
569
|
pairUser?.active === true) {
|
|
379
570
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
380
|
-
const
|
|
381
|
-
if (!
|
|
571
|
+
const read = await readCredentialedPrincipal(user);
|
|
572
|
+
if (!read.ok)
|
|
573
|
+
return credentialedLookupRefusal(user, read.error);
|
|
574
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
382
575
|
request._tpsAuthVerified = true;
|
|
383
576
|
request.user = pairUser;
|
|
384
577
|
request.headers.set("x-tps-agent", user);
|
|
@@ -409,11 +602,13 @@ server.http(async (request, nextLayer) => {
|
|
|
409
602
|
// ── Ed25519 agent auth ────────────────────────────────────────────────────
|
|
410
603
|
const parsed = parseTpsEd25519Header(header);
|
|
411
604
|
if (!parsed) {
|
|
605
|
+
if (isTpsEd25519)
|
|
606
|
+
return new Response(JSON.stringify({ error: "invalid_authorization_header" }), { status: 401 });
|
|
412
607
|
// For browser-accessible admin pages, emit `WWW-Authenticate: Basic` so
|
|
413
608
|
// the browser shows a native auth dialog instead of a bare 401 page.
|
|
414
609
|
// JSON API endpoints don't get this — they should keep the structured
|
|
415
610
|
// 401 body so the client can parse the error.
|
|
416
|
-
const isAdminPage =
|
|
611
|
+
const isAdminPage = routedDecisionPath === "/Admin" || routedDecisionPath.startsWith("/Admin");
|
|
417
612
|
if (isAdminPage) {
|
|
418
613
|
return new Response("Authentication required.", {
|
|
419
614
|
status: 401,
|
|
@@ -475,15 +670,6 @@ server.http(async (request, nextLayer) => {
|
|
|
475
670
|
request.tpsAgent = agentId;
|
|
476
671
|
request._tpsAuthVerified = true;
|
|
477
672
|
request.tpsAgentIsAdmin = await isAdmin(agentId);
|
|
478
|
-
// Grant Harper-level permissions for the cryptographically-verified agent by
|
|
479
|
-
// setting request.user directly. Setting request.user is the supported
|
|
480
|
-
// extension path (and the only one that works post-5.0.9: Harper resolves
|
|
481
|
-
// request.user from the Authorization header BEFORE this middleware runs, and
|
|
482
|
-
// a TPS-Ed25519 header matches no Basic/Bearer strategy, so request.user
|
|
483
|
-
// arrives null — see #456). getUser(name, null) looks up the record WITHOUT
|
|
484
|
-
// password validation, safe here because the Ed25519 signature already proved
|
|
485
|
-
// identity cryptographically.
|
|
486
|
-
//
|
|
487
673
|
// RESHAPE (auth-rbac) — THE FLIP: per-agent DE-ELEVATION. A cryptographically-
|
|
488
674
|
// verified NON-admin agent resolves to the least-privilege `flair-agent` user,
|
|
489
675
|
// NOT admin super_user. The flair_agent role grants exactly the table CRUD agents
|
|
@@ -530,15 +716,26 @@ server.http(async (request, nextLayer) => {
|
|
|
530
716
|
// SQL and GraphQL endpoints bypass all resource-level scoping — block them
|
|
531
717
|
// for non-admin agents. Admins (bootstrap, consolidation scripts) still pass.
|
|
532
718
|
if (!request.tpsAgentIsAdmin) {
|
|
533
|
-
const
|
|
534
|
-
if (
|
|
535
|
-
|
|
719
|
+
const lowerPath = (routed ? routedDecisionPath : routedResourcePath(targetPath, RAW_QUERY_RESOURCES)).toLowerCase();
|
|
720
|
+
if (lowerPath === "/sql" || lowerPath.startsWith("/sql/") ||
|
|
721
|
+
lowerPath === "/graphql" || lowerPath.startsWith("/graphql/")) {
|
|
536
722
|
return new Response(JSON.stringify({ error: "forbidden: raw query endpoints require admin access" }), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
537
723
|
}
|
|
538
724
|
}
|
|
539
725
|
// ── Server-side permission guards ──────────────────────────────────────────
|
|
540
726
|
const method = request.method.toUpperCase();
|
|
541
727
|
const isMutation = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
|
|
728
|
+
// A signed non-admin agent's mutation that reaches this point (the earlier
|
|
729
|
+
// checks, e.g. the rate limit and the raw-query refusal, answer first) is
|
|
730
|
+
// refused before the owner decisions below when Harper's route lookup threw, or
|
|
731
|
+
// when Harper matched the target but its request-target parsing or path parsing
|
|
732
|
+
// could not resolve the record id.
|
|
733
|
+
if (isMutation && !request.tpsAgentIsAdmin && routeLookupFailed) {
|
|
734
|
+
return routeLookupFailedRefusal();
|
|
735
|
+
}
|
|
736
|
+
if (isMutation && !request.tpsAgentIsAdmin && routed?.recordIdUnresolved) {
|
|
737
|
+
return unresolvedTargetRefusal();
|
|
738
|
+
}
|
|
542
739
|
// ── THE record-ownership rule, for every table, on every mutating verb ─────
|
|
543
740
|
//
|
|
544
741
|
// One enforcement point rather than one per resource. See
|
|
@@ -556,21 +753,38 @@ server.http(async (request, nextLayer) => {
|
|
|
556
753
|
// resource's own no-forge attribution. That keeps this incapable of breaking a
|
|
557
754
|
// create, a self-write, or a legitimate cross-agent field like MemoryGrant's
|
|
558
755
|
// granteeId — it can only narrow mutation of another agent's stored row.
|
|
559
|
-
|
|
560
|
-
|
|
756
|
+
// A Memory mutation whose raw id ends in the reserved `.content` suffix is a
|
|
757
|
+
// request the resource layer refuses by SHAPE (flair#2199, 400
|
|
758
|
+
// memory_id_content_suffix) and commits no row — Harper mutates nothing, so
|
|
759
|
+
// the ownership guard below must not pre-empt that with a 403 on the base row
|
|
760
|
+
// the `.content` property parse happens to name. Skip the guard for it and let
|
|
761
|
+
// the resource's named 400 answer, as it did before the routed-id resolution.
|
|
762
|
+
const isReservedContentMutation = isMutation &&
|
|
763
|
+
(routedDecisionPath === "/Memory" || routedDecisionPath.startsWith("/Memory/")) &&
|
|
764
|
+
decodeMemoryIdSegment(lastRawPathSegment(targetPath)).endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX);
|
|
765
|
+
if (isMutation && !request.tpsAgentIsAdmin && !isReservedContentMutation) {
|
|
766
|
+
const guarded = routed
|
|
767
|
+
? resolveGuardedRecordById(routed.resource, routed.recordId)
|
|
768
|
+
: resolveGuardedRecord(targetPath);
|
|
561
769
|
if (guarded) {
|
|
770
|
+
let record;
|
|
562
771
|
try {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
772
|
+
record = await databases.flair[guarded.table]?.get(guarded.id);
|
|
773
|
+
}
|
|
774
|
+
catch {
|
|
775
|
+
// The ownership read is the authorization input. A read that FAILED is
|
|
776
|
+
// not "no owner" and must not fall through to the resource's allow* as
|
|
777
|
+
// though the check passed — fail closed with a named, retryable refusal.
|
|
778
|
+
return ownerReadFailedRefusal(guarded.table);
|
|
779
|
+
}
|
|
780
|
+
if (isForbiddenOwnerMutation(record, guarded.ownerField, agentId)) {
|
|
781
|
+
return ownerMutationRefusal(guarded.table);
|
|
567
782
|
}
|
|
568
|
-
catch { /* unreadable row → fall through to the resource's own rules */ }
|
|
569
783
|
}
|
|
570
784
|
}
|
|
571
785
|
if (isMutation) {
|
|
572
786
|
// OrgEvent: authorId must match authenticated agent
|
|
573
|
-
if ((
|
|
787
|
+
if ((routedDecisionPath === "/OrgEvent" || routedDecisionPath.startsWith("/OrgEvent/")) &&
|
|
574
788
|
(method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
575
789
|
if (!request.tpsAgentIsAdmin) {
|
|
576
790
|
try {
|
|
@@ -591,25 +805,28 @@ server.http(async (request, nextLayer) => {
|
|
|
591
805
|
}
|
|
592
806
|
}
|
|
593
807
|
// OrgEvent DELETE: ownership check
|
|
594
|
-
if (
|
|
808
|
+
if (routedDecisionPath.startsWith("/OrgEvent/") && method === "DELETE") {
|
|
595
809
|
if (!request.tpsAgentIsAdmin) {
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
810
|
+
const eventId = routed ? routed.recordId : (routedRecordId(targetPath)?.id ?? null);
|
|
811
|
+
if (eventId) {
|
|
812
|
+
let record;
|
|
813
|
+
try {
|
|
814
|
+
record = await databases.flair.OrgEvent.get(eventId);
|
|
815
|
+
}
|
|
816
|
+
catch {
|
|
817
|
+
// A failed read is not "no author": refuse, as the shared owner rule does.
|
|
818
|
+
return ownerReadFailedRefusal("OrgEvent");
|
|
819
|
+
}
|
|
820
|
+
if (record && record.authorId && record.authorId !== agentId) {
|
|
821
|
+
return new Response(JSON.stringify({
|
|
822
|
+
error: "forbidden: cannot delete events authored by another agent"
|
|
823
|
+
}), { status: 403 });
|
|
606
824
|
}
|
|
607
825
|
}
|
|
608
|
-
catch { }
|
|
609
826
|
}
|
|
610
827
|
}
|
|
611
828
|
// WorkspaceState: agent-scoped mutations (non-admin can only write own records)
|
|
612
|
-
if ((
|
|
829
|
+
if ((routedDecisionPath === "/WorkspaceState" || routedDecisionPath.startsWith("/WorkspaceState/")) &&
|
|
613
830
|
(method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
614
831
|
if (!request.tpsAgentIsAdmin) {
|
|
615
832
|
try {
|
|
@@ -630,21 +847,24 @@ server.http(async (request, nextLayer) => {
|
|
|
630
847
|
}
|
|
631
848
|
}
|
|
632
849
|
// WorkspaceState DELETE: ownership check
|
|
633
|
-
if ((
|
|
850
|
+
if ((routedDecisionPath.startsWith("/WorkspaceState/")) && method === "DELETE") {
|
|
634
851
|
if (!request.tpsAgentIsAdmin) {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
852
|
+
const wsId = routed ? routed.recordId : (routedRecordId(targetPath)?.id ?? null);
|
|
853
|
+
if (wsId) {
|
|
854
|
+
let record;
|
|
855
|
+
try {
|
|
856
|
+
record = await databases.flair.WorkspaceState.get(wsId);
|
|
857
|
+
}
|
|
858
|
+
catch {
|
|
859
|
+
// A failed read is not "no owner": refuse, as the shared owner rule does.
|
|
860
|
+
return ownerReadFailedRefusal("WorkspaceState");
|
|
861
|
+
}
|
|
862
|
+
if (record && record.agentId && record.agentId !== agentId) {
|
|
863
|
+
return new Response(JSON.stringify({
|
|
864
|
+
error: "forbidden: cannot delete workspace state for another agent"
|
|
865
|
+
}), { status: 403 });
|
|
645
866
|
}
|
|
646
867
|
}
|
|
647
|
-
catch { }
|
|
648
868
|
}
|
|
649
869
|
}
|
|
650
870
|
// Soul mutations: only the owner or an admin may write a soul entry.
|
|
@@ -679,7 +899,7 @@ server.http(async (request, nextLayer) => {
|
|
|
679
899
|
// The path test stays `startsWith("/Soul")` so sibling routes keep the
|
|
680
900
|
// body check they already had; the record lookup is scoped to the real
|
|
681
901
|
// `/Soul/<id>` collection so it never resolves an unrelated id.
|
|
682
|
-
if (
|
|
902
|
+
if (routedDecisionPath.startsWith("/Soul") &&
|
|
683
903
|
(method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE")) {
|
|
684
904
|
if (!request.tpsAgentIsAdmin) {
|
|
685
905
|
// (a) A PRESENT, mismatched body agentId is a forged attribution.
|
|
@@ -712,7 +932,7 @@ server.http(async (request, nextLayer) => {
|
|
|
712
932
|
}
|
|
713
933
|
// ── WorkspaceState read guard: agent-scoped reads ───────────────────────────
|
|
714
934
|
if (method === "GET" && !request.tpsAgentIsAdmin) {
|
|
715
|
-
if (
|
|
935
|
+
if (routedDecisionPath === "/WorkspaceState" || routedDecisionPath === "/WorkspaceState/") {
|
|
716
936
|
const queryAgent = url.searchParams.get("agentId");
|
|
717
937
|
if (queryAgent && queryAgent !== agentId) {
|
|
718
938
|
return new Response(JSON.stringify({
|
|
@@ -741,21 +961,40 @@ server.http(async (request, nextLayer) => {
|
|
|
741
961
|
// contract, applied in `Memory.get`/`Memory.search`). The by-id
|
|
742
962
|
// read-scope denial is enforced by the resource layer (memoryByIdReadGate),
|
|
743
963
|
// which returns the same 404 this middleware used to return.
|
|
744
|
-
|
|
745
|
-
|
|
964
|
+
// (A malformed `.content` segment was refused before any auth branch, above.)
|
|
965
|
+
if (!request.tpsAgentIsAdmin && (method === "GET" || method === "HEAD") && isMemoryReadPath(routedDecisionPath)) {
|
|
966
|
+
// flair#2199: an id segment carrying an encoded `/` before a declared
|
|
967
|
+
// property suffix is ambiguous — the suffix could be part of the id or a
|
|
968
|
+
// selector on a slash-containing id. This branch runs for a signed
|
|
969
|
+
// non-admin agent: Basic-admin and anonymous requests returned to the next
|
|
970
|
+
// layer before it.
|
|
971
|
+
if (isAmbiguousEncodedSlashSelector(request.url)) {
|
|
972
|
+
return new Response(method === "HEAD" ? null : JSON.stringify({
|
|
973
|
+
error: "ambiguous_memory_id",
|
|
974
|
+
message: `a Memory request whose id segment contains an encoded '/' before a "${MEMORY_CONTENT_SELECTOR_SUFFIX}" (or other property) suffix is refused: the suffix cannot be told from part of the id`,
|
|
975
|
+
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
976
|
+
}
|
|
977
|
+
// The path rewrite inside stripMemorySelection runs only when Harper's own
|
|
978
|
+
// routing returned a Memory route with a record id. With no route (e.g. no
|
|
979
|
+
// live registry, no match, or a matcher error) or no record id, the path is
|
|
980
|
+
// left as sent; the query-selection removal does not depend on this.
|
|
981
|
+
const routedToMemoryRecord = routed !== null && routed.resource === "Memory" && routed.recordId !== null;
|
|
982
|
+
const stripped = stripMemorySelection(request.url, routedToMemoryRecord);
|
|
746
983
|
if (stripped !== request.url)
|
|
747
984
|
request.url = stripped;
|
|
748
985
|
}
|
|
749
986
|
// ── Embedding backfill ─────────────────────────────────────────────────────
|
|
750
|
-
const isMemoryWrite = isMutation &&
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
987
|
+
const isMemoryWrite = isMutation && method !== "DELETE" &&
|
|
988
|
+
(routedDecisionPath === "/Memory" || routedDecisionPath.startsWith("/Memory/"));
|
|
989
|
+
const routedMemoryWrite = routed
|
|
990
|
+
? (routed.resource === "Memory" ? routed.recordId : null)
|
|
991
|
+
: (() => { const r = routedRecordId(targetPath); return r?.resource === "Memory" ? r.id : null; })();
|
|
992
|
+
const routedCommittedId = (method === "PUT" || method === "PATCH") ? routedMemoryWrite : null;
|
|
756
993
|
const response = await nextLayer(request);
|
|
757
|
-
if (isMemoryWrite &&
|
|
758
|
-
|
|
994
|
+
if (isMemoryWrite && response.status >= 200 && response.status < 300) {
|
|
995
|
+
const committedId = committedMemoryIdFromResult(response) ?? routedCommittedId;
|
|
996
|
+
if (committedId)
|
|
997
|
+
backfillEmbedding(committedId).catch(() => { });
|
|
759
998
|
}
|
|
760
999
|
return response;
|
|
761
1000
|
}, { runFirst: true, name: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME });
|