| 1 | import { randomBytes } from "node:crypto"; |
| 2 | import { AuthClient, authSubjectForUser, identityFromUser } from "./client.js"; |
| 3 | import { parseCookies, publicOrigin, isSecureRequest, setCookie, clearCookie } from "./cookies.js"; |
| 4 | |
| 5 | const EXTEND_INTERVAL_MS = 45 * 60 * 1000; |
| 6 | |
| 7 | export class OAuthAuth |
| 8 | { |
| 9 | constructor (config, client = new AuthClient(config), stateDb = null) |
| 10 | { |
| 11 | this.config = config; |
| 12 | this.client = client; |
| 13 | this.stateDb = stateDb; |
| 14 | this.sessions = new Set(); |
| 15 | } |
| 16 | |
| 17 | register (session) |
| 18 | { |
| 19 | this.sessions.add(session); |
| 20 | } |
| 21 | |
| 22 | release (session) |
| 23 | { |
| 24 | this.sessions.delete(session); |
| 25 | if (session.extendTimer) |
| 26 | { |
| 27 | clearInterval(session.extendTimer); |
| 28 | session.extendTimer = null; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | redirectUriFor (req) |
| 33 | { |
| 34 | if (this.config.redirectUri) |
| 35 | { return this.config.redirectUri; } |
| 36 | return `${publicOrigin(req)}/auth/callback`; |
| 37 | } |
| 38 | |
| 39 | beginLogin (req, res, returnTo = "/") |
| 40 | { |
| 41 | const state = randomBytes(24).toString("hex"); |
| 42 | const secure = isSecureRequest(req); |
| 43 | setCookie(res, this.config.stateCookie, state, { |
| 44 | maxAgeSec: 600, |
| 45 | secure, |
| 46 | httpOnly: true |
| 47 | }); |
| 48 | setCookie(res, "questward_return_to", safeReturnTo(returnTo), { |
| 49 | maxAgeSec: 600, |
| 50 | secure, |
| 51 | httpOnly: true |
| 52 | }); |
| 53 | const redirectUri = encodeURIComponent(this.redirectUriFor(req)); |
| 54 | const clientId = encodeURIComponent(this.config.clientId); |
| 55 | const location = `${this.config.baseUrl}/oauth/authorize` |
| 56 | + `?client_id=${clientId}` |
| 57 | + `&redirect_uri=${redirectUri}` |
| 58 | + `&response_type=code` |
| 59 | + `&state=${state}`; |
| 60 | res.writeHead(302, { Location: location }); |
| 61 | res.end(); |
| 62 | } |
| 63 | |
| 64 | async finishLogin (req, res) |
| 65 | { |
| 66 | const url = new URL(req.url ?? "/", publicOrigin(req)); |
| 67 | const code = url.searchParams.get("code"); |
| 68 | const state = url.searchParams.get("state"); |
| 69 | const secure = isSecureRequest(req); |
| 70 | const cookies = parseCookies(req.headers.cookie); |
| 71 | const expectedState = cookies[this.config.stateCookie]; |
| 72 | const returnTo = safeReturnTo(cookies.questward_return_to ?? "/"); |
| 73 | clearCookie(res, this.config.stateCookie, { secure }); |
| 74 | clearCookie(res, "questward_return_to", { secure }); |
| 75 | |
| 76 | if (!code || !state || !expectedState || state !== expectedState) |
| 77 | { |
| 78 | res.writeHead(302, { Location: `/auth/error?message=${encodeURIComponent("Sign-in failed. Please try again.")}` }); |
| 79 | res.end(); |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | try |
| 84 | { |
| 85 | const tokenPayload = await this.client.exchangeCode({ |
| 86 | code, |
| 87 | redirectUri: this.redirectUriFor(req) |
| 88 | }); |
| 89 | const token = tokenPayload.access_token; |
| 90 | const user = await this.client.fetchMe(token); |
| 91 | if (!user) |
| 92 | { |
| 93 | throw new Error("Could not load your account profile after sign-in."); |
| 94 | } |
| 95 | const identity = identityFromUser(user, token); |
| 96 | this.#clearLocalSession(res, req, cookies); |
| 97 | setCookie(res, this.config.tokenCookie, token, { |
| 98 | maxAgeSec: tokenPayload.expires_in ?? 3600, |
| 99 | secure, |
| 100 | httpOnly: true |
| 101 | }); |
| 102 | this.#issueLocalSession(res, req, identity); |
| 103 | res.writeHead(302, { Location: returnTo }); |
| 104 | res.end(); |
| 105 | } |
| 106 | catch (error) |
| 107 | { |
| 108 | res.writeHead(302, { |
| 109 | Location: `/auth/error?message=${encodeURIComponent(error.message ?? "Sign-in failed.")}` |
| 110 | }); |
| 111 | res.end(); |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | async logout (req, res, returnTo = "/") |
| 116 | { |
| 117 | const secure = isSecureRequest(req); |
| 118 | const cookies = parseCookies(req.headers.cookie); |
| 119 | const token = cookies[this.config.tokenCookie]; |
| 120 | this.#clearLocalSession(res, req, cookies); |
| 121 | await this.client.revokeToken(token); |
| 122 | clearCookie(res, this.config.tokenCookie, { secure }); |
| 123 | res.writeHead(302, { Location: safeReturnTo(returnTo) }); |
| 124 | res.end(); |
| 125 | } |
| 126 | |
| 127 | async statusFromRequest (req, res = null) |
| 128 | { |
| 129 | const identity = await this.authenticateRequest(req, res); |
| 130 | if (!identity) |
| 131 | { return { authenticated: false }; } |
| 132 | return { |
| 133 | authenticated: true, |
| 134 | authSubject: identity.authSubject, |
| 135 | username: identity.username, |
| 136 | email: identity.email |
| 137 | }; |
| 138 | } |
| 139 | |
| 140 | async authenticateRequest (req, res = null) |
| 141 | { |
| 142 | const cookies = parseCookies(req.headers.cookie); |
| 143 | const localIdentity = this.#identityFromLocalSession(cookies); |
| 144 | if (localIdentity) |
| 145 | { return localIdentity; } |
| 146 | |
| 147 | const token = cookies[this.config.tokenCookie]; |
| 148 | if (!token) |
| 149 | { return null; } |
| 150 | |
| 151 | let user; |
| 152 | try |
| 153 | { |
| 154 | user = await this.client.fetchMe(token); |
| 155 | } |
| 156 | catch |
| 157 | { |
| 158 | return null; |
| 159 | } |
| 160 | if (!user) |
| 161 | { return null; } |
| 162 | |
| 163 | const identity = identityFromUser(user, token); |
| 164 | if (res) |
| 165 | { |
| 166 | this.#clearLocalSession(res, req, cookies); |
| 167 | this.#issueLocalSession(res, req, identity); |
| 168 | } |
| 169 | return identity; |
| 170 | } |
| 171 | |
| 172 | startSessionMaintenance (session) |
| 173 | { |
| 174 | if (!session.accessToken) |
| 175 | { return; } |
| 176 | session.extendTimer = setInterval(() => |
| 177 | { |
| 178 | void this.client.extendSession(session.accessToken); |
| 179 | }, EXTEND_INTERVAL_MS); |
| 180 | if (typeof session.extendTimer.unref === "function") |
| 181 | { session.extendTimer.unref(); } |
| 182 | } |
| 183 | |
| 184 | #identityFromLocalSession (cookies) |
| 185 | { |
| 186 | if (!this.stateDb) |
| 187 | { return null; } |
| 188 | const sessionId = cookies[this.config.sessionCookie]; |
| 189 | if (!sessionId) |
| 190 | { return null; } |
| 191 | const row = this.stateDb.getAuthSession(sessionId); |
| 192 | if (!row) |
| 193 | { return null; } |
| 194 | if (row.expires_at <= Date.now()) |
| 195 | { |
| 196 | this.stateDb.deleteAuthSession(sessionId); |
| 197 | return null; |
| 198 | } |
| 199 | return { |
| 200 | authSubject: row.auth_subject, |
| 201 | username: row.username ?? null, |
| 202 | email: row.email ?? null, |
| 203 | accessToken: row.access_token ?? null, |
| 204 | localSession: true |
| 205 | }; |
| 206 | } |
| 207 | |
| 208 | #issueLocalSession (res, req, identity) |
| 209 | { |
| 210 | if (!this.stateDb) |
| 211 | { return; } |
| 212 | const secure = isSecureRequest(req); |
| 213 | const sessionId = randomBytes(32).toString("hex"); |
| 214 | const maxAgeSec = this.config.sessionMaxAgeSec; |
| 215 | this.stateDb.createAuthSession({ |
| 216 | sessionId, |
| 217 | authSubject: identity.authSubject, |
| 218 | username: identity.username ?? null, |
| 219 | email: identity.email ?? null, |
| 220 | accessToken: identity.accessToken ?? null, |
| 221 | expiresAtMs: Date.now() + maxAgeSec * 1000 |
| 222 | }); |
| 223 | setCookie(res, this.config.sessionCookie, sessionId, { |
| 224 | maxAgeSec, |
| 225 | secure, |
| 226 | httpOnly: true |
| 227 | }); |
| 228 | } |
| 229 | |
| 230 | #clearLocalSession (res, req, cookies) |
| 231 | { |
| 232 | if (!this.stateDb) |
| 233 | { return; } |
| 234 | const secure = isSecureRequest(req); |
| 235 | const sessionId = cookies[this.config.sessionCookie]; |
| 236 | this.stateDb.deleteAuthSession(sessionId); |
| 237 | clearCookie(res, this.config.sessionCookie, { secure }); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | function safeReturnTo (value) |
| 242 | { |
| 243 | if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//")) |
| 244 | { return "/"; } |
| 245 | return value; |
| 246 | } |
| 247 | |
| 248 | export { authSubjectForUser, identityFromUser }; |