-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
87 lines (80 loc) · 2.3 KB
/
utils.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
import { IncomingHttpHeaders } from 'node:http'
import crypto, { BinaryLike, timingSafeEqual } from 'node:crypto'
import { DiscordEmbed } from '@book000/node-utils'
import { EmbedColors } from './embed-colors'
import { User, Team } from '@octokit/webhooks-types'
import { GitHubUserMapManager } from './manager/github-user'
export type SomeRequired<T, K extends keyof T> = Omit<T, K> &
Required<Pick<T, K>>
export function isSignatureValid(
secret: string,
headers: IncomingHttpHeaders,
payload: BinaryLike
): boolean {
const signature = headers['x-hub-signature-256']
if (!signature) {
return false
}
if (typeof signature !== 'string') {
return false
}
const [algorithm, signatureHash] = signature.split('=')
if (!algorithm || !signatureHash) {
return false
}
const hmac = crypto.createHmac(algorithm, secret)
hmac.update(payload)
const digest = hmac.digest('hex')
return timingSafeEqual(
Buffer.from(digest, 'ascii'),
Buffer.from(signatureHash, 'ascii')
)
}
export function createEmbed(
eventName: string,
embedColor: (typeof EmbedColors)[keyof typeof EmbedColors],
extraEmbed: SomeRequired<
Omit<DiscordEmbed, 'footer' | 'timestamp' | 'color'>,
'title'
>
): DiscordEmbed {
return {
footer: {
text: `Powered by book000/github-webhook-bridge (${eventName} event)`,
icon_url: 'https://i.imgur.com/PdvExHP.png',
},
timestamp: new Date().toISOString(),
color: embedColor,
...extraEmbed,
}
}
/**
* GitHubのユーザーからDiscordのユーザーに変換し、メンション一覧を作成する
*
* @param sender アクションを送信したユーザー
* @param userOrTeams User と Team の配列
* @returns Discordのメンション一覧
*/
export async function getUsersMentions(
sender: User,
userOrTeams: (User | Team)[]
): Promise<string> {
const githubUserMap = new GitHubUserMapManager()
await githubUserMap.load()
return userOrTeams
.map((reviewer) => {
if (!('login' in reviewer)) {
return null
}
if (reviewer.login === sender.login) {
return null
}
const discordUserId = githubUserMap.get(reviewer.id)
if (!discordUserId) {
return null
}
return `<@${discordUserId}>`
})
.filter((mention) => mention !== null)
.join(' ')
}