Files
loki/scripts/test/account-export.ts
CatoandClaude Fable 5.1 9c84c929e4 feat(engines): your own key builds when you say so; welcome builds, then the plan's, then your own; capacity you can read (#1347)
* feat(settings): your own key builds, when you say so — a key marked for building reaches your private builder

Track 1, PR 6 of docs/architecture/private-builders.md.

- user_model_keys.for_building (migration 0123), off by default; one
  switch per key in Settings → AI, offered only on keys that can drive an
  agent CLI (config/build-engines.ts: Anthropic → ANTHROPIC_API_KEY for
  Claude Code, OpenAI → Codex, xAI → Grok, Google → Gemini CLI) and only
  to an account with a builder on the cloud.
- scripts/write-tenant-engines.ts (root on the box, from the reconcile
  timer) opens the marked keys with the app's sealing secret and writes
  them to /etc/loki/runners/<short>.env; a unit whose file changed is
  drain-restarted, so the key reaches its next agent without ending a
  session mid-task. No route ever returns an opened key.
- Records: changelog {#your-engine}; roadmap milestones ticked.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(settings): the building switch sits in one row with its sentence

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* feat(engines): welcome builds, then the plan's, then your own — and capacity you can read

Track 2 (2.1, 2.2, 2.5) and Track 4.1 of docs/master-plan-2026-10.md.

- users.build_engine (migration 0124): "own" by default — the person's
  sign-in or a key marked for building, never counted — or "loki": Loki's
  key within WELCOME_BUILDS (3, config/welcome-changes.ts) and the plan's
  PLAN_LIMITS.buildsMonthly (10 / 40 / 100). Every run records which
  engine paid for it (payload.engine); welcome and plan builds are counted
  from that marker. A dispatch past the last build is refused with the way
  forward (code engine-exhausted), and the kickoff screen shows it with
  one tap to Settings. Loki's welcome spending stops for everyone at
  WELCOME_MONTHLY_CAP_CHF (20), at CHF_PER_USD, a hand-set rate.
- The box writes Loki's key (LOKI_BUILD_ENGINE_ANTHROPIC_KEY from the
  app's env) into a tenant's unit only while they chose Loki's engine and
  have builds left; otherwise their own marked keys.
- Settings → AI: "Your engine for building", one Segmented choice with the
  numbers; /api/settings/build-engine. The kickoff's no-builder copy says
  the operator switches a private builder on per account.
- System → Capacity: how long work waited for a builder in the last day
  per channel (median, worst), this month's builds, tokens and cost per
  account, and welcome spend against its cap.
- /pricing and the whitepaper (0.3.3) state the builds a month on Loki's
  engine and the rule. Records: changelog {#welcome-changes}
  {#capacity-card}; roadmap milestones ticked.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* style(engines): format resolve.ts the way prettier wants it

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-20 12:55:35 +02:00

115 lines
3.9 KiB
TypeScript

// Data controls: the account export must never carry credential hashes, and the
// manifest must state exactly what it withheld.
//
// The projection is no longer this module's own deny-list — it is toExportUser,
// the same schema-exhaustive allow-list /api/me uses (scripts/test/user-client-view.ts
// is what keeps that list honest as the schema grows). What this file checks is
// the export-specific part: billing ids are dropped, everything else survives,
// and the manifest cannot claim an exclusion it did not make.
// Run: npx tsx scripts/test/account-export.ts
import { toExportUser, buildExportManifest, ACCOUNT_EXPORT_FILENAME } from "@/lib/account-export";
import {
USER_CLIENT_FIELDS,
USER_EXPORT_OMITTED_FIELDS,
USER_WITHHELD_FIELDS,
} from "@/lib/user-client-view";
import type { User } from "@/db/schema/users";
let pass = 0;
let fail = 0;
function ok(cond: boolean, label: string) {
if (cond) {
pass++;
} else {
fail++;
console.error(`✗ ${label}`);
}
}
const userRow = {
id: "u-1",
name: "G",
email: "g@example.com",
emailVerified: null,
image: null,
username: "g",
isDefault: false,
privateBuilder: false,
buildEngine: "own",
onboardedAt: null,
orangecatActorId: null,
plan: "pro",
planStatus: "active",
planExpiresAt: null,
privateZonePinSetAt: new Date("2026-01-01"),
fleetSettings: { a: 1 },
createdAt: new Date("2026-01-01"),
updatedAt: new Date("2026-01-02"),
passwordHash: "bcrypt$secret",
privateZonePinHash: "scrypt$pin",
} as unknown as User;
const exported = toExportUser(userRow) as Record<string, unknown>;
const serialized = JSON.stringify(exported);
// Secrets: withheld because they are secret, for every projection.
for (const field of Object.keys(USER_WITHHELD_FIELDS)) {
ok(!(field in exported), `${field} absent from export`);
}
ok(!serialized.includes("bcrypt$secret"), "serialized export does not contain the password hash");
ok(!serialized.includes("scrypt$pin"), "serialized export does not contain the PIN hash");
// Fields withheld from the export specifically.
for (const field of USER_EXPORT_OMITTED_FIELDS) {
ok(!(field in exported), `${field} omitted from export`);
}
// Everything else the owner may see must survive — an export that quietly drops
// data fails its purpose (right of access) as surely as one that leaks.
const omitted = new Set<string>(USER_EXPORT_OMITTED_FIELDS);
for (const field of USER_CLIENT_FIELDS) {
if (omitted.has(field)) continue;
ok(field in exported, `${field} present in export`);
}
ok(exported.email === "g@example.com", "email kept");
ok(exported.plan === "pro", "plan kept");
ok(JSON.stringify(exported.fleetSettings) === JSON.stringify({ a: 1 }), "fleetSettings kept");
ok(userRow.passwordHash === "bcrypt$secret", "input row not mutated");
// The manifest is generated from the same lists, so it cannot describe an
// exclusion that did not happen — assert the linkage, not a copy of the words.
const manifest = buildExportManifest("u-1", ["a", "b"]);
ok(manifest.user_id === "u-1", "manifest user_id");
ok(Array.isArray(manifest.scope) && manifest.scope.length === 2, "manifest scope");
for (const field of Object.keys(USER_WITHHELD_FIELDS)) {
ok(
manifest.excluded.some((e) => e.includes(field)),
`manifest names ${field} as excluded`,
);
}
for (const field of USER_EXPORT_OMITTED_FIELDS) {
ok(
manifest.excluded.some((e) => e.includes(field)),
`manifest names ${field} as excluded`,
);
}
ok(
manifest.excluded.every((line) =>
line
.split(":")
.slice(1)
.join(":")
.split(",")
.map((f) => f.trim())
.every((f) => !f || !(f in exported)),
),
"every field the manifest claims to exclude really is absent",
);
ok(ACCOUNT_EXPORT_FILENAME.endsWith(".json"), "filename is json");
if (fail > 0) {
console.error(`account-export: ${fail} failed, ${pass} passed`);
process.exit(1);
}
console.log(`account-export: ${pass} checks passed`);