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.tsxBlame625 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";
edf7c36Claude24import { getSsoConfig } 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";
134750bClaude190 const csrf = c.get("csrfToken") as string | undefined;
06d5ffeClaude191 return c.html(
192 <Layout title="Sign in">
193 <div class="auth-container">
194 <h2>Sign in</h2>
195 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
0316dbbClaude196 <Form
b9968e3Claude197 method="post"
06d5ffeClaude198 action={`/login${redirect ? `?redirect=${encodeURIComponent(redirect)}` : ""}`}
134750bClaude199 csrfToken={csrf}
06d5ffeClaude200 >
bb0f894Claude201 <FormGroup label="Username or email" htmlFor="username">
202 <Input
06d5ffeClaude203 type="text"
204 name="username"
205 required
206 placeholder="username or email"
207 autocomplete="username"
2c3ba6ecopilot-swe-agent[bot]208 aria-label="Username or email"
06d5ffeClaude209 />
bb0f894Claude210 </FormGroup>
211 <FormGroup label="Password" htmlFor="password">
212 <Input
06d5ffeClaude213 type="password"
214 name="password"
215 required
216 placeholder="Password"
217 autocomplete="current-password"
2c3ba6ecopilot-swe-agent[bot]218 aria-label="Password"
06d5ffeClaude219 />
bb0f894Claude220 </FormGroup>
221 <Button type="submit" variant="primary">
06d5ffeClaude222 Sign in
bb0f894Claude223 </Button>
224 </Form>
09be7bfClaude225 {ssoEnabled && (
226 <div class="auth-sso">
227 <div class="auth-divider">or</div>
228 <LinkButton href="/login/sso">Sign in with {ssoLabel}</LinkButton>
229 </div>
230 )}
fa06ad2Claude231 <div class="auth-passkey">
232 <div class="auth-divider">or</div>
233 <button type="button" id="pk-signin-btn" class="btn">
234 Sign in with passkey
235 </button>
236 <div
237 id="pk-signin-status"
238 class="auth-status"
239 aria-live="polite"
240 ></div>
241 </div>
06d5ffeClaude242 <p class="auth-switch">
bb0f894Claude243 <Text>New to gluecron? <a href="/register">Create an account</a></Text>
06d5ffeClaude244 </p>
2df1f8cClaude245 <script
246 dangerouslySetInnerHTML={{
247 __html: /* js */ `
248 (function () {
249 const btn = document.getElementById('pk-signin-btn');
250 const status = document.getElementById('pk-signin-status');
251 const userInput = document.getElementById('username');
252 const redirect = ${JSON.stringify(redirect || "/")};
253 if (!btn) return;
254 function b64uToBuf(s) {
255 s = s.replace(/-/g,'+').replace(/_/g,'/');
256 while (s.length % 4) s += '=';
257 const bin = atob(s);
258 const buf = new Uint8Array(bin.length);
259 for (let i=0;i<bin.length;i++) buf[i] = bin.charCodeAt(i);
260 return buf.buffer;
261 }
262 function bufToB64u(buf) {
263 const bytes = new Uint8Array(buf);
264 let bin = '';
265 for (let i=0;i<bytes.length;i++) bin += String.fromCharCode(bytes[i]);
266 return btoa(bin).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');
267 }
268 btn.addEventListener('click', async function () {
269 if (!window.PublicKeyCredential) {
270 status.textContent = 'Passkeys not supported in this browser.';
271 return;
272 }
273 status.textContent = 'Preparing…';
274 try {
275 const username = (userInput && userInput.value || '').trim();
276 const optsRes = await fetch('/api/passkeys/auth/options', {
277 method: 'POST',
278 headers: { 'content-type': 'application/json' },
279 body: JSON.stringify(username ? { username: username } : {})
280 });
281 if (!optsRes.ok) throw new Error('options failed');
282 const { options, sessionKey } = await optsRes.json();
283 options.challenge = b64uToBuf(options.challenge);
284 if (options.allowCredentials) {
285 options.allowCredentials = options.allowCredentials.map(function (c) {
286 return Object.assign({}, c, { id: b64uToBuf(c.id) });
287 });
288 }
289 status.textContent = 'Touch your authenticator…';
290 const cred = await navigator.credentials.get({ publicKey: options });
291 const resp = {
292 id: cred.id,
293 rawId: bufToB64u(cred.rawId),
294 type: cred.type,
295 response: {
296 clientDataJSON: bufToB64u(cred.response.clientDataJSON),
297 authenticatorData: bufToB64u(cred.response.authenticatorData),
298 signature: bufToB64u(cred.response.signature),
299 userHandle: cred.response.userHandle ? bufToB64u(cred.response.userHandle) : null
300 },
301 clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
302 };
303 const verifyRes = await fetch('/api/passkeys/auth/verify', {
304 method: 'POST',
305 headers: { 'content-type': 'application/json' },
306 body: JSON.stringify({ sessionKey: sessionKey, response: resp })
307 });
308 if (!verifyRes.ok) {
309 const j = await verifyRes.json().catch(function () { return {}; });
310 throw new Error(j.error || 'verify failed');
311 }
312 status.textContent = 'Signed in. Redirecting…';
313 window.location.href = redirect;
314 } catch (e) {
315 status.textContent = 'Error: ' + (e && e.message ? e.message : e);
316 }
317 });
318 })();
319 `,
320 }}
321 />
06d5ffeClaude322 </div>
323 </Layout>
324 );
325});
326
327auth.post("/login", async (c) => {
328 const body = await c.req.parseBody();
329 const identifier = String(body.username || "").trim();
330 const password = String(body.password || "");
331 const redirect = c.req.query("redirect") || "/";
332
333 if (!identifier || !password) {
334 return c.redirect("/login?error=All+fields+are+required");
335 }
336
337 // Find user by username or email
338 const isEmail = identifier.includes("@");
339 const [user] = await db
340 .select()
341 .from(users)
342 .where(
343 isEmail
344 ? eq(users.email, identifier)
345 : eq(users.username, identifier)
346 )
347 .limit(1);
348
349 if (!user) {
350 return c.redirect("/login?error=Invalid+credentials");
351 }
352
353 const valid = await verifyPassword(password, user.passwordHash);
354 if (!valid) {
355 return c.redirect("/login?error=Invalid+credentials");
356 }
357
7298a17Claude358 // B4: if the user has TOTP enabled, issue a pending-2fa session and
359 // redirect to the code prompt.
360 const [totp] = await db
361 .select({ enabledAt: userTotp.enabledAt })
362 .from(userTotp)
363 .where(eq(userTotp.userId, user.id))
364 .limit(1);
365 const needs2fa = !!(totp && totp.enabledAt);
366
06d5ffeClaude367 const token = generateSessionToken();
368 await db.insert(sessions).values({
369 userId: user.id,
370 token,
371 expiresAt: sessionExpiry(),
7298a17Claude372 requires2fa: needs2fa,
06d5ffeClaude373 });
374
375 setCookie(c, "session", token, sessionCookieOptions());
7298a17Claude376 if (needs2fa) {
377 return c.redirect(
378 `/login/2fa?redirect=${encodeURIComponent(redirect)}`
379 );
380 }
06d5ffeClaude381 return c.redirect(redirect);
382});
383
7298a17Claude384// --- 2FA verify (B4) ---
385auth.get("/login/2fa", async (c) => {
386 const token = getCookie(c, "session");
387 if (!token) return c.redirect("/login");
388 const error = c.req.query("error");
389 const redirect = c.req.query("redirect") || "/";
390 return c.html(
391 <Layout title="Two-factor authentication">
392 <div class="auth-container">
393 <h2>Enter your code</h2>
394 <p
395 class="auth-switch"
396 style="margin-bottom: 16px; margin-top: 0"
397 >
398 Open your authenticator app and enter the 6-digit code. Lost your
399 device? Paste a recovery code instead.
400 </p>
401 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
402 <form
b9968e3Claude403 method="post"
7298a17Claude404 action={`/login/2fa?redirect=${encodeURIComponent(redirect)}`}
405 >
134750bClaude406 <input type="hidden" name="_csrf" value={(c.get("csrfToken") as string | undefined) || ""} />
7298a17Claude407 <div class="form-group">
408 <label for="code">Code</label>
409 <input
410 type="text"
411 id="code"
412 name="code"
413 required
414 autocomplete="one-time-code"
415 inputmode="numeric"
416 maxLength={24}
417 placeholder="123456 or xxxx-xxxx-xxxx"
418 />
419 </div>
420 <button type="submit" class="btn btn-primary">
421 Verify
422 </button>
423 </form>
424 <p class="auth-switch">
425 <a href="/logout">Cancel</a>
426 </p>
427 </div>
428 </Layout>
429 );
430});
431
432auth.post("/login/2fa", async (c) => {
433 const token = getCookie(c, "session");
434 if (!token) return c.redirect("/login");
435 const body = await c.req.parseBody();
436 const code = String(body.code || "").trim();
437 const redirect = c.req.query("redirect") || "/";
438
439 if (!code) {
440 return c.redirect(
441 `/login/2fa?error=Code+is+required&redirect=${encodeURIComponent(redirect)}`
442 );
443 }
444
445 try {
446 const [session] = await db
447 .select()
448 .from(sessions)
449 .where(eq(sessions.token, token))
450 .limit(1);
451 if (
452 !session ||
453 new Date(session.expiresAt) < new Date() ||
454 !session.requires2fa
455 ) {
456 return c.redirect("/login");
457 }
458
459 const [totp] = await db
460 .select()
461 .from(userTotp)
462 .where(eq(userTotp.userId, session.userId))
463 .limit(1);
464 if (!totp || !totp.enabledAt) {
465 // User doesn't have 2FA actually enabled — clear the flag and let
466 // them in. This can only happen if 2FA was disabled in another
467 // session between password check and code prompt.
468 await db
469 .update(sessions)
470 .set({ requires2fa: false })
471 .where(eq(sessions.token, token));
472 return c.redirect(redirect);
473 }
474
475 // Try TOTP code first.
476 const isSix = /^\d{6}$/.test(code);
477 let ok = false;
478 if (isSix) {
479 ok = await verifyTotpCode(totp.secret, code);
480 }
481 // Fall through to recovery code.
482 if (!ok) {
483 const hash = await hashRecoveryCode(code);
484 const [rec] = await db
485 .select()
486 .from(userRecoveryCodes)
487 .where(
488 and(
489 eq(userRecoveryCodes.userId, session.userId),
490 eq(userRecoveryCodes.codeHash, hash),
491 isNull(userRecoveryCodes.usedAt)
492 )
493 )
494 .limit(1);
495 if (rec) {
496 await db
497 .update(userRecoveryCodes)
498 .set({ usedAt: new Date() })
499 .where(eq(userRecoveryCodes.id, rec.id));
500 ok = true;
501 }
502 }
503
504 if (!ok) {
505 return c.redirect(
506 `/login/2fa?error=Invalid+code&redirect=${encodeURIComponent(redirect)}`
507 );
508 }
509
510 await db
511 .update(sessions)
512 .set({ requires2fa: false })
513 .where(eq(sessions.token, token));
514 await db
515 .update(userTotp)
516 .set({ lastUsedAt: new Date() })
517 .where(eq(userTotp.userId, session.userId));
518
519 return c.redirect(redirect);
520 } catch (err) {
521 console.error("[auth] 2fa verify:", err);
522 return c.redirect(
523 `/login/2fa?error=Service+unavailable&redirect=${encodeURIComponent(redirect)}`
524 );
525 }
526});
527
06d5ffeClaude528auth.get("/logout", async (c) => {
529 deleteCookie(c, "session", { path: "/" });
530 return c.redirect("/");
531});
532
533// --- API ---
534
535auth.post("/api/auth/register", async (c) => {
536 const body = await c.req.json<{
537 username: string;
538 email: string;
539 password: string;
540 }>();
541
542 if (!body.username || !body.email || !body.password) {
543 return c.json({ error: "username, email, and password are required" }, 400);
544 }
545
546 if (!/^[a-zA-Z0-9_-]+$/.test(body.username)) {
547 return c.json({ error: "Invalid username" }, 400);
548 }
549
550 if (body.password.length < 8) {
551 return c.json({ error: "Password must be at least 8 characters" }, 400);
552 }
553
554 const [existing] = await db
555 .select()
556 .from(users)
557 .where(eq(users.username, body.username))
558 .limit(1);
559 if (existing) {
560 return c.json({ error: "Username already taken" }, 409);
561 }
562
563 const passwordHash = await hashPassword(body.password);
564 const [user] = await db
565 .insert(users)
566 .values({
567 username: body.username,
568 email: body.email,
569 passwordHash,
570 })
571 .returning();
572
573 const token = generateSessionToken();
574 await db.insert(sessions).values({
575 userId: user.id,
576 token,
577 expiresAt: sessionExpiry(),
578 });
579
580 return c.json(
581 {
582 user: { id: user.id, username: user.username, email: user.email },
583 token,
584 },
585 201
586 );
587});
588
589auth.post("/api/auth/login", async (c) => {
590 const body = await c.req.json<{ username: string; password: string }>();
591
592 if (!body.username || !body.password) {
593 return c.json({ error: "username and password are required" }, 400);
594 }
595
596 const isEmail = body.username.includes("@");
597 const [user] = await db
598 .select()
599 .from(users)
600 .where(
601 isEmail
602 ? eq(users.email, body.username)
603 : eq(users.username, body.username)
604 )
605 .limit(1);
606
607 if (!user) return c.json({ error: "Invalid credentials" }, 401);
608
609 const valid = await verifyPassword(body.password, user.passwordHash);
610 if (!valid) return c.json({ error: "Invalid credentials" }, 401);
611
612 const token = generateSessionToken();
613 await db.insert(sessions).values({
614 userId: user.id,
615 token,
616 expiresAt: sessionExpiry(),
617 });
618
619 return c.json({
620 user: { id: user.id, username: user.username, email: user.email },
621 token,
622 });
623});
624
625export default auth;