-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.ts
63 lines (54 loc) · 1.93 KB
/
http.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
import jwt from 'jsonwebtoken'
import { Context, Json } from './context.js'
export * from '@riddance/host/lib/http'
export * from './context.js'
/*@__INLINE__*/
export function withStatus(error: Error, status: number) {
return Object.assign(error, { statusCode: status })
}
export function withPublicMessage(error: Error, message?: string): Error {
if (message) {
const enriched = error as unknown as { [key: string]: unknown }
if (enriched.body) {
;(enriched.body as { [key: string]: unknown }).message = message
} else {
enriched.body = { message }
}
}
return error
}
export function badRequest(publicMessage?: string) {
return withPublicMessage(withStatus(new Error('Bad request'), 400), publicMessage)
}
// Please authenticate yourself, e.g. log in or refresh your tokens
export function unauthorized() {
return withStatus(new Error('Unauthorized'), 401)
}
// I known who you are; you're never getting in
export function forbidden() {
return withStatus(new Error('Forbidden'), 403)
}
export function notFound() {
return withStatus(new Error('Not found'), 404)
}
export function notImplemented() {
return withStatus(new Error('Not implemented'), 501)
}
export function getBearer(context: Context, req: { headers: { authorization?: string } }): Json {
const key = context.env.BEARER_PUBLIC_KEY
if (!key) {
throw Error('Please set the BEARER_PUBLIC_KEY environment variable to extract bearer.')
}
const authHeader = req.headers.authorization
if (!authHeader?.startsWith('Bearer ')) {
throw unauthorized()
}
try {
const token = authHeader.substring('Bearer '.length)
const certificate = '-----BEGIN PUBLIC KEY-----\n' + key + '\n-----END PUBLIC KEY-----'
return jwt.verify(token, certificate, {})
} catch (e) {
context.log.debug('Error verifying jwt.', e)
throw unauthorized()
}
}