diff --git a/apps/pwa/package.json b/apps/pwa/package.json index 4f04bd80..773b145f 100644 --- a/apps/pwa/package.json +++ b/apps/pwa/package.json @@ -3,7 +3,7 @@ "version": "0.1.1", "private": true, "type": "module", - "description": "LogicSRC credentials — Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.", + "description": "LogicSRC credentials \u2014 Express app on Postgres (@profullstack/libsql-pg): auth + end-to-end-encrypted team credential sharing.", "scripts": { "start": "bun src/server.mjs", "dev": "bun --watch src/server.mjs", @@ -13,10 +13,11 @@ "dependencies": { "@logicsrc/cli": "workspace:*", "@profullstack/coinpay-onboard": "0.3.1", - "@profullstack/key-rotation": "0.1.0", "@profullstack/footer": "latest", + "@profullstack/key-rotation": "0.1.0", "@profullstack/libsql-pg": "^0.1.4", "@profullstack/profile": "0.1.8", + "@profullstack/sealed-secrets": "0.1.1", "@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/server": "^14.0.3", "cookie-parser": "^1.4.7", diff --git a/apps/pwa/public/app-grant.js b/apps/pwa/public/app-grant.js new file mode 100644 index 00000000..c3ccd83a --- /dev/null +++ b/apps/pwa/public/app-grant.js @@ -0,0 +1,110 @@ +// App grant consent (/grant) and the /apps revoke buttons. +// +// The value is decrypted HERE with the member's identity key (same libsodium +// calls as vault.js), sealed with @profullstack/sealed-secrets to the app's +// per-user inbox key, and only the sealed text is posted. The identity key and +// the plaintext never leave this page. +import { createSealer } from "/vendor/sealed-secrets/index.js"; + +const STORE = "logicsrc.identityKey"; +const $ = (s) => document.querySelector(s); + +for (const b of document.querySelectorAll("[data-revoke]")) { + b.addEventListener("click", async () => { + if (!confirm("Revoke this key from the app? Rotate it too if it may have been used.")) return; + await fetch(`/api/v1/app-grants/${encodeURIComponent(b.dataset.revoke)}`, { method: "DELETE", credentials: "same-origin" }); + location.reload(); + }); +} + +const main = $("#grant"); +if (main) { + const status = $("#grant-status"); + const say = (m) => (status.textContent = m || ""); + const requestId = main.dataset.requestId; + const registered = main.dataset.publicKey; + const recipient = JSON.parse(main.dataset.recipient); + const returnUrl = main.dataset.returnUrl; + + const saved = () => { + try { + return sessionStorage.getItem(STORE) || localStorage.getItem(STORE) || ""; + } catch { + return ""; + } + }; + const parseKey = (raw) => { + let t = String(raw || "").trim(); + if (t.startsWith("{")) { + const j = JSON.parse(t); + t = (j.keys && j.keys.secretKey) || j.secretKey || ""; + } + return t.replace(/^["']|["']$/g, "").replace(/\s+/g, ""); + }; + const getJSON = async (url) => { + const res = await fetch(url, { credentials: "same-origin", headers: { accept: "application/json" } }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`); + return body; + }; + const postJSON = async (url, data) => { + const res = await fetch(url, { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(data) }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`); + return body; + }; + + async function openVault(vaultId, secretKeyB64) { + if (!window.sodium) throw new Error("The crypto library did not load. Reload the page."); + const na = await window.sodium.ready.then(() => window.sodium); + const V = na.base64_variants.ORIGINAL; + const sk = na.from_base64(secretKeyB64, V); + const pk = na.crypto_scalarmult_base(sk); + if (na.to_base64(pk, V) !== registered) throw new Error("That key does not match the identity registered for your account."); + const g = await getJSON(`/api/credshare/vaults/${encodeURIComponent(vaultId)}/grant`); + const dek = na.crypto_box_seal_open(na.from_base64(g.wrappedDek, V), pk, sk); + const body = await getJSON(`/api/credshare/vaults/${encodeURIComponent(vaultId)}/secrets`); + const out = {}; + for (const s of body.secrets || []) { + out[s.name] = { fingerprint: s.fingerprint, open: () => na.to_string(na.crypto_secretbox_open_easy(na.from_base64(s.ciphertext, V), na.from_base64(s.nonce, V), dek)) }; + } + return out; + } + + $("#grant-approve").addEventListener("click", async () => { + const btn = $("#grant-approve"); + btn.disabled = true; + try { + const vaultId = $("#grant-vault").value; + if (!vaultId) throw new Error("Pick a vault."); + const key = parseKey($("#grant-key").value || saved()); + if (!key) throw new Error("Paste your identity key."); + say("Opening the vault in this browser…"); + const secrets = await openVault(vaultId, key); + const sealer = createSealer({ app: recipient.app, scope: recipient.scope }); + const deliveries = []; + for (const row of document.querySelectorAll("tr[data-key]")) { + const keyName = row.dataset.key; + const source = row.querySelector("input[name=src]").value.trim(); + const s = secrets[source]; + if (!s) throw new Error(`No secret named ${source} in that vault.`); + // Same shape the app's own secrets page stores: sealed:v2:, field = the app's key name. + const entry = await sealer.sealToInbox(recipient.inbox_public_key, { [keyName]: s.open() }, recipient.user_id); + deliveries.push({ key_name: keyName, vault_id: vaultId, source_name: source, fingerprint: s.fingerprint, sealed: `sealed:v2:${JSON.stringify(entry)}` }); + } + say("Sealed. Sending…"); + const r = await postJSON(`/api/v1/app-grants/requests/${encodeURIComponent(requestId)}/approve`, { deliveries }); + const failed = r.delivered.filter((d) => !d.delivered); + say(failed.length ? `Granted, but the app did not take ${failed.map((d) => d.key_name).join(", ")} yet (${failed[0].error}). It retries on the next rotation; you can also revoke on /apps.` : "Done. Returning to the app…"); + if (!failed.length) setTimeout(() => (location.href = r.return_url || returnUrl), 800); + } catch (e) { + say(e.message); + btn.disabled = false; + } + }); + + $("#grant-deny").addEventListener("click", async () => { + const r = await postJSON(`/api/v1/app-grants/requests/${encodeURIComponent(requestId)}/deny`, {}).catch(() => ({})); + location.href = r.return_url || returnUrl; + }); +} diff --git a/apps/pwa/src/lib/app-grants.mjs b/apps/pwa/src/lib/app-grants.mjs new file mode 100644 index 00000000..7016ef63 --- /dev/null +++ b/apps/pwa/src/lib/app-grants.mjs @@ -0,0 +1,186 @@ +// App grants: hand one named secret to an external app, sealed in the person's +// browser to that app's per-user inbox key. See migrations/013_app_grants.sql. +// +// The app proves who it is by serving the grant manifest from its own origin +// over TLS; logicsrc fetches it, never trusts a body the app POSTed. +// +// GET /.well-known/logicsrc-grant/ +// { "v": 1, "app_name": "MeshHook", +// "keys": [{ "name": "COINPAY_API_KEY", "description": "..." }], +// "recipient": { "format": "sealed-secrets/inbox-v2", "app": "meshhook", +// "scope": "workflow_secrets", "user_id": "", +// "inbox_public_key": "" }, +// "webhook_url": "", "webhook_secret": "<32+ chars>", +// "return_url": "", "expires_at": } + +import { createHash, createHmac, randomBytes } from "node:crypto"; +import { lookup } from "node:dns/promises"; +import { isIP } from "node:net"; + +export const MANIFEST_PATH = "/.well-known/logicsrc-grant/"; +export const RECIPIENT_FORMAT = "sealed-secrets/inbox-v2"; +export const SEALED_PREFIX = "sealed:v2:"; +export const MAX_KEYS = 20; +const KEY_NAME = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/; + +export class GrantError extends Error { + constructor(message, status = 400, code = "bad_request") { + super(message); + this.status = status; + this.code = code; + } +} + +/** Only https origins with a real host name (http://localhost only when allowed, for tests and dev). */ +export function parseOrigin(raw, { allowLocal = false } = {}) { + let u; + try { + u = new URL(String(raw ?? "")); + } catch { + throw new GrantError("origin must be a URL such as https://meshhook.com"); + } + const local = allowLocal && u.protocol === "http:" && ["localhost", "127.0.0.1"].includes(u.hostname); + if (u.protocol !== "https:" && !local) throw new GrantError("origin must be https"); + if (u.username || u.password || (u.pathname !== "/" && u.pathname !== "") || u.search || u.hash) { + throw new GrantError("origin must be a bare origin, like https://meshhook.com"); + } + if (!local && (isIP(u.hostname) || !u.hostname.includes("."))) throw new GrantError("origin must use a public host name"); + return u.origin; +} + +/** v4/v6 ranges a manifest fetch must never reach (loopback, private, link-local, CGNAT, metadata). */ +export function isPrivateAddress(ip) { + if (isIP(ip) === 4) { + const [a, b] = ip.split(".").map(Number); + return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224; + } + const v = ip.toLowerCase(); + if (v.startsWith("::ffff:")) return isPrivateAddress(v.slice(7)); + return v === "::1" || v === "::" || v.startsWith("fc") || v.startsWith("fd") || v.startsWith("fe8") || v.startsWith("fe9") || + v.startsWith("fea") || v.startsWith("feb") || v.startsWith("ff"); +} + +async function assertPublicHost(hostname) { + const addrs = await lookup(hostname, { all: true }).catch(() => []); + if (!addrs.length) throw new GrantError(`${hostname} does not resolve`, 502, "origin_unreachable"); + if (addrs.some((a) => isPrivateAddress(a.address))) throw new GrantError(`${hostname} resolves to a private address`, 400, "origin_private"); +} + +const sameOrigin = (url, origin) => { + try { + return new URL(url).origin === origin; + } catch { + return false; + } +}; + +/** Validate a manifest against the origin it was fetched from. Returns a normalised copy. */ +export function validateManifest(m, origin, { now = Date.now() } = {}) { + if (!m || typeof m !== "object" || m.v !== 1) throw new GrantError("manifest must be an object with v: 1", 502, "bad_manifest"); + const appName = String(m.app_name ?? "").trim().slice(0, 80); + if (!appName) throw new GrantError("manifest needs app_name", 502, "bad_manifest"); + if (!Array.isArray(m.keys) || !m.keys.length || m.keys.length > MAX_KEYS) throw new GrantError(`manifest needs 1 to ${MAX_KEYS} keys`, 502, "bad_manifest"); + const keys = m.keys.map((k) => { + const name = String(k?.name ?? ""); + if (!KEY_NAME.test(name)) throw new GrantError(`"${name}" is not a valid key name`, 502, "bad_manifest"); + return { name, description: String(k?.description ?? "").slice(0, 200) }; + }); + const r = m.recipient ?? {}; + if (r.format !== RECIPIENT_FORMAT) throw new GrantError(`recipient.format must be ${RECIPIENT_FORMAT}`, 502, "bad_manifest"); + for (const f of ["app", "scope", "user_id", "inbox_public_key"]) { + if (typeof r[f] !== "string" || !r[f]) throw new GrantError(`recipient.${f} is required`, 502, "bad_manifest"); + } + if (!sameOrigin(m.webhook_url, origin)) throw new GrantError("webhook_url must be on the app's own origin", 502, "bad_manifest"); + if (typeof m.webhook_secret !== "string" || m.webhook_secret.length < 32) throw new GrantError("webhook_secret must be 32+ characters", 502, "bad_manifest"); + const returnUrl = m.return_url && sameOrigin(m.return_url, origin) ? m.return_url : origin; + const expiresAt = Number(m.expires_at) || now + 15 * 60_000; + if (expiresAt <= now) throw new GrantError("this grant request has expired; start again from the app", 410, "expired"); + return { + v: 1, + app_name: appName, + keys, + recipient: { format: r.format, app: r.app, scope: r.scope, user_id: r.user_id, inbox_public_key: r.inbox_public_key }, + webhook_url: m.webhook_url, + webhook_secret: m.webhook_secret, + return_url: returnUrl, + expires_at: Math.min(expiresAt, now + 60 * 60_000), + }; +} + +/** Fetch the manifest from the app's origin: TLS is what proves which app is asking. */ +export async function fetchManifest(origin, nonce, { fetchImpl = fetch, allowLocal = false, now = Date.now() } = {}) { + if (!/^[A-Za-z0-9_-]{16,128}$/.test(String(nonce ?? ""))) throw new GrantError("nonce must be 16 to 128 URL-safe characters"); + const o = parseOrigin(origin, { allowLocal }); + if (!allowLocal) await assertPublicHost(new URL(o).hostname); + let res; + try { + res = await fetchImpl(`${o}${MANIFEST_PATH}${encodeURIComponent(nonce)}`, { + headers: { accept: "application/json", "user-agent": "logicsrc-grants/1" }, + redirect: "error", + signal: AbortSignal.timeout(8000), + }); + } catch (e) { + throw new GrantError(`could not reach ${o}: ${e.message}`, 502, "origin_unreachable"); + } + if (res.status === 404) throw new GrantError("the app does not know this request (expired or already used)", 404, "unknown_request"); + if (!res.ok) throw new GrantError(`${o} answered ${res.status}`, 502, "origin_error"); + const text = await res.text(); + if (text.length > 64_000) throw new GrantError("manifest too large", 502, "bad_manifest"); + let body; + try { + body = JSON.parse(text); + } catch { + throw new GrantError("manifest is not JSON", 502, "bad_manifest"); + } + return validateManifest(body, o, { now }); +} + +/** A short, stable fingerprint of a recipient (what changes if the app's inbox key changes). */ +export const recipientFingerprint = (r) => + createHash("sha256").update(`${r.app}\n${r.scope}\n${r.user_id}\n${r.inbox_public_key}`).digest("hex").slice(0, 16); + +/** + * Standard Webhooks signature: v1,..")>. + * The secret is the app's webhook_secret as UTF-8 (a whsec_ prefix is base64 per the spec). + */ +export function signWebhook(secret, id, ts, body) { + const key = secret.startsWith("whsec_") ? Buffer.from(secret.slice(6), "base64") : Buffer.from(secret, "utf8"); + return `v1,${createHmac("sha256", key).update(`${id}.${ts}.${body}`).digest("base64")}`; +} + +/** POST one event to the app. Returns { ok, status?, error? }; never throws. */ +export async function sendWebhook(url, secret, payload, { fetchImpl = fetch, allowLocal = false } = {}) { + // Re-checked on every delivery: a host that resolved publicly at consent time + // may point inside our network by the time a rotation fires. + if (!allowLocal) { + try { + await assertPublicHost(new URL(url).hostname); + } catch (e) { + return { ok: false, error: e.message }; + } + } + const body = JSON.stringify(payload); + const id = `msg_${randomBytes(12).toString("hex")}`; + const ts = Math.floor(Date.now() / 1000); + try { + const res = await fetchImpl(url, { + method: "POST", + headers: { + "content-type": "application/json", + "webhook-id": id, + "webhook-timestamp": String(ts), + "webhook-signature": signWebhook(secret, id, ts, body), + "user-agent": "logicsrc-grants/1", + }, + body, + redirect: "error", + signal: AbortSignal.timeout(10_000), + }); + return res.ok ? { ok: true, status: res.status } : { ok: false, status: res.status, error: `HTTP ${res.status}` }; + } catch (e) { + return { ok: false, error: e.message }; + } +} + +export const isSealed = (v) => typeof v === "string" && v.startsWith(SEALED_PREFIX) && v.length < 32_000; diff --git a/apps/pwa/src/migrations-pg/013_app_grants.sql b/apps/pwa/src/migrations-pg/013_app_grants.sql new file mode 100644 index 00000000..238ba1b9 --- /dev/null +++ b/apps/pwa/src/migrations-pg/013_app_grants.sql @@ -0,0 +1,39 @@ +-- Postgres copy of migrations/013_app_grants.sql (INTEGER -> bigint). Additive only. +create table if not exists app_grant_requests ( + id TEXT PRIMARY KEY, + origin TEXT NOT NULL, + nonce TEXT NOT NULL, + app_name TEXT NOT NULL, + manifest TEXT NOT NULL, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + created_at bigint NOT NULL, + expires_at bigint NOT NULL, + decided_at bigint, + UNIQUE (origin, nonce) +); + +create table if not exists app_grants ( + id TEXT PRIMARY KEY, + request_id TEXT NOT NULL REFERENCES app_grant_requests(id) ON DELETE CASCADE, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + origin TEXT NOT NULL, + app_name TEXT NOT NULL, + key_name TEXT NOT NULL, + vault_id TEXT NOT NULL, + source_name TEXT NOT NULL, + fingerprint TEXT NOT NULL, + recipient TEXT NOT NULL, + recipient_fingerprint TEXT NOT NULL, + webhook_url TEXT NOT NULL, + webhook_secret TEXT NOT NULL, + status TEXT NOT NULL, + created_at bigint NOT NULL, + revoked_at bigint, + last_delivered_at bigint, + last_error TEXT +); + +CREATE INDEX IF NOT EXISTS idx_app_grants_user ON app_grants(user_id); +CREATE INDEX IF NOT EXISTS idx_app_grants_fingerprint ON app_grants(fingerprint); +CREATE INDEX IF NOT EXISTS idx_app_grants_vault ON app_grants(vault_id); diff --git a/apps/pwa/src/migrations/013_app_grants.sql b/apps/pwa/src/migrations/013_app_grants.sql new file mode 100644 index 00000000..a3b8705f --- /dev/null +++ b/apps/pwa/src/migrations/013_app_grants.sql @@ -0,0 +1,46 @@ +-- App grants: a person hands one named secret to an external app (meshhook, +-- smshub, ...), sealed in their browser to that app's per-user inbox key. +-- The server stores ciphertext and metadata only, never a value. +-- +-- A request is created from a manifest logicsrc fetched itself from the app's +-- origin over TLS (/.well-known/logicsrc-grant/), so the consent page +-- shows a verified origin, not a name the app claimed. + +CREATE TABLE IF NOT EXISTS app_grant_requests ( + id TEXT PRIMARY KEY, + origin TEXT NOT NULL, + nonce TEXT NOT NULL, + app_name TEXT NOT NULL, + manifest TEXT NOT NULL, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + decided_at INTEGER, + UNIQUE (origin, nonce) +); + +CREATE TABLE IF NOT EXISTS app_grants ( + id TEXT PRIMARY KEY, + request_id TEXT NOT NULL REFERENCES app_grant_requests(id) ON DELETE CASCADE, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + origin TEXT NOT NULL, + app_name TEXT NOT NULL, + key_name TEXT NOT NULL, + vault_id TEXT NOT NULL, + source_name TEXT NOT NULL, + fingerprint TEXT NOT NULL, + recipient TEXT NOT NULL, + recipient_fingerprint TEXT NOT NULL, + webhook_url TEXT NOT NULL, + webhook_secret TEXT NOT NULL, + status TEXT NOT NULL, + created_at INTEGER NOT NULL, + revoked_at INTEGER, + last_delivered_at INTEGER, + last_error TEXT +); + +CREATE INDEX IF NOT EXISTS idx_app_grants_user ON app_grants(user_id); +CREATE INDEX IF NOT EXISTS idx_app_grants_fingerprint ON app_grants(fingerprint); +CREATE INDEX IF NOT EXISTS idx_app_grants_vault ON app_grants(vault_id); diff --git a/apps/pwa/src/routes/app-grants.mjs b/apps/pwa/src/routes/app-grants.mjs new file mode 100644 index 00000000..e46a54dc --- /dev/null +++ b/apps/pwa/src/routes/app-grants.mjs @@ -0,0 +1,271 @@ +// App grants (see lib/app-grants.mjs and migrations/013_app_grants.sql). +// +// GET /grant?origin=&nonce= consent page (session) +// POST /api/v1/app-grants/requests/:id/approve sealed values from the browser (session) +// POST /api/v1/app-grants/requests/:id/deny +// GET /api/v1/app-grants[?fingerprint=] yours, or every active grant on a value +// in vaults you can open (rotation) +// POST /api/v1/app-grants/:id/deliveries re-seal after rotation (session or person key) +// DELETE /api/v1/app-grants/:id revoke +// GET /apps the apps holding your keys (session) +// +// Values are decrypted and sealed only in the browser or the CLI; this file +// handles ciphertext and metadata. Signing keys (wallet keys, seeds, SSH keys) +// are never granted to an app. + +import { Router } from "express"; +import { get, all, run } from "../db.mjs"; +import { id } from "../lib/crypto.mjs"; +import { page, appBar, esc } from "../lib/html.mjs"; +import { requireAuth } from "../lib/session.mjs"; +import { isSigningKeyName } from "../lib/signing-keys.mjs"; +import { api, audit } from "./credshare.mjs"; +import { GrantError, fetchManifest, isSealed, recipientFingerprint, sendWebhook } from "../lib/app-grants.mjs"; + +export const appGrantsRouter = Router(); + +// Tests point manifests at a local server; production only fetches public https origins. +const ALLOW_LOCAL = process.env.APP_GRANTS_ALLOW_LOCAL === "1"; +let fetchImpl = (...a) => fetch(...a); +export const _setFetch = (f) => (fetchImpl = f); + +const fail = (res, e) => { + if (e instanceof GrantError) return res.status(e.status).json({ error: e.message, code: e.code }); + console.error("app-grants:", e); + return res.status(500).json({ error: e.message || String(e) }); +}; + +/** Vaults this person can open (they hold a grant), for the consent page's picker. */ +async function openableVaults(userId) { + return all( + `SELECT v.id, v.name, t.slug AS team FROM credshare_vault_grants g + JOIN credshare_vaults v ON v.id = g.vault_id + JOIN credshare_teams t ON t.id = v.team_id + JOIN credshare_members m ON m.team_id = t.id AND m.user_id = g.user_id AND m.status = 'active' + WHERE g.user_id = ? ORDER BY t.slug, v.name`, + [userId], + ); +} + +async function canOpenVault(userId, vaultId) { + return Boolean(await get( + `SELECT 1 FROM credshare_vault_grants g JOIN credshare_vaults v ON v.id = g.vault_id + JOIN credshare_members m ON m.team_id = v.team_id AND m.user_id = g.user_id AND m.status = 'active' + WHERE g.user_id = ? AND g.vault_id = ?`, + [userId, vaultId], + )); +} + +const parseJson = (s, d = null) => { + try { + return typeof s === "string" ? JSON.parse(s) : s ?? d; + } catch { + return d; + } +}; + +async function deliver(grants, type, sealedById = {}) { + // One webhook per grant: an app may route keys to different places. + const out = []; + for (const g of grants) { + const payload = { + type, + grant_id: g.id, + request_id: g.request_id, + key_name: g.key_name, + recipient_user_id: parseJson(g.recipient, {})?.user_id ?? null, + ...(sealedById[g.id] ? { sealed: sealedById[g.id] } : {}), + }; + const r = await sendWebhook(g.webhook_url, g.webhook_secret, payload, { fetchImpl, allowLocal: ALLOW_LOCAL }); + await run(`UPDATE app_grants SET last_delivered_at = ?, last_error = ? WHERE id = ?`, [r.ok ? Date.now() : g.last_delivered_at ?? null, r.ok ? null : r.error, g.id]); + out.push({ grant_id: g.id, key_name: g.key_name, delivered: r.ok, ...(r.ok ? {} : { error: r.error }) }); + } + return out; +} + +// ---------------------------------------------------------------- consent page + +appGrantsRouter.get("/grant", requireAuth, async (req, res) => { + const user = req.user; + let manifest, origin; + try { + origin = String(req.query.origin ?? ""); + manifest = await fetchManifest(origin, req.query.nonce, { fetchImpl, allowLocal: ALLOW_LOCAL }); + origin = new URL(origin).origin; + } catch (e) { + const msg = e instanceof GrantError ? e.message : "could not load this request"; + return res.status(e.status ?? 400).type("html").send(page({ title: "LogicSRC ▸ app request", body: `${appBar(req)}

Can't load this request

${esc(msg)}

` })); + } + + // One request per (origin, nonce); it belongs to the first person who opens it. + let reqRow = await get(`SELECT * FROM app_grant_requests WHERE origin = ? AND nonce = ?`, [origin, String(req.query.nonce)]); + if (reqRow && reqRow.user_id !== user.id) { + return res.status(409).type("html").send(page({ body: `${appBar(req)}

Request already taken

Another account opened this request. Start again from the app.

` })); + } + if (!reqRow) { + reqRow = { id: id(), status: "pending" }; + await run( + `INSERT INTO app_grant_requests (id, origin, nonce, app_name, manifest, user_id, status, created_at, expires_at) VALUES (?,?,?,?,?,?,?,?,?)`, + [reqRow.id, origin, String(req.query.nonce), manifest.app_name, JSON.stringify(manifest), user.id, "pending", Date.now(), manifest.expires_at], + ); + } + if (reqRow.status !== "pending") { + return res.type("html").send(page({ body: `${appBar(req)}

Already ${esc(reqRow.status)}

Back to ${esc(manifest.app_name)}

` })); + } + + const vaults = await openableVaults(user.id); + const pk = (await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, [user.id]))?.public_key ?? ""; + const signing = manifest.keys.filter((k) => isSigningKeyName(k.name)).map((k) => k.name); + const host = new URL(origin).host; + const body = `${appBar(req)} +
+

${esc(manifest.app_name)} wants keys from your vault

+

Verified origin: ${esc(host)}. logicsrc fetched this request from ${esc(origin)} over TLS. + Each value is decrypted here in your browser and sealed so that only your account on ${esc(host)} can open it, and only while you have unlocked it there.

+ ${signing.length ? `

Refused: ${signing.map(esc).join(", ")} ${signing.length > 1 ? "are" : "is"} a signing key (wallet, seed or SSH). Those never leave logicsrc.

` : ""} + ${pk ? "" : `

Your account has no identity key yet. Run logicsrc login once, then reload.

`} +
+ + + ${manifest.keys.filter((k) => !signing.includes(k.name)).map((k) => ``).join("")} +
${esc(manifest.app_name)} asks forFrom this secret in the vault
${esc(k.name)}${k.description ? `
${esc(k.description)}` : ""}
+ +

Already unlocked a vault in this tab? The key is reused. It never leaves this page.

+
+
+

+
+
+ + +`; + res.type("html").send(page({ title: `LogicSRC ▸ ${manifest.app_name} wants keys`, body })); +}); + +// -------------------------------------------------------------- approve / deny + +appGrantsRouter.post("/api/v1/app-grants/requests/:id/approve", api(async (req, res, user) => { + try { + const r = await get(`SELECT * FROM app_grant_requests WHERE id = ?`, [req.params.id]); + if (!r || r.user_id !== user.id) throw new GrantError("unknown request", 404, "unknown_request"); + if (r.status !== "pending") throw new GrantError(`request is ${r.status}`, 409, "not_pending"); + if (Number(r.expires_at) <= Date.now()) throw new GrantError("request expired; start again from the app", 410, "expired"); + const manifest = parseJson(r.manifest); + const wanted = new Set(manifest.keys.map((k) => k.name)); + const items = Array.isArray(req.body?.deliveries) ? req.body.deliveries : []; + if (!items.length) throw new GrantError("nothing to grant"); + + const rows = []; + for (const d of items) { + if (!wanted.has(d.key_name)) throw new GrantError(`${manifest.app_name} did not ask for ${d.key_name}`); + if (isSigningKeyName(d.key_name) || isSigningKeyName(d.source_name)) throw new GrantError(`${d.source_name || d.key_name} is a signing key; it never leaves logicsrc`, 403, "signing_key"); + if (!isSealed(d.sealed)) throw new GrantError(`${d.key_name}: not a sealed value`); + if (!(await canOpenVault(user.id, d.vault_id))) throw new GrantError("you cannot open that vault", 403, "no_vault_access"); + const s = await get(`SELECT fingerprint FROM credshare_secrets WHERE vault_id = ? AND name = ?`, [d.vault_id, d.source_name]); + if (!s) throw new GrantError(`no secret ${d.source_name} in that vault`, 404, "no_secret"); + if (s.fingerprint !== d.fingerprint) throw new GrantError(`${d.source_name} changed since you opened it; reload and try again`, 409, "stale"); + rows.push({ ...d, fingerprint: s.fingerprint }); + } + + const recipient = JSON.stringify(manifest.recipient); + const rfp = recipientFingerprint(manifest.recipient); + const grants = []; + const sealedById = {}; + for (const d of rows) { + const g = { + id: id(), request_id: r.id, user_id: user.id, origin: r.origin, app_name: r.app_name, key_name: d.key_name, + vault_id: d.vault_id, source_name: d.source_name, fingerprint: d.fingerprint, recipient, recipient_fingerprint: rfp, + webhook_url: manifest.webhook_url, webhook_secret: manifest.webhook_secret, status: "active", created_at: Date.now(), + }; + await run( + `INSERT INTO app_grants (id, request_id, user_id, origin, app_name, key_name, vault_id, source_name, fingerprint, recipient, recipient_fingerprint, webhook_url, webhook_secret, status, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + [g.id, g.request_id, g.user_id, g.origin, g.app_name, g.key_name, g.vault_id, g.source_name, g.fingerprint, g.recipient, g.recipient_fingerprint, g.webhook_url, g.webhook_secret, g.status, g.created_at], + ); + const vault = await get(`SELECT team_id FROM credshare_vaults WHERE id = ?`, [d.vault_id]); + await audit({ req, teamId: vault?.team_id ?? null, vaultId: d.vault_id, actorUserId: user.id, action: "app:grant", keyName: `${d.source_name} -> ${new URL(r.origin).host} ${d.key_name}`, fingerprint: d.fingerprint }); + grants.push(g); + sealedById[g.id] = d.sealed; + } + await run(`UPDATE app_grant_requests SET status = 'approved', decided_at = ? WHERE id = ?`, [Date.now(), r.id]); + const delivered = await deliver(grants, "grant.delivered", sealedById); + res.json({ ok: true, return_url: manifest.return_url, delivered }); + } catch (e) { + fail(res, e); + } +})); + +appGrantsRouter.post("/api/v1/app-grants/requests/:id/deny", api(async (req, res, user) => { + const r = await get(`SELECT * FROM app_grant_requests WHERE id = ?`, [req.params.id]); + if (!r || r.user_id !== user.id) return res.status(404).json({ error: "unknown request" }); + if (r.status === "pending") await run(`UPDATE app_grant_requests SET status = 'denied', decided_at = ? WHERE id = ?`, [Date.now(), r.id]); + res.json({ ok: true, return_url: parseJson(r.manifest)?.return_url ?? r.origin }); +})); + +// ------------------------------------------------------------ list / rotate / revoke + +const publicGrant = (g) => ({ + id: g.id, app_name: g.app_name, origin: g.origin, key_name: g.key_name, vault_id: g.vault_id, source_name: g.source_name, + fingerprint: g.fingerprint, recipient: parseJson(g.recipient), status: g.status, created_at: Number(g.created_at), + last_delivered_at: g.last_delivered_at == null ? null : Number(g.last_delivered_at), last_error: g.last_error ?? null, +}); + +appGrantsRouter.get("/api/v1/app-grants", api(async (req, res, user) => { + const fp = req.query.fingerprint ? String(req.query.fingerprint) : null; + if (!fp) { + const rows = await all(`SELECT * FROM app_grants WHERE user_id = ? ORDER BY created_at DESC`, [user.id]); + return res.json({ grants: rows.map(publicGrant) }); + } + // Rotation: every active grant of this value in a vault the caller can open, + // whoever made it, so a teammate's rotation reaches the apps too. + const rows = await all(`SELECT * FROM app_grants WHERE fingerprint = ? AND status = 'active'`, [fp]); + const out = []; + for (const g of rows) if (await canOpenVault(user.id, g.vault_id)) out.push(publicGrant(g)); + res.json({ grants: out }); +})); + +appGrantsRouter.post("/api/v1/app-grants/:id/deliveries", api(async (req, res, user) => { + try { + const g = await get(`SELECT * FROM app_grants WHERE id = ?`, [req.params.id]); + if (!g || g.status !== "active") throw new GrantError("unknown or revoked grant", 404, "unknown_grant"); + if (!(await canOpenVault(user.id, g.vault_id))) throw new GrantError("you cannot open that grant's vault", 403, "no_vault_access"); + const { sealed, fingerprint } = req.body ?? {}; + if (!isSealed(sealed)) throw new GrantError("not a sealed value"); + const s = await get(`SELECT fingerprint FROM credshare_secrets WHERE vault_id = ? AND name = ?`, [g.vault_id, g.source_name]); + if (!s || s.fingerprint !== fingerprint) throw new GrantError("fingerprint does not match the vault's current value", 409, "stale"); + await run(`UPDATE app_grants SET fingerprint = ? WHERE id = ?`, [fingerprint, g.id]); + const vault = await get(`SELECT team_id FROM credshare_vaults WHERE id = ?`, [g.vault_id]); + await audit({ req, teamId: vault?.team_id ?? null, vaultId: g.vault_id, actorUserId: user.id, action: "app:grant:update", keyName: `${g.source_name} -> ${new URL(g.origin).host} ${g.key_name}`, fingerprint }); + const [d] = await deliver([{ ...g, fingerprint }], "grant.updated", { [g.id]: sealed }); + res.json({ ok: true, ...d }); + } catch (e) { + fail(res, e); + } +})); + +appGrantsRouter.delete("/api/v1/app-grants/:id", api(async (req, res, user) => { + const g = await get(`SELECT * FROM app_grants WHERE id = ?`, [req.params.id]); + if (!g || g.user_id !== user.id) return res.status(404).json({ error: "unknown grant" }); + if (g.status === "active") { + await run(`UPDATE app_grants SET status = 'revoked', revoked_at = ? WHERE id = ?`, [Date.now(), g.id]); + const vault = await get(`SELECT team_id FROM credshare_vaults WHERE id = ?`, [g.vault_id]); + await audit({ req, teamId: vault?.team_id ?? null, vaultId: g.vault_id, actorUserId: user.id, action: "app:revoke", keyName: `${new URL(g.origin).host} ${g.key_name}` }); + await deliver([g], "grant.revoked"); + } + res.json({ ok: true, note: "The app deleted its copy if it was online. A value it already opened is still known to it: rotate the key to be sure." }); +})); + +// ------------------------------------------------------------------ /apps page + +appGrantsRouter.get("/apps", requireAuth, async (req, res) => { + const rows = (await all(`SELECT * FROM app_grants WHERE user_id = ? ORDER BY status, created_at DESC`, [req.user.id])).map(publicGrant); + const body = `${appBar(req)}

Apps holding your keys

+

Each row is one secret sealed to one app. Revoking tells the app to delete its copy; rotate the key too if it may have been used.

+ ${rows.length ? ` + ${rows.map((g) => ` + + `).join("")} +
AppKeyFromStatus
${esc(g.app_name)}
${esc(new URL(g.origin).host)}
${esc(g.key_name)}${esc(g.source_name)}${esc(g.status)}${g.last_error ? `
last delivery failed: ${esc(g.last_error)}` : ""}
${g.status === "active" ? `` : ""}
` : `

No app holds a key from your vaults.

`} +
`; + res.type("html").send(page({ title: "LogicSRC ▸ apps", body })); +}); diff --git a/apps/pwa/src/server.mjs b/apps/pwa/src/server.mjs index 729f9e66..bd3663ea 100644 --- a/apps/pwa/src/server.mjs +++ b/apps/pwa/src/server.mjs @@ -10,6 +10,7 @@ import { authRouter } from "./routes/auth.mjs"; import { passkeyRouter } from "./routes/passkey.mjs"; import { coinpayRouter } from "./routes/coinpay.mjs"; import { credshareRouter } from "./routes/credshare.mjs"; +import { appGrantsRouter } from "./routes/app-grants.mjs"; import { rotationRouter } from "./routes/rotation.mjs"; import { autoRotationRouter } from "./routes/auto-rotation.mjs"; import { sweepAutoRotation } from "./lib/auto-rotation.mjs"; @@ -61,6 +62,10 @@ const sodiumWrappers = requireHere.resolve("libsodium-wrappers"); const sodiumCore = createRequire(sodiumWrappers).resolve("libsodium"); app.get("/vendor/libsodium.js", (_req, res) => res.sendFile(sodiumCore)); app.get("/vendor/libsodium-wrappers.js", (_req, res) => res.sendFile(sodiumWrappers)); +// @profullstack/sealed-secrets for app grants (public/app-grant.js): plain ESM over +// WebCrypto, served as its own src/ so the browser seals exactly as the apps open. +const sealedSecretsSrc = path.join(path.dirname(requireHere.resolve("@profullstack/sealed-secrets/package.json")), "src"); +app.use("/vendor/sealed-secrets", express.static(sealedSecretsSrc, { maxAge: "1h", index: false })); // The signup profile's progressive enhancement, as a file: the CSP allows no inline script. app.get("/vendor/profile-enhance.js", (_req, res) => res.type("application/javascript").set("Cache-Control", "public, max-age=3600").send(PROFILE_ENHANCE_SCRIPT)); @@ -82,6 +87,7 @@ app.use(authRouter); // GET / (+ /auth/login|register|logout) app.use(passkeyRouter); app.use(coinpayRouter); app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer) +app.use(appGrantsRouter); // /grant consent, /apps, /api/v1/app-grants/* (keys sealed to external apps) app.use(autoRotationRouter); // paid automatic rotation: CoinPay checkout + /api/coinpay/webhook app.use(rotationRouter); // /api/credshare/teams/:slug/rotation* + /teams/:slug/rotation (plan + run queue, never values) app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key) diff --git a/apps/pwa/test/app-grants.test.mjs b/apps/pwa/test/app-grants.test.mjs new file mode 100644 index 00000000..772b6d3f --- /dev/null +++ b/apps/pwa/test/app-grants.test.mjs @@ -0,0 +1,195 @@ +// App grants: a person seals one secret to an external app's per-user inbox. +// The app proves its origin by serving the manifest; the server only ever +// handles ciphertext; the app's own key opens what was delivered; signing keys +// never leave; stale values, other people's requests and revokes behave. +process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:"; +process.env.APP_GRANTS_ALLOW_LOCAL = "1"; + +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, readdirSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import { createHmac } from "node:crypto"; +import express from "express"; +import cookieParser from "cookie-parser"; +import { createSealer } from "@profullstack/sealed-secrets"; + +const here = dirname(fileURLToPath(import.meta.url)); +const { db, run, get, isPostgres } = await import("../src/db.mjs"); +const { appGrantsRouter } = await import("../src/routes/app-grants.mjs"); +const { isPrivateAddress, parseOrigin, validateManifest, signWebhook } = await import("../src/lib/app-grants.mjs"); + +if (isPostgres) { + await db.execute("DROP SCHEMA public CASCADE"); + await db.execute("CREATE SCHEMA public"); +} +const migDir = join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations"); +for (const file of readdirSync(migDir).filter((f) => f.endsWith(".sql")).sort()) { + const sql = readFileSync(join(migDir, file), "utf8"); + for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement); +} +const now = Date.now(); +for (const uid of ["u1", "u2"]) await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, `${uid}@e.test`, now]); +await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t1", "acme", "acme", "u1", now]); +await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m1", "t1", "u1", "u1@e.test", "owner", "active", now]); +await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["v1", "t1", "meshhook--prod", "u1", now]); +await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`, ["v1", "u1", "wrapped", "u1", now]); +for (const [name, fp] of [["COINPAY_API_KEY", "fp-coinpay-1"], ["X402_PRIVATE_KEY", "fp-x402"]]) { + await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`, ["v1", name, "n", "c", fp, 1, "u1", now]); +} + +// ---- the external app: an inbox for its user, a manifest, a webhook receiver +const appSealer = createSealer({ app: "meshhook", scope: "workflow_secrets" }); +const appUser = "mh-user-42"; +const vault = await appSealer.createSeal("correct horse battery staple", appUser); +const WEBHOOK_SECRET = "s".repeat(40); +const received = []; +const ext = express(); +ext.use(express.text({ type: "*/*" })); +let extBase = ""; +const manifests = new Map(); +ext.get("/.well-known/logicsrc-grant/:nonce", (req, res) => (manifests.has(req.params.nonce) ? res.json(manifests.get(req.params.nonce)) : res.sendStatus(404))); +ext.post("/hook", (req, res) => { + received.push({ headers: req.headers, body: req.body }); + res.sendStatus(200); +}); +const extServer = ext.listen(0); +await new Promise((r) => extServer.once("listening", r)); +extBase = `http://127.0.0.1:${extServer.address().port}`; +const manifest = (keys = ["COINPAY_API_KEY"]) => ({ + v: 1, + app_name: "MeshHook", + keys: keys.map((name) => ({ name })), + recipient: { format: "sealed-secrets/inbox-v2", app: "meshhook", scope: "workflow_secrets", user_id: appUser, inbox_public_key: vault.seal.inbox_public_key }, + webhook_url: `${extBase}/hook`, + webhook_secret: WEBHOOK_SECRET, + return_url: `${extBase}/secrets`, +}); + +// ---- logicsrc +const app = express(); +app.use(express.json()); +app.use(cookieParser()); +app.use((req, _res, next) => { + const u = req.get("x-user"); + req.user = u ? { id: u, email: `${u}@e.test` } : null; + next(); +}); +app.use(appGrantsRouter); +const server = app.listen(0); +await new Promise((r) => server.once("listening", r)); +const base = `http://127.0.0.1:${server.address().port}`; +test.after(() => Promise.all([new Promise((r) => server.close(r)), new Promise((r) => extServer.close(r))])); + +const call = async (method, path, user, body) => { + const res = await fetch(base + path, { method, headers: { "x-user": user, "content-type": "application/json", accept: "application/json" }, body: body ? JSON.stringify(body) : undefined }); + const text = await res.text(); + let json = null; + try { + json = JSON.parse(text); + } catch {} + return { status: res.status, json, text }; +}; +const open = (nonce, user = "u1") => call("GET", `/grant?origin=${encodeURIComponent(extBase)}&nonce=${nonce}`, user); +const requestIdOf = (html) => html.match(/data-request-id="([^"]+)"/)?.[1]; +// What the browser does: seal the plaintext to the app's inbox. +const seal = async (keyName, value) => `sealed:v2:${JSON.stringify(await appSealer.sealToInbox(vault.seal.inbox_public_key, { [keyName]: value }, appUser))}`; +const verifySig = ({ headers, body }) => + headers["webhook-signature"] === `v1,${createHmac("sha256", WEBHOOK_SECRET).update(`${headers["webhook-id"]}.${headers["webhook-timestamp"]}.${body}`).digest("base64")}`; + +test("origin and manifest checks", () => { + assert.equal(parseOrigin("https://meshhook.com"), "https://meshhook.com"); + assert.throws(() => parseOrigin("http://meshhook.com"), /https/); + assert.throws(() => parseOrigin("https://10.0.0.1"), /public host/); + assert.throws(() => parseOrigin("https://meshhook.com/path"), /bare origin/); + for (const ip of ["127.0.0.1", "10.1.2.3", "192.168.1.1", "172.20.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1", "::ffff:10.0.0.1"]) assert.ok(isPrivateAddress(ip), ip); + for (const ip of ["8.8.8.8", "2606:4700::1111"]) assert.ok(!isPrivateAddress(ip), ip); + const m = manifest(); + assert.throws(() => validateManifest({ ...m, webhook_url: "https://evil.test/hook" }, extBase), /own origin/); + assert.throws(() => validateManifest({ ...m, webhook_secret: "short" }, extBase), /32\+/); + assert.equal(validateManifest({ ...m, return_url: "https://evil.test/" }, extBase).return_url, extBase); + assert.match(signWebhook("whsec_" + Buffer.from("k").toString("base64"), "id", 1, "b"), /^v1,/); +}); + +test("approve seals a value the app can open, and the webhook is signed", async () => { + manifests.set("nonce-approve-0001", manifest()); + const page = await open("nonce-approve-0001"); + assert.equal(page.status, 200); + assert.match(page.text, /Verified origin: 127\.0\.0\.1:\d+<\/b>/); + const rid = requestIdOf(page.text); + assert.ok(rid); + + // Someone else cannot take or approve it. + assert.equal((await open("nonce-approve-0001", "u2")).status, 409); + const sealed = await seal("COINPAY_API_KEY", "cp_live_fixture_value"); + assert.equal((await call("POST", `/api/v1/app-grants/requests/${rid}/approve`, "u2", { deliveries: [{ key_name: "COINPAY_API_KEY", vault_id: "v1", source_name: "COINPAY_API_KEY", fingerprint: "fp-coinpay-1", sealed }] })).status, 404); + + // Stale value (rotated since the page opened) is refused. + const stale = await call("POST", `/api/v1/app-grants/requests/${rid}/approve`, "u1", { deliveries: [{ key_name: "COINPAY_API_KEY", vault_id: "v1", source_name: "COINPAY_API_KEY", fingerprint: "old", sealed }] }); + assert.equal(stale.status, 409); + + const ok = await call("POST", `/api/v1/app-grants/requests/${rid}/approve`, "u1", { deliveries: [{ key_name: "COINPAY_API_KEY", vault_id: "v1", source_name: "COINPAY_API_KEY", fingerprint: "fp-coinpay-1", sealed }] }); + assert.equal(ok.status, 200, ok.text); + assert.equal(ok.json.delivered[0].delivered, true); + assert.equal(ok.json.return_url, `${extBase}/secrets`); + + const hook = received.at(-1); + assert.ok(verifySig(hook), "webhook signature"); + const event = JSON.parse(hook.body); + assert.equal(event.type, "grant.delivered"); + assert.equal(event.recipient_user_id, appUser); + // The app opens it with its own data key: the full round trip. + const entry = JSON.parse(event.sealed.slice("sealed:v2:".length)); + assert.deepEqual(await appSealer.openInbox(vault.dek, vault.seal, [entry], appUser).then((r) => r.patch), { COINPAY_API_KEY: "cp_live_fixture_value" }); + + // Nothing readable was stored by logicsrc. + const row = await get(`SELECT * FROM app_grants WHERE request_id = ?`, [rid]); + assert.ok(!JSON.stringify(row).includes("cp_live_fixture_value")); + assert.equal((await call("POST", `/api/v1/app-grants/requests/${rid}/approve`, "u1", { deliveries: [] })).status, 409); +}); + +test("signing keys never go to an app", async () => { + manifests.set("nonce-signing-0001", manifest(["X402_PRIVATE_KEY", "COINPAY_API_KEY"])); + const page = await open("nonce-signing-0001"); + assert.match(page.text, /Refused: X402_PRIVATE_KEY/); + const rid = requestIdOf(page.text); + const r = await call("POST", `/api/v1/app-grants/requests/${rid}/approve`, "u1", { deliveries: [{ key_name: "X402_PRIVATE_KEY", vault_id: "v1", source_name: "X402_PRIVATE_KEY", fingerprint: "fp-x402", sealed: await seal("X402_PRIVATE_KEY", "k") }] }); + assert.equal(r.status, 403); + assert.equal(r.json.code, "signing_key"); +}); + +test("rotation re-delivers by fingerprint; revoke tells the app", async () => { + const mine = await call("GET", "/api/v1/app-grants?fingerprint=fp-coinpay-1", "u1"); + assert.equal(mine.json.grants.length, 1); + assert.equal((await call("GET", "/api/v1/app-grants?fingerprint=fp-coinpay-1", "u2")).json.grants.length, 0, "no vault access, no grants"); + const g = mine.json.grants[0]; + + await run(`UPDATE credshare_secrets SET fingerprint = ? WHERE vault_id = ? AND name = ?`, ["fp-coinpay-2", "v1", "COINPAY_API_KEY"]); + const sealed = await seal("COINPAY_API_KEY", "cp_live_rotated"); + assert.equal((await call("POST", `/api/v1/app-grants/${g.id}/deliveries`, "u1", { sealed, fingerprint: "fp-coinpay-1" })).status, 409); + const d = await call("POST", `/api/v1/app-grants/${g.id}/deliveries`, "u1", { sealed, fingerprint: "fp-coinpay-2" }); + assert.equal(d.status, 200, d.text); + const upd = JSON.parse(received.at(-1).body); + assert.equal(upd.type, "grant.updated"); + assert.equal(upd.grant_id, g.id); + + const rv = await call("DELETE", `/api/v1/app-grants/${g.id}`, "u1"); + assert.equal(rv.status, 200); + assert.equal(JSON.parse(received.at(-1).body).type, "grant.revoked"); + assert.equal((await call("POST", `/api/v1/app-grants/${g.id}/deliveries`, "u1", { sealed, fingerprint: "fp-coinpay-2" })).status, 404); +}); + +test("an unknown nonce or a bad manifest is refused", async () => { + assert.equal((await open("nonce-missing-00001")).status, 404); + manifests.set("nonce-badhook-0001", { ...manifest(), webhook_url: "https://elsewhere.test/hook" }); + assert.equal((await open("nonce-badhook-0001")).status, 502); +}); + +test("a webhook host that now resolves privately gets no delivery", async () => { + const { sendWebhook } = await import("../src/lib/app-grants.mjs"); + let called = false; + const r = await sendWebhook("https://localhost.localdomain./hook", "s".repeat(40), {}, { fetchImpl: async () => ((called = true), new Response("ok")) }); + assert.equal(r.ok, false); + assert.equal(called, false); +}); diff --git a/bun.lock b/bun.lock index 30e3b99e..e765dc9d 100644 --- a/bun.lock +++ b/bun.lock @@ -88,6 +88,7 @@ "@profullstack/key-rotation": "0.1.0", "@profullstack/libsql-pg": "^0.1.4", "@profullstack/profile": "0.1.8", + "@profullstack/sealed-secrets": "0.1.1", "@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/server": "^14.0.3", "cookie-parser": "^1.4.7", @@ -176,6 +177,7 @@ "@logicsrc/validators": "file:../validators", "@profullstack/hqtui": "^0.11.1", "@profullstack/logicsrc-mcp": "file:../logicsrc-mcp", + "@profullstack/sealed-secrets": "0.1.1", "commander": "^15.0.0", }, "devDependencies": { @@ -781,6 +783,8 @@ "@profullstack/referrals": ["@profullstack/referrals@0.1.0", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"] }, "sha512-u66SdBVpsv3kc0N+NWISPoYD5vjCERyv5wfD07iSkZwQeC2IA+ihX5jNA4e7Xr+Y4AUvxLycG+3b4VaROqzgRg=="], + "@profullstack/sealed-secrets": ["@profullstack/sealed-secrets@0.1.1", "", {}, "sha512-HQH7PlWDGmKhJYkVyVwH5GBoRjP0+ndHcXCJLYuv+/4VuICOMNDnLGw8UdG8CsbGZIuI6X8nS99mTl7CaOMKXw=="], + "@profullstack/stack": ["@profullstack/stack@0.5.0", "", { "dependencies": { "@profullstack/emailer": "^1.0.1", "@profullstack/form-guard": "^0.1.1", "@profullstack/referrals": "^0.1.0" }, "peerDependencies": { "@supabase/ssr": ">=0.5.0", "next": ">=13.0.0", "react": ">=18.0.0" }, "optionalPeers": ["@supabase/ssr", "next", "react"] }, "sha512-LbXovIhyzLEq+a+y3q8KWC+jN1tJjvSoUiFEhpiEBisQn5U+iutIGHDgg16Lul74kQaFZeFlbp7CMPAVJ8KL6g=="], "@profullstack/x402-gateway": ["@profullstack/x402-gateway@0.13.1", "", { "dependencies": { "@profullstack/keys": "^0.1.0" } }, "sha512-V7liSO0tShZRlp8dancuDuUSF/rqrr5YF3bzLoZy9wn6ixf1RIRPYTepe72s36JOdSVzi3wfuhaZFm9y0RpV4w=="], diff --git a/packages/cli/package.json b/packages/cli/package.json index 90ae4fee..c0544d12 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -35,6 +35,7 @@ "@logicsrc/validators": "file:../validators", "@profullstack/hqtui": "^0.11.1", "@profullstack/logicsrc-mcp": "file:../logicsrc-mcp", + "@profullstack/sealed-secrets": "0.1.1", "commander": "^15.0.0" }, "devDependencies": { diff --git a/packages/cli/src/rotate-app-grants.test.ts b/packages/cli/src/rotate-app-grants.test.ts new file mode 100644 index 00000000..f5271a34 --- /dev/null +++ b/packages/cli/src/rotate-app-grants.test.ts @@ -0,0 +1,44 @@ +// A rotation re-seals the new value to every app that holds the old one +// through a logicsrc app grant, reading each grant's own vault and name. +import { describe, expect, it } from "vitest"; +import { createSealer } from "@profullstack/sealed-secrets"; +import { encryptValue, fingerprintValue, generateVaultKey } from "@logicsrc/plugin-credential-sharing"; +import { resealAppGrants } from "./rotate-keys.js"; + +describe("resealAppGrants", () => { + it("seals the new value to the app's inbox and delivers it with the new fingerprint", async () => { + const appSealer = createSealer({ app: "meshhook", scope: "workflow_secrets" }); + const inbox = await appSealer.createSeal("correct horse battery staple", "mh-user-1"); + const dek = await generateVaultKey(); + const fresh = "cp_live_rotated_fixture"; + const delivered: Array<{ id: string; sealed: string; fingerprint: string }> = []; + const client = { + listAppGrants: async (fp: string) => ({ + grants: fp === "fp-old" + ? [{ id: "g1", app_name: "MeshHook", origin: "https://meshhook.com", key_name: "COINPAY_API_KEY", vault_id: "v1", source_name: "COINPAY_API_KEY", fingerprint: "fp-old", status: "active", + recipient: { format: "sealed-secrets/inbox-v2", app: "meshhook", scope: "workflow_secrets", user_id: "mh-user-1", inbox_public_key: inbox.seal.inbox_public_key } }, + { id: "g2", app_name: "Other", origin: "https://other.example", key_name: "K", vault_id: "v-locked", source_name: "K", fingerprint: "fp-old", status: "active", + recipient: { format: "sealed-secrets/inbox-v2", app: "x", scope: "y", user_id: "u", inbox_public_key: inbox.seal.inbox_public_key } }] + : [] + }), + listSecrets: async () => ({ secrets: [{ name: "COINPAY_API_KEY", ...(await encryptValue(fresh, dek)), fingerprint: fingerprintValue(fresh) }] }), + deliverAppGrant: async (id: string, sealed: string, fingerprint: string) => { + delivered.push({ id, sealed, fingerprint }); + return { ok: true, delivered: true }; + } + }; + const team = { client: client as never, vaults: [{ id: "v1", name: "meshhook--prod", project: "meshhook", env: "prod", secrets: [] }], dek: async () => dek }; + + const report = await resealAppGrants(team, "fp-old"); + expect(report).toEqual(["meshhook.com:COINPAY_API_KEY updated", "other.example:K not updated (no access to its vault)"]); + expect(delivered).toHaveLength(1); + expect(delivered[0]!.fingerprint).toBe(fingerprintValue(fresh)); + const entry = JSON.parse(delivered[0]!.sealed.slice("sealed:v2:".length)); + const { patch } = await appSealer.openInbox(inbox.dek, inbox.seal, [entry], "mh-user-1"); + expect(patch).toEqual({ COINPAY_API_KEY: fresh }); + }); + + it("does nothing for a client without app grants (older servers, test fakes)", async () => { + expect(await resealAppGrants({ client: {} as never, vaults: [], dek: async () => "" }, "fp")).toEqual([]); + }); +}); diff --git a/packages/cli/src/rotate-keys.ts b/packages/cli/src/rotate-keys.ts index fd360532..1b95e261 100644 --- a/packages/cli/src/rotate-keys.ts +++ b/packages/cli/src/rotate-keys.ts @@ -13,6 +13,7 @@ import { type RemoteSecret, type TeamClient } from "@logicsrc/plugin-credential-sharing"; +import { createSealer } from "@profullstack/sealed-secrets"; import { print, printColumns, type OutputFormat } from "./format.js"; import { authedClient, splitVaultName, vaultName } from "./teams.js"; import { @@ -339,6 +340,47 @@ export interface RotationResult { disruptive?: string; note?: string; error?: string; + /** Apps that hold this value through a logicsrc app grant, and whether each got the new one. */ + apps?: string[]; +} + +/** + * After a rotation, every app holding the OLD value through an app grant gets + * the new one, sealed here to that app's inbox key (the server sees ciphertext). + * Each grant reads the value from its own vault and name, so a per-vault + * rewrite (URLs) reaches the right app. Never throws: a failure is reported. + */ +export async function resealAppGrants(team: Pick, oldFingerprint: string): Promise { + const client = team.client as TeamClient & { listAppGrants?: TeamClient["listAppGrants"] }; + if (typeof client.listAppGrants !== "function") return []; + let grants; + try { + ({ grants } = await client.listAppGrants(oldFingerprint)); + } catch (err) { + return [`app grants not checked: ${(err as Error).message}`]; + } + const out: string[] = []; + for (const g of grants) { + const label = `${new URL(g.origin).host}:${g.key_name}`; + try { + const vault = team.vaults.find((v) => v.id === g.vault_id); + if (!vault) { + out.push(`${label} not updated (no access to its vault)`); + continue; + } + const { secrets } = await client.listSecrets(vault.id); + const s = secrets.find((x) => x.name === g.source_name); + if (!s || s.fingerprint === oldFingerprint) continue; + const value = await decryptValue({ nonce: s.nonce, ciphertext: s.ciphertext }, await team.dek(vault)); + const sealer = createSealer({ app: g.recipient.app, scope: g.recipient.scope }); + const entry = await sealer.sealToInbox(g.recipient.inbox_public_key, { [g.key_name]: value }, g.recipient.user_id); + const r = await client.deliverAppGrant(g.id, `sealed:v2:${JSON.stringify(entry)}`, s.fingerprint); + out.push(r.delivered ? `${label} updated` : `${label} sealed, app offline (${r.error ?? "no answer"})`); + } catch (err) { + out.push(`${label} failed: ${(err as Error).message}`); + } + } + return out; } async function readStdin(): Promise { @@ -664,6 +706,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider" || spec?.method === "desktop")) { const r = await rotateTwoPhase(team, p, targets, base, options, deps); if (r.status === "rotated" || r.status === "rolled-back") live++; + if (r.status === "rotated") r.apps = await resealAppGrants(team, p.fingerprint); results.push(r); continue; } @@ -702,7 +745,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter const { applied } = await team.client.putSecrets(vault.id, upserts, []); for (const name of applied) written.push(`${vault.name}:${name}`); } - results.push({ ...base, status: "rotated", written, publicKey: replacement.publicKey }); + results.push({ ...base, status: "rotated", written, publicKey: replacement.publicKey, apps: await resealAppGrants(team, p.fingerprint) }); } catch (err) { // A login wall or a person at the desk is not a failure: that key waits, the others go on. const status = err instanceof DesktopError && (err.code === "needs-login" || err.code === "busy") ? err.code : "failed"; @@ -725,7 +768,8 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter next: r.status === "todo" ? (r.error ?? r.url ?? "see --format json") : r.error ?? r.note ?? "" })) ); - for (const r of results.filter((x) => x.publicKey)) console.error(`\n${r.key} new public key (install it, remove the old one):\n${r.publicKey}`); + for (const r of results.filter((x) => x.apps?.length)) console.error(`${r.key} apps: ${r.apps!.join("; ")}`); + for (const r of results.filter((x) => x.publicKey)) console.error(`\n${r.key} new public key (install it, remove the old one):\n${r.publicKey}`); const todo = results.filter((r) => r.status === "todo").length; const waiting = results.filter((r) => r.status === "needs-login" || r.status === "busy"); if (waiting.length) console.error(`\n${waiting.length} desktop key(s) waiting: ${waiting.map((r) => `${r.key} (${r.status})`).join(", ")}. Sign in in the desktop's agent browser / wait until the desk is free, then run again.`); diff --git a/plugins/credential-sharing/src/client.ts b/plugins/credential-sharing/src/client.ts index 740970bf..454c026a 100644 --- a/plugins/credential-sharing/src/client.ts +++ b/plugins/credential-sharing/src/client.ts @@ -180,6 +180,19 @@ export interface RemoteRotationRun { summary: string | null; } +/** One secret sealed to an external app (see apps/pwa/src/routes/app-grants.mjs). */ +export interface AppGrant { + id: string; + app_name: string; + origin: string; + key_name: string; + vault_id: string; + source_name: string; + fingerprint: string; + recipient: { format: string; app: string; scope: string; user_id: string; inbox_public_key: string }; + status: string; +} + export class TeamClient { private readonly apiUrl: string; private token?: string; @@ -193,6 +206,16 @@ export class TeamClient { this.token = token; } + /** App grants holding a value (by fingerprint) in vaults this identity can open. */ + listAppGrants(fingerprint: string): Promise<{ grants: AppGrant[] }> { + return this.requestAt(`/api/v1/app-grants?fingerprint=${encodeURIComponent(fingerprint)}`, "GET"); + } + + /** Hand an app the re-sealed value after a rotation (ciphertext only). */ + deliverAppGrant(grantId: string, sealed: string, fingerprint: string): Promise<{ ok: boolean; delivered: boolean; error?: string }> { + return this.requestAt(`/api/v1/app-grants/${encodeURIComponent(grantId)}/deliveries`, "POST", { sealed, fingerprint }); + } + private request(method: string, path: string, body?: unknown): Promise { return this.requestAt(`/api/credshare${path}`, method, body); }