Repository navigation
Expand file tree
/
Copy pathhttp-client.ts
More file actions
184 lines (180 loc) · 5.54 KB
/
Copy pathhttp-client.ts
File metadata and controls
184 lines (180 loc) · 5.54 KB
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
import {
providerCall,
InvalidTokenResponseError,
ProviderRequestTimeoutError,
} from "./errors";
import axios from "axios";
import * as oidc from "openid-client";
import type { UserInfo } from "@/shared/contracts";
import qs from "qs";
const DEFAULT_PROVIDER_TIMEOUT_MS = 15000;
function providerTimeoutMs() {
const value = process.env.PROVIDER_HTTP_TIMEOUT_MS || "";
const timeout = /^\d+$/.test(value) ? Number(value) : 0;
return timeout >= 1 && timeout <= 120000
? timeout
: DEFAULT_PROVIDER_TIMEOUT_MS;
}
async function providerPost<T>(
url: string,
data: unknown,
headers: Record<string, string>,
) {
const timeout = providerTimeoutMs();
try {
// Bound connection and response time. Authentication codes are never retried here.
return (
await axios.post<T>(url, data, {
headers,
timeout,
signal: AbortSignal.timeout(timeout),
})
).data;
} catch (error) {
if (
axios.isAxiosError(error) &&
["ECONNABORTED", "ETIMEDOUT", "ERR_CANCELED"].includes(error.code || "")
)
throw new ProviderRequestTimeoutError();
throw error;
}
}
export function postForm<T = Record<string, unknown>>(
url: string,
data: Record<string, unknown>,
) {
return providerPost<T>(url, qs.stringify(data), {
"Content-Type": "application/x-www-form-urlencoded",
});
}
export function postJson<T = unknown>(
url: string,
data: unknown,
headers: Record<string, string> = {},
) {
return providerPost<T>(url, data, {
"Content-Type": "application/json",
...headers,
});
}
export async function exchangeCodeAndGetUserInfo(
tokenUrl: string,
userUrl: string,
params: Record<string, unknown>,
browser?: { state: string; nonce: string; jwksUri: string },
): Promise<{
tokenInfo: Record<string, unknown> & { access_token: string };
userInfo: UserInfo;
}> {
const tokenEndpoint = new URL(tokenUrl);
const userInfoEndpoint = new URL(userUrl);
const config = new oidc.Configuration(
{
issuer: tokenEndpoint.href.includes("/protocol/openid-connect/")
? tokenEndpoint.href.split("/protocol/openid-connect/")[0]
: tokenEndpoint.origin,
token_endpoint: tokenEndpoint.href,
userinfo_endpoint: userInfoEndpoint.href,
...(browser ? { jwks_uri: browser.jwksUri } : {}),
},
String(params.client_id || ""),
String(params.client_secret || ""),
);
config.timeout = providerTimeoutMs() / 1000;
// HTTP is only enabled for the loopback fixture used by local tests.
if (
tokenEndpoint.protocol === "http:" &&
userInfoEndpoint.protocol === "http:" &&
["127.0.0.1", "localhost", "[::1]"].includes(tokenEndpoint.hostname) &&
tokenEndpoint.origin === userInfoEndpoint.origin
)
oidc.allowInsecureRequests(config);
if (browser) oidc.enableNonRepudiationChecks(config);
const grantParameters = new URLSearchParams();
for (const [name, value] of Object.entries(params)) {
if (
!["client_id", "client_secret", "grant_type"].includes(name) &&
value != null
)
grantParameters.set(name, String(value));
}
const tokenInfo = await providerCall("token", async () => {
try {
if (browser) {
const callback = new URL(String(params.redirect_uri));
callback.searchParams.set("code", String(params.code));
callback.searchParams.set("state", browser.state);
return await oidc.authorizationCodeGrant(config, callback, {
expectedState: browser.state,
expectedNonce: browser.nonce,
});
}
return await oidc.genericGrantRequest(
config,
String(params.grant_type || "authorization_code"),
grantParameters,
);
} catch (error) {
throw normalizeOidcError(error, true);
}
});
const userInfo = await providerCall("userinfo", async () => {
try {
// Browser authorization has a verified ID-token subject; generic mobile
// and Play Integrity exchanges do not yet have an attempt-bound subject.
return await oidc.fetchUserInfo(
config,
tokenInfo.access_token,
browser ? tokenInfo.claims()!.sub : oidc.skipSubjectCheck,
);
} catch (error) {
throw normalizeOidcError(error, false);
}
});
return { tokenInfo, userInfo };
}
function normalizeOidcError(error: unknown, token: boolean): unknown {
if (error && typeof error === "object") {
const details = error as {
code?: string;
status?: number;
message?: string;
cause?: unknown;
response?: Response;
};
if (details.code === "OAUTH_TIMEOUT")
return new ProviderRequestTimeoutError();
if (token && details.code === "OAUTH_INVALID_RESPONSE")
return new InvalidTokenResponseError();
const status =
details.status ||
details.response?.status ||
(details.cause instanceof Response ? details.cause.status : undefined);
if (status)
return {
message: `Request failed with status code ${status}`,
response: {
status,
data:
details.cause && !(details.cause instanceof Response)
? details.cause
: undefined,
},
};
}
return error;
}
export function validateTokenResponse(
value: unknown,
): Record<string, unknown> & { access_token: string } {
if (
!value ||
typeof value !== "object" ||
Array.isArray(value) ||
!("access_token" in value) ||
typeof value.access_token !== "string" ||
!value.access_token.trim()
)
throw new InvalidTokenResponseError();
return value as Record<string, unknown> & { access_token: string };
}