Skip to content

Protect all persisted account credentials from plaintext storage - #698

Merged
micahflee merged 9 commits into
mainfrom
issue-671-credential-storage
Sep 11, 2026
Merged

micahflee merged 9 commits into
mainfrom
issue-671-credential-storage

Conversation

@micahflee

Copy link
Copy Markdown
Member

Fixes #671.

Cyd serialized the X-to-Bluesky migration's OAuth state and session — access and refresh tokens plus a private DPoP key — into the account's plaintext SQLite config table, and the shared SQL debug logger echoed those values into logs and error reports. This adds one credential facility for the desktop and moves that material into it.

What changed

src/credentials/ — one store for account-control credentials. accountCredentials(accountID) returns a per-account vault encrypted through Electron safeStorage, written owner-only to <settings>/credentials/account-{id}.json, outside every account database, media directory, and Cyd archive. Callers name a credential and nothing else. When no facility can protect a value it throws CredentialStoreUnavailableError rather than falling back to plaintext.

Backend detection. Keychain on macOS, OS-backed protection on Windows, libsecret or KWallet on Linux. basic_text is the single deliberate fallback, allowed only because a Linux desktop without a keyring is common, and only with disclosure. A password store Cyd does not recognize is refused, not guessed at. The selection is logged at startup and surfaced in a warning bar that names the backend.

OAuth material out of SQLite. The migration's state and session now live in the vault. setConfig throws if a credential key is written to the config table, so it cannot come back.

Legacy sweep. Opening an account database migrates old plaintext rows into the vault, deletes them, then checkpoints the WAL and vacuums so the deleted bytes do not survive. When the credentials cannot be protected it destroys them and clears the stored DID, so the account stops claiming a connection whose session is gone.

Redaction. SQL statement parameters reach debug logs and error reports as <string:42> / <buffer:1024>, never as values. The OAuth state and the callback query string that carries the authorization code are no longer logged.

Revoke before discard. Disconnecting and deleting an account both ask the authorization server to invalidate the session first; a failed revocation never blocks a deletion the user asked for.

Docs. docs/security/credential-store.md covers the threat model, the platform table, and a manual verification checklist for macOS Keychain, Windows, GNOME/libsecret, KDE/KWallet, the basic_text fallback, an unrecognized store, and the upgrade path. ADR 0033 records the decisions; CONTEXT.md gains the two terms.

Testing

npm test: 1265 tests passing, no type errors. npm run lint clean. New coverage for protected storage, the vault format, migration including WAL remnants, redaction, deletion, unavailable and unrecognized backends, and the disclosed Linux fallback.

Judgement calls worth a second opinion

  • The warning bar is dismissible for the session and reappears next launch, matching Cyd's other bars. A reviewer could reasonably want a security disclosure that cannot be silenced.
  • Parameter redaction is blanket rather than limited to secret-bearing statements. A key-based filter only redacts secrets someone remembered to name, and the other parameters are mostly tweet text and DMs — but it does cost debuggability in support bundles.
  • Refusing an unrecognized Linux password store will block the migration for anyone on an exotic store that may in fact be fine.

(This was written by an LLM.)

🤖 Generated with Claude Code

micahflee and others added 3 commits September 10, 2026 13:56
Cyd serialized the X-to-Bluesky migration's OAuth state and session,
which carry access and refresh tokens plus a private DPoP key, into the
account's plaintext SQLite config table, and the SQL debug logger echoed
those values into logs and error reports.

Introduce one credential facility for the desktop:

- src/credentials keeps per-account vaults encrypted through Electron's
  safeStorage, outside every account database, media directory, and
  archive, owner-only on disk. It refuses to persist anything when no
  OS facility is available rather than falling back to plaintext.
- Detect the platform backend honestly: Keychain on macOS, OS-backed
  protection on Windows, libsecret or KWallet on Linux, with Chromium's
  basic_text and unrecognized stores treated as unprotected, logged at
  startup and disclosed in a dismissible in-app warning bar.
- Move the migration's OAuth state and session into the vault, and
  refuse credential keys in the config table so they cannot come back.
- Sweep legacy plaintext rows when an account database opens: migrate
  what can be protected, discard what cannot, then checkpoint the WAL
  and vacuum so the deleted bytes do not survive.
- Redact SQL statement parameters to type and length in debug logs and
  in the errors that reach error reports.
- Delete an account's whole credential namespace when the account is
  deleted, alongside the existing disconnect revocation.

Document the threat model, platform behavior, and a manual verification
checklist in docs/security/credential-storage.md.

Fixes #671

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Standards axis:

- Use the glossary's term throughout: "Cyd credential store", not
  "credential storage". Renames the error, the availability check, the
  renderer bar, and its i18n namespace.
- Stop logging credential names, which can carry a Bluesky DID (ADR
  0029), and stop logging the OAuth state and the callback query string
  that carries the authorization code.
- Record the new decisions as ADR 0033 rather than only in docs/security.
- Move the IPC definition to src/credentials/ipc.ts, matching how the
  account modules are laid out.
- Name the credential keys once in src/credentials/keys.ts instead of
  three times across the store, the sweep, and the config guard.
