App grants: one secret sealed to an external app (key hub phase 1) (#286)
Some checks failed
CI / build (push) Has been cancelled
Deploy to dev2 / deploy (push) Has been cancelled
test / test (push) Has been cancelled

* App grants: hand one secret to an external app, sealed to its per-user inbox

Phase 1 of the CoinPay <-> logicsrc key hub (spec: claude.ai/artifact/LAZgAiqWqeLQ14uJ5JpdKb).

- /grant consent page: logicsrc fetches the request manifest from the app's
  own origin over TLS (/.well-known/logicsrc-grant/<nonce>), public hosts
  only, so the page shows a verified origin, not a claimed name
- The browser decrypts with the identity key (as the vault page does) and
  seals with @profullstack/sealed-secrets to the app's inbox; the server
  stores ciphertext + metadata only (app_grant_requests, app_grants)
- Signed Standard Webhooks to the app: grant.delivered / updated / revoked
- Signing keys (wallet, seed, SSH) are refused for apps
- rotate-keys re-seals the new value to every app grant on the old
  fingerprint (resealAppGrants); /apps lists and revokes grants

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* App grants: re-check the webhook host is public on every delivery

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-11-11 05:16:37 -08:00 • committed by GitHub
parent 64eb42e2c1
commit bbf640abeb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 974 additions and 4 deletions

View file

@ -3,7 +3,7 @@
"version": "0.1.1", "version": "0.1.1",
"private": true, "private": true,
"type": "module", "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": { "scripts": {
"start": "bun src/server.mjs", "start": "bun src/server.mjs",
"dev": "bun --watch src/server.mjs", "dev": "bun --watch src/server.mjs",
@ -13,10 +13,11 @@
"dependencies": { "dependencies": {
"@logicsrc/cli": "workspace:*", "@logicsrc/cli": "workspace:*",
"@profullstack/coinpay-onboard": "0.3.1", "@profullstack/coinpay-onboard": "0.3.1",
"@profullstack/key-rotation": "0.1.0",
"@profullstack/footer": "latest", "@profullstack/footer": "latest",
"@profullstack/key-rotation": "0.1.0",
"@profullstack/libsql-pg": "^0.1.4", "@profullstack/libsql-pg": "^0.1.4",
"@profullstack/profile": "0.1.8", "@profullstack/profile": "0.1.8",
"@profullstack/sealed-secrets": "0.1.1",
"@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/browser": "^14.0.0",
"@simplewebauthn/server": "^14.0.3", "@simplewebauthn/server": "^14.0.3",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",

View file

@ -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:<inbox entry>, 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;
});
}

View file

@ -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 <origin>/.well-known/logicsrc-grant/<nonce>
// { "v": 1, "app_name": "MeshHook",
// "keys": [{ "name": "COINPAY_API_KEY", "description": "..." }],
// "recipient": { "format": "sealed-secrets/inbox-v2", "app": "meshhook",
// "scope": "workflow_secrets", "user_id": "<app user id>",
// "inbox_public_key": "<base64>" },
// "webhook_url": "<same origin, https>", "webhook_secret": "<32+ chars>",
// "return_url": "<same origin>", "expires_at": <ms> }
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,<base64 HMAC-SHA256(secret, "<id>.<ts>.<body>")>.
* 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;

View file

@ -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);

View file

@ -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/<nonce>), 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);

View file

