ReviewOS

also looking at this

stacks/stx

chore: wip stx improvements

#1649
Merged fingersandmind wants to merge feat/stx-improvements into main
241 files +19022 -1323
packages/auth/src/oauth.tsadded+75-0
Changes to packages/auth/src/oauth.ts
@@ -0,0 +1,75 @@
1import type { OAuthProviderConfig } from './types'
2
3interface OAuthUrls {
4 [provider: string]: {
5 authorize: string
6 token: string
7 userInfo: string
8 }
9}
10
11const providerUrls: OAuthUrls = {
12 github: {
13 authorize: 'https://github.com/login/oauth/authorize',
14 token: 'https://github.com/login/oauth/access_token',
15 userInfo: 'https://api.github.com/user',
16 },
17 google: {
18 authorize: 'https://accounts.google.com/o/oauth2/v2/auth',
19 token: 'https://oauth2.googleapis.com/token',
20 userInfo: 'https://www.googleapis.com/oauth2/v2/userinfo',
21 },
22}
23
24export function oauthRedirectUrl(provider: string, config: OAuthProviderConfig): string {
25 const urls = providerUrls[provider]
26 if (!urls)
27 throw new Error(`Unsupported OAuth provider: ${provider}`)
28
29 const params = new URLSearchParams({
30 client_id: config.clientId,
31 redirect_uri: config.redirectUri ?? '',
32 scope: (config.scopes ?? []).join(' '),
33 response_type: 'code',
34 })
35
36 return `${urls.authorize}?${params.toString()}`
37}
38
39export async function handleOAuthCallback(
40 provider: string,
41 code: string,
42 config: OAuthProviderConfig,
43): Promise<{ accessToken: string, user: Record<string, unknown> }> {
44 const urls = providerUrls[provider]
45 if (!urls)
46 throw new Error(`Unsupported OAuth provider: ${provider}`)
47
48 const tokenResponse = await fetch(urls.token, {
49 method: 'POST',
50 headers: {
51 'Content-Type': 'application/json',
52 'Accept': 'application/json',
53 },
54 body: JSON.stringify({
55 client_id: config.clientId,
56 client_secret: config.clientSecret,
57 code,
58 redirect_uri: config.redirectUri ?? '',
59 }),
60 })
61
62 const tokenData = await tokenResponse.json() as { access_token: string }
63 const accessToken = tokenData.access_token
64
65 const userResponse = await fetch(urls.userInfo, {
66 headers: {
67 Authorization: `Bearer ${accessToken}`,
68 Accept: 'application/json',
69 },
70 })
71
72 const user = await userResponse.json() as Record<string, unknown>
73
74 return { accessToken, user }
75}