-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
worker.js
168 lines (137 loc) · 4.35 KB
/
worker.js
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
import * as config from './config.json'
import { Hono } from 'hono'
import * as jose from 'jose'
const algorithm = {
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' },
}
const importAlgo = {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
}
async function loadOrGenerateKeyPair(KV) {
let keyPair = {}
let keyPairJson = await KV.get('keys', { type: 'json' })
if (keyPairJson !== null) {
keyPair.publicKey = await crypto.subtle.importKey('jwk', keyPairJson.publicKey, importAlgo, true, ['verify'])
keyPair.privateKey = await crypto.subtle.importKey('jwk', keyPairJson.privateKey, importAlgo, true, ['sign'])
return keyPair
} else {
keyPair = await crypto.subtle.generateKey(algorithm, true, ['sign', 'verify'])
await KV.put('keys', JSON.stringify({
privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey),
publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey)
}))
return keyPair
}
}
const app = new Hono()
app.get('/authorize/:scopemode', async (c) => {
if (c.req.query('client_id') !== config.clientId
|| c.req.query('redirect_uri') !== config.redirectURL
|| !['guilds', 'email'].includes(c.req.param('scopemode'))) {
return c.text('Bad request.', 400)
}
const params = new URLSearchParams({
'client_id': config.clientId,
'redirect_uri': config.redirectURL,
'response_type': 'code',
'scope': c.req.param('scopemode') == 'guilds' ? 'identify email guilds' : 'identify email',
'state': c.req.query('state'),
'prompt': 'none'
}).toString()
return c.redirect('https://discord.com/oauth2/authorize?' + params)
})
app.post('/token', async (c) => {
const body = await c.req.parseBody()
const code = body['code']
const params = new URLSearchParams({
'client_id': config.clientId,
'client_secret': config.clientSecret,
'redirect_uri': config.redirectURL,
'code': code,
'grant_type': 'authorization_code',
'scope': 'identify email'
}).toString()
const r = await fetch('https://discord.com/api/v10/oauth2/token', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(res => res.json())
if (r === null) return new Response("Bad request.", { status: 400 })
const userInfo = await fetch('https://discord.com/api/v10/users/@me', {
headers: {
'Authorization': 'Bearer ' + r['access_token']
}
}).then(res => res.json())
if (!userInfo['verified']) return c.text('Bad request.', 400)
let servers = []
const serverResp = await fetch('https://discord.com/api/v10/users/@me/guilds', {
headers: {
'Authorization': 'Bearer ' + r['access_token']
}
})
if (serverResp.status === 200) {
const serverJson = await serverResp.json()
servers = serverJson.map(item => {
return item['id']
})
}
let roleClaims = {}
if (c.env.DISCORD_TOKEN && 'serversToCheckRolesFor' in config) {
await Promise.all(config.serversToCheckRolesFor.map(async guildId => {
if (servers.includes(guildId)) {
let memberPromise = fetch(`https://discord.com/api/v10/guilds/${guildId}/members/${userInfo['id']}`, {
headers: {
'Authorization': 'Bot ' + c.env.DISCORD_TOKEN
}
})
// i had issues doing this any other way?
const memberResp = await memberPromise
const memberJson = await memberResp.json()
roleClaims[`roles:${guildId}`] = memberJson.roles
}
}
))
}
let preferred_username = userInfo['username']
if (userInfo['discriminator'] && userInfo['discriminator'] !== '0'){
preferred_username += `#${userInfo['discriminator']}`
}
let displayName = userInfo['global_name'] ?? userInfo['username']
const idToken = await new jose.SignJWT({
iss: 'https://cloudflare.com',
aud: config.clientId,
preferred_username,
...userInfo,
...roleClaims,
email: userInfo['email'],
global_name: userInfo['global_name'],
name: displayName,
guilds: servers
})
.setProtectedHeader({ alg: 'RS256' })
.setExpirationTime('1h')
.setAudience(config.clientId)
.sign((await loadOrGenerateKeyPair(c.env.KV)).privateKey)
return c.json({
...r,
scope: 'identify email',
id_token: idToken
})
})
app.get('/jwks.json', async (c) => {
let publicKey = (await loadOrGenerateKeyPair(c.env.KV)).publicKey
return c.json({
keys: [{
alg: 'RS256',
kid: 'jwtRS256',
...(await crypto.subtle.exportKey('jwk', publicKey))
}]
})
})
export default app