@ -0,0 +1,271 @@
// App grants (see lib/app-grants.mjs and migrations/013_app_grants.sql).
//
// GET /grant?origin=<https origin>&nonce=<n> 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=<fp>] 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)}<main class="wrap"><h1>Can't load this request</h1><p>${esc(msg)}</p></main>` }));
}
// 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)}<main class="wrap"><h1>Request already taken</h1><p>Another account opened this request. Start again from the app.</p></main>` }));
}
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)}<main class="wrap"><h1>Already ${esc(reqRow.status)}</h1><p><a href="${esc(manifest.return_url)}">Back to ${esc(manifest.app_name)}</a></p></main>` }));
}
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)}
<main class="wrap" id="grant" data-request-id="${esc(reqRow.id)}" data-public-key="${esc(pk)}" data-return-url="${esc(manifest.return_url)}"
data-recipient="${esc(JSON.stringify(manifest.recipient))}">
<h1>${esc(manifest.app_name)} wants keys from your vault</h1>
<p class="lead">Verified origin: <b>${esc(host)}</b>. logicsrc fetched this request from <code>${esc(origin)}</code> 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.</p>
${signing.length ? `<p class="warn">Refused: ${signing.map(esc).join(", ")} ${signing.length > 1 ? "are" : "is"} a signing key (wallet, seed or SSH). Those never leave logicsrc.</p>` : ""}
${pk ? "" : `<p class="warn">Your account has no identity key yet. Run <code>logicsrc login</code> once, then reload.</p>`}
<section class="card">
<label>Vault <select id="grant-vault">${vaults.map((v) => `<option value="${esc(v.id)}">${esc(v.team)} / ${esc(v.name)}</option>`).join("") || `<option value="">No vaults you can open</option>`}</select></label>
<table class="kv"><thead><tr><th>${esc(manifest.app_name)} asks for</th><th>From this secret in the vault</th></tr></thead><tbody>
${manifest.keys.filter((k) => !signing.includes(k.name)).map((k) => `<tr data-key="${esc(k.name)}"><td><code>${esc(k.name)}</code>${k.description ? `<br><small>${esc(k.description)}</small>` : ""}</td><td><input name="src" value="${esc(k.name)}" aria-label="Source secret for ${esc(k.name)}"></td></tr>`).join("")}
</tbody></table>
<label>Your identity key <textarea id="grant-key" rows="2" placeholder="Paste keys.secretKey from ~/.config/logicsrc/identity.json (or the whole file)"></textarea></label>
<p class="hint">Already unlocked a vault in this tab? The key is reused. It never leaves this page.</p>
<div class="row"><button class="btn" id="grant-approve" type="button">Seal and send to ${esc(host)}</button>
<button class="btn ghost" id="grant-deny" type="button">Deny</button></div>
<p id="grant-status" role="status"></p>
</section>
</main>
<script src="/vendor/libsodium.js" defer></script>
<script src="/vendor/libsodium-wrappers.js" defer></script>
<script type="module" src="/app-grant.js"></script>`;
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)}<main class="wrap"><h1>Apps holding your keys</h1>
<p class="lead">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.</p>
${rows.length ? `<table class="kv"><thead><tr><th>App</th><th>Key</th><th>From</th><th>Status</th><th></th></tr></thead><tbody>
${rows.map((g) => `<tr><td>${esc(g.app_name)}<br><small>${esc(new URL(g.origin).host)}</small></td><td><code>${esc(g.key_name)}</code></td><td><code>${esc(g.source_name)}</code></td>
<td>${esc(g.status)}${g.last_error ? `<br><small>last delivery failed: ${esc(g.last_error)}</small>` : ""}</td>
<td>${g.status === "active" ? `<button class="btn compact ghost" data-revoke="${esc(g.id)}">Revoke</button>` : ""}</td></tr>`).join("")}
</tbody></table>` : `<p>No app holds a key from your vaults.</p>`}
<script type="module" src="/app-grant.js"></script></main>`;
res.type("html").send(page({ title: "LogicSRC ▸ apps", body }));
});

View file

@ -10,6 +10,7 @@ import { authRouter } from "./routes/auth.mjs";
import { passkeyRouter } from "./routes/passkey.mjs"; import { passkeyRouter } from "./routes/passkey.mjs";
import { coinpayRouter } from "./routes/coinpay.mjs"; import { coinpayRouter } from "./routes/coinpay.mjs";
import { credshareRouter } from "./routes/credshare.mjs"; import { credshareRouter } from "./routes/credshare.mjs";
import { appGrantsRouter } from "./routes/app-grants.mjs";
import { rotationRouter } from "./routes/rotation.mjs"; import { rotationRouter } from "./routes/rotation.mjs";
import { autoRotationRouter } from "./routes/auto-rotation.mjs"; import { autoRotationRouter } from "./routes/auto-rotation.mjs";
import { sweepAutoRotation } from "./lib/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"); const sodiumCore = createRequire(sodiumWrappers).resolve("libsodium");
app.get("/vendor/libsodium.js", (_req, res) => res.sendFile(sodiumCore)); app.get("/vendor/libsodium.js", (_req, res) => res.sendFile(sodiumCore));
app.get("/vendor/libsodium-wrappers.js", (_req, res) => res.sendFile(sodiumWrappers)); 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. // 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)); 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(passkeyRouter);
app.use(coinpayRouter); app.use(coinpayRouter);
app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer) 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(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(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) app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)

View file

@ -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: <b>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);
});

View file

@ -88,6 +88,7 @@
"@profullstack/key-rotation": "0.1.0", "@profullstack/key-rotation": "0.1.0",
"@profullstack/libsql-pg": "^0.1.4", "@profullstack/libsql-pg": "^0.1.4",
"@profullstack/profile": "0.1.8", "@profullstack/profile": "0.1.8",
"@profullstack/sealed-secrets": "0.1.1",
"@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/browser": "^14.0.0",
"@simplewebauthn/server": "^14.0.3", "@simplewebauthn/server": "^14.0.3",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
@ -176,6 +177,7 @@
"@logicsrc/validators": "file:../validators", "@logicsrc/validators": "file:../validators",
"@profullstack/hqtui": "^0.11.1", "@profullstack/hqtui": "^0.11.1",
"@profullstack/logicsrc-mcp": "file:../logicsrc-mcp", "@profullstack/logicsrc-mcp": "file:../logicsrc-mcp",
"@profullstack/sealed-secrets": "0.1.1",
"commander": "^15.0.0", "commander": "^15.0.0",
}, },
"devDependencies": { "devDependencies": {
@ -781,6 +783,8 @@
"@profullstack/referrals": ["@profullstack/referrals@0.1.0", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"] }, "sha512-u66SdBVpsv3kc0N+NWISPoYD5vjCERyv5wfD07iSkZwQeC2IA+ihX5jNA4e7Xr+Y4AUvxLycG+3b4VaROqzgRg=="], "@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/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=="], "@profullstack/x402-gateway": ["@profullstack/x402-gateway@0.13.1", "", { "dependencies": { "@profullstack/keys": "^0.1.0" } }, "sha512-V7liSO0tShZRlp8dancuDuUSF/rqrr5YF3bzLoZy9wn6ixf1RIRPYTepe72s36JOdSVzi3wfuhaZFm9y0RpV4w=="],

View file

@ -35,6 +35,7 @@
"@logicsrc/validators": "file:../validators", "@logicsrc/validators": "file:../validators",
"@profullstack/hqtui": "^0.11.1", "@profullstack/hqtui": "^0.11.1",
"@profullstack/logicsrc-mcp": "file:../logicsrc-mcp", "@profullstack/logicsrc-mcp": "file:../logicsrc-mcp",
"@profullstack/sealed-secrets": "0.1.1",
"commander": "^15.0.0" "commander": "^15.0.0"
}, },
"devDependencies": { "devDependencies": {

View file

@ -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([]);
});
});

View file

@ -13,6 +13,7 @@ import {
type RemoteSecret, type RemoteSecret,
type TeamClient type TeamClient
} from "@logicsrc/plugin-credential-sharing"; } from "@logicsrc/plugin-credential-sharing";
import { createSealer } from "@profullstack/sealed-secrets";
import { print, printColumns, type OutputFormat } from "./format.js"; import { print, printColumns, type OutputFormat } from "./format.js";
import { authedClient, splitVaultName, vaultName } from "./teams.js"; import { authedClient, splitVaultName, vaultName } from "./teams.js";
import { import {
@ -339,6 +340,47 @@ export interface RotationResult {
disruptive?: string; disruptive?: string;
note?: string; note?: string;
error?: 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<Loaded, "client" | "vaults" | "dek">, oldFingerprint: string): Promise<string[]> {
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<string> { async function readStdin(): Promise<string> {
@ -664,6 +706,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider" || spec?.method === "desktop")) { if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider" || spec?.method === "desktop")) {
const r = await rotateTwoPhase(team, p, targets, base, options, deps); const r = await rotateTwoPhase(team, p, targets, base, options, deps);
if (r.status === "rotated" || r.status === "rolled-back") live++; if (r.status === "rotated" || r.status === "rolled-back") live++;
if (r.status === "rotated") r.apps = await resealAppGrants(team, p.fingerprint);
results.push(r); results.push(r);
continue; continue;
} }
@ -702,7 +745,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
const { applied } = await team.client.putSecrets(vault.id, upserts, []); const { applied } = await team.client.putSecrets(vault.id, upserts, []);
for (const name of applied) written.push(`${vault.name}:${name}`); 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) { } catch (err) {
// A login wall or a person at the desk is not a failure: that key waits, the others go on. // 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"; 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 ?? "" 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 todo = results.filter((r) => r.status === "todo").length;
const waiting = results.filter((r) => r.status === "needs-login" || r.status === "busy"); 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.`); 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.`);

View file

@ -180,6 +180,19 @@ export interface RemoteRotationRun {
summary: string | null; 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 { export class TeamClient {
private readonly apiUrl: string; private readonly apiUrl: string;
private token?: string; private token?: string;
@ -193,6 +206,16 @@ export class TeamClient {
this.token = token; 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<T>(method: string, path: string, body?: unknown): Promise<T> { private request<T>(method: string, path: string, body?: unknown): Promise<T> {
return this.requestAt<T>(`/api/credshare${path}`, method, body); return this.requestAt<T>(`/api/credshare${path}`, method, body);
} }