-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmiddleware.ts
188 lines (159 loc) · 5.69 KB
/
middleware.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
import { createFactory } from 'hono/factory';
import {
extractAmount,
generateRandomString,
hexToBytes,
isBountyComment,
} from './utils';
import { addBountyToNotion } from './notion';
import {
generateOAuth2AuthLink,
loginWithOauth2,
refreshOAuth2Token,
tweet,
} from './twitter';
const encoder = new TextEncoder();
const factory = createFactory();
export const healthCheckHandler = factory.createHandlers(async (c) => {
console.log(c.env.GITHUB_WEBHOOK_SECRET);
const accessToken = await c.env.access_token.get('access_token');
const refreshToken = await c.env.refresh_token.get('refresh_token');
const state = await c.env.state.get('state');
const codeVerifier = await c.env.codeVerifier.get('codeVerifier');
console.log({ accessToken, refreshToken, state, codeVerifier });
return c.text('Hello Hono!');
});
// Check if the request is coming from GitHub webhook
export const checkGhSignature = factory.createMiddleware(async (c, next) => {
try {
const ghWebhookSecret = c.env.GITHUB_WEBHOOK_SECRET;
const sigHex = c.req.header()['x-hub-signature-256'].split('=')[1];
const algorithm = { name: 'HMAC', hash: { name: 'SHA-256' } };
const keyBytes = encoder.encode(ghWebhookSecret);
const extractable = false;
const key = await crypto.subtle.importKey(
'raw',
keyBytes,
algorithm,
extractable,
['sign', 'verify']
);
const sigBytes = hexToBytes(sigHex);
const dataBytes = encoder.encode(JSON.stringify(await c.req.json()));
const equal = await crypto.subtle.verify(
algorithm.name,
key,
sigBytes,
dataBytes
);
if (!equal) c.set('error', 'unauthorized');
return await next();
} catch (e) {
console.log(e);
c.set('error', 'unauthorized');
return await next();
}
});
export const webhookHandler = factory.createHandlers(
checkGhSignature,
async (c) => {
try {
const adminUsernames: string[] = c.env.ADMIN_USERNAMES.split(',');
const notionDatabaseId = c.env.NOTION_DATABASE_ID;
const notionApiKey = c.env.NOTION_API_KEY;
if (c.var.error) return c.status(401);
const body = await c.req.json();
const username = body.sender.login;
const message = body.comment.body;
const author = body.issue.user.login;
const pr_link = body.issue.html_url;
const createdAt = body.comment.created_at.split("T")[0]
if (
!isBountyComment(message) ||
!adminUsernames.find((adminUsername) => adminUsername === username)
) {
c.status(200);
return c.json({ message: 'Not a bounty comment' });
}
const bountyAmount = extractAmount(message);
if (!bountyAmount) return c.status(200);
await addBountyToNotion({
username: author,
amount: bountyAmount,
pr: pr_link,
date: createdAt,
notion: {
apiKey: notionApiKey,
databaseId: notionDatabaseId,
},
});
const refreshToken = await c.env.refresh_token.get('refresh_token');
const tweetPayload = `Contrulations to the user ${author} for winning a bounty of ${bountyAmount}! 🎉🎉🎉 #bounty #winner`;
const { accessToken: newAccessToken, refreshToken: newRefreshToken } =
await refreshOAuth2Token({
refreshToken: refreshToken,
clientId: c.env.TWITTER_CLIENT_API_KEY,
});
await c.env.access_token.put('access_token', newAccessToken);
await c.env.refresh_token.put('refresh_token', newRefreshToken);
// Tweeting
const response = await tweet({
tweet: tweetPayload,
accessToken: newAccessToken,
});
if (!response.data) {
return c.json({ message: 'Error in tweeting but saved in notion.' });
}
return c.json({ message: 'Webhook received' });
} catch (e) {
console.log(e);
c.status(200);
return c.json({ message: 'Unauthorized' });
}
}
);
/**
* Creating a oauth2 url and redirecting the user to the Twitter for authentication
*/
export const settingUpTwitter = factory.createHandlers(async (c) => {
const state = generateRandomString(32);
const codeVerifier = 'codeVerifier';
const { url } = await generateOAuth2AuthLink({
callbackUrl: c.env.TWITTER_CALLBACK_URL,
state: state,
codeChallenge: codeVerifier,
code_challenge_method: 'plain',
scope: ['tweet.read', 'tweet.write', 'users.read', 'offline.access'],
clientId: c.env.TWITTER_CLIENT_API_KEY,
});
await c.env.codeVerifier.put('codeVerifier', codeVerifier);
await c.env.state.put('state', state);
return c.redirect(url);
});
/**
* Handling the callback from the Twitter after the user has authenticated
* @param code The code returned from the OAuth2 authorization.
* @param state The state returned from the OAuth2 authorization.
*/
export const twitterOauth2CallbackHandler = factory.createHandlers(
async (c) => {
const { code, state } = c.req.query();
const storedState = await c.env.state.get('state');
// if the state is not the same as the stored state then return unauthorized
if (state !== storedState) {
return c.status(401);
}
const storedCodeVerifier = await c.env.codeVerifier.get('codeVerifier');
const { accessToken, refreshToken } = await loginWithOauth2({
code: code,
codeVerifier: storedCodeVerifier,
redirectUri: c.env.TWITTER_CALLBACK_URL,
clientId: c.env.TWITTER_CLIENT_API_KEY,
clientSecret: c.env.TWITTER_CLIENT_SECRET,
});
if (!accessToken || !refreshToken) return c.status(401);
await c.env.access_token.put('access_token', accessToken);
await c.env.refresh_token.put('refresh_token', refreshToken);
return c.json({ message: 'Twitter Setup is complete.' });
}
);