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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
|
import type { SsoConfig } from "../db/schema";
export type FetchImpl = typeof fetch;
export function buildGoogleAuthorizeUrl(
cfg: Pick<SsoConfig, "authorizationEndpoint" | "clientId" | "scopes">,
state: string,
redirectUri: string,
nonce: string
): string {
if (!cfg.authorizationEndpoint || !cfg.clientId) {
throw new Error(
"Google OAuth config missing authorization_endpoint or client_id"
);
}
const u = new URL(cfg.authorizationEndpoint);
u.searchParams.set("client_id", cfg.clientId);
u.searchParams.set("redirect_uri", redirectUri);
u.searchParams.set("response_type", "code");
u.searchParams.set("scope", cfg.scopes || "openid email profile");
u.searchParams.set("state", state);
u.searchParams.set("nonce", nonce);
u.searchParams.set("access_type", "online");
u.searchParams.set("prompt", "select_account");
return u.toString();
}
export async function exchangeGoogleCode(
cfg: Pick<SsoConfig, "tokenEndpoint" | "clientId" | "clientSecret">,
code: string,
redirectUri: string,
fetchImpl: FetchImpl = fetch
): Promise<{ accessToken: string; idToken: string | null }> {
if (!cfg.tokenEndpoint || !cfg.clientId || !cfg.clientSecret) {
throw new Error(
"Google OAuth config missing token_endpoint or client credentials"
);
}
const body = new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
client_id: cfg.clientId,
client_secret: cfg.clientSecret,
});
const res = await fetchImpl(cfg.tokenEndpoint, {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
accept: "application/json",
},
body: body.toString(),
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(
`google token endpoint ${res.status}: ${text.slice(0, 200) || "no body"}`
);
}
const json = (await res.json()) as {
access_token?: string;
id_token?: string;
error?: string;
error_description?: string;
};
if (json.error) {
throw new Error(
`google token endpoint: ${json.error}${json.error_description ? ` — ${json.error_description}` : ""}`
);
}
if (!json.access_token) {
throw new Error("google token endpoint response missing access_token");
}
return {
accessToken: json.access_token,
idToken: typeof json.id_token === "string" ? json.id_token : null,
};
}
export interface GoogleUserinfo {
sub: string;
email: string | null;
emailVerified: boolean;
name: string | null;
picture: string | null;
}
export async function fetchGoogleUserinfo(
cfg: Pick<SsoConfig, "userinfoEndpoint">,
accessToken: string,
fetchImpl: FetchImpl = fetch
): Promise<GoogleUserinfo> {
if (!cfg.userinfoEndpoint) {
throw new Error("Google OAuth config missing userinfo_endpoint");
}
const res = await fetchImpl(cfg.userinfoEndpoint, {
headers: {
authorization: `Bearer ${accessToken}`,
accept: "application/json",
},
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(
`google /userinfo ${res.status}: ${text.slice(0, 200) || "no body"}`
);
}
const raw = (await res.json()) as {
sub?: string;
email?: string | null;
email_verified?: boolean | string;
name?: string | null;
picture?: string | null;
};
if (typeof raw.sub !== "string" || !raw.sub) {
throw new Error("google /userinfo response missing sub");
}
return {
sub: raw.sub,
email: raw.email ?? null,
emailVerified:
raw.email_verified === true || raw.email_verified === "true",
name: raw.name ?? null,
picture: raw.picture ?? null,
};
}
export function resolveGoogleRedirectUri(opts: {
configuredBaseUrl?: string | null;
forwardedProto?: string | null;
forwardedHost?: string | null;
host?: string | null;
requestUrl?: string | null;
}): string {
const PATH = "/login/google/callback";
const firstValue = (v: string | null | undefined): string =>
(v || "").split(",")[0].trim();
const configured = (opts.configuredBaseUrl || "").trim().replace(/\/+$/, "");
if (
configured.startsWith("https://") &&
!configured.includes("localhost") &&
!configured.includes("127.0.0.1")
) {
return `${configured}${PATH}`;
}
let host = firstValue(opts.forwardedHost) || firstValue(opts.host);
let urlProto = "";
if (opts.requestUrl) {
try {
const u = new URL(opts.requestUrl);
if (!host) host = u.host;
urlProto = u.protocol.replace(":", "");
} catch {
}
}
if (!host) {
const base = configured || "http://localhost:3000";
return `${base.replace(/\/+$/, "")}${PATH}`;
}
const isLocal =
host.startsWith("localhost") || host.startsWith("127.0.0.1");
let proto = firstValue(opts.forwardedProto);
if (!proto) proto = isLocal ? urlProto || "http" : "https";
return `${proto}://${host}${PATH}`;
}
|