@tpsdev-ai/flair 0.58.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/SECURITY.md +36 -0
- package/config.yaml +15 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1030 -343
- package/dist/commands/agent.js +384 -45
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +601 -163
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +146 -53
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +81 -8
- package/dist/lib/doctor-run.js +140 -35
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +120 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +27 -2
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1775 -338
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +103 -7
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +348 -8
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +19 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +752 -132
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +227 -64
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/OrgSkillAssignment.js +209 -0
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +212 -65
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/agent-status-guard.js +63 -0
- package/dist/resources/auth-middleware.js +402 -162
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +94 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/flair-agent-role-boot.js +26 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +130 -20
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +31 -0
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +26 -12
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +150 -23
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/multi-worker-guard.js +121 -0
- package/dist/resources/oauth-discovery.js +1 -0
- package/dist/resources/oauth-wellknown.js +8 -4
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +17 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +145 -21
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +190 -0
- package/dist/resources/skill-provenance.js +15 -10
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +120 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +768 -0
- package/docs/api-reference.md +52 -13
- package/docs/auth.md +10 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deepseek-harness.md +1 -1
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +6 -6
- package/docs/mcp-clients.md +10 -5
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +34 -28
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +12 -6
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +115 -5
- package/schemas/oauth.graphql +27 -4
- package/schemas/schema.graphql +2 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
|
@@ -1,12 +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
|
-
import {
|
|
14
|
+
import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
|
|
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";
|
|
10
19
|
// --- Non-admin Memory read: ignore the caller's selection --------------------
|
|
11
20
|
//
|
|
12
21
|
// flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
|
|
@@ -18,30 +27,38 @@ const DECLARED_MEMORY_ATTRIBUTE_SET = new Set(DECLARED_MEMORY_ATTRIBUTES);
|
|
|
18
27
|
function isMemoryReadPath(pathname) {
|
|
19
28
|
return pathname === "/Memory" || pathname === "/Memory/" || pathname.startsWith("/Memory/");
|
|
20
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
|
+
}
|
|
21
40
|
// Drop a caller's `select(...)` and `property` from a Memory read URL, keeping
|
|
22
41
|
// conditions, operator, sort, limit and offset. Returns the input unchanged when
|
|
23
42
|
// the URL carries no selection.
|
|
24
|
-
|
|
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) {
|
|
25
50
|
const q = rawUrl.indexOf("?");
|
|
26
51
|
let pathPart = q === -1 ? rawUrl : rawUrl.slice(0, q);
|
|
27
52
|
let query = q === -1 ? "" : rawUrl.slice(q + 1);
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const slash = pathPart.lastIndexOf("/");
|
|
38
|
-
const seg = pathPart.slice(slash + 1);
|
|
39
|
-
const decodedSeg = decodePathSegment(seg);
|
|
40
|
-
const dot = decodedSeg.indexOf(".");
|
|
41
|
-
if (dot > -1 && DECLARED_MEMORY_ATTRIBUTE_SET.has(decodedSeg.slice(dot + 1))) {
|
|
42
|
-
// Rebuild the id from its decoded form. Harper decodes the path it is handed,
|
|
43
|
-
// so this re-encoded segment addresses the SAME id, without the property.
|
|
44
|
-
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)}`;
|
|
45
62
|
}
|
|
46
63
|
// Query form: drop every `select(...)` token and every `property` parameter.
|
|
47
64
|
for (const [start, end] of selectSpans(query).reverse()) {
|
|
@@ -58,16 +75,19 @@ function stripMemorySelection(rawUrl) {
|
|
|
58
75
|
return pathPart;
|
|
59
76
|
return query === "" ? pathPart : `${pathPart}?${query}`;
|
|
60
77
|
}
|
|
61
|
-
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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;
|
|
71
91
|
}
|
|
72
92
|
// [start, end) ranges of every `select(...)` call in a query string, accounting
|
|
73
93
|
// for Harper's nested-list form `select((a,b))`.
|
|
@@ -143,26 +163,149 @@ function getAdminPass() {
|
|
|
143
163
|
// them, and the crypto/decoder logic can't drift.
|
|
144
164
|
async function backfillEmbedding(memoryId) {
|
|
145
165
|
try {
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
+
}
|
|
160
231
|
}
|
|
161
232
|
catch (err) {
|
|
162
233
|
console.error(`[auto-embed] Failed for ${memoryId}: ${err.message}`);
|
|
163
234
|
}
|
|
164
235
|
}
|
|
165
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
|
+
}
|
|
166
309
|
// Flair's clients use exactly these HTTP methods. Harper routes other methods
|
|
167
310
|
// to resource handlers as well; refusing them here, before any other branch of
|
|
168
311
|
// the default REST middleware, keeps the tables it serves to the methods their
|
|
@@ -171,11 +314,48 @@ async function backfillEmbedding(memoryId) {
|
|
|
171
314
|
const ALLOWED_HTTP_METHODS = new Set([
|
|
172
315
|
"GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE",
|
|
173
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"]);
|
|
174
326
|
server.http(async (request, nextLayer) => {
|
|
175
|
-
// ──
|
|
176
|
-
//
|
|
177
|
-
//
|
|
178
|
-
//
|
|
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.
|
|
179
359
|
// Exact match: HTTP methods are case-sensitive, and these are the spellings
|
|
180
360
|
// Flair's clients send.
|
|
181
361
|
const httpMethod = String(request.method ?? "");
|
|
@@ -188,6 +368,9 @@ server.http(async (request, nextLayer) => {
|
|
|
188
368
|
headers: { "content-type": "application/json", allow: [...ALLOWED_HTTP_METHODS].join(", ") },
|
|
189
369
|
});
|
|
190
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.
|
|
191
374
|
const url = new URL(request.url, "http://" + (request.headers.get("host") || "localhost"));
|
|
192
375
|
// ── Rate limiting, right after the method check ────────────────────────────
|
|
193
376
|
// Before the public-path passthrough below (the OAuth endpoints all sit on it,
|
|
@@ -208,9 +391,25 @@ server.http(async (request, nextLayer) => {
|
|
|
208
391
|
// Only the OAuth endpoints named in rate-limit.ts's PATH_POLICY are affected.
|
|
209
392
|
// Every other path — /Memory, /Presence, /FederationSync, everything agents
|
|
210
393
|
// actually use — returns null here and is untouched.
|
|
211
|
-
|
|
394
|
+
//
|
|
395
|
+
const routedDecisionPath = routed?.decisionPath ?? routedResourcePath(targetPath, NAME_ROUTED_RESOURCES);
|
|
396
|
+
const limited = checkHttpRateLimit(request, routedDecisionPath);
|
|
212
397
|
if (limited)
|
|
213
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
|
+
}
|
|
214
413
|
// A2A discovery endpoints: GET returns public agent-card metadata (per
|
|
215
414
|
// A2A spec, cards are intentionally public). POST invokes JSON-RPC
|
|
216
415
|
// actions (message/send writes OrgEvents on behalf of agents,
|
|
@@ -218,60 +417,47 @@ server.http(async (request, nextLayer) => {
|
|
|
218
417
|
// OrgEvents) — those must be authenticated. Narrowing to GET-only
|
|
219
418
|
// closes the P0 where any caller could forge OrgEvents as any agent
|
|
220
419
|
// and read all internal Beads issues unauthenticated.
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
|
|
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" ||
|
|
224
429
|
(request.method === "GET" && isA2APath) ||
|
|
225
|
-
|
|
226
|
-
|
|
430
|
+
routedDecisionPath === "/AgentCard" ||
|
|
431
|
+
routedDecisionPath.startsWith("/AgentCard/") ||
|
|
227
432
|
// FederationSync uses Ed25519 body-signature auth with anti-replay, validated
|
|
228
433
|
// by the resource handler (allowCreate=true, same pattern as FederationPair).
|
|
229
|
-
|
|
434
|
+
routedDecisionPath === "/FederationSync" ||
|
|
230
435
|
// FederationPair uses one-time PairingToken in the request body, validated
|
|
231
436
|
// by the resource itself (allowCreate=true on the Resource lets anonymous
|
|
232
437
|
// POST through Harper's role gate). Bearer can't be used here because
|
|
233
438
|
// Harper's auth layer claims any "Bearer X" Authorization header for itself.
|
|
234
|
-
|
|
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) ||
|
|
235
448
|
// OAuth 2.1 public endpoints (spec requires no pre-auth)
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
449
|
+
routedDecisionPath === "/OAuthRegister" ||
|
|
450
|
+
routedDecisionPath === "/OAuthAuthorize" ||
|
|
451
|
+
routedDecisionPath === "/OAuthToken" ||
|
|
452
|
+
routedDecisionPath === "/OAuthRevoke" ||
|
|
240
453
|
// Belt-and-braces since flair#1000: `/.well-known/oauth-authorization-server`
|
|
241
454
|
// is served from its OWN urlPath mount (resources/oauth-wellknown.ts), which
|
|
242
455
|
// gets its own dispatch chain — this middleware never sees a request for it.
|
|
243
456
|
// The entry stays so the path is still public if that mount ever moves back
|
|
244
457
|
// onto the default chain.
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
// Presence roster is public-safe (field-allowlisted); GET serves the
|
|
248
|
-
// Office Space renderer without auth. Scoped to GET only (#604): the
|
|
249
|
-
// exact-path match used to match ANY method, so a bare `PUT /Presence`
|
|
250
|
-
// (collection-level, no id — Harper routes it to the same .put() as
|
|
251
|
-
// by-id PUT) early-returned here too, skipping this middleware entirely.
|
|
252
|
-
// A credential-less loopback PUT then reached Presence.put()'s
|
|
253
|
-
// resolveAgentAuth() call with NO tpsAnonymous/tpsAgent annotation, which
|
|
254
|
-
// fell through to raw `context.user` — populated by Harper's
|
|
255
|
-
// `authorizeLocal` (config true) ambient super_user injection for ANY
|
|
256
|
-
// credential-less loopback request — so the ownership check saw an
|
|
257
|
-
// "admin" caller (isAdmin=true) and let the write through unauthenticated
|
|
258
|
-
// (`super.put()`, no signature, no password). Mirrors the A2A GET-only
|
|
259
|
-
// pattern above: POST/PUT/DELETE now always transit the general
|
|
260
|
-
// middleware path below, which marks a genuinely headerless request
|
|
261
|
-
// tpsAnonymous BEFORE Harper's ambient elevation lands (resolveAgentAuth
|
|
262
|
-
// checks tpsAnonymous first — see agent-auth.ts's resolution order), so
|
|
263
|
-
// the ownership check in Presence.put()/delete() correctly denies it.
|
|
264
|
-
// POST (the heartbeat) is unaffected in practice: it already prefers
|
|
265
|
-
// request.tpsAgent when the middleware set it, and falls back to its own
|
|
266
|
-
// Ed25519 header parse otherwise — transiting the general path now just
|
|
267
|
-
// means a genuinely headerless POST gets marked anonymous (still 401)
|
|
268
|
-
// instead of skipping straight to that fallback parse.
|
|
269
|
-
(request.method === "GET" && url.pathname === "/Presence"))
|
|
458
|
+
routedDecisionPath === "/.well-known/oauth-authorization-server" ||
|
|
459
|
+
routedDecisionPath === "/OAuthMetadata"))
|
|
270
460
|
return nextLayer(request);
|
|
271
|
-
// Read the Authorization header ONCE, up front — the super_user branch below
|
|
272
|
-
// needs it too (hoisted from its former position just after the branch as part
|
|
273
|
-
// of the flair#610 belt-and-suspenders check).
|
|
274
|
-
const header = request.headers.get("authorization") || request.headers?.asObject?.authorization || "";
|
|
275
461
|
// If Harper has already authorized this request (e.g. Basic admin, or
|
|
276
462
|
// authorizeLocal=true on localhost), trust Harper's auth decision and pass
|
|
277
463
|
// through. Annotate the admin identity so resources' resolveAgentAuth recognizes
|
|
@@ -287,13 +473,15 @@ server.http(async (request, nextLayer) => {
|
|
|
287
473
|
// live vector today — but it keeps the trust decision from ever hinging on
|
|
288
474
|
// ambient elevation alone. (The root-cause gate lives in resolveAgentAuth; see
|
|
289
475
|
// agent-auth.ts hasCredentialEvidence.)
|
|
290
|
-
if (header && request.user?.role?.permission?.super_user === true) {
|
|
476
|
+
if (!isTpsEd25519 && header && request.user?.role?.permission?.super_user === true) {
|
|
291
477
|
const username = request.user.username ?? "admin";
|
|
292
478
|
// Deactivation guard — same predicate as the Ed25519 path.
|
|
293
479
|
// A deactivated principal must not receive a tpsAgent annotation, even
|
|
294
480
|
// when Harper's ambient auth already verified the credential.
|
|
295
|
-
const
|
|
296
|
-
if (!
|
|
481
|
+
const read = await readCredentialedPrincipal(username);
|
|
482
|
+
if (!read.ok)
|
|
483
|
+
return credentialedLookupRefusal(username, read.error);
|
|
484
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
297
485
|
request.tpsAgent = username;
|
|
298
486
|
request.tpsAgentIsAdmin = true;
|
|
299
487
|
try {
|
|
@@ -315,7 +503,7 @@ server.http(async (request, nextLayer) => {
|
|
|
315
503
|
// 1. HDB_ADMIN_PASSWORD env-var fast-path (user must be "admin" with exact pass)
|
|
316
504
|
// 2. Harper super_user check — any user with super_user:true permission accepted
|
|
317
505
|
// Checked BEFORE Ed25519 so admin tools can use simple auth.
|
|
318
|
-
if (
|
|
506
|
+
if (isBasic) {
|
|
319
507
|
try {
|
|
320
508
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf-8");
|
|
321
509
|
const colonIdx = decoded.indexOf(":");
|
|
@@ -326,8 +514,10 @@ server.http(async (request, nextLayer) => {
|
|
|
326
514
|
const adminPass = getAdminPass();
|
|
327
515
|
if (adminPass !== null && user === "admin" && pass === adminPass) {
|
|
328
516
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
329
|
-
const
|
|
330
|
-
if (!
|
|
517
|
+
const read = await readCredentialedPrincipal("admin");
|
|
518
|
+
if (!read.ok)
|
|
519
|
+
return credentialedLookupRefusal("admin", read.error);
|
|
520
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
331
521
|
// Mark as verified and set Harper user directly
|
|
332
522
|
request._tpsAuthVerified = true;
|
|
333
523
|
try {
|
|
@@ -351,8 +541,10 @@ server.http(async (request, nextLayer) => {
|
|
|
351
541
|
catch { /* fall through — invalid creds, non-existent user, etc. */ }
|
|
352
542
|
if (harperUser?.role?.permission?.super_user === true) {
|
|
353
543
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
354
|
-
const
|
|
355
|
-
if (!
|
|
544
|
+
const read = await readCredentialedPrincipal(user);
|
|
545
|
+
if (!read.ok)
|
|
546
|
+
return credentialedLookupRefusal(user, read.error);
|
|
547
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
356
548
|
request._tpsAuthVerified = true;
|
|
357
549
|
request.user = harperUser;
|
|
358
550
|
request.headers.set("x-tps-agent", user);
|
|
@@ -367,7 +559,7 @@ server.http(async (request, nextLayer) => {
|
|
|
367
559
|
// Path 3: flair_pair_initiator — restricted to /FederationPair only.
|
|
368
560
|
// Bootstrap credentials (pair-bootstrap-<id>) may only be used on this
|
|
369
561
|
// one endpoint. Any other path must fall through to 401.
|
|
370
|
-
if (
|
|
562
|
+
if (routedDecisionPath === "/FederationPair" && user.startsWith("pair-bootstrap-")) {
|
|
371
563
|
let pairUser = null;
|
|
372
564
|
try {
|
|
373
565
|
pairUser = await server.getUser(user, pass, request);
|
|
@@ -376,8 +568,10 @@ server.http(async (request, nextLayer) => {
|
|
|
376
568
|
if (pairUser?.role?.role === "flair_pair_initiator" &&
|
|
377
569
|
pairUser?.active === true) {
|
|
378
570
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
379
|
-
const
|
|
380
|
-
if (!
|
|
571
|
+
const read = await readCredentialedPrincipal(user);
|
|
572
|
+
if (!read.ok)
|
|
573
|
+
return credentialedLookupRefusal(user, read.error);
|
|
574
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
381
575
|
request._tpsAuthVerified = true;
|
|
382
576
|
request.user = pairUser;
|
|
383
577
|
request.headers.set("x-tps-agent", user);
|
|
@@ -408,11 +602,13 @@ server.http(async (request, nextLayer) => {
|
|
|
408
602
|
// ── Ed25519 agent auth ────────────────────────────────────────────────────
|
|
409
603
|
const parsed = parseTpsEd25519Header(header);
|
|
410
604
|
if (!parsed) {
|
|
605
|
+
if (isTpsEd25519)
|
|
606
|
+
return new Response(JSON.stringify({ error: "invalid_authorization_header" }), { status: 401 });
|
|
411
607
|
// For browser-accessible admin pages, emit `WWW-Authenticate: Basic` so
|
|
412
608
|
// the browser shows a native auth dialog instead of a bare 401 page.
|
|
413
609
|
// JSON API endpoints don't get this — they should keep the structured
|
|
414
610
|
// 401 body so the client can parse the error.
|
|
415
|
-
const isAdminPage =
|
|
611
|
+
const isAdminPage = routedDecisionPath === "/Admin" || routedDecisionPath.startsWith("/Admin");
|
|
416
612
|
if (isAdminPage) {
|
|
417
613
|
return new Response("Authentication required.", {
|
|
418
614
|
status: 401,
|
|
@@ -474,15 +670,6 @@ server.http(async (request, nextLayer) => {
|
|
|
474
670
|
request.tpsAgent = agentId;
|
|
475
671
|
request._tpsAuthVerified = true;
|
|
476
672
|
request.tpsAgentIsAdmin = await isAdmin(agentId);
|
|
477
|
-
// Grant Harper-level permissions for the cryptographically-verified agent by
|
|
478
|
-
// setting request.user directly. Setting request.user is the supported
|
|
479
|
-
// extension path (and the only one that works post-5.0.9: Harper resolves
|
|
480
|
-
// request.user from the Authorization header BEFORE this middleware runs, and
|
|
481
|
-
// a TPS-Ed25519 header matches no Basic/Bearer strategy, so request.user
|
|
482
|
-
// arrives null — see #456). getUser(name, null) looks up the record WITHOUT
|
|
483
|
-
// password validation, safe here because the Ed25519 signature already proved
|
|
484
|
-
// identity cryptographically.
|
|
485
|
-
//
|
|
486
673
|
// RESHAPE (auth-rbac) — THE FLIP: per-agent DE-ELEVATION. A cryptographically-
|
|
487
674
|
// verified NON-admin agent resolves to the least-privilege `flair-agent` user,
|
|
488
675
|
// NOT admin super_user. The flair_agent role grants exactly the table CRUD agents
|
|
@@ -529,15 +716,26 @@ server.http(async (request, nextLayer) => {
|
|
|
529
716
|
// SQL and GraphQL endpoints bypass all resource-level scoping — block them
|
|
530
717
|
// for non-admin agents. Admins (bootstrap, consolidation scripts) still pass.
|
|
531
718
|
if (!request.tpsAgentIsAdmin) {
|
|
532
|
-
const
|
|
533
|
-
if (
|
|
534
|
-
|
|
719
|
+
const lowerPath = (routed ? routedDecisionPath : routedResourcePath(targetPath, RAW_QUERY_RESOURCES)).toLowerCase();
|
|
720
|
+
if (lowerPath === "/sql" || lowerPath.startsWith("/sql/") ||
|
|
721
|
+
lowerPath === "/graphql" || lowerPath.startsWith("/graphql/")) {
|
|
535
722
|
return new Response(JSON.stringify({ error: "forbidden: raw query endpoints require admin access" }), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
536
723
|
}
|
|
537
724
|
}
|
|
538
725
|
// ── Server-side permission guards ──────────────────────────────────────────
|
|
539
726
|
const method = request.method.toUpperCase();
|
|
540
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
|
+
}
|
|
541
739
|
// ── THE record-ownership rule, for every table, on every mutating verb ─────
|
|
542
740
|
//
|
|
543
741
|
// One enforcement point rather than one per resource. See
|
|
@@ -555,21 +753,38 @@ server.http(async (request, nextLayer) => {
|
|
|
555
753
|
// resource's own no-forge attribution. That keeps this incapable of breaking a
|
|
556
754
|
// create, a self-write, or a legitimate cross-agent field like MemoryGrant's
|
|
557
755
|
// granteeId — it can only narrow mutation of another agent's stored row.
|
|
558
|
-
|
|
559
|
-
|
|
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);
|
|
560
769
|
if (guarded) {
|
|
770
|
+
let record;
|
|
561
771
|
try {
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
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);
|
|
566
782
|
}
|
|
567
|
-
catch { /* unreadable row → fall through to the resource's own rules */ }
|
|
568
783
|
}
|
|
569
784
|
}
|
|
570
785
|
if (isMutation) {
|
|
571
786
|
// OrgEvent: authorId must match authenticated agent
|
|
572
|
-
if ((
|
|
787
|
+
if ((routedDecisionPath === "/OrgEvent" || routedDecisionPath.startsWith("/OrgEvent/")) &&
|
|
573
788
|
(method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
574
789
|
if (!request.tpsAgentIsAdmin) {
|
|
575
790
|
try {
|
|
@@ -590,25 +805,28 @@ server.http(async (request, nextLayer) => {
|
|
|
590
805
|
}
|
|
591
806
|
}
|
|
592
807
|
// OrgEvent DELETE: ownership check
|
|
593
|
-
if (
|
|
808
|
+
if (routedDecisionPath.startsWith("/OrgEvent/") && method === "DELETE") {
|
|
594
809
|
if (!request.tpsAgentIsAdmin) {
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
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 });
|
|
605
824
|
}
|
|
606
825
|
}
|
|
607
|
-
catch { }
|
|
608
826
|
}
|
|
609
827
|
}
|
|
610
828
|
// WorkspaceState: agent-scoped mutations (non-admin can only write own records)
|
|
611
|
-
if ((
|
|
829
|
+
if ((routedDecisionPath === "/WorkspaceState" || routedDecisionPath.startsWith("/WorkspaceState/")) &&
|
|
612
830
|
(method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
613
831
|
if (!request.tpsAgentIsAdmin) {
|
|
614
832
|
try {
|
|
@@ -629,21 +847,24 @@ server.http(async (request, nextLayer) => {
|
|
|
629
847
|
}
|
|
630
848
|
}
|
|
631
849
|
// WorkspaceState DELETE: ownership check
|
|
632
|
-
if ((
|
|
850
|
+
if ((routedDecisionPath.startsWith("/WorkspaceState/")) && method === "DELETE") {
|
|
633
851
|
if (!request.tpsAgentIsAdmin) {
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
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 });
|
|
644
866
|
}
|
|
645
867
|
}
|
|
646
|
-
catch { }
|
|
647
868
|
}
|
|
648
869
|
}
|
|
649
870
|
// Soul mutations: only the owner or an admin may write a soul entry.
|
|
@@ -678,7 +899,7 @@ server.http(async (request, nextLayer) => {
|
|
|
678
899
|
// The path test stays `startsWith("/Soul")` so sibling routes keep the
|
|
679
900
|
// body check they already had; the record lookup is scoped to the real
|
|
680
901
|
// `/Soul/<id>` collection so it never resolves an unrelated id.
|
|
681
|
-
if (
|
|
902
|
+
if (routedDecisionPath.startsWith("/Soul") &&
|
|
682
903
|
(method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE")) {
|
|
683
904
|
if (!request.tpsAgentIsAdmin) {
|
|
684
905
|
// (a) A PRESENT, mismatched body agentId is a forged attribution.
|
|
@@ -711,7 +932,7 @@ server.http(async (request, nextLayer) => {
|
|
|
711
932
|
}
|
|
712
933
|
// ── WorkspaceState read guard: agent-scoped reads ───────────────────────────
|
|
713
934
|
if (method === "GET" && !request.tpsAgentIsAdmin) {
|
|
714
|
-
if (
|
|
935
|
+
if (routedDecisionPath === "/WorkspaceState" || routedDecisionPath === "/WorkspaceState/") {
|
|
715
936
|
const queryAgent = url.searchParams.get("agentId");
|
|
716
937
|
if (queryAgent && queryAgent !== agentId) {
|
|
717
938
|
return new Response(JSON.stringify({
|
|
@@ -740,21 +961,40 @@ server.http(async (request, nextLayer) => {
|
|
|
740
961
|
// contract, applied in `Memory.get`/`Memory.search`). The by-id
|
|
741
962
|
// read-scope denial is enforced by the resource layer (memoryByIdReadGate),
|
|
742
963
|
// which returns the same 404 this middleware used to return.
|
|
743
|
-
|
|
744
|
-
|
|
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);
|
|
745
983
|
if (stripped !== request.url)
|
|
746
984
|
request.url = stripped;
|
|
747
985
|
}
|
|
748
986
|
// ── Embedding backfill ─────────────────────────────────────────────────────
|
|
749
|
-
const isMemoryWrite = isMutation &&
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
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;
|
|
755
993
|
const response = await nextLayer(request);
|
|
756
|
-
if (isMemoryWrite &&
|
|
757
|
-
|
|
994
|
+
if (isMemoryWrite && response.status >= 200 && response.status < 300) {
|
|
995
|
+
const committedId = committedMemoryIdFromResult(response) ?? routedCommittedId;
|
|
996
|
+
if (committedId)
|
|
997
|
+
backfillEmbedding(committedId).catch(() => { });
|
|
758
998
|
}
|
|
759
999
|
return response;
|
|
760
|
-
}, { runFirst: true });
|
|
1000
|
+
}, { runFirst: true, name: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME });
|