security: harden credentials app after the 2026-10-27 dev2 incident (CLI 0.10.0)

An attacker with root on dev2 read identity.json (identity secret key + a user
lsk_ token) and used the token against app.logicsrc.com. This closes the gaps
that made that worse than it had to be, and adds the tools to recover.

Identity keys
- A registered identity public key is never replaced by a login any more
  ("last login wins" let a stolen token swap in an attacker key). Changing it
  needs `logicsrc teams rotate-identity`: the server seals a random answer to
  the CURRENT key (single use, 5 min); the CLI proves possession and re-seals
  every vault grant to the new key in one transaction (POST /keys/rotate).
- Lost key: reset from a signed-in browser (Settings), which drops every grant
  sealed to the old key. `logicsrc teams key --import` moves a key to a new box.

Vault re-key
- `logicsrc teams rekey <team> <project> <env>` and `--all`: new vault key,
  values re-encrypted client side, re-sealed to every current member and
  machine key. Server bumps credshare_vaults.key_version; writes that name a
  retired version get 409, and the rekey UPDATE only touches rows whose value
  did not change mid-flight. A verify pass (per vault and a final sweep)
  re-seals any value a racing older client wrote under the retired key.

Key pinning (TOFU)
- CLI pins teammates' and machine keys' fingerprints in known-keys.json (0600)
  and refuses to seal (grant, rekey) to a changed key without
  --accept-key-change. `teams members` shows fingerprints and pin status;
  the dashboard shows fingerprints and public/pins.js flags changes.

Audit
- Every person read of a vault key (/grant) and of ciphertext (/secrets) is
  audited with IP and user agent (also denied reads and identity events).
  GET /teams/:slug/audit, `logicsrc teams audit`, and tables on the dashboard
  and vault pages.

At rest / transport
- Session tokens stored as sha256 (rows hashed in migration 007); CLI auth
  codes hashed. New API keys no longer travel in the /settings URL.
- CSP (script-src 'self', no inline script or handlers, frame-ancestors none),
  HSTS, X-Frame-Options, Referrer-Policy no-referrer, COOP/CORP, no-store on
  authenticated pages. Inline scripts moved to /app.js and
  /vendor/profile-enhance.js.
- The shared footer renders from the bundled template of a pinned
  @profullstack/footer 0.5.0 (allowlist sanitizer); no runtime CDN fetch.
- Migrations can run as a separate owner role (MIGRATE_DATABASE_URL) so the
  app can connect as a DML-only role with an append-only audit table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-28 16:04:22 +00:00
parent 18477340e7
commit ae6298851b
34 changed files with 1633 additions and 112 deletions

View file

