-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
318 lines (276 loc) · 8.28 KB
/
auth.ts
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import type { FreshContext } from "$fresh/server.ts";
import { type Cookie, deleteCookie, getCookies, setCookie } from "@std/http";
import { timingSafeEqual } from "node:crypto";
import { decodeBase64Url, encodeBase64Url } from "@std/encoding/base64url";
import { ensureUserExists } from "./lib/users.ts";
const OAUTH2_CLIENT_ID = Deno.env.get("OAUTH2_CLIENT_ID")!;
const OAUTH2_CLIENT_SECRET = Deno.env.get("OAUTH2_CLIENT_SECRET")!;
const OAUTH2_AUTHORIZE_URL = Deno.env.get("OAUTH2_AUTHORIZE_URL")!;
const OAUTH2_TOKEN_URL = Deno.env.get("OAUTH2_TOKEN_URL")!;
// 10 minutes.
const SESSION_TIME = 1000 * 60 * 15;
{
const missing = Object.entries({
OAUTH2_CLIENT_ID,
OAUTH2_CLIENT_SECRET,
OAUTH2_AUTHORIZE_URL,
OAUTH2_TOKEN_URL,
}).filter(([_, value]) => !value?.trim?.()).map(([key]) => key).join(", ");
if (missing) {
throw new Error(`Missing environment variables: ${missing}`);
}
}
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(OAUTH2_CLIENT_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"],
);
export interface Session {
exp: number;
sub: string;
email: string;
name: string;
viewer: boolean;
short_url: boolean;
vanity_url: boolean;
administrator: boolean;
}
export interface StateWithCleanup {
_auth_cleanup?: (response: Response) => void;
}
export interface StateWithCookies {
cookies: Record<string, string>;
}
export interface StateWithSession {
session: Session;
}
export interface StateWithNewSession {
newSessionCookie?: Cookie;
}
const e = new TextEncoder();
const d = new TextDecoder();
async function signSession(
session: Session,
) {
const salt: Uint8Array = crypto.getRandomValues(new Uint8Array(32));
const body = e.encode(JSON.stringify(session));
const saltAndBody = new Uint8Array(salt.length + body.length);
saltAndBody.set(salt);
saltAndBody.set(body, salt.length);
const signature = new Uint8Array(
await crypto.subtle.sign(
{ name: "HMAC", hash: "SHA-256" },
key,
saltAndBody,
),
);
const signatureAndSaltAndBody = new Uint8Array(
signature.byteLength + saltAndBody.byteLength,
);
signatureAndSaltAndBody.set(signature);
signatureAndSaltAndBody.set(saltAndBody, signature.byteLength);
return encodeBase64Url(signatureAndSaltAndBody);
}
async function verifySession(
sessionStr: string,
verifyTime = true,
): Promise<void | Session> {
const signatureAndSaltAndBody = decodeBase64Url(sessionStr);
const signature1 = signatureAndSaltAndBody.slice(0, 32);
const saltAndBody = signatureAndSaltAndBody.slice(32);
const signature2 = new Uint8Array(
await crypto.subtle.sign(
{ name: "HMAC", hash: "SHA-256" },
key,
saltAndBody,
),
);
if (!timingSafeEqual(signature1, signature2)) {
return;
}
const body: Session = JSON.parse(d.decode(saltAndBody.slice(32)));
if (typeof body !== "object" || body === null) {
return;
}
if (verifyTime && (body.exp < Date.now())) {
console.log("Session expired", sessionStr);
return;
}
return body;
}
export async function getSessionDetails(
request: Request,
context: FreshContext<
StateWithCookies & StateWithNewSession & StateWithCleanup
>,
): Promise<void | Session> {
const cookies = getCookies(request.headers);
context.state.cookies = cookies;
if (cookies.session) {
const session = await verifySession(cookies.session);
if (typeof session !== "object" || session === null) {
context.state._auth_cleanup = (response) =>
deleteCookie(response.headers, "session");
return;
}
session.exp = Date.now() + SESSION_TIME;
context.state.newSessionCookie = {
name: "session",
value: await signSession(session),
expires: session.exp,
httpOnly: true,
sameSite: "Strict",
path: "/",
};
return session;
}
}
function refresh(url: URL) {
return new Response(
`<!DOCTYPE html><html><head><title>Refreshing...</title><meta http-equiv="refresh" content="0; url=${url.href}"/></head><body><p>Redirecting...</p></body></html>`,
{
status: 200,
headers: {
"Content-Type": "text/html",
},
},
);
}
async function authorize(
_: Request,
context: FreshContext<StateWithCookies>,
): Promise<Response> {
const url = new URL(OAUTH2_AUTHORIZE_URL);
url.searchParams.set("client_id", OAUTH2_CLIENT_ID);
url.searchParams.set("response_type", "code");
url.searchParams.set("redirect_uri", context.url.origin);
url.searchParams.set("scope", "openid");
url.searchParams.set("response_mode", "form_post");
url.searchParams.set(
"state",
await signSession({ exp: Date.now() } as Session),
);
return refresh(url);
}
async function callback(
request: Request,
context: FreshContext<StateWithCookies>,
): Promise<Response> {
const form = await request.formData();
const code = form.get("code")?.toString()!;
const state = form.get("state")?.toString()!;
const error = form.get("error")?.toString()!;
const error_description = form.get("error_description")?.toString()!;
if (error || error_description) {
throw new Deno.errors.Http(`Error: ${error} - ${error_description}`, {
cause: "oauth2",
});
}
if (!await verifySession(state, false)) {
throw new Deno.errors.Http("Invalid state", { cause: "oauth2" });
}
const res = await fetch(OAUTH2_TOKEN_URL, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: OAUTH2_CLIENT_ID,
scope: "openid",
code,
redirect_uri: context.url.origin,
grant_type: "authorization_code",
client_secret: OAUTH2_CLIENT_SECRET,
}),
});
const result = await res.json();
if (result.error) {
throw new Deno.errors.Http(
`Error: ${result.error} (${
result.error_codes?.join(",")
}) - ${result.error_description}`,
{ cause: "oauth2" },
);
}
const session: Session = {
exp: Date.now() + SESSION_TIME,
} as Session;
{
const firstDot = result.access_token.indexOf(".");
const secondDot = result.access_token.indexOf(".", firstDot + 1);
const payload = JSON.parse(
d.decode(
decodeBase64Url(result.access_token.slice(firstDot + 1, secondDot)),
),
);
session.email = payload.upn;
session.name = payload.given_name;
}
{
const firstDot = result.id_token.indexOf(".");
const secondDot = result.id_token.indexOf(".", firstDot + 1);
const payload = JSON.parse(
d.decode(decodeBase64Url(result.id_token.slice(firstDot + 1, secondDot))),
);
session.sub = payload.sub;
payload.roles?.forEach((role: string) => {
switch (role?.trim()?.toLowerCase()) {
case "viewer":
session.viewer = true;
break;
case "short_url":
session.viewer = true;
session.short_url = true;
break;
case "vanity_url":
session.viewer = true;
session.vanity_url = true;
break;
case "administrator":
session.viewer = true;
session.short_url = true;
session.vanity_url = true;
session.administrator = true;
break;
}
});
}
const response = refresh(new URL("/", context.url.origin));
const sessionStr = await signSession(session);
setCookie(response.headers, {
name: "session",
value: sessionStr,
expires: session.exp,
httpOnly: true,
sameSite: "Strict",
});
await ensureUserExists(session);
console.log("Created session", sessionStr);
return response;
}
export async function ensureUserIsAuthenticated(
request: Request,
context: FreshContext<
& Partial<StateWithCookies>
& Partial<StateWithSession>
& Partial<StateWithNewSession>
>,
): Promise<void | Response> {
const session = await getSessionDetails(
request,
context as FreshContext<StateWithCookies>,
);
if (session) {
context.state.session = session;
return;
}
console.debug("No session found, redirecting to auth");
console.debug("Request URL", request.method, request.url);
if (request.method === "GET") {
return await authorize(request, context as FreshContext<StateWithCookies>);
} else if (request.method === "POST") {
return await callback(request, context as FreshContext<StateWithCookies>);
}
}