Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

auth.tsx

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

auth.tsxBlame881 lines · 3 contributors
06d5ffeClaude1/**
2 * Auth routes — register, login, logout (web + API).
3 */
4
5import { Hono } from "hono";
7298a17Claude6import { setCookie, deleteCookie, getCookie } from "hono/cookie";
a4f3e24Claude7import { and, eq, isNull, sql } from "drizzle-orm";
06d5ffeClaude8import { db } from "../db";
7298a17Claude9import {
10 users,
11 sessions,
12 organizations,
13 userTotp,
14 userRecoveryCodes,
15} from "../db/schema";
06d5ffeClaude16import {
17 hashPassword,
18 verifyPassword,
19 generateSessionToken,
20 sessionCookieOptions,
21 sessionExpiry,
22} from "../lib/auth";
7298a17Claude23import { verifyTotpCode, hashRecoveryCode } from "../lib/totp";
c63b860Claude24import { cancelAccountDeletion } from "../lib/account-deletion";
582cdacClaude25import {
26 getSsoConfig,
27 getGithubOauthConfig,
28 getGoogleOauthConfig,
29} from "../lib/sso";
06d5ffeClaude30import { Layout } from "../views/layout";
bb0f894Claude31import {
32 Form,
33 FormGroup,
34 Input,
35 Button,
09be7bfClaude36 LinkButton,
bb0f894Claude37 Alert,
38 Text,
39} from "../views/ui";
36cc17aClaude40import { softAuth } from "../middleware/auth";
06d5ffeClaude41import type { AuthEnv } from "../middleware/auth";
42
43const auth = new Hono<AuthEnv>();
44
976d7f7Claude45// One-shot latch — log the auto-verify warning at most once per process,
46// since the misconfiguration is operator-level (env var) and won't change
47// between requests.
48let _autoVerifyWarned = false;
49
ebe6d64Claude50// ───────────────────────────────────────────────────────────────────────
51// Scoped mobile polish — tightens the existing `.auth-container` shell
52// from layout.tsx for ≤720px viewports. Only adds rules; does not
53// redefine the desktop styling. Kept inline so this file remains the
54// single source of truth for the auth surface.
55// ───────────────────────────────────────────────────────────────────────
56const authMobileCss = `
57 @media (max-width: 720px) {
58 .auth-container {
59 margin: 24px 12px;
60 padding: 24px 20px 22px;
61 max-width: 100%;
62 }
63 .auth-container .btn-primary { min-height: 44px; }
64 .auth-container .oauth-btn { min-height: 44px; }
65 .auth-container input[type="text"],
66 .auth-container input[type="email"],
67 .auth-container input[type="password"] { min-height: 44px; }
68 .auth-forgot { text-align: left !important; }
69 }
70`;
71const AuthMobileStyle = () => (
72 <style dangerouslySetInnerHTML={{ __html: authMobileCss }} />
73);
74
06d5ffeClaude75// --- Web UI ---
76
36cc17aClaude77auth.get("/register", softAuth, (c) => {
78 // If the user is already signed in, drop them on their dashboard rather
79 // than rendering the logged-out sign-up shell over an authed session.
80 const existing = c.get("user");
81 if (existing) return c.redirect("/dashboard");
06d5ffeClaude82 const error = c.req.query("error");
134750bClaude83 const csrf = c.get("csrfToken") as string | undefined;
06d5ffeClaude84 return c.html(
36cc17aClaude85 <Layout title="Register" user={null}>
ebe6d64Claude86 <AuthMobileStyle />
06d5ffeClaude87 <div class="auth-container">
98f45b4Claude88 <h2>Create your account</h2>
89 <p class="auth-subtitle">
90 Get the full AI suite — code review, auto-merge, spec-to-PR — on
91 unlimited public repos. No credit card.
92 </p>
06d5ffeClaude93 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
134750bClaude94 <Form method="post" action="/register" csrfToken={csrf}>
0316dbbClaude95 <FormGroup label="Username" htmlFor="username">
96 <Input
97 id="username"
06d5ffeClaude98 type="text"
99 name="username"
100 required
101 pattern="^[a-zA-Z0-9_-]+$"
102 minLength={2}
103 maxLength={39}
104 placeholder="your-username"
105 autocomplete="username"
106 />
bb0f894Claude107 </FormGroup>
108 <FormGroup label="Email" htmlFor="email">
109 <Input
06d5ffeClaude110 type="email"
111 name="email"
112 required
113 placeholder="you@example.com"
114 autocomplete="email"
2c3ba6ecopilot-swe-agent[bot]115 aria-label="Email"
06d5ffeClaude116 />
bb0f894Claude117 </FormGroup>
118 <FormGroup label="Password" htmlFor="password">
119 <Input
06d5ffeClaude120 type="password"
121 name="password"
122 required
123 minLength={8}
124 placeholder="Min 8 characters"
125 autocomplete="new-password"
2c3ba6ecopilot-swe-agent[bot]126 aria-label="Password"
06d5ffeClaude127 />
bb0f894Claude128 </FormGroup>
c63b860Claude129 {/* P3 — Terms / Privacy acceptance. Required client-side via the
130 `required` attribute; server-side re-checked in POST handler. */}
131 <div class="form-group" style="margin: 12px 0">
132 <label style="display: flex; gap: 8px; align-items: flex-start; font-size: 13px; color: var(--text-muted)">
133 <input
134 type="checkbox"
135 name="accept_terms"
136 value="1"
137 required
138 style="margin-top: 3px"
139 aria-label="Accept Terms of Service and Privacy Policy"
140 />
141 <span>
142 I agree to the{" "}
2e8a4d5Claude143 <a href="/terms" target="_blank" rel="noopener">
c63b860Claude144 Terms of Service
145 </a>{" "}
146 and{" "}
2e8a4d5Claude147 <a href="/privacy" target="_blank" rel="noopener">
c63b860Claude148 Privacy Policy
149 </a>
150 .
151 </span>
152 </label>
153 </div>
bb0f894Claude154 <Button type="submit" variant="primary">
06d5ffeClaude155 Create account
bb0f894Claude156 </Button>
157 </Form>
06d5ffeClaude158 <p class="auth-switch">
bb0f894Claude159 <Text>Already have an account? <a href="/login">Sign in</a></Text>
06d5ffeClaude160 </p>
161 </div>
162 </Layout>
163 );
164});
165
166auth.post("/register", async (c) => {
167 const body = await c.req.parseBody();
168 const username = String(body.username || "").trim();
169 const email = String(body.email || "").trim();
170 const password = String(body.password || "");
171
172 if (!username || !email || !password) {
173 return c.redirect("/register?error=All+fields+are+required");
174 }
175
c63b860Claude176 // Block P3 — Terms acceptance is required. The form's checkbox has
177 // `required` so browsers normally enforce client-side; the server
178 // re-checks for defensive depth (curl, scripted POST, etc.).
179 if (!body.accept_terms) {
180 return c.redirect(
181 "/register?error=Please+accept+the+Terms+of+Service+and+Privacy+Policy"
182 );
183 }
184
06d5ffeClaude185 if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
186 return c.redirect(
187 "/register?error=Username+may+only+contain+letters%2C+numbers%2C+hyphens+and+underscores"
188 );
189 }
190
191 if (password.length < 8) {
192 return c.redirect("/register?error=Password+must+be+at+least+8+characters");
193 }
194
195 // Check existing
196 const [existingUser] = await db
197 .select()
198 .from(users)
199 .where(eq(users.username, username))
200 .limit(1);
201 if (existingUser) {
202 return c.redirect("/register?error=Username+already+taken");
203 }
204
7437605Claude205 // B2: usernames share the URL namespace with org slugs; refuse collisions.
206 const [existingOrg] = await db
207 .select({ id: organizations.id })
208 .from(organizations)
209 .where(eq(organizations.slug, username.toLowerCase()))
210 .limit(1);
211 if (existingOrg) {
212 return c.redirect("/register?error=Username+already+taken");
213 }
214
06d5ffeClaude215 const [existingEmail] = await db
216 .select()
217 .from(users)
218 .where(eq(users.email, email))
219 .limit(1);
220 if (existingEmail) {
221 return c.redirect("/register?error=Email+already+registered");
222 }
223
224 const passwordHash = await hashPassword(password);
225
a4f3e24Claude226 // First user ever registered becomes admin automatically
227 const [userCount] = await db
228 .select({ count: sql`count(*)::int` })
229 .from(users);
230 const isFirstUser = (userCount?.count as number) === 0;
231
06d5ffeClaude232 const [user] = await db
233 .insert(users)
c63b860Claude234 .values({
235 username,
236 email,
237 passwordHash,
238 isAdmin: isFirstUser,
239 // P3 — record terms acceptance now. Version bumps when Terms change.
240 termsAcceptedAt: new Date(),
241 termsVersion: "1.0",
242 })
06d5ffeClaude243 .returning();
244
2d985e5Claude245 // If username matches SITE_ADMIN_USERNAME env, grant site admin instantly
246 // so the operator doesn't have to wait for the next boot's bootstrap pass.
a28cedeClaude247 await import("../lib/admin-bootstrap")
248 .then((m) => m.ensureEnvAdminOnRegister({ userId: user.id, username }))
249 .catch((err) => {
250 console.warn(
251 `[admin-bootstrap] ensureEnvAdminOnRegister failed for ${username}:`,
252 err instanceof Error ? err.message : err
253 );
254 });
2d985e5Claude255
06d5ffeClaude256 // Create session
257 const token = generateSessionToken();
258 await db.insert(sessions).values({
259 userId: user.id,
260 token,
261 expiresAt: sessionExpiry(),
262 });
263
264 setCookie(c, "session", token, sessionCookieOptions());
265
976d7f7Claude266 // Block P2 — email verification. If RESEND_API_KEY is configured the
267 // verification email goes out and the user clicks the link to verify.
268 // If email is NOT configured (EMAIL_PROVIDER=log, no RESEND_API_KEY,
269 // etc.), the email would silently never arrive and the user would be
270 // locked out — AUDIT-v2.md P0 #3. In that case, auto-verify the
271 // account on registration so the user can actually use the site.
272 // Operators who want real verification should set EMAIL_PROVIDER=resend
273 // + RESEND_API_KEY in their environment.
274 const { config: _emailConfig } = await import("../lib/config");
275 const emailConfigured =
276 _emailConfig.emailProvider === "resend" && !!_emailConfig.resendApiKey;
277 if (emailConfigured) {
278 import("../lib/email-verification")
279 .then((m) => m.startEmailVerification(user.id, email))
280 .catch((err) => {
281 console.error(
282 `[auth] startEmailVerification failed for ${user.id}:`,
283 err instanceof Error ? err.message : err
284 );
285 });
286 } else {
287 // Auto-verify immediately so the user isn't trapped in an unverified
288 // state. Log once so operators notice the misconfiguration.
289 if (!_autoVerifyWarned) {
290 _autoVerifyWarned = true;
291 console.warn(
292 "[auth] EMAIL_PROVIDER is not configured (set EMAIL_PROVIDER=resend + RESEND_API_KEY). Auto-verifying new account email addresses to avoid lockout."
293 );
294 }
295 await db
296 .update(users)
297 .set({ emailVerifiedAt: new Date() })
298 .where(eq(users.id, user.id))
299 .catch((err) => {
300 console.error(
301 `[auth] auto-verify failed for ${user.id}:`,
302 err instanceof Error ? err.message : err
303 );
304 });
305 }
c63b860Claude306
307 // P3 — default landing is /onboarding (the guided first-five-minutes
308 // flow). The `redirect=` query is still honoured for OAuth-style flows.
309 const redirect = c.req.query("redirect") || "/onboarding?welcome=1";
06d5ffeClaude310 return c.redirect(redirect);
311});
312
36cc17aClaude313auth.get("/login", softAuth, async (c) => {
314 // Already-authed users hitting the sign-in page get bounced to their
315 // dashboard (or the `redirect=` target if one was supplied).
316 const existing = c.get("user");
06d5ffeClaude317 const error = c.req.query("error");
c63b860Claude318 const success = c.req.query("success");
06d5ffeClaude319 const redirect = c.req.query("redirect") || "";
36cc17aClaude320 if (existing) return c.redirect(redirect || "/dashboard");
edf7c36Claude321 const ssoCfg = await getSsoConfig();
322 const ssoEnabled =
323 !!ssoCfg?.enabled &&
324 !!ssoCfg.authorizationEndpoint &&
325 !!ssoCfg.tokenEndpoint &&
326 !!ssoCfg.userinfoEndpoint &&
327 !!ssoCfg.clientId &&
328 !!ssoCfg.clientSecret;
fc0ca99Claude329 const ssoLabel =
330 ssoCfg?.providerName || inferSsoProviderName(ssoCfg) || "SSO";
46d6165Claude331 // Block L6 — "Sign in with GitHub" (separate row keyed id='github').
332 const githubCfg = await getGithubOauthConfig();
333 const githubEnabled =
334 !!githubCfg?.enabled && !!githubCfg.clientId && !!githubCfg.clientSecret;
582cdacClaude335 // "Sign in with Google" (separate row keyed id='google'). Same wiring
336 // pattern as GitHub OAuth.
337 const googleCfg = await getGoogleOauthConfig();
338 const googleEnabled =
339 !!googleCfg?.enabled && !!googleCfg.clientId && !!googleCfg.clientSecret;
134750bClaude340 const csrf = c.get("csrfToken") as string | undefined;
06d5ffeClaude341 return c.html(
36cc17aClaude342 <Layout title="Sign in" user={null}>
ebe6d64Claude343 <AuthMobileStyle />
06d5ffeClaude344 <div class="auth-container">
98f45b4Claude345 <h2>Welcome back</h2>
346 <p class="auth-subtitle">
347 Sign in to your gluecron account.
348 </p>
06d5ffeClaude349 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
c63b860Claude350 {success && (
351 <div class="auth-success">{decodeURIComponent(success)}</div>
352 )}
0316dbbClaude353 <Form
b9968e3Claude354 method="post"
06d5ffeClaude355 action={`/login${redirect ? `?redirect=${encodeURIComponent(redirect)}` : ""}`}
134750bClaude356 csrfToken={csrf}
06d5ffeClaude357 >
bb0f894Claude358 <FormGroup label="Username or email" htmlFor="username">
359 <Input
06d5ffeClaude360 type="text"
361 name="username"
362 required
363 placeholder="username or email"
364 autocomplete="username"
2c3ba6ecopilot-swe-agent[bot]365 aria-label="Username or email"
06d5ffeClaude366 />
bb0f894Claude367 </FormGroup>
368 <FormGroup label="Password" htmlFor="password">
369 <Input
06d5ffeClaude370 type="password"
371 name="password"
372 required
373 placeholder="Password"
374 autocomplete="current-password"
2c3ba6ecopilot-swe-agent[bot]375 aria-label="Password"
06d5ffeClaude376 />
bb0f894Claude377 </FormGroup>
c63b860Claude378 <div class="auth-forgot" style="margin:-8px 0 12px;text-align:right;font-size:13px">
379 <a href="/forgot-password">Forgot password?</a>
cd4f63bTest User380 {/* BLOCK Q2 — magic-link sign-in. */}
381 <span style="margin:0 6px;color:var(--text-muted)">·</span>
382 <a href="/login/magic">Sign in with a magic link instead</a>
c63b860Claude383 </div>
bb0f894Claude384 <Button type="submit" variant="primary">
06d5ffeClaude385 Sign in
bb0f894Claude386 </Button>
387 </Form>
582cdacClaude388 {/* Provider buttons (Google + GitHub) — only rendered when the
389 admin has configured + enabled them via /admin/google-oauth or
390 /admin/github-oauth. The "or" divider above the first available
391 provider sets the visual break from the password form. */}
392 {(googleEnabled || githubEnabled) && (
393 <div class="auth-divider">or</div>
394 )}
395 {googleEnabled && (
396 <a
397 href="/login/google"
398 class="btn btn-block oauth-btn oauth-google"
399 aria-label="Sign in with Google"
400 >
401 <svg
402 class="oauth-icon"
403 width="18"
404 height="18"
405 viewBox="0 0 18 18"
406 aria-hidden="true"
407 >
408 <path
409 d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"
410 fill="#4285F4"
411 />
412 <path
413 d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z"
414 fill="#34A853"
415 />
416 <path
417 d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"
418 fill="#FBBC05"
419 />
420 <path
421 d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"
422 fill="#EA4335"
423 />
424 </svg>
425 <span>Sign in with Google</span>
426 </a>
427 )}
46d6165Claude428 {githubEnabled && (
582cdacClaude429 <a
430 href="/login/github"
431 class="btn btn-block oauth-btn oauth-github"
432 aria-label="Sign in with GitHub"
433 style={googleEnabled ? "margin-top:8px" : undefined}
434 >
435 <svg
436 class="oauth-icon"
437 width="18"
438 height="18"
439 viewBox="0 0 16 16"
440 aria-hidden="true"
441 fill="currentColor"
442 >
443 <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z" />
444 </svg>
445 <span>Sign in with GitHub</span>
446 </a>
46d6165Claude447 )}
09be7bfClaude448 {ssoEnabled && (
582cdacClaude449 <a
450 href="/login/sso"
451 class="btn btn-block oauth-btn oauth-sso"
452 aria-label={`Sign in with ${ssoLabel}`}
453 style={(googleEnabled || githubEnabled) ? "margin-top:8px" : undefined}
454 >
455 <span>Sign in with {ssoLabel}</span>
456 </a>
09be7bfClaude457 )}
fa06ad2Claude458 <div class="auth-passkey">
459 <div class="auth-divider">or</div>
460 <button type="button" id="pk-signin-btn" class="btn">
461 Sign in with passkey
462 </button>
463 <div
464 id="pk-signin-status"
465 class="auth-status"
466 aria-live="polite"
467 ></div>
468 </div>
06d5ffeClaude469 <p class="auth-switch">
bb0f894Claude470 <Text>New to gluecron? <a href="/register">Create an account</a></Text>
06d5ffeClaude471 </p>
2df1f8cClaude472 <script
473 dangerouslySetInnerHTML={{
474 __html: /* js */ `
475 (function () {
476 const btn = document.getElementById('pk-signin-btn');
477 const status = document.getElementById('pk-signin-status');
478 const userInput = document.getElementById('username');
479 const redirect = ${JSON.stringify(redirect || "/")};
480 if (!btn) return;
481 function b64uToBuf(s) {
482 s = s.replace(/-/g,'+').replace(/_/g,'/');
483 while (s.length % 4) s += '=';
484 const bin = atob(s);
485 const buf = new Uint8Array(bin.length);
486 for (let i=0;i<bin.length;i++) buf[i] = bin.charCodeAt(i);
487 return buf.buffer;
488 }
489 function bufToB64u(buf) {
490 const bytes = new Uint8Array(buf);
491 let bin = '';
492 for (let i=0;i<bytes.length;i++) bin += String.fromCharCode(bytes[i]);
493 return btoa(bin).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');
494 }
495 btn.addEventListener('click', async function () {
496 if (!window.PublicKeyCredential) {
497 status.textContent = 'Passkeys not supported in this browser.';
498 return;
499 }
500 status.textContent = 'Preparing…';
501 try {
502 const username = (userInput && userInput.value || '').trim();
503 const optsRes = await fetch('/api/passkeys/auth/options', {
504 method: 'POST',
505 headers: { 'content-type': 'application/json' },
506 body: JSON.stringify(username ? { username: username } : {})
507 });
508 if (!optsRes.ok) throw new Error('options failed');
509 const { options, sessionKey } = await optsRes.json();
510 options.challenge = b64uToBuf(options.challenge);
511 if (options.allowCredentials) {
512 options.allowCredentials = options.allowCredentials.map(function (c) {
513 return Object.assign({}, c, { id: b64uToBuf(c.id) });
514 });
515 }
516 status.textContent = 'Touch your authenticator…';
517 const cred = await navigator.credentials.get({ publicKey: options });
518 const resp = {
519 id: cred.id,
520 rawId: bufToB64u(cred.rawId),
521 type: cred.type,
522 response: {
523 clientDataJSON: bufToB64u(cred.response.clientDataJSON),
524 authenticatorData: bufToB64u(cred.response.authenticatorData),
525 signature: bufToB64u(cred.response.signature),
526 userHandle: cred.response.userHandle ? bufToB64u(cred.response.userHandle) : null
527 },
528 clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
529 };
530 const verifyRes = await fetch('/api/passkeys/auth/verify', {
531 method: 'POST',
532 headers: { 'content-type': 'application/json' },
533 body: JSON.stringify({ sessionKey: sessionKey, response: resp })
534 });
535 if (!verifyRes.ok) {
536 const j = await verifyRes.json().catch(function () { return {}; });
537 throw new Error(j.error || 'verify failed');
538 }
539 status.textContent = 'Signed in. Redirecting…';
540 window.location.href = redirect;
541 } catch (e) {
542 status.textContent = 'Error: ' + (e && e.message ? e.message : e);
543 }
544 });
545 })();
546 `,
547 }}
548 />
06d5ffeClaude549 </div>
550 </Layout>
551 );
552});
553
554auth.post("/login", async (c) => {
555 const body = await c.req.parseBody();
556 const identifier = String(body.username || "").trim();
557 const password = String(body.password || "");
558 const redirect = c.req.query("redirect") || "/";
559
560 if (!identifier || !password) {
561 return c.redirect("/login?error=All+fields+are+required");
562 }
563
564 // Find user by username or email
565 const isEmail = identifier.includes("@");
566 const [user] = await db
567 .select()
568 .from(users)
569 .where(
570 isEmail
571 ? eq(users.email, identifier)
572 : eq(users.username, identifier)
573 )
574 .limit(1);
575
576 if (!user) {
577 return c.redirect("/login?error=Invalid+credentials");
578 }
579
580 const valid = await verifyPassword(password, user.passwordHash);
581 if (!valid) {
582 return c.redirect("/login?error=Invalid+credentials");
583 }
584
7298a17Claude585 // B4: if the user has TOTP enabled, issue a pending-2fa session and
586 // redirect to the code prompt.
587 const [totp] = await db
588 .select({ enabledAt: userTotp.enabledAt })
589 .from(userTotp)
590 .where(eq(userTotp.userId, user.id))
591 .limit(1);
592 const needs2fa = !!(totp && totp.enabledAt);
593
06d5ffeClaude594 const token = generateSessionToken();
595 await db.insert(sessions).values({
596 userId: user.id,
597 token,
598 expiresAt: sessionExpiry(),
7298a17Claude599 requires2fa: needs2fa,
06d5ffeClaude600 });
601
602 setCookie(c, "session", token, sessionCookieOptions());
c63b860Claude603
604 // Block P5 — If account was scheduled for deletion but user signed back
605 // in, cancel the deletion. Safe regardless of 2FA: password was proven.
606 if (user.deletedAt) {
607 await cancelAccountDeletion(user.id);
608 }
609
7298a17Claude610 if (needs2fa) {
611 return c.redirect(
612 `/login/2fa?redirect=${encodeURIComponent(redirect)}`
613 );
614 }
06d5ffeClaude615 return c.redirect(redirect);
616});
617
7298a17Claude618// --- 2FA verify (B4) ---
619auth.get("/login/2fa", async (c) => {
620 const token = getCookie(c, "session");
621 if (!token) return c.redirect("/login");
622 const error = c.req.query("error");
623 const redirect = c.req.query("redirect") || "/";
624 return c.html(
36cc17aClaude625 <Layout title="Two-factor authentication" user={null}>
ebe6d64Claude626 <AuthMobileStyle />
7298a17Claude627 <div class="auth-container">
628 <h2>Enter your code</h2>
629 <p
630 class="auth-switch"
631 style="margin-bottom: 16px; margin-top: 0"
632 >
633 Open your authenticator app and enter the 6-digit code. Lost your
634 device? Paste a recovery code instead.
635 </p>
636 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
637 <form
b9968e3Claude638 method="post"
7298a17Claude639 action={`/login/2fa?redirect=${encodeURIComponent(redirect)}`}
640 >
134750bClaude641 <input type="hidden" name="_csrf" value={(c.get("csrfToken") as string | undefined) || ""} />
7298a17Claude642 <div class="form-group">
643 <label for="code">Code</label>
644 <input
645 type="text"
646 id="code"
647 name="code"
648 required
649 autocomplete="one-time-code"
650 inputmode="numeric"
651 maxLength={24}
652 placeholder="123456 or xxxx-xxxx-xxxx"
653 />
654 </div>
655 <button type="submit" class="btn btn-primary">
656 Verify
657 </button>
658 </form>
659 <p class="auth-switch">
660 <a href="/logout">Cancel</a>
661 </p>
662 </div>
663 </Layout>
664 );
665});
666
667auth.post("/login/2fa", async (c) => {
668 const token = getCookie(c, "session");
669 if (!token) return c.redirect("/login");
670 const body = await c.req.parseBody();
671 const code = String(body.code || "").trim();
672 const redirect = c.req.query("redirect") || "/";
673
674 if (!code) {
675 return c.redirect(
676 `/login/2fa?error=Code+is+required&redirect=${encodeURIComponent(redirect)}`
677 );
678 }
679
680 try {
681 const [session] = await db
682 .select()
683 .from(sessions)
684 .where(eq(sessions.token, token))
685 .limit(1);
686 if (
687 !session ||
688 new Date(session.expiresAt) < new Date() ||
689 !session.requires2fa
690 ) {
691 return c.redirect("/login");
692 }
693
694 const [totp] = await db
695 .select()
696 .from(userTotp)
697 .where(eq(userTotp.userId, session.userId))
698 .limit(1);
699 if (!totp || !totp.enabledAt) {
700 // User doesn't have 2FA actually enabled — clear the flag and let
701 // them in. This can only happen if 2FA was disabled in another
702 // session between password check and code prompt.
703 await db
704 .update(sessions)
705 .set({ requires2fa: false })
706 .where(eq(sessions.token, token));
707 return c.redirect(redirect);
708 }
709
710 // Try TOTP code first.
711 const isSix = /^\d{6}$/.test(code);
712 let ok = false;
713 if (isSix) {
714 ok = await verifyTotpCode(totp.secret, code);
715 }
716 // Fall through to recovery code.
717 if (!ok) {
718 const hash = await hashRecoveryCode(code);
719 const [rec] = await db
720 .select()
721 .from(userRecoveryCodes)
722 .where(
723 and(
724 eq(userRecoveryCodes.userId, session.userId),
725 eq(userRecoveryCodes.codeHash, hash),
726 isNull(userRecoveryCodes.usedAt)
727 )
728 )
729 .limit(1);
730 if (rec) {
731 await db
732 .update(userRecoveryCodes)
733 .set({ usedAt: new Date() })
734 .where(eq(userRecoveryCodes.id, rec.id));
735 ok = true;
736 }
737 }
738
739 if (!ok) {
740 return c.redirect(
741 `/login/2fa?error=Invalid+code&redirect=${encodeURIComponent(redirect)}`
742 );
743 }
744
745 await db
746 .update(sessions)
747 .set({ requires2fa: false })
748 .where(eq(sessions.token, token));
749 await db
750 .update(userTotp)
751 .set({ lastUsedAt: new Date() })
752 .where(eq(userTotp.userId, session.userId));
753
754 return c.redirect(redirect);
755 } catch (err) {
756 console.error("[auth] 2fa verify:", err);
757 return c.redirect(
758 `/login/2fa?error=Service+unavailable&redirect=${encodeURIComponent(redirect)}`
759 );
760 }
761});
762
06d5ffeClaude763auth.get("/logout", async (c) => {
764 deleteCookie(c, "session", { path: "/" });
765 return c.redirect("/");
766});
767
768// --- API ---
769
770auth.post("/api/auth/register", async (c) => {
771 const body = await c.req.json<{
772 username: string;
773 email: string;
774 password: string;
775 }>();
776
777 if (!body.username || !body.email || !body.password) {
778 return c.json({ error: "username, email, and password are required" }, 400);
779 }
780
781 if (!/^[a-zA-Z0-9_-]+$/.test(body.username)) {
782 return c.json({ error: "Invalid username" }, 400);
783 }
784
785 if (body.password.length < 8) {
786 return c.json({ error: "Password must be at least 8 characters" }, 400);
787 }
788
789 const [existing] = await db
790 .select()
791 .from(users)
792 .where(eq(users.username, body.username))
793 .limit(1);
794 if (existing) {
795 return c.json({ error: "Username already taken" }, 409);
796 }
797
798 const passwordHash = await hashPassword(body.password);
799 const [user] = await db
800 .insert(users)
801 .values({
802 username: body.username,
803 email: body.email,
804 passwordHash,
805 })
806 .returning();
807
808 const token = generateSessionToken();
809 await db.insert(sessions).values({
810 userId: user.id,
811 token,
812 expiresAt: sessionExpiry(),
813 });
814
815 return c.json(
816 {
817 user: { id: user.id, username: user.username, email: user.email },
818 token,
819 },
820 201
821 );
822});
823
824auth.post("/api/auth/login", async (c) => {
825 const body = await c.req.json<{ username: string; password: string }>();
826
827 if (!body.username || !body.password) {
828 return c.json({ error: "username and password are required" }, 400);
829 }
830
831 const isEmail = body.username.includes("@");
832 const [user] = await db
833 .select()
834 .from(users)
835 .where(
836 isEmail
837 ? eq(users.email, body.username)
838 : eq(users.username, body.username)
839 )
840 .limit(1);
841
842 if (!user) return c.json({ error: "Invalid credentials" }, 401);
843
844 const valid = await verifyPassword(body.password, user.passwordHash);
845 if (!valid) return c.json({ error: "Invalid credentials" }, 401);
846
847 const token = generateSessionToken();
848 await db.insert(sessions).values({
849 userId: user.id,
850 token,
851 expiresAt: sessionExpiry(),
852 });
853
854 return c.json({
855 user: { id: user.id, username: user.username, email: user.email },
856 token,
857 });
858});
859
fc0ca99Claude860/**
861 * Pick a friendly provider name for the "Sign in with X" button when the
862 * admin hasn't set one explicitly. Looks at the configured IdP URLs.
863 * Falls back to undefined so the caller can default to a literal "SSO".
864 */
865function inferSsoProviderName(
866 cfg: { issuer?: string | null; authorizationEndpoint?: string | null } | null | undefined
867): string | undefined {
868 const urls = [cfg?.issuer, cfg?.authorizationEndpoint]
869 .filter((s): s is string => !!s)
870 .join(" ")
871 .toLowerCase();
872 if (!urls) return undefined;
873 if (urls.includes("google")) return "Google";
874 if (urls.includes("okta")) return "Okta";
875 if (urls.includes("microsoftonline") || urls.includes("azure")) return "Microsoft";
876 if (urls.includes("auth0.com")) return "Auth0";
877 if (urls.includes("authentik")) return "Authentik";
878 return undefined;
879}
880
06d5ffeClaude881export default auth;