mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
feat(auth): add password reset and recovery flow
This commit is contained in:
parent
e60d31a1b4
commit
2c65baecbb
6 changed files with 184 additions and 18 deletions
10
apps/pwa/src/migrations-pg/007_password_resets.sql
Normal file
10
apps/pwa/src/migrations-pg/007_password_resets.sql
Normal file
|
|
@ -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);
|
||||||
10
apps/pwa/src/migrations-pg/008_recovery_tokens.sql
Normal file
10
apps/pwa/src/migrations-pg/008_recovery_tokens.sql
Normal file
|
|
@ -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);
|
||||||
10
apps/pwa/src/migrations/007_password_resets.sql
Normal file
10
apps/pwa/src/migrations/007_password_resets.sql
Normal file
|
|
@ -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);
|
||||||
10
apps/pwa/src/migrations/008_recovery_tokens.sql
Normal file
10
apps/pwa/src/migrations/008_recovery_tokens.sql
Normal file
|
|
@ -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);
|
||||||
|
|
@ -2,8 +2,9 @@
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { page, footer, esc } from "../lib/html.mjs";
|
import { page, footer, esc } from "../lib/html.mjs";
|
||||||
import { csrfInput, createSession, destroySession, takeNext } from "../lib/session.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 { createUserWithPassword, userByEmail } from "../lib/users.mjs";
|
||||||
|
import { get, run, batch } from "../db.mjs";
|
||||||
import { dashboardHandler } from "./pages.mjs";
|
import { dashboardHandler } from "./pages.mjs";
|
||||||
import { config } from "../config.mjs";
|
import { config } from "../config.mjs";
|
||||||
import { ringFooter } from "../lib/ring-footer.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();
|
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 = `
|
const body = `
|
||||||
<main class="wrap" style="max-width:440px;padding-top:8vh">
|
<main class="wrap" style="max-width:440px;padding-top:8vh">
|
||||||
<a class="brand" href="/" style="justify-content:center;font-size:1.5rem;margin-bottom:6px"><span class="mark">LS</span>LogicSRC<span class="app">credentials</span></a>
|
<a class="brand" href="/" style="justify-content:center;font-size:1.5rem;margin-bottom:6px"><span class="mark">LS</span>LogicSRC<span class="app">credentials</span></a>
|
||||||
<p class="label" style="text-align:center;margin-bottom:26px">Share secrets, end-to-end encrypted</p>
|
<p class="label" style="text-align:center;margin-bottom:26px">Share secrets, end-to-end encrypted</p>
|
||||||
<div class="card"><div class="card-body">
|
<div class="card"><div class="card-body">
|
||||||
${error ? `<div class="notice err">${esc(error)}</div>` : ""}
|
${error ? `<div class="notice err">${esc(error)}</div>` : ""}
|
||||||
<form method="post" action="/auth/${mode === "up" ? "register" : "login"}">
|
${notice ? `<div class="notice ok">${esc(notice)}</div>` : ""}
|
||||||
|
<form method="post" action="${action}">
|
||||||
${csrfInput(req)}
|
${csrfInput(req)}
|
||||||
|
${isReset ? `<input type="hidden" name="token" value="${esc(values.token ?? req.query.token ?? "")}">` : ""}
|
||||||
<label class="field"><span>Email</span>
|
<label class="field"><span>Email</span>
|
||||||
<input type="email" name="email" autocomplete="username" required placeholder="you@example.com" value="${esc(values.email ?? req.query.email ?? "")}"></label>
|
<input type="email" name="email" autocomplete="username" ${isReset ? "readonly" : "required"} placeholder="you@example.com" value="${esc(values.email ?? req.query.email ?? "")}"></label>
|
||||||
${mode === "up" ? renderProfileFields({ fields: SIGNUP_FIELDS, values, errors, idPrefix: "signup-" }) : ""}
|
${isSignup ? renderProfileFields({ fields: SIGNUP_FIELDS, values, errors, idPrefix: "signup-" }) : ""}
|
||||||
<label class="field"><span>Password</span>
|
${isForgot ? "" : `<label class="field"><span>${isReset ? "New password" : "Password"}</span>
|
||||||
<input type="password" name="password" autocomplete="${mode === "up" ? "new-password" : "current-password"}" required minlength="8" placeholder="8+ characters"></label>
|
<input type="password" name="password" autocomplete="${isSignup || isReset ? "new-password" : "current-password"}" required minlength="8" placeholder="8+ characters"></label>`}
|
||||||
<button class="btn acid block" type="submit">${mode === "up" ? "Create account" : "Sign in"}</button>
|
${isReset ? `<label class="field"><span>Confirm new password</span><input type="password" name="password_confirmation" autocomplete="new-password" required minlength="8" placeholder="repeat password"></label>` : ""}
|
||||||
|
<button class="btn acid block" type="submit">${isForgot ? "Email reset link" : isReset ? "Reset password" : isSignup ? "Create account" : "Sign in"}</button>
|
||||||
</form>
|
</form>
|
||||||
<p class="mono" style="text-align:center;font-size:.74rem;margin:14px 0 0">
|
<p class="mono" style="text-align:center;font-size:.74rem;margin:14px 0 0">
|
||||||
${mode === "up"
|
${isForgot || isReset
|
||||||
|
? `<a class="acid" href="/?mode=in">Back to sign in</a>`
|
||||||
|
: isSignup
|
||||||
? `Already have an account? <a class="acid" href="/?mode=in">Sign in</a>`
|
? `Already have an account? <a class="acid" href="/?mode=in">Sign in</a>`
|
||||||
: `New here? <a class="acid" href="/?mode=up">Create account</a>`}
|
: `New here? <a class="acid" href="/?mode=up">Create account</a>`}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div class="divider">or</div>
|
${mode === "in" ? `<p class="mono" style="text-align:center;font-size:.74rem;margin:8px 0 0"><a class="acid" href="/?mode=forgot">Forgot password?</a></p>` : ""}
|
||||||
|
|
||||||
<button class="btn block" type="button" id="passkey-btn" style="margin-bottom:10px">🔑 Continue with a passkey</button>
|
${isForgot || isReset ? "" : `<div class="divider">or</div>`}
|
||||||
|
|
||||||
|
${isForgot || isReset ? "" : `<button class="btn block" type="button" id="passkey-btn" style="margin-bottom:10px">🔑 Continue with a passkey</button>
|
||||||
${config.coinpayLoginEnabled
|
${config.coinpayLoginEnabled
|
||||||
? `<a class="btn block" href="/auth/coinpay/start">◆ Continue with CoinPay</a>`
|
? `<a class="btn block" href="/auth/coinpay/start">◆ Continue with CoinPay</a>`
|
||||||
: `<button class="btn block" type="button" disabled title="Set COINPAY_OAUTH_* to enable">◆ Continue with CoinPay</button>`}
|
: `<button class="btn block" type="button" disabled title="Set COINPAY_OAUTH_* to enable">◆ Continue with CoinPay</button>`}
|
||||||
<p id="passkey-msg" class="mono faint" style="font-size:.72rem;text-align:center;margin:12px 0 0"></p>
|
<p id="passkey-msg" class="mono faint" style="font-size:.72rem;text-align:center;margin:12px 0 0"></p>`}
|
||||||
</div></div>
|
</div></div>
|
||||||
</main>${footer}${ringFooter()}
|
</main>${footer}${ringFooter()}
|
||||||
<script src="/vendor/simplewebauthn-browser.umd.js"></script>
|
${isForgot || isReset ? "" : `<script src="/vendor/simplewebauthn-browser.umd.js"></script><script src="/passkey.js"></script>`}${isSignup ? `<script src="/vendor/profile-enhance.js" defer></script>` : ""}`;
|
||||||
<script src="/passkey.js"></script>${mode === "up" ? `<script src="/vendor/profile-enhance.js" defer></script>` : ""}`;
|
|
||||||
return page({ title: "LogicSRC ▸ sign in", body });
|
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) => {
|
authRouter.get("/", (req, res) => {
|
||||||
if (req.user) {
|
if (req.user) {
|
||||||
const next = takeNext(req, res);
|
const next = takeNext(req, res);
|
||||||
if (next) return res.redirect(next);
|
if (next) return res.redirect(next);
|
||||||
return dashboardHandler(req, res); // dashboard lives at the root
|
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) => {
|
authRouter.post("/auth/register", async (req, res) => {
|
||||||
|
|
@ -94,6 +144,63 @@ authRouter.post("/auth/login", async (req, res) => {
|
||||||
res.redirect(takeNext(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) => {
|
authRouter.post("/auth/logout", async (req, res) => {
|
||||||
await destroySession(req, res);
|
await destroySession(req, res);
|
||||||
res.redirect("/");
|
res.redirect("/");
|
||||||
|
|
|
||||||
|
|
@ -4,16 +4,15 @@
|
||||||
// (public/vault.js); everything else here is ciphertext metadata.
|
// (public/vault.js); everything else here is ciphertext metadata.
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { get, all, run, batch } from "../db.mjs";
|
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 { 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 { ApiKeyError, createApiKey, keyCoversVault, listApiKeys, machineKeyOptions, revokeApiKey } from "../lib/apikey.mjs";
|
||||||
import { requestOrigin } from "../lib/origin.mjs";
|
import { requestOrigin } from "../lib/origin.mjs";
|
||||||
import { CLI_HINT } from "../lib/cli-hint.mjs";
|
import { CLI_HINT } from "../lib/cli-hint.mjs";
|
||||||
import { vaultPageBody } from "../lib/vault-page.mjs";
|
import { vaultPageBody } from "../lib/vault-page.mjs";
|
||||||
import { keyFingerprint } from "../lib/keyfp.mjs";
|
import { keyFingerprint } from "../lib/keyfp.mjs";
|
||||||
import { teamAudit } from "./credshare.mjs";
|
import { teamAudit } from "./credshare.mjs";
|
||||||
import { setCeremony, getCeremony, clearCeremony } from "../lib/session.mjs";
|
|
||||||
import { config } from "../config.mjs";
|
import { config } from "../config.mjs";
|
||||||
import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile";
|
import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile";
|
||||||
import { profiles } from "../lib/profile.mjs";
|
import { profiles } from "../lib/profile.mjs";
|
||||||
|
|
@ -304,12 +303,15 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
|
||||||
res.set("Cache-Control", "no-store");
|
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 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 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 err = req.query.err ? String(req.query.err).slice(0, 200) : "";
|
||||||
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
|
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
|
||||||
const body = `${appBar(req)}
|
const body = `${appBar(req)}
|
||||||
<main class="wrap" style="max-width:720px;padding-top:30px">
|
<main class="wrap" style="max-width:720px;padding-top:30px">
|
||||||
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
|
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
|
||||||
${newKey ? `<div class="notice ok">New API key (copy it now — shown once):<br><b class="mono" style="word-break:break-all">${esc(newKey)}</b></div>` : ""}
|
${newKey ? `<div class="notice ok">New API key (copy it now — shown once):<br><b class="mono" style="word-break:break-all">${esc(newKey)}</b></div>` : ""}
|
||||||
|
${recoveryToken ? `<div class="notice ok">Emergency recovery token — copy it into Bitwarden now; it is shown once:<br><b class="mono" style="word-break:break-all">${esc(recoveryToken)}</b><br><span class="faint">Use it at ${esc(`${config.origin}/auth/recover?token=${recoveryToken}`)} to set a new password. It is single-use.</span></div>` : ""}
|
||||||
${err ? `<div class="notice err">${esc(KEY_ERRORS[err] || err)}</div>` : ""}
|
${err ? `<div class="notice err">${esc(KEY_ERRORS[err] || err)}</div>` : ""}
|
||||||
${req.query.saved === "profile" ? `<div class="notice ok">Your details are saved.</div>` : ""}
|
${req.query.saved === "profile" ? `<div class="notice ok">Your details are saved.</div>` : ""}
|
||||||
${req.query.saved === "identity-reset" ? `<div class="notice ok">Your identity key is reset and your vault grants are gone. Run <code>logicsrc login</code> to register a new key, then ask a teammate to grant you each vault again.</div>` : ""}
|
${req.query.saved === "identity-reset" ? `<div class="notice ok">Your identity key is reset and your vault grants are gone. Run <code>logicsrc login</code> to register a new key, then ask a teammate to grant you each vault again.</div>` : ""}
|
||||||
|
|
@ -355,6 +357,11 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
|
||||||
<button class="btn">Create key</button>
|
<button class="btn">Create key</button>
|
||||||
</form>
|
</form>
|
||||||
</div></div>
|
</div></div>
|
||||||
|
<div class="card" style="margin-top:20px"><div class="card-head"><span class="h">Emergency recovery</span></div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="dim" style="font-size:.85rem;margin-top:0">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.</p>
|
||||||
|
<form method="post" action="/settings/recovery-token">${csrfInput(req)}<button class="btn danger">Generate recovery token</button></form>
|
||||||
|
</div></div>
|
||||||
</main>${footer}`;
|
</main>${footer}`;
|
||||||
res.type("html").send(page({ title: "LogicSRC ▸ settings", body }));
|
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);
|
await revokeApiKey(req.user.id, req.params.id);
|
||||||
res.redirect("/settings");
|
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");
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue