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.tsxBlame635 lines · 2 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";
46d6165Claude24import { getSsoConfig, getGithubOauthConfig } from "../lib/sso";
06d5ffeClaude25import { Layout } from "../views/layout";
bb0f894Claude26import {
27 Form,
28 FormGroup,
29 Input,
30 Button,
09be7bfClaude31 LinkButton,
bb0f894Claude32 Alert,
33 Text,
34} from "../views/ui";
06d5ffeClaude35import type { AuthEnv } from "../middleware/auth";
36
37const auth = new Hono<AuthEnv>();
38
39// --- Web UI ---
40
41auth.get("/register", (c) => {
42 const error = c.req.query("error");
134750bClaude43 const csrf = c.get("csrfToken") as string | undefined;
06d5ffeClaude44 return c.html(
45 <Layout title="Register">
46 <div class="auth-container">
47 <h2>Create account</h2>
48 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
134750bClaude49 <Form method="post" action="/register" csrfToken={csrf}>
0316dbbClaude50 <FormGroup label="Username" htmlFor="username">
51 <Input
52 id="username"
06d5ffeClaude53 type="text"
54 name="username"
55 required
56 pattern="^[a-zA-Z0-9_-]+$"
57 minLength={2}
58 maxLength={39}
59 placeholder="your-username"
60 autocomplete="username"
61 />
bb0f894Claude62 </FormGroup>
63 <FormGroup label="Email" htmlFor="email">
64 <Input
06d5ffeClaude65 type="email"
66 name="email"
67 required
68 placeholder="you@example.com"
69 autocomplete="email"
2c3ba6ecopilot-swe-agent[bot]70 aria-label="Email"
06d5ffeClaude71 />
bb0f894Claude72 </FormGroup>
73 <FormGroup label="Password" htmlFor="password">
74 <Input
06d5ffeClaude75 type="password"
76 name="password"
77 required
78 minLength={8}
79 placeholder="Min 8 characters"
80 autocomplete="new-password"
2c3ba6ecopilot-swe-agent[bot]81 aria-label="Password"
06d5ffeClaude82 />
bb0f894Claude83 </FormGroup>
84 <Button type="submit" variant="primary">
06d5ffeClaude85 Create account
bb0f894Claude86 </Button>
87 </Form>
06d5ffeClaude88 <p class="auth-switch">
bb0f894Claude89 <Text>Already have an account? <a href="/login">Sign in</a></Text>
06d5ffeClaude90 </p>
91 </div>
92 </Layout>
93 );
94});
95
96auth.post("/register", async (c) => {
97 const body = await c.req.parseBody();
98 const username = String(body.username || "").trim();
99 const email = String(body.email || "").trim();
100 const password = String(body.password || "");
101
102 if (!username || !email || !password) {
103 return c.redirect("/register?error=All+fields+are+required");
104 }
105
106 if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
107 return c.redirect(
108 "/register?error=Username+may+only+contain+letters%2C+numbers%2C+hyphens+and+underscores"
109 );
110 }
111
112 if (password.length < 8) {
113 return c.redirect("/register?error=Password+must+be+at+least+8+characters");
114 }
115
116 // Check existing
117 const [existingUser] = await db
118 .select()
119 .from(users)
120 .where(eq(users.username, username))
121 .limit(1);
122 if (existingUser) {
123 return c.redirect("/register?error=Username+already+taken");
124 }
125
7437605Claude126 // B2: usernames share the URL namespace with org slugs; refuse collisions.
127 const [existingOrg] = await db
128 .select({ id: organizations.id })
129 .from(organizations)
130 .where(eq(organizations.slug, username.toLowerCase()))
131 .limit(1);
132 if (existingOrg) {
133 return c.redirect("/register?error=Username+already+taken");
134 }
135
06d5ffeClaude136 const [existingEmail] = await db
137 .select()
138 .from(users)
139 .where(eq(users.email, email))
140 .limit(1);
141 if (existingEmail) {
142 return c.redirect("/register?error=Email+already+registered");
143 }
144
145 const passwordHash = await hashPassword(password);
146
a4f3e24Claude147 // First user ever registered becomes admin automatically
148 const [userCount] = await db
149 .select({ count: sql`count(*)::int` })
150 .from(users);
151 const isFirstUser = (userCount?.count as number) === 0;
152
06d5ffeClaude153 const [user] = await db
154 .insert(users)
a4f3e24Claude155 .values({ username, email, passwordHash, isAdmin: isFirstUser })
06d5ffeClaude156 .returning();
157
2d985e5Claude158 // If username matches SITE_ADMIN_USERNAME env, grant site admin instantly
159 // so the operator doesn't have to wait for the next boot's bootstrap pass.
160 await import("../lib/admin-bootstrap").then((m) =>
161 m.ensureEnvAdminOnRegister({ userId: user.id, username })
162 ).catch(() => {});
163
06d5ffeClaude164 // Create session
165 const token = generateSessionToken();
166 await db.insert(sessions).values({
167 userId: user.id,
168 token,
169 expiresAt: sessionExpiry(),
170 });
171
172 setCookie(c, "session", token, sessionCookieOptions());
173
174 const redirect = c.req.query("redirect") || "/";
175 return c.redirect(redirect);
176});
177
edf7c36Claude178auth.get("/login", async (c) => {
06d5ffeClaude179 const error = c.req.query("error");
180 const redirect = c.req.query("redirect") || "";
edf7c36Claude181 const ssoCfg = await getSsoConfig();
182 const ssoEnabled =
183 !!ssoCfg?.enabled &&
184 !!ssoCfg.authorizationEndpoint &&
185 !!ssoCfg.tokenEndpoint &&
186 !!ssoCfg.userinfoEndpoint &&
187 !!ssoCfg.clientId &&
188 !!ssoCfg.clientSecret;
189 const ssoLabel = ssoCfg?.providerName || "SSO";
46d6165Claude190 // Block L6 — "Sign in with GitHub" (separate row keyed id='github').
191 const githubCfg = await getGithubOauthConfig();
192 const githubEnabled =
193 !!githubCfg?.enabled && !!githubCfg.clientId && !!githubCfg.clientSecret;
134750bClaude194 const csrf = c.get("csrfToken") as string | undefined;
06d5ffeClaude195 return c.html(
196 <Layout title="Sign in">
197 <div class="auth-container">
198 <h2>Sign in</h2>
199 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
0316dbbClaude200 <Form
b9968e3Claude201 method="post"
06d5ffeClaude202 action={`/login${redirect ? `?redirect=${encodeURIComponent(redirect)}` : ""}`}
134750bClaude203 csrfToken={csrf}
06d5ffeClaude204 >
bb0f894Claude205 <FormGroup label="Username or email" htmlFor="username">
206 <Input
06d5ffeClaude207 type="text"
208 name="username"
209 required
210 placeholder="username or email"
211 autocomplete="username"
2c3ba6ecopilot-swe-agent[bot]212 aria-label="Username or email"
06d5ffeClaude213 />
bb0f894Claude214 </FormGroup>
215 <FormGroup label="Password" htmlFor="password">
216 <Input
06d5ffeClaude217 type="password"
218 name="password"
219 required
220 placeholder="Password"
221 autocomplete="current-password"
2c3ba6ecopilot-swe-agent[bot]222 aria-label="Password"
06d5ffeClaude223 />
bb0f894Claude224 </FormGroup>
225 <Button type="submit" variant="primary">
06d5ffeClaude226 Sign in
bb0f894Claude227 </Button>
228 </Form>
46d6165Claude229 {githubEnabled && (
230 <div class="auth-sso">
231 <div class="auth-divider">or</div>
232 <LinkButton href="/login/github">Sign in with GitHub</LinkButton>
233 </div>
234 )}
09be7bfClaude235 {ssoEnabled && (
236 <div class="auth-sso">
237 <div class="auth-divider">or</div>
238 <LinkButton href="/login/sso">Sign in with {ssoLabel}</LinkButton>
239 </div>
240 )}
fa06ad2Claude241 <div class="auth-passkey">
242 <div class="auth-divider">or</div>
243 <button type="button" id="pk-signin-btn" class="btn">
244 Sign in with passkey
245 </button>
246 <div
247 id="pk-signin-status"
248 class="auth-status"
249 aria-live="polite"
250 ></div>
251 </div>
06d5ffeClaude252 <p class="auth-switch">
bb0f894Claude253 <Text>New to gluecron? <a href="/register">Create an account</a></Text>
06d5ffeClaude254 </p>
2df1f8cClaude255 <script
256 dangerouslySetInnerHTML={{
257 __html: /* js */ `
258 (function () {
259 const btn = document.getElementById('pk-signin-btn');
260 const status = document.getElementById('pk-signin-status');
261 const userInput = document.getElementById('username');
262 const redirect = ${JSON.stringify(redirect || "/")};
263 if (!btn) return;
264 function b64uToBuf(s) {
265 s = s.replace(/-/g,'+').replace(/_/g,'/');
266 while (s.length % 4) s += '=';
267 const bin = atob(s);
268 const buf = new Uint8Array(bin.length);
269 for (let i=0;i<bin.length;i++) buf[i] = bin.charCodeAt(i);
270 return buf.buffer;
271 }
272 function bufToB64u(buf) {
273 const bytes = new Uint8Array(buf);
274 let bin = '';
275 for (let i=0;i<bytes.length;i++) bin += String.fromCharCode(bytes[i]);
276 return btoa(bin).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');
277 }
278 btn.addEventListener('click', async function () {
279 if (!window.PublicKeyCredential) {
280 status.textContent = 'Passkeys not supported in this browser.';
281 return;
282 }
283 status.textContent = 'Preparing…';
284 try {
285 const username = (userInput && userInput.value || '').trim();
286 const optsRes = await fetch('/api/passkeys/auth/options', {
287 method: 'POST',
288 headers: { 'content-type': 'application/json' },
289 body: JSON.stringify(username ? { username: username } : {})
290 });
291 if (!optsRes.ok) throw new Error('options failed');
292 const { options, sessionKey } = await optsRes.json();
293 options.challenge = b64uToBuf(options.challenge);
294 if (options.allowCredentials) {
295 options.allowCredentials = options.allowCredentials.map(function (c) {
296 return Object.assign({}, c, { id: b64uToBuf(c.id) });
297 });
298 }
299 status.textContent = 'Touch your authenticator…';
300 const cred = await navigator.credentials.get({ publicKey: options });
301 const resp = {
302 id: cred.id,
303 rawId: bufToB64u(cred.rawId),
304 type: cred.type,
305 response: {
306 clientDataJSON: bufToB64u(cred.response.clientDataJSON),
307 authenticatorData: bufToB64u(cred.response.authenticatorData),
308 signature: bufToB64u(cred.response.signature),
309 userHandle: cred.response.userHandle ? bufToB64u(cred.response.userHandle) : null
310 },
311 clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
312 };
313 const verifyRes = await fetch('/api/passkeys/auth/verify', {
314 method: 'POST',
315 headers: { 'content-type': 'application/json' },
316 body: JSON.stringify({ sessionKey: sessionKey, response: resp })
317 });
318 if (!verifyRes.ok) {
319 const j = await verifyRes.json().catch(function () { return {}; });
320 throw new Error(j.error || 'verify failed');
321 }
322 status.textContent = 'Signed in. Redirecting…';
323 window.location.href = redirect;
324 } catch (e) {
325 status.textContent = 'Error: ' + (e && e.message ? e.message : e);
326 }
327 });
328 })();
329 `,
330 }}
331 />
06d5ffeClaude332 </div>
333 </Layout>
334 );
335});
336
337auth.post("/login", async (c) => {
338 const body = await c.req.parseBody();
339 const identifier = String(body.username || "").trim();
340 const password = String(body.password || "");
341 const redirect = c.req.query("redirect") || "/";
342
343 if (!identifier || !password) {
344 return c.redirect("/login?error=All+fields+are+required");
345 }
346
347 // Find user by username or email
348 const isEmail = identifier.includes("@");
349 const [user] = await db
350 .select()
351 .from(users)
352 .where(
353 isEmail
354 ? eq(users.email, identifier)
355 : eq(users.username, identifier)
356 )
357 .limit(1);
358
359 if (!user) {
360 return c.redirect("/login?error=Invalid+credentials");
361 }
362
363 const valid = await verifyPassword(password, user.passwordHash);
364 if (!valid) {
365 return c.redirect("/login?error=Invalid+credentials");
366 }
367
7298a17Claude368 // B4: if the user has TOTP enabled, issue a pending-2fa session and
369 // redirect to the code prompt.
370 const [totp] = await db
371 .select({ enabledAt: userTotp.enabledAt })
372 .from(userTotp)
373 .where(eq(userTotp.userId, user.id))
374 .limit(1);
375 const needs2fa = !!(totp && totp.enabledAt);
376
06d5ffeClaude377 const token = generateSessionToken();
378 await db.insert(sessions).values({
379 userId: user.id,
380 token,
381 expiresAt: sessionExpiry(),
7298a17Claude382 requires2fa: needs2fa,
06d5ffeClaude383 });
384
385 setCookie(c, "session", token, sessionCookieOptions());
7298a17Claude386 if (needs2fa) {
387 return c.redirect(
388 `/login/2fa?redirect=${encodeURIComponent(redirect)}`
389 );
390 }
06d5ffeClaude391 return c.redirect(redirect);
392});
393
7298a17Claude394// --- 2FA verify (B4) ---
395auth.get("/login/2fa", async (c) => {
396 const token = getCookie(c, "session");
397 if (!token) return c.redirect("/login");
398 const error = c.req.query("error");
399 const redirect = c.req.query("redirect") || "/";
400 return c.html(
401 <Layout title="Two-factor authentication">
402 <div class="auth-container">
403 <h2>Enter your code</h2>
404 <p
405 class="auth-switch"
406 style="margin-bottom: 16px; margin-top: 0"
407 >
408 Open your authenticator app and enter the 6-digit code. Lost your
409 device? Paste a recovery code instead.
410 </p>
411 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
412 <form
b9968e3Claude413 method="post"
7298a17Claude414 action={`/login/2fa?redirect=${encodeURIComponent(redirect)}`}
415 >
134750bClaude416 <input type="hidden" name="_csrf" value={(c.get("csrfToken") as string | undefined) || ""} />
7298a17Claude417 <div class="form-group">
418 <label for="code">Code</label>
419 <input
420 type="text"
421 id="code"
422 name="code"
423 required
424 autocomplete="one-time-code"
425 inputmode="numeric"
426 maxLength={24}
427 placeholder="123456 or xxxx-xxxx-xxxx"
428 />
429 </div>
430 <button type="submit" class="btn btn-primary">
431 Verify
432 </button>
433 </form>
434 <p class="auth-switch">
435 <a href="/logout">Cancel</a>
436 </p>
437 </div>
438 </Layout>
439 );
440});
441
442auth.post("/login/2fa", async (c) => {
443 const token = getCookie(c, "session");
444 if (!token) return c.redirect("/login");
445 const body = await c.req.parseBody();
446 const code = String(body.code || "").trim();
447 const redirect = c.req.query("redirect") || "/";
448
449 if (!code) {
450 return c.redirect(
451 `/login/2fa?error=Code+is+required&redirect=${encodeURIComponent(redirect)}`
452 );
453 }
454
455 try {
456 const [session] = await db
457 .select()
458 .from(sessions)
459 .where(eq(sessions.token, token))
460 .limit(1);
461 if (
462 !session ||
463 new Date(session.expiresAt) < new Date() ||
464 !session.requires2fa
465 ) {
466 return c.redirect("/login");
467 }
468
469 const [totp] = await db
470 .select()
471 .from(userTotp)
472 .where(eq(userTotp.userId, session.userId))
473 .limit(1);
474 if (!totp || !totp.enabledAt) {
475 // User doesn't have 2FA actually enabled — clear the flag and let
476 // them in. This can only happen if 2FA was disabled in another
477 // session between password check and code prompt.
478 await db
479 .update(sessions)
480 .set({ requires2fa: false })
481 .where(eq(sessions.token, token));
482 return c.redirect(redirect);
483 }
484
485 // Try TOTP code first.
486 const isSix = /^\d{6}$/.test(code);
487 let ok = false;
488 if (isSix) {
489 ok = await verifyTotpCode(totp.secret, code);
490 }
491 // Fall through to recovery code.
492 if (!ok) {
493 const hash = await hashRecoveryCode(code);
494 const [rec] = await db
495 .select()
496 .from(userRecoveryCodes)
497 .where(
498 and(
499 eq(userRecoveryCodes.userId, session.userId),
500 eq(userRecoveryCodes.codeHash, hash),
501 isNull(userRecoveryCodes.usedAt)
502 )
503 )
504 .limit(1);
505 if (rec) {
506 await db
507 .update(userRecoveryCodes)
508 .set({ usedAt: new Date() })
509 .where(eq(userRecoveryCodes.id, rec.id));
510 ok = true;
511 }
512 }
513
514 if (!ok) {
515 return c.redirect(
516 `/login/2fa?error=Invalid+code&redirect=${encodeURIComponent(redirect)}`
517 );
518 }
519
520 await db
521 .update(sessions)
522 .set({ requires2fa: false })
523 .where(eq(sessions.token, token));
524 await db
525 .update(userTotp)
526 .set({ lastUsedAt: new Date() })
527 .where(eq(userTotp.userId, session.userId));
528
529 return c.redirect(redirect);
530 } catch (err) {
531 console.error("[auth] 2fa verify:", err);
532 return c.redirect(
533 `/login/2fa?error=Service+unavailable&redirect=${encodeURIComponent(redirect)}`
534 );
535 }
536});
537
06d5ffeClaude538auth.get("/logout", async (c) => {
539 deleteCookie(c, "session", { path: "/" });
540 return c.redirect("/");
541});
542
543// --- API ---
544
545auth.post("/api/auth/register", async (c) => {
546 const body = await c.req.json<{
547 username: string;
548 email: string;
549 password: string;
550 }>();
551
552 if (!body.username || !body.email || !body.password) {
553 return c.json({ error: "username, email, and password are required" }, 400);
554 }
555
556 if (!/^[a-zA-Z0-9_-]+$/.test(body.username)) {
557 return c.json({ error: "Invalid username" }, 400);
558 }
559
560 if (body.password.length < 8) {
561 return c.json({ error: "Password must be at least 8 characters" }, 400);
562 }
563
564 const [existing] = await db
565 .select()
566 .from(users)
567 .where(eq(users.username, body.username))
568 .limit(1);
569 if (existing) {
570 return c.json({ error: "Username already taken" }, 409);
571 }
572
573 const passwordHash = await hashPassword(body.password);
574 const [user] = await db
575 .insert(users)
576 .values({
577 username: body.username,
578 email: body.email,
579 passwordHash,
580 })
581 .returning();
582
583 const token = generateSessionToken();
584 await db.insert(sessions).values({
585 userId: user.id,
586 token,
587 expiresAt: sessionExpiry(),
588 });
589
590 return c.json(
591 {
592 user: { id: user.id, username: user.username, email: user.email },
593 token,
594 },
595 201
596 );
597});
598
599auth.post("/api/auth/login", async (c) => {
600 const body = await c.req.json<{ username: string; password: string }>();
601
602 if (!body.username || !body.password) {
603 return c.json({ error: "username and password are required" }, 400);
604 }
605
606 const isEmail = body.username.includes("@");
607 const [user] = await db
608 .select()
609 .from(users)
610 .where(
611 isEmail
612 ? eq(users.email, body.username)
613 : eq(users.username, body.username)
614 )
615 .limit(1);
616
617 if (!user) return c.json({ error: "Invalid credentials" }, 401);
618
619 const valid = await verifyPassword(body.password, user.passwordHash);
620 if (!valid) return c.json({ error: "Invalid credentials" }, 401);
621
622 const token = generateSessionToken();
623 await db.insert(sessions).values({
624 userId: user.id,
625 token,
626 expiresAt: sessionExpiry(),
627 });
628
629 return c.json({
630 user: { id: user.id, username: user.username, email: user.email },
631 token,
632 });
633});
634
635export default auth;