- Replace the (namespace, key) pair threaded through six functions with
  accountCredentials(accountID), so callers name a credential and
  nothing else.
- Share one safeStorage test double through the electron fixture.
- Validate the vault version on read, which also fixes a spread that
  defeated its own default.

Spec axis:

- Revoke before discarding: deleting an account now asks the
  authorization server to invalidate the Bluesky session first, and a
  failed revocation never blocks the deletion.
- When the sweep discards credentials it could not protect, clear the
  stored DID too, so the account stops claiming a connection whose
  session is gone.
- Refuse to persist to an unrecognized Linux password store. basic_text
  is the only sanctioned fallback; Cyd cannot vouch for a store it
  cannot name.
- Give each disclosure its own words, and say that Chromium keeps
  persisting X login cookies either way, rather than implying Cyd stores
  nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Manual review on Linux found the basic_text fallback unreachable.
Electron's safeStorage.isEncryptionAvailable() returns false whenever
Chromium falls back to the basic_text password store, unless the app
calls setUsePlainTextEncryption(true), which Cyd does not. That is
exactly the keyring-less case the fallback existed for, so
getCredentialProtection() short-circuited to "unavailable" and never
reached its basic_text branch. On a Linux desktop with no keyring the
migration could not connect at all, and the legacy sweep destroyed a
working session and cleared blueskyDID on first launch after upgrade.
The unit tests could not catch it: the shared safeStorage double pinned
isEncryptionAvailable to true while overriding only the backend name,
describing a machine that cannot exist.

Cyd now always persists, and discloses when it cannot protect:

- Vault version 2 records "protected" per value. safeStorage ciphertext
  where the OS offers a keyring, the credential itself where it does
  not. Per value rather than per vault, so installing a keyring protects
  everything written afterwards without invalidating what is on disk.
  Version 1 vaults still read. Owner-only permissions are unchanged.
- getCredentialProtection() decides only whether the OS protects, never
  whether to persist. It reads the Linux password store even when
  encryption is unavailable, so the warning bar can name it, and it
  treats a keyring-backed name with no working encryption as
  unprotected: a backend name is not a promise.
- The legacy sweep always migrates. The rows still leave the config
  table, the WAL, and the free pages, which is the real improvement
  without a keyring, because the vault is owner-only and outside the
  archives, exports, and error reports the config table was not. It no
  longer discards credentials or clears the DID.
- Drop CredentialStoreUnavailableError, isCredentialStoreAvailable, and
  CredentialProtection.canPersist. Nothing refuses any more, and a field
  that is always true invites a caller to branch on it.
- The unrecognized and unavailable warnings said Cyd would not save the
  connection. Both now say the credentials are stored without
  operating-system protection and that anyone who can read the files can
  use them.

Cyd stores plaintext itself rather than calling
setUsePlainTextEncryption(true). Chromium's basic_text encrypts with a
hard-coded key: the same exposure, but it would write base64 that looks
encrypted and record protected: true.

ADR 0033 is rewritten and renamed, and docs/security/credential-store.md
follows, including the Electron coupling that made the original design
look correct.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@micahflee

Copy link
Copy Markdown
Member Author

Manual verification harness (Linux done, macOS/Windows open)

This exercises the real credential code against the real OS keyring, which the unit tests cannot do: the shared safeStorage double pins isEncryptionAvailable to true, and that is precisely what hid the basic_text bug fixed in 09895f8.

It uses a throwaway settings directory via TEST_MODE=1 / TEST_SETTINGS_PATH, so it never touches a real Cyd profile. It checks backend detection, vault format and permissions, encryption vs. disclosed plaintext, the config-table guard, SQL parameter redaction, and the legacy sweep including WAL and -shm remnants with a canary token.

Running it

Save as /tmp/cyd-manual/harness.ts, then from the repo root:

# node_modules must resolve from the harness directory
ln -sfn "$PWD/node_modules" /tmp/cyd-manual/node_modules

./node_modules/.bin/esbuild /tmp/cyd-manual/harness.ts \
  --bundle --platform=node --format=cjs --target=node20 \
  --external:electron --external:better-sqlite3 --external:electron-log \
  --outfile=/tmp/cyd-manual/harness.js

rm -rf /tmp/cyd-manual/profile && mkdir -p /tmp/cyd-manual/profile/settings
TEST_MODE=1 TEST_SETTINGS_PATH=/tmp/cyd-manual/profile/settings \
  ./node_modules/.bin/electron --no-sandbox \
  --user-data-dir=/tmp/cyd-manual/profile /tmp/cyd-manual/harness.js

Exit code is non-zero if any check fails. Add --password-store=basic (Linux only) for the unprotected path.

Linux results on 09895f8

Mode Reported Result
GNOME + gnome-keyring gnome_libsecret, osProtected: true all pass, vault ciphertext, no disclosure
--password-store=basic basic_text, osProtected: false all pass, vault plaintext as disclosed, session migrated, DID kept
dbus-run-session, no keyring basic_text, osProtected: false identical to above

In every mode the legacy canary is greppable in the db/WAL before the sweep and absent from .sqlite3, -wal, and -shm after.

For macOS and Windows

