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

@ -30,9 +30,26 @@ export interface RemoteMember {
role: "owner" | "admin" | "member";
status: "active" | "invited";
hasPublicKey: boolean;
/** The member's identity public key and its fingerprint (servers before 2026-10-28 omit these). */
publicKey?: string | null;
fingerprint?: string | null;
joinedAt: string | null;
}
/** One audit row, as GET /teams/:slug/audit returns it. */
export interface RemoteAuditRow {
at: number;
action: string;
actor: string | null;
vault: string | null;
target: string | null;
fingerprint: string | null;
apiKey: string | null;
apiKeyKind: string | null;
ip: string | null;
userAgent: string | null;
}
export interface RemoteVault {
id: string;
name: string;
@ -66,6 +83,8 @@ export interface RekeyResult {
/** Machine keys re-sealed to the new DEK, and the ones dropped (servers before machine keys omit these). */
keysResealed?: string[];
keysDropped?: string[];
/** The vault's key version after this re-key. */
keyVersion?: number;
}
/** The credential a request was made with, as /api/credshare/me describes it. Null for a browser session. */
@ -228,7 +247,24 @@ export class TeamClient {
return this.request<{ vault: { id: string; name: string } }>("POST", `/teams/${encodeURIComponent(slug)}/vaults`, { name });
}
getMyGrant(vaultId: string) {
return this.request<{ wrappedDek: string }>("GET", `/vaults/${encodeURIComponent(vaultId)}/grant`);
return this.request<{ wrappedDek: string; keyVersion?: number }>("GET", `/vaults/${encodeURIComponent(vaultId)}/grant`);
}
/** Every vault grant the caller holds, for re-sealing them during an identity rotation. */
myGrants() {
return this.request<{ grants: Array<{ vaultId: string; vault: string; team: string; wrappedDek: string }> }>("GET", "/me/grants");
}
/** A random answer sealed to the caller's CURRENT identity key: opening it proves possession. */
identityChallenge() {
return this.request<{ challengeId: string; sealed: string; publicKey: string; fingerprint: string; expiresAt: number }>("POST", "/keys/challenge", {});
}
rotateIdentity(body: { publicKey: string; challengeId: string; answer: string; grants: Array<{ vaultId: string; wrappedDek: string }> }) {
return this.request<{ ok: boolean; publicKey: string; fingerprint: string; previousFingerprint: string; regranted: number }>("POST", "/keys/rotate", body);
}
teamAudit(slug: string, query: { vault?: string; actor?: string; action?: string; since?: number; limit?: number } = {}) {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null && v !== "") qs.set(k, String(v));
const suffix = qs.toString() ? `?${qs}` : "";
return this.request<{ audit: RemoteAuditRow[] }>("GET", `/teams/${encodeURIComponent(slug)}/audit${suffix}`);
}
listGrants(vaultId: string) {
return this.request<{ grants: RemoteGrantRow[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/grants`);
@ -237,10 +273,15 @@ export class TeamClient {
return this.request<{ ok: boolean }>("POST", `/vaults/${encodeURIComponent(vaultId)}/grants`, { email, wrappedDek });
}
listSecrets(vaultId: string) {
return this.request<{ vaultId: string; secrets: RemoteSecret[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/secrets`);
return this.request<{ vaultId: string; keyVersion?: number; secrets: RemoteSecret[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/secrets`);
}
putSecrets(vaultId: string, upserts: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>, deletes: string[]) {
return this.request<{ ok: boolean; applied: string[] }>("PUT", `/vaults/${encodeURIComponent(vaultId)}/secrets`, { upserts, deletes });
/**
* `keyVersion` is the vault key version the ciphertext was made under (from
* getMyGrant). The server refuses the write if the vault was re-keyed since,
* so nothing lands under a retired key.
*/
putSecrets(vaultId: string, upserts: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>, deletes: string[], keyVersion?: number) {
return this.request<{ ok: boolean; applied: string[] }>("PUT", `/vaults/${encodeURIComponent(vaultId)}/secrets`, { upserts, deletes, ...(keyVersion !== undefined ? { keyVersion } : {}) });
}
/**
* Swap the vault to a fresh DEK. The whole next state goes over in one call

View file

@ -83,6 +83,7 @@ export {
type RemoteKeyInfo,
type RemoteApiKey,
type RemoteKeyGrant,
type RemoteAuditRow,
type CreateApiKeyInput
} from "./client.js";
export {
@ -130,6 +131,16 @@ export {
type CredentialStore
} from "./store.js";
export { fingerprintValue, fingerprintsEqual } from "./fingerprint.js";
export {
keyFingerprint,
knownKeysPath,
pinStatus,
checkAndPinKey,
repinKey,
KeyChangedError,
type KnownKey,
type PinStatus
} from "./known-keys.js";
export {
planVaultRekey,
type RekeyPlan,

View file

@ -0,0 +1,137 @@
import { createHash } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { logicsrcHome } from "./identity.js";
/**
* Trust-on-first-use pins for the identity public keys this CLI seals vault
* keys to (teammates and machine keys).
*
* The server hands out public keys, and a server (or a stolen session) that
* swaps one in could get every vault re-sealed to an attacker. So the first
* key seen for a member is pinned in `<home>/known-keys.json`, and a later
* DIFFERENT key is refused for sealing until the user confirms it
* (`--accept-key-change <email>`), after checking the fingerprint with the
* person. A rotation (`teams rotate-identity`) or a reset changes a key
* legitimately; this makes that change visible instead of silent.
*
* Fingerprints match the web app's: sha256 over the raw 32-byte key, first 16
* bytes as eight groups of four hex digits.
*/
export function keyFingerprint(publicKeyB64: string | null | undefined): string | null {
if (!publicKeyB64) return null;
const raw = Buffer.from(publicKeyB64, "base64");
if (raw.length !== 32) return null;
const hex = createHash("sha256").update(raw).digest("hex").slice(0, 32);
return hex.match(/.{4}/g)!.join(" ");
}
export interface KnownKey {
publicKey: string;
fingerprint: string;
firstSeen: string;
lastSeen: string;
/** Set when a change was accepted: the fingerprint it replaced. */
replaced?: string;
}
interface KnownKeysFile {
version: 1;
/** Keyed by `<apiUrl>|<email>` for people and `<apiUrl>|key:<id>` for machine keys. */
keys: Record<string, KnownKey>;
}
export type PinStatus = "pinned" | "new" | "changed" | "none";
export class KeyChangedError extends Error {
constructor(
public readonly subject: string,
public readonly pinned: string,
public readonly presented: string
) {
super(
`The identity key for ${subject} CHANGED since this machine pinned it.\n` +
` pinned: ${pinned}\n presented: ${presented}\n` +
"This is expected after they ran `logicsrc teams rotate-identity` or reset their key, and it is exactly what a swapped-in attacker key looks like. " +
`Confirm the new fingerprint with ${subject} out of band, then re-run with --accept-key-change ${subject}`
);
this.name = "KeyChangedError";
}
}
export function knownKeysPath(): string {
return join(logicsrcHome(), "known-keys.json");
}
function load(): KnownKeysFile {
const file = knownKeysPath();
if (!existsSync(file)) return { version: 1, keys: {} };
try {
const parsed = JSON.parse(readFileSync(file, "utf8")) as KnownKeysFile;
return parsed && typeof parsed.keys === "object" ? parsed : { version: 1, keys: {} };
} catch {
throw new Error(`${file} is not valid JSON. Fix or remove it (removing it re-pins every key on first use).`);
}
}
function save(data: KnownKeysFile): void {
const file = knownKeysPath();
mkdirSync(dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
renameSync(tmp, file);
try { chmodSync(file, 0o600); } catch { /* no modes on this platform */ }
}
const pinId = (apiUrl: string, subject: string) => `${apiUrl.replace(/\/+$/, "")}|${subject.toLowerCase()}`;
/** What we know about a key, without changing anything. */
export function pinStatus(apiUrl: string, subject: string, publicKey: string | null | undefined): { status: PinStatus; pinned?: KnownKey } {
if (!publicKey) return { status: "none" };
const pinned = load().keys[pinId(apiUrl, subject)];
if (!pinned) return { status: "new" };
return { status: pinned.publicKey === publicKey ? "pinned" : "changed", pinned };
}
/**
* Check a key before sealing anything to it. Pins it on first use; throws
* KeyChangedError on a change unless `accept` names the subject (or is true).
* Returns what happened, so callers can tell the user about a new pin.
*/
export function checkAndPinKey(
apiUrl: string,
subject: string,
publicKey: string,
accept: boolean | string[] = false
): PinStatus {
const data = load();
const id = pinId(apiUrl, subject);
const fp = keyFingerprint(publicKey) ?? "(not a valid key)";
const now = new Date().toISOString();
const pinned = data.keys[id];
if (!pinned) {
data.keys[id] = { publicKey, fingerprint: fp, firstSeen: now, lastSeen: now };
save(data);
return "new";
}
if (pinned.publicKey === publicKey) {
pinned.lastSeen = now;
save(data);
return "pinned";
}
const accepted = accept === true || (Array.isArray(accept) && accept.some((a) => a.toLowerCase() === subject.toLowerCase()));
if (!accepted) throw new KeyChangedError(subject, pinned.fingerprint, fp);
data.keys[id] = { publicKey, fingerprint: fp, firstSeen: now, lastSeen: now, replaced: pinned.fingerprint };
save(data);
return "changed";
}
/** Record our OWN new key after a rotation, so our own machine does not flag it. */
export function repinKey(apiUrl: string, subject: string, publicKey: string): void {
const data = load();
const id = pinId(apiUrl, subject);
const now = new Date().toISOString();
const previous = data.keys[id];
data.keys[id] = { publicKey, fingerprint: keyFingerprint(publicKey) ?? "", firstSeen: now, lastSeen: now, ...(previous && previous.publicKey !== publicKey ? { replaced: previous.fingerprint } : {}) };
save(data);
}

View file

@ -55,9 +55,13 @@ async function resolveVaultId(ctx: TeamContext, slug: string, vault: string, cre
/** Fetch (or, for a brand-new vault, mint) the vault DEK, decrypting nothing yet. */
async function acquireDek(ctx: TeamContext, slug: string, vault: string, vaultId: string, allowMint: boolean): Promise<string> {
return (await acquireDekVersioned(ctx, slug, vault, vaultId, allowMint)).dek;
}
async function acquireDekVersioned(ctx: TeamContext, slug: string, vault: string, vaultId: string, allowMint: boolean): Promise<{ dek: string; keyVersion?: number }> {
try {
const { wrappedDek } = await ctx.client.getMyGrant(vaultId);
return unwrapVaultKey(wrappedDek, ctx.identity.keys);
const { wrappedDek, keyVersion } = await ctx.client.getMyGrant(vaultId);
return { dek: await unwrapVaultKey(wrappedDek, ctx.identity.keys), keyVersion };
} catch (error) {
if (!(error instanceof TeamApiError) || error.status !== 403) throw error;
if (ctx.identity.keyKind === "machine") {
@ -81,7 +85,7 @@ async function acquireDek(ctx: TeamContext, slug: string, vault: string, vaultId
const dek = await generateVaultKey();
const wrapped = await wrapVaultKey(dek, ctx.identity.keys.publicKey);
await ctx.client.putGrant(vaultId, ctx.identity.email, wrapped);
return dek;
return { dek };
}
}
@ -158,14 +162,18 @@ export const teamProvider: CredentialProvider = {
if (upsertNames.length === 0 && input.deletes.length === 0) return results;
const dek = upsertNames.length > 0 ? await acquireDek(ctx, slug, vault, vaultId, true) : undefined;
const acquired = upsertNames.length > 0 ? await acquireDekVersioned(ctx, slug, vault, vaultId, true) : undefined;
const dek = acquired?.dek;
const encrypted: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }> = [];
for (const name of upsertNames) {
const sealed = await encryptValue(input.upserts[name], dek!);
encrypted.push({ name, nonce: sealed.nonce, ciphertext: sealed.ciphertext, fingerprint: fingerprintValue(input.upserts[name]) });
}
const { applied } = await ctx.client.putSecrets(vaultId, encrypted, input.deletes);
// The key version pins this write to the vault key it was encrypted under: a
// re-key landing in between makes the server refuse it rather than store
// ciphertext nobody can open. Re-running the push picks up the new key.
const { applied } = await ctx.client.putSecrets(vaultId, encrypted, input.deletes, acquired?.keyVersion);
const appliedSet = new Set(applied);
for (const name of upsertNames) results.push({ key: name, applied: appliedSet.has(name) });
for (const name of input.deletes) results.push({ key: name, applied: appliedSet.has(name) });