better-auth 1.8.0-beta.6 → 1.8.0-beta.8
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/dist/api/index.d.mts +67 -1
- package/dist/api/index.mjs +4 -1
- package/dist/api/routes/account.mjs +2 -0
- package/dist/api/routes/id-token-nonce.d.mts +85 -0
- package/dist/api/routes/id-token-nonce.mjs +80 -0
- package/dist/api/routes/index.d.mts +2 -1
- package/dist/api/routes/sign-in.mjs +2 -0
- package/dist/client/proxy.mjs +4 -11
- package/dist/db/get-migration.mjs +9 -11
- package/dist/db/internal-adapter.mjs +37 -28
- package/dist/db/schema.mjs +17 -8
- package/dist/package.mjs +1 -1
- package/dist/plugins/admin/routes.mjs +13 -11
- package/dist/plugins/device-authorization/index.d.mts +1 -0
- package/dist/plugins/device-authorization/routes.mjs +18 -1
- package/dist/plugins/generic-oauth/index.d.mts +1 -4
- package/dist/plugins/generic-oauth/index.mjs +39 -23
- package/dist/plugins/generic-oauth/types.d.mts +10 -2
- package/dist/plugins/one-tap/client.d.mts +4 -0
- package/dist/plugins/one-tap/client.mjs +90 -77
- package/dist/plugins/one-tap/index.d.mts +40 -0
- package/dist/plugins/one-tap/index.mjs +112 -85
- package/dist/plugins/open-api/generator.mjs +2 -1
- package/dist/plugins/organization/adapter.mjs +4 -0
- package/dist/plugins/organization/routes/crud-invites.mjs +1 -1
- package/dist/plugins/siwe/index.mjs +41 -24
- package/dist/plugins/username/index.mjs +3 -2
- package/dist/state.d.mts +2 -5
- package/dist/state.mjs +2 -6
- package/dist/test-utils/http-test-instance.d.mts +8 -0
- package/dist/utils/hide-metadata.d.mts +2 -5
- package/dist/utils/hide-metadata.mjs +1 -4
- package/package.json +8 -8
|
@@ -5,6 +5,7 @@ import { getAuthoritativeSessionFromCtx, getSessionFromCtx } from "../../api/rou
|
|
|
5
5
|
import { assertPasswordNotTooLong, assertPasswordNotTooShort } from "../../utils/password.mjs";
|
|
6
6
|
import { ADMIN_ERROR_CODES } from "./error-codes.mjs";
|
|
7
7
|
import { hasPermission } from "./has-permission.mjs";
|
|
8
|
+
import { runWithTransaction } from "@better-auth/core/context";
|
|
8
9
|
import { APIError, BASE_ERROR_CODES } from "@better-auth/core/error";
|
|
9
10
|
import { whereOperators } from "@better-auth/core/db/adapter";
|
|
10
11
|
import { createAuthEndpoint, createAuthMiddleware } from "@better-auth/core/api";
|
|
@@ -193,22 +194,23 @@ const createUser = (opts) => createAuthEndpoint("/admin/create-user", {
|
|
|
193
194
|
if (!z.email().safeParse(email).success) throw APIError.from("BAD_REQUEST", BASE_ERROR_CODES.INVALID_EMAIL);
|
|
194
195
|
if (ctx.body.password) assertPasswordNotTooLong(ctx, ctx.body.password);
|
|
195
196
|
if (await ctx.context.internalAdapter.findUserByEmail(email)) throw APIError.from("BAD_REQUEST", ADMIN_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
await ctx.context.internalAdapter.linkAccount({
|
|
197
|
+
const hashedPassword = ctx.body.password ? await ctx.context.password.hash(ctx.body.password) : void 0;
|
|
198
|
+
const user = await runWithTransaction(ctx.context.adapter, async () => {
|
|
199
|
+
const user = await ctx.context.internalAdapter.createUser({
|
|
200
|
+
...userData,
|
|
201
|
+
email,
|
|
202
|
+
name: ctx.body.name,
|
|
203
|
+
role: requestedRole !== void 0 ? parseRoles(requestedRole) : opts?.defaultRole ?? "user"
|
|
204
|
+
}, { method: "admin" });
|
|
205
|
+
if (!user) throw APIError.from("INTERNAL_SERVER_ERROR", ADMIN_ERROR_CODES.FAILED_TO_CREATE_USER);
|
|
206
|
+
if (hashedPassword !== void 0) await ctx.context.internalAdapter.linkAccount({
|
|
206
207
|
providerId: "credential",
|
|
207
208
|
accountId: user.id,
|
|
208
209
|
password: hashedPassword,
|
|
209
210
|
userId: user.id
|
|
210
211
|
});
|
|
211
|
-
|
|
212
|
+
return user;
|
|
213
|
+
});
|
|
212
214
|
return ctx.json({ user: parseUserOutput(ctx.context.options, user) });
|
|
213
215
|
});
|
|
214
216
|
const adminUpdateUserBodySchema = z.object({
|
|
@@ -305,6 +305,7 @@ export declare const deviceAuthorization: <Grant extends DeviceAuthorizationGran
|
|
|
305
305
|
invalid_request: "invalid_request";
|
|
306
306
|
expired_token: "expired_token";
|
|
307
307
|
access_denied: "access_denied";
|
|
308
|
+
invalid_client: "invalid_client";
|
|
308
309
|
authorization_pending: "authorization_pending";
|
|
309
310
|
slow_down: "slow_down";
|
|
310
311
|
invalid_grant: "invalid_grant";
|
|
@@ -369,6 +369,7 @@ const deviceTokenErrorSchema = z.object({
|
|
|
369
369
|
"expired_token",
|
|
370
370
|
"access_denied",
|
|
371
371
|
"invalid_request",
|
|
372
|
+
"invalid_client",
|
|
372
373
|
"invalid_grant"
|
|
373
374
|
]).meta({ description: "Error code" }),
|
|
374
375
|
error_description: z.string().meta({ description: "Detailed error description" })
|
|
@@ -504,6 +505,7 @@ Follow [rfc8628#section-3.4](https://datatracker.ietf.org/doc/html/rfc8628#secti
|
|
|
504
505
|
"expired_token",
|
|
505
506
|
"access_denied",
|
|
506
507
|
"invalid_request",
|
|
508
|
+
"invalid_client",
|
|
507
509
|
"invalid_grant"
|
|
508
510
|
]
|
|
509
511
|
},
|
|
@@ -518,7 +520,7 @@ Follow [rfc8628#section-3.4](https://datatracker.ietf.org/doc/html/rfc8628#secti
|
|
|
518
520
|
const { device_code, client_id } = ctx.body;
|
|
519
521
|
if (opts.validateClient) {
|
|
520
522
|
if (!await opts.validateClient(client_id)) throw new APIError("BAD_REQUEST", {
|
|
521
|
-
error: "
|
|
523
|
+
error: "invalid_client",
|
|
522
524
|
error_description: "Invalid client ID"
|
|
523
525
|
});
|
|
524
526
|
}
|
|
@@ -632,6 +634,21 @@ const deviceVerify = (grant) => createAuthEndpoint("/device", {
|
|
|
632
634
|
increment: {},
|
|
633
635
|
set: { userId: session.user.id }
|
|
634
636
|
})) deviceCodeRecord.userId = session.user.id;
|
|
637
|
+
else {
|
|
638
|
+
const current = await ctx.context.adapter.findOne({
|
|
639
|
+
model: "deviceCode",
|
|
640
|
+
where: [{
|
|
641
|
+
field: "id",
|
|
642
|
+
value: deviceCodeRecord.id
|
|
643
|
+
}]
|
|
644
|
+
});
|
|
645
|
+
if (!current) throw new APIError("BAD_REQUEST", {
|
|
646
|
+
error: "invalid_request",
|
|
647
|
+
error_description: DEVICE_AUTHORIZATION_ERROR_CODES.INVALID_USER_CODE.message
|
|
648
|
+
});
|
|
649
|
+
deviceCodeRecord.userId = current.userId;
|
|
650
|
+
deviceCodeRecord.status = current.status;
|
|
651
|
+
}
|
|
635
652
|
}
|
|
636
653
|
const canReviewRequest = session?.user.id !== void 0 && deviceCodeRecord.userId === session.user.id;
|
|
637
654
|
return ctx.json({
|
|
@@ -25,10 +25,7 @@ declare module "@better-auth/core" {
|
|
|
25
25
|
* Extracts common fields from GenericOAuthConfig for provider helpers.
|
|
26
26
|
*/
|
|
27
27
|
export type BaseOAuthProviderOptions = Pick<GenericOAuthConfig, "clientId" | "clientSecret" | "tokenEndpointAuth" | "scopes" | "redirectURI" | "endSessionEndpoint" | "postLogoutRedirectURI" | "disableProviderLogout" | "pkce" | "disableImplicitSignUp" | "disableSignUp" | "overrideUserInfo">;
|
|
28
|
-
type PendingDiscovery = Map<string,
|
|
29
|
-
config: GenericOAuthConfig;
|
|
30
|
-
attempt?: Promise<void> | undefined;
|
|
31
|
-
}>;
|
|
28
|
+
type PendingDiscovery = Map<string, GenericOAuthConfig>;
|
|
32
29
|
/**
|
|
33
30
|
* A generic OAuth plugin that registers any OAuth/OIDC provider
|
|
34
31
|
* as a first-class social provider.
|
|
@@ -25,6 +25,7 @@ function isClientSecretTokenEndpointAuth(tokenEndpointAuth) {
|
|
|
25
25
|
}
|
|
26
26
|
/** A request waits on a discovery retry, so bound it (the SSO plugin uses 10s too). */
|
|
27
27
|
const DISCOVERY_RETRY_TIMEOUT_MS = 1e4;
|
|
28
|
+
const MAX_DISCOVERY_REDIRECTS = 5;
|
|
28
29
|
/**
|
|
29
30
|
* Providers skipped because startup discovery failed. Init stores them on each auth
|
|
30
31
|
* instance's context, so one plugin object can serve several instances. It is a context
|
|
@@ -44,18 +45,35 @@ const readIdTokenClaims = (idToken) => {
|
|
|
44
45
|
}
|
|
45
46
|
};
|
|
46
47
|
async function fetchDiscovery(url, headers, timeout) {
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
48
|
+
const signal = timeout ? AbortSignal.timeout(timeout) : void 0;
|
|
49
|
+
let target = url;
|
|
50
|
+
for (let hop = 0;; hop++) {
|
|
51
|
+
const redirect = {};
|
|
52
|
+
const result = await betterFetch(target, {
|
|
53
|
+
method: "GET",
|
|
54
|
+
headers,
|
|
55
|
+
redirect: headers ? "manual" : void 0,
|
|
56
|
+
signal,
|
|
57
|
+
onError: ({ response }) => {
|
|
58
|
+
if (response.status >= 300 && response.status < 400) redirect.location = response.headers.get("location");
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
if (headers && redirect.location) {
|
|
62
|
+
const next = new URL(redirect.location, target);
|
|
63
|
+
if (next.origin !== new URL(url).origin) throw new Error(`discovery redirected to ${next.origin}; with discoveryHeaders set, only same-origin redirects are followed. Set discoveryUrl to the final URL.`);
|
|
64
|
+
if (hop >= MAX_DISCOVERY_REDIRECTS) throw new Error(`discovery redirected more than ${MAX_DISCOVERY_REDIRECTS} times. Set discoveryUrl to the final URL.`);
|
|
65
|
+
target = next.href;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (headers && result.error?.status === 0) throw new Error("discovery redirected; with discoveryHeaders set, set discoveryUrl to the final URL.");
|
|
69
|
+
if (result.error || !result.data) return null;
|
|
70
|
+
if (result.data.issuer) try {
|
|
71
|
+
new URL(result.data.issuer);
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
return result.data;
|
|
57
76
|
}
|
|
58
|
-
return result.data;
|
|
59
77
|
}
|
|
60
78
|
async function fetchUserInfo(tokens, userInfoUrl, idTokenClaims) {
|
|
61
79
|
if (tokens.idToken) {
|
|
@@ -100,6 +118,7 @@ const genericOAuth = (options) => {
|
|
|
100
118
|
const buildProviders = async (configs, ctx, discoveryTimeout) => {
|
|
101
119
|
const genericProviders = [];
|
|
102
120
|
for (const c of configs) {
|
|
121
|
+
if (Object.keys(c.authorizationHeaders ?? {}).some((name) => name.toLowerCase() === "authorization")) throw new Error(`Provider "${c.providerId}": authorizationHeaders cannot set "Authorization". Use tokenEndpointAuth: { method: "custom", customizeRequest } instead.`);
|
|
103
122
|
let authorizationUrl = c.authorizationUrl;
|
|
104
123
|
let tokenUrl = c.tokenUrl;
|
|
105
124
|
let userInfoUrl = c.userInfoUrl;
|
|
@@ -128,8 +147,9 @@ const genericOAuth = (options) => {
|
|
|
128
147
|
ctx.logger.error(`Provider "${c.providerId}": invalid jwks_uri "${discovered.jwks_uri}" in discovery document. Provider skipped.`);
|
|
129
148
|
continue;
|
|
130
149
|
}
|
|
150
|
+
const jwksHeaders = jwksUrl.origin === new URL(c.discoveryUrl).origin ? c.discoveryHeaders : void 0;
|
|
131
151
|
idTokenConfig = {
|
|
132
|
-
jwks: createRemoteJWKSet(jwksUrl),
|
|
152
|
+
jwks: createRemoteJWKSet(jwksUrl, jwksHeaders && { headers: jwksHeaders }),
|
|
133
153
|
issuer: discovered.issuer,
|
|
134
154
|
audience: c.clientId,
|
|
135
155
|
algorithms: isOidc ? signingAlgs : void 0
|
|
@@ -287,7 +307,8 @@ const genericOAuth = (options) => {
|
|
|
287
307
|
authentication: c.authentication,
|
|
288
308
|
tokenEndpointAuth,
|
|
289
309
|
tokenEndpoint: tokenUrl,
|
|
290
|
-
extraParams: resolvedRefreshParams
|
|
310
|
+
extraParams: resolvedRefreshParams,
|
|
311
|
+
headers: c.authorizationHeaders
|
|
291
312
|
});
|
|
292
313
|
return applyDefaultAccessTokenExpiry(tokens, c.accessTokenExpiresIn);
|
|
293
314
|
},
|
|
@@ -303,18 +324,13 @@ const genericOAuth = (options) => {
|
|
|
303
324
|
}
|
|
304
325
|
return genericProviders;
|
|
305
326
|
};
|
|
306
|
-
const retryDiscovery = (ctx, providerId) => {
|
|
327
|
+
const retryDiscovery = async (ctx, providerId) => {
|
|
307
328
|
const pendingDiscovery = getPendingDiscovery(ctx);
|
|
308
329
|
const pending = pendingDiscovery?.get(providerId);
|
|
309
330
|
if (!pending) return;
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
ctx.socialProviders.unshift(provider);
|
|
314
|
-
}).finally(() => {
|
|
315
|
-
pending.attempt = void 0;
|
|
316
|
-
});
|
|
317
|
-
return pending.attempt;
|
|
331
|
+
const [provider] = await buildProviders([pending], ctx, DISCOVERY_RETRY_TIMEOUT_MS);
|
|
332
|
+
if (!provider || !pendingDiscovery?.delete(providerId)) return;
|
|
333
|
+
ctx.socialProviders.unshift(provider);
|
|
318
334
|
};
|
|
319
335
|
const requestedProviderId = (context) => {
|
|
320
336
|
const id = context.body?.provider ?? context.body?.providerId ?? context.query?.provider ?? context.params?.id;
|
|
@@ -326,7 +342,7 @@ const genericOAuth = (options) => {
|
|
|
326
342
|
init: async (ctx) => {
|
|
327
343
|
const genericProviders = await buildProviders(options.config, ctx);
|
|
328
344
|
const built = new Set(genericProviders.map((p) => p.id));
|
|
329
|
-
const genericOAuthPendingDiscovery = new Map(options.config.filter((c) => !built.has(c.providerId)).map((c) => [c.providerId,
|
|
345
|
+
const genericOAuthPendingDiscovery = new Map(options.config.filter((c) => !built.has(c.providerId)).map((c) => [c.providerId, c]));
|
|
330
346
|
const existingIds = new Set(ctx.socialProviders.map((p) => p.id));
|
|
331
347
|
for (const gp of genericProviders) if (existingIds.has(gp.id)) ctx.logger.warn(`Generic OAuth provider "${gp.id}" shadows a built-in social provider with the same ID`);
|
|
332
348
|
return { context: {
|
|
@@ -211,13 +211,21 @@ export interface GenericOAuthConfig<ID extends string = string> {
|
|
|
211
211
|
*/
|
|
212
212
|
authentication?: ("basic" | "post") | undefined;
|
|
213
213
|
/**
|
|
214
|
-
* Custom headers to include in the discovery request
|
|
214
|
+
* Custom headers to include in the discovery request, and in the JWKS request when
|
|
215
|
+
* `jwks_uri` has the same origin as `discoveryUrl`. When set, discovery follows
|
|
216
|
+
* redirects only within that origin and fails on a redirect to another origin.
|
|
215
217
|
* Useful for providers like Epic that require specific headers (e.g., Epic-Client-ID).
|
|
216
218
|
*/
|
|
217
219
|
discoveryHeaders?: Record<string, string> | undefined;
|
|
218
220
|
/**
|
|
219
|
-
* Custom headers to include in the authorization
|
|
221
|
+
* Custom headers to include in token endpoint requests: the authorization
|
|
222
|
+
* code exchange and token refresh. A custom `getToken` replaces the default
|
|
223
|
+
* code exchange, so it must add these headers itself.
|
|
220
224
|
* Useful for providers like Qonto that require specific headers (e.g., X-Qonto-Staging-Token for local development).
|
|
225
|
+
*
|
|
226
|
+
* `Authorization` is not allowed in any letter case, and initialization fails
|
|
227
|
+
* if it is present. Set it from `tokenEndpointAuth` with `method: "custom"`
|
|
228
|
+
* and `customizeRequest` instead.
|
|
221
229
|
*/
|
|
222
230
|
authorizationHeaders?: Record<string, string> | undefined;
|
|
223
231
|
/**
|
|
@@ -138,6 +138,10 @@ export interface GoogleOneTapActionOptions extends Omit<GoogleOneTapOptions, "cl
|
|
|
138
138
|
* This lets you render an alternative UI (e.g. a Google Sign-In button) to restart the process.
|
|
139
139
|
*/
|
|
140
140
|
onPromptNotification?: ((notification?: any | undefined) => void) | undefined;
|
|
141
|
+
/**
|
|
142
|
+
* @deprecated Ignored. The client fetches a single-use nonce from
|
|
143
|
+
* `/one-tap/nonce` for every prompt and button render.
|
|
144
|
+
*/
|
|
141
145
|
nonce?: string | undefined;
|
|
142
146
|
/**
|
|
143
147
|
* Button mode configuration. When provided, renders a "Sign In with Google" button
|
|
@@ -2,6 +2,9 @@ import { PACKAGE_VERSION } from "../../version.mjs";
|
|
|
2
2
|
import { isSafeUrlScheme } from "@better-auth/core/utils/url";
|
|
3
3
|
//#region src/plugins/one-tap/client.ts
|
|
4
4
|
let isRequestInProgress = false;
|
|
5
|
+
const BUTTON_NONCE_REFRESH_MS = 24e4;
|
|
6
|
+
const BUTTON_NONCE_RETRY_MS = 1e4;
|
|
7
|
+
const buttonRefreshTimers = /* @__PURE__ */ new WeakMap();
|
|
5
8
|
function isFedCMSupported() {
|
|
6
9
|
return typeof window !== "undefined" && "IdentityCredential" in window;
|
|
7
10
|
}
|
|
@@ -33,102 +36,112 @@ const oneTapClient = (options) => {
|
|
|
33
36
|
console.warn("Google One Tap is only available in browser environments");
|
|
34
37
|
return;
|
|
35
38
|
}
|
|
36
|
-
if (opts?.
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if (!container) {
|
|
40
|
-
console.error("Google One Tap: Button container not found", opts.button.container);
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
async function callback(idToken) {
|
|
44
|
-
if ((await $fetch("/one-tap/callback", {
|
|
45
|
-
method: "POST",
|
|
46
|
-
body: {
|
|
47
|
-
idToken,
|
|
48
|
-
callbackURL: opts?.callbackURL
|
|
49
|
-
},
|
|
50
|
-
...opts?.fetchOptions,
|
|
51
|
-
...fetchOptions
|
|
52
|
-
}))?.error) return;
|
|
53
|
-
if (!opts?.fetchOptions && !fetchOptions || opts?.callbackURL) {
|
|
54
|
-
const target = opts?.callbackURL ?? "/";
|
|
55
|
-
if (isSafeUrlScheme(target)) window.location.href = target;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
const autoSelect = opts?.autoSelect ?? options.autoSelect;
|
|
59
|
-
const cancelOnTapOutside = opts?.cancelOnTapOutside ?? options.cancelOnTapOutside;
|
|
60
|
-
const contextValue = opts?.context ?? options.context ?? "signin";
|
|
61
|
-
window.google?.accounts.id.initialize({
|
|
62
|
-
client_id: options.clientId,
|
|
63
|
-
callback: async (response) => {
|
|
64
|
-
try {
|
|
65
|
-
await callback(response.credential);
|
|
66
|
-
} catch (error) {
|
|
67
|
-
console.error("Error during button callback:", error);
|
|
68
|
-
}
|
|
69
|
-
},
|
|
70
|
-
auto_select: autoSelect,
|
|
71
|
-
cancel_on_tap_outside: cancelOnTapOutside,
|
|
72
|
-
context: contextValue,
|
|
73
|
-
ux_mode: opts?.uxMode || "popup",
|
|
74
|
-
nonce: opts?.nonce,
|
|
75
|
-
itp_support: true,
|
|
76
|
-
...opts.button.fedCM && {
|
|
77
|
-
use_fedcm_for_button: true,
|
|
78
|
-
button_auto_select: autoSelect
|
|
79
|
-
},
|
|
80
|
-
...options.additionalOptions
|
|
81
|
-
});
|
|
82
|
-
window.google?.accounts.id.renderButton(container, opts.button.config ?? { type: "icon" });
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
async function callback(idToken) {
|
|
39
|
+
if (opts?.nonce !== void 0) console.warn("Google One Tap: the `nonce` option is ignored; the nonce is issued by the server.");
|
|
40
|
+
/** Returns whether it navigated away. */
|
|
41
|
+
async function callback(idToken, nonce) {
|
|
86
42
|
if ((await $fetch("/one-tap/callback", {
|
|
87
43
|
method: "POST",
|
|
88
44
|
body: {
|
|
89
45
|
idToken,
|
|
46
|
+
nonce,
|
|
90
47
|
callbackURL: opts?.callbackURL
|
|
91
48
|
},
|
|
92
49
|
...opts?.fetchOptions,
|
|
93
50
|
...fetchOptions
|
|
94
|
-
}))?.error) return;
|
|
51
|
+
}))?.error) return false;
|
|
95
52
|
if (!opts?.fetchOptions && !fetchOptions || opts?.callbackURL) {
|
|
96
53
|
const target = opts?.callbackURL ?? "/";
|
|
97
|
-
if (isSafeUrlScheme(target))
|
|
54
|
+
if (isSafeUrlScheme(target)) {
|
|
55
|
+
window.location.href = target;
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
98
58
|
}
|
|
59
|
+
return false;
|
|
99
60
|
}
|
|
61
|
+
const { body: _body, query: _query, params: _params, output: _output, errorSchema: _errorSchema, onResponse: _onResponse, onSuccess: _onSuccess, onError: _onError, onRetry: _onRetry, ...nonceFetchOptions } = {
|
|
62
|
+
...opts?.fetchOptions,
|
|
63
|
+
...fetchOptions
|
|
64
|
+
};
|
|
65
|
+
const fetchNonce = async () => {
|
|
66
|
+
const { data, error } = await $fetch("/one-tap/nonce", {
|
|
67
|
+
...nonceFetchOptions,
|
|
68
|
+
method: "POST",
|
|
69
|
+
throw: false
|
|
70
|
+
});
|
|
71
|
+
if (!data?.nonce) throw new Error("Google One Tap: failed to fetch a nonce", { cause: error });
|
|
72
|
+
return data.nonce;
|
|
73
|
+
};
|
|
100
74
|
const autoSelect = opts?.autoSelect ?? options.autoSelect;
|
|
101
|
-
const
|
|
102
|
-
|
|
75
|
+
const initialize = (nonce, onCredential) => window.google?.accounts.id.initialize({
|
|
76
|
+
client_id: options.clientId,
|
|
77
|
+
callback: onCredential,
|
|
78
|
+
auto_select: autoSelect,
|
|
79
|
+
cancel_on_tap_outside: opts?.cancelOnTapOutside ?? options.cancelOnTapOutside,
|
|
80
|
+
context: opts?.context ?? options.context ?? "signin",
|
|
81
|
+
ux_mode: opts?.uxMode || "popup",
|
|
82
|
+
/**
|
|
83
|
+
* @see {@link https://developers.google.com/identity/gsi/web/guides/overview}
|
|
84
|
+
*/
|
|
85
|
+
itp_support: true,
|
|
86
|
+
...opts?.button?.fedCM && {
|
|
87
|
+
use_fedcm_for_button: true,
|
|
88
|
+
button_auto_select: autoSelect
|
|
89
|
+
},
|
|
90
|
+
...options.additionalOptions,
|
|
91
|
+
nonce
|
|
92
|
+
});
|
|
93
|
+
if (opts?.button) {
|
|
94
|
+
await loadGoogleScript();
|
|
95
|
+
const container = typeof opts.button.container === "string" ? document.querySelector(opts.button.container) : opts.button.container;
|
|
96
|
+
if (!container) {
|
|
97
|
+
console.error("Google One Tap: Button container not found", opts.button.container);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const buttonConfig = opts.button.config ?? { type: "icon" };
|
|
101
|
+
const renderButton = async () => {
|
|
102
|
+
clearTimeout(buttonRefreshTimers.get(container));
|
|
103
|
+
const nonce = await fetchNonce();
|
|
104
|
+
initialize(nonce, async (response) => {
|
|
105
|
+
let navigated = false;
|
|
106
|
+
try {
|
|
107
|
+
navigated = await callback(response.credential, nonce);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.error("Error during button callback:", error);
|
|
110
|
+
}
|
|
111
|
+
if (!navigated) await refreshButton();
|
|
112
|
+
});
|
|
113
|
+
container.replaceChildren();
|
|
114
|
+
buttonRefreshTimers.set(container, setTimeout(refreshButton, BUTTON_NONCE_REFRESH_MS));
|
|
115
|
+
window.google?.accounts.id.renderButton(container, buttonConfig);
|
|
116
|
+
};
|
|
117
|
+
const refreshButton = async () => {
|
|
118
|
+
if (!container.isConnected) return;
|
|
119
|
+
try {
|
|
120
|
+
await renderButton();
|
|
121
|
+
} catch (error) {
|
|
122
|
+
console.error("Google One Tap: failed to refresh the button", error);
|
|
123
|
+
buttonRefreshTimers.set(container, setTimeout(refreshButton, BUTTON_NONCE_RETRY_MS));
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
await renderButton();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
103
129
|
isRequestInProgress = true;
|
|
104
130
|
try {
|
|
105
|
-
await loadGoogleScript();
|
|
131
|
+
const [, nonce] = await Promise.all([loadGoogleScript(), fetchNonce()]);
|
|
106
132
|
await new Promise((resolve, reject) => {
|
|
107
133
|
let isResolved = false;
|
|
108
134
|
const baseDelay = options.promptOptions?.baseDelay ?? 1e3;
|
|
109
135
|
const maxAttempts = options.promptOptions?.maxAttempts ?? 5;
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
reject(error);
|
|
120
|
-
}
|
|
121
|
-
},
|
|
122
|
-
auto_select: autoSelect,
|
|
123
|
-
cancel_on_tap_outside: cancelOnTapOutside,
|
|
124
|
-
context: contextValue,
|
|
125
|
-
ux_mode: opts?.uxMode || "popup",
|
|
126
|
-
nonce: opts?.nonce,
|
|
127
|
-
/**
|
|
128
|
-
* @see {@link https://developers.google.com/identity/gsi/web/guides/overview}
|
|
129
|
-
*/
|
|
130
|
-
itp_support: true,
|
|
131
|
-
...options.additionalOptions
|
|
136
|
+
initialize(nonce, async (response) => {
|
|
137
|
+
isResolved = true;
|
|
138
|
+
try {
|
|
139
|
+
await callback(response.credential, nonce);
|
|
140
|
+
resolve();
|
|
141
|
+
} catch (error) {
|
|
142
|
+
console.error("Error during One Tap callback:", error);
|
|
143
|
+
reject(error);
|
|
144
|
+
}
|
|
132
145
|
});
|
|
133
146
|
const handlePrompt = (attempt) => {
|
|
134
147
|
if (isResolved) return;
|
|
@@ -26,10 +26,50 @@ export declare const oneTap: (options?: OneTapOptions | undefined) => {
|
|
|
26
26
|
id: "one-tap";
|
|
27
27
|
version: string;
|
|
28
28
|
endpoints: {
|
|
29
|
+
/**
|
|
30
|
+
* ### Endpoint
|
|
31
|
+
*
|
|
32
|
+
* POST `/one-tap/nonce`
|
|
33
|
+
*
|
|
34
|
+
* Issues a single-use nonce to pass to Google before requesting the
|
|
35
|
+
* One Tap ID token. `/one-tap/callback` consumes it and requires the
|
|
36
|
+
* token's `nonce` claim to match.
|
|
37
|
+
*/
|
|
38
|
+
oneTapNonce: import("better-call").StrictEndpoint<"/one-tap/nonce", {
|
|
39
|
+
method: "POST";
|
|
40
|
+
metadata: {
|
|
41
|
+
noStore: boolean;
|
|
42
|
+
openapi: {
|
|
43
|
+
summary: string;
|
|
44
|
+
description: string;
|
|
45
|
+
responses: {
|
|
46
|
+
200: {
|
|
47
|
+
description: string;
|
|
48
|
+
content: {
|
|
49
|
+
"application/json": {
|
|
50
|
+
schema: {
|
|
51
|
+
type: "object";
|
|
52
|
+
properties: {
|
|
53
|
+
nonce: {
|
|
54
|
+
type: "string";
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
required: string[];
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
}, {
|
|
66
|
+
nonce: string;
|
|
67
|
+
}>;
|
|
29
68
|
oneTapCallback: import("better-call").StrictEndpoint<"/one-tap/callback", {
|
|
30
69
|
method: "POST";
|
|
31
70
|
body: z.ZodObject<{
|
|
32
71
|
idToken: z.ZodString;
|
|
72
|
+
nonce: z.ZodString;
|
|
33
73
|
callbackURL: z.ZodOptional<z.ZodString>;
|
|
34
74
|
}, z.core.$strip>;
|
|
35
75
|
metadata: {
|