diff --git a/apps/pwa/src/migrations-pg/007_password_resets.sql b/apps/pwa/src/migrations-pg/007_password_resets.sql new file mode 100644 index 00000000..f7962e13 --- /dev/null +++ b/apps/pwa/src/migrations-pg/007_password_resets.sql @@ -0,0 +1,10 @@ +create table if not exists password_resets ( + id text PRIMARY KEY, + user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash text NOT NULL UNIQUE, + created_at bigint NOT NULL, + expires_at bigint NOT NULL, + used_at bigint +); +CREATE INDEX IF NOT EXISTS idx_password_resets_user ON password_resets(user_id); +CREATE INDEX IF NOT EXISTS idx_password_resets_expiry ON password_resets(expires_at); diff --git a/apps/pwa/src/migrations-pg/008_recovery_tokens.sql b/apps/pwa/src/migrations-pg/008_recovery_tokens.sql new file mode 100644 index 00000000..f828647c --- /dev/null +++ b/apps/pwa/src/migrations-pg/008_recovery_tokens.sql @@ -0,0 +1,10 @@ +create table if not exists recovery_tokens ( + id text PRIMARY KEY, + user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash text NOT NULL UNIQUE, + created_at bigint NOT NULL, + expires_at bigint NOT NULL, + used_at bigint, + revoked_at bigint +); +CREATE INDEX IF NOT EXISTS idx_recovery_tokens_user ON recovery_tokens(user_id); diff --git a/apps/pwa/src/migrations/007_password_resets.sql b/apps/pwa/src/migrations/007_password_resets.sql new file mode 100644 index 00000000..760e7bb7 --- /dev/null +++ b/apps/pwa/src/migrations/007_password_resets.sql @@ -0,0 +1,10 @@ +CREATE TABLE IF NOT EXISTS password_resets ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + used_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_password_resets_user ON password_resets(user_id); +CREATE INDEX IF NOT EXISTS idx_password_resets_expiry ON password_resets(expires_at); diff --git a/apps/pwa/src/migrations/008_recovery_tokens.sql b/apps/pwa/src/migrations/008_recovery_tokens.sql new file mode 100644 index 00000000..0a60b93e --- /dev/null +++ b/apps/pwa/src/migrations/008_recovery_tokens.sql @@ -0,0 +1,10 @@ +CREATE TABLE IF NOT EXISTS recovery_tokens ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + used_at INTEGER, + revoked_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_recovery_tokens_user ON recovery_tokens(user_id); diff --git a/apps/pwa/src/routes/auth.mjs b/apps/pwa/src/routes/auth.mjs index 1df387c5..6b6a7f44 100644 --- a/apps/pwa/src/routes/auth.mjs +++ b/apps/pwa/src/routes/auth.mjs @@ -2,8 +2,9 @@ import { Router } from "express"; import { page, footer, esc } from "../lib/html.mjs"; import { csrfInput, createSession, destroySession, takeNext } from "../lib/session.mjs"; -import { hashPassword, verifyPassword } from "../lib/crypto.mjs"; +import { hashPassword, verifyPassword, id, token, sha256 } from "../lib/crypto.mjs"; import { createUserWithPassword, userByEmail } from "../lib/users.mjs"; +import { get, run, batch } from "../db.mjs"; import { dashboardHandler } from "./pages.mjs"; import { config } from "../config.mjs"; import { ringFooter } from "../lib/ring-footer.mjs"; @@ -15,49 +16,98 @@ const SIGNUP_FIELDS = ["first_name", "last_name", "company_domain", "job_title", export const authRouter = Router(); -function authPage(req, { error = "", mode = "in", values = {}, errors = {} } = {}) { +function authPage(req, { error = "", notice = "", mode = "in", values = {}, errors = {} } = {}) { + const isForgot = mode === "forgot"; + const isReset = mode === "reset" || mode === "recover"; + const isSignup = mode === "up"; + const action = isForgot ? "/auth/forgot" : mode === "recover" ? "/auth/recover" : isReset ? "/auth/reset" : isSignup ? "/auth/register" : "/auth/login"; const body = `
LSLogicSRCcredentials

Share secrets, end-to-end encrypted

${error ? `
${esc(error)}
` : ""} -
+ ${notice ? `
${esc(notice)}
` : ""} + ${csrfInput(req)} + ${isReset ? `` : ""} - ${mode === "up" ? renderProfileFields({ fields: SIGNUP_FIELDS, values, errors, idPrefix: "signup-" }) : ""} - - + + ${isSignup ? renderProfileFields({ fields: SIGNUP_FIELDS, values, errors, idPrefix: "signup-" }) : ""} + ${isForgot ? "" : ``} + ${isReset ? `` : ""} +

- ${mode === "up" + ${isForgot || isReset + ? `Back to sign in` + : isSignup ? `Already have an account? Sign in` : `New here? Create account`}

-
or
+ ${mode === "in" ? `

Forgot password?

` : ""} - + ${isForgot || isReset ? "" : `
or
`} + + ${isForgot || isReset ? "" : ` ${config.coinpayLoginEnabled ? `â—† Continue with CoinPay` : ``} -

+

`}
${footer}${ringFooter()} - - ${mode === "up" ? `` : ""}`; + ${isForgot || isReset ? "" : ``}${isSignup ? `` : ""}`; return page({ title: "LogicSRC â–¸ sign in", body }); } +async function sendPasswordResetEmail(to, rawToken) { + if (!config.resend.apiKey) return false; + const url = `${config.origin}/auth/reset?token=${encodeURIComponent(rawToken)}`; + const response = await fetch("https://api.resend.com/emails", { + method: "POST", + headers: { authorization: `Bearer ${config.resend.apiKey}`, "content-type": "application/json" }, + body: JSON.stringify({ + from: config.resend.from, + to, + subject: "Reset your LogicSRC password", + text: `Someone requested a password reset for your LogicSRC account.\n\nReset it here: ${url}\n\nThis link expires in 30 minutes and can only be used once. If you did not request it, you can ignore this email.`, + }), + }).catch(() => null); + return Boolean(response && response.ok); +} + authRouter.get("/", (req, res) => { if (req.user) { const next = takeNext(req, res); if (next) return res.redirect(next); return dashboardHandler(req, res); // dashboard lives at the root } - res.type("html").send(authPage(req, { mode: req.query.mode === "up" ? "up" : "in" })); + res.type("html").send(authPage(req, { + mode: req.query.mode === "up" ? "up" : req.query.mode === "forgot" ? "forgot" : "in", + notice: req.query.reset === "1" ? "Password reset. You can sign in with your new password." : "", + })); +}); + +authRouter.get("/auth/reset", async (req, res) => { + const rawToken = String(req.query.token || ""); + const reset = rawToken ? await get( + `SELECT u.email FROM password_resets r JOIN users u ON u.id = r.user_id WHERE r.token_hash = ? AND r.used_at IS NULL AND r.expires_at > ?`, + [sha256(rawToken), Date.now()], + ) : null; + if (!reset) return res.type("html").send(authPage(req, { mode: "in", error: "That reset link is invalid or expired. Request a new one." })); + res.type("html").send(authPage(req, { mode: "reset", values: { email: reset.email, token: rawToken } })); +}); + +authRouter.get("/auth/recover", async (req, res) => { + const rawToken = String(req.query.token || ""); + const recovery = rawToken ? await get( + `SELECT u.email FROM recovery_tokens r JOIN users u ON u.id = r.user_id WHERE r.token_hash = ? AND r.used_at IS NULL AND r.revoked_at IS NULL AND r.expires_at > ?`, + [sha256(rawToken), Date.now()], + ) : null; + if (!recovery) return res.type("html").send(authPage(req, { mode: "in", error: "That recovery token is invalid, revoked, or already used." })); + res.type("html").send(authPage(req, { mode: "recover", values: { email: recovery.email, token: rawToken } })); }); authRouter.post("/auth/register", async (req, res) => { @@ -94,6 +144,63 @@ authRouter.post("/auth/login", async (req, res) => { res.redirect(takeNext(req, res) || "/"); }); +authRouter.post("/auth/forgot", async (req, res) => { + const email = String(req.body.email || "").trim().toLowerCase(); + const user = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) ? await userByEmail(email) : null; + if (user) { + const rawToken = token(32); + await run(`DELETE FROM password_resets WHERE user_id = ? OR expires_at <= ?`, [user.id, Date.now()]); + await run(`INSERT INTO password_resets (id, user_id, token_hash, created_at, expires_at) VALUES (?,?,?,?,?)`, + [id(), user.id, sha256(rawToken), Date.now(), Date.now() + 1000 * 60 * 30]); + await sendPasswordResetEmail(email, rawToken); + } + res.type("html").send(authPage(req, { + mode: "forgot", + values: { email }, + notice: "If an account exists for that email, a reset link is on its way.", + })); +}); + +authRouter.post("/auth/reset", async (req, res) => { + const rawToken = String(req.body.token || ""); + const password = String(req.body.password || ""); + const confirmation = String(req.body.password_confirmation || ""); + const reset = rawToken ? await get( + `SELECT r.id, r.user_id, u.email FROM password_resets r JOIN users u ON u.id = r.user_id WHERE r.token_hash = ? AND r.used_at IS NULL AND r.expires_at > ?`, + [sha256(rawToken), Date.now()], + ) : null; + if (!reset) return res.type("html").send(authPage(req, { mode: "in", error: "That reset link is invalid or expired. Request a new one." })); + if (password.length < 8) return res.type("html").send(authPage(req, { mode: "reset", error: "Password must be at least 8 characters.", values: { email: reset.email, token: rawToken } })); + if (password !== confirmation) return res.type("html").send(authPage(req, { mode: "reset", error: "Passwords do not match.", values: { email: reset.email, token: rawToken } })); + const now = Date.now(); + await batch([ + { sql: `UPDATE users SET password_hash = ? WHERE id = ?`, args: [hashPassword(password), reset.user_id] }, + { sql: `UPDATE password_resets SET used_at = ? WHERE id = ?`, args: [now, reset.id] }, + { sql: `DELETE FROM sessions WHERE user_id = ?`, args: [reset.user_id] }, + ]); + res.redirect("/?reset=1"); +}); + +authRouter.post("/auth/recover", async (req, res) => { + const rawToken = String(req.body.token || ""); + const password = String(req.body.password || ""); + const confirmation = String(req.body.password_confirmation || ""); + const recovery = rawToken ? await get( + `SELECT r.id, r.user_id, u.email FROM recovery_tokens r JOIN users u ON u.id = r.user_id WHERE r.token_hash = ? AND r.used_at IS NULL AND r.revoked_at IS NULL AND r.expires_at > ?`, + [sha256(rawToken), Date.now()], + ) : null; + if (!recovery) return res.type("html").send(authPage(req, { mode: "in", error: "That recovery token is invalid, revoked, or already used." })); + if (password.length < 8) return res.type("html").send(authPage(req, { mode: "recover", error: "Password must be at least 8 characters.", values: { email: recovery.email, token: rawToken } })); + if (password !== confirmation) return res.type("html").send(authPage(req, { mode: "recover", error: "Passwords do not match.", values: { email: recovery.email, token: rawToken } })); + const now = Date.now(); + await batch([ + { sql: `UPDATE users SET password_hash = ? WHERE id = ?`, args: [hashPassword(password), recovery.user_id] }, + { sql: `UPDATE recovery_tokens SET used_at = ? WHERE id = ?`, args: [now, recovery.id] }, + { sql: `DELETE FROM sessions WHERE user_id = ?`, args: [recovery.user_id] }, + ]); + res.redirect("/?reset=1"); +}); + authRouter.post("/auth/logout", async (req, res) => { await destroySession(req, res); res.redirect("/"); diff --git a/apps/pwa/src/routes/pages.mjs b/apps/pwa/src/routes/pages.mjs index 48142915..c0428f62 100644 --- a/apps/pwa/src/routes/pages.mjs +++ b/apps/pwa/src/routes/pages.mjs @@ -4,16 +4,15 @@ // (public/vault.js); everything else here is ciphertext metadata. import { Router } from "express"; import { get, all, run, batch } from "../db.mjs"; -import { id, sha256 } from "../lib/crypto.mjs"; +import { id, token, sha256 } from "../lib/crypto.mjs"; import { page, footer, appBar, esc } from "../lib/html.mjs"; -import { requireAuth, csrfInput } from "../lib/session.mjs"; +import { requireAuth, csrfInput, getCeremony, setCeremony, clearCeremony } from "../lib/session.mjs"; import { ApiKeyError, createApiKey, keyCoversVault, listApiKeys, machineKeyOptions, revokeApiKey } from "../lib/apikey.mjs"; import { requestOrigin } from "../lib/origin.mjs"; import { CLI_HINT } from "../lib/cli-hint.mjs"; import { vaultPageBody } from "../lib/vault-page.mjs"; import { keyFingerprint } from "../lib/keyfp.mjs"; import { teamAudit } from "./credshare.mjs"; -import { setCeremony, getCeremony, clearCeremony } from "../lib/session.mjs"; import { config } from "../config.mjs"; import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile"; import { profiles } from "../lib/profile.mjs"; @@ -304,12 +303,15 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => { res.set("Cache-Control", "no-store"); const myKey = await get(`SELECT public_key, updated_at FROM credshare_keys WHERE user_id = ?`, [req.user.id]); const myGrants = await get(`SELECT COUNT(*) AS n FROM credshare_vault_grants WHERE user_id = ?`, [req.user.id]); + const recoveryToken = getCeremony(req, "recovery") || ""; + if (recoveryToken) clearCeremony(res, "recovery"); const err = req.query.err ? String(req.query.err).slice(0, 200) : ""; const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `
no keys yet
`; const body = `${appBar(req)}

Settings

${newKey ? `
New API key (copy it now — shown once):
${esc(newKey)}
` : ""} + ${recoveryToken ? `
Emergency recovery token — copy it into Bitwarden now; it is shown once:
${esc(recoveryToken)}
Use it at ${esc(`${config.origin}/auth/recover?token=${recoveryToken}`)} to set a new password. It is single-use.
` : ""} ${err ? `
${esc(KEY_ERRORS[err] || err)}
` : ""} ${req.query.saved === "profile" ? `
Your details are saved.
` : ""} ${req.query.saved === "identity-reset" ? `
Your identity key is reset and your vault grants are gone. Run logicsrc login to register a new key, then ask a teammate to grant you each vault again.
` : ""} @@ -355,6 +357,11 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => { +
Emergency recovery
+
+

Create a single-use recovery token for your password manager. The server stores only a hash; if you lose the plaintext, it cannot be recovered. Creating a new token revokes older ones.

+
${csrfInput(req)}
+
${footer}`; res.type("html").send(page({ title: "LogicSRC â–¸ settings", body })); }); @@ -416,3 +423,15 @@ pagesRouter.post("/settings/apikeys/:id/delete", requireAuth, async (req, res) = await revokeApiKey(req.user.id, req.params.id); res.redirect("/settings"); }); + +pagesRouter.post("/settings/recovery-token", requireAuth, async (req, res) => { + const rawToken = token(32); + const now = Date.now(); + await batch([ + { sql: `UPDATE recovery_tokens SET revoked_at = ? WHERE user_id = ? AND used_at IS NULL AND revoked_at IS NULL`, args: [now, req.user.id] }, + { sql: `INSERT INTO recovery_tokens (id, user_id, token_hash, created_at, expires_at) VALUES (?,?,?,?,?)`, args: [id(), req.user.id, sha256(rawToken), now, now + 1000 * 60 * 60 * 24 * 365] }, + ]); + // Keep the bearer token out of the URL, browser history, referrers, and access logs. + setCeremony(res, "recovery", rawToken, 1000 * 60 * 5); + res.redirect("/settings"); +});