mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +00:00
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>
This commit is contained in:
parent
64eb42e2c1
commit
f19b817c70
13 changed files with 957 additions and 4 deletions
177
apps/pwa/src/lib/app-grants.mjs
Normal file
177
apps/pwa/src/lib/app-grants.mjs
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
// 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 } = {}) {
|
||||
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;
|
||||
39
apps/pwa/src/migrations-pg/013_app_grants.sql
Normal file
39
apps/pwa/src/migrations-pg/013_app_grants.sql
Normal 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);
|
||||
46
apps/pwa/src/migrations/013_app_grants.sql
Normal file
46
apps/pwa/src/migrations/013_app_grants.sql
Normal 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);
|
||||
271
apps/pwa/src/routes/app-grants.mjs
Normal file
271
apps/pwa/src/routes/app-grants.mjs
Normal 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 });
|
||||
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 }));
|
||||
});
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue