@absolutejs/auth 0.69.0 → 0.69.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/client/createAuthClient.d.ts +1 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +412 -380
- package/dist/client/index.js.map +6 -5
- package/dist/client/mobile.d.ts +1 -0
- package/dist/client/mobile.js +601 -0
- package/dist/client/mobile.js.map +11 -0
- package/dist/client/runtimeTransport.d.ts +3 -0
- package/package.json +10 -2
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
function __accessProp(key) {
|
|
8
|
+
return this[key];
|
|
9
|
+
}
|
|
10
|
+
var __toESMCache_node;
|
|
11
|
+
var __toESMCache_esm;
|
|
12
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
13
|
+
var canCache = mod != null && typeof mod === "object";
|
|
14
|
+
if (canCache) {
|
|
15
|
+
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
16
|
+
var cached = cache.get(mod);
|
|
17
|
+
if (cached)
|
|
18
|
+
return cached;
|
|
19
|
+
}
|
|
20
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
21
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
22
|
+
for (let key of __getOwnPropNames(mod))
|
|
23
|
+
if (!__hasOwnProp.call(to, key))
|
|
24
|
+
__defProp(to, key, {
|
|
25
|
+
get: __accessProp.bind(mod, key),
|
|
26
|
+
enumerable: true
|
|
27
|
+
});
|
|
28
|
+
if (canCache)
|
|
29
|
+
cache.set(mod, to);
|
|
30
|
+
return to;
|
|
31
|
+
};
|
|
32
|
+
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
33
|
+
var __returnValue = (v) => v;
|
|
34
|
+
function __exportSetter(name, newValue) {
|
|
35
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
36
|
+
}
|
|
37
|
+
var __export = (target, all) => {
|
|
38
|
+
for (var name in all)
|
|
39
|
+
__defProp(target, name, {
|
|
40
|
+
get: all[name],
|
|
41
|
+
enumerable: true,
|
|
42
|
+
configurable: true,
|
|
43
|
+
set: __exportSetter.bind(all, name)
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
47
|
+
var __require = import.meta.require;
|
|
48
|
+
|
|
49
|
+
// src/client/runtimeTransport.ts
|
|
50
|
+
var AUTH_TRANSPORT_REGISTRY = Symbol.for("@absolutejs/auth/client-runtime-transport");
|
|
51
|
+
var host = globalThis;
|
|
52
|
+
var isRegistry = (value) => typeof value === "object" && value !== null && Array.isArray(Reflect.get(value, "installations"));
|
|
53
|
+
var registry = (() => {
|
|
54
|
+
const existing = host[AUTH_TRANSPORT_REGISTRY];
|
|
55
|
+
if (isRegistry(existing))
|
|
56
|
+
return existing;
|
|
57
|
+
const created = { installations: [] };
|
|
58
|
+
Object.defineProperty(host, AUTH_TRANSPORT_REGISTRY, {
|
|
59
|
+
configurable: false,
|
|
60
|
+
enumerable: false,
|
|
61
|
+
value: created,
|
|
62
|
+
writable: false
|
|
63
|
+
});
|
|
64
|
+
return created;
|
|
65
|
+
})();
|
|
66
|
+
var getAuthClientRuntimeTransport = () => registry.installations.at(-1)?.transport;
|
|
67
|
+
var installAuthClientRuntimeTransport = (transport) => {
|
|
68
|
+
const installation = { transport };
|
|
69
|
+
registry.installations.push(installation);
|
|
70
|
+
return () => {
|
|
71
|
+
const index = registry.installations.indexOf(installation);
|
|
72
|
+
if (index >= 0)
|
|
73
|
+
registry.installations.splice(index, 1);
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// src/client/mobile.ts
|
|
78
|
+
class MobileAuthError extends Error {
|
|
79
|
+
code;
|
|
80
|
+
cause;
|
|
81
|
+
constructor(code, message, options) {
|
|
82
|
+
super(message);
|
|
83
|
+
this.name = "MobileAuthError";
|
|
84
|
+
this.code = code;
|
|
85
|
+
this.cause = options?.cause;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
var PENDING_KEY = "oidc.pending";
|
|
89
|
+
var REFRESH_KEY = "oidc.refresh";
|
|
90
|
+
var DEFAULT_CLOCK_SKEW_MS = 30000;
|
|
91
|
+
var PENDING_TTL_MS = 10 * 60000;
|
|
92
|
+
var RANDOM_BYTES = 32;
|
|
93
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
94
|
+
var base64Url = (value) => {
|
|
95
|
+
let binary = "";
|
|
96
|
+
for (const byte of value)
|
|
97
|
+
binary += String.fromCharCode(byte);
|
|
98
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
99
|
+
};
|
|
100
|
+
var decodeBase64Url = (value) => {
|
|
101
|
+
const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
102
|
+
const padded = normalized.padEnd(normalized.length + (4 - normalized.length % 4) % 4, "=");
|
|
103
|
+
const binary = atob(padded);
|
|
104
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
105
|
+
};
|
|
106
|
+
var randomValue = () => {
|
|
107
|
+
const value = new Uint8Array(RANDOM_BYTES);
|
|
108
|
+
crypto.getRandomValues(value);
|
|
109
|
+
return base64Url(value);
|
|
110
|
+
};
|
|
111
|
+
var pkceChallenge = async (verifier) => base64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
|
|
112
|
+
var normalizeIssuer = (value) => {
|
|
113
|
+
const issuer = new URL(value);
|
|
114
|
+
const loopback = issuer.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(issuer.hostname);
|
|
115
|
+
if (issuer.protocol !== "https:" && !loopback)
|
|
116
|
+
throw new TypeError("Mobile auth issuer must use HTTPS.");
|
|
117
|
+
if (issuer.username || issuer.password || issuer.search || issuer.hash)
|
|
118
|
+
throw new TypeError("Mobile auth issuer cannot contain credentials, query, or fragment.");
|
|
119
|
+
issuer.pathname = issuer.pathname.replace(/\/$/u, "");
|
|
120
|
+
return issuer.href.replace(/\/$/u, "");
|
|
121
|
+
};
|
|
122
|
+
var exactRedirect = (actualValue, expectedValue) => {
|
|
123
|
+
const actual = new URL(actualValue);
|
|
124
|
+
const expected = new URL(expectedValue);
|
|
125
|
+
return actual.protocol === expected.protocol && actual.host === expected.host && actual.pathname === expected.pathname && actual.username === "" && actual.password === "";
|
|
126
|
+
};
|
|
127
|
+
var parsePending = (value) => {
|
|
128
|
+
if (value === null)
|
|
129
|
+
return;
|
|
130
|
+
try {
|
|
131
|
+
const parsed = JSON.parse(value);
|
|
132
|
+
if (!isRecord(parsed) || typeof parsed.createdAt !== "number" || typeof parsed.nonce !== "string" || typeof parsed.state !== "string" || typeof parsed.verifier !== "string")
|
|
133
|
+
return;
|
|
134
|
+
return {
|
|
135
|
+
createdAt: parsed.createdAt,
|
|
136
|
+
nonce: parsed.nonce,
|
|
137
|
+
state: parsed.state,
|
|
138
|
+
verifier: parsed.verifier
|
|
139
|
+
};
|
|
140
|
+
} catch {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
var parseTokenResponse = (value) => {
|
|
145
|
+
if (!isRecord(value) || typeof value.access_token !== "string" || typeof value.expires_in !== "number" || !Number.isFinite(value.expires_in) || value.expires_in <= 0 || typeof value.id_token !== "string" || typeof value.refresh_token !== "string" || typeof value.token_type !== "string")
|
|
146
|
+
throw new MobileAuthError("token", "The token response is malformed.");
|
|
147
|
+
if (value.token_type.toLowerCase() !== "bearer")
|
|
148
|
+
throw new MobileAuthError("token", `Unsupported mobile token type ${value.token_type}; DPoP is not enabled for this client.`);
|
|
149
|
+
return {
|
|
150
|
+
access_token: value.access_token,
|
|
151
|
+
expires_in: value.expires_in,
|
|
152
|
+
id_token: value.id_token,
|
|
153
|
+
refresh_token: value.refresh_token,
|
|
154
|
+
scope: typeof value.scope === "string" ? value.scope : undefined,
|
|
155
|
+
token_type: value.token_type
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
var responseBody = async (response) => {
|
|
159
|
+
const text = await response.text();
|
|
160
|
+
try {
|
|
161
|
+
return JSON.parse(text);
|
|
162
|
+
} catch {
|
|
163
|
+
return text;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
var requireEndpoint = (value, name, issuer) => {
|
|
167
|
+
if (typeof value !== "string")
|
|
168
|
+
throw new MobileAuthError("discovery", `OIDC discovery is missing ${name}.`);
|
|
169
|
+
const endpoint = new URL(value);
|
|
170
|
+
if (endpoint.protocol !== "https:" && new URL(issuer).protocol === "https:")
|
|
171
|
+
throw new MobileAuthError("discovery", `OIDC discovery ${name} must use HTTPS.`);
|
|
172
|
+
return endpoint.href;
|
|
173
|
+
};
|
|
174
|
+
var parseDiscovery = (value, issuer) => {
|
|
175
|
+
if (!isRecord(value) || value.issuer !== issuer)
|
|
176
|
+
throw new MobileAuthError("discovery", "OIDC discovery issuer does not match the configured issuer.");
|
|
177
|
+
const methods = Array.isArray(value.code_challenge_methods_supported) ? value.code_challenge_methods_supported.filter((method) => typeof method === "string") : undefined;
|
|
178
|
+
if (!methods?.includes("S256"))
|
|
179
|
+
throw new MobileAuthError("discovery", "OIDC provider does not advertise S256 PKCE.");
|
|
180
|
+
const authMethods = Array.isArray(value.token_endpoint_auth_methods_supported) ? value.token_endpoint_auth_methods_supported.filter((method) => typeof method === "string") : undefined;
|
|
181
|
+
if (!authMethods?.includes("none"))
|
|
182
|
+
throw new MobileAuthError("discovery", "OIDC provider does not accept public clients at the token endpoint.");
|
|
183
|
+
return {
|
|
184
|
+
authorization_endpoint: requireEndpoint(value.authorization_endpoint, "authorization_endpoint", issuer),
|
|
185
|
+
code_challenge_methods_supported: methods,
|
|
186
|
+
issuer,
|
|
187
|
+
jwks_uri: requireEndpoint(value.jwks_uri, "jwks_uri", issuer),
|
|
188
|
+
revocation_endpoint: typeof value.revocation_endpoint === "string" ? requireEndpoint(value.revocation_endpoint, "revocation_endpoint", issuer) : undefined,
|
|
189
|
+
socket_ticket_endpoint: typeof value.socket_ticket_endpoint === "string" ? requireEndpoint(value.socket_ticket_endpoint, "socket_ticket_endpoint", issuer) : undefined,
|
|
190
|
+
token_endpoint: requireEndpoint(value.token_endpoint, "token_endpoint", issuer),
|
|
191
|
+
token_endpoint_auth_methods_supported: authMethods,
|
|
192
|
+
userinfo_endpoint: requireEndpoint(value.userinfo_endpoint, "userinfo_endpoint", issuer)
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
var verifyIdToken = async ({
|
|
196
|
+
clientId,
|
|
197
|
+
fetchImpl,
|
|
198
|
+
idToken,
|
|
199
|
+
issuer,
|
|
200
|
+
jwksUri,
|
|
201
|
+
nonce,
|
|
202
|
+
now
|
|
203
|
+
}) => {
|
|
204
|
+
const [encodedHeader, encodedPayload, encodedSignature, ...extra] = idToken.split(".");
|
|
205
|
+
if (!encodedHeader || !encodedPayload || !encodedSignature || extra.length)
|
|
206
|
+
throw new MobileAuthError("id-token", "The ID token is malformed.");
|
|
207
|
+
let header;
|
|
208
|
+
let payload;
|
|
209
|
+
try {
|
|
210
|
+
header = JSON.parse(new TextDecoder().decode(decodeBase64Url(encodedHeader)));
|
|
211
|
+
payload = JSON.parse(new TextDecoder().decode(decodeBase64Url(encodedPayload)));
|
|
212
|
+
} catch (cause) {
|
|
213
|
+
throw new MobileAuthError("id-token", "The ID token is malformed.", {
|
|
214
|
+
cause
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
if (!isRecord(header) || header.alg !== "ES256" || typeof header.kid !== "string" || !isRecord(payload))
|
|
218
|
+
throw new MobileAuthError("id-token", "The ID token header or claims are invalid.");
|
|
219
|
+
const response = await fetchImpl(jwksUri, { cache: "no-store" });
|
|
220
|
+
if (!response.ok)
|
|
221
|
+
throw new MobileAuthError("network", "Unable to fetch OIDC signing keys.");
|
|
222
|
+
const body = await response.json();
|
|
223
|
+
const keys = isRecord(body) && Array.isArray(body.keys) ? body.keys : [];
|
|
224
|
+
const jwk = keys.find((candidate) => isRecord(candidate) && candidate.kid === header.kid);
|
|
225
|
+
if (!jwk)
|
|
226
|
+
throw new MobileAuthError("id-token", "The ID token signing key is unknown.");
|
|
227
|
+
const key = await crypto.subtle.importKey("jwk", jwk, { hash: "SHA-256", name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
|
|
228
|
+
const valid = await crypto.subtle.verify({ hash: "SHA-256", name: "ECDSA" }, key, decodeBase64Url(encodedSignature), new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`));
|
|
229
|
+
const audience = payload.aud;
|
|
230
|
+
if (!valid || payload.iss !== issuer || !(audience === clientId || Array.isArray(audience) && audience.includes(clientId)) || payload.nonce !== nonce || typeof payload.exp !== "number" || payload.exp * 1000 <= now)
|
|
231
|
+
throw new MobileAuthError("id-token", "The ID token signature or claims are invalid.");
|
|
232
|
+
};
|
|
233
|
+
var createMobileAuthClient = (config) => {
|
|
234
|
+
const issuer = normalizeIssuer(config.issuer);
|
|
235
|
+
const redirectUri = new URL(config.redirectUri).href;
|
|
236
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
237
|
+
const now = config.now ?? Date.now;
|
|
238
|
+
const clockSkewMs = config.clockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
|
|
239
|
+
const scopes = [...new Set(config.scopes ?? ["openid", "profile"])];
|
|
240
|
+
const resource = config.resource ?? issuer;
|
|
241
|
+
if (!scopes.includes("openid"))
|
|
242
|
+
scopes.unshift("openid");
|
|
243
|
+
const allowedOrigins = new Set((config.allowedOrigins ?? [new URL(issuer).origin]).map((value) => new URL(value).origin));
|
|
244
|
+
let discoveryPromise;
|
|
245
|
+
let access;
|
|
246
|
+
let refreshPromise;
|
|
247
|
+
let stopLinks;
|
|
248
|
+
let stopResume;
|
|
249
|
+
let startPromise;
|
|
250
|
+
const pendingSignIns = new Map;
|
|
251
|
+
const fetchDiscovery = async () => {
|
|
252
|
+
const url = new URL("/.well-known/openid-configuration", `${issuer}/`);
|
|
253
|
+
const response = await fetchImpl(url, {
|
|
254
|
+
cache: "no-store",
|
|
255
|
+
headers: { accept: "application/json" }
|
|
256
|
+
});
|
|
257
|
+
if (!response.ok)
|
|
258
|
+
throw new MobileAuthError("discovery", `OIDC discovery failed with HTTP ${response.status}.`);
|
|
259
|
+
return parseDiscovery(await response.json(), issuer);
|
|
260
|
+
};
|
|
261
|
+
const discovery = () => {
|
|
262
|
+
discoveryPromise ??= fetchDiscovery();
|
|
263
|
+
return discoveryPromise;
|
|
264
|
+
};
|
|
265
|
+
const assertSecureStorage = async () => {
|
|
266
|
+
const capability = await config.storage.capability?.();
|
|
267
|
+
if (capability && !capability.available)
|
|
268
|
+
throw new MobileAuthError("secure-storage", capability.message ?? "Native secure credential storage is unavailable.");
|
|
269
|
+
};
|
|
270
|
+
const tokenRequest = async (metadata, body, nonce) => {
|
|
271
|
+
let response;
|
|
272
|
+
try {
|
|
273
|
+
response = await fetchImpl(metadata.token_endpoint, {
|
|
274
|
+
body,
|
|
275
|
+
credentials: "omit",
|
|
276
|
+
headers: {
|
|
277
|
+
accept: "application/json",
|
|
278
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
279
|
+
},
|
|
280
|
+
method: "POST"
|
|
281
|
+
});
|
|
282
|
+
} catch (cause) {
|
|
283
|
+
throw new MobileAuthError("network", "The token request failed.", {
|
|
284
|
+
cause
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
const value = await responseBody(response);
|
|
288
|
+
if (!response.ok) {
|
|
289
|
+
const oauthCode = isRecord(value) && typeof value.error === "string" ? value.error : `HTTP ${response.status}`;
|
|
290
|
+
throw new MobileAuthError("oauth", `The authorization server rejected the token request (${oauthCode}).`);
|
|
291
|
+
}
|
|
292
|
+
const tokens = parseTokenResponse(value);
|
|
293
|
+
if (nonce)
|
|
294
|
+
await verifyIdToken({
|
|
295
|
+
clientId: config.clientId,
|
|
296
|
+
fetchImpl,
|
|
297
|
+
idToken: tokens.id_token,
|
|
298
|
+
issuer,
|
|
299
|
+
jwksUri: metadata.jwks_uri,
|
|
300
|
+
nonce,
|
|
301
|
+
now: now()
|
|
302
|
+
});
|
|
303
|
+
return tokens;
|
|
304
|
+
};
|
|
305
|
+
const acceptTokens = async (tokens) => {
|
|
306
|
+
try {
|
|
307
|
+
await config.storage.set(REFRESH_KEY, tokens.refresh_token);
|
|
308
|
+
} catch (cause) {
|
|
309
|
+
access = undefined;
|
|
310
|
+
await config.storage.remove(REFRESH_KEY).catch(() => {
|
|
311
|
+
return;
|
|
312
|
+
});
|
|
313
|
+
throw new MobileAuthError("secure-storage", "The rotated refresh credential could not be saved securely.", { cause });
|
|
314
|
+
}
|
|
315
|
+
access = {
|
|
316
|
+
accessToken: tokens.access_token,
|
|
317
|
+
expiresAt: now() + tokens.expires_in * 1000,
|
|
318
|
+
idToken: tokens.id_token,
|
|
319
|
+
scope: tokens.scope?.split(" ").filter(Boolean) ?? scopes,
|
|
320
|
+
tokenType: "Bearer"
|
|
321
|
+
};
|
|
322
|
+
return { ...access, refreshToken: tokens.refresh_token };
|
|
323
|
+
};
|
|
324
|
+
const rotateAccessToken = async () => {
|
|
325
|
+
await assertSecureStorage();
|
|
326
|
+
const refreshToken = await config.storage.get(REFRESH_KEY);
|
|
327
|
+
if (!refreshToken)
|
|
328
|
+
throw new MobileAuthError("token", "This app has no renewable mobile session.");
|
|
329
|
+
const metadata = await discovery();
|
|
330
|
+
const body = new URLSearchParams({
|
|
331
|
+
client_id: config.clientId,
|
|
332
|
+
grant_type: "refresh_token",
|
|
333
|
+
refresh_token: refreshToken
|
|
334
|
+
});
|
|
335
|
+
body.set("resource", resource);
|
|
336
|
+
const tokens = await tokenRequest(metadata, body);
|
|
337
|
+
return (await acceptTokens(tokens)).accessToken;
|
|
338
|
+
};
|
|
339
|
+
const refreshAccessToken = async () => {
|
|
340
|
+
if (access && access.expiresAt - clockSkewMs > now())
|
|
341
|
+
return access.accessToken;
|
|
342
|
+
if (refreshPromise)
|
|
343
|
+
return refreshPromise;
|
|
344
|
+
refreshPromise = rotateAccessToken().finally(() => {
|
|
345
|
+
refreshPromise = undefined;
|
|
346
|
+
});
|
|
347
|
+
return refreshPromise;
|
|
348
|
+
};
|
|
349
|
+
const handleCallback = async (value) => {
|
|
350
|
+
if (!exactRedirect(value, redirectUri))
|
|
351
|
+
throw new MobileAuthError("callback", "The authorization callback does not match this app registration.");
|
|
352
|
+
const url = new URL(value);
|
|
353
|
+
const pending = parsePending(await config.storage.get(PENDING_KEY));
|
|
354
|
+
if (!pending || now() - pending.createdAt > PENDING_TTL_MS) {
|
|
355
|
+
await config.storage.remove(PENDING_KEY).catch(() => {
|
|
356
|
+
return;
|
|
357
|
+
});
|
|
358
|
+
throw new MobileAuthError("callback", "The authorization transaction is missing or expired.");
|
|
359
|
+
}
|
|
360
|
+
const deferred = pendingSignIns.get(pending.state);
|
|
361
|
+
const reject = (error) => {
|
|
362
|
+
pendingSignIns.delete(pending.state);
|
|
363
|
+
config.storage.remove(PENDING_KEY);
|
|
364
|
+
deferred?.reject(error);
|
|
365
|
+
throw error;
|
|
366
|
+
};
|
|
367
|
+
if (url.searchParams.get("state") !== pending.state)
|
|
368
|
+
return reject(new MobileAuthError("callback", "The authorization callback state does not match."));
|
|
369
|
+
if (url.searchParams.get("iss") !== issuer)
|
|
370
|
+
return reject(new MobileAuthError("callback", "The authorization callback issuer does not match."));
|
|
371
|
+
const oauthError = url.searchParams.get("error");
|
|
372
|
+
if (oauthError) {
|
|
373
|
+
await config.storage.remove(PENDING_KEY);
|
|
374
|
+
return reject(new MobileAuthError("oauth", `Authorization failed (${oauthError}).`));
|
|
375
|
+
}
|
|
376
|
+
const code = url.searchParams.get("code");
|
|
377
|
+
if (!code)
|
|
378
|
+
return reject(new MobileAuthError("callback", "The authorization callback contains no code."));
|
|
379
|
+
await config.storage.remove(PENDING_KEY);
|
|
380
|
+
try {
|
|
381
|
+
const metadata = await discovery();
|
|
382
|
+
const body = new URLSearchParams({
|
|
383
|
+
client_id: config.clientId,
|
|
384
|
+
code,
|
|
385
|
+
code_verifier: pending.verifier,
|
|
386
|
+
grant_type: "authorization_code",
|
|
387
|
+
redirect_uri: redirectUri
|
|
388
|
+
});
|
|
389
|
+
body.set("resource", resource);
|
|
390
|
+
const tokens = await acceptTokens(await tokenRequest(metadata, body, pending.nonce));
|
|
391
|
+
pendingSignIns.delete(pending.state);
|
|
392
|
+
deferred?.resolve(tokens);
|
|
393
|
+
return tokens;
|
|
394
|
+
} catch (error) {
|
|
395
|
+
return reject(error);
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
const initialize = async () => {
|
|
399
|
+
await assertSecureStorage();
|
|
400
|
+
stopLinks = await config.links.onOpen((url) => {
|
|
401
|
+
if (exactRedirect(url, redirectUri))
|
|
402
|
+
handleCallback(url).catch(() => {
|
|
403
|
+
return;
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
if (config.lifecycle?.onResume)
|
|
407
|
+
stopResume = await config.lifecycle.onResume(() => {
|
|
408
|
+
refreshAccessToken().catch(() => {
|
|
409
|
+
return;
|
|
410
|
+
});
|
|
411
|
+
});
|
|
412
|
+
const launchUrl = await config.links.getLaunchUrl();
|
|
413
|
+
if (launchUrl && exactRedirect(launchUrl, redirectUri))
|
|
414
|
+
await handleCallback(launchUrl);
|
|
415
|
+
};
|
|
416
|
+
const start = () => {
|
|
417
|
+
startPromise ??= initialize();
|
|
418
|
+
return startPromise;
|
|
419
|
+
};
|
|
420
|
+
const signIn = async (options = {}) => {
|
|
421
|
+
await start();
|
|
422
|
+
if (options.signal?.aborted)
|
|
423
|
+
throw new MobileAuthError("aborted", "Authorization was cancelled.");
|
|
424
|
+
const metadata = await discovery();
|
|
425
|
+
const pending = {
|
|
426
|
+
createdAt: now(),
|
|
427
|
+
nonce: randomValue(),
|
|
428
|
+
state: randomValue(),
|
|
429
|
+
verifier: randomValue()
|
|
430
|
+
};
|
|
431
|
+
await config.storage.set(PENDING_KEY, JSON.stringify(pending));
|
|
432
|
+
const url = new URL(metadata.authorization_endpoint);
|
|
433
|
+
url.search = new URLSearchParams({
|
|
434
|
+
client_id: config.clientId,
|
|
435
|
+
code_challenge: await pkceChallenge(pending.verifier),
|
|
436
|
+
code_challenge_method: "S256",
|
|
437
|
+
nonce: pending.nonce,
|
|
438
|
+
redirect_uri: redirectUri,
|
|
439
|
+
response_type: "code",
|
|
440
|
+
scope: scopes.join(" "),
|
|
441
|
+
state: pending.state,
|
|
442
|
+
...options.authorizationParameters
|
|
443
|
+
}).toString();
|
|
444
|
+
url.searchParams.set("resource", resource);
|
|
445
|
+
const result = new Promise((resolve, reject) => {
|
|
446
|
+
pendingSignIns.set(pending.state, { reject, resolve });
|
|
447
|
+
options.signal?.addEventListener("abort", () => {
|
|
448
|
+
pendingSignIns.delete(pending.state);
|
|
449
|
+
config.storage.remove(PENDING_KEY);
|
|
450
|
+
reject(new MobileAuthError("aborted", "Authorization was cancelled."));
|
|
451
|
+
}, { once: true });
|
|
452
|
+
});
|
|
453
|
+
try {
|
|
454
|
+
await config.links.openExternal(url.href);
|
|
455
|
+
} catch (error) {
|
|
456
|
+
pendingSignIns.delete(pending.state);
|
|
457
|
+
await config.storage.remove(PENDING_KEY);
|
|
458
|
+
throw error;
|
|
459
|
+
}
|
|
460
|
+
return result;
|
|
461
|
+
};
|
|
462
|
+
const authenticatedFetch = async (input, init) => {
|
|
463
|
+
const original = new Request(input, init);
|
|
464
|
+
if (!allowedOrigins.has(new URL(original.url).origin))
|
|
465
|
+
throw new MobileAuthError("origin", "Mobile auth refused to send a credential to an unregistered origin.");
|
|
466
|
+
const send = async (forceRefresh) => {
|
|
467
|
+
if (forceRefresh)
|
|
468
|
+
access = undefined;
|
|
469
|
+
const token = await refreshAccessToken();
|
|
470
|
+
const request = original.clone();
|
|
471
|
+
const headers = new Headers(request.headers);
|
|
472
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
473
|
+
return fetchImpl(new Request(request, { credentials: "omit", headers }));
|
|
474
|
+
};
|
|
475
|
+
const response = await send(false);
|
|
476
|
+
return response.status === 401 ? send(true) : response;
|
|
477
|
+
};
|
|
478
|
+
const optionalAuthenticatedFetch = async (input, init) => {
|
|
479
|
+
const request = new Request(input, init);
|
|
480
|
+
if (!allowedOrigins.has(new URL(request.url).origin))
|
|
481
|
+
throw new MobileAuthError("origin", "Mobile auth refused to send a request outside an allowed origin.");
|
|
482
|
+
const refreshToken = await config.storage.get(REFRESH_KEY);
|
|
483
|
+
if (access || refreshToken)
|
|
484
|
+
return authenticatedFetch(request);
|
|
485
|
+
return fetchImpl(new Request(request, { credentials: "omit" }));
|
|
486
|
+
};
|
|
487
|
+
const status = async () => {
|
|
488
|
+
try {
|
|
489
|
+
const metadata = await discovery();
|
|
490
|
+
const response = await authenticatedFetch(metadata.userinfo_endpoint);
|
|
491
|
+
if (response.status === 401)
|
|
492
|
+
return null;
|
|
493
|
+
if (!response.ok)
|
|
494
|
+
throw new MobileAuthError("network", `User info failed with HTTP ${response.status}.`);
|
|
495
|
+
const user = await response.json();
|
|
496
|
+
if (!isRecord(user) || typeof user.sub !== "string")
|
|
497
|
+
throw new MobileAuthError("token", "The user-info response is malformed.");
|
|
498
|
+
return { ...user, sub: user.sub };
|
|
499
|
+
} catch (error) {
|
|
500
|
+
if (error instanceof MobileAuthError && (error.code === "oauth" || error.code === "token"))
|
|
501
|
+
return null;
|
|
502
|
+
throw error;
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
const socketTicket = async (audience = resource) => {
|
|
506
|
+
const metadata = await discovery();
|
|
507
|
+
if (!metadata.socket_ticket_endpoint)
|
|
508
|
+
throw new MobileAuthError("discovery", "The authorization server does not advertise WebSocket tickets.");
|
|
509
|
+
const response = await authenticatedFetch(metadata.socket_ticket_endpoint, {
|
|
510
|
+
body: JSON.stringify({ audience }),
|
|
511
|
+
headers: { "content-type": "application/json" },
|
|
512
|
+
method: "POST"
|
|
513
|
+
});
|
|
514
|
+
const body = await responseBody(response);
|
|
515
|
+
if (!response.ok || !isRecord(body) || typeof body.ticket !== "string")
|
|
516
|
+
throw new MobileAuthError(response.ok ? "token" : "oauth", `WebSocket ticket request failed with HTTP ${response.status}.`);
|
|
517
|
+
return body.ticket;
|
|
518
|
+
};
|
|
519
|
+
const revokeRefreshToken = async (refreshToken) => {
|
|
520
|
+
const metadata = await discovery();
|
|
521
|
+
if (metadata.revocation_endpoint)
|
|
522
|
+
await fetchImpl(metadata.revocation_endpoint, {
|
|
523
|
+
body: new URLSearchParams({
|
|
524
|
+
client_id: config.clientId,
|
|
525
|
+
token: refreshToken,
|
|
526
|
+
token_type_hint: "refresh_token"
|
|
527
|
+
}),
|
|
528
|
+
credentials: "omit",
|
|
529
|
+
headers: {
|
|
530
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
531
|
+
},
|
|
532
|
+
method: "POST"
|
|
533
|
+
});
|
|
534
|
+
};
|
|
535
|
+
const signOut = async () => {
|
|
536
|
+
const refreshToken = await config.storage.get(REFRESH_KEY);
|
|
537
|
+
try {
|
|
538
|
+
if (refreshToken)
|
|
539
|
+
await revokeRefreshToken(refreshToken);
|
|
540
|
+
} finally {
|
|
541
|
+
access = undefined;
|
|
542
|
+
await Promise.all([
|
|
543
|
+
config.storage.remove(PENDING_KEY),
|
|
544
|
+
config.storage.remove(REFRESH_KEY)
|
|
545
|
+
]);
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
const stop = async () => {
|
|
549
|
+
await Promise.all([stopLinks?.(), stopResume?.()]);
|
|
550
|
+
stopLinks = undefined;
|
|
551
|
+
stopResume = undefined;
|
|
552
|
+
startPromise = undefined;
|
|
553
|
+
};
|
|
554
|
+
return {
|
|
555
|
+
fetch: authenticatedFetch,
|
|
556
|
+
fetchOptional: optionalAuthenticatedFetch,
|
|
557
|
+
handleCallback,
|
|
558
|
+
refresh: refreshAccessToken,
|
|
559
|
+
signIn,
|
|
560
|
+
signOut,
|
|
561
|
+
socketTicket,
|
|
562
|
+
start,
|
|
563
|
+
status,
|
|
564
|
+
stop
|
|
565
|
+
};
|
|
566
|
+
};
|
|
567
|
+
var createMobileAuthTransport = (client) => ({
|
|
568
|
+
fetch: client.fetchOptional,
|
|
569
|
+
signInEmail: async ({ email }) => {
|
|
570
|
+
await client.signIn({
|
|
571
|
+
authorizationParameters: { login_hint: email }
|
|
572
|
+
});
|
|
573
|
+
return { status: "authenticated" };
|
|
574
|
+
},
|
|
575
|
+
signOut: async () => {
|
|
576
|
+
await client.signOut();
|
|
577
|
+
return null;
|
|
578
|
+
},
|
|
579
|
+
signUpEmail: async ({ email }) => {
|
|
580
|
+
await client.signIn({
|
|
581
|
+
authorizationParameters: {
|
|
582
|
+
login_hint: email,
|
|
583
|
+
screen_hint: "signup"
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
return { status: "authenticated" };
|
|
587
|
+
},
|
|
588
|
+
status: async () => {
|
|
589
|
+
const user = await client.status();
|
|
590
|
+
return { user };
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
export {
|
|
594
|
+
installAuthClientRuntimeTransport,
|
|
595
|
+
createMobileAuthTransport,
|
|
596
|
+
createMobileAuthClient,
|
|
597
|
+
MobileAuthError
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
//# debugId=2EC3954C683DF95B64756E2164756E21
|
|
601
|
+
//# sourceMappingURL=mobile.js.map
|