BlueGit

timfa questward

Files

questward / server / src / auth / oauth.js

oauth.js

oauth.js 4.1 KiB Download Raw
1import { randomBytes } from "node:crypto";
2import { AuthClient, authSubjectForUser, identityFromUser } from "./client.js";
3import { parseCookies, publicOrigin, isSecureRequest, setCookie, clearCookie } from "./cookies.js";
4
5const EXTEND_INTERVAL_MS = 45 * 60 * 1000;
6
7export class OAuthAuth
8{
9 constructor (config, client = new AuthClient(config))
10 {
11 this.config = config;
12 this.client = client;
13 this.sessions = new Set();
14 }
15
16 register (session)
17 {
18 this.sessions.add(session);
19 }
20
21 release (session)
22 {
23 this.sessions.delete(session);
24 if (session.extendTimer)
25 {
26 clearInterval(session.extendTimer);
27 session.extendTimer = null;
28 }
29 }
30
31 redirectUriFor (req)
32 {
33 if (this.config.redirectUri)
34 { return this.config.redirectUri; }
35 return `${publicOrigin(req)}/auth/callback`;
36 }
37
38 beginLogin (req, res, returnTo = "/")
39 {
40 const state = randomBytes(24).toString("hex");
41 const secure = isSecureRequest(req);
42 setCookie(res, this.config.stateCookie, state, {
43 maxAgeSec: 600,
44 secure,
45 httpOnly: true
46 });
47 setCookie(res, "questward_return_to", safeReturnTo(returnTo), {
48 maxAgeSec: 600,
49 secure,
50 httpOnly: true
51 });
52 const redirectUri = encodeURIComponent(this.redirectUriFor(req));
53 const clientId = encodeURIComponent(this.config.clientId);
54 const location = `${this.config.baseUrl}/oauth/authorize`
55 + `?client_id=${clientId}`
56 + `&redirect_uri=${redirectUri}`
57 + `&response_type=code`
58 + `&state=${state}`;
59 res.writeHead(302, { Location: location });
60 res.end();
61 }
62
63 async finishLogin (req, res)
64 {
65 const url = new URL(req.url ?? "/", publicOrigin(req));
66 const code = url.searchParams.get("code");
67 const state = url.searchParams.get("state");
68 const secure = isSecureRequest(req);
69 const cookies = parseCookies(req.headers.cookie);
70 const expectedState = cookies[this.config.stateCookie];
71 const returnTo = safeReturnTo(cookies.questward_return_to ?? "/");
72 clearCookie(res, this.config.stateCookie, { secure });
73 clearCookie(res, "questward_return_to", { secure });
74
75 if (!code || !state || !expectedState || state !== expectedState)
76 {
77 res.writeHead(302, { Location: `/auth/error?message=${encodeURIComponent("Sign-in failed. Please try again.")}` });
78 res.end();
79 return;
80 }
81
82 try
83 {
84 const tokenPayload = await this.client.exchangeCode({
85 code,
86 redirectUri: this.redirectUriFor(req)
87 });
88 setCookie(res, this.config.tokenCookie, tokenPayload.access_token, {
89 maxAgeSec: tokenPayload.expires_in ?? 3600,
90 secure,
91 httpOnly: true
92 });
93 res.writeHead(302, { Location: returnTo });
94 res.end();
95 }
96 catch (error)
97 {
98 res.writeHead(302, {
99 Location: `/auth/error?message=${encodeURIComponent(error.message ?? "Sign-in failed.")}`
100 });
101 res.end();
102 }
103 }
104
105 async logout (req, res, returnTo = "/")
106 {
107 const secure = isSecureRequest(req);
108 const cookies = parseCookies(req.headers.cookie);
109 const token = cookies[this.config.tokenCookie];
110 await this.client.revokeToken(token);
111 clearCookie(res, this.config.tokenCookie, { secure });
112 res.writeHead(302, { Location: safeReturnTo(returnTo) });
113 res.end();
114 }
115
116 async statusFromRequest (req)
117 {
118 const identity = await this.authenticateRequest(req);
119 if (!identity)
120 { return { authenticated: false }; }
121 return {
122 authenticated: true,
123 authSubject: identity.authSubject,
124 username: identity.username,
125 email: identity.email
126 };
127 }
128
129 async authenticateRequest (req)
130 {
131 const cookies = parseCookies(req.headers.cookie);
132 const token = cookies[this.config.tokenCookie];
133 if (!token)
134 { return null; }
135 const user = await this.client.fetchMe(token);
136 if (!user)
137 { return null; }
138 return identityFromUser(user, token);
139 }
140
141 startSessionMaintenance (session)
142 {
143 if (!session.accessToken)
144 { return; }
145 session.extendTimer = setInterval(() =>
146 {
147 void this.client.extendSession(session.accessToken);
148 }, EXTEND_INTERVAL_MS);
149 if (typeof session.extendTimer.unref === "function")
150 { session.extendTimer.unref(); }
151 }
152}
153
154function safeReturnTo (value)
155{
156 if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//"))
157 { return "/"; }
158 return value;
159}
160
161export { authSubjectForUser, identityFromUser };