| 135dfe5 | | | 1 | import type { FastifyInstance } from "fastify"; |
| 135dfe5 | | | 2 | import { z } from "zod"; |
| 3c994d3 | | | 3 | import { createHash } from "crypto"; |
| 135dfe5 | | | 4 | import { |
| 135dfe5 | | | 5 | generateRegistrationOptions, |
| 135dfe5 | | | 6 | verifyRegistrationResponse, |
| 135dfe5 | | | 7 | generateAuthenticationOptions, |
| 135dfe5 | | | 8 | verifyAuthenticationResponse, |
| 135dfe5 | | | 9 | } from "@simplewebauthn/server"; |
| 135dfe5 | | | 10 | import type { |
| 135dfe5 | | | 11 | RegistrationResponseJSON, |
| 135dfe5 | | | 12 | AuthenticationResponseJSON, |
| 135dfe5 | | | 13 | AuthenticatorTransportFuture, |
| 135dfe5 | | | 14 | } from "@simplewebauthn/server"; |
| 135dfe5 | | | 15 | |
| 135dfe5 | | | 16 | const RP_NAME = "Grove"; |
| 135dfe5 | | | 17 | const RP_ID = process.env.RP_ID ?? "localhost"; |
| a33b2b6 | | | 18 | const ORIGIN_ENV = process.env.ORIGIN ?? "http://localhost:3000"; |
| a33b2b6 | | | 19 | const EXPECTED_ORIGINS = ORIGIN_ENV.split(",") |
| a33b2b6 | | | 20 | .map((origin) => origin.trim()) |
| a33b2b6 | | | 21 | .filter(Boolean); |
| a33b2b6 | | | 22 | const EXPECTED_ORIGIN = EXPECTED_ORIGINS.length === 1 |
| a33b2b6 | | | 23 | ? EXPECTED_ORIGINS[0] |
| a33b2b6 | | | 24 | : EXPECTED_ORIGINS; |
| 135dfe5 | | | 25 | const CHALLENGE_TTL = 5 * 60 * 1000; |
| 135dfe5 | | | 26 | |
| 135dfe5 | | | 27 | const registerBeginSchema = z.object({ |
| 135dfe5 | | | 28 | username: z.string().min(2).max(39).regex(/^[a-zA-Z0-9_-]+$/), |
| 135dfe5 | | | 29 | display_name: z.string().optional(), |
| 135dfe5 | | | 30 | }); |
| 135dfe5 | | | 31 | |
| 135dfe5 | | | 32 | export async function authRoutes(app: FastifyInstance) { |
| 135dfe5 | | | 33 | const db = (app as any).db; |
| 135dfe5 | | | 34 | const challenges = (app as any).challenges as Map< |
| 135dfe5 | | | 35 | string, |
| 135dfe5 | | | 36 | { username?: string; displayName?: string; userId?: number; expiresAt: number } |
| 135dfe5 | | | 37 | >; |
| 135dfe5 | | | 38 | |
| 135dfe5 | | | 39 | // ── Registration Step 1: Generate challenge ────────────────────── |
| 135dfe5 | | | 40 | |
| 135dfe5 | | | 41 | app.post("/register/begin", async (request, reply) => { |
| 135dfe5 | | | 42 | const parsed = registerBeginSchema.safeParse(request.body); |
| 135dfe5 | | | 43 | if (!parsed.success) { |
| 135dfe5 | | | 44 | return reply.code(400).send({ error: parsed.error.flatten() }); |
| 135dfe5 | | | 45 | } |
| 135dfe5 | | | 46 | |
| 135dfe5 | | | 47 | const { username, display_name } = parsed.data; |
| 135dfe5 | | | 48 | |
| 135dfe5 | | | 49 | const existing = db |
| 135dfe5 | | | 50 | .prepare("SELECT id FROM users WHERE username = ?") |
| 135dfe5 | | | 51 | .get(username); |
| 79efd41 | | | 52 | const orgExists = db |
| 79efd41 | | | 53 | .prepare("SELECT 1 FROM orgs WHERE name = ?") |
| 79efd41 | | | 54 | .get(username); |
| 135dfe5 | | | 55 | |
| 79efd41 | | | 56 | if (existing || orgExists) { |
| 135dfe5 | | | 57 | return reply.code(409).send({ error: "Username already taken" }); |
| 135dfe5 | | | 58 | } |
| 135dfe5 | | | 59 | |
| 135dfe5 | | | 60 | const options = await generateRegistrationOptions({ |
| 135dfe5 | | | 61 | rpName: RP_NAME, |
| 135dfe5 | | | 62 | rpID: RP_ID, |
| 135dfe5 | | | 63 | userName: username, |
| 135dfe5 | | | 64 | userDisplayName: display_name ?? username, |
| 135dfe5 | | | 65 | attestationType: "none", |
| 135dfe5 | | | 66 | authenticatorSelection: { |
| 135dfe5 | | | 67 | residentKey: "preferred", |
| 135dfe5 | | | 68 | userVerification: "preferred", |
| 135dfe5 | | | 69 | }, |
| 135dfe5 | | | 70 | }); |
| 135dfe5 | | | 71 | |
| 135dfe5 | | | 72 | challenges.set(options.challenge, { |
| 135dfe5 | | | 73 | username, |
| 135dfe5 | | | 74 | displayName: display_name ?? username, |
| 135dfe5 | | | 75 | expiresAt: Date.now() + CHALLENGE_TTL, |
| 135dfe5 | | | 76 | }); |
| 135dfe5 | | | 77 | |
| 135dfe5 | | | 78 | return { options }; |
| 135dfe5 | | | 79 | }); |
| 135dfe5 | | | 80 | |
| 135dfe5 | | | 81 | // ── Registration Step 2: Verify attestation ────────────────────── |
| 135dfe5 | | | 82 | |
| 135dfe5 | | | 83 | app.post("/register/complete", async (request, reply) => { |
| 135dfe5 | | | 84 | const body = request.body as { |
| 135dfe5 | | | 85 | response: RegistrationResponseJSON; |
| 135dfe5 | | | 86 | challenge: string; |
| 135dfe5 | | | 87 | }; |
| 135dfe5 | | | 88 | |
| 135dfe5 | | | 89 | const stored = challenges.get(body.challenge); |
| 135dfe5 | | | 90 | if (!stored || stored.expiresAt < Date.now()) { |
| 135dfe5 | | | 91 | return reply.code(400).send({ error: "Challenge expired or invalid" }); |
| 135dfe5 | | | 92 | } |
| 135dfe5 | | | 93 | |
| 135dfe5 | | | 94 | try { |
| 135dfe5 | | | 95 | const verification = await verifyRegistrationResponse({ |
| 135dfe5 | | | 96 | response: body.response, |
| 135dfe5 | | | 97 | expectedChallenge: body.challenge, |
| a33b2b6 | | | 98 | expectedOrigin: EXPECTED_ORIGIN, |
| 135dfe5 | | | 99 | expectedRPID: RP_ID, |
| 135dfe5 | | | 100 | }); |
| 135dfe5 | | | 101 | |
| 135dfe5 | | | 102 | if (!verification.verified || !verification.registrationInfo) { |
| 135dfe5 | | | 103 | return reply.code(400).send({ error: "Registration verification failed" }); |
| 135dfe5 | | | 104 | } |
| 135dfe5 | | | 105 | |
| 135dfe5 | | | 106 | const { credential, credentialDeviceType, credentialBackedUp } = |
| 135dfe5 | | | 107 | verification.registrationInfo; |
| 135dfe5 | | | 108 | |
| 135dfe5 | | | 109 | const userResult = db |
| 135dfe5 | | | 110 | .prepare("INSERT INTO users (username, display_name) VALUES (?, ?)") |
| 135dfe5 | | | 111 | .run(stored.username, stored.displayName); |
| 135dfe5 | | | 112 | |
| 135dfe5 | | | 113 | const userId = userResult.lastInsertRowid; |
| 135dfe5 | | | 114 | |
| 135dfe5 | | | 115 | db.prepare(` |
| 135dfe5 | | | 116 | INSERT INTO credentials (id, user_id, public_key, counter, transports, device_type, backed_up) |
| 135dfe5 | | | 117 | VALUES (?, ?, ?, ?, ?, ?, ?) |
| 135dfe5 | | | 118 | `).run( |
| 135dfe5 | | | 119 | credential.id, |
| 135dfe5 | | | 120 | userId, |
| 135dfe5 | | | 121 | Buffer.from(credential.publicKey), |
| 135dfe5 | | | 122 | credential.counter, |
| 135dfe5 | | | 123 | JSON.stringify(credential.transports ?? []), |
| 135dfe5 | | | 124 | credentialDeviceType, |
| 135dfe5 | | | 125 | credentialBackedUp ? 1 : 0 |
| 135dfe5 | | | 126 | ); |
| 135dfe5 | | | 127 | |
| 135dfe5 | | | 128 | challenges.delete(body.challenge); |
| 135dfe5 | | | 129 | |
| 3c994d3 | | | 130 | const token = app.jwt.sign({ |
| 3c994d3 | | | 131 | id: Number(userId), |
| 3c994d3 | | | 132 | username: stored.username!, |
| 3c994d3 | | | 133 | display_name: stored.displayName, |
| 3c994d3 | | | 134 | type: "session", |
| 3c994d3 | | | 135 | }); |
| 135dfe5 | | | 136 | |
| 135dfe5 | | | 137 | return reply.code(201).send({ |
| 135dfe5 | | | 138 | token, |
| 135dfe5 | | | 139 | user: { |
| 135dfe5 | | | 140 | id: Number(userId), |
| 135dfe5 | | | 141 | username: stored.username, |
| 135dfe5 | | | 142 | display_name: stored.displayName, |
| 135dfe5 | | | 143 | }, |
| 135dfe5 | | | 144 | }); |
| 135dfe5 | | | 145 | } catch (err: any) { |
| 135dfe5 | | | 146 | return reply.code(400).send({ error: err.message }); |
| 135dfe5 | | | 147 | } |
| 135dfe5 | | | 148 | }); |
| 135dfe5 | | | 149 | |
| 135dfe5 | | | 150 | // ── Login Step 1: Generate challenge ───────────────────────────── |
| 135dfe5 | | | 151 | |
| 135dfe5 | | | 152 | app.post("/login/begin", async (request, reply) => { |
| 135dfe5 | | | 153 | let allowCredentials: { id: string; transports?: AuthenticatorTransportFuture[] }[] | undefined; |
| 135dfe5 | | | 154 | |
| 135dfe5 | | | 155 | const body = (request.body ?? {}) as { username?: string }; |
| 135dfe5 | | | 156 | |
| 135dfe5 | | | 157 | if (body.username) { |
| 135dfe5 | | | 158 | const user = db |
| 135dfe5 | | | 159 | .prepare("SELECT id FROM users WHERE username = ?") |
| 135dfe5 | | | 160 | .get(body.username) as any; |
| 135dfe5 | | | 161 | |
| 135dfe5 | | | 162 | if (!user) { |
| 135dfe5 | | | 163 | return reply.code(404).send({ error: "User not found" }); |
| 135dfe5 | | | 164 | } |
| 135dfe5 | | | 165 | |
| 135dfe5 | | | 166 | const creds = db |
| 135dfe5 | | | 167 | .prepare("SELECT id, transports FROM credentials WHERE user_id = ?") |
| 135dfe5 | | | 168 | .all(user.id) as any[]; |
| 135dfe5 | | | 169 | |
| 135dfe5 | | | 170 | allowCredentials = creds.map((c) => ({ |
| 135dfe5 | | | 171 | id: c.id, |
| 135dfe5 | | | 172 | transports: JSON.parse(c.transports || "[]") as AuthenticatorTransportFuture[], |
| 135dfe5 | | | 173 | })); |
| 135dfe5 | | | 174 | } |
| 135dfe5 | | | 175 | |
| 135dfe5 | | | 176 | const options = await generateAuthenticationOptions({ |
| 135dfe5 | | | 177 | rpID: RP_ID, |
| 135dfe5 | | | 178 | allowCredentials, |
| 135dfe5 | | | 179 | }); |
| 135dfe5 | | | 180 | |
| 135dfe5 | | | 181 | challenges.set(options.challenge, { |
| 135dfe5 | | | 182 | username: body.username, |
| 135dfe5 | | | 183 | expiresAt: Date.now() + CHALLENGE_TTL, |
| 135dfe5 | | | 184 | }); |
| 135dfe5 | | | 185 | |
| 135dfe5 | | | 186 | return { options }; |
| 135dfe5 | | | 187 | }); |
| 135dfe5 | | | 188 | |
| 135dfe5 | | | 189 | // ── Login Step 2: Verify assertion ─────────────────────────────── |
| 135dfe5 | | | 190 | |
| 135dfe5 | | | 191 | app.post("/login/complete", async (request, reply) => { |
| 135dfe5 | | | 192 | const body = request.body as { |
| 135dfe5 | | | 193 | response: AuthenticationResponseJSON; |
| 135dfe5 | | | 194 | challenge: string; |
| 135dfe5 | | | 195 | }; |
| 135dfe5 | | | 196 | |
| 135dfe5 | | | 197 | const stored = challenges.get(body.challenge); |
| 135dfe5 | | | 198 | if (!stored || stored.expiresAt < Date.now()) { |
| 135dfe5 | | | 199 | return reply.code(400).send({ error: "Challenge expired or invalid" }); |
| 135dfe5 | | | 200 | } |
| 135dfe5 | | | 201 | |
| 135dfe5 | | | 202 | const credentialId = body.response.id; |
| 135dfe5 | | | 203 | const credRow = db |
| 135dfe5 | | | 204 | .prepare(` |
| 135dfe5 | | | 205 | SELECT c.*, u.username, u.display_name |
| 135dfe5 | | | 206 | FROM credentials c |
| 135dfe5 | | | 207 | JOIN users u ON c.user_id = u.id |
| 135dfe5 | | | 208 | WHERE c.id = ? |
| 135dfe5 | | | 209 | `) |
| 135dfe5 | | | 210 | .get(credentialId) as any; |
| 135dfe5 | | | 211 | |
| 135dfe5 | | | 212 | if (!credRow) { |
| 135dfe5 | | | 213 | return reply.code(400).send({ error: "Unknown credential" }); |
| 135dfe5 | | | 214 | } |
| 135dfe5 | | | 215 | |
| 135dfe5 | | | 216 | try { |
| 135dfe5 | | | 217 | const verification = await verifyAuthenticationResponse({ |
| 135dfe5 | | | 218 | response: body.response, |
| 135dfe5 | | | 219 | expectedChallenge: body.challenge, |
| a33b2b6 | | | 220 | expectedOrigin: EXPECTED_ORIGIN, |
| 135dfe5 | | | 221 | expectedRPID: RP_ID, |
| 135dfe5 | | | 222 | credential: { |
| 135dfe5 | | | 223 | id: credRow.id, |
| 135dfe5 | | | 224 | publicKey: new Uint8Array(credRow.public_key), |
| 135dfe5 | | | 225 | counter: credRow.counter, |
| 135dfe5 | | | 226 | transports: JSON.parse(credRow.transports || "[]"), |
| 135dfe5 | | | 227 | }, |
| 135dfe5 | | | 228 | }); |
| 135dfe5 | | | 229 | |
| 135dfe5 | | | 230 | if (!verification.verified) { |
| 135dfe5 | | | 231 | return reply.code(400).send({ error: "Authentication failed" }); |
| 135dfe5 | | | 232 | } |
| 135dfe5 | | | 233 | |
| 135dfe5 | | | 234 | db.prepare("UPDATE credentials SET counter = ? WHERE id = ?") |
| 135dfe5 | | | 235 | .run(verification.authenticationInfo.newCounter, credRow.id); |
| 135dfe5 | | | 236 | |
| 135dfe5 | | | 237 | challenges.delete(body.challenge); |
| 135dfe5 | | | 238 | |
| 135dfe5 | | | 239 | const token = app.jwt.sign({ |
| 135dfe5 | | | 240 | id: credRow.user_id, |
| 135dfe5 | | | 241 | username: credRow.username, |
| 3c994d3 | | | 242 | display_name: credRow.display_name, |
| 3c994d3 | | | 243 | type: "session", |
| 135dfe5 | | | 244 | }); |
| 135dfe5 | | | 245 | |
| 135dfe5 | | | 246 | return { |
| 135dfe5 | | | 247 | token, |
| 135dfe5 | | | 248 | user: { |
| 135dfe5 | | | 249 | id: credRow.user_id, |
| 135dfe5 | | | 250 | username: credRow.username, |
| 135dfe5 | | | 251 | display_name: credRow.display_name, |
| 135dfe5 | | | 252 | }, |
| 135dfe5 | | | 253 | }; |
| 135dfe5 | | | 254 | } catch (err: any) { |
| 135dfe5 | | | 255 | return reply.code(400).send({ error: err.message }); |
| 135dfe5 | | | 256 | } |
| 135dfe5 | | | 257 | }); |
| 135dfe5 | | | 258 | |
| 7010ba9 | | | 259 | // ── Device Code Flow (for headless/remote CLI auth) ────────────── |
| 7010ba9 | | | 260 | |
| 7010ba9 | | | 261 | const deviceCodes = new Map< |
| 7010ba9 | | | 262 | string, |
| 7010ba9 | | | 263 | { expiresAt: number; token?: string; status: "pending" | "complete" } |
| 7010ba9 | | | 264 | >(); |
| 7010ba9 | | | 265 | |
| 7010ba9 | | | 266 | // Cleanup expired device codes |
| 7010ba9 | | | 267 | setInterval(() => { |
| 7010ba9 | | | 268 | const now = Date.now(); |
| 7010ba9 | | | 269 | for (const [key, val] of deviceCodes) { |
| 7010ba9 | | | 270 | if (val.expiresAt < now) deviceCodes.delete(key); |
| 7010ba9 | | | 271 | } |
| 7010ba9 | | | 272 | }, 60 * 1000); |
| 7010ba9 | | | 273 | |
| 7010ba9 | | | 274 | function generateCode(): string { |
| 7010ba9 | | | 275 | const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; |
| 7010ba9 | | | 276 | let code = ""; |
| 7010ba9 | | | 277 | for (let i = 0; i < 8; i++) { |
| 7010ba9 | | | 278 | if (i === 4) code += "-"; |
| 7010ba9 | | | 279 | code += chars[Math.floor(Math.random() * chars.length)]; |
| 7010ba9 | | | 280 | } |
| 7010ba9 | | | 281 | return code; |
| 7010ba9 | | | 282 | } |
| 7010ba9 | | | 283 | |
| 7010ba9 | | | 284 | // CLI calls this to start device code flow |
| 7010ba9 | | | 285 | app.post("/device-code", async () => { |
| 7010ba9 | | | 286 | const code = generateCode(); |
| 7010ba9 | | | 287 | deviceCodes.set(code, { |
| 7010ba9 | | | 288 | expiresAt: Date.now() + 10 * 60 * 1000, // 10 minutes |
| 7010ba9 | | | 289 | status: "pending", |
| 7010ba9 | | | 290 | }); |
| 7010ba9 | | | 291 | const origin = ORIGIN_ENV.split(",")[0].trim(); |
| 7010ba9 | | | 292 | return { code, url: `${origin}/cli-auth?code=${code}`, expires_in: 600 }; |
| 7010ba9 | | | 293 | }); |
| 7010ba9 | | | 294 | |
| 7010ba9 | | | 295 | // CLI polls this to check if user approved |
| 7010ba9 | | | 296 | app.get("/device-code/:code", async (request, reply) => { |
| 7010ba9 | | | 297 | const { code } = request.params as { code: string }; |
| 7010ba9 | | | 298 | const entry = deviceCodes.get(code); |
| 7010ba9 | | | 299 | |
| 7010ba9 | | | 300 | if (!entry || entry.expiresAt < Date.now()) { |
| 7010ba9 | | | 301 | return reply.code(404).send({ error: "Code not found or expired" }); |
| 7010ba9 | | | 302 | } |
| 7010ba9 | | | 303 | |
| 7010ba9 | | | 304 | if (entry.status === "complete" && entry.token) { |
| 7010ba9 | | | 305 | deviceCodes.delete(code); |
| 7010ba9 | | | 306 | return { status: "complete", token: entry.token }; |
| 7010ba9 | | | 307 | } |
| 7010ba9 | | | 308 | |
| 7010ba9 | | | 309 | return { status: "pending" }; |
| 7010ba9 | | | 310 | }); |
| 7010ba9 | | | 311 | |
| 7010ba9 | | | 312 | // Web page calls this (authenticated) to approve the device code |
| 7010ba9 | | | 313 | app.post("/device-code/:code/approve", { |
| 7010ba9 | | | 314 | preHandler: [(app as any).authenticate], |
| 7010ba9 | | | 315 | handler: async (request, reply) => { |
| 7010ba9 | | | 316 | const { code } = request.params as { code: string }; |
| 7010ba9 | | | 317 | const entry = deviceCodes.get(code); |
| 7010ba9 | | | 318 | |
| 7010ba9 | | | 319 | if (!entry || entry.expiresAt < Date.now()) { |
| 7010ba9 | | | 320 | return reply.code(404).send({ error: "Code not found or expired" }); |
| 7010ba9 | | | 321 | } |
| 7010ba9 | | | 322 | |
| 7010ba9 | | | 323 | if (entry.status === "complete") { |
| 7010ba9 | | | 324 | return reply.code(400).send({ error: "Code already used" }); |
| 7010ba9 | | | 325 | } |
| 7010ba9 | | | 326 | |
| 7010ba9 | | | 327 | const payload = request.user as any; |
| 7010ba9 | | | 328 | const user = db |
| 7010ba9 | | | 329 | .prepare("SELECT id, username, display_name FROM users WHERE id = ?") |
| 7010ba9 | | | 330 | .get(payload.id) as any; |
| 7010ba9 | | | 331 | |
| 7010ba9 | | | 332 | if (!user) { |
| 7010ba9 | | | 333 | return reply.code(404).send({ error: "User not found" }); |
| 7010ba9 | | | 334 | } |
| 7010ba9 | | | 335 | |
| 7010ba9 | | | 336 | // Create a PAT |
| 7010ba9 | | | 337 | const token = app.jwt.sign( |
| 7010ba9 | | | 338 | { |
| 7010ba9 | | | 339 | id: user.id, |
| 7010ba9 | | | 340 | username: user.username, |
| 7010ba9 | | | 341 | display_name: user.display_name, |
| 7010ba9 | | | 342 | type: "pat", |
| 7010ba9 | | | 343 | }, |
| 7010ba9 | | | 344 | { expiresIn: "365d" } |
| 7010ba9 | | | 345 | ); |
| 7010ba9 | | | 346 | |
| 7010ba9 | | | 347 | const tokenHash = createHash("sha256").update(token).digest("hex"); |
| 7010ba9 | | | 348 | const expiresAt = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(); |
| 7010ba9 | | | 349 | |
| 7010ba9 | | | 350 | db.prepare( |
| 7010ba9 | | | 351 | "INSERT INTO api_tokens (user_id, name, token_hash, expires_at) VALUES (?, ?, ?, ?)" |
| 7010ba9 | | | 352 | ).run(user.id, `CLI (${new Date().toLocaleDateString()})`, tokenHash, expiresAt); |
| 7010ba9 | | | 353 | |
| 7010ba9 | | | 354 | entry.status = "complete"; |
| 7010ba9 | | | 355 | entry.token = token; |
| 7010ba9 | | | 356 | |
| 7010ba9 | | | 357 | return { status: "approved" }; |
| 7010ba9 | | | 358 | }, |
| 7010ba9 | | | 359 | }); |
| 7010ba9 | | | 360 | |
| fafa260 | | | 361 | // ── TLS client certificates (for Sapling mTLS with Mononoke) ──── |
| fafa260 | | | 362 | |
| fafa260 | | | 363 | const TLS_DIR = process.env.TLS_DIR ?? "/data/grove/tls"; |
| fafa260 | | | 364 | |
| fafa260 | | | 365 | app.get("/tls-certs", { |
| fafa260 | | | 366 | preHandler: [(app as any).authenticate], |
| fafa260 | | | 367 | handler: async (_request, reply) => { |
| fafa260 | | | 368 | const { readFileSync, existsSync } = await import("fs"); |
| fafa260 | | | 369 | const { join } = await import("path"); |
| fafa260 | | | 370 | |
| fafa260 | | | 371 | const caPath = join(TLS_DIR, "ca.crt"); |
| fafa260 | | | 372 | const certPath = join(TLS_DIR, "client.crt"); |
| fafa260 | | | 373 | const keyPath = join(TLS_DIR, "client.key"); |
| fafa260 | | | 374 | |
| fafa260 | | | 375 | if (!existsSync(caPath) || !existsSync(certPath) || !existsSync(keyPath)) { |
| fafa260 | | | 376 | return reply.code(503).send({ error: "TLS certificates not configured on this instance" }); |
| fafa260 | | | 377 | } |
| fafa260 | | | 378 | |
| fafa260 | | | 379 | return { |
| fafa260 | | | 380 | ca: readFileSync(caPath, "utf-8"), |
| fafa260 | | | 381 | cert: readFileSync(certPath, "utf-8"), |
| fafa260 | | | 382 | key: readFileSync(keyPath, "utf-8"), |
| fafa260 | | | 383 | }; |
| fafa260 | | | 384 | }, |
| fafa260 | | | 385 | }); |
| fafa260 | | | 386 | |
| 135dfe5 | | | 387 | // ── Get current user ───────────────────────────────────────────── |
| 135dfe5 | | | 388 | |
| 135dfe5 | | | 389 | app.get("/me", { |
| 135dfe5 | | | 390 | preHandler: [(app as any).authenticate], |
| 135dfe5 | | | 391 | handler: async (request) => { |
| 135dfe5 | | | 392 | const payload = request.user as any; |
| 135dfe5 | | | 393 | |
| 135dfe5 | | | 394 | const user = db |
| 135dfe5 | | | 395 | .prepare("SELECT id, username, display_name, created_at FROM users WHERE id = ?") |
| 135dfe5 | | | 396 | .get(payload.id); |
| 135dfe5 | | | 397 | |
| 135dfe5 | | | 398 | return { user }; |
| 135dfe5 | | | 399 | }, |
| 135dfe5 | | | 400 | }); |
| 3c994d3 | | | 401 | |
| a9b2860 | | | 402 | // ── Refresh session token ──────────────────────────────────────── |
| a9b2860 | | | 403 | |
| a9b2860 | | | 404 | app.post("/refresh", { |
| a9b2860 | | | 405 | preHandler: [(app as any).authenticate], |
| a9b2860 | | | 406 | handler: async (request, reply) => { |
| a9b2860 | | | 407 | const payload = request.user as any; |
| a9b2860 | | | 408 | |
| a9b2860 | | | 409 | if (payload.type !== "session") { |
| a9b2860 | | | 410 | return reply.code(403).send({ error: "Only session tokens can be refreshed" }); |
| a9b2860 | | | 411 | } |
| a9b2860 | | | 412 | |
| a9b2860 | | | 413 | const user = db |
| a9b2860 | | | 414 | .prepare("SELECT id, username, display_name FROM users WHERE id = ?") |
| a9b2860 | | | 415 | .get(payload.id) as any; |
| a9b2860 | | | 416 | |
| a9b2860 | | | 417 | if (!user) { |
| a9b2860 | | | 418 | return reply.code(401).send({ error: "User not found" }); |
| a9b2860 | | | 419 | } |
| a9b2860 | | | 420 | |
| a9b2860 | | | 421 | const token = app.jwt.sign({ |
| a9b2860 | | | 422 | id: user.id, |
| a9b2860 | | | 423 | username: user.username, |
| a9b2860 | | | 424 | display_name: user.display_name, |
| a9b2860 | | | 425 | type: "session", |
| a9b2860 | | | 426 | }); |
| a9b2860 | | | 427 | |
| a9b2860 | | | 428 | return { token, user: { id: user.id, username: user.username, display_name: user.display_name } }; |
| a9b2860 | | | 429 | }, |
| a9b2860 | | | 430 | }); |
| a9b2860 | | | 431 | |
| 3c994d3 | | | 432 | // ── Personal Access Tokens (PATs) ───────────────────────────────── |
| 3c994d3 | | | 433 | |
| 3c994d3 | | | 434 | const createTokenSchema = z.object({ |
| 3c994d3 | | | 435 | name: z.string().min(1).max(100), |
| 3c994d3 | | | 436 | expires_in: z.enum(["30d", "90d", "1y"]).default("1y"), |
| 3c994d3 | | | 437 | }); |
| 3c994d3 | | | 438 | |
| 3c994d3 | | | 439 | const EXPIRY_MAP: Record<string, string> = { |
| 3c994d3 | | | 440 | "30d": "30d", |
| 3c994d3 | | | 441 | "90d": "90d", |
| 3c994d3 | | | 442 | "1y": "365d", |
| 3c994d3 | | | 443 | }; |
| 3c994d3 | | | 444 | |
| 3c994d3 | | | 445 | app.post("/tokens", { |
| 3c994d3 | | | 446 | preHandler: [(app as any).authenticate], |
| 3c994d3 | | | 447 | handler: async (request, reply) => { |
| 3c994d3 | | | 448 | const parsed = createTokenSchema.safeParse(request.body); |
| 3c994d3 | | | 449 | if (!parsed.success) { |
| 3c994d3 | | | 450 | return reply.code(400).send({ error: parsed.error.flatten() }); |
| 3c994d3 | | | 451 | } |
| 3c994d3 | | | 452 | |
| 3c994d3 | | | 453 | const payload = request.user as any; |
| 3c994d3 | | | 454 | const { name, expires_in } = parsed.data; |
| 3c994d3 | | | 455 | |
| 3c994d3 | | | 456 | const user = db |
| 3c994d3 | | | 457 | .prepare("SELECT id, username, display_name FROM users WHERE id = ?") |
| 3c994d3 | | | 458 | .get(payload.id) as any; |
| 3c994d3 | | | 459 | |
| 3c994d3 | | | 460 | if (!user) { |
| 3c994d3 | | | 461 | return reply.code(404).send({ error: "User not found" }); |
| 3c994d3 | | | 462 | } |
| 3c994d3 | | | 463 | |
| 3c994d3 | | | 464 | const token = app.jwt.sign( |
| 3c994d3 | | | 465 | { |
| 3c994d3 | | | 466 | id: user.id, |
| 3c994d3 | | | 467 | username: user.username, |
| 3c994d3 | | | 468 | display_name: user.display_name, |
| 3c994d3 | | | 469 | type: "pat", |
| 3c994d3 | | | 470 | }, |
| 3c994d3 | | | 471 | { expiresIn: EXPIRY_MAP[expires_in] } |
| 3c994d3 | | | 472 | ); |
| 3c994d3 | | | 473 | |
| 3c994d3 | | | 474 | const tokenHash = createHash("sha256").update(token).digest("hex"); |
| 3c994d3 | | | 475 | const expiresAt = new Date( |
| 3c994d3 | | | 476 | Date.now() + parseInt(EXPIRY_MAP[expires_in]) * 24 * 60 * 60 * 1000 |
| 3c994d3 | | | 477 | ).toISOString(); |
| 3c994d3 | | | 478 | |
| 3c994d3 | | | 479 | const result = db |
| 3c994d3 | | | 480 | .prepare( |
| 3c994d3 | | | 481 | "INSERT INTO api_tokens (user_id, name, token_hash, expires_at) VALUES (?, ?, ?, ?)" |
| 3c994d3 | | | 482 | ) |
| 3c994d3 | | | 483 | .run(user.id, name, tokenHash, expiresAt); |
| 3c994d3 | | | 484 | |
| 3c994d3 | | | 485 | return reply.code(201).send({ |
| 3c994d3 | | | 486 | token, |
| 3c994d3 | | | 487 | api_token: { |
| 3c994d3 | | | 488 | id: result.lastInsertRowid, |
| 3c994d3 | | | 489 | name, |
| 3c994d3 | | | 490 | expires_at: expiresAt, |
| 3c994d3 | | | 491 | created_at: new Date().toISOString(), |
| 3c994d3 | | | 492 | }, |
| 3c994d3 | | | 493 | }); |
| 3c994d3 | | | 494 | }, |
| 3c994d3 | | | 495 | }); |
| 3c994d3 | | | 496 | |
| 3c994d3 | | | 497 | app.get("/tokens", { |
| 3c994d3 | | | 498 | preHandler: [(app as any).authenticate], |
| 3c994d3 | | | 499 | handler: async (request) => { |
| 3c994d3 | | | 500 | const payload = request.user as any; |
| 3c994d3 | | | 501 | |
| 3c994d3 | | | 502 | const tokens = db |
| 3c994d3 | | | 503 | .prepare( |
| 3c994d3 | | | 504 | "SELECT id, name, expires_at, last_used_at, created_at FROM api_tokens WHERE user_id = ? ORDER BY created_at DESC" |
| 3c994d3 | | | 505 | ) |
| 3c994d3 | | | 506 | .all(payload.id); |
| 3c994d3 | | | 507 | |
| 3c994d3 | | | 508 | return { tokens }; |
| 3c994d3 | | | 509 | }, |
| 3c994d3 | | | 510 | }); |
| 3c994d3 | | | 511 | |
| 3c994d3 | | | 512 | app.delete("/tokens/:id", { |
| 3c994d3 | | | 513 | preHandler: [(app as any).authenticate], |
| 3c994d3 | | | 514 | handler: async (request, reply) => { |
| 3c994d3 | | | 515 | const payload = request.user as any; |
| 3c994d3 | | | 516 | const { id } = request.params as { id: string }; |
| 3c994d3 | | | 517 | |
| 3c994d3 | | | 518 | const result = db |
| 3c994d3 | | | 519 | .prepare("DELETE FROM api_tokens WHERE id = ? AND user_id = ?") |
| 3c994d3 | | | 520 | .run(id, payload.id); |
| 3c994d3 | | | 521 | |
| 3c994d3 | | | 522 | if (result.changes === 0) { |
| 3c994d3 | | | 523 | return reply.code(404).send({ error: "Token not found" }); |
| 3c994d3 | | | 524 | } |
| 3c994d3 | | | 525 | |
| 3c994d3 | | | 526 | return reply.code(204).send(); |
| 3c994d3 | | | 527 | }, |
| 3c994d3 | | | 528 | }); |
| 135dfe5 | | | 529 | } |