The --password-store modes are Linux-only, but everything else is portable. Worth confirming there, since I could not exercise it on Linux:

  • osProtected on macOS/Windows is inferred from process.platform plus isEncryptionAvailable() alone, with no backend name to cross-check. Confirm the vault entries are "protected": true and hold no readable token.
  • On Windows, supportsOwnerOnlyPermissions() is false, so the 600/700 checks are skipped by design — the harness still asserts them on POSIX only.
  • Copy a vault to a second OS user and confirm it does not decrypt (checklist item in docs/security/credential-store.md).

harness.ts

Full source
import fs from "fs";
import path from "path";
import { app, safeStorage } from "electron";
import Database from "better-sqlite3";

import {
  getCredentialProtection,
  accountCredentials,
  credentialsDirectoryPath,
  sweepLegacyOAuthCredentials,
  isCredentialKey,
} from "/home/user/code/lockdown-systems/cyd/src/credentials";
import { redactSQLParams } from "/home/user/code/lockdown-systems/cyd/src/database/common";
import { setConfig } from "/home/user/code/lockdown-systems/cyd/src/database/config";

const ACCOUNT = 9001;
// Distinctive canaries so a grep hit is unambiguous.
const SESSION_CANARY =
  '{"refresh_token":"CANARY-REFRESH-8f3a1c","dpopJwk":{"d":"CANARY-DPOP-PRIVATE-KEY-77b2"}}';
const STATE_CANARY = '{"verifier":"CANARY-PKCE-VERIFIER-42d9"}';

const out: string[] = [];
const ok = (label: string, pass: boolean, detail = "") =>
  out.push(`${pass ? "PASS" : "FAIL"}  ${label}${detail ? " :: " + detail : ""}`);
const info = (label: string, detail: string) => out.push(`INFO  ${label} :: ${detail}`);

const fileMode = (p: string) => (fs.statSync(p).mode & 0o777).toString(8);

const grepFile = (p: string, needles: string[]): string[] => {
  if (!fs.existsSync(p)) return [];
  const buf = fs.readFileSync(p);
  const hay = buf.toString("latin1");
  return needles.filter((n) => hay.includes(n));
};