@ -1,6 +1,6 @@
{
"name": "@logicsrc/cli",
"version": "0.9.0",
"version": "0.10.0",
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
"type": "module",
"main": "./dist/index.js",

View file

@ -0,0 +1,183 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { Server } from "node:http";
/**
* The post-incident flow end to end against the real credentials-app routes on
* an in-memory database:
*
* rotate-identity new keypair, every grant re-sealed, proof of the old key
* rekey new vault key, values unchanged, members + machine keys re-sealed
* race a value written under the retired key is re-sealed by the verify pass
* pins a teammate's changed key is refused until accepted
* login a different local key is refused instead of replacing the registered one
*/
const here = dirname(fileURLToPath(import.meta.url));
const pwa = (rel: string) => pathToFileURL(join(here, "..", "..", "..", "apps", "pwa", "src", rel)).href;
type Db = { execute(stmt: string | { sql: string; args: unknown[] }): Promise<{ rows: Array<Record<string, unknown>> }> };
let db: Db;
let server: Server;
let base = "";
let annToken = "";
let bobToken = "";
const scratch = mkdtempSync(join(process.env.LOGICSRC_TEST_TMP || tmpdir(), "logicsrc-hardening-"));
const annHome = join(scratch, "ann");
const bobHome = join(scratch, "bob");
const otherHome = join(scratch, "ann-other-machine");
const saved = { ...process.env };
const as = (home: string) => {
process.env.LOGICSRC_HOME = home;
delete process.env.LOGICSRC_API_KEY;
};
const identityOf = (home: string) => JSON.parse(readFileSync(join(home, "identity.json"), "utf8"));
const envFile = (name: string, body: string) => {
const p = join(scratch, name);
writeFileSync(p, body);
return p;
};
beforeAll(async () => {
process.env.DATABASE_URL = ":memory:";
delete process.env.LOGICSRC_IDENTITY_FILE;
({ db } = (await import(pwa("db.mjs"))) as { db: Db });
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(fileURLToPath(pwa(join("migrations", file))), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}
for (const [id, email] of [["u_ann", "ann@example.com"], ["u_bob", "bob@example.com"]]) {
await db.execute({ sql: "INSERT INTO users (id, email, created_at) VALUES (?,?,?)", args: [id, email, Date.now()] });
}
const expressModule = "express";
const { default: express } = (await import(expressModule)) as { default: any };
const { credshareRouter } = await import(pwa("routes/credshare.mjs"));
const { apiKeysRouter } = await import(pwa("routes/apikeys.mjs"));
const { createApiKey } = await import(pwa("lib/apikey.mjs"));
const app = express();
app.use(express.json());
app.use(credshareRouter);
app.use(apiKeysRouter);
server = app.listen(0);
await new Promise((resolve) => server.once("listening", resolve));
base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
process.env.LOGICSRC_API = base;
annToken = (await createApiKey("u_ann", "ann-laptop")).plaintext;
bobToken = (await createApiKey("u_bob", "bob-laptop")).plaintext;
});
afterAll(async () => {
await new Promise((resolve) => server?.close(resolve));
for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
Object.assign(process.env, saved);
rmSync(scratch, { recursive: true, force: true });
});
describe("identity rotation, re-key and key pinning", () => {
it("sets up: ann and bob log in, ann pushes two vaults and grants bob one", async () => {
const { loginAction, teamsPushAction, teamsGrantAction } = await import("./teams.js");
const { TeamClient } = await import("@logicsrc/plugin-credential-sharing");
as(bobHome);
await loginAction({ token: bobToken });
as(annHome);
await loginAction({ token: annToken });
const ann = new TeamClient({ apiUrl: base, token: annToken });
await ann.createTeam("acme");
const invite = await ann.invite("acme", "bob@example.com");
await new TeamClient({ apiUrl: base, token: bobToken }).acceptInvite(invite.token!);
await teamsPushAction("acme", "web", "prod", { env: envFile("web.env", "A=1\nB=two\n"), format: "json" });
await teamsPushAction("acme", "api", "prod", { env: envFile("api.env", "C=3\n"), format: "json" });
await teamsGrantAction("acme", "web", "prod", "bob@example.com", "json");
const pins = JSON.parse(readFileSync(join(annHome, "known-keys.json"), "utf8"));
expect(Object.keys(pins.keys).some((k) => k.endsWith("|bob@example.com"))).toBe(true);
expect(statSync(join(annHome, "known-keys.json")).mode & 0o777).toBe(0o600);
});
it("a login on another machine cannot replace ann's registered key", async () => {
const { loginAction } = await import("./teams.js");
const before = identityOf(annHome).keys.publicKey;
as(otherHome);
await expect(loginAction({ token: annToken })).rejects.toThrow(/not the registered one/);
const r = await db.execute({ sql: "SELECT public_key FROM credshare_keys WHERE user_id = ?", args: ["u_ann"] });
expect(r.rows[0]?.public_key).toBe(before);
});
it("rotate-identity swaps ann's key and every grant, and she can still pull", async () => {
const { teamsRotateIdentityAction } = await import("./hardening.js");
const { teamsPullAction } = await import("./teams.js");
as(annHome);
const before = identityOf(annHome).keys.publicKey;
await teamsRotateIdentityAction({ format: "json" });
const after = identityOf(annHome).keys.publicKey;
expect(after).not.toBe(before);
expect(statSync(join(annHome, "identity.json")).mode & 0o777).toBe(0o600);
const r = await db.execute({ sql: "SELECT public_key FROM credshare_keys WHERE user_id = ?", args: ["u_ann"] });
expect(r.rows[0]?.public_key).toBe(after);
const out = join(scratch, "web-after-rotate.env");
await teamsPullAction("acme", "web", "prod", { env: out, format: "json" });
expect(readFileSync(out, "utf8")).toMatch(/B=two/);
});
it("bob's CLI refuses to seal to ann's changed key until he accepts it", async () => {
const { teamsGrantAction } = await import("./teams.js");
as(bobHome);
// bob pins ann's (old) key the first time he sees it...
const { checkAndPinKey } = await import("@logicsrc/plugin-credential-sharing");
checkAndPinKey(base, "ann@example.com", "B".repeat(43) + "=");
// ...so the rotated key is a change.
await expect(teamsGrantAction("acme", "web", "prod", "ann@example.com", "json")).rejects.toThrow(/CHANGED/);
await teamsGrantAction("acme", "web", "prod", "ann@example.com", "json", { acceptKeyChange: ["ann@example.com"] });
});
it("rekey --all changes every vault key, keeps the values, and keeps bob", async () => {
const { teamsRekeyAction } = await import("./hardening.js");
const { teamsPullAction } = await import("./teams.js");
as(annHome);
const grantsBefore = await db.execute({ sql: "SELECT vault_id, user_id, wrapped_dek FROM credshare_vault_grants ORDER BY vault_id, user_id", args: [] });
await teamsRekeyAction("acme", undefined, undefined, { all: true, format: "json" });
const grantsAfter = await db.execute({ sql: "SELECT vault_id, user_id, wrapped_dek FROM credshare_vault_grants ORDER BY vault_id, user_id", args: [] });
expect(grantsAfter.rows.length).toBe(grantsBefore.rows.length);
for (let i = 0; i < grantsAfter.rows.length; i++) expect(grantsAfter.rows[i]!.wrapped_dek).not.toBe(grantsBefore.rows[i]!.wrapped_dek);
const versions = await db.execute({ sql: "SELECT key_version FROM credshare_vaults", args: [] });
expect(versions.rows.every((r) => Number(r.key_version) === 2)).toBe(true);
as(bobHome);
const out = join(scratch, "bob-web.env");
await teamsPullAction("acme", "web", "prod", { env: out, format: "json" });
expect(readFileSync(out, "utf8")).toMatch(/A=1/);
});
it("a value written under the retired key during a re-key is re-sealed, not lost", async () => {
const { teamsRekeyAction, verifyAndRepair } = await import("./hardening.js");
const { teamsPullAction } = await import("./teams.js");
const { TeamClient, unwrapVaultKey, encryptValue, fingerprintValue } = await import("@logicsrc/plugin-credential-sharing");
as(annHome);
const ann = identityOf(annHome);
const client = new TeamClient({ apiUrl: base, token: annToken });
const { vaults } = await client.listVaults("acme");
const web = vaults.find((v) => v.name === "web--prod")!;
// An old client: read the key now, write after the re-key, sending no key version.
const staleDek = await unwrapVaultKey((await client.getMyGrant(web.id)).wrappedDek, ann.keys);
await teamsRekeyAction("acme", "web", "prod", { format: "json" });
const sealed = await encryptValue("late-value", staleDek);
await client.putSecrets(web.id, [{ name: "LATE", ...sealed, fingerprint: fingerprintValue("late-value") }], []);
// The verify pass a re-key run ends with re-seals it under the current key.
const fixed = await verifyAndRepair(client, ann.keys, { vaultId: web.id, vault: web.name, oldDeks: [staleDek] });
expect(fixed.repaired).toBe(1);
expect(fixed.unreadable).toEqual([]);
const out = join(scratch, "web-late.env");
await teamsPullAction("acme", "web", "prod", { env: out, format: "json" });
expect(readFileSync(out, "utf8")).toMatch(/LATE=late-value/);
});
it("the audit trail records the reads with the acting user", async () => {
const { TeamClient } = await import("@logicsrc/plugin-credential-sharing");
const { audit } = await new TeamClient({ apiUrl: base, token: annToken }).teamAudit("acme", { action: "vault:read" });
expect(audit.some((a) => a.actor === "bob@example.com" && a.vault === "web--prod")).toBe(true);
const rot = await new TeamClient({ apiUrl: base, token: annToken }).teamAudit("acme", { action: "identity:rotate" });
expect(rot.audit.length).toBeGreaterThan(0);
});
});

View file

@ -0,0 +1,404 @@
import { existsSync, readFileSync, rmSync } from "node:fs";
import {
TeamApiError,
checkAndPinKey,
decryptValue,
encryptValue,
fingerprintValue,
fingerprintsEqual,
generateIdentityKeyPair,
identityPath,
keyFingerprint,
planVaultRekey,
publicKeyForSecret,
readIdentity,
repinKey,
resolveApiUrl,
saveIdentity,
unwrapVaultKey,
wrapVaultKey,
type RemoteVault,
type TeamClient
} from "@logicsrc/plugin-credential-sharing";
import { authedClient, splitVaultName, vaultName } from "./teams.js";
import { print, type OutputFormat } from "./format.js";
/**
* Post-incident commands (2026-10-28): rotate your identity key, re-key vaults,
* read the audit trail, and import an identity copied from another machine.
*
* All crypto stays on this machine. The server sees public keys, sealed boxes
* and ciphertext only, as everywhere else in `logicsrc teams`.
*/
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const b64ToUtf8 = (b64: string) => Buffer.from(b64, "base64").toString("utf8");
function personClient() {
const { client, identity } = authedClient();
if (identity.keyKind === "machine") {
throw new Error("This needs a person's login (logicsrc login), not a machine API key.");
}
return { client, identity, apiUrl: resolveApiUrl(identity) };
}
/** The server's key must be the one this machine holds, or nothing here can work. */
async function assertLocalKeyIsRegistered(client: TeamClient, publicKey: string): Promise<void> {
const me = await client.me();
if (me.user.publicKey !== publicKey) {
throw new Error(
`This machine's identity key (${keyFingerprint(publicKey)}) is not the one registered for ${me.user.email} (${keyFingerprint(me.user.publicKey) ?? "none"}). ` +
"Run this on the machine that holds the registered key, or import it here: logicsrc teams key --import"
);
}
}
// ------------------------------------------------------------- rotate-identity
export async function teamsRotateIdentityAction(options: { format: OutputFormat }): Promise<void> {
const { client, identity, apiUrl } = personClient();
if (!identity.keys?.secretKey || (await publicKeyForSecret(identity.keys.secretKey)) !== identity.keys.publicKey) {
throw new Error(`${identityPath()} is missing or damaged; cannot prove the current key.`);
}
await assertLocalKeyIsRegistered(client, identity.keys.publicKey);
const next = await generateIdentityKeyPair();
// Keep the new key on disk BEFORE the server switches to it: if this process
// dies between the server's commit and the local write, the key is not lost.
const pending = `${identityPath()}.next`;
saveIdentity({ ...identity, keys: next }, pending);
let result: Awaited<ReturnType<TeamClient["rotateIdentity"]>> | undefined;
for (let attempt = 1; attempt <= 3 && !result; attempt++) {
const { grants } = await client.myGrants();
const resealed: Array<{ vaultId: string; wrappedDek: string }> = [];
for (const g of grants) {
const dek = await unwrapVaultKey(g.wrappedDek, identity.keys);
resealed.push({ vaultId: g.vaultId, wrappedDek: await wrapVaultKey(dek, next.publicKey) });
}
const challenge = await client.identityChallenge();
const answer = b64ToUtf8(await unwrapVaultKey(challenge.sealed, identity.keys));
try {
result = await client.rotateIdentity({ publicKey: next.publicKey, challengeId: challenge.challengeId, answer, grants: resealed });
} catch (error) {
// A grant added or removed while we were re-sealing: read them again.
if (error instanceof TeamApiError && error.status === 409 && attempt < 3) { await sleep(500); continue; }
rmSync(pending, { force: true });
throw error;
}
}
if (!result) {
rmSync(pending, { force: true });
throw new Error("Identity rotation did not complete; nothing changed.");
}
const stored = readIdentity() ?? identity;
saveIdentity({ ...stored, keys: next });
rmSync(pending, { force: true });
repinKey(apiUrl, identity.email, next.publicKey);
console.error(
`Rotated your identity key: ${result.previousFingerprint} -> ${result.fingerprint}. Re-sealed ${result.regranted} vault grant(s). ` +
`${identityPath()} now holds the new key (0600).`
);
console.error(
"The vault keys themselves did not change. If the old secret key leaked, re-key the vaults now: logicsrc teams rekey <team> --all\n" +
"Other machines with the old key must import the new one (logicsrc teams key here, then logicsrc teams key --import there). " +
"Teammates will see your fingerprint change and must confirm it before granting you anything."
);
print({ previousFingerprint: result.previousFingerprint, fingerprint: result.fingerprint, regranted: result.regranted }, options.format);
}
// ------------------------------------------------------------------ key import
export async function teamsKeyImportAction(options: { format: OutputFormat }): Promise<void> {
const raw = readFileSync(0, "utf8").trim();
if (!raw) throw new Error("Paste the identity secret key (or the whole identity.json) on stdin.");
let secretKey = raw;
if (raw.startsWith("{")) {
const parsed = JSON.parse(raw) as { keys?: { secretKey?: string }; secretKey?: string };
secretKey = parsed.keys?.secretKey ?? parsed.secretKey ?? "";
}
if (!/^[A-Za-z0-9+/]{43}=$/.test(secretKey)) throw new Error("That is not a base64 X25519 secret key.");
const publicKey = await publicKeyForSecret(secretKey);
const current = readIdentity();
if (current?.apiToken) {
const { client } = authedClient();
const me = await client.me();
if (me.user.publicKey && me.user.publicKey !== publicKey) {
throw new Error(
`That key (${keyFingerprint(publicKey)}) is not the one registered for ${me.user.email} (${keyFingerprint(me.user.publicKey)}). Nothing written.`
);
}
if (!me.user.publicKey) await client.uploadPublicKey(publicKey);
}
if (current?.keys?.secretKey && current.keys.publicKey !== publicKey && existsSync(identityPath())) {
console.error(`Replacing this machine's previous identity key (${keyFingerprint(current.keys.publicKey)}).`);
}
saveIdentity({ ...(current ?? { createdAt: new Date().toISOString() }), keys: { publicKey, secretKey } } as Parameters<typeof saveIdentity>[0]);
console.error(`Imported identity key ${keyFingerprint(publicKey)} into ${identityPath()} (0600).`);
print({ fingerprint: keyFingerprint(publicKey), file: identityPath() }, options.format);
}
// ----------------------------------------------------------------------- rekey
export interface RekeyOptions {
all?: boolean;
acceptKeyChange?: string[];
concurrency?: number;
dryRun?: boolean;
format: OutputFormat;
}
interface RekeyOutcome {
vault: string;
status: "rekeyed" | "planned" | "skipped" | "failed";
secrets?: number;
members?: number;
machineKeys?: number;
keysDropped?: string[];
repaired?: number;
unreadable?: string[];
keyVersion?: number;
note?: string;
}
interface Retired {
vaultId: string;
vault: string;
oldDeks: string[];
}
/**
* Check every secret opens under the vault's CURRENT key. A value that does
* not, but opens under a retired one, was pushed by a client that read the old
* key just before the re-key: re-seal it under the current key. Values never
* change here (the fingerprint is checked both ways).
*/
export async function verifyAndRepair(client: TeamClient, identityKeys: { publicKey: string; secretKey: string }, retired: Retired) {
const { wrappedDek, keyVersion } = await client.getMyGrant(retired.vaultId);
const dek = await unwrapVaultKey(wrappedDek, identityKeys);
const { secrets } = await client.listSecrets(retired.vaultId);
const repairs: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }> = [];
const unreadable: string[] = [];
for (const s of secrets) {
let value: string | null = null;
try {
value = await decryptValue({ nonce: s.nonce, ciphertext: s.ciphertext }, dek);
if (fingerprintsEqual(s.fingerprint, fingerprintValue(value))) continue;
value = null;
} catch { /* not under the current key */ }
for (const old of retired.oldDeks) {
try {
const v = await decryptValue({ nonce: s.nonce, ciphertext: s.ciphertext }, old);
if (fingerprintsEqual(s.fingerprint, fingerprintValue(v))) { value = v; break; }
} catch { /* try the next */ }
}
if (value === null) { unreadable.push(s.name); continue; }
const sealed = await encryptValue(value, dek);
repairs.push({ name: s.name, nonce: sealed.nonce, ciphertext: sealed.ciphertext, fingerprint: fingerprintValue(value) });
}
if (repairs.length) await client.putSecrets(retired.vaultId, repairs, [], keyVersion);
return { repaired: repairs.length, unreadable, secrets: secrets.length };
}
async function rekeyOne(
client: TeamClient,
identity: { email: string; keys: { publicKey: string; secretKey: string } },
apiUrl: string,
v: RemoteVault,
options: RekeyOptions,
retiredOut: Retired[]
): Promise<RekeyOutcome> {
if (!v.hasAccess) return { vault: v.name, status: "skipped", note: "you hold no grant" };
const accept = options.acceptKeyChange ?? [];
const oldDeks: string[] = [];
for (let attempt = 1; attempt <= 4; attempt++) {
const [{ wrappedDek }, { secrets }, { grants }, { keyGrants }] = await Promise.all([
client.getMyGrant(v.id),
client.listSecrets(v.id),
client.listGrants(v.id),
client.listKeyGrants(v.id)
]);
// Seal only to keys this machine has pinned (or pins now, first use).
for (const g of grants) {
if (!g.hasAccess || !g.publicKey) continue;
if (g.email.toLowerCase() === identity.email.toLowerCase()) {
if (g.publicKey !== identity.keys.publicKey) throw new Error(`The server holds a different key for you (${keyFingerprint(g.publicKey)}) than this machine (${keyFingerprint(identity.keys.publicKey)}). Refusing to re-key.`);
continue;
}
checkAndPinKey(apiUrl, g.email, g.publicKey, accept);
}
for (const k of keyGrants) {
if (k.publicKey) checkAndPinKey(apiUrl, `key:${k.keyId}`, k.publicKey, accept.includes(k.name) || accept.includes(k.keyId) || accept.includes(`key:${k.keyId}`));
}
const oldDek = await unwrapVaultKey(wrappedDek, identity.keys);
if (!oldDeks.includes(oldDek)) oldDeks.push(oldDek);
const plan = await planVaultRekey({
myWrappedDek: wrappedDek,
identity: identity.keys,
secrets: secrets.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint })),
members: grants.map((g) => ({ email: g.email, publicKey: g.publicKey, status: g.status, hasAccess: g.hasAccess })),
scope: "all",
machineKeys: keyGrants.map((k) => ({ keyId: k.keyId, name: k.name, owner: k.owner, publicKey: k.publicKey }))
});
if (options.dryRun) {
return { vault: v.name, status: "planned", secrets: plan.secrets.length, members: plan.grants.length, machineKeys: plan.keyGrants.length, keysDropped: plan.keysDropped };
}
try {
const result = await client.rekeyVault(v.id, { grants: plan.grants, secrets: plan.secrets, revoke: plan.revoked, keyGrants: plan.keyGrants });
const retired = { vaultId: v.id, vault: v.name, oldDeks };
retiredOut.push(retired);
const check = await verifyAndRepair(client, identity.keys, retired);
return {
vault: v.name,
status: "rekeyed",
secrets: result.rekeyed,
members: result.granted.length,
machineKeys: result.keysResealed?.length ?? 0,
keysDropped: result.keysDropped ?? [],
repaired: check.repaired,
unreadable: check.unreadable,
keyVersion: result.keyVersion
};
} catch (error) {
// 409: a push changed the vault between our read and the re-key. Read again.
if (error instanceof TeamApiError && error.status === 409 && attempt < 4) { await sleep(400 * attempt); continue; }
throw error;
}
}
return { vault: v.name, status: "failed", note: "kept changing under us" };
}
async function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const out = new Array<R>(items.length);
let next = 0;
const worker = async () => {
while (next < items.length) {
const i = next++;
out[i] = await fn(items[i]!);
}
};
await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
return out;
}
export async function teamsRekeyAction(slug: string, project: string | undefined, env: string | undefined, options: RekeyOptions): Promise<void> {
const { client, identity, apiUrl } = personClient();
await assertLocalKeyIsRegistered(client, identity.keys.publicKey);
const { vaults } = await client.listVaults(slug);
let selected: RemoteVault[];
if (options.all) {
if (project || env) throw new Error("Give <project> <env> or --all, not both.");
selected = vaults;
} else {
if (!project || !env) throw new Error("Re-key which vault? Give <project> <env>, or --all for every vault you can open.");
const name = vaultName(project, env);
const found = vaults.find((v) => v.name === name);
if (!found) throw new Error(`Vault "${name}" not found in team "${slug}".`);
selected = [found];
}
const retired: Retired[] = [];
let done = 0;
const outcomes = await mapLimit(selected, Math.max(1, Math.min(options.concurrency ?? 4, 8)), async (v) => {
try {
return await rekeyOne(client, identity, apiUrl, v, options, retired);
} catch (error) {
return { vault: v.name, status: "failed", note: error instanceof Error ? error.message.split("\n")[0] : String(error) } as RekeyOutcome;
} finally {
done++;
if (selected.length > 1 && process.stderr.isTTY) process.stderr.write(`\r ${done}/${selected.length} vaults`);
}
});
if (selected.length > 1 && process.stderr.isTTY) process.stderr.write("\n");
// A push that read the old key moments before a re-key can land after the
// per-vault check. One more pass over everything re-keyed catches it.
let lateRepairs = 0;
if (!options.dryRun && retired.length) {
await sleep(2000);
const byVault = new Map(outcomes.map((o) => [o.vault, o]));
await mapLimit(retired, Math.max(1, Math.min(options.concurrency ?? 4, 8)), async (r) => {
try {
const check = await verifyAndRepair(client, identity.keys, r);
lateRepairs += check.repaired;
const o = byVault.get(r.vault);
if (o) { o.repaired = (o.repaired ?? 0) + check.repaired; o.unreadable = check.unreadable; }
} catch (error) {
const o = byVault.get(r.vault);
if (o) o.note = `verify failed: ${error instanceof Error ? error.message : String(error)}`;
}
});
}
const count = (s: RekeyOutcome["status"]) => outcomes.filter((o) => o.status === s).length;
const unreadable = outcomes.filter((o) => o.unreadable?.length);
console.error(
options.dryRun
? `Dry run: ${count("planned")} vault(s) would be re-keyed, ${count("skipped")} skipped, ${count("failed")} cannot be.`
: `Re-keyed ${count("rekeyed")} vault(s); ${count("skipped")} skipped (no grant), ${count("failed")} failed. ` +
`Repaired ${outcomes.reduce((n, o) => n + (o.repaired ?? 0), 0)} value(s) written under a retired key (${lateRepairs} in the final pass).` +
(unreadable.length ? ` ${unreadable.length} vault(s) hold values that open under no key we know: see "unreadable".` : "")
);
print(
outcomes.map((o) => ({
vault: o.vault,
status: o.status,
secrets: o.secrets ?? "",
members: o.members ?? "",
machineKeys: o.machineKeys ?? "",
...(o.keysDropped?.length ? { keysDropped: o.keysDropped.join(",") } : {}),
...(o.repaired ? { repaired: o.repaired } : {}),
...(o.unreadable?.length ? { unreadable: o.unreadable.join(",") } : {}),
...(o.note ? { note: o.note } : {})
})),
options.format
);
if (count("failed")) process.exitCode = 1;
}
// ----------------------------------------------------------------------- audit
function parseSince(value: string | undefined): number | undefined {
if (!value) return undefined;
const m = /^(\d+)\s*(m|h|d|w)$/i.exec(value.trim());
if (m) return Date.now() - Number(m[1]) * { m: 60e3, h: 3600e3, d: 86400e3, w: 7 * 86400e3 }[m[2]!.toLowerCase() as "m"];
const t = Date.parse(value);
if (Number.isNaN(t)) throw new Error(`Cannot read --since "${value}". Use 24h, 7d, or a date.`);
return t;
}
export async function teamsAuditAction(
slug: string,
project: string | undefined,
env: string | undefined,
options: { actor?: string; action?: string; since?: string; limit?: string; format: OutputFormat }
): Promise<void> {
const { client } = authedClient();
if (project && !env) throw new Error("Give both <project> and <env>, or neither.");
const { audit } = await client.teamAudit(slug, {
vault: project && env ? vaultName(project, env) : undefined,
actor: options.actor,
action: options.action,
since: parseSince(options.since),
limit: options.limit ? Number(options.limit) : 200
});
print(
audit.length
? audit.map((a) => ({
at: new Date(a.at).toISOString().replace("T", " ").slice(0, 19),
actor: a.actor ?? "?",
via: a.apiKey ? `${a.apiKeyKind === "machine" ? "machine:" : ""}${a.apiKey}` : "",
action: a.action,
vault: a.vault ?? "",
target: a.apiKey ? "" : (a.target ?? ""),
ip: a.ip ?? "",
userAgent: options.format === "table" ? (a.userAgent ?? "").slice(0, 40) : (a.userAgent ?? "")
}))
: [{ note: "No audit rows match." }],
options.format
);
}
export { splitVaultName };

