@tpsdev-ai/flair 0.55.2 → 0.57.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 +18 -19
- package/dist/bridges/builtins/markdown.js +2 -2
- package/dist/bridges/discover.js +2 -2
- package/dist/bridges/runtime/allow-list.js +2 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +125 -26
- package/dist/commands/agent.js +22 -15
- package/dist/commands/attention.js +2 -2
- package/dist/commands/backup.js +2 -2
- package/dist/commands/bridge.js +40 -3
- package/dist/commands/doctor.js +91 -28
- package/dist/commands/export.js +2 -2
- package/dist/commands/federation.js +441 -68
- package/dist/commands/hook.js +4 -4
- package/dist/commands/init.js +59 -12
- package/dist/commands/mcp.js +2 -2
- package/dist/commands/migrate-harness-memory.js +8 -8
- package/dist/commands/rem.js +2 -2
- package/dist/commands/service.js +25 -1
- package/dist/commands/session.js +2 -2
- package/dist/commands/uninstall.js +2 -2
- package/dist/commands/upgrade.js +3 -3
- package/dist/doctor-client.js +5 -23
- package/dist/engine-version.js +2 -2
- package/dist/federation/scheduler.js +5 -5
- package/dist/install/clients.js +5 -10
- package/dist/keystore.js +10 -2
- package/dist/lib/auth-resolve.js +51 -5
- package/dist/lib/doctor-config-path.js +2 -2
- package/dist/lib/flair-paths.js +29 -0
- package/dist/lib/home.js +60 -0
- package/dist/lib/instance-identity-row.js +580 -0
- package/dist/lib/launchd-repair.js +6 -0
- package/dist/lib/mcp-enable.js +4 -4
- package/dist/lib/owned-pins.js +1 -13
- package/dist/lib/redact-token-id.js +197 -0
- package/dist/lib/socket-path-limit.js +120 -0
- package/dist/lib/uninstall-purge.js +2 -18
- package/dist/lib/upgrade-plain-tree.js +2 -2
- package/dist/mcp-client-assertion.js +3 -3
- package/dist/rem/runner.js +3 -3
- package/dist/rem/scheduler.js +5 -5
- package/dist/rem/snapshot.js +2 -2
- package/dist/resources/AgentSeed.js +4 -1
- package/dist/resources/Asset.js +3 -11
- package/dist/resources/Credential.js +4 -10
- package/dist/resources/Federation.js +232 -78
- package/dist/resources/Integration.js +8 -32
- package/dist/resources/Memory.js +58 -16
- package/dist/resources/MemoryBootstrap.js +19 -12
- package/dist/resources/MemoryCandidate.js +3 -11
- package/dist/resources/MemoryDedupStats.js +1 -1
- package/dist/resources/MemoryFeed.js +10 -2
- package/dist/resources/MemoryGrant.js +19 -40
- package/dist/resources/MemoryUsage.js +7 -20
- package/dist/resources/OAuth.js +62 -11
- package/dist/resources/Presence.js +135 -47
- package/dist/resources/Relationship.js +3 -11
- package/dist/resources/SemanticSearch.js +25 -13
- package/dist/resources/admin-layout.js +7 -2
- package/dist/resources/auth-middleware.js +32 -5
- package/dist/resources/bm25.js +13 -14
- package/dist/resources/federation-cleanup.js +289 -51
- package/dist/resources/health.js +48 -8
- package/dist/resources/in-process-api.js +2 -1
- package/dist/resources/instance-create-lock.js +363 -0
- package/dist/resources/instance-identity-rows.js +43 -0
- package/dist/resources/instance-identity.js +94 -10
- package/dist/resources/mcp-handler.js +9 -1
- package/dist/resources/mcp-tool-arguments.js +83 -0
- package/dist/resources/mcp-tools.js +4 -5
- package/dist/resources/memory-reflect-lib.js +17 -1
- package/dist/resources/memory-visibility.js +10 -7
- package/dist/resources/rate-limit.js +6 -4
- package/dist/resources/record-type-kit.js +47 -23
- package/dist/resources/search-readiness.js +7 -1
- package/dist/resources/semantic-retrieval-core.js +98 -3
- package/dist/resources/table-helpers.js +33 -0
- package/dist/resources/tool-descriptors/index.js +2 -2
- package/dist/src/keystore.js +10 -2
- package/dist/src/lib/home.js +60 -0
- package/dist/src/lib/instance-identity-row.js +580 -0
- package/dist/src/lib/redact-token-id.js +197 -0
- package/dist/src/rem/scheduler.js +5 -5
- package/dist/version-check.js +2 -2
- package/dist/version-handshake.js +2 -2
- package/docs/api-reference.md +32 -7
- package/docs/auth.md +19 -7
- package/docs/claude-code.md +5 -6
- package/docs/deploying-on-fabric.md +8 -4
- package/docs/deployment.md +26 -37
- package/docs/embedding-in-a-harper-app.md +4 -2
- package/docs/entity-vocabulary.md +5 -5
- package/docs/federation.md +48 -21
- package/docs/hosted-on-fabric.md +7 -4
- package/docs/integrations.md +24 -15
- package/docs/mcp-clients.md +44 -23
- package/docs/n8n.md +8 -8
- package/docs/notes/mcp-oauth-model2.md +12 -17
- package/docs/openclaw.md +29 -28
- package/docs/spoke-bringup.md +44 -22
- package/docs/standalone-local.md +12 -16
- package/docs/supply-chain-policy.md +21 -8
- package/docs/system-requirements.md +1 -1
- package/docs/upgrade.md +2 -2
- package/package.json +1 -1
|
@@ -4,6 +4,10 @@ import nacl from "tweetnacl";
|
|
|
4
4
|
import { allowAdmin } from "./agent-auth.js";
|
|
5
5
|
import { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce, } from "./federation-crypto.js";
|
|
6
6
|
import { reconcileState } from "./relay-lib.js";
|
|
7
|
+
import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY, multipleInstanceRowsMessage, } from "../src/lib/instance-identity-row.js";
|
|
8
|
+
import { readAllInstanceRows } from "./instance-identity-rows.js";
|
|
9
|
+
import { findOrCreateInstance } from "./instance-create-lock.js";
|
|
10
|
+
import { withDetachedTxnAsync } from "./table-helpers.js";
|
|
7
11
|
import { isSkillWrite } from "./skill-write.js";
|
|
8
12
|
import { noteWriteStamp } from "./embedding-space-guard.js";
|
|
9
13
|
import { initFederationCleanup } from "./federation-cleanup.js";
|
|
@@ -52,12 +56,19 @@ function requireRecordPrincipal() {
|
|
|
52
56
|
return (process.env.FLAIR_FEDERATION_REQUIRE_RECORD_PRINCIPAL ?? "").toLowerCase() === "true";
|
|
53
57
|
}
|
|
54
58
|
// ─── Conflict resolution ─────────────────────────────────────────────────────
|
|
59
|
+
/**
|
|
60
|
+
* The row written is `record.data`, but the row checked (and merged against) is
|
|
61
|
+
* `record.id`. The payload must carry that same id, or the record is not applied.
|
|
62
|
+
*/
|
|
63
|
+
export function payloadIdMismatch(record) {
|
|
64
|
+
return !record.data || record.data.id !== record.id;
|
|
65
|
+
}
|
|
55
66
|
/**
|
|
56
67
|
* Field-level Last-Write-Wins merge.
|
|
57
68
|
* For each field, the value with the later `updatedAt` wins.
|
|
58
69
|
* Records with no local counterpart are accepted directly.
|
|
59
70
|
*/
|
|
60
|
-
function mergeRecord(local, remote) {
|
|
71
|
+
export function mergeRecord(local, remote) {
|
|
61
72
|
if (!local)
|
|
62
73
|
return remote.data;
|
|
63
74
|
const merged = { ...local };
|
|
@@ -67,7 +78,11 @@ function mergeRecord(local, remote) {
|
|
|
67
78
|
// Field-level LWW is the spec target but record-level is sufficient
|
|
68
79
|
// for the initial implementation and avoids per-field clock tracking.
|
|
69
80
|
if (remoteUpdated > localUpdated) {
|
|
70
|
-
|
|
81
|
+
// Preserve stored visibility on updates before applying write policy.
|
|
82
|
+
const incoming = { ...remote.data };
|
|
83
|
+
if (incoming.visibility === null || incoming.visibility === undefined)
|
|
84
|
+
delete incoming.visibility;
|
|
85
|
+
Object.assign(merged, incoming);
|
|
71
86
|
merged.updatedAt = remoteUpdated;
|
|
72
87
|
}
|
|
73
88
|
return merged;
|
|
@@ -97,91 +112,184 @@ export function noteFederationMergedMemory(recordTable, mergedData) {
|
|
|
97
112
|
}
|
|
98
113
|
}
|
|
99
114
|
// ─── Instance identity ───────────────────────────────────────────────────────
|
|
115
|
+
/**
|
|
116
|
+
* Every `flair.Instance` row on this instance, or a THROWN error — the ONE
|
|
117
|
+
* strict reader (resources/instance-identity-rows.ts), re-exported here so
|
|
118
|
+
* existing consumers keep importing it from the Federation resource.
|
|
119
|
+
*
|
|
120
|
+
* The readers used to take the first row `search()` yielded. `search()` order is
|
|
121
|
+
* not a fact about an identity: on a table with two rows one reader reported one
|
|
122
|
+
* identity and a pairing peer was handed the other, and which was which depended
|
|
123
|
+
* on the table's internal ordering (flair#1883 round 3).
|
|
124
|
+
*
|
|
125
|
+
* A read that FAILS must not look like a table with no rows: the callers answer
|
|
126
|
+
* 5xx and write nothing, because only a SUCCESSFUL read of zero rows may mint an
|
|
127
|
+
* identity.
|
|
128
|
+
*
|
|
129
|
+
* And neither must a row the reader cannot NAME (flair#1883 round 4): an entry
|
|
130
|
+
* without a usable id used to be skipped here, so a table serving one bad entry
|
|
131
|
+
* (or a good one beside it) read as "the rows I could name" — possibly zero — and
|
|
132
|
+
* the GET's create branch could mint a second identity from a read that never
|
|
133
|
+
* saw the table. `readableInstanceRows` throws instead, which the callers map to
|
|
134
|
+
* 5xx and no write.
|
|
135
|
+
*/
|
|
136
|
+
export { readAllInstanceRows };
|
|
100
137
|
/**
|
|
101
138
|
* GET /FederationInstance — return this instance's identity.
|
|
102
|
-
*
|
|
139
|
+
*
|
|
140
|
+
* The admin UI and CLI tooling read it. Peers do NOT read it while pairing: a
|
|
141
|
+
* spoke is handed this instance's identity in the `POST /FederationPair`
|
|
142
|
+
* response, which FederationPair.post() builds server-side by reading the
|
|
143
|
+
* Instance table directly. (The pair CLI must not GET this path to fill a missing
|
|
144
|
+
* pair publicKey either — flair#822: allowRead is allowAdmin, and get() creates an
|
|
145
|
+
* identity when it finds none, which would invent a hub row; #839.)
|
|
103
146
|
*
|
|
104
147
|
* allowRead()=allowAdmin (defense-in-depth, authorizeLocal-escalation-class
|
|
105
148
|
* follow-up to #601/#604/#609/#612 — flair#614's backstop found this one had
|
|
106
149
|
* NO allow* at all, so Harper's own default — `user?.role.permission.
|
|
107
150
|
* super_user`, satisfiable only by a genuine admin OR authorizeLocal's forged
|
|
108
|
-
* loopback super_user — was silently standing in).
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
* missing pair publicKey (flair#822): allowRead is allowAdmin, and get()
|
|
114
|
-
* find-or-creates an Instance (that would invent a hub row; #839).
|
|
151
|
+
* loopback super_user — was silently standing in).
|
|
152
|
+
*
|
|
153
|
+
* With SEVERAL rows there is no single identity to report, so this answers 409
|
|
154
|
+
* naming every row and the prune. It never reports the row the search happened
|
|
155
|
+
* to yield first (flair#1883 round 3).
|
|
115
156
|
*/
|
|
116
157
|
export class FederationInstance extends Resource {
|
|
117
158
|
async allowRead() {
|
|
118
159
|
return allowAdmin(this.getContext?.());
|
|
119
160
|
}
|
|
120
161
|
async get() {
|
|
121
|
-
// Find or create instance identity
|
|
122
|
-
|
|
162
|
+
// Find or create instance identity.
|
|
163
|
+
//
|
|
164
|
+
// A read that did not happen is an ERROR, never "no row" (flair#1883 round 2).
|
|
165
|
+
// This used to log and fall through to the create branch: on a persistent
|
|
166
|
+
// storage or permission failure the GET then MINTED A SECOND identity row on
|
|
167
|
+
// every call, and which identity this instance reported depended on which row
|
|
168
|
+
// `search()` yielded first. Only a SUCCESSFUL read that returns zero rows may
|
|
169
|
+
// create.
|
|
170
|
+
// Every row, not the first one (flair#1883 round 3): with several rows the
|
|
171
|
+
// first is a coin toss, and reporting one identity here while a peer is
|
|
172
|
+
// handed another is how the two writers disagreed in the first place.
|
|
173
|
+
let rows = null;
|
|
174
|
+
let readError = null;
|
|
123
175
|
try {
|
|
124
|
-
|
|
125
|
-
instance = i;
|
|
126
|
-
break;
|
|
127
|
-
}
|
|
176
|
+
rows = await readAllInstanceRows();
|
|
128
177
|
}
|
|
129
178
|
catch (err) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
// server
|
|
136
|
-
console.
|
|
137
|
-
"
|
|
138
|
-
`${
|
|
179
|
+
readError = err;
|
|
180
|
+
}
|
|
181
|
+
if (readError) {
|
|
182
|
+
// 5xx: the caller retries, and a retry that finally reads is the only thing
|
|
183
|
+
// that creates. flair#1233's warn stays — the error class belongs in the
|
|
184
|
+
// server log — but it is no longer a licence to write.
|
|
185
|
+
console.error("[federation] GET /FederationInstance could not read the Instance table — answering 503 and creating NOTHING. " +
|
|
186
|
+
"A read error is not first boot; minting an identity here would add a second row to an instance that already has one. " +
|
|
187
|
+
`${readError?.constructor?.name ?? "Error"}: ${readError?.message ?? readError}`);
|
|
188
|
+
return new Response(JSON.stringify({
|
|
189
|
+
error: "instance_identity_unreadable",
|
|
190
|
+
detail: "The Instance table could not be read, so this instance's identity is unknown. Nothing was created.",
|
|
191
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
192
|
+
}
|
|
193
|
+
const decision = decideInstanceAnswer(rows);
|
|
194
|
+
if (decision.kind === "refuse-multiple") {
|
|
195
|
+
// 409: several rows means there is no canonical identity, and reporting
|
|
196
|
+
// one of them would be exactly the coin toss #1883 exists to end — a peer
|
|
197
|
+
// could go on to pin it. Nothing is created and nothing is deleted; the
|
|
198
|
+
// operator resolves the table with the prune this names.
|
|
199
|
+
console.error(`[federation] GET /FederationInstance found ${decision.rows.length} Instance rows — answering 409 and creating NOTHING. ` +
|
|
200
|
+
"Which row this instance reports must not depend on which row the search yields first.");
|
|
201
|
+
return new Response(JSON.stringify({
|
|
202
|
+
error: "multiple_instance_rows",
|
|
203
|
+
detail: multipleInstanceRowsMessage(decision.rows, "GET /FederationInstance"),
|
|
204
|
+
rows: decision.rows,
|
|
205
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
139
206
|
}
|
|
207
|
+
let instance = decision.kind === "answer" ? decision.row : null;
|
|
140
208
|
// Runtime-only signal (flair#1233): whether this instance's private key
|
|
141
209
|
// seed is present in the keystore, i.e. whether it can SIGN (pair/sync).
|
|
142
210
|
// Deliberately NOT persisted — the Instance.status enum is
|
|
143
211
|
// schema-constrained and this is transient machine state; recomputed on
|
|
144
212
|
// every GET.
|
|
145
213
|
let signingKeyAvailable = false;
|
|
146
|
-
if (
|
|
147
|
-
// First boot
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
214
|
+
if (decision.kind === "none") {
|
|
215
|
+
// First boot: the read OUTSIDE the lock found no row. The create runs in the
|
|
216
|
+
// filesystem bakery critical section (flair#1897) — shared by EVERY HTTP
|
|
217
|
+
// worker of this process AND every process on this Flair home: a read taken
|
|
218
|
+
// UNDER the lock, the mint, the put, the keystore seed and a confirming
|
|
219
|
+
// re-read — so two concurrent first-boot GETs mint ONE row and both are
|
|
220
|
+
// answered with it. A GET that found a row above never reaches here, so
|
|
221
|
+
// reads stay concurrent.
|
|
222
|
+
const outcome = await findOrCreateInstance({
|
|
223
|
+
// Detach the request's transaction for EVERY read inside the lock: the
|
|
224
|
+
// outer read above opened the request's transaction BEFORE this create, so
|
|
225
|
+
// reusing it here would read the pre-create snapshot and mint a second row
|
|
226
|
+
// even serialised (the table-helpers.ts class). A fresh transaction sees
|
|
227
|
+
// the row the prior lock holder committed.
|
|
228
|
+
readAll: () => withDetachedTxnAsync(this.getContext?.(), () => readAllInstanceRows()),
|
|
229
|
+
// Commit the WRITE before the lock releases: both the row put and the
|
|
230
|
+
// keystore seed run in a DETACHED transaction, so Harper builds a fresh
|
|
231
|
+
// ImmediateTransaction that commits on its own rather than at the end of
|
|
232
|
+
// the request (the lock cannot serialise a write that commits after the
|
|
233
|
+
// method returns — the earlier BLOCKED finding, flair#1897 slice 1).
|
|
234
|
+
put: (row) => withDetachedTxnAsync(this.getContext?.(), () => databases.flair.Instance.put(row)),
|
|
235
|
+
setSeed: (createdId, seed) => withDetachedTxnAsync(this.getContext?.(), async () => {
|
|
236
|
+
const { keystore } = await import("../src/keystore.js");
|
|
237
|
+
keystore.setPrivateKeySeed(createdId, seed);
|
|
238
|
+
}),
|
|
239
|
+
seedPresent: async (rowId) => {
|
|
240
|
+
try {
|
|
241
|
+
const { keystore } = await import("../src/keystore.js");
|
|
242
|
+
return keystore.getPrivateKeySeed(rowId) !== null;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
mint: () => {
|
|
249
|
+
const kp = nacl.sign.keyPair();
|
|
250
|
+
return {
|
|
251
|
+
id: `flair_${randomBytes(4).toString("hex")}`,
|
|
252
|
+
publicKey: Buffer.from(kp.publicKey).toString("base64url"),
|
|
253
|
+
secretKey: kp.secretKey,
|
|
254
|
+
};
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
if (outcome.kind === "refuse-multiple") {
|
|
258
|
+
if (outcome.putCommitted) {
|
|
259
|
+
// This request's OWN detached put committed a row AND the table holds >1.
|
|
260
|
+
console.error(`[federation] GET /FederationInstance: this request committed row ${outcome.mintedId}; the table now holds ` +
|
|
261
|
+
`${outcome.rows.length} rows — hand to ${INSTANCE_ROW_PRUNE_REMEDY}.`);
|
|
262
|
+
return new Response(JSON.stringify({
|
|
263
|
+
error: "multiple_instance_rows",
|
|
264
|
+
detail: multipleInstanceRowsMessage(outcome.rows, "GET /FederationInstance"),
|
|
265
|
+
rows: outcome.rows,
|
|
266
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
267
|
+
}
|
|
268
|
+
// Pre-put (the read before or the first in-lock read) — nothing created.
|
|
269
|
+
console.error(`[federation] GET /FederationInstance found ${outcome.rows.length} Instance rows under the create lock — answering 409 and creating NOTHING.`);
|
|
270
|
+
return new Response(JSON.stringify({
|
|
271
|
+
error: "multiple_instance_rows",
|
|
272
|
+
detail: multipleInstanceRowsMessage(outcome.rows, "GET /FederationInstance"),
|
|
273
|
+
rows: outcome.rows,
|
|
274
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
175
275
|
}
|
|
176
|
-
|
|
177
|
-
console.error(
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
276
|
+
if (outcome.kind === "refuse-unobservable") {
|
|
277
|
+
console.error(`[federation] GET /FederationInstance: minted ${outcome.mintedId} but the confirming re-read saw NO row — ` +
|
|
278
|
+
`the detached write was not observable. Refusing (no retry).`);
|
|
279
|
+
return new Response(JSON.stringify({
|
|
280
|
+
error: "instance_identity_unobservable",
|
|
281
|
+
detail: `This instance minted ${outcome.mintedId} but could not read it back — the write did not commit where expected. ` +
|
|
282
|
+
`Nothing is answered. Retry; if it persists, inspect the flair.Instance table.`,
|
|
283
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
284
|
+
}
|
|
285
|
+
if (outcome.kind === "refuse-lock") {
|
|
286
|
+
console.error(`[federation] GET /FederationInstance: ${outcome.detail}`);
|
|
287
|
+
return new Response(JSON.stringify({ error: "instance_create_lock_unavailable", detail: outcome.detail }), { status: 503, headers: { "content-type": "application/json" } });
|
|
184
288
|
}
|
|
289
|
+
if (outcome.warning)
|
|
290
|
+
console.error(`[federation] ${outcome.warning}`);
|
|
291
|
+
instance = outcome.row;
|
|
292
|
+
signingKeyAvailable = outcome.seeded;
|
|
185
293
|
}
|
|
186
294
|
else {
|
|
187
295
|
// Existing identity: report whether its signing key is present and
|
|
@@ -245,6 +353,56 @@ export class FederationPair extends Resource {
|
|
|
245
353
|
status: 401, headers: { "content-type": "application/json" },
|
|
246
354
|
});
|
|
247
355
|
}
|
|
356
|
+
// ── The identity this response hands the peer, decided BEFORE the pairing
|
|
357
|
+
// token is consumed, BEFORE the peer is read and before ANY peer is written
|
|
358
|
+
// (flair#1883 round 3). ──────────────────────────────────────────────────
|
|
359
|
+
//
|
|
360
|
+
// NOT "before anything": the signature check above has already run and
|
|
361
|
+
// RECORDED ITS NONCE (verifyBodySignatureFresh → NonceStore.set(), see
|
|
362
|
+
// federation-nonce-store.ts). That is deliberate anti-replay state, not a
|
|
363
|
+
// pairing effect — but it is written, and the refusal is precise about what
|
|
364
|
+
// it precedes.
|
|
365
|
+
//
|
|
366
|
+
// A spoke PINS what it is handed here as its hub peer, so this value is the
|
|
367
|
+
// identity a pairing outcome depends on. It used to be "the first row of an
|
|
368
|
+
// unordered search", read AFTER the pairing token was consumed and the peer
|
|
369
|
+
// written — so a hub holding two rows could burn a one-time token, record the
|
|
370
|
+
// new peer, and only then answer with whichever row the table yielded first.
|
|
371
|
+
// The read now comes first, and an unreadable table or several rows refuse
|
|
372
|
+
// with the token still unused and NO peer written.
|
|
373
|
+
let identityRows = null;
|
|
374
|
+
try {
|
|
375
|
+
identityRows = await readAllInstanceRows();
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
console.error("[federation] POST /FederationPair could not read the Instance table — answering 503, consuming NO token and writing NO peer. " +
|
|
379
|
+
`${err?.constructor?.name ?? "Error"}: ${err?.message ?? err}`);
|
|
380
|
+
return new Response(JSON.stringify({
|
|
381
|
+
error: "instance_identity_unreadable",
|
|
382
|
+
detail: "The Instance table could not be read, so this hub's identity is unknown. Nothing was paired: the pairing token is unconsumed and no peer was written.",
|
|
383
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
384
|
+
}
|
|
385
|
+
const identity = decideInstanceAnswer(identityRows);
|
|
386
|
+
if (identity.kind === "refuse-multiple") {
|
|
387
|
+
// 409: with several rows there is no identity this hub can hand a peer
|
|
388
|
+
// without picking one, and the peer would pin the pick. Refuse before the
|
|
389
|
+
// token is consumed and before any Peer row is written.
|
|
390
|
+
//
|
|
391
|
+
// This route is PUBLIC, and this refusal runs before the pairing token or
|
|
392
|
+
// a re-pairing peer's key is checked: any caller with a self-signed body
|
|
393
|
+
// reaches it. So the answer names no row. Each row's id, role and
|
|
394
|
+
// createdAt go to this hub's log; the caller learns only what it can act
|
|
395
|
+
// on: pairing is blocked on the hub side, and the hub's operator resolves
|
|
396
|
+
// it with the prune, which needs admin credentials.
|
|
397
|
+
console.error(`[federation] POST /FederationPair answering 409, consuming NO token and writing NO peer. ` +
|
|
398
|
+
multipleInstanceRowsMessage(identity.rows, "POST /FederationPair"));
|
|
399
|
+
return new Response(JSON.stringify({
|
|
400
|
+
error: "multiple_instance_rows",
|
|
401
|
+
detail: "This hub has more than one Instance row, so it has no single identity to hand a peer. Nothing was paired: " +
|
|
402
|
+
"the pairing token is unconsumed and no peer was written. The hub's operator must keep one row and delete the rest with: " +
|
|
403
|
+
INSTANCE_ROW_PRUNE_REMEDY,
|
|
404
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
405
|
+
}
|
|
248
406
|
// Check if already paired (re-pairing doesn't need a token)
|
|
249
407
|
const existing = await databases.flair.Peer.get(instanceId);
|
|
250
408
|
if (existing) {
|
|
@@ -327,25 +485,17 @@ export class FederationPair extends Resource {
|
|
|
327
485
|
console.warn(`[federation] drop_user failed: ${err?.message} — cleanup sweep will retry`);
|
|
328
486
|
}
|
|
329
487
|
}
|
|
330
|
-
// Return our own identity for the peer to record
|
|
331
|
-
//
|
|
332
|
-
// `instance
|
|
333
|
-
// #839, not a pair-response-shape bug. The spoke must ERROR, never
|
|
488
|
+
// Return our own identity for the peer to record — `{ id, publicKey, role }`,
|
|
489
|
+
// decided BEFORE the token was consumed (above; flair#1883 round 3). An
|
|
490
|
+
// `instance` of `null` means a SUCCESSFUL read found no FederationInstance:
|
|
491
|
+
// that is #839, not a pair-response-shape bug. The spoke must ERROR, never
|
|
334
492
|
// store publicKey:"" (flair#822).
|
|
335
|
-
let ourInstance = null;
|
|
336
|
-
try {
|
|
337
|
-
for await (const i of databases.flair.Instance.search()) {
|
|
338
|
-
ourInstance = i;
|
|
339
|
-
break;
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
catch { }
|
|
343
493
|
return {
|
|
344
494
|
paired: true,
|
|
345
|
-
instance:
|
|
346
|
-
id:
|
|
347
|
-
publicKey:
|
|
348
|
-
role:
|
|
495
|
+
instance: identity.kind === "answer" ? {
|
|
496
|
+
id: identity.row.id,
|
|
497
|
+
publicKey: identity.row.publicKey,
|
|
498
|
+
role: identity.row.role,
|
|
349
499
|
} : null,
|
|
350
500
|
};
|
|
351
501
|
}
|
|
@@ -431,6 +581,10 @@ export class FederationSync extends Resource {
|
|
|
431
581
|
const knownTables = new Set(Object.keys(tableMap));
|
|
432
582
|
for (const record of records) {
|
|
433
583
|
try {
|
|
584
|
+
if (payloadIdMismatch(record)) {
|
|
585
|
+
recordSkip("id_mismatch");
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
434
588
|
const table = (record.table in tableMap)
|
|
435
589
|
? tableMap[record.table]
|
|
436
590
|
: undefined;
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { databases } from "harper";
|
|
2
2
|
import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
|
|
3
3
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
4
|
+
import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
|
|
5
|
+
// Owner-only read scope, applied through the shared by-id gate and scoped search
|
|
6
|
+
// (resources/record-type-kit.ts).
|
|
7
|
+
const integrationReadScope = makeReadScope("owner-only", "agentId");
|
|
8
|
+
const integrationByIdReadGate = makeByIdReadGate(integrationReadScope);
|
|
9
|
+
const integrationScopedSearch = makeScopedSearch(integrationReadScope);
|
|
4
10
|
const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
5
11
|
const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
6
12
|
const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
|
|
@@ -33,30 +39,7 @@ export class Integration extends databases.flair.Integration {
|
|
|
33
39
|
* integration ids.
|
|
34
40
|
*/
|
|
35
41
|
async get(target) {
|
|
36
|
-
|
|
37
|
-
// `isCollection === true`, and are governed by search() (same owner
|
|
38
|
-
// scoping). Only a genuine by-id get is ownership-checked below — see
|
|
39
|
-
// Memory.ts's get() for the full rationale (same bug class).
|
|
40
|
-
if (!target || (typeof target === "object" && target.isCollection)) {
|
|
41
|
-
return this.search(target);
|
|
42
|
-
}
|
|
43
|
-
const auth = await this._auth();
|
|
44
|
-
// Anonymous by-id read is already blocked at the allowRead() gate (403);
|
|
45
|
-
// this is defense-in-depth if get() is ever reached directly.
|
|
46
|
-
if (auth.kind === "anonymous") {
|
|
47
|
-
return NOT_FOUND();
|
|
48
|
-
}
|
|
49
|
-
// Trusted internal call or admin agent — unfiltered, unchanged behavior.
|
|
50
|
-
if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
|
|
51
|
-
return super.get(target);
|
|
52
|
-
}
|
|
53
|
-
// Non-admin agent: only its own integrations.
|
|
54
|
-
const record = await super.get(target);
|
|
55
|
-
if (!record)
|
|
56
|
-
return NOT_FOUND();
|
|
57
|
-
if (record.agentId !== auth.agentId)
|
|
58
|
-
return NOT_FOUND();
|
|
59
|
-
return record;
|
|
42
|
+
return integrationByIdReadGate.call(this, target, (t) => super.get(t));
|
|
60
43
|
}
|
|
61
44
|
async search(query) {
|
|
62
45
|
const auth = await this._auth();
|
|
@@ -65,14 +48,7 @@ export class Integration extends databases.flair.Integration {
|
|
|
65
48
|
if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
|
|
66
49
|
return super.search(query);
|
|
67
50
|
}
|
|
68
|
-
|
|
69
|
-
if (query && typeof query === "object" && !Array.isArray(query)) {
|
|
70
|
-
const existing = query.conditions ?? [];
|
|
71
|
-
query.conditions = Array.isArray(existing) ? [agentIdCondition, ...existing] : [agentIdCondition, existing];
|
|
72
|
-
return super.search(query);
|
|
73
|
-
}
|
|
74
|
-
const conditions = Array.isArray(query) && query.length > 0 ? [agentIdCondition, ...query] : [agentIdCondition];
|
|
75
|
-
return super.search(conditions);
|
|
51
|
+
return integrationScopedSearch(auth.agentId, query, (q) => super.search(q));
|
|
76
52
|
}
|
|
77
53
|
async post(content, context) {
|
|
78
54
|
const auth = await this._auth();
|
package/dist/resources/Memory.js
CHANGED
|
@@ -10,7 +10,7 @@ import { isEmbeddingSpaceUniform, noteWriteStamp } from "./embedding-space-guard
|
|
|
10
10
|
import { scanFields, isStrictMode } from "./content-safety.js";
|
|
11
11
|
import { invalidEntitiesResponse } from "./entity-vocab.js";
|
|
12
12
|
import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
|
|
13
|
-
import { assertValidVisibility, assertVisibilityAllowedForDurability } from "./memory-visibility.js";
|
|
13
|
+
import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
|
|
14
14
|
import { assertValidDurability } from "./memory-durability.js";
|
|
15
15
|
import { enforceSkillDurability, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate } from "./skill-write.js";
|
|
16
16
|
import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
|
|
@@ -47,8 +47,10 @@ function wantsTrust(target, opts) {
|
|
|
47
47
|
return raw === "true" || raw === true;
|
|
48
48
|
}
|
|
49
49
|
/**
|
|
50
|
-
*
|
|
51
|
-
*
|
|
50
|
+
* resolveAllowedOwners (./memory-read-scope.ts) no longer bounds reads — a
|
|
51
|
+
* non-admin reader sees its own records at any visibility plus every other
|
|
52
|
+
* agent's non-private records (resolveReadScope()); the helper is kept for
|
|
53
|
+
* admin tooling only.
|
|
52
54
|
* The full read-scope condition + private-exclusion predicate is now
|
|
53
55
|
* consumed through ./record-type-kit.ts's makeReadScope(), parameterized
|
|
54
56
|
* from RECORD_TYPES.Memory (record-types slice 2, flair#520) rather than a
|
|
@@ -292,7 +294,7 @@ async function runDedupGate(ctx, content) {
|
|
|
292
294
|
return findConservativeDedupMatch(ctx, content.agentId, embedText, embedding, cosineThreshold, lexicalThreshold);
|
|
293
295
|
}
|
|
294
296
|
/** Build the final write response: always `written: true`, always includes
|
|
295
|
-
* `id`, `visibility
|
|
297
|
+
* `id`, includes `visibility` when the persisted row has one, and layers the dedup collision signal on top when
|
|
296
298
|
* present. Never a code path where a match suppresses these base fields.
|
|
297
299
|
*
|
|
298
300
|
* ── Why `visibility` is in the write response (flair#991) ──────────────────
|
|
@@ -309,9 +311,9 @@ async function runDedupGate(ctx, content) {
|
|
|
309
311
|
* Read from `content`, not from `base`: `content.visibility` is the value
|
|
310
312
|
* that was actually persisted a few lines earlier, and assigning after the
|
|
311
313
|
* `...base` spread means the persisted value wins over anything the storage
|
|
312
|
-
* layer echoes back. Omitted (not `null`) when unset, which happens only
|
|
313
|
-
*
|
|
314
|
-
*
|
|
314
|
+
* layer echoes back. Omitted (not `null`) when unset, which happens only for
|
|
315
|
+
* an existing record that has no stored writable visibility — reporting `null`
|
|
316
|
+
* there would read as "no one but the owner",
|
|
315
317
|
* the opposite of what an absent field means to `isPrivateVisibility()`. */
|
|
316
318
|
function buildWriteResponse(content, result, dedupMatch) {
|
|
317
319
|
const base = result && typeof result === "object" && !Array.isArray(result) ? result : {};
|
|
@@ -350,8 +352,9 @@ async function closeSupersededRecord(ctx, oldId, patch) {
|
|
|
350
352
|
noteMemoryUpsert(closed);
|
|
351
353
|
}
|
|
352
354
|
/** Does an agent hold a "write" grant from `ownerId`? Same MemoryGrant lookup
|
|
353
|
-
*
|
|
354
|
-
* here for the "write" scope that gates
|
|
355
|
+
* the read paths used before the open-within-org reframe (reads no longer
|
|
356
|
+
* consult MemoryGrant); it survives here for the "write" scope that gates
|
|
357
|
+
* cross-agent supersede. */
|
|
355
358
|
async function hasWriteGrant(granteeId, ownerId) {
|
|
356
359
|
try {
|
|
357
360
|
for await (const grant of databases.flair.MemoryGrant.search({
|
|
@@ -512,8 +515,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
512
515
|
* describe (`GET /Memory`) to a path outside search() — neither was gated
|
|
513
516
|
* before this fix, so an anonymous caller got a 200 with full record
|
|
514
517
|
* content / schema even though search() (and the write paths) correctly
|
|
515
|
-
* 401/403'd. Per-record
|
|
516
|
-
*
|
|
518
|
+
* 401/403'd. Per-record read scoping happens in get() below (its own records
|
|
519
|
+
* at any visibility plus every other agent's non-private records — grants are
|
|
520
|
+
* not consulted on reads; resolveReadScope()); the collection scope is still
|
|
521
|
+
* in search().
|
|
517
522
|
*
|
|
518
523
|
* allowCreate/allowUpdate/allowDelete are deliberately NOT added here:
|
|
519
524
|
* post()/put()/delete() already self-enforce per-agent ownership inline
|
|
@@ -535,7 +540,8 @@ export class Memory extends databases.flair.Memory {
|
|
|
535
540
|
async get(target, opts) {
|
|
536
541
|
// Collection / query reads — the `GET /Memory/?<query>` form and the bare
|
|
537
542
|
// collection — arrive as a RequestTarget with `isCollection === true`, and
|
|
538
|
-
// are governed by search() (same
|
|
543
|
+
// are governed by search() (same open-within-org read scope; grants are not
|
|
544
|
+
// consulted on reads). Only a genuine by-id
|
|
539
545
|
// get is ownership-checked below. Without this guard, get() would receive
|
|
540
546
|
// the query's RequestTarget, super.get() would return the (truthy) result
|
|
541
547
|
// set, the single-record check would find no `.agentId` on it, and a valid
|
|
@@ -573,7 +579,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
573
579
|
* boolean injection (e.g. [..., "or", { wildcard }]).
|
|
574
580
|
*
|
|
575
581
|
* Admin agents and unauthenticated internal calls pass through unfiltered.
|
|
576
|
-
* Non-admin calls
|
|
582
|
+
* Non-admin calls are scoped to the reader's own records at any visibility
|
|
583
|
+
* plus every other agent's non-private records — the shipped open-within-org
|
|
584
|
+
* read model. MemoryGrant is NOT consulted on reads; the one place the scope
|
|
585
|
+
* is resolved is memory-read-scope.ts's resolveReadScope().
|
|
577
586
|
*/
|
|
578
587
|
async search(query) {
|
|
579
588
|
// Access request context via Harper's Resource instance context.
|
|
@@ -589,8 +598,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
589
598
|
return gate.response;
|
|
590
599
|
if (gate.kind === "unfiltered")
|
|
591
600
|
return overlayHitStatsResult(super.search(query), ctx);
|
|
592
|
-
// Non-admin agent: scope to own
|
|
593
|
-
//
|
|
601
|
+
// Non-admin agent: scope to own records at any visibility plus every other
|
|
602
|
+
// agent's non-private records (open-within-org; MemoryGrant is not
|
|
603
|
+
// consulted on reads). Centralized in
|
|
594
604
|
// memoryReadScope (record-type-kit.ts's makeReadScope(), parameterized
|
|
595
605
|
// from RECORD_TYPES.Memory — see this file's header — delegating
|
|
596
606
|
// "open-within-org" to memory-read-scope.ts's resolveReadScope()
|
|
@@ -901,6 +911,22 @@ export class Memory extends databases.flair.Memory {
|
|
|
901
911
|
const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
902
912
|
if (denial)
|
|
903
913
|
return denial;
|
|
914
|
+
// Preserve stored visibility on updates before applying write policy: a
|
|
915
|
+
// null is no change (PATCH merges), and a present value goes through the
|
|
916
|
+
// same validator and ephemeral-tier guard as put().
|
|
917
|
+
if (content && "visibility" in content && content.visibility == null)
|
|
918
|
+
delete content.visibility;
|
|
919
|
+
if (content && (content.visibility !== undefined || content.durability !== undefined)) {
|
|
920
|
+
const visibilityError = assertValidVisibility(content.visibility);
|
|
921
|
+
if (visibilityError) {
|
|
922
|
+
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
923
|
+
}
|
|
924
|
+
const stored = await super.get();
|
|
925
|
+
const tierError = assertVisibilityAllowedForDurability(content.durability ?? stored?.durability, content.visibility ?? stored?.visibility);
|
|
926
|
+
if (tierError) {
|
|
927
|
+
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
928
|
+
}
|
|
929
|
+
}
|
|
904
930
|
// ── flair#1542 + residual (Kern #1543 review 5135715289): reject skill patches ──
|
|
905
931
|
// patch() routes past put() (and thus past the SkillScan gate + forced
|
|
906
932
|
// durability), so a skill write on this verb would land unscanned. There are
|
|
@@ -945,6 +971,14 @@ export class Memory extends databases.flair.Memory {
|
|
|
945
971
|
});
|
|
946
972
|
}
|
|
947
973
|
delete content._reindex;
|
|
974
|
+
// Preserve stored visibility on updates before applying write policy:
|
|
975
|
+
// a reindex payload that omits it keeps the record's stored value.
|
|
976
|
+
if (content.visibility === undefined || content.visibility === null) {
|
|
977
|
+
const stored = await super.get();
|
|
978
|
+
if (stored && (stored.visibility === PRIVATE_VISIBILITY || stored.visibility === SHARED_VISIBILITY)) {
|
|
979
|
+
content.visibility = stored.visibility;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
948
982
|
const reindexed = await super.put(content);
|
|
949
983
|
noteMemoryUpsert(content);
|
|
950
984
|
noteWriteStamp(content?.embeddingModel); // embedding-space-guard slice 1 (see post())
|
|
@@ -1019,9 +1053,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
1019
1053
|
// `{...existing, ...patch}` payload, and must never have their stored
|
|
1020
1054
|
// visibility overwritten by a default recomputed from that merged content
|
|
1021
1055
|
// — only a genuinely NEW id gets the default stamped.
|
|
1056
|
+
// A lookup failure fails the write (it is not the same as "no record").
|
|
1022
1057
|
const preExisting = content.id
|
|
1023
|
-
? await databases.flair.Memory.get(content.id)
|
|
1058
|
+
? await databases.flair.Memory.get(content.id)
|
|
1024
1059
|
: null;
|
|
1060
|
+
// Preserve stored visibility on updates before applying write policy
|
|
1061
|
+
// (only the two writable values; the guards below see the result).
|
|
1062
|
+
if (preExisting &&
|
|
1063
|
+
(content.visibility === undefined || content.visibility === null) &&
|
|
1064
|
+
(preExisting.visibility === PRIVATE_VISIBILITY || preExisting.visibility === SHARED_VISIBILITY)) {
|
|
1065
|
+
content.visibility = preExisting.visibility;
|
|
1066
|
+
}
|
|
1025
1067
|
// ─── Default visibility (durability-keyed) — Layer 1, part A ────────────
|
|
1026
1068
|
// Explicit visibility on the write ALWAYS overrides; only stamp the
|
|
1027
1069
|
// default when the caller left it unset AND this is a fresh record.
|