const run = async () => {
  await app.whenReady();

  // ---------- A. Backend detection ----------
  const protection = getCredentialProtection();
  info("protection", JSON.stringify(protection));
  info(
    "safeStorage.isEncryptionAvailable()",
    String((() => { try { return safeStorage.isEncryptionAvailable(); } catch (e) { return "threw: " + e; } })()),
  );
  info(
    "safeStorage.getSelectedStorageBackend()",
    String((() => { try { return safeStorage.getSelectedStorageBackend?.(); } catch (e) { return "threw: " + e; } })()),
  );

  const creds = accountCredentials(ACCOUNT);

  // ---------- B. Vault behavior ----------
  let setThrew: Error | null = null;
  try {
    creds.set("blueskySessionStore-did:plc:canary", SESSION_CANARY);
    creds.set("blueskyStateStore-canary", STATE_CANARY);
  } catch (e) {
    setThrew = e as Error;
  }

  const vaultFile = path.join(credentialsDirectoryPath(), `account-${ACCOUNT}.json`);

  ok("set() never refuses, whatever the backend", setThrew === null, setThrew?.message ?? "");
  ok("vault file exists", fs.existsSync(vaultFile), vaultFile);
  if (fs.existsSync(vaultFile)) {
    ok("vault file mode is 600", fileMode(vaultFile) === "600", fileMode(vaultFile));
    ok(
      "vault dir mode is 700",
      fileMode(credentialsDirectoryPath()) === "700",
      fileMode(credentialsDirectoryPath()),
    );
    const raw = fs.readFileSync(vaultFile, "utf-8");
    const parsed = JSON.parse(raw);
    const entry = parsed.credentials["blueskySessionStore-did:plc:canary"];
    ok("vault is version 2", parsed.version === 2, String(parsed.version));
    ok(
      "entry records whether it is protected",
      typeof entry?.protected === "boolean",
      JSON.stringify(entry?.protected),
    );
    ok(
      "entry protection matches the reported backend",
      entry?.protected === protection.osProtected,
      `entry.protected=${entry?.protected} osProtected=${protection.osProtected}`,
    );

    const hits = grepFile(vaultFile, [
      "CANARY-REFRESH-8f3a1c",
      "CANARY-DPOP-PRIVATE-KEY-77b2",
      "CANARY-PKCE-VERIFIER-42d9",
    ]);
    if (protection.osProtected) {
      ok("protected vault contains NO plaintext credential", hits.length === 0, hits.join(","));
    } else {
      // The disclosed case: the credential really is in the clear, and the
      // warning bar and startup log say so.
      ok("unprotected vault stores the credential in the clear, as disclosed", hits.length > 0, hits.join(","));
      ok("disclosure is required for this backend", protection.disclosureRequired === true);
      ok(
        "the backend is still named, so the warning can identify it",
        protection.rawBackend !== null || protection.backend !== "unknown",
        `backend=${protection.backend} rawBackend=${protection.rawBackend}`,
      );
    }
    info("vault file contents (first 220 chars)", raw.slice(0, 220));
  }
  ok(
    "get() round-trips the session",
    creds.get("blueskySessionStore-did:plc:canary") === SESSION_CANARY,
  );
  ok("keys() lists both credentials", creds.keys().length === 2, creds.keys().join(","));
  ok(
    "vault lives outside the account directory",
    credentialsDirectoryPath().endsWith(path.join("settings", "credentials")),
    credentialsDirectoryPath(),
  );

  // ---------- C. config table guard ----------
  let guardThrew: Error | null = null;
  try {
    setConfig("blueskySessionStore-did:plc:canary", SESSION_CANARY, new Database(":memory:"));
  } catch (e) {
    guardThrew = e as Error;
  }
  ok("setConfig refuses a credential key", guardThrew !== null, guardThrew?.message ?? "did not throw");
  ok("isCredentialKey(blueskyDID) is false (identifier, not credential)", !isCredentialKey("blueskyDID"));

  // ---------- D. SQL parameter redaction ----------
  const redacted = redactSQLParams([SESSION_CANARY, 42, null, Buffer.from(SESSION_CANARY)]);
  ok(
    "redactSQLParams hides string and buffer values",
    !JSON.stringify(redacted).includes("CANARY"),
    JSON.stringify(redacted),
  );

  // ---------- E. Legacy sweep, with real WAL remnants ----------
  const legacyDir = path.join(process.env.TEST_SETTINGS_PATH!, `account-${ACCOUNT}`);
  fs.mkdirSync(legacyDir, { recursive: true });
  const legacyDB = path.join(legacyDir, "data.sqlite3");
  const db = new Database(legacyDB);
  db.pragma("journal_mode = WAL");
  db.exec("CREATE TABLE config (id INTEGER PRIMARY KEY, key TEXT, value TEXT)");
  db.prepare("INSERT INTO config (key, value) VALUES (?, ?)").run(
    "blueskySessionStore-did:plc:canary",
    SESSION_CANARY,
  );
  db.prepare("INSERT INTO config (key, value) VALUES (?, ?)").run(
    "blueskyStateStore-canary",
    STATE_CANARY,
  );
  // The old code blanked rows instead of deleting them.
  db.prepare("INSERT INTO config (key, value) VALUES (?, ?)").run("blueskyStateStore-tombstone", "");
  db.prepare("INSERT INTO config (key, value) VALUES (?, ?)").run("blueskyDID", "did:plc:canary");
  db.prepare("INSERT INTO config (key, value) VALUES (?, ?)").run("keepMe", "not-a-credential");

  const needles = ["CANARY-REFRESH-8f3a1c", "CANARY-DPOP-PRIVATE-KEY-77b2", "CANARY-PKCE-VERIFIER-42d9"];
  const preHits = [
    ...grepFile(legacyDB, needles),
    ...grepFile(legacyDB + "-wal", needles),
    ...grepFile(legacyDB + "-shm", needles),
  ];
  ok("BEFORE sweep: canary is readable in the plaintext db/WAL (setup sanity)", preHits.length > 0, preHits.join(","));

  creds.deleteAll(); // start the sweep from an empty vault
  const sweep = sweepLegacyOAuthCredentials(db, ACCOUNT);
  info("sweep result", JSON.stringify(sweep));

  const remainingKeys = (db.prepare("SELECT key FROM config").all() as { key: string }[]).map((r) => r.key);
  ok("legacy credential rows are gone from config", !remainingKeys.some((k) => isCredentialKey(k)), remainingKeys.join(","));
  ok("blank tombstone row is also gone", !remainingKeys.includes("blueskyStateStore-tombstone"));
  ok("non-credential config row survives", remainingKeys.includes("keepMe"));

  const postHits = [
    ...grepFile(legacyDB, needles).map((h) => "db:" + h),
    ...grepFile(legacyDB + "-wal", needles).map((h) => "wal:" + h),
    ...grepFile(legacyDB + "-shm", needles).map((h) => "shm:" + h),
  ];
  ok("AFTER sweep: no canary in db, -wal, or -shm", postHits.length === 0, postHits.join(","));

  ok("sweep moved both credentials", sweep.moved.length === 2, JSON.stringify(sweep.moved));
  ok("sweep discarded nothing", sweep.discarded.length === 0, JSON.stringify(sweep.discarded));
  ok(
    "migrated session is readable from the vault",
    creds.get("blueskySessionStore-did:plc:canary") === SESSION_CANARY,
  );
  ok("blueskyDID is kept, so the account stays connected", remainingKeys.includes("blueskyDID"));

  // Idempotency
  const second = sweepLegacyOAuthCredentials(db, ACCOUNT);
  ok("second sweep is a no-op", second.moved.length === 0 && second.discarded.length === 0);
  db.close();

  // ---------- F. Deletion ----------
  creds.deleteAll();
  ok("deleteAll removes the vault file", !fs.existsSync(vaultFile));

  console.log("\n===== CYD CREDENTIAL MANUAL CHECK =====");
  console.log(out.join("\n"));
  console.log("===== END =====\n");
  app.exit(out.some((l) => l.startsWith("FAIL")) ? 1 : 0);
};

