@tpsdev-ai/flair 0.63.0 → 0.63.1
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 +8 -7
- package/SECURITY.md +55 -33
- package/dist/bridges/runtime/import-runner.js +4 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +243 -83
- package/dist/commands/agent.js +298 -72
- package/dist/commands/attention.js +2 -0
- package/dist/commands/bootstrap.js +2 -0
- package/dist/commands/bridge.js +10 -0
- package/dist/commands/doctor.js +87 -42
- package/dist/commands/export.js +141 -11
- package/dist/commands/import.js +36 -15
- package/dist/commands/init.js +373 -157
- package/dist/commands/keys.js +12 -8
- package/dist/commands/mcp.js +146 -62
- package/dist/commands/memory.js +5 -2
- package/dist/commands/migrate-harness-memory.js +9 -3
- package/dist/commands/principal.js +19 -14
- package/dist/commands/quality.js +23 -3
- package/dist/commands/reembed.js +468 -111
- package/dist/commands/search.js +2 -0
- package/dist/commands/service.js +25 -0
- package/dist/commands/status.js +130 -107
- package/dist/doctor-client.js +2 -23
- package/dist/federation/scheduler.js +148 -12
- package/dist/keystore.js +77 -10
- package/dist/lib/agent-key-file.js +509 -0
- package/dist/lib/agent-rotation-lock.js +249 -0
- package/dist/lib/atomic-write.js +2 -2
- package/dist/lib/auth-resolve.js +14 -14
- package/dist/lib/key-dir.js +203 -0
- package/dist/lib/launchd-management.js +7 -3
- package/dist/lib/local-instance-pair.js +8 -1
- package/dist/lib/node-alias-path.js +50 -2
- package/dist/lib/remote-admin-pass.js +157 -0
- package/dist/lib/scheduler-platform.js +13 -0
- package/dist/lib/service-repoint.js +13 -4
- package/dist/lib/skill-seed.js +35 -3
- package/dist/lib/terminal-text.js +32 -0
- package/dist/mcp-client-assertion.js +5 -4
- package/dist/resources/Memory.js +47 -3
- package/dist/resources/health.js +39 -22
- package/dist/resources/in-process-api.js +74 -11
- package/dist/resources/mcp-client-metadata-fields.js +4 -0
- package/dist/resources/mcp-handler.js +40 -1
- package/dist/resources/mcp-oauth.js +17 -1
- package/dist/resources/mcp-tool-scopes.js +69 -0
- package/dist/resources/mcp-tools.js +10 -0
- package/dist/resources/skill-version-write.js +16 -0
- package/dist/src/keystore.js +77 -10
- package/dist/src/lib/atomic-write.js +2 -2
- package/dist/src/lib/key-dir.js +203 -0
- package/dist/src/lib/scheduler-platform.js +13 -0
- package/docs/access-control.md +21 -12
- package/docs/api-reference.md +35 -24
- package/docs/auth.md +31 -22
- package/docs/deploying-on-fabric.md +10 -2
- package/docs/embedding-in-a-harper-app.md +7 -7
- package/docs/entity-vocabulary.md +4 -5
- package/docs/hosted-on-fabric.md +1 -1
- package/docs/secrets-and-keys.md +8 -13
- package/docs/upgrade.md +15 -5
- package/package.json +1 -1
package/dist/commands/doctor.js
CHANGED
|
@@ -8,7 +8,7 @@ import { ALL_CLIENTS, decideCodexPinOnly, decideJsonPinOnly, detectClients, wire
|
|
|
8
8
|
import { checkGlobalBinOnPath, resolveNpmGlobalPrefix } from "../install/global-bin-path.js";
|
|
9
9
|
import { buildEd25519Auth, defaultAdminPassPath, defaultKeysDir, requestTarget, requestUrl, resolveAdminUser, resolveKeyPath, resolveLocalAdminPass } from "../lib/auth-resolve.js";
|
|
10
10
|
import { proveLocalHarperListener } from "../lib/local-instance-pair.js";
|
|
11
|
-
import { AGENT_ID_RULE } from "../lib/agent-id-rule.js";
|
|
11
|
+
import { AGENT_ID_RULE, isValidAgentId } from "../lib/agent-id-rule.js";
|
|
12
12
|
import { agentHomeEndpoint, readAgentHomeRows, resolveTargetInstanceIdentity } from "../lib/agent-home.js";
|
|
13
13
|
import { describeInstructionEventImpostors, readInstructionEventTables } from "../lib/instruction-event-doctor.js";
|
|
14
14
|
import { describeLiveSkillTombstones, readSkillTombstoneTables } from "../lib/skill-tombstone-doctor.js";
|
|
@@ -22,6 +22,7 @@ import { describeEmbedGpuDoctorFinding } from "../lib/embed-gpu-doctor.js";
|
|
|
22
22
|
import { describeEmbeddingSpaceDoctorFinding } from "../lib/embedding-space-doctor.js";
|
|
23
23
|
import { adminPassDesyncFinding, detectPersistedAdminUser } from "../lib/init-admin-pass.js";
|
|
24
24
|
import { opsApiBindFinding } from "../lib/ops-api-bind.js";
|
|
25
|
+
import { agentKeyPath, formatKeyModeFinding, keyModesUnsupported, KEY_MODES_UNSUPPORTED_MESSAGE, scanAgentKeyModes, scanKeyDir, sameKeyDir } from "../lib/key-dir.js";
|
|
25
26
|
import { instanceIdentityLines, probeInstanceIdentity, } from "../lib/instance-identity-row.js";
|
|
26
27
|
import { flairCliVersion, unpinnedSpecWarning } from "../lib/mcp-spec.js";
|
|
27
28
|
import { discriminateMcpOAuthDiscovery, reportMcpOAuthDiscovery } from "../lib/mcp-enable.js";
|
|
@@ -313,8 +314,8 @@ export function renderEmbeddingSpaceDoctorFinding(embeddingSpace, write = (line)
|
|
|
313
314
|
* - `--fix` counts the divergence FIXED only after the unit was re-pointed,
|
|
314
315
|
* the instance restarted, and the serving tree re-proven to be this CLI's —
|
|
315
316
|
* "nothing to rewrite" or a failed restart is never a fix;
|
|
316
|
-
* - a federation-sync shim
|
|
317
|
-
*
|
|
317
|
+
* - a federation-sync shim the dry run would re-point is one issue, fixed
|
|
318
|
+
* only when re-pointed AND re-read as current or as a node pin.
|
|
318
319
|
*
|
|
319
320
|
* Extracted from the action (like renderEmbedGpuDoctorFinding) so the counting
|
|
320
321
|
* is exercised directly; the action passes the real adapters.
|
|
@@ -402,14 +403,15 @@ export async function runInstallTreeDoctorSection(mode, deps, write = (line) =>
|
|
|
402
403
|
break;
|
|
403
404
|
case "would-rewrite": {
|
|
404
405
|
issues++;
|
|
405
|
-
write(` ${bad} the federation-sync shim
|
|
406
|
+
write(` ${bad} the federation-sync shim would be re-pointed — ${f.detail}`);
|
|
406
407
|
if (mode.autoFix && mode.dryRun) {
|
|
407
408
|
write(` ${info} ${render.wrap(render.c.dim, "[dry-run] would re-point the shim's exec line (the scheduler unit is not rewritten)")}`);
|
|
408
409
|
}
|
|
409
410
|
else if (mode.autoFix) {
|
|
410
411
|
const r = deps.rewriteFederation(false);
|
|
411
412
|
const verify = r.status === "rewritten" ? deps.rewriteFederation(true) : null;
|
|
412
|
-
|
|
413
|
+
// A re-pointed Homebrew Cellar node that is not this CLI's node re-reads as a pin (flair#3056).
|
|
414
|
+
if (verify?.status === "current" || verify?.status === "pinned-node") {
|
|
413
415
|
fixed++;
|
|
414
416
|
write(` ${ok} ${r.detail}`);
|
|
415
417
|
}
|
|
@@ -456,6 +458,16 @@ export function register(program) {
|
|
|
456
458
|
.option("--dry-run", "Show what --fix would do without making changes")
|
|
457
459
|
.action(async (opts) => {
|
|
458
460
|
signedOnlyTransport = false; // flair#2526: decided per run, below
|
|
461
|
+
const namedAgentId = opts.agent ?? (process.env.FLAIR_AGENT_ID || undefined);
|
|
462
|
+
if (namedAgentId !== undefined) {
|
|
463
|
+
try {
|
|
464
|
+
agentKeyPath(defaultKeysDir(), namedAgentId);
|
|
465
|
+
}
|
|
466
|
+
catch (err) {
|
|
467
|
+
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
468
|
+
process.exit(1);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
459
471
|
const port = resolveHttpPort(opts);
|
|
460
472
|
const autoFix = opts.fix ?? false;
|
|
461
473
|
const dryRun = opts.dryRun ?? false;
|
|
@@ -852,46 +864,59 @@ export function register(program) {
|
|
|
852
864
|
}
|
|
853
865
|
// 2. Keys directory
|
|
854
866
|
const keysDir = defaultKeysDir();
|
|
867
|
+
let keysDirUnreadable = false;
|
|
868
|
+
if (keyModesUnsupported()) {
|
|
869
|
+
console.log(` ${render.icons.info} ${render.wrap(render.c.dim, KEY_MODES_UNSUPPORTED_MESSAGE)}`);
|
|
870
|
+
}
|
|
855
871
|
if (existsSync(keysDir)) {
|
|
856
|
-
const
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
// inferred as, an agent. Partition them out here so every downstream
|
|
861
|
-
// consumer of keyAgentIds (registration checks, --fix inference,
|
|
862
|
-
// fixCommandAgentHint) is node-free by construction.
|
|
863
|
-
const partitioned = partitionKeyIds(keyFiles.map((f) => f.replace(/\.key$/, "")), keysDir);
|
|
864
|
-
keyAgentIds = partitioned.agentKeyIds;
|
|
865
|
-
nodeKeyIds = partitioned.nodeKeyIds;
|
|
866
|
-
if (keyAgentIds.length > 0) {
|
|
867
|
-
console.log(` ${render.icons.ok} Keys found: ${render.wrap(render.c.bold, String(keyAgentIds.length))} agent(s) in ${render.wrap(render.c.dim, keysDir)}`);
|
|
868
|
-
if (partitioned.nodeKeyIds.length > 0) {
|
|
869
|
-
console.log(` ${render.icons.info} ${render.wrap(render.c.dim, `${partitioned.nodeKeyIds.length} node-scoped federation key(s) present — not agent signing keys; skipping`)}`);
|
|
870
|
-
}
|
|
871
|
-
}
|
|
872
|
-
else if (partitioned.nodeKeyIds.length > 0) {
|
|
873
|
-
// Node keys but no agent key: functionally there is no agent identity
|
|
874
|
-
// here. Report it plainly (not the old DECODER false alarm) and point
|
|
875
|
-
// at the real remedy. Kept a warn — not an issues++ — so a genuine
|
|
876
|
-
// federation-only host doesn't newly fail doctor's exit code.
|
|
877
|
-
console.log(` ${render.icons.warn} No agent signing key found — only ${render.wrap(render.c.bold, String(nodeKeyIds.length))} node-scoped federation key(s) in ${render.wrap(render.c.dim, keysDir)}`);
|
|
878
|
-
console.log(` ${render.wrap(render.c.dim, "These are Fabric node keys, not agent identities. Fix:")} flair init --agent-id <your-agent>`);
|
|
879
|
-
}
|
|
880
|
-
else {
|
|
881
|
-
console.log(` ${render.icons.error} Keys directory exists but no .key files found`);
|
|
882
|
-
console.log(` ${render.wrap(render.c.dim, "Fix:")} flair init --agent-id <your-agent>`);
|
|
872
|
+
const keyScan = scanKeyDir(keysDir);
|
|
873
|
+
if (keyScan.state === "unreadable") {
|
|
874
|
+
// A keys directory doctor cannot read is not a clean result.
|
|
875
|
+
keysDirUnreadable = true;
|
|
883
876
|
issues++;
|
|
877
|
+
console.log(` ${render.icons.warn} Keys directory could not be read: ${render.wrap(render.c.dim, keysDir)} — key checks skipped`);
|
|
884
878
|
}
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
879
|
+
else {
|
|
880
|
+
const keyFiles = keyScan.entries.filter((e) => e.kind === "key").map((e) => e.name);
|
|
881
|
+
// ~/.flair/keys is shared by agent Ed25519 signing keys and node-scoped
|
|
882
|
+
// federation keys (flair#1193). Partition by file name (see
|
|
883
|
+
// partitionKeyIds): downstream consumers of keyAgentIds (registration
|
|
884
|
+
// checks, --fix inference, fixCommandAgentHint) skip ids classified as
|
|
885
|
+
// node keys. A node-shaped id with a sibling `.pub` is classified as an
|
|
886
|
+
// agent key.
|
|
887
|
+
const partitioned = partitionKeyIds(keyFiles.map((f) => f.replace(/\.key$/, "")), keysDir);
|
|
888
|
+
keyAgentIds = partitioned.agentKeyIds.filter((id) => isValidAgentId(id));
|
|
889
|
+
nodeKeyIds = partitioned.nodeKeyIds;
|
|
890
|
+
if (keyAgentIds.length > 0) {
|
|
891
|
+
console.log(` ${render.icons.ok} Keys found: ${render.wrap(render.c.bold, String(keyAgentIds.length))} agent(s) in ${render.wrap(render.c.dim, keysDir)}`);
|
|
892
|
+
if (partitioned.nodeKeyIds.length > 0) {
|
|
893
|
+
console.log(` ${render.icons.info} ${render.wrap(render.c.dim, `${partitioned.nodeKeyIds.length} node-scoped federation key(s) present — not agent signing keys; skipping`)}`);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
else if (partitioned.nodeKeyIds.length > 0) {
|
|
897
|
+
// Node keys but no agent key: functionally there is no agent identity
|
|
898
|
+
// here. Report it plainly (not the old DECODER false alarm) and point
|
|
899
|
+
// at the real remedy. Kept a warn — not an issues++ — so a genuine
|
|
900
|
+
// federation-only host doesn't newly fail doctor's exit code.
|
|
901
|
+
console.log(` ${render.icons.warn} No agent signing key found — only ${render.wrap(render.c.bold, String(nodeKeyIds.length))} node-scoped federation key(s) in ${render.wrap(render.c.dim, keysDir)}`);
|
|
902
|
+
console.log(` ${render.wrap(render.c.dim, "These are Fabric node keys, not agent identities. Fix:")} flair init --agent-id <your-agent>`);
|
|
888
903
|
}
|
|
889
904
|
else {
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
905
|
+
console.log(` ${render.icons.error} Keys directory exists but no .key files found`);
|
|
906
|
+
console.log(` ${render.wrap(render.c.dim, "Fix:")} flair init --agent-id <your-agent>`);
|
|
907
|
+
issues++;
|
|
908
|
+
}
|
|
909
|
+
if (nodeKeyIds.length > 0 && harperResponding) {
|
|
910
|
+
if (pairNotRun) {
|
|
911
|
+
reportPairNotRun("Node key instance check");
|
|
912
|
+
}
|
|
913
|
+
else {
|
|
914
|
+
const advisory = await readNodeSeedAdvisory({
|
|
915
|
+
nodeKeyIds, keysDir, baseUrl, port: opts.port, resolveHttpPort, resolveOpsPort,
|
|
916
|
+
});
|
|
917
|
+
if (advisory)
|
|
918
|
+
console.log(` ${render.icons.info} ${advisory}`);
|
|
919
|
+
}
|
|
895
920
|
}
|
|
896
921
|
}
|
|
897
922
|
}
|
|
@@ -900,6 +925,22 @@ export function register(program) {
|
|
|
900
925
|
console.log(` ${render.wrap(render.c.dim, "Fix:")} flair init --agent-id <your-agent>`);
|
|
901
926
|
issues++;
|
|
902
927
|
}
|
|
928
|
+
// Agent key files must be owner-only on POSIX (flair#3077). Read-only:
|
|
929
|
+
// this never changes a file. It covers the standard `resolveKeyPath` locations,
|
|
930
|
+
// not only the default keys directory.
|
|
931
|
+
if (!keyModesUnsupported()) {
|
|
932
|
+
const modeScan = scanAgentKeyModes();
|
|
933
|
+
for (const { dir, code } of modeScan.unreadable) {
|
|
934
|
+
if (keysDirUnreadable && sameKeyDir(dir, keysDir))
|
|
935
|
+
continue;
|
|
936
|
+
issues++;
|
|
937
|
+
console.log(` ${render.icons.warn} agent key directory ${render.wrap(render.c.dim, dir)} could not be read (${code}) — key file modes not checked`);
|
|
938
|
+
}
|
|
939
|
+
for (const finding of modeScan.findings) {
|
|
940
|
+
issues++;
|
|
941
|
+
console.log(` ${render.icons.warn} ${render.wrap(render.c.yellow, formatKeyModeFinding(finding))}`);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
903
944
|
// 3. Config file (flair#1514) — same resolution Harper uses: cwd, then
|
|
904
945
|
// the component/package dir, then ~/.flair. Looking only at
|
|
905
946
|
// ~/.flair/config.yaml printed "using defaults" on wrapper-launched
|
|
@@ -2264,7 +2305,7 @@ export function register(program) {
|
|
|
2264
2305
|
const registered = renderAgentGateHeader(gate);
|
|
2265
2306
|
if (!registered)
|
|
2266
2307
|
continue;
|
|
2267
|
-
const keyPath = resolveKeyPath(gate.id) ??
|
|
2308
|
+
const keyPath = resolveKeyPath(gate.id) ?? agentKeyPath(defaultKeysDir(), gate.id);
|
|
2268
2309
|
const headers = { Authorization: buildEd25519Auth(gate.id, "GET", requestTarget(presenceUrl), keyPath) };
|
|
2269
2310
|
await fetchAndRenderFleetPresence(headers, true, " ");
|
|
2270
2311
|
}
|
|
@@ -2513,7 +2554,7 @@ export function register(program) {
|
|
|
2513
2554
|
const passedGates = agentGates.filter((g) => describeAgentGateFinding(g.id, g.state, g.detail, { instanceReachable: harperResponding }) === null);
|
|
2514
2555
|
for (const gate of passedGates) {
|
|
2515
2556
|
renderAgentGateHeader(gate);
|
|
2516
|
-
const keyPath = resolveKeyPath(gate.id) ??
|
|
2557
|
+
const keyPath = resolveKeyPath(gate.id) ?? agentKeyPath(defaultKeysDir(), gate.id);
|
|
2517
2558
|
const headers = { Authorization: buildEd25519Auth(gate.id, "GET", requestTarget(healthDetailUrl), keyPath) };
|
|
2518
2559
|
issues += await fetchAndRenderMigrations(healthDetailUrl, headers, " ");
|
|
2519
2560
|
}
|
|
@@ -2607,6 +2648,9 @@ export function register(program) {
|
|
|
2607
2648
|
const lastExit = d.status.installed && d.status.active === true
|
|
2608
2649
|
? queryLastExitStatus({ plat: d.status.platform, darwinTarget: d.darwinTarget, linuxServiceUnit: d.linuxServiceUnit })
|
|
2609
2650
|
: null;
|
|
2651
|
+
// flair#3056: set when the unit file names the flair-generated shim as
|
|
2652
|
+
// its program and the node path on the shim's exec line does not exist.
|
|
2653
|
+
const shimMissingNode = d.kind === "federation" && d.status.installed ? fedSched.inspectFederationShimNode() : null;
|
|
2610
2654
|
const facts = {
|
|
2611
2655
|
label: d.label,
|
|
2612
2656
|
enableCommand: d.enableCommand,
|
|
@@ -2614,6 +2658,7 @@ export function register(program) {
|
|
|
2614
2658
|
installed: d.status.installed,
|
|
2615
2659
|
active: d.status.active,
|
|
2616
2660
|
lastExit,
|
|
2661
|
+
shimMissingNode,
|
|
2617
2662
|
stderrLogPath: d.stderrLogPath,
|
|
2618
2663
|
};
|
|
2619
2664
|
const finding = d.kind === "federation"
|
package/dist/commands/export.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { defaultKeysDir, resolveAdminUser, addAdminPassOptions } from "../lib/auth-resolve.js";
|
|
2
2
|
import * as render from "../render.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { closeSync, constants as fsConstants, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { writeFilesAtomically } from "../lib/atomic-write.js";
|
|
6
|
+
import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
|
|
7
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
5
8
|
import { resolveHome } from "../lib/home.js";
|
|
6
9
|
import { encodeRecordId } from "../lib/record-id-path.js";
|
|
7
10
|
let cli;
|
|
@@ -19,6 +22,96 @@ const AGENT_REQUIRED_FIELDS = ["id", "name", "publicKey", "createdAt"];
|
|
|
19
22
|
const MEMORY_REQUIRED_FIELDS = ["id", "agentId", "content", "createdAt"];
|
|
20
23
|
const SOUL_REQUIRED_FIELDS = ["id", "agentId", "key", "value", "createdAt"];
|
|
21
24
|
const GRANT_REQUIRED_FIELDS = ["id", "ownerId", "granteeId", "scope"];
|
|
25
|
+
export function exportFileMode(outputPath, platform = process.platform) {
|
|
26
|
+
return platform === "win32" ? "mode bits are not enforced on Windows" : (statSync(outputPath).mode & 0o7777).toString(8);
|
|
27
|
+
}
|
|
28
|
+
/** The default export path for `agentId` inside `exportsDir`, or null when the
|
|
29
|
+
* resolved path is not a direct child of the resolved exports directory. */
|
|
30
|
+
export function defaultExportOutputPath(exportsDir, agentId, now = Date.now()) {
|
|
31
|
+
const dir = resolve(exportsDir);
|
|
32
|
+
const candidate = resolve(dir, `${agentId}-${now}.json`);
|
|
33
|
+
return dirname(candidate) === dir ? candidate : null;
|
|
34
|
+
}
|
|
35
|
+
/** The clock the default export name reads. `FLAIR_TEST_EXPORT_CLOCK_MS` fixes
|
|
36
|
+
* it so a test can plant a path at the exact default name. */
|
|
37
|
+
function defaultExportClockMs() {
|
|
38
|
+
const raw = process.env.FLAIR_TEST_EXPORT_CLOCK_MS;
|
|
39
|
+
const parsed = raw === undefined ? NaN : Number(raw);
|
|
40
|
+
return Number.isFinite(parsed) ? parsed : Date.now();
|
|
41
|
+
}
|
|
42
|
+
/** The file operations `writeDefaultExport` performs. A test replaces a member
|
|
43
|
+
* to inject a failure through the module seam. */
|
|
44
|
+
export const defaultExportWriteOps = {
|
|
45
|
+
openTemp: (tempPath, mode) => openSync(tempPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0), mode),
|
|
46
|
+
write: (fd, content) => { writeFileSync(fd, content); },
|
|
47
|
+
fsync: (fd) => { fsyncSync(fd); },
|
|
48
|
+
close: (fd) => { closeSync(fd); },
|
|
49
|
+
link: (tempPath, outputPath) => { linkSync(tempPath, outputPath); },
|
|
50
|
+
unlink: (path) => { unlinkSync(path); },
|
|
51
|
+
};
|
|
52
|
+
/** Report a temp file this call could not remove. */
|
|
53
|
+
function removeExportTemp(tempPath) {
|
|
54
|
+
try {
|
|
55
|
+
defaultExportWriteOps.unlink(tempPath);
|
|
56
|
+
}
|
|
57
|
+
catch (cleanupErr) {
|
|
58
|
+
console.error(`Error: failed to remove the temporary export at ${tempPath}: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** With no concurrent changes to directory entries by another writer, write
|
|
62
|
+
* `content` to a complete temp file in the same directory and link it to
|
|
63
|
+
* `outputPath`. An existing path — file, symlink or anything else — is refused
|
|
64
|
+
* and survives. A failed write, fsync, close or link attempts to remove only this
|
|
65
|
+
* call's temp; a failed removal is reported with its path. */
|
|
66
|
+
function writeDefaultExport(outputPath, content, mode) {
|
|
67
|
+
const name = basename(outputPath);
|
|
68
|
+
let tempPath = "";
|
|
69
|
+
let fd;
|
|
70
|
+
for (let attempt = 0; attempt < 5 && fd === undefined; attempt += 1) {
|
|
71
|
+
const candidate = join(dirname(outputPath), `.${name}.tmp-${randomBytes(8).toString("hex")}`);
|
|
72
|
+
try {
|
|
73
|
+
fd = defaultExportWriteOps.openTemp(candidate, mode);
|
|
74
|
+
tempPath = candidate;
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
if (err.code !== "EEXIST" || attempt === 4)
|
|
78
|
+
throw err;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (fd === undefined)
|
|
82
|
+
throw new Error(`could not create a temporary export beside ${outputPath}`);
|
|
83
|
+
try {
|
|
84
|
+
defaultExportWriteOps.write(fd, content);
|
|
85
|
+
defaultExportWriteOps.fsync(fd);
|
|
86
|
+
const owned = fd;
|
|
87
|
+
fd = undefined;
|
|
88
|
+
defaultExportWriteOps.close(owned);
|
|
89
|
+
try {
|
|
90
|
+
defaultExportWriteOps.link(tempPath, outputPath);
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
if (err.code === "EEXIST") {
|
|
94
|
+
removeExportTemp(tempPath);
|
|
95
|
+
console.error(`Error: refusing to write to existing path ${outputPath}`);
|
|
96
|
+
process.exit(1);
|
|
97
|
+
}
|
|
98
|
+
throw err;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
if (fd !== undefined) {
|
|
103
|
+
try {
|
|
104
|
+
defaultExportWriteOps.close(fd);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// The original write or fsync failure is what this call reports.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
removeExportTemp(tempPath);
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
removeExportTemp(tempPath);
|
|
114
|
+
}
|
|
22
115
|
function hasRequiredStringFields(value, fields) {
|
|
23
116
|
return !!value
|
|
24
117
|
&& typeof value === "object"
|
|
@@ -37,6 +130,11 @@ export function register(program) {
|
|
|
37
130
|
.option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
|
|
38
131
|
.option("--keys-dir <dir>", "Keys directory", defaultKeysDir())
|
|
39
132
|
.action(async (agentId, opts) => {
|
|
133
|
+
// flair#3136 — the ONE agent-ID rule, before this action reads export data or a key or writes its file.
|
|
134
|
+
if (!isValidAgentId(agentId)) {
|
|
135
|
+
console.error(`Error: ${invalidAgentIdMessage(agentId)}`);
|
|
136
|
+
process.exit(1);
|
|
137
|
+
}
|
|
40
138
|
const baseUrl = opts.url ?? `http://127.0.0.1:${resolveHttpPort(opts)}`;
|
|
41
139
|
const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
|
|
42
140
|
if (!adminPass) {
|
|
@@ -122,14 +220,46 @@ export function register(program) {
|
|
|
122
220
|
grants,
|
|
123
221
|
...(privateKey ? { privateKey } : {}),
|
|
124
222
|
};
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
223
|
+
let outputPath;
|
|
224
|
+
let wroteDefault = false;
|
|
225
|
+
if (opts.output !== undefined) {
|
|
226
|
+
outputPath = resolve(opts.output);
|
|
227
|
+
mkdirSync(dirname(outputPath), { recursive: true });
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
const home = resolveHome();
|
|
231
|
+
const exportsDir = join(home, ".flair", "exports");
|
|
232
|
+
const lexicalPath = defaultExportOutputPath(exportsDir, agentId, defaultExportClockMs());
|
|
233
|
+
if (lexicalPath === null) {
|
|
234
|
+
console.error(`Error: refusing to write agent '${agentId}' outside the exports directory ${resolve(exportsDir)}`);
|
|
235
|
+
process.exit(1);
|
|
236
|
+
}
|
|
237
|
+
mkdirSync(dirname(lexicalPath), { recursive: true });
|
|
238
|
+
// The exports directory must be the one under the REAL home. Checked once,
|
|
239
|
+
// after the directory exists and before any temp file is created; a
|
|
240
|
+
// concurrent replacement of .flair or exports between this check and the
|
|
241
|
+
// write is not prevented: the Node filesystem API used here has no directory-relative
|
|
242
|
+
// create or link anchored to a held directory descriptor.
|
|
243
|
+
const resolvedExports = realpathSync(exportsDir);
|
|
244
|
+
if (resolvedExports !== join(realpathSync(home), ".flair", "exports")) {
|
|
245
|
+
console.error(`Error: refusing to write agent '${agentId}' outside the exports directory ${resolve(exportsDir)}`);
|
|
246
|
+
process.exit(1);
|
|
247
|
+
}
|
|
248
|
+
outputPath = join(resolvedExports, basename(lexicalPath));
|
|
249
|
+
wroteDefault = true;
|
|
250
|
+
}
|
|
251
|
+
const fileMode = opts.includeKey ? 0o600 : 0o644;
|
|
252
|
+
const content = JSON.stringify(exportData, null, 2);
|
|
253
|
+
if (wroteDefault) {
|
|
254
|
+
writeDefaultExport(outputPath, content, fileMode);
|
|
255
|
+
}
|
|
256
|
+
else if (opts.includeKey) {
|
|
257
|
+
// Stage at 0600 to avoid retaining an existing output file's wider mode.
|
|
258
|
+
writeFilesAtomically([{ path: outputPath, content, mode: 0o600 }]);
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
writeFileSync(outputPath, content, { mode: fileMode });
|
|
262
|
+
}
|
|
133
263
|
console.log(`\n${render.icons.ok} ${render.wrap(render.c.green, `Agent '${agentId}' exported`)}`);
|
|
134
264
|
console.log(render.kv("Memories", render.wrap(render.c.bold, String(memories.length))));
|
|
135
265
|
console.log(render.kv("Souls", render.wrap(render.c.bold, String(souls.length))));
|
|
@@ -138,7 +268,7 @@ export function register(program) {
|
|
|
138
268
|
? `${render.wrap(render.c.magenta, "included")} ${render.wrap(render.c.red, "(UNENCRYPTED — protect this file)")}`
|
|
139
269
|
: render.wrap(render.c.dim, "not included");
|
|
140
270
|
console.log(render.kv("Key", keyText));
|
|
141
|
-
console.log(render.kv("Mode",
|
|
271
|
+
console.log(render.kv("Mode", exportFileMode(outputPath)));
|
|
142
272
|
console.log(render.kv("Output", render.wrap(render.c.dim, outputPath)));
|
|
143
273
|
});
|
|
144
274
|
}
|
package/dist/commands/import.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { addAdminPassOptions, ApiHttpError, ApiRequestOutcomeUnknown, apiErrorRawBody, defaultKeysDir, isLocalBase, resolveAdminUser, sendJsonRequest, } from "../lib/auth-resolve.js";
|
|
2
2
|
import { encodeRecordId } from "../lib/record-id-path.js";
|
|
3
|
+
import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
|
|
3
4
|
import { SOUL_SCOPE_FIELDS_REFUSAL, suppliesSoulScopeFields } from "../lib/soul-scope-fields.js";
|
|
4
5
|
import * as render from "../render.js";
|
|
5
|
-
import {
|
|
6
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
+
import { ensureAgentKeysDir, readOrCreateAgentKey } from "../lib/agent-key-file.js";
|
|
6
8
|
import nacl from "tweetnacl";
|
|
7
9
|
/** The fixed error names Flair's write guards return for a Soul or Memory
|
|
8
10
|
* write. A response body's `error` is displayed only when it is one of these;
|
|
@@ -150,33 +152,52 @@ export function register(program) {
|
|
|
150
152
|
process.exit(1);
|
|
151
153
|
}
|
|
152
154
|
const agentId = data.agent?.id;
|
|
153
|
-
|
|
155
|
+
// Only a missing agent.id (absent or null) means "no agent ID in export".
|
|
156
|
+
// A supplied string, including the empty string, goes through the shared
|
|
157
|
+
// rule below; a supplied non-string is refused just below.
|
|
158
|
+
if (agentId === undefined || agentId === null) {
|
|
154
159
|
console.error("Error: no agent ID in export");
|
|
155
160
|
process.exit(1);
|
|
156
161
|
}
|
|
162
|
+
// A present non-string id is refused before the shared rule: String(0) or
|
|
163
|
+
// String(123) would itself match the rule, so the shared message would
|
|
164
|
+
// wrongly say the id violates it. A type message states the actual refusal.
|
|
165
|
+
if (typeof agentId !== "string") {
|
|
166
|
+
console.error(`Error: agent id in export must be a string (got ${typeof agentId})`);
|
|
167
|
+
process.exit(1);
|
|
168
|
+
}
|
|
169
|
+
// flair#2359 — the ONE agent-ID rule, before the keys directory is created
|
|
170
|
+
// or any key file is written, and before any `fetch` call made by the command action.
|
|
171
|
+
if (!isValidAgentId(agentId)) {
|
|
172
|
+
console.error(`Error: ${invalidAgentIdMessage(agentId)}`);
|
|
173
|
+
process.exit(1);
|
|
174
|
+
}
|
|
157
175
|
console.log(`Importing agent '${agentId}'...`);
|
|
158
176
|
// Register agent (generates new key if export doesn't include one)
|
|
159
177
|
const keysDir = opts.keysDir ?? defaultKeysDir();
|
|
160
|
-
mkdirSync(keysDir, { recursive: true });
|
|
161
178
|
const privPath = privKeyPath(agentId, keysDir);
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
179
|
+
let keyFile;
|
|
180
|
+
try {
|
|
181
|
+
ensureAgentKeysDir(keysDir);
|
|
182
|
+
keyFile = readOrCreateAgentKey(privPath, () => {
|
|
183
|
+
if (data.privateKey)
|
|
184
|
+
return data.privateKey;
|
|
185
|
+
const kp = nacl.sign.keyPair();
|
|
186
|
+
return Buffer.from(kp.secretKey.slice(0, 32));
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
191
|
+
process.exit(1);
|
|
167
192
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const kp = nacl.sign.keyPair();
|
|
171
|
-
writeFileSync(privPath, Buffer.from(kp.secretKey.slice(0, 32)));
|
|
172
|
-
chmodSync(privPath, 0o600);
|
|
173
|
-
console.log(` New key generated: ${privPath}`);
|
|
193
|
+
if (keyFile.created) {
|
|
194
|
+
console.log(data.privateKey ? ` Key restored: ${privPath}` : ` New key generated: ${privPath}`);
|
|
174
195
|
}
|
|
175
196
|
else {
|
|
176
197
|
console.log(` Using existing key: ${privPath}`);
|
|
177
198
|
}
|
|
178
199
|
// Read public key for registration
|
|
179
|
-
const seed =
|
|
200
|
+
const seed = Buffer.from(keyFile.bytes);
|
|
180
201
|
const decodedSeed = seed.length === 32 ? seed : Buffer.from(seed.toString("utf-8").trim(), "base64");
|
|
181
202
|
const pubKey = decodedSeed.length === 32
|
|
182
203
|
? nacl.sign.keyPair.fromSeed(new Uint8Array(decodedSeed)).publicKey
|