aboutsummaryrefslogtreecommitdiffhomepage
path: root/pkgs/server/src/routes/auth.ts
blob: a2e6c8e4e0b1e2d745ad715870740ea9546e303c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import { createHash, randomBytes } from "node:crypto";
import {
	createUserSchema,
	loginSchema,
	refreshTokenSchema,
} from "@kioku/shared";
import * as argon2 from "argon2";
import { and, eq, gt } from "drizzle-orm";
import { Hono } from "hono";
import { sign } from "hono/jwt";
import { db, refreshTokens, users } from "../db";
import { Errors } from "../middleware";

const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
	throw new Error("JWT_SECRET environment variable is required");
}
const ACCESS_TOKEN_EXPIRES_IN = 60 * 15; // 15 minutes
const REFRESH_TOKEN_EXPIRES_IN = 60 * 60 * 24 * 7; // 7 days

function generateRefreshToken(): string {
	return randomBytes(32).toString("hex");
}

function hashToken(token: string): string {
	return createHash("sha256").update(token).digest("hex");
}

const auth = new Hono();

auth.post("/register", async (c) => {
	const body = await c.req.json();

	const parsed = createUserSchema.safeParse(body);
	if (!parsed.success) {
		throw Errors.validationError(parsed.error.issues[0]?.message);
	}

	const { username, password } = parsed.data;

	// Check if username already exists
	const existingUser = await db
		.select({ id: users.id })
		.from(users)
		.where(eq(users.username, username))
		.limit(1);

	if (existingUser.length > 0) {
		throw Errors.conflict("Username already exists", "USERNAME_EXISTS");
	}

	// Hash password with Argon2
	const passwordHash = await argon2.hash(password);

	// Create user
	const [newUser] = await db
		.insert(users)
		.values({
			username,
			passwordHash,
		})
		.returning({
			id: users.id,
			username: users.username,
			createdAt: users.createdAt,
		});

	return c.json({ user: newUser }, 201);
});

auth.post("/login", async (c) => {
	const body = await c.req.json();

	const parsed = loginSchema.safeParse(body);
	if (!parsed.success) {
		throw Errors.validationError(parsed.error.issues[0]?.message);
	}

	const { username, password } = parsed.data;

	// Find user by username
	const [user] = await db
		.select({
			id: users.id,
			username: users.username,
			passwordHash: users.passwordHash,
		})
		.from(users)
		.where(eq(users.username, username))
		.limit(1);

	if (!user) {
		throw Errors.unauthorized(
			"Invalid username or password",
			"INVALID_CREDENTIALS",
		);
	}

	// Verify password
	const isPasswordValid = await argon2.verify(user.passwordHash, password);
	if (!isPasswordValid) {
		throw Errors.unauthorized(
			"Invalid username or password",
			"INVALID_CREDENTIALS",
		);
	}

	// Generate JWT access token
	const now = Math.floor(Date.now() / 1000);
	const accessToken = await sign(
		{
			sub: user.id,
			iat: now,
			exp: now + ACCESS_TOKEN_EXPIRES_IN,
		},
		JWT_SECRET,
	);

	// Generate refresh token
	const refreshToken = generateRefreshToken();
	const tokenHash = hashToken(refreshToken);
	const expiresAt = new Date(Date.now() + REFRESH_TOKEN_EXPIRES_IN * 1000);

	// Store refresh token in database
	await db.insert(refreshTokens).values({
		userId: user.id,
		tokenHash,
		expiresAt,
	});

	return c.json({
		accessToken,
		refreshToken,
		user: {
			id: user.id,
			username: user.username,
		},
	});
});

auth.post("/refresh", async (c) => {
	const body = await c.req.json();

	const parsed = refreshTokenSchema.safeParse(body);
	if (!parsed.success) {
		throw Errors.validationError(parsed.error.issues[0]?.message);
	}

	const { refreshToken } = parsed.data;
	const tokenHash = hashToken(refreshToken);

	// Find valid refresh token
	const [storedToken] = await db
		.select({
			id: refreshTokens.id,
			userId: refreshTokens.userId,
			expiresAt: refreshTokens.expiresAt,
		})
		.from(refreshTokens)
		.where(
			and(
				eq(refreshTokens.tokenHash, tokenHash),
				gt(refreshTokens.expiresAt, new Date()),
			),
		)
		.limit(1);

	if (!storedToken) {
		throw Errors.unauthorized(
			"Invalid or expired refresh token",
			"INVALID_REFRESH_TOKEN",
		);
	}

	// Get user info
	const [user] = await db
		.select({
			id: users.id,
			username: users.username,
		})
		.from(users)
		.where(eq(users.id, storedToken.userId))
		.limit(1);

	if (!user) {
		throw Errors.unauthorized("User not found", "USER_NOT_FOUND");
	}

	// Delete old refresh token (rotation)
	await db.delete(refreshTokens).where(eq(refreshTokens.id, storedToken.id));

	// Generate new access token
	const now = Math.floor(Date.now() / 1000);
	const accessToken = await sign(
		{
			sub: user.id,
			iat: now,
			exp: now + ACCESS_TOKEN_EXPIRES_IN,
		},
		JWT_SECRET,
	);

	// Generate new refresh token (rotation)
	const newRefreshToken = generateRefreshToken();
	const newTokenHash = hashToken(newRefreshToken);
	const expiresAt = new Date(Date.now() + REFRESH_TOKEN_EXPIRES_IN * 1000);

	await db.insert(refreshTokens).values({
		userId: user.id,
		tokenHash: newTokenHash,
		expiresAt,
	});

	return c.json({
		accessToken,
		refreshToken: newRefreshToken,
		user: {
			id: user.id,
			username: user.username,
		},
	});
});

export { auth };