run().catch((e) => {
  console.error("HARNESS ERROR", e);
  app.exit(2);
});

(This comment was written by an LLM.)

🤖 Generated with Claude Code

micahflee and others added 3 commits September 10, 2026 16:24
openCydURL() logged the whole callback URL, and the callback handler
logged url.search again, both at info level. That query string carries
the OAuth authorization code, which is an account-control credential,
and dev builds write info to disk, so the code landed in main.log
verbatim. The "Invalid Cyd URL" dialog printed it on screen too, on
exactly the path that fails today.

Log and display the URL without its query string. The renderer half of
this was already fixed; this is the main-process half, which the
credential work missed because nothing greps the logs.

Unreachable in practice until #699 is fixed, since the callback never
arrives, but live the moment it is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Manual testing on Linux found the warning bar below the fold. It was
position: relative, so it sat in the document flow after TabsView and
the user had to scroll the whole window to reach it. A security
disclosure nobody sees is not a disclosure.

Anchor both bottom bars in one .bottom-bars flex column, so they stack
instead of overlapping however far their text wraps. The updates bar
keeps its right-hand alignment but is laid out in flow inside the stack,
rather than positioning itself absolutely, which means no pixel offset
to get wrong when the disclosure wraps to another line. The container
ignores pointer events so it does not swallow clicks in the empty space
beside a bar.

Shorten the three disclosures by about 40%. Each still says what is
wrong, what the risk is, and how to fix it, and the bar still names the
password store:

  No system keyring found, so Cyd stores your logins unencrypted.
  Anyone who can read your files can use them. Install GNOME Keyring
  (libsecret) or KWallet, then restart Cyd.

Verified in the app on a real profile running with --password-store=basic:
the bar is visible without scrolling, names basic_text, dismisses, and
returns on the next launch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Manual review on Windows found two claims in the threat model that do not
hold there, both invisible to the unit tests.

supportsOwnerOnlyPermissions() is false on win32, so the store never
chmods and the vault inherits its directory's ACL. Measured with icacls:
under the default %APPDATA% profile that inheritance is owner-only (the
user, SYSTEM, Administrators), but a profile placed with --user-data-dir
somewhere permissive, such as C:\temp, inherits BUILTIN\Users:(RX) and
Authenticated Users:(M) and is readable and writable by every local
account. On POSIX the explicit chmod clamps this back wherever the
profile sits; on Windows nothing does. The threat model stated 0700/0600
without qualification.

The Windows checklist also asked for the wrong experiment. safeStorage
on Windows is not a separate OS vault: Chromium encrypts with its own
random AES-256-GCM key, hands Cyd a v10 blob for the vault, and keeps
that key in the profile's Local State wrapped with DPAPI. Both halves
are files inside the profile, so DPAPI is the only barrier. Copying the
vault alone to a second account fails merely because that profile minted
a different AES key, which would happen even with DPAPI doing nothing.
The check now copies Local State too.

Restarts were never covered. Local State is written at shutdown, so a
profile killed before its first clean quit loses the AES key and every
entry in the vault; that is now a checklist item, alongside the Windows
results this review confirmed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R8TQnZEgvPamkxnqNrHkRB
@micahflee

micahflee commented Sep 11, 2026 •

Copy link
Copy Markdown
Member Author

Windows manual verification

Windows 11 Pro 26200, Electron 41.7.1, branch at 61ec7f55. Run against the real
safeStorage, not the shared test double, using a Windows port of the harness from
the Linux comment.

npm run lint clean. npm run test:windows: 1265 passed, 2 failed — both are
EPERM on fs.rmSync of a temp directory in
src/bluesky_archive_v2/__tests__/canonicalFixtures.test.ts, a file this branch does
not touch and which is byte-identical to main. It fails in isolation too, so it is a
pre-existing Windows-only issue, unrelated to this PR. Worth noting separately that
npm run test:windows exits 0 even with failing tests.

Confirmed

  • Backend detection reports exactly what the platform table claims:
    {"platform":"win32","backend":"windows_dpapi","rawBackend":null,"osProtected":true}.
    getSelectedStorageBackend() is undefined off Linux, so rawBackend: null is
    correct rather than a detection gap.
  • Vault is version 2, entries are "protected": true, and the stored value is a real
    v10 AES-256-GCM blob: it holds no readable fragment of the canary, its length
    differs from the plaintext, and encrypting the same value twice gives different
    ciphertext.
  • The legacy sweep migrates on Windows and the canary is absent from .sqlite3,
    -wal, and -shm afterwards. Second sweep is a no-op, blueskyDID is kept,
    non-credential rows survive.
  • setConfig refuses credential keys; redactSQLParams hides strings and buffers.
  • An entry that cannot be decrypted is logged, dropped, and leaves the rest of the
    vault intact.

Finding 1 — the 0700/0600 claim does not hold on Windows, and the gap is location-dependent

supportsOwnerOnlyPermissions() is false on win32, so the store never chmods and the
vault inherits whatever ACL its directory carries. That is fine at the default location
and not fine everywhere.

Default profile, %APPDATA%\Cyd Dev\settings\credentials\ — owner-only in practice:

NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
BUILTIN\Administrators:(I)(OI)(CI)(F)
DESKTOP-6R6E9O0\user:(I)(OI)(CI)(F)

The same tree under C:\temp\..., which is what --user-data-dir=C:\temp\cyd-walkthrough
produces:

BUILTIN\Administrators:(I)(OI)(CI)(F)
NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
BUILTIN\Users:(I)(OI)(CI)(RX)
NT AUTHORITY\Authenticated Users:(I)(M)
NT AUTHORITY\Authenticated Users:(I)(OI)(CI)(IO)(M)

Every local account can read the vault file there, and Authenticated Users can modify
it. On POSIX the explicit chmod 0600 clamps this back wherever the profile is put; on
Windows nothing does. The threat model's "the vault directory is 0700 and each vault
file 0600" was therefore stated without platform qualification and is not true here.

Documentation fix in b4719266, per the maintainer's call: the threat model now states
the Windows guarantee comes from inherited NTFS ACLs plus DPAPI, holds at the default
location, and can be lost by a permissive --user-data-dir. No code change — this is
the platform behaving as the ADR describes, claimed more precisely.

Finding 2 — the checklist's cross-user test does not test what it says

This one changes the check rather than the code.

On Windows safeStorage is not a separate OS vault the way the Keychain is. Chromium
encrypts with its own random AES-256-GCM key and hands Cyd a v10 blob to store; that
key lives in the profile's Local State under os_crypt.encrypted_key, wrapped with
DPAPI. Verified directly: the blob is prefixed with the ASCII string DPAPI, carries the
canonical provider GUID d08c9ddf-0115-d111-8c7a-00c04fc297eb, and CryptUnprotectData
returns a 32-byte key.

So both halves are ordinary files inside the profile directory, and DPAPI is the only
barrier. Two experiments, same OS user, fresh profile each time:

Copied into the new profile Result
vault only does not decrypt — could not decrypt a credential for account 9001, discarding it, entry dropped
vault + Local State decrypts fine, returns the original canary

The checklist currently says "copy the vault to another Windows user account and confirm
Cyd there cannot decrypt it". That passes for the wrong reason: the receiving profile
minted a different AES key, which would happen even if DPAPI were doing nothing at all.
The test that actually exercises DPAPI must copy Local State too. Checklist corrected
in this branch.

Finding 3 — a credential written before the first clean quit is lost

Local State is written during shutdown. A profile killed before it ever quits cleanly
never persists the AES key, so the next launch mints a new one and every vault entry
becomes undecryptable and is dropped. Confirmed both ways: app.exit() left no Local State and lost the credential; a graceful quit wrote it and the credential survived the
restart.

Recoverable — the user reconnects — and the blast radius is only the first session. But
nothing in the tests or the checklist covered a restart at all, so it is now a checklist
item.

Still outstanding

  • Cross-user decryption — done, see the follow-up comment. Confirmed against a
    second local account: both files readable, DPAPI refused the key. Checklist updated in
    53f19a10.
  • Live OAuth connect / disconnect / delete, still blocked behind Bluesky OAuth callback never reaches the desktop app: redirect scheme and path do not match what Cyd registers #699. The credential
    write path itself is exercised by the harness against real safeStorage, but
    revocation-at-the-server on disconnect remains unverified on every platform.
  • Warning bar absence in the running app. Asserted indirectly: disclosureRequired
    is false on this machine.

(This comment was written by an LLM.)

Confirmed against a second local account on the same machine. Both the
vault and the profile's Local State were readable by that account, and
DPAPI still refused the wrapped AES key with "Key not valid for use in
specified state", so the v10 ciphertext is undecryptable there.

This is the one place in the checklist where protection at rest is shown
adversarially rather than inferred, and it now tests the right thing: a
readable file and an unusable credential, which is the guarantee Windows
actually offers, rather than a vault that failed to decrypt only because
the receiving profile had minted a different key.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R8TQnZEgvPamkxnqNrHkRB
@micahflee

Copy link
Copy Markdown
Member Author

Cross-user decryption: confirmed

The last outstanding Windows item is now done, in the corrected form — vault and
Local State copied together, so that DPAPI is the only thing left to stop the second
account. Run from a throwaway local user on the same machine:

Running as: DESKTOP-6R6E9O0\cydtest

--- 1. File readability (NTFS permissions) ---
  READABLE  account-9001.json  (256 chars)
  READABLE  Local State  (490 chars)

--- 2. DPAPI unwrap of os_crypt.encrypted_key ---
  key blob prefix : DPAPI   (expected: DPAPI)
  key blob length : 283 bytes

  RESULT: DPAPI refused to unwrap the key.
  Exception calling "Unprotect" with "3" argument(s): "Key not valid for use in
  specified state."

Both halves of the credential were readable by the second account — the staging
directory sat under C:\temp, which is exactly the permissive case from Finding 1 — and
the credential was still unusable. Key not valid for use in specified state is DPAPI's
cross-user refusal.

The positive control matters here: run as the owning user, the same script unwraps the
key and returns 32 bytes. So the failure above is DPAPI's per-user scope, not a malformed
blob or a missing file.