View file

@ -37,6 +37,7 @@ import { registerKeysCommands } from "./keys.js";
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
import { credentialsRotateAction } from "./rotate.js";
import { teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
import { teamsAuditAction, teamsKeyImportAction, teamsRekeyAction, teamsRotateIdentityAction } from "./hardening.js";
import { boards, tasks } from "./fixtures.js";
import { print, type OutputFormat } from "./format.js";
import { parsePositiveInteger } from "./numeric-options.js";
@ -742,6 +743,10 @@ Quick start (<team> is e.g. profullstack; see yours with "logicsrc teams list"):
logicsrc teams push <team> <project> <env> ./.env -> vault
logicsrc teams grant <team> <project> <env> dev@example.com
logicsrc teams key your key, to read values in the web app
logicsrc teams members <team> members + key fingerprints (pinned on first use)
logicsrc teams audit <team> [project] [env] who read what, from where
logicsrc teams rotate-identity new identity key, grants re-sealed
logicsrc teams rekey <team> --all new vault keys, values re-encrypted
logicsrc teams rotation <team> how each secret is rotated (agents: --format json)
logicsrc teams rotate-keys <team> [project] [env] rotate values (dry run; --approve to write)
@ -978,9 +983,72 @@ there; the key is checked against your registered public key and never sent.
Examples:
logicsrc teams key print it
logicsrc teams key | pbcopy straight to the clipboard (macOS; wl-copy / xclip on Linux)
logicsrc teams key --import < key use a key copied from your other machine (must be the registered one)
`
)
.action(() => teamsKeyAction());
.option("--import", "Read an identity secret key (or identity.json) from stdin and use it on this machine")
.option("--format <format>", "table, json, or markdown", "table")
.action((options) => (options.import ? teamsKeyImportAction({ format: options.format as OutputFormat }) : teamsKeyAction()));
teams
.command("rotate-identity")
.option("--format <format>", "table, json, or markdown", "table")
.description("Replace your identity key: new keypair, every vault grant re-sealed to it, registered with proof of the current key.")
.addHelpText(
"after",
`
Run it on the machine that holds your current key (the server seals a challenge
to it). The vault keys are unchanged, so if the old secret key leaked, follow
with: logicsrc teams rekey <team> --all
Other machines then import the new key: logicsrc teams key | ssh other 'logicsrc teams key --import'`
)
.action((options) => teamsRotateIdentityAction({ format: options.format as OutputFormat }));
teams
.command("rekey")
.argument("<slug>", "Team slug")
.argument("[project]", "Project name")
.argument("[env]", "Environment name")
.option("--all", "Every vault in the team you can open")
.option("--accept-key-change <email>", "Seal to this member's (or machine key's) CHANGED key; repeat or comma-separate", collectList)
.option("--concurrency <n>", "Vaults in flight at once (1-8)", "4")
.option("--dry-run", "Plan only; change nothing")
.option("--format <format>", "table, json, or markdown", "table")
.description("New vault key: re-encrypt every value here, re-seal to every current member and machine key (pinned keys only).")
.addHelpText(
"after",
`
Values do not change. Everyone who holds the vault keeps it, under a fresh key;
anyone holding only an OLD wrapped key (or the old key itself) loses it. A push
racing the re-key is caught: the vault is re-checked afterwards and any value
written under the retired key is re-sealed under the new one.
logicsrc teams rekey acme web prod
logicsrc teams rekey acme --all --dry-run
logicsrc teams rekey acme --all`
)
.action((slug, project, env, options) =>
teamsRekeyAction(slug, project, env, {
all: Boolean(options.all),
acceptKeyChange: options.acceptKeyChange,
concurrency: Number(options.concurrency) || 4,
dryRun: Boolean(options.dryRun),
format: options.format as OutputFormat
})
);
teams
.command("audit")
.argument("<slug>", "Team slug")
.argument("[project]", "Project name (with env: one vault)")
.argument("[env]", "Environment name")
.option("--actor <email>", "Only this person")
.option("--action <prefix>", "Only actions starting with this (vault:read, secrets:fetch, identity:, vault:rekey …)")
.option("--since <when>", "24h, 7d, or a date")
.option("--limit <n>", "Rows (max 1000)", "200")
.option("--format <format>", "table, json, or markdown", "table")
.description("Who read which vault key or ciphertext, when, from which IP and user agent; plus grants, re-keys and identity changes.")
.action((slug, project, env, options) => teamsAuditAction(slug, project, env, { ...options, format: options.format as OutputFormat }));
teams
.command("tui")
@ -996,9 +1064,10 @@ teams
.argument("<env>", "Environment name (prod, staging, …)")
.argument("[email]", "Teammate email to grant vault access")
.option("--key <name>", "Grant one of your machine API keys instead of a person (name, id, or prefix)")
.option("--accept-key-change <email>", "Their key changed since you pinned it and you have confirmed the new fingerprint with them", collectList)
.option("--format <format>", "table, json, or markdown", "table")
.description("Grant a member, or a machine API key, decryption access to a vault (re-seals the vault key to their key).")
.action((slug, project, env, email, options) => teamsGrantAction(slug, project, env, email, options.format as OutputFormat, { key: options.key }));
.action((slug, project, env, email, options) => teamsGrantAction(slug, project, env, email, options.format as OutputFormat, { key: options.key, acceptKeyChange: options.acceptKeyChange }));
teams
.command("push")

View file

@ -50,7 +50,7 @@ beforeAll(async () => {
process.env.LOGICSRC_IDENTITY_FILE = "";
delete process.env.LOGICSRC_IDENTITY_FILE;
({ db } = (await import(pwa("db.mjs"))) as { db: Db });
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(fileURLToPath(pwa(join("migrations", file))), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}

View file

@ -25,6 +25,9 @@ import {
setActiveKey,
activeKeyPath,
readActiveKeyIdentity,
checkAndPinKey,
keyFingerprint,
pinStatus,
type CredentialEndpoint,
type RemoteVault
} from "@logicsrc/plugin-credential-sharing";
@ -330,11 +333,22 @@ export async function loginAction(options: { apiUrl?: string; token?: string; ap
}
const client = new TeamClient({ apiUrl, token: token! });
await client.uploadPublicKey(identity.keys.publicKey);
let keyMismatch: string | null = null;
try {
await client.uploadPublicKey(identity.keys.publicKey);
} catch (error) {
// Since 2026-10-28 a registered identity key is never silently replaced by a
// login: that was how a stolen token could swap in an attacker's key.
if (!(error instanceof TeamApiError) || error.status !== 409) throw error;
keyMismatch = error.message;
}
await updateIdentity({ email: email ?? undefined, userId, apiToken: token, apiUrl });
// A person login takes over from any key chosen with --api-key.
rmSync(activeKeyPath(), { force: true });
if (keyMismatch) {
throw new Error(`Logged in${email ? ` as ${email}` : ""}, but this machine's identity key is not the registered one, so it cannot open any vault.\n${keyMismatch}`);
}
console.error(`Logged in${email ? ` as ${email}` : ""}. Identity key registered on ${apiUrl}.`);
print({ email, apiUrl }, "table");
}
@ -450,11 +464,29 @@ export async function teamsAcceptAction(token: string, format: OutputFormat): Pr
print({ joined: result.team?.slug ?? null }, format);
}
/** A member's key fingerprint and what this machine's pins say about it. */
export function memberKeyColumns(apiUrl: string, email: string, publicKey: string | null | undefined, ownPublicKey?: string) {
const fp = keyFingerprint(publicKey ?? null);
if (!fp) return { fingerprint: "—", pin: "no key" };
if (ownPublicKey && publicKey === ownPublicKey) return { fingerprint: fp, pin: "you" };
const { status, pinned } = pinStatus(apiUrl, email, publicKey);
return {
fingerprint: fp,
pin: status === "pinned" ? "pinned" : status === "new" ? "not pinned yet" : `CHANGED (pinned ${pinned?.fingerprint})`
};
}
export async function teamsMembersAction(slug: string, format: OutputFormat): Promise<void> {
const { client } = authedClient();
const { client, identity } = authedClient();
const { members } = await client.listMembers(slug);
const apiUrl = resolveApiUrl(identity);
print(
members.map((m) => ({ email: m.email, role: m.role, status: m.status, hasKey: m.hasPublicKey })),
members.map((m) => ({
email: m.email,
role: m.role,
status: m.status,
...memberKeyColumns(apiUrl, m.email, m.publicKey ?? null, identity.keys?.publicKey)
})),
format
);
}
@ -485,7 +517,7 @@ export async function teamsGrantAction(
env: string,
email: string | undefined,
format: OutputFormat,
options: { key?: string } = {}
options: { key?: string; acceptKeyChange?: string[] } = {}
): Promise<void> {
if (!email && !options.key) throw new Error("Grant whom? Give a teammate's email, or --key <name> for a machine API key.");
if (email && options.key) throw new Error("Give an email or --key, not both.");
@ -522,7 +554,11 @@ export async function teamsGrantAction(
}
const dek = await unwrapVaultKey(myWrapped, identity.keys);
const apiUrl = resolveApiUrl(identity);
const accept = options.acceptKeyChange ?? [];
if (machineKey) {
const pinned = checkAndPinKey(apiUrl, `key:${machineKey.id}`, machineKey.publicKey!, accept.includes(machineKey.name) || accept.includes(machineKey.id));
if (pinned === "new") console.error(`Pinned machine key "${machineKey.name}" at ${keyFingerprint(machineKey.publicKey)}.`);
await client.putKeyGrant(vaultId, machineKey.id, await wrapVaultKey(dek, machineKey.publicKey!));
console.error(
`Granted machine key "${machineKey.name}" ${machineKey.readOnly ? "read-only " : ""}access to ${slug}/${vault}. ` +
@ -536,6 +572,10 @@ export async function teamsGrantAction(
const target = await client.lookupUser(email);
if (!target.userId) throw new Error(`${email} has not logged in yet. Ask them to run: logicsrc login --email ${email}`);
if (!target.publicKey) throw new Error(`${email} has not registered a key yet. Ask them to run: logicsrc login --email ${email}`);
// Trust on first use: seal only to the key pinned for this person, or pin it now.
const pin = checkAndPinKey(apiUrl, email, target.publicKey, accept);
if (pin === "new") console.error(`Pinned ${email}'s identity key at ${keyFingerprint(target.publicKey)}. Compare it with them (logicsrc teams members ${slug}).`);
if (pin === "changed") console.error(`Accepted a CHANGED key for ${email}: now ${keyFingerprint(target.publicKey)}.`);
await client.putGrant(vaultId, email, await wrapVaultKey(dek, target.publicKey));
console.error(`Granted ${email} access to ${slug}/${vault}. They can now: logicsrc teams pull ${slug} ${project} ${env}`);