@tpsdev-ai/flair 0.59.0 → 0.63.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 +10 -10
- package/SECURITY.md +49 -5
- package/config.yaml +23 -12
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/execute.js +1 -0
- 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/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1054 -367
- package/dist/commands/agent.js +233 -90
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +211 -39
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +71 -8
- package/dist/commands/doctor.js +711 -146
- package/dist/commands/export.js +57 -23
- package/dist/commands/federation.js +787 -82
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +27 -19
- package/dist/commands/import.js +136 -20
- package/dist/commands/init.js +469 -200
- package/dist/commands/integrity.js +387 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +108 -52
- package/dist/commands/memory.js +203 -35
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +51 -47
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +428 -62
- package/dist/commands/quality.js +13 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +537 -80
- package/dist/commands/restore.js +413 -65
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +235 -40
- package/dist/commands/soul.js +4 -9
- package/dist/commands/status.js +94 -38
- package/dist/commands/test.js +7 -3
- package/dist/commands/upgrade.js +77 -23
- package/dist/commands/workspace.js +13 -11
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +136 -4
- package/dist/doctor-client.js +534 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +273 -180
- package/dist/hook-install.js +670 -6
- package/dist/install/clients.js +171 -35
- 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 +88 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1069 -60
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +43 -11
- 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/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -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/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +38 -3
- 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 +1182 -341
- 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 +4 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/ops-url.js +52 -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/promotion-content-hash.js +20 -0
- 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-archive.js +760 -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-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +448 -0
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +114 -14
- package/dist/memory-id-checkpoint.js +347 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +303 -26
- package/dist/rem/runner.js +317 -96
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +463 -33
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +248 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +238 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -78
- package/dist/resources/Credential.js +183 -10
- package/dist/resources/Federation.js +915 -145
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +3300 -758
- package/dist/resources/MemoryArchive.js +171 -53
- package/dist/resources/MemoryBootstrap.js +122 -61
- package/dist/resources/MemoryCandidate.js +37 -3
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +545 -50
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +368 -46
- package/dist/resources/MemoryPurge.js +348 -0
- package/dist/resources/MemoryReflect.js +71 -12
- package/dist/resources/MemoryReindex.js +111 -17
- package/dist/resources/Message.js +16 -5
- package/dist/resources/OAuth.js +342 -48
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +405 -19
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +166 -51
- package/dist/resources/PromoteMemoryCandidate.js +24 -7
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +191 -76
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +207 -63
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +138 -83
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +534 -171
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +161 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +60 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +163 -22
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +587 -0
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +141 -19
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +450 -56
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +187 -40
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +4 -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 +144 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +32 -7
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +489 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +90 -19
- package/dist/resources/migrations/dir-safety.js +61 -3
- package/dist/resources/migrations/embedding-stamp.js +462 -82
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +27 -27
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +870 -77
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +81 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +113 -72
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +40 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -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 +256 -0
- package/dist/resources/owner-scoped-writes.js +89 -0
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +143 -17
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-type-kit.js +2 -4
- 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 +163 -0
- package/dist/resources/request-transaction.js +46 -1
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +116 -0
- package/dist/resources/semantic-retrieval-core.js +27 -15
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +24 -14
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +789 -0
- package/dist/resources/skill-write-fault.js +20 -0
- package/dist/resources/skill-write-policy.js +68 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -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 +235 -0
- package/dist/resources/usage-recording.js +186 -70
- package/dist/resources/write-back.js +383 -0
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -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 +88 -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/federation-retry-row.js +101 -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/instruction-event-contract.js +17 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +4 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/open-live-row.js +20 -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/soul-scope-fields.js +26 -0
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +164 -54
- package/docs/api-reference.md +165 -32
- package/docs/auth.md +46 -30
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +37 -7
- package/docs/deploying-on-fabric.md +178 -0
- package/docs/deployment.md +19 -0
- package/docs/embedding-in-a-harper-app.md +17 -15
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +61 -3
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +14 -14
- package/docs/mcp-clients.md +12 -7
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +16 -13
- package/docs/notes/mcp-oauth-model2.md +40 -11
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +4 -4
- package/docs/quickstart.md +12 -4
- package/docs/releasing.md +25 -19
- package/docs/rem.md +32 -3
- package/docs/secrets-and-keys.md +21 -4
- package/docs/standalone-local.md +30 -2
- package/docs/supply-chain-policy.md +34 -16
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +46 -6
- package/package.json +24 -12
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +6 -3
- package/schemas/federation.graphql +41 -1
- package/schemas/memory.graphql +91 -7
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { WRITE_BACK_ATTEMPTS, WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
|
|
2
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
3
|
+
import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
|
|
2
4
|
import { server, databases } from "harper";
|
|
3
|
-
import { getEmbedding } from "./embeddings-provider.js";
|
|
4
|
-
import {
|
|
5
|
+
import { getEmbedding, getModelId } from "./embeddings-provider.js";
|
|
6
|
+
import { noteWriteStamp } from "./embedding-space-guard.js";
|
|
7
|
+
import { hashEmbeddedText, holdsOwnStaleVector } from "./memory-embed-hash.js";
|
|
8
|
+
import { MEMORY_EMBEDDING_INPUT_FIELDS, skillEmbedText } from "./skill-write.js";
|
|
9
|
+
import { agentIsAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME, readCredentialedPrincipal, AGENT_LOOKUP_FAILED } from "./agent-auth.js";
|
|
5
10
|
import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
|
|
11
|
+
import { BASIC_AUTH_HEADER_RE, parseBasicAuthHeader } from "./basic-auth-header.js";
|
|
6
12
|
import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
|
|
7
|
-
import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord } from "./record-owner-guard.js";
|
|
13
|
+
import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord, resolveGuardedRecordById } from "./record-owner-guard.js";
|
|
14
|
+
import { routeWithHarper } from "./harper-routing.js";
|
|
8
15
|
import { checkHttpRateLimit } from "./rate-limit.js";
|
|
9
16
|
import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
|
|
10
|
-
import {
|
|
17
|
+
import { DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
|
|
18
|
+
import { idSegmentHasEncodedSlash, decodeMemoryIdSegment, MEMORY_CONTENT_SELECTOR_SUFFIX } from "../src/lib/memory-id-policy.js";
|
|
19
|
+
import { contentSuffixIdDenial } from "./memory-id-guard.js";
|
|
20
|
+
import { isCanonicalRequestTarget, nonCanonicalRequestTargetRefusal, requestPath, lastRawPathSegment, routedRecordId, routedResourceAndRemainder, routedIdAfterPropertyRule, routedResourcePath, whatwgUrlMatchesRawTarget, } from "./request-target.js";
|
|
11
21
|
// --- Non-admin Memory read: ignore the caller's selection --------------------
|
|
12
22
|
//
|
|
13
23
|
// flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
|
|
@@ -19,30 +29,38 @@ const DECLARED_MEMORY_ATTRIBUTE_SET = new Set(DECLARED_MEMORY_ATTRIBUTES);
|
|
|
19
29
|
function isMemoryReadPath(pathname) {
|
|
20
30
|
return pathname === "/Memory" || pathname === "/Memory/" || pathname.startsWith("/Memory/");
|
|
21
31
|
}
|
|
32
|
+
/** True when a path segment is valid percent-encoding. */
|
|
33
|
+
function isValidPercentEncoding(segment) {
|
|
34
|
+
try {
|
|
35
|
+
decodeURIComponent(segment);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
22
42
|
// Drop a caller's `select(...)` and `property` from a Memory read URL, keeping
|
|
23
43
|
// conditions, operator, sort, limit and offset. Returns the input unchanged when
|
|
24
44
|
// the URL carries no selection.
|
|
25
|
-
|
|
45
|
+
//
|
|
46
|
+
// The path rewrite runs ONLY when Harper routed this target to a Memory RECORD
|
|
47
|
+
// (`routedToMemoryRecord`): the raw path alone is not enough, because a target
|
|
48
|
+
// Harper resolved with no record id — e.g. `/Memory.json/<id>.content`, whose
|
|
49
|
+
// suffixed first segment routes to the Memory COLLECTION with an empty remainder
|
|
50
|
+
// — must not be turned into a by-id read of a row the target does not address.
|
|
51
|
+
function stripMemorySelection(rawUrl, routedToMemoryRecord) {
|
|
26
52
|
const q = rawUrl.indexOf("?");
|
|
27
53
|
let pathPart = q === -1 ? rawUrl : rawUrl.slice(0, q);
|
|
28
54
|
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))}`;
|
|
55
|
+
// Strip a declared-attribute suffix after the first dot in the decoded remainder.
|
|
56
|
+
const { remainder } = routedResourceAndRemainder(pathPart);
|
|
57
|
+
const decodedId = decodeMemoryIdSegment(remainder);
|
|
58
|
+
const stripped = routedIdAfterPropertyRule(decodedId, DECLARED_MEMORY_ATTRIBUTE_SET);
|
|
59
|
+
// An encoded `/` in the id makes the suffix ambiguous (the caller is refused
|
|
60
|
+
// upstream in the middleware), so only rewrite when there is no encoded slash
|
|
61
|
+
// and the first-dot rule actually dropped a declared-attribute suffix.
|
|
62
|
+
if (routedToMemoryRecord && !idSegmentHasEncodedSlash(remainder) && stripped !== decodedId) {
|
|
63
|
+
pathPart = `/Memory/${encodeURIComponent(stripped)}`;
|
|
46
64
|
}
|
|
47
65
|
// Query form: drop every `select(...)` token and every `property` parameter.
|
|
48
66
|
for (const [start, end] of selectSpans(query).reverse()) {
|
|
@@ -59,16 +77,19 @@ function stripMemorySelection(rawUrl) {
|
|
|
59
77
|
return pathPart;
|
|
60
78
|
return query === "" ? pathPart : `${pathPart}?${query}`;
|
|
61
79
|
}
|
|
62
|
-
/**
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
80
|
+
/**
|
|
81
|
+
* True when a Memory by-id read path names an id that carries an encoded `/`
|
|
82
|
+
* (`%2F`/`%2f`) AND would otherwise be given the property-suffix rewrite in
|
|
83
|
+
* stripMemorySelection. Such an id is ambiguous — the trailing
|
|
84
|
+
* `.<declared attribute>` could be part of the id or a selector on an id that
|
|
85
|
+
* contains a slash (flair#2199).
|
|
86
|
+
*/
|
|
87
|
+
function isAmbiguousEncodedSlashSelector(rawUrl) {
|
|
88
|
+
const { remainder } = routedResourceAndRemainder(requestPath(rawUrl));
|
|
89
|
+
if (!idSegmentHasEncodedSlash(remainder))
|
|
90
|
+
return false;
|
|
91
|
+
const decodedId = decodeMemoryIdSegment(remainder);
|
|
92
|
+
return routedIdAfterPropertyRule(decodedId, DECLARED_MEMORY_ATTRIBUTE_SET) !== decodedId;
|
|
72
93
|
}
|
|
73
94
|
// [start, end) ranges of every `select(...)` call in a query string, accounting
|
|
74
95
|
// for Harper's nested-list form `select((a,b))`.
|
|
@@ -132,10 +153,10 @@ function getAdminPass() {
|
|
|
132
153
|
return null;
|
|
133
154
|
}
|
|
134
155
|
// ─── Admin resolution ─────────────────────────────────────────────────────────
|
|
135
|
-
// `
|
|
136
|
-
// in agent-auth.ts as the single source of truth, imported above.
|
|
137
|
-
//
|
|
138
|
-
//
|
|
156
|
+
// `agentIsAdmin` (FLAIR_ADMIN_AGENTS env + the Agent row's role === "admin")
|
|
157
|
+
// lives in agent-auth.ts as the single source of truth, imported above. This
|
|
158
|
+
// gate passes it the Agent row it verifies the signature against, exactly as
|
|
159
|
+
// agent-auth.ts's own verifier does, so the two cannot diverge.
|
|
139
160
|
// ─── Crypto + replay-guard helpers ────────────────────────────────────────────
|
|
140
161
|
// WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
|
|
141
162
|
// guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
|
|
@@ -143,27 +164,265 @@ function getAdminPass() {
|
|
|
143
164
|
// any one of the three call sites, on any worker thread, is refused by all of
|
|
144
165
|
// them, and the crypto/decoder logic can't drift.
|
|
145
166
|
async function backfillEmbedding(memoryId) {
|
|
167
|
+
let unconfirmed = false;
|
|
168
|
+
// Whether the attempt that just ended saw its write confirmed on the committed
|
|
169
|
+
// row, so a failure after the commit is not reported as the outcome of an
|
|
170
|
+
// earlier attempt.
|
|
171
|
+
let lastAttemptConfirmed = false;
|
|
146
172
|
try {
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
173
|
+
const table = databases.flair.Memory;
|
|
174
|
+
// flair#2484: compute the vector before the owned write transaction opens.
|
|
175
|
+
// The text embedded is the one Memory's own writers embed (flair#2465,
|
|
176
|
+
// `skillEmbedText`: a skill-tagged row's non-empty `trigger`, else
|
|
177
|
+
// `content`). Rows without that text or with an embedding longer than 100
|
|
178
|
+
// entries skip before the text comparison. For eligible rows, `matchFields`
|
|
179
|
+
// compares every field that selects the text (`content`, `trigger`, `tags`)
|
|
180
|
+
// before staging; the helper confirms the committed row afterward. Drift
|
|
181
|
+
// observed before commit aborts the attempt; remaining outer attempts
|
|
182
|
+
// re-read and may recompute.
|
|
183
|
+
//
|
|
184
|
+
// flair#2573: the vector is stamped with the current model id, the space it
|
|
185
|
+
// was computed in, and the embedding-space guard is notified after the write
|
|
186
|
+
// commits with that stamp and the row it replaced, as for any other notified
|
|
187
|
+
// vector write.
|
|
188
|
+
//
|
|
189
|
+
// flair#2478 slice 3: the write runs under the id's per-id Memory write lock
|
|
190
|
+
// shared with the owner verbs (resources/memory-write-lock.ts): one
|
|
191
|
+
// non-waiting acquisition per attempt of the loop below, taken after that
|
|
192
|
+
// attempt's vector is computed, so no provider call runs while the id is
|
|
193
|
+
// locked; a retry acquires it again.
|
|
194
|
+
// A held id, an id with an unresolved write outcome, or a store with no lock
|
|
195
|
+
// is skipped and logged, and that attempt writes nothing. After an earlier
|
|
196
|
+
// attempt of this call committed unconfirmed, every exit that ends the call
|
|
197
|
+
// without a verified write (a lock miss, a row now gone or already embedded,
|
|
198
|
+
// a provider that returned no vector, a thrown error, which is logged and not
|
|
199
|
+
// rethrown) logs the outcome as unconfirmed instead; a later verified write
|
|
200
|
+
// is logged as written, or, when its write-stamp notification then fails,
|
|
201
|
+
// as confirmed with that failure named. A skipped backfill is not
|
|
202
|
+
// retried by this call. The backfill starts only from the post-response hook
|
|
203
|
+
// at the end of this middleware (the "Embedding backfill" block below),
|
|
204
|
+
// which a successful HTTP Memory POST, PUT or PATCH reaches when a verified
|
|
205
|
+
// Ed25519 agent signed it; a valid Basic-admin request returns earlier
|
|
206
|
+
// (the super_user and Basic branches call nextLayer directly) and starts
|
|
207
|
+
// none, and neither does a raw or direct table write. So the id's next such
|
|
208
|
+
// signed write starts another, and a row with a stale or missing stamp is
|
|
209
|
+
// re-embedded by the embedding-stamp migration.
|
|
210
|
+
//
|
|
211
|
+
// Holding the lock, the helper's first read is the committed row: a row
|
|
212
|
+
// whose text changed, or that has a vector of more than 100 entries, is not
|
|
213
|
+
// written (a changed text ends this attempt; the next attempt of the loop
|
|
214
|
+
// below re-reads and re-embeds after the lock is released). The helper
|
|
215
|
+
// stages the update and confirms the committed row: a change visible at
|
|
216
|
+
// that confirmation aborts the transaction, writes nothing, and the helper
|
|
217
|
+
// retries from a fresh read under the same lock. Then it commits and reads
|
|
218
|
+
// the committed row back (identity, the written fields, and the text the
|
|
219
|
+
// vector was computed for) before the lock is released. A readable
|
|
220
|
+
// read-back that does not show them retries from a fresh read: within the
|
|
221
|
+
// helper's own bound (WRITE_BACK_ATTEMPTS, 3) under the same lock, and,
|
|
222
|
+
// when that retry finds the text changed, through the next attempt of the
|
|
223
|
+
// loop below (at most WRITE_BACK_ATTEMPTS attempts, each with its own
|
|
224
|
+
// acquisition). An unreadable read-back stops without a retry. The
|
|
225
|
+
// read-back checks only the final committed state of those fields, so a
|
|
226
|
+
// lock-bypassing write committed and then overwritten inside this write's
|
|
227
|
+
// window is not detected. An outcome the read-back did not confirm
|
|
228
|
+
// (unreadable, or the attempts exhausted) is logged as unconfirmed; it does
|
|
229
|
+
// not mark the id outcome-unknown.
|
|
230
|
+
//
|
|
231
|
+
// The backfill writes a row whose vector is missing or has at most 100
|
|
232
|
+
// entries, whatever stored it. A row holding a longer vector counts as
|
|
233
|
+
// already embedded and is skipped, except one whose stored vector matches,
|
|
234
|
+
// within a relative tolerance that accepts a float32 copy of an in-range
|
|
235
|
+
// component (a non-finite component never matches), the
|
|
236
|
+
// vector an earlier unconfirmed attempt of this call staged, while its text
|
|
237
|
+
// is no longer the text that vector was computed from (holdsOwnStaleVector):
|
|
238
|
+
// the row holds a vector equal to this call's computation for a text it no
|
|
239
|
+
// longer has, whoever stored it. That row is re-read and re-embedded by the
|
|
240
|
+
// next attempt of the loop below while one remains, which needs the
|
|
241
|
+
// read-back that found the mismatch to have been readable. The check
|
|
242
|
+
// compares vectors, not the stored text hash: a row with an empty
|
|
243
|
+
// owner stores a null hash, which would match any text. A longer stored
|
|
244
|
+
// vector that does not match the staged one is skipped like any other
|
|
245
|
+
// already-embedded row; a non-match says nothing about who stored it.
|
|
246
|
+
let ownUnconfirmed;
|
|
247
|
+
const alreadyEmbedded = (row) => row.embedding?.length > 100 && !holdsOwnStaleVector(row, ownUnconfirmed);
|
|
248
|
+
// After an earlier attempt of this call committed and its read-back did not
|
|
249
|
+
// confirm it, every exit that ends the call without a verified write logs
|
|
250
|
+
// the outcome as unconfirmed; an exit that wrote nothing says so for its own
|
|
251
|
+
// attempt only (flair#2478).
|
|
252
|
+
const endAfterUnconfirmed = (ended) => {
|
|
253
|
+
if (unconfirmed)
|
|
254
|
+
console.warn("[auto-embed] %s: %s; an earlier attempt's vector was not confirmed on the committed row; outcome: unconfirmed", memoryId, ended, { outcome: "unconfirmed" });
|
|
255
|
+
};
|
|
256
|
+
for (let attempt = 1; attempt <= WRITE_BACK_ATTEMPTS; attempt++) {
|
|
257
|
+
lastAttemptConfirmed = false;
|
|
258
|
+
const record = await table.get(memoryId, {});
|
|
259
|
+
const text = record ? skillEmbedText(record) : undefined;
|
|
260
|
+
if (typeof text !== "string" || text.length === 0) {
|
|
261
|
+
endAfterUnconfirmed("the row is gone or has no text, so this attempt wrote nothing");
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (alreadyEmbedded(record)) {
|
|
265
|
+
endAfterUnconfirmed("the row now counts as already embedded, so this attempt wrote nothing");
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const embedding = await getEmbedding(text, "document");
|
|
269
|
+
if (!Array.isArray(embedding) || embedding.length === 0) {
|
|
270
|
+
endAfterUnconfirmed("the provider returned no vector, so this attempt wrote nothing");
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const model = getModelId();
|
|
274
|
+
// Test-only: inert unless the fault-injection opt-in is armed. The vector
|
|
275
|
+
// is computed and the id's lock is not yet taken.
|
|
276
|
+
const entry = txnPausePoint("backfill-embedding-entry");
|
|
277
|
+
if (entry)
|
|
278
|
+
await entry;
|
|
279
|
+
// The vector fields of the committed row the update replaces, for the
|
|
280
|
+
// guard notification.
|
|
281
|
+
let replaced = null;
|
|
282
|
+
try {
|
|
283
|
+
const locked = await withMemoryWriteLockOnce(table.primaryStore, [memoryId], async () => {
|
|
284
|
+
const written = await writeBackCommittedRow(table, memoryId, (row) => {
|
|
285
|
+
const rowText = row ? skillEmbedText(row) : undefined;
|
|
286
|
+
if (typeof rowText !== "string" || rowText.length === 0)
|
|
287
|
+
return { skip: true };
|
|
288
|
+
if (alreadyEmbedded(row))
|
|
289
|
+
return { skip: true };
|
|
290
|
+
replaced = { embedding: row.embedding, embeddingModel: row.embeddingModel };
|
|
291
|
+
// Only `embedding`, its model stamp and its text hash: an incremental
|
|
292
|
+
// update, never a full-row put of the row read above (flair#2470,
|
|
293
|
+
// flair#2465). The newly computed hash is of `text`, the text this
|
|
294
|
+
// vector was computed from (null for an empty owner).
|
|
295
|
+
return { idempotent: true, update: { embedding, embeddingModel: model, embeddedContentHash: hashEmbeddedText(row.agentId, text) ?? null } };
|
|
296
|
+
}, {
|
|
297
|
+
label: "backfillEmbedding",
|
|
298
|
+
onUnconfirmed: () => { unconfirmed = true; ownUnconfirmed = { embedding, text }; },
|
|
299
|
+
expectedRow: record,
|
|
300
|
+
// Compare the text-selecting fields before staging, after the plan's skip checks.
|
|
301
|
+
matchFields: [...MEMORY_EMBEDDING_INPUT_FIELDS, "tags"],
|
|
302
|
+
// After the commit, the committed row must still carry the text this
|
|
303
|
+
// vector was computed from.
|
|
304
|
+
verifyAlso: (committed) => skillEmbedText(committed) === text,
|
|
305
|
+
pausePre: () => txnPausePoint("backfill-embedding-pre"),
|
|
306
|
+
pausePoint: () => txnPausePoint("backfill-embedding"),
|
|
307
|
+
pauseAfterStage: () => txnPausePoint("backfill-embedding-staged"),
|
|
308
|
+
pauseBeforeCommit: () => txnPausePoint("backfill-embedding-commit"),
|
|
309
|
+
});
|
|
310
|
+
// Test-only: the update has committed and been read back; the lock is
|
|
311
|
+
// still held. A plan that skipped wrote nothing, so it does not reach
|
|
312
|
+
// this point.
|
|
313
|
+
if (!("skip" in written)) {
|
|
314
|
+
const committed = txnPausePoint("backfill-embedding-committed");
|
|
315
|
+
if (committed)
|
|
316
|
+
await committed;
|
|
317
|
+
}
|
|
318
|
+
return written;
|
|
319
|
+
}, { phase: "auto-embed" });
|
|
320
|
+
if (locked.kind !== "done") {
|
|
321
|
+
if (unconfirmed)
|
|
322
|
+
endAfterUnconfirmed(`skipped; the per-id write lock answered ${locked.kind}, so this attempt wrote nothing`);
|
|
323
|
+
else
|
|
324
|
+
console.warn("[auto-embed] %s: skipped; the per-id write lock answered %s, so nothing was written", memoryId, locked.kind);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const outcome = locked.value;
|
|
328
|
+
if ("update" in outcome) {
|
|
329
|
+
lastAttemptConfirmed = true;
|
|
330
|
+
noteWriteStamp(outcome.update.embeddingModel, replaced);
|
|
331
|
+
console.log(`[auto-embed] ${memoryId}: ${outcome.update.embedding.length}d`);
|
|
332
|
+
}
|
|
333
|
+
else if (unconfirmed) {
|
|
334
|
+
console.warn("[auto-embed] %s: an earlier attempt's vector was not confirmed on the committed row, and the row is now skipped; outcome: unconfirmed", memoryId, { outcome: "unconfirmed" });
|
|
335
|
+
}
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
catch (err) {
|
|
339
|
+
if (err instanceof WriteBackConflictError && attempt < WRITE_BACK_ATTEMPTS)
|
|
340
|
+
continue;
|
|
341
|
+
throw err;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
161
344
|
}
|
|
162
345
|
catch (err) {
|
|
163
|
-
|
|
346
|
+
if (lastAttemptConfirmed) {
|
|
347
|
+
console.error("[auto-embed] %s for %s: the vector is confirmed on the committed row; the embedding-space write-stamp notification failed: %s", "Outcome confirmed", memoryId, err.message, { outcome: "stamp_notification_failed" });
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
console.error("[auto-embed] %s for %s: %s", unconfirmed ? "Outcome unconfirmed" : "Failed", memoryId, err.message, ...(unconfirmed ? [{ outcome: "unconfirmed" }] : err instanceof WriteBackConflictError ? [{ outcome: err.outcome }] : []));
|
|
164
351
|
}
|
|
165
352
|
}
|
|
166
353
|
// ─── HTTP middleware ──────────────────────────────────────────────────────────
|
|
354
|
+
/**
|
|
355
|
+
* Refuse a credentialed Basic-auth request whose Agent row could not be READ:
|
|
356
|
+
* log the named error and return it. A read that FAILED is never an absent
|
|
357
|
+
* principal (flair#2403); the same rule resources/AgentSeed.ts applies as
|
|
358
|
+
* `agent_lookup_failed`.
|
|
359
|
+
*/
|
|
360
|
+
function credentialedLookupRefusal(username, error) {
|
|
361
|
+
console.error("auth-middleware: the credentialed principal lookup failed, so the request was refused", { username, error });
|
|
362
|
+
return new Response(JSON.stringify({
|
|
363
|
+
error: AGENT_LOOKUP_FAILED,
|
|
364
|
+
message: "the principal record could not be read, so the request was refused",
|
|
365
|
+
}), { status: 500, headers: { "content-type": "application/json" } });
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* A guarded mutation whose stored-owner read FAILED is refused, not allowed
|
|
369
|
+
* through. The ownership read is the authorization input; a failed read is not
|
|
370
|
+
* "no owner", so it must fail closed. 503 because a retry can succeed.
|
|
371
|
+
*/
|
|
372
|
+
function ownerReadFailedRefusal(table) {
|
|
373
|
+
console.error("auth-middleware: the stored-owner read failed, so the mutation was refused", { table });
|
|
374
|
+
return new Response(JSON.stringify({
|
|
375
|
+
error: "owner_lookup_failed",
|
|
376
|
+
message: "the record's owner could not be read, so the write was refused",
|
|
377
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* A signed non-admin agent's mutation that reaches the owner checks is refused
|
|
381
|
+
* when Harper's route lookup threw: the owner decisions need Harper's route, and
|
|
382
|
+
* the pure fallback does not stand in for it. 503 because a retry can succeed. The message is fixed and
|
|
383
|
+
* names no part of the target.
|
|
384
|
+
*/
|
|
385
|
+
function routeLookupFailedRefusal() {
|
|
386
|
+
console.error("auth-middleware: the route lookup failed, so the mutation was refused");
|
|
387
|
+
return new Response(JSON.stringify({
|
|
388
|
+
error: "route_lookup_failed",
|
|
389
|
+
message: "the request could not be routed, so the write was refused",
|
|
390
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* A signed non-admin agent's mutation that reaches the owner checks, whose target
|
|
394
|
+
* Harper matched but whose record id Harper's request-target parsing or path
|
|
395
|
+
* parsing could not resolve, is refused before any owner decision: those
|
|
396
|
+
* decisions need the id. 400: the target cannot be parsed into a record id. The
|
|
397
|
+
* message is fixed and names no part of the target.
|
|
398
|
+
*/
|
|
399
|
+
function unresolvedTargetRefusal() {
|
|
400
|
+
return new Response(JSON.stringify({
|
|
401
|
+
error: "unresolved_request_target",
|
|
402
|
+
message: "the request target could not be resolved to a record id, so the write was refused",
|
|
403
|
+
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* The id a Memory write COMMITTED, read from the writer's own response result
|
|
407
|
+
* (its `id` field) — the trustworthy source, since a by-id write can commit a
|
|
408
|
+
* successor with a different id. Returns null when the result names no id as a
|
|
409
|
+
* plain string body (a 204, a streamed or compressed body); the caller then
|
|
410
|
+
* falls back to the routed id for a PUT or PATCH, and otherwise skips. Reads
|
|
411
|
+
* only the already-serialized string body; never consumes a stream.
|
|
412
|
+
*/
|
|
413
|
+
function committedMemoryIdFromResult(response) {
|
|
414
|
+
const body = response?.body;
|
|
415
|
+
if (typeof body !== "string" || body.length === 0)
|
|
416
|
+
return null;
|
|
417
|
+
try {
|
|
418
|
+
const parsed = JSON.parse(body);
|
|
419
|
+
const id = parsed?.id;
|
|
420
|
+
return typeof id === "string" && id.length > 0 ? id : null;
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
167
426
|
// Flair's clients use exactly these HTTP methods. Harper routes other methods
|
|
168
427
|
// to resource handlers as well; refusing them here, before any other branch of
|
|
169
428
|
// the default REST middleware, keeps the tables it serves to the methods their
|
|
@@ -172,11 +431,48 @@ async function backfillEmbedding(memoryId) {
|
|
|
172
431
|
const ALLOWED_HTTP_METHODS = new Set([
|
|
173
432
|
"GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE",
|
|
174
433
|
]);
|
|
434
|
+
// The resources the middleware makes a by-NAME decision on: the public-path
|
|
435
|
+
// allowance and the OAuth rate-limit policy.
|
|
436
|
+
const NAME_ROUTED_RESOURCES = new Set([
|
|
437
|
+
"health", "Health", "a2a", "A2AAdapter", "AgentCard",
|
|
438
|
+
"FederationSync", "FederationPair",
|
|
439
|
+
"OAuthRegister", "OAuthAuthorize", "OAuthToken", "OAuthRevoke", "OAuthMetadata",
|
|
440
|
+
"Admin",
|
|
441
|
+
]);
|
|
442
|
+
const RAW_QUERY_RESOURCES = new Set(["sql", "graphql"]);
|
|
175
443
|
server.http(async (request, nextLayer) => {
|
|
176
|
-
// ──
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
//
|
|
444
|
+
// ── Canonical request target, FIRST ────────────────────────────────────────
|
|
445
|
+
// This check reads the RAW request target, the string Harper routes. A target
|
|
446
|
+
// that is not in canonical form (a `.`/`..` segment, raw or percent-encoded;
|
|
447
|
+
// repeated slashes; a raw backslash) is answered with the named 400 here,
|
|
448
|
+
// before any other request processing: no method check, no rate-limit budget,
|
|
449
|
+
// no credential read, no next layer. See resources/request-target.ts.
|
|
450
|
+
const rawTarget = typeof request.url === "string" ? request.url : String(request.url ?? "");
|
|
451
|
+
if (!isCanonicalRequestTarget(rawTarget)) {
|
|
452
|
+
return nonCanonicalRequestTargetRefusal(String(request.method ?? ""));
|
|
453
|
+
}
|
|
454
|
+
const targetPath = requestPath(rawTarget);
|
|
455
|
+
// ── Resolve the target through Harper's OWN routing, FIRST ──────────────────
|
|
456
|
+
// Synchronous and before any await (getMatch mutates its entry in place; see
|
|
457
|
+
// harper-routing.ts). The helpers in request-target.ts are the fallback when
|
|
458
|
+
// no route is returned: the live registry or Harper's `RequestTarget` is absent
|
|
459
|
+
// (a unit test mocking `harper`), the target matches no route, or the matcher
|
|
460
|
+
// throws. When the matcher throws, a signed non-admin agent's mutation that
|
|
461
|
+
// reaches the owner checks is refused instead (below), before any owner
|
|
462
|
+
// decision; the checks that run earlier (e.g. the rate limit and the raw-query
|
|
463
|
+
// refusal) still answer first.
|
|
464
|
+
let routed = null;
|
|
465
|
+
let routeLookupFailed = false;
|
|
466
|
+
try {
|
|
467
|
+
routed = routeWithHarper(rawTarget, request.headers);
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
routeLookupFailed = true;
|
|
471
|
+
}
|
|
472
|
+
// ── HTTP method allowlist ──────────────────────────────────────────────────
|
|
473
|
+
// After the canonical check and route resolution: before the public-path passthrough
|
|
474
|
+
// and before any auth branch, so no path and no caller (anonymous, agent or
|
|
475
|
+
// admin) can reach a handler through any other method.
|
|
180
476
|
// Exact match: HTTP methods are case-sensitive, and these are the spellings
|
|
181
477
|
// Flair's clients send.
|
|
182
478
|
const httpMethod = String(request.method ?? "");
|
|
@@ -189,6 +485,9 @@ server.http(async (request, nextLayer) => {
|
|
|
189
485
|
headers: { "content-type": "application/json", allow: [...ALLOWED_HTTP_METHODS].join(", ") },
|
|
190
486
|
});
|
|
191
487
|
}
|
|
488
|
+
// The parsed URL is read for the signed payload (the client signs the
|
|
489
|
+
// pathname and search of the URL it built) and for query parameters only.
|
|
490
|
+
// A path decision is never made on its parsed pathname.
|
|
192
491
|
const url = new URL(request.url, "http://" + (request.headers.get("host") || "localhost"));
|
|
193
492
|
// ── Rate limiting, right after the method check ────────────────────────────
|
|
194
493
|
// Before the public-path passthrough below (the OAuth endpoints all sit on it,
|
|
@@ -209,9 +508,25 @@ server.http(async (request, nextLayer) => {
|
|
|
209
508
|
// Only the OAuth endpoints named in rate-limit.ts's PATH_POLICY are affected.
|
|
210
509
|
// Every other path — /Memory, /Presence, /FederationSync, everything agents
|
|
211
510
|
// actually use — returns null here and is untouched.
|
|
212
|
-
|
|
511
|
+
//
|
|
512
|
+
const routedDecisionPath = routed?.decisionPath ?? routedResourcePath(targetPath, NAME_ROUTED_RESOURCES);
|
|
513
|
+
const limited = checkHttpRateLimit(request, routedDecisionPath);
|
|
213
514
|
if (limited)
|
|
214
515
|
return limited;
|
|
516
|
+
// ── Malformed `.content` Memory path: the named 400, for every caller ────────
|
|
517
|
+
// flair#2307 item 2: Harper's OWN path decode answers a 500 for invalid
|
|
518
|
+
// percent-encoding, before any resource by-id guard can run. A Memory path
|
|
519
|
+
// whose last segment is invalid percent-encoding AND ends in the `.content`
|
|
520
|
+
// property suffix is refused here with the guard's named 400 instead. Placed
|
|
521
|
+
// before every auth branch (the public-path passthrough, the Basic-admin and
|
|
522
|
+
// anonymous early returns, the signed-agent path), so the refusal does not
|
|
523
|
+
// depend on the request's credential, and no row is read or written for it.
|
|
524
|
+
if (isMemoryReadPath(targetPath)) {
|
|
525
|
+
const seg = lastRawPathSegment(targetPath);
|
|
526
|
+
if (seg.endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX) && !isValidPercentEncoding(seg)) {
|
|
527
|
+
return contentSuffixIdDenial(seg);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
215
530
|
// A2A discovery endpoints: GET returns public agent-card metadata (per
|
|
216
531
|
// A2A spec, cards are intentionally public). POST invokes JSON-RPC
|
|
217
532
|
// actions (message/send writes OrgEvents on behalf of agents,
|
|
@@ -219,60 +534,47 @@ server.http(async (request, nextLayer) => {
|
|
|
219
534
|
// OrgEvents) — those must be authenticated. Narrowing to GET-only
|
|
220
535
|
// closes the P0 where any caller could forge OrgEvents as any agent
|
|
221
536
|
// and read all internal Beads issues unauthenticated.
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
537
|
+
const header = request.headers.get("authorization") || request.headers?.asObject?.authorization || "";
|
|
538
|
+
const isTpsEd25519 = /^TPS-Ed25519(?:\s|$)/i.test(header);
|
|
539
|
+
// Scheme names are case-insensitive (RFC 9110): "basic"/"BASIC"/"Basic" all
|
|
540
|
+
// select the Basic branch below, exactly as "Basic" does. Used for both the
|
|
541
|
+
// /FederationPair public-bypass test and the Basic branch itself.
|
|
542
|
+
const isBasic = BASIC_AUTH_HEADER_RE.test(header);
|
|
543
|
+
const isA2APath = routedDecisionPath === "/a2a" || routedDecisionPath === "/A2AAdapter" || routedDecisionPath.startsWith("/A2AAdapter/");
|
|
544
|
+
if (!isTpsEd25519 && (routedDecisionPath === "/health" ||
|
|
545
|
+
routedDecisionPath === "/Health" ||
|
|
225
546
|
(request.method === "GET" && isA2APath) ||
|
|
226
|
-
|
|
227
|
-
|
|
547
|
+
routedDecisionPath === "/AgentCard" ||
|
|
548
|
+
routedDecisionPath.startsWith("/AgentCard/") ||
|
|
228
549
|
// FederationSync uses Ed25519 body-signature auth with anti-replay, validated
|
|
229
550
|
// by the resource handler (allowCreate=true, same pattern as FederationPair).
|
|
230
|
-
|
|
551
|
+
routedDecisionPath === "/FederationSync" ||
|
|
231
552
|
// FederationPair uses one-time PairingToken in the request body, validated
|
|
232
553
|
// by the resource itself (allowCreate=true on the Resource lets anonymous
|
|
233
554
|
// POST through Harper's role gate). Bearer can't be used here because
|
|
234
555
|
// Harper's auth layer claims any "Bearer X" Authorization header for itself.
|
|
235
|
-
|
|
556
|
+
//
|
|
557
|
+
// A Basic-credentialled pair request is NOT passed through here. The Basic
|
|
558
|
+
// block below is what authenticates the token's bootstrap user
|
|
559
|
+
// (pair-bootstrap-<id>, Path 3) and annotates `tpsAgent`; passing straight
|
|
560
|
+
// through skipped that annotation, so the resource's bootstrap-user binding
|
|
561
|
+
// (PR-4, resources/Federation.ts) could never see a caller and never
|
|
562
|
+
// refused a mismatch. An anonymous pair request (no Authorization header)
|
|
563
|
+
// still passes through.
|
|
564
|
+
(routedDecisionPath === "/FederationPair" && !isBasic) ||
|
|
236
565
|
// OAuth 2.1 public endpoints (spec requires no pre-auth)
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
566
|
+
routedDecisionPath === "/OAuthRegister" ||
|
|
567
|
+
routedDecisionPath === "/OAuthAuthorize" ||
|
|
568
|
+
routedDecisionPath === "/OAuthToken" ||
|
|
569
|
+
routedDecisionPath === "/OAuthRevoke" ||
|
|
241
570
|
// Belt-and-braces since flair#1000: `/.well-known/oauth-authorization-server`
|
|
242
571
|
// is served from its OWN urlPath mount (resources/oauth-wellknown.ts), which
|
|
243
572
|
// gets its own dispatch chain — this middleware never sees a request for it.
|
|
244
573
|
// The entry stays so the path is still public if that mount ever moves back
|
|
245
574
|
// 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"))
|
|
575
|
+
routedDecisionPath === "/.well-known/oauth-authorization-server" ||
|
|
576
|
+
routedDecisionPath === "/OAuthMetadata"))
|
|
271
577
|
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
578
|
// If Harper has already authorized this request (e.g. Basic admin, or
|
|
277
579
|
// authorizeLocal=true on localhost), trust Harper's auth decision and pass
|
|
278
580
|
// through. Annotate the admin identity so resources' resolveAgentAuth recognizes
|
|
@@ -288,13 +590,15 @@ server.http(async (request, nextLayer) => {
|
|
|
288
590
|
// live vector today — but it keeps the trust decision from ever hinging on
|
|
289
591
|
// ambient elevation alone. (The root-cause gate lives in resolveAgentAuth; see
|
|
290
592
|
// agent-auth.ts hasCredentialEvidence.)
|
|
291
|
-
if (header && request.user?.role?.permission?.super_user === true) {
|
|
593
|
+
if (!isTpsEd25519 && header && request.user?.role?.permission?.super_user === true) {
|
|
292
594
|
const username = request.user.username ?? "admin";
|
|
293
595
|
// Deactivation guard — same predicate as the Ed25519 path.
|
|
294
596
|
// A deactivated principal must not receive a tpsAgent annotation, even
|
|
295
597
|
// when Harper's ambient auth already verified the credential.
|
|
296
|
-
const
|
|
297
|
-
if (!
|
|
598
|
+
const read = await readCredentialedPrincipal(username);
|
|
599
|
+
if (!read.ok)
|
|
600
|
+
return credentialedLookupRefusal(username, read.error);
|
|
601
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
298
602
|
request.tpsAgent = username;
|
|
299
603
|
request.tpsAgentIsAdmin = true;
|
|
300
604
|
try {
|
|
@@ -316,19 +620,18 @@ server.http(async (request, nextLayer) => {
|
|
|
316
620
|
// 1. HDB_ADMIN_PASSWORD env-var fast-path (user must be "admin" with exact pass)
|
|
317
621
|
// 2. Harper super_user check — any user with super_user:true permission accepted
|
|
318
622
|
// Checked BEFORE Ed25519 so admin tools can use simple auth.
|
|
319
|
-
if (
|
|
623
|
+
if (isBasic) {
|
|
320
624
|
try {
|
|
321
|
-
const
|
|
322
|
-
const colonIdx = decoded.indexOf(":");
|
|
323
|
-
const user = colonIdx >= 0 ? decoded.slice(0, colonIdx) : decoded;
|
|
324
|
-
const pass = colonIdx >= 0 ? decoded.slice(colonIdx + 1) : "";
|
|
625
|
+
const { user, pass } = parseBasicAuthHeader(header);
|
|
325
626
|
// Path 1: Env-var fast-path (back-compat). Only matches user==="admin"
|
|
326
627
|
// with exact HDB_ADMIN_PASSWORD. Non-match falls through to Path 2.
|
|
327
628
|
const adminPass = getAdminPass();
|
|
328
629
|
if (adminPass !== null && user === "admin" && pass === adminPass) {
|
|
329
630
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
330
|
-
const
|
|
331
|
-
if (!
|
|
631
|
+
const read = await readCredentialedPrincipal("admin");
|
|
632
|
+
if (!read.ok)
|
|
633
|
+
return credentialedLookupRefusal("admin", read.error);
|
|
634
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
332
635
|
// Mark as verified and set Harper user directly
|
|
333
636
|
request._tpsAuthVerified = true;
|
|
334
637
|
try {
|
|
@@ -352,8 +655,10 @@ server.http(async (request, nextLayer) => {
|
|
|
352
655
|
catch { /* fall through — invalid creds, non-existent user, etc. */ }
|
|
353
656
|
if (harperUser?.role?.permission?.super_user === true) {
|
|
354
657
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
355
|
-
const
|
|
356
|
-
if (!
|
|
658
|
+
const read = await readCredentialedPrincipal(user);
|
|
659
|
+
if (!read.ok)
|
|
660
|
+
return credentialedLookupRefusal(user, read.error);
|
|
661
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
357
662
|
request._tpsAuthVerified = true;
|
|
358
663
|
request.user = harperUser;
|
|
359
664
|
request.headers.set("x-tps-agent", user);
|
|
@@ -368,7 +673,7 @@ server.http(async (request, nextLayer) => {
|
|
|
368
673
|
// Path 3: flair_pair_initiator — restricted to /FederationPair only.
|
|
369
674
|
// Bootstrap credentials (pair-bootstrap-<id>) may only be used on this
|
|
370
675
|
// one endpoint. Any other path must fall through to 401.
|
|
371
|
-
if (
|
|
676
|
+
if (routedDecisionPath === "/FederationPair" && user.startsWith("pair-bootstrap-")) {
|
|
372
677
|
let pairUser = null;
|
|
373
678
|
try {
|
|
374
679
|
pairUser = await server.getUser(user, pass, request);
|
|
@@ -377,8 +682,10 @@ server.http(async (request, nextLayer) => {
|
|
|
377
682
|
if (pairUser?.role?.role === "flair_pair_initiator" &&
|
|
378
683
|
pairUser?.active === true) {
|
|
379
684
|
// Deactivation guard — same predicate, called before tpsAgent is stamped.
|
|
380
|
-
const
|
|
381
|
-
if (!
|
|
685
|
+
const read = await readCredentialedPrincipal(user);
|
|
686
|
+
if (!read.ok)
|
|
687
|
+
return credentialedLookupRefusal(user, read.error);
|
|
688
|
+
if (!isPrincipalDeactivated(read.agent)) {
|
|
382
689
|
request._tpsAuthVerified = true;
|
|
383
690
|
request.user = pairUser;
|
|
384
691
|
request.headers.set("x-tps-agent", user);
|
|
@@ -409,11 +716,13 @@ server.http(async (request, nextLayer) => {
|
|
|
409
716
|
// ── Ed25519 agent auth ────────────────────────────────────────────────────
|
|
410
717
|
const parsed = parseTpsEd25519Header(header);
|
|
411
718
|
if (!parsed) {
|
|
719
|
+
if (isTpsEd25519)
|
|
720
|
+
return new Response(JSON.stringify({ error: "invalid_authorization_header" }), { status: 401 });
|
|
412
721
|
// For browser-accessible admin pages, emit `WWW-Authenticate: Basic` so
|
|
413
722
|
// the browser shows a native auth dialog instead of a bare 401 page.
|
|
414
723
|
// JSON API endpoints don't get this — they should keep the structured
|
|
415
724
|
// 401 body so the client can parse the error.
|
|
416
|
-
const isAdminPage =
|
|
725
|
+
const isAdminPage = routedDecisionPath === "/Admin" || routedDecisionPath.startsWith("/Admin");
|
|
417
726
|
if (isAdminPage) {
|
|
418
727
|
return new Response("Authentication required.", {
|
|
419
728
|
status: 401,
|
|
@@ -438,6 +747,11 @@ server.http(async (request, nextLayer) => {
|
|
|
438
747
|
return nextLayer(request);
|
|
439
748
|
}
|
|
440
749
|
const { agentId, tsRaw, nonce, signatureB64 } = parsed;
|
|
750
|
+
// Refuse a signed request whose raw target WHATWG URL parsing would rewrite
|
|
751
|
+
// before verification, so the signature covers the target exactly as received.
|
|
752
|
+
if (!whatwgUrlMatchesRawTarget(rawTarget)) {
|
|
753
|
+
return nonCanonicalRequestTargetRefusal(String(request.method ?? ""));
|
|
754
|
+
}
|
|
441
755
|
const ts = Number(tsRaw);
|
|
442
756
|
const now = Date.now();
|
|
443
757
|
if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
|
|
@@ -474,16 +788,12 @@ server.http(async (request, nextLayer) => {
|
|
|
474
788
|
return new Response(JSON.stringify({ error: claim.error }), { status: claim.status });
|
|
475
789
|
request.tpsAgent = agentId;
|
|
476
790
|
request._tpsAuthVerified = true;
|
|
477
|
-
|
|
478
|
-
//
|
|
479
|
-
//
|
|
480
|
-
//
|
|
481
|
-
|
|
482
|
-
|
|
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
|
-
//
|
|
791
|
+
// The admin decision uses the Agent row the signature was just verified
|
|
792
|
+
// against, plus the configured admin ids. The marker tells a handler that
|
|
793
|
+
// tpsAgentIsAdmin already is that decision (agent-auth.ts
|
|
794
|
+
// annotatedCallerIsAdmin), so no handler re-decides it from another read.
|
|
795
|
+
request.tpsAgentIsAdmin = agentIsAdmin(agentId, agent);
|
|
796
|
+
request.tpsAgentAdminFromVerifiedRow = true;
|
|
487
797
|
// RESHAPE (auth-rbac) — THE FLIP: per-agent DE-ELEVATION. A cryptographically-
|
|
488
798
|
// verified NON-admin agent resolves to the least-privilege `flair-agent` user,
|
|
489
799
|
// NOT admin super_user. The flair_agent role grants exactly the table CRUD agents
|
|
@@ -530,15 +840,26 @@ server.http(async (request, nextLayer) => {
|
|
|
530
840
|
// SQL and GraphQL endpoints bypass all resource-level scoping — block them
|
|
531
841
|
// for non-admin agents. Admins (bootstrap, consolidation scripts) still pass.
|
|
532
842
|
if (!request.tpsAgentIsAdmin) {
|
|
533
|
-
const
|
|
534
|
-
if (
|
|
535
|
-
|
|
843
|
+
const lowerPath = (routed ? routedDecisionPath : routedResourcePath(targetPath, RAW_QUERY_RESOURCES)).toLowerCase();
|
|
844
|
+
if (lowerPath === "/sql" || lowerPath.startsWith("/sql/") ||
|
|
845
|
+
lowerPath === "/graphql" || lowerPath.startsWith("/graphql/")) {
|
|
536
846
|
return new Response(JSON.stringify({ error: "forbidden: raw query endpoints require admin access" }), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
537
847
|
}
|
|
538
848
|
}
|
|
539
849
|
// ── Server-side permission guards ──────────────────────────────────────────
|
|
540
850
|
const method = request.method.toUpperCase();
|
|
541
851
|
const isMutation = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
|
|
852
|
+
// A signed non-admin agent's mutation that reaches this point (the earlier
|
|
853
|
+
// checks, e.g. the rate limit and the raw-query refusal, answer first) is
|
|
854
|
+
// refused before the owner decisions below when Harper's route lookup threw, or
|
|
855
|
+
// when Harper matched the target but its request-target parsing or path parsing
|
|
856
|
+
// could not resolve the record id.
|
|
857
|
+
if (isMutation && !request.tpsAgentIsAdmin && routeLookupFailed) {
|
|
858
|
+
return routeLookupFailedRefusal();
|
|
859
|
+
}
|
|
860
|
+
if (isMutation && !request.tpsAgentIsAdmin && routed?.recordIdUnresolved) {
|
|
861
|
+
return unresolvedTargetRefusal();
|
|
862
|
+
}
|
|
542
863
|
// ── THE record-ownership rule, for every table, on every mutating verb ─────
|
|
543
864
|
//
|
|
544
865
|
// One enforcement point rather than one per resource. See
|
|
@@ -556,21 +877,38 @@ server.http(async (request, nextLayer) => {
|
|
|
556
877
|
// resource's own no-forge attribution. That keeps this incapable of breaking a
|
|
557
878
|
// create, a self-write, or a legitimate cross-agent field like MemoryGrant's
|
|
558
879
|
// granteeId — it can only narrow mutation of another agent's stored row.
|
|
559
|
-
|
|
560
|
-
|
|
880
|
+
// A Memory mutation whose raw id ends in the reserved `.content` suffix is a
|
|
881
|
+
// request the resource layer refuses by SHAPE (flair#2199, 400
|
|
882
|
+
// memory_id_content_suffix) and commits no row — Harper mutates nothing, so
|
|
883
|
+
// the ownership guard below must not pre-empt that with a 403 on the base row
|
|
884
|
+
// the `.content` property parse happens to name. Skip the guard for it and let
|
|
885
|
+
// the resource's named 400 answer, as it did before the routed-id resolution.
|
|
886
|
+
const isReservedContentMutation = isMutation &&
|
|
887
|
+
(routedDecisionPath === "/Memory" || routedDecisionPath.startsWith("/Memory/")) &&
|
|
888
|
+
decodeMemoryIdSegment(lastRawPathSegment(targetPath)).endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX);
|
|
889
|
+
if (isMutation && !request.tpsAgentIsAdmin && !isReservedContentMutation) {
|
|
890
|
+
const guarded = routed
|
|
891
|
+
? resolveGuardedRecordById(routed.resource, routed.recordId)
|
|
892
|
+
: resolveGuardedRecord(targetPath);
|
|
561
893
|
if (guarded) {
|
|
894
|
+
let record;
|
|
562
895
|
try {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
896
|
+
record = await databases.flair[guarded.table]?.get(guarded.id);
|
|
897
|
+
}
|
|
898
|
+
catch {
|
|
899
|
+
// The ownership read is the authorization input. A read that FAILED is
|
|
900
|
+
// not "no owner" and must not fall through to the resource's allow* as
|
|
901
|
+
// though the check passed — fail closed with a named, retryable refusal.
|
|
902
|
+
return ownerReadFailedRefusal(guarded.table);
|
|
903
|
+
}
|
|
904
|
+
if (isForbiddenOwnerMutation(record, guarded.ownerField, agentId)) {
|
|
905
|
+
return ownerMutationRefusal(guarded.table);
|
|
567
906
|
}
|
|
568
|
-
catch { /* unreadable row → fall through to the resource's own rules */ }
|
|
569
907
|
}
|
|
570
908
|
}
|
|
571
909
|
if (isMutation) {
|
|
572
910
|
// OrgEvent: authorId must match authenticated agent
|
|
573
|
-
if ((
|
|
911
|
+
if ((routedDecisionPath === "/OrgEvent" || routedDecisionPath.startsWith("/OrgEvent/")) &&
|
|
574
912
|
(method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
575
913
|
if (!request.tpsAgentIsAdmin) {
|
|
576
914
|
try {
|
|
@@ -591,25 +929,28 @@ server.http(async (request, nextLayer) => {
|
|
|
591
929
|
}
|
|
592
930
|
}
|
|
593
931
|
// OrgEvent DELETE: ownership check
|
|
594
|
-
if (
|
|
932
|
+
if (routedDecisionPath.startsWith("/OrgEvent/") && method === "DELETE") {
|
|
595
933
|
if (!request.tpsAgentIsAdmin) {
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
934
|
+
const eventId = routed ? routed.recordId : (routedRecordId(targetPath)?.id ?? null);
|
|
935
|
+
if (eventId) {
|
|
936
|
+
let record;
|
|
937
|
+
try {
|
|
938
|
+
record = await databases.flair.OrgEvent.get(eventId);
|
|
939
|
+
}
|
|
940
|
+
catch {
|
|
941
|
+
// A failed read is not "no author": refuse, as the shared owner rule does.
|
|
942
|
+
return ownerReadFailedRefusal("OrgEvent");
|
|
943
|
+
}
|
|
944
|
+
if (record && record.authorId && record.authorId !== agentId) {
|
|
945
|
+
return new Response(JSON.stringify({
|
|
946
|
+
error: "forbidden: cannot delete events authored by another agent"
|
|
947
|
+
}), { status: 403 });
|
|
606
948
|
}
|
|
607
949
|
}
|
|
608
|
-
catch { }
|
|
609
950
|
}
|
|
610
951
|
}
|
|
611
952
|
// WorkspaceState: agent-scoped mutations (non-admin can only write own records)
|
|
612
|
-
if ((
|
|
953
|
+
if ((routedDecisionPath === "/WorkspaceState" || routedDecisionPath.startsWith("/WorkspaceState/")) &&
|
|
613
954
|
(method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
614
955
|
if (!request.tpsAgentIsAdmin) {
|
|
615
956
|
try {
|
|
@@ -630,21 +971,24 @@ server.http(async (request, nextLayer) => {
|
|
|
630
971
|
}
|
|
631
972
|
}
|
|
632
973
|
// WorkspaceState DELETE: ownership check
|
|
633
|
-
if ((
|
|
974
|
+
if ((routedDecisionPath.startsWith("/WorkspaceState/")) && method === "DELETE") {
|
|
634
975
|
if (!request.tpsAgentIsAdmin) {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
976
|
+
const wsId = routed ? routed.recordId : (routedRecordId(targetPath)?.id ?? null);
|
|
977
|
+
if (wsId) {
|
|
978
|
+
let record;
|
|
979
|
+
try {
|
|
980
|
+
record = await databases.flair.WorkspaceState.get(wsId);
|
|
981
|
+
}
|
|
982
|
+
catch {
|
|
983
|
+
// A failed read is not "no owner": refuse, as the shared owner rule does.
|
|
984
|
+
return ownerReadFailedRefusal("WorkspaceState");
|
|
985
|
+
}
|
|
986
|
+
if (record && record.agentId && record.agentId !== agentId) {
|
|
987
|
+
return new Response(JSON.stringify({
|
|
988
|
+
error: "forbidden: cannot delete workspace state for another agent"
|
|
989
|
+
}), { status: 403 });
|
|
645
990
|
}
|
|
646
991
|
}
|
|
647
|
-
catch { }
|
|
648
992
|
}
|
|
649
993
|
}
|
|
650
994
|
// Soul mutations: only the owner or an admin may write a soul entry.
|
|
@@ -679,7 +1023,7 @@ server.http(async (request, nextLayer) => {
|
|
|
679
1023
|
// The path test stays `startsWith("/Soul")` so sibling routes keep the
|
|
680
1024
|
// body check they already had; the record lookup is scoped to the real
|
|
681
1025
|
// `/Soul/<id>` collection so it never resolves an unrelated id.
|
|
682
|
-
if (
|
|
1026
|
+
if (routedDecisionPath.startsWith("/Soul") &&
|
|
683
1027
|
(method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE")) {
|
|
684
1028
|
if (!request.tpsAgentIsAdmin) {
|
|
685
1029
|
// (a) A PRESENT, mismatched body agentId is a forged attribution.
|
|
@@ -712,7 +1056,7 @@ server.http(async (request, nextLayer) => {
|
|
|
712
1056
|
}
|
|
713
1057
|
// ── WorkspaceState read guard: agent-scoped reads ───────────────────────────
|
|
714
1058
|
if (method === "GET" && !request.tpsAgentIsAdmin) {
|
|
715
|
-
if (
|
|
1059
|
+
if (routedDecisionPath === "/WorkspaceState" || routedDecisionPath === "/WorkspaceState/") {
|
|
716
1060
|
const queryAgent = url.searchParams.get("agentId");
|
|
717
1061
|
if (queryAgent && queryAgent !== agentId) {
|
|
718
1062
|
return new Response(JSON.stringify({
|
|
@@ -741,21 +1085,40 @@ server.http(async (request, nextLayer) => {
|
|
|
741
1085
|
// contract, applied in `Memory.get`/`Memory.search`). The by-id
|
|
742
1086
|
// read-scope denial is enforced by the resource layer (memoryByIdReadGate),
|
|
743
1087
|
// which returns the same 404 this middleware used to return.
|
|
744
|
-
|
|
745
|
-
|
|
1088
|
+
// (A malformed `.content` segment was refused before any auth branch, above.)
|
|
1089
|
+
if (!request.tpsAgentIsAdmin && (method === "GET" || method === "HEAD") && isMemoryReadPath(routedDecisionPath)) {
|
|
1090
|
+
// flair#2199: an id segment carrying an encoded `/` before a declared
|
|
1091
|
+
// property suffix is ambiguous — the suffix could be part of the id or a
|
|
1092
|
+
// selector on a slash-containing id. This branch runs for a signed
|
|
1093
|
+
// non-admin agent: Basic-admin and anonymous requests returned to the next
|
|
1094
|
+
// layer before it.
|
|
1095
|
+
if (isAmbiguousEncodedSlashSelector(request.url)) {
|
|
1096
|
+
return new Response(method === "HEAD" ? null : JSON.stringify({
|
|
1097
|
+
error: "ambiguous_memory_id",
|
|
1098
|
+
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`,
|
|
1099
|
+
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
1100
|
+
}
|
|
1101
|
+
// The path rewrite inside stripMemorySelection runs only when Harper's own
|
|
1102
|
+
// routing returned a Memory route with a record id. With no route (e.g. no
|
|
1103
|
+
// live registry, no match, or a matcher error) or no record id, the path is
|
|
1104
|
+
// left as sent; the query-selection removal does not depend on this.
|
|
1105
|
+
const routedToMemoryRecord = routed !== null && routed.resource === "Memory" && routed.recordId !== null;
|
|
1106
|
+
const stripped = stripMemorySelection(request.url, routedToMemoryRecord);
|
|
746
1107
|
if (stripped !== request.url)
|
|
747
1108
|
request.url = stripped;
|
|
748
1109
|
}
|
|
749
1110
|
// ── Embedding backfill ─────────────────────────────────────────────────────
|
|
750
|
-
const isMemoryWrite = isMutation &&
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
1111
|
+
const isMemoryWrite = isMutation && method !== "DELETE" &&
|
|
1112
|
+
(routedDecisionPath === "/Memory" || routedDecisionPath.startsWith("/Memory/"));
|
|
1113
|
+
const routedMemoryWrite = routed
|
|
1114
|
+
? (routed.resource === "Memory" ? routed.recordId : null)
|
|
1115
|
+
: (() => { const r = routedRecordId(targetPath); return r?.resource === "Memory" ? r.id : null; })();
|
|
1116
|
+
const routedCommittedId = (method === "PUT" || method === "PATCH") ? routedMemoryWrite : null;
|
|
756
1117
|
const response = await nextLayer(request);
|
|
757
|
-
if (isMemoryWrite &&
|
|
758
|
-
|
|
1118
|
+
if (isMemoryWrite && response.status >= 200 && response.status < 300) {
|
|
1119
|
+
const committedId = committedMemoryIdFromResult(response) ?? routedCommittedId;
|
|
1120
|
+
if (committedId)
|
|
1121
|
+
backfillEmbedding(committedId).catch(() => { });
|
|
759
1122
|
}
|
|
760
1123
|
return response;
|
|
761
1124
|
}, { runFirst: true, name: FLAIR_AUTH_MIDDLEWARE_HTTP_NAME });
|