What this establishes: on Windows the vault's protection at rest is real, and it rests
on DPAPI rather than on file permissions. A readable file and an unusable credential is
the guarantee this platform offers, which is now what the threat model says. Checklist
item recorded in 53f19a10.

What it does not establish: nothing about an attacker who is already the user, or who
is an administrator able to reach the user's DPAPI master key. Both were already out of
scope in the threat model and remain so.

Still outstanding on Windows, unchanged: the live connect / disconnect / delete walkthrough
behind #699, including whether disconnect actually revokes at the authorization server
rather than only forgetting locally. That one is open on every platform.

(This comment was written by an LLM.)

Manual verification on Windows against a real Bluesky session. This is
the first time revoke-before-discard has been exercised on any platform,
and it holds: disconnecting revokes at the authorization server, and the
refresh token is rejected with "Invalid refresh token" on the next
attempt, so a copied session cannot be renewed.

Two things the threat model did not say, both found while checking it.

Revocation kills the grant, not the tokens already minted from it. An
access token issued before the disconnect keeps working until it
expires, an hour at most on Bluesky, because an authorization server
cannot retract one it has already signed. A check that reuses the access
token therefore shows a session that looks alive when the grant is
already dead, which is how this was nearly misread; the check has to
back-date the saved token set's expiry to force the refresh path.

A failed revocation is not detectable locally. @atproto/oauth-client
discards the outcome of the revocation request, so Cyd cannot log it,
retry it, or tell the user. A disconnect looks identical whether the
server honored it or never received it, which is worth stating in a
document that otherwise presents revocation as unconditional.

The connect item is checked off as well: the vault holds only the
session entry once the callback completes, and the account database's
config table holds blueskyDID and nothing else. Deleting an account
stays unchecked, but is noted as reaching the same disconnect() rather
than being a second implementation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R8TQnZEgvPamkxnqNrHkRB
@micahflee

Copy link
Copy Markdown
Member Author

Disconnect does revoke server-side — with two caveats worth documenting

Ran the live connect/disconnect flow on Windows against a real Bluesky account,
using the blueskyCallback workaround from #699. This is the first time
revoke-before-discard has been exercised on any platform, and it holds.
Recorded in 43834bea.

Connect

  • Vault appears at <settings>\credentials\account-1.json, version 2, one entry,
    protected: true.
  • Ciphertext is a real v10 AES-256-GCM blob (1213 bytes); no refresh_token,
    dpopJwk, or access_token anywhere in the file.
  • The OAuth state entry is already gone after a successful callback; only the
    session remains.
  • The X account database's config table holds exactly one row: blueskyDID.
  • icacls on the real default profile: SYSTEM, Administrators, and the user.
    No Users, no Authenticated Users.
  • No warning bar, and the app logs
    {"platform":"win32","backend":"windows_dpapi","rawBackend":null,"osProtected":true}.

Worth noting the config-table guard is stronger than a grep can show. There is
exactly one write path into any config table in the codebase —
src/database/config.ts:49, inside setConfig — and it throws on
isCredentialKey(key) before reaching the SQL. Credentials cannot land there by
any code path, rather than merely not being there today.

Disconnect

Vault file removed, and the session really is revoked:

POST https://bsky.social/oauth/revoke  -> 400   (DPoP nonce challenge)
POST https://bsky.social/oauth/revoke  -> 200
...
POST https://bsky.social/oauth/token   -> 400   "Invalid refresh token"

Caveat 1: revocation kills the grant, not tokens already minted

This nearly produced a false finding. Immediately after disconnect, a saved
session still authenticated fine — com.atproto.server.getSession returned 200.
That is not a revocation failure: the access token was issued before the
disconnect and stays valid until expires_at (an hour at most on Bluesky),
because an authorization server cannot retract one it has already signed.

The grant was dead the whole time. Back-dating the saved token set's expiry to
force the refresh path gives Invalid refresh token at once. So a copied session
can never be renewed, but a copied access token keeps working for up to an
hour after disconnect.

Any future check of this must force the refresh path. Testing with the access
token will show a live session and mean nothing.

Caveat 2: a failed revocation is invisible to Cyd

@atproto/oauth-client's server agent discards the result outright:

async revoke(token) {
  try { await this.request('revocation', { token }); }
  catch { /* Don't care */ }
}

So signOut() resolves whether or not the server ever heard about it, and the
catch in BlueskyService.disconnect() never fires for a revocation failure.
Today's disconnect genuinely worked — but an offline or rejected one would look
identical locally: no error, no log line, no retry, no way to tell the user.

The threat model states revocation unconditionally, so I documented the gap
rather than changing behavior. Closing it means either working around the
library or deciding the silence is acceptable — a maintainer's call, and worth
a moment's thought given "Cyd revokes before it discards" is load-bearing for
the "credentials outliving the account" claim.

Still unchecked

Deleting an account. It is the same code path, not a second implementation:
revokeAccountConnections → revokeXBlueskyConnection → blueskyDisconnect()
→ the disconnect() verified above, returning early when no blueskyDID is
stored. The deletion itself was not exercised by hand.

(This comment was written by an LLM.)

