${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.
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.
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.
+
+
${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");
+});