logicsrc/apps/pwa/src/routes/coinpay.mjs
Anthony Ettinger 9ba044577f
Some checks failed
CI / build (push) Has been cancelled
test / test (push) Has been cancelled
feat(pwa): logicsrc credentials app — real auth + Turso, redesigned; retire commandboard-api credshare
Adds apps/pwa: an Express + libSQL/Turso app that is now the home of team
credential sharing, with the moshcode-style auth stack ported and reskinned to
match logicsrc.com (light theme, Inter, green accent).

apps/pwa
- auth: email/password (scrypt), passkeys (WebAuthn), CoinPay OAuth, cookie
  sessions, and lsk_ API keys for the CLI via a loopback OAuth-PKCE flow
  (/cli/authorize + /cli/token). Ported from the moshcode PWA.
- credshare API (/api/credshare/*): teams, members, invites, vaults, sealed
  grants, ciphertext secrets, audit — authed by session OR Bearer lsk_ key.
  Zero-knowledge: only ciphertext + sealed vault keys + public keys stored.
- teams dashboard, accept-invite, and settings (API keys) pages, server-rendered
  in the LogicSRC brand (lib/html.mjs).
- migrations (libSQL) 001_auth + 002_credshare, migrate-on-boot; Turso via
  TURSO_DATABASE_URL / TURSO_AUTH_TOKEN, or a local file db for dev.
- trimmed moshcode-specific approvals/credits/push/deliver.

CLI
- `logicsrc login` now does browser loopback OAuth-PKCE against the app and
  stores an lsk_ token (email-OTP removed); --token for CI. Client repointed.

Distribution
- install.sh (served at logicsrc.com/install.sh) installs the CLI from the
  GitHub repo: tarball -> npm install -> `npm run build:cli` -> logicsrc wrapper.
- root build:cli builds only the CLI's workspace chain (skips web/api/next).

Cleanup
- removed the commandboard-api credshare backend (superseded by the PWA) and its
  Supabase/Turso stores + libsql dep; commandboard-api tests green (40).
- removed the Next.js /teams page (the PWA is the web UI now).

Verified end-to-end: two accounts register on the PWA, mint lsk_ keys, CLI login
uploads identity keys, owner pushes an encrypted .env, teammate invited ->
accepted -> granted -> pulls the exact file. Server stores ciphertext only.
Full workspace build + tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 14:29:29 +00:00

68 lines
2.8 KiB
JavaScript

// "Sign in with CoinPay" — OAuth 2.0 authorization-code + PKCE.
import { Router } from "express";
import crypto from "node:crypto";
import { config } from "../config.mjs";
import { token } from "../lib/crypto.mjs";
import { createSession, setCeremony, getCeremony, clearCeremony, takeNext } from "../lib/session.mjs";
import { userByCoinpay, createUserForCoinpay } from "../lib/users.mjs";
export const coinpayRouter = Router();
const b64url = (buf) => Buffer.from(buf).toString("base64url");
coinpayRouter.get("/auth/coinpay/start", (req, res) => {
if (!config.coinpayLoginEnabled) return res.redirect("/?err=coinpay-not-configured");
const state = token(16);
const verifier = b64url(crypto.randomBytes(32));
const challenge = b64url(crypto.createHash("sha256").update(verifier).digest());
setCeremony(res, "cp", { state, verifier }, 1000 * 60 * 10);
const u = new URL(config.coinpay.oauth.authorizeUrl);
u.searchParams.set("response_type", "code");
u.searchParams.set("client_id", config.coinpay.oauth.clientId);
u.searchParams.set("redirect_uri", config.coinpay.oauth.redirectUri);
u.searchParams.set("scope", config.coinpay.oauth.scope);
u.searchParams.set("state", state);
u.searchParams.set("code_challenge", challenge);
u.searchParams.set("code_challenge_method", "S256");
res.redirect(u.toString());
});
coinpayRouter.get("/auth/coinpay/callback", async (req, res) => {
const ceremony = getCeremony(req, "cp");
clearCeremony(res, "cp");
if (!ceremony || req.query.state !== ceremony.state) return res.redirect("/?err=coinpay-state");
if (!req.query.code) return res.redirect("/?err=coinpay-denied");
try {
const tokenRes = await fetch(config.coinpay.oauth.tokenUrl, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code: String(req.query.code),
redirect_uri: config.coinpay.oauth.redirectUri,
client_id: config.coinpay.oauth.clientId,
code_verifier: ceremony.verifier,
}),
});
if (!tokenRes.ok) throw new Error(`token exchange ${tokenRes.status}`);
const tok = await tokenRes.json();
const infoRes = await fetch(config.coinpay.oauth.userinfoUrl, {
headers: { authorization: `Bearer ${tok.access_token}` },
});
if (!infoRes.ok) throw new Error(`userinfo ${infoRes.status}`);
const info = await infoRes.json();
const sub = String(info.sub || info.id || info.user_id || "");
if (!sub) throw new Error("no subject in userinfo");
let user = await userByCoinpay(sub);
if (!user) user = await createUserForCoinpay(sub, info.name || info.username);
await createSession(res, user.id);
res.redirect(takeNext(req, res) || "/");
} catch (e) {
console.error("coinpay login failed:", e.message);
res.redirect("/?err=coinpay-failed");
}
});