The Keychain path had never been exercised. On macOS `osProtected` is
inferred from the platform plus `isEncryptionAvailable()` alone, with no
backend name to cross-check, so the checklist now asks for the Keychain
item itself and for its creation time to match the startup log line.

Note the two paths that differ on macOS and produce a false pass when
taken from the Linux instructions: the log lives under `~/Library/Logs`
rather than userData, and `--user-data-dir` does not redirect `dataPath`.

Also record that revoking at a Bluesky-hosted entryway can take fifteen
minutes to propagate, which is a second reason an access token outlives a
disconnect and makes a hand-tested revocation look like it failed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@micahflee

Copy link
Copy Markdown
Member Author

macOS (Keychain) passes — and the osProtected inference checks out

Ran the full script on macOS 26.6 (Darwin 25.6.0) against a real Bluesky
account, using the blueskyCallback workaround from #699. The Keychain path
had never been exercised before this. Recorded in 9a4c3c85.

No bugs found. Unlike the Linux pass, nothing needed fixing.

Setup: 99 files, 1269 tests, no type errors; lint clean.

The thing actually worth testing here

On macOS osProtected is inferred from process.platform plus
safeStorage.isEncryptionAvailable() alone — Chromium names no password store
off Linux, so rawBackend is null and there is nothing to cross-check the
claim against. The Keychain item is the only corroboration available:

0x00000007 <blob>="Cyd Dev Safe Storage"
"acct"<blob>="Cyd Dev Key"
"cdat"<timedate>="20260911164458Z"

cdat is 16:44:58Z = 09:44:58 local, the same second as

[2026-09-11 09:44:58.826] Credential protection: {"platform":"darwin","backend":"macos_keychain","rawBackend":null,"osProtected":true}

so this launch minted the key rather than inheriting one from an earlier
install. No warning bar, and no NOT protected at rest line.

Connect

  • Vault at <settings>/credentials/account-1.json, version 2, one entry,
    protected: true, mode 600 inside a 700 directory.
  • Decodes to v10\x81 6\xcdQ\xbaL\x98\x11\xfb… — opaque bytes, 1584 chars
    base64 to 1187 bytes. Not readable JSON, so protected: true is not lying.
  • config holds exactly blueskyDID. Zero token bytes in data.sqlite3,
    -wal, and -shm.
  • Grepping the entire profile and dataPath for dpopJwk/refresh_token,
    rather than the three named files: no match anywhere.

Legacy sweep

sweepLegacyOAuthCredentials: migrated 1 and discarded 0 legacy credentials for account 1

The canary arrives in the vault encrypted (protected: True, v10, 211
bytes), not merely relocated, and the real session beside it is untouched. The
blank tombstone row goes too. Canary count in .sqlite3, -wal, -shm: 0/0/0,
and nowhere else under dataPath either.

Disconnect and delete

Vault file gone both times. Worth noting it disappears rather than going
empty, by design — writeVault (src/credentials/store.ts:133) removes a vault
whose last entry went, "leaving the file behind would suggest credentials still
exist". Deleting the account then removed a synthetic probe entry, confirming
deleteAccount → deleteAll() (src/database/account.ts:261) fires
unconditionally, after the per-type branch, even for an account that never
connected.

Server-side revocation was not re-verified here. disconnect() lives in
BlueskyService with no darwin branch and was confirmed on Windows, so it is
platform-independent rather than untested. I could not find a connected-apps
screen for bsky.social accounts — atproto#4838
is still open, and bsky.social/account 400s.

Corrections to the walkthrough

Four things in the script are wrong on macOS, three of which produce a false
pass
rather than an obvious failure:

  1. The log is not under userData. electron-log writes to
    ~/Library/Logs/Cyd Dev/main.log whatever --user-data-dir says;
    <userData>/logs/main.log does not exist. That file is also shared across
    profiles, so tail -1 can hand you another run's result.
  2. --user-data-dir does not give you a throwaway dataPath. The profile
    still reads and writes the real ~/Documents/Cyd Dev, and the sweep test
    vacuums a database there. Back it up first.
  3. The disconnect log grep proves nothing. grep -i "revok\|signOut\|disconnect"
    matched one unrelated ATProto warning. There is no success line; the only
    local signal is the absence of BlueskyService.disconnect: Error revoking session, which rules out a network failure, not a refusal.
  4. The Keychain service is Cyd Dev Safe Storage on a dev build, not
    Cyd Safe Storage.

One finding for the threat model

Per OAuth Improvements,
Bluesky-hosted accounts revoke through an "entryway" service where propagation
takes up to fifteen minutes: refresh tokens die at once, access tokens do
not. A free-standing PDS revokes both immediately.

The doc explained the surviving access token solely as "an authorization server
cannot retract one it has already signed" — true, but the entryway lag is a
second, independent cause, and it is the one that makes a hand-tested disconnect
look like it failed. Now recorded alongside caveat 1 from the Windows pass.

@micahflee
micahflee merged commit 4192374 into main Sep 11, 2026
1 check passed
@micahflee
micahflee deleted the issue-671-credential-storage branch September 11, 2026 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Protect all persisted account credentials from plaintext storage

1 participant