@zenauth/react 0.0.0-stage → 0.5.0
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/LICENSE +21 -0
- package/README.md +132 -2
- package/dist/index.cjs +1468 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +470 -0
- package/dist/index.d.ts +470 -0
- package/dist/index.js +1429 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1429 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
// src/react/provider.tsx
|
|
4
|
+
import { createContext, useContext, useEffect, useMemo, useSyncExternalStore } from "react";
|
|
5
|
+
|
|
6
|
+
// src/core/pkce.ts
|
|
7
|
+
var toBase64Url = (bytes) => {
|
|
8
|
+
let binary = "";
|
|
9
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
10
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
11
|
+
};
|
|
12
|
+
var getCrypto = () => {
|
|
13
|
+
const c = globalThis.crypto;
|
|
14
|
+
if (!c?.subtle) {
|
|
15
|
+
throw new Error("ZenAuth needs the Web Crypto API. Serve your app over HTTPS (localhost is fine for development).");
|
|
16
|
+
}
|
|
17
|
+
return c;
|
|
18
|
+
};
|
|
19
|
+
var randomString = (byteLength = 32) => toBase64Url(getCrypto().getRandomValues(new Uint8Array(byteLength)));
|
|
20
|
+
var createCodeChallenge = async (verifier) => {
|
|
21
|
+
const digest = await getCrypto().subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
22
|
+
return toBase64Url(new Uint8Array(digest));
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// src/core/client.ts
|
|
26
|
+
var ZenAuthError = class extends Error {
|
|
27
|
+
constructor(code, message) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.name = "ZenAuthError";
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var DEFAULT_SCOPE = "openid profile email";
|
|
34
|
+
var EXPIRY_SKEW_MS = 3e4;
|
|
35
|
+
var TERMINAL_TOKEN_ERRORS = /* @__PURE__ */ new Set(["invalid_grant", "invalid_client", "unauthorized_client", "invalid_request"]);
|
|
36
|
+
var SERVER_STATE = { status: "loading", user: null, error: null };
|
|
37
|
+
var createMemoryStorage = () => {
|
|
38
|
+
const map = /* @__PURE__ */ new Map();
|
|
39
|
+
return {
|
|
40
|
+
getItem: (k) => map.get(k) ?? null,
|
|
41
|
+
setItem: (k, v) => void map.set(k, v),
|
|
42
|
+
removeItem: (k) => void map.delete(k)
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
var defaultStorage = () => {
|
|
46
|
+
try {
|
|
47
|
+
if (typeof sessionStorage !== "undefined") {
|
|
48
|
+
sessionStorage.setItem("__zenauth_probe", "1");
|
|
49
|
+
sessionStorage.removeItem("__zenauth_probe");
|
|
50
|
+
return sessionStorage;
|
|
51
|
+
}
|
|
52
|
+
} catch {
|
|
53
|
+
}
|
|
54
|
+
return createMemoryStorage();
|
|
55
|
+
};
|
|
56
|
+
var decodeJwtPayload = (jwt) => {
|
|
57
|
+
const part = jwt.split(".")[1];
|
|
58
|
+
if (!part) throw new ZenAuthError("invalid_id_token", "Malformed ID token");
|
|
59
|
+
try {
|
|
60
|
+
const binary = atob(part.replace(/-/g, "+").replace(/_/g, "/"));
|
|
61
|
+
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
62
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
63
|
+
} catch {
|
|
64
|
+
throw new ZenAuthError("invalid_id_token", "Malformed ID token");
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var safeReturnTo = (value) => value && value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\") ? value : void 0;
|
|
68
|
+
var ZenAuthClient = class {
|
|
69
|
+
constructor(config) {
|
|
70
|
+
this.config = config;
|
|
71
|
+
if (!config.clientId) throw new Error("ZenAuth: `clientId` is required");
|
|
72
|
+
if (!config.redirectUri) throw new Error("ZenAuth: `redirectUri` is required");
|
|
73
|
+
if (!config.issuer) throw new Error("ZenAuth: `issuer` is required");
|
|
74
|
+
this.issuer = config.issuer.replace(/\/+$/, "");
|
|
75
|
+
this.scope = config.scope ?? DEFAULT_SCOPE;
|
|
76
|
+
this.storage = config.storage ?? defaultStorage();
|
|
77
|
+
this.fetchFn = config.fetch ?? ((...args) => globalThis.fetch(...args));
|
|
78
|
+
this.navigate = config.navigate ?? ((url) => window.location.assign(url));
|
|
79
|
+
this.now = config.now ?? Date.now;
|
|
80
|
+
}
|
|
81
|
+
state = SERVER_STATE;
|
|
82
|
+
listeners = /* @__PURE__ */ new Set();
|
|
83
|
+
metadataPromise;
|
|
84
|
+
initPromise;
|
|
85
|
+
refreshPromise;
|
|
86
|
+
scope;
|
|
87
|
+
storage;
|
|
88
|
+
fetchFn;
|
|
89
|
+
navigate;
|
|
90
|
+
now;
|
|
91
|
+
issuer;
|
|
92
|
+
// ── State (shaped for React's useSyncExternalStore) ───────
|
|
93
|
+
getState = () => this.state;
|
|
94
|
+
getServerState = () => SERVER_STATE;
|
|
95
|
+
subscribe = (listener) => {
|
|
96
|
+
this.listeners.add(listener);
|
|
97
|
+
return () => this.listeners.delete(listener);
|
|
98
|
+
};
|
|
99
|
+
setState(next) {
|
|
100
|
+
const prev = this.state;
|
|
101
|
+
if (prev.status === next.status && prev.user === next.user && prev.error === next.error) return;
|
|
102
|
+
this.state = next;
|
|
103
|
+
this.listeners.forEach((l) => l());
|
|
104
|
+
}
|
|
105
|
+
// ── Lifecycle ─────────────────────────────────────────────
|
|
106
|
+
/**
|
|
107
|
+
* Call once on page load with the current URL. Finishes a sign-in redirect if there is one,
|
|
108
|
+
* otherwise restores the stored session. Safe to call repeatedly (e.g. React StrictMode).
|
|
109
|
+
*/
|
|
110
|
+
initialize(currentUrl) {
|
|
111
|
+
this.initPromise ??= this.run(currentUrl);
|
|
112
|
+
return this.initPromise;
|
|
113
|
+
}
|
|
114
|
+
async run(currentUrl) {
|
|
115
|
+
const params = new URL(currentUrl).searchParams;
|
|
116
|
+
const pending = this.readPending();
|
|
117
|
+
const looksLikeRedirect = params.has("code") || params.has("error");
|
|
118
|
+
if (pending && looksLikeRedirect) {
|
|
119
|
+
try {
|
|
120
|
+
const returnTo = await this.handleRedirect(currentUrl);
|
|
121
|
+
return { handledRedirect: true, returnTo };
|
|
122
|
+
} catch (err) {
|
|
123
|
+
this.clearSession();
|
|
124
|
+
this.setState({ status: "unauthenticated", user: null, error: err.message });
|
|
125
|
+
return { handledRedirect: true };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
await this.restoreSession();
|
|
129
|
+
return { handledRedirect: false };
|
|
130
|
+
}
|
|
131
|
+
async restoreSession() {
|
|
132
|
+
let tokens = this.readTokens();
|
|
133
|
+
if (!tokens) return this.setState({ status: "unauthenticated", user: null, error: null });
|
|
134
|
+
try {
|
|
135
|
+
if (tokens.expiresAt - EXPIRY_SKEW_MS <= this.now()) {
|
|
136
|
+
tokens = await this.refreshTokens();
|
|
137
|
+
if (!tokens) return;
|
|
138
|
+
}
|
|
139
|
+
let user;
|
|
140
|
+
try {
|
|
141
|
+
user = await this.fetchUser(tokens.accessToken);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
if (!(err instanceof ZenAuthError) || err.code !== "invalid_token") throw err;
|
|
144
|
+
const fresh = await this.refreshTokens();
|
|
145
|
+
if (!fresh) return;
|
|
146
|
+
user = await this.fetchUser(fresh.accessToken);
|
|
147
|
+
}
|
|
148
|
+
const cachedContext = this.readCachedUser()?.login_context;
|
|
149
|
+
if (cachedContext) user = { ...user, login_context: cachedContext };
|
|
150
|
+
this.storage.setItem(this.key("user"), JSON.stringify(user));
|
|
151
|
+
this.setState({ status: "authenticated", user, error: null });
|
|
152
|
+
} catch (err) {
|
|
153
|
+
const cached = this.readCachedUser();
|
|
154
|
+
if (cached) return this.setState({ status: "authenticated", user: cached, error: null });
|
|
155
|
+
this.setState({ status: "unauthenticated", user: null, error: err.message });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// ── Sign in ───────────────────────────────────────────────
|
|
159
|
+
/**
|
|
160
|
+
* Sends the browser to ZenAuth. Resolves right before navigation starts.
|
|
161
|
+
* Failures (e.g. ZenAuth unreachable) are reported through `state.error` instead of throwing,
|
|
162
|
+
* so it is safe to call straight from a click handler.
|
|
163
|
+
*/
|
|
164
|
+
async signIn(options = {}) {
|
|
165
|
+
let authorizeUrl;
|
|
166
|
+
try {
|
|
167
|
+
authorizeUrl = await this.buildAuthorizeUrl(options.returnTo);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
this.setState({ ...this.state, error: err.message });
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
this.navigate(authorizeUrl);
|
|
173
|
+
}
|
|
174
|
+
async buildAuthorizeUrl(returnTo) {
|
|
175
|
+
const metadata = await this.getMetadata();
|
|
176
|
+
const context = await this.createAuthContext(returnTo);
|
|
177
|
+
const url = new URL(metadata.authorization_endpoint);
|
|
178
|
+
url.searchParams.set("response_type", "code");
|
|
179
|
+
for (const [key, value] of Object.entries(context)) url.searchParams.set(key, value);
|
|
180
|
+
return url.toString();
|
|
181
|
+
}
|
|
182
|
+
/** Fresh PKCE verifier, state and nonce for one sign-in attempt. The verifier stays in storage. */
|
|
183
|
+
async createAuthContext(returnTo) {
|
|
184
|
+
const verifier = randomString(32);
|
|
185
|
+
const state = randomString(16);
|
|
186
|
+
const nonce = randomString(16);
|
|
187
|
+
const challenge = await createCodeChallenge(verifier);
|
|
188
|
+
this.writePending({ state, verifier, nonce, returnTo: safeReturnTo(returnTo) });
|
|
189
|
+
return {
|
|
190
|
+
client_id: this.config.clientId,
|
|
191
|
+
redirect_uri: this.config.redirectUri,
|
|
192
|
+
scope: this.scope,
|
|
193
|
+
state,
|
|
194
|
+
nonce,
|
|
195
|
+
code_challenge: challenge,
|
|
196
|
+
code_challenge_method: "S256"
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
// ── Embedded sign-in (no redirect to ZenAuth's page) ─────
|
|
200
|
+
/**
|
|
201
|
+
* Signs in with email/username + password using the app's OWN form. Throws a `ZenAuthError` with a
|
|
202
|
+
* user-presentable message on failure. A `complete` result means signed in (browser-only mode) or
|
|
203
|
+
* that the browser is already navigating to your server's redirect URI (backend mode).
|
|
204
|
+
* `mfa_required` means the account has two-factor: collect a code and call `verifyMfa`.
|
|
205
|
+
*/
|
|
206
|
+
async signInWithPassword(credentials, options = {}) {
|
|
207
|
+
return this.authorize({ ...credentials }, options);
|
|
208
|
+
}
|
|
209
|
+
/** Passwordless step 1: emails a 6-digit sign-in code. Always succeeds for unknown emails (no enumeration). */
|
|
210
|
+
async sendEmailCode(email) {
|
|
211
|
+
await this.post("/o/email-code", { client_id: this.config.clientId, email });
|
|
212
|
+
}
|
|
213
|
+
/** Passwordless step 2: signs in with the emailed code. */
|
|
214
|
+
async signInWithEmailCode(input, options = {}) {
|
|
215
|
+
return this.authorize({ email: input.email, otp: input.code }, options);
|
|
216
|
+
}
|
|
217
|
+
/** Second factor: the `mfaToken` and `context` come from the `mfa_required` result. Accepts an authenticator or backup code. */
|
|
218
|
+
async verifyMfa(input, options = {}) {
|
|
219
|
+
const body = await this.post("/o/authorize/mfa", {
|
|
220
|
+
...input.context,
|
|
221
|
+
consent_granted: true,
|
|
222
|
+
mfa_token: input.mfaToken,
|
|
223
|
+
code: input.code.trim()
|
|
224
|
+
});
|
|
225
|
+
return this.finish(body, Boolean(options.backend));
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Creates an account. ZenAuth emails a verification link; the user can sign in after confirming it.
|
|
229
|
+
* `captchaToken` is the Cloudflare Turnstile token (see `<SignUpForm turnstileSiteKey>`).
|
|
230
|
+
*/
|
|
231
|
+
async signUp(input) {
|
|
232
|
+
const body = await this.post("/o/register", { client_id: this.config.clientId, ...input });
|
|
233
|
+
return body.message ?? "Account created. Check your email to verify your address.";
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* "Email me a reset link". The email goes out under YOUR app's name and its link opens your own
|
|
237
|
+
* `/reset-password` page. Always succeeds for unknown emails (no account enumeration).
|
|
238
|
+
*/
|
|
239
|
+
async forgotPassword(input) {
|
|
240
|
+
const body = await this.post("/o/forgot-password", { client_id: this.config.clientId, ...input });
|
|
241
|
+
return body.message ?? "If an account exists for this email, a password reset link has been sent.";
|
|
242
|
+
}
|
|
243
|
+
/** Sets a new password with the token from the reset link. */
|
|
244
|
+
async resetPassword(input) {
|
|
245
|
+
const body = await this.post("/o/reset-password", { client_id: this.config.clientId, ...input });
|
|
246
|
+
return body.message ?? "Password updated. You can now sign in.";
|
|
247
|
+
}
|
|
248
|
+
/** Confirms an email address with the token from the verification link. */
|
|
249
|
+
async verifyEmail(token) {
|
|
250
|
+
const body = await this.post("/o/verify-email", { client_id: this.config.clientId, token });
|
|
251
|
+
return body.message ?? "Email verified. You can now sign in.";
|
|
252
|
+
}
|
|
253
|
+
/** Starts a social sign-in (e.g. Google). The provider has to leave the page; you come back signed in. */
|
|
254
|
+
async signInWithProvider(provider, options = {}) {
|
|
255
|
+
const context = options.context ?? await this.createAuthContext(options.returnTo);
|
|
256
|
+
const url = new URL(`${this.issuer}/api/auth/providers/${encodeURIComponent(provider)}`);
|
|
257
|
+
url.searchParams.set("proxy_state", JSON.stringify(context));
|
|
258
|
+
this.navigate(url.toString());
|
|
259
|
+
}
|
|
260
|
+
/** First step of a credentials sign-in: PKCE context (or the server's), credentials, then finish or ask for MFA. */
|
|
261
|
+
async authorize(credentials, options) {
|
|
262
|
+
const backend = Boolean(options.context);
|
|
263
|
+
const context = options.context ?? await this.createAuthContext(options.returnTo);
|
|
264
|
+
let body;
|
|
265
|
+
try {
|
|
266
|
+
body = await this.post("/o/authorize", { ...context, consent_granted: true, ...credentials }, { allowMfa: true });
|
|
267
|
+
} catch (err) {
|
|
268
|
+
if (!backend) this.clearPending();
|
|
269
|
+
throw err;
|
|
270
|
+
}
|
|
271
|
+
if (body.mfa_required && body.mfa_token) return { status: "mfa_required", mfaToken: body.mfa_token, context };
|
|
272
|
+
return this.finish(body, backend);
|
|
273
|
+
}
|
|
274
|
+
/** Turns an authorization response into a finished sign-in (or the navigation that finishes it). */
|
|
275
|
+
async finish(body, backend) {
|
|
276
|
+
const data = body.data;
|
|
277
|
+
if (!data?.code || !data.redirect_uri) {
|
|
278
|
+
throw new ZenAuthError("invalid_response", "The sign-in response had no authorization code.");
|
|
279
|
+
}
|
|
280
|
+
const redirect = new URL(data.redirect_uri);
|
|
281
|
+
redirect.searchParams.set("code", data.code);
|
|
282
|
+
if (data.state) redirect.searchParams.set("state", data.state);
|
|
283
|
+
if (backend) {
|
|
284
|
+
this.navigate(redirect.toString());
|
|
285
|
+
return { status: "complete" };
|
|
286
|
+
}
|
|
287
|
+
return { status: "complete", returnTo: await this.handleRedirect(redirect.toString()) };
|
|
288
|
+
}
|
|
289
|
+
/** POST JSON to a ZenAuth endpoint; failures become a `ZenAuthError` with the server's message. */
|
|
290
|
+
async post(path, payload, opts = {}) {
|
|
291
|
+
let res;
|
|
292
|
+
try {
|
|
293
|
+
res = await this.fetchFn(`${this.issuer}${path}`, {
|
|
294
|
+
method: "POST",
|
|
295
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
296
|
+
body: JSON.stringify(payload)
|
|
297
|
+
});
|
|
298
|
+
} catch {
|
|
299
|
+
throw new ZenAuthError("network_error", "Could not reach the sign-in service. Check your connection and try again.");
|
|
300
|
+
}
|
|
301
|
+
const body = await res.json().catch(() => ({}));
|
|
302
|
+
if (opts.allowMfa && res.status === 403 && body.mfa_required && body.mfa_token) return body;
|
|
303
|
+
if (!res.ok) throw new ZenAuthError(body.code ?? "request_failed", body.message ?? `Request failed (${res.status}).`);
|
|
304
|
+
return body;
|
|
305
|
+
}
|
|
306
|
+
/** Completes the redirect back from ZenAuth. Returns the `returnTo` path, if any. */
|
|
307
|
+
async handleRedirect(url) {
|
|
308
|
+
const params = new URL(url).searchParams;
|
|
309
|
+
const pending = this.readPending();
|
|
310
|
+
this.clearPending();
|
|
311
|
+
if (!pending) throw new ZenAuthError("no_pending_login", "No sign-in is in progress. Please try again.");
|
|
312
|
+
if (params.get("state") !== pending.state) {
|
|
313
|
+
throw new ZenAuthError("state_mismatch", "The sign-in response did not match your request. Please try again.");
|
|
314
|
+
}
|
|
315
|
+
const error = params.get("error");
|
|
316
|
+
if (error) {
|
|
317
|
+
throw new ZenAuthError(
|
|
318
|
+
error,
|
|
319
|
+
params.get("error_description") ?? (error === "access_denied" ? "Sign-in was cancelled." : "Sign-in failed. Please try again.")
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
const code = params.get("code");
|
|
323
|
+
if (!code) throw new ZenAuthError("invalid_response", "The sign-in response had no authorization code.");
|
|
324
|
+
const tokens = await this.requestTokens({
|
|
325
|
+
grant_type: "authorization_code",
|
|
326
|
+
code,
|
|
327
|
+
redirect_uri: this.config.redirectUri,
|
|
328
|
+
code_verifier: pending.verifier
|
|
329
|
+
});
|
|
330
|
+
if (tokens.idToken) await this.verifyIdToken(tokens.idToken, pending.nonce);
|
|
331
|
+
const loginContext = tokens.idToken ? decodeJwtPayload(tokens.idToken).login_context : void 0;
|
|
332
|
+
const user = {
|
|
333
|
+
...await this.fetchUser(tokens.accessToken),
|
|
334
|
+
...loginContext && { login_context: loginContext }
|
|
335
|
+
};
|
|
336
|
+
this.saveTokens(tokens);
|
|
337
|
+
this.storage.setItem(this.key("user"), JSON.stringify(user));
|
|
338
|
+
this.setState({ status: "authenticated", user, error: null });
|
|
339
|
+
return pending.returnTo;
|
|
340
|
+
}
|
|
341
|
+
// ── Tokens ────────────────────────────────────────────────
|
|
342
|
+
/**
|
|
343
|
+
* A valid access token for calling your own API, refreshed when it is about to expire.
|
|
344
|
+
* `null` means signed out. Throws on transient network failures (the session is kept: retry).
|
|
345
|
+
*/
|
|
346
|
+
async getAccessToken() {
|
|
347
|
+
const tokens = this.readTokens();
|
|
348
|
+
if (!tokens) return null;
|
|
349
|
+
if (tokens.expiresAt - EXPIRY_SKEW_MS > this.now()) return tokens.accessToken;
|
|
350
|
+
return (await this.refreshTokens())?.accessToken ?? null;
|
|
351
|
+
}
|
|
352
|
+
refreshTokens() {
|
|
353
|
+
this.refreshPromise ??= this.doRefresh().finally(() => {
|
|
354
|
+
this.refreshPromise = void 0;
|
|
355
|
+
});
|
|
356
|
+
return this.refreshPromise;
|
|
357
|
+
}
|
|
358
|
+
async doRefresh() {
|
|
359
|
+
const current = this.readTokens();
|
|
360
|
+
if (!current?.refreshToken) {
|
|
361
|
+
this.clearSession();
|
|
362
|
+
this.setState({ status: "unauthenticated", user: null, error: null });
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
try {
|
|
366
|
+
const next = await this.requestTokens({ grant_type: "refresh_token", refresh_token: current.refreshToken });
|
|
367
|
+
const merged = { ...next, refreshToken: next.refreshToken ?? current.refreshToken };
|
|
368
|
+
this.saveTokens(merged);
|
|
369
|
+
return merged;
|
|
370
|
+
} catch (err) {
|
|
371
|
+
if (err instanceof ZenAuthError && TERMINAL_TOKEN_ERRORS.has(err.code)) {
|
|
372
|
+
this.clearSession();
|
|
373
|
+
this.setState({ status: "unauthenticated", user: null, error: "Your session has expired. Please sign in again." });
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
throw err;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async requestTokens(params) {
|
|
380
|
+
const metadata = await this.getMetadata();
|
|
381
|
+
const res = await this.fetchFn(metadata.token_endpoint, {
|
|
382
|
+
method: "POST",
|
|
383
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
384
|
+
body: new URLSearchParams({ client_id: this.config.clientId, ...params })
|
|
385
|
+
});
|
|
386
|
+
const body = await res.json().catch(() => ({}));
|
|
387
|
+
if (!res.ok) {
|
|
388
|
+
throw new ZenAuthError(
|
|
389
|
+
typeof body.error === "string" ? body.error : "token_error",
|
|
390
|
+
String(body.error_description ?? body.message ?? `Token request failed (${res.status})`)
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
if (typeof body.access_token !== "string") {
|
|
394
|
+
throw new ZenAuthError("invalid_response", "The token response had no access token.");
|
|
395
|
+
}
|
|
396
|
+
const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 3600;
|
|
397
|
+
return {
|
|
398
|
+
accessToken: body.access_token,
|
|
399
|
+
refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : void 0,
|
|
400
|
+
idToken: typeof body.id_token === "string" ? body.id_token : void 0,
|
|
401
|
+
scope: typeof body.scope === "string" ? body.scope : void 0,
|
|
402
|
+
expiresAt: this.now() + expiresIn * 1e3
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Checks the claims that bind the token to this login. The token arrives straight from the token
|
|
407
|
+
* endpoint over TLS (OIDC Core 3.1.3.7), so the signature check is not required for this flow.
|
|
408
|
+
*/
|
|
409
|
+
async verifyIdToken(idToken, expectedNonce) {
|
|
410
|
+
const claims = decodeJwtPayload(idToken);
|
|
411
|
+
const metadata = await this.getMetadata();
|
|
412
|
+
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
413
|
+
if (!aud.includes(this.config.clientId)) {
|
|
414
|
+
throw new ZenAuthError("invalid_id_token", "The ID token was issued for a different application.");
|
|
415
|
+
}
|
|
416
|
+
if (metadata.issuer && claims.iss !== metadata.issuer) {
|
|
417
|
+
throw new ZenAuthError("invalid_id_token", "The ID token came from an unexpected issuer.");
|
|
418
|
+
}
|
|
419
|
+
if (claims.nonce !== expectedNonce) {
|
|
420
|
+
throw new ZenAuthError("invalid_id_token", "The ID token nonce did not match. Please try again.");
|
|
421
|
+
}
|
|
422
|
+
if (typeof claims.exp === "number" && claims.exp * 1e3 <= this.now()) {
|
|
423
|
+
throw new ZenAuthError("invalid_id_token", "The ID token has expired.");
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async fetchUser(accessToken) {
|
|
427
|
+
const metadata = await this.getMetadata();
|
|
428
|
+
const res = await this.fetchFn(metadata.userinfo_endpoint, {
|
|
429
|
+
headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" }
|
|
430
|
+
});
|
|
431
|
+
if (res.status === 401) throw new ZenAuthError("invalid_token", "The access token was rejected.");
|
|
432
|
+
const body = await res.json().catch(() => ({}));
|
|
433
|
+
if (!res.ok || typeof body.sub !== "string") {
|
|
434
|
+
throw new ZenAuthError("userinfo_error", `Could not load the user profile (${res.status}).`);
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
sub: body.sub,
|
|
438
|
+
...typeof body.name === "string" && { name: body.name },
|
|
439
|
+
...typeof body.email === "string" && { email: body.email },
|
|
440
|
+
...typeof body.email_verified === "boolean" && { email_verified: body.email_verified },
|
|
441
|
+
...typeof body.role === "string" && { role: body.role },
|
|
442
|
+
...Array.isArray(body.orgs) && { orgs: body.orgs }
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
// ── Sign out ──────────────────────────────────────────────
|
|
446
|
+
/**
|
|
447
|
+
* Ends the local session and revokes the refresh token at ZenAuth (best effort).
|
|
448
|
+
*
|
|
449
|
+
* Pass `endSession` (or `postLogoutRedirectUri`) to also sign out of ZenAuth itself: the browser goes
|
|
450
|
+
* to ZenAuth's logout page and comes back to `postLogoutRedirectUri`, which must be listed under the
|
|
451
|
+
* app's "Logout redirect URIs".
|
|
452
|
+
*/
|
|
453
|
+
async signOut(options = {}) {
|
|
454
|
+
const tokens = this.readTokens();
|
|
455
|
+
this.clearSession();
|
|
456
|
+
this.setState({ status: "unauthenticated", user: null, error: null });
|
|
457
|
+
const endSession = options.endSession ?? Boolean(options.postLogoutRedirectUri);
|
|
458
|
+
if (!tokens?.refreshToken && !endSession) return;
|
|
459
|
+
let metadata;
|
|
460
|
+
try {
|
|
461
|
+
metadata = await this.getMetadata();
|
|
462
|
+
if (tokens?.refreshToken && metadata.revocation_endpoint) {
|
|
463
|
+
await this.fetchFn(metadata.revocation_endpoint, {
|
|
464
|
+
method: "POST",
|
|
465
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
466
|
+
body: new URLSearchParams({ token: tokens.refreshToken, client_id: this.config.clientId })
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
} catch {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (!endSession || !metadata.end_session_endpoint) return;
|
|
473
|
+
const url = new URL(metadata.end_session_endpoint);
|
|
474
|
+
url.searchParams.set("client_id", this.config.clientId);
|
|
475
|
+
if (tokens?.idToken) url.searchParams.set("id_token_hint", tokens.idToken);
|
|
476
|
+
if (options.postLogoutRedirectUri) url.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri);
|
|
477
|
+
this.navigate(url.toString());
|
|
478
|
+
}
|
|
479
|
+
// ── Discovery ─────────────────────────────────────────────
|
|
480
|
+
getMetadata() {
|
|
481
|
+
this.metadataPromise ??= this.loadMetadata().catch((err) => {
|
|
482
|
+
this.metadataPromise = void 0;
|
|
483
|
+
throw err;
|
|
484
|
+
});
|
|
485
|
+
return this.metadataPromise;
|
|
486
|
+
}
|
|
487
|
+
async loadMetadata() {
|
|
488
|
+
const res = await this.fetchFn(`${this.issuer}/.well-known/openid-configuration`, {
|
|
489
|
+
headers: { Accept: "application/json" }
|
|
490
|
+
});
|
|
491
|
+
if (!res.ok) throw new ZenAuthError("discovery_failed", `Could not reach ZenAuth at ${this.issuer} (${res.status}).`);
|
|
492
|
+
const m = await res.json();
|
|
493
|
+
if (!m.authorization_endpoint || !m.token_endpoint || !m.userinfo_endpoint) {
|
|
494
|
+
throw new ZenAuthError("discovery_failed", "ZenAuth returned an incomplete discovery document.");
|
|
495
|
+
}
|
|
496
|
+
return m;
|
|
497
|
+
}
|
|
498
|
+
// ── Storage ───────────────────────────────────────────────
|
|
499
|
+
key = (name) => `zenauth:${this.config.clientId}:${name}`;
|
|
500
|
+
readJson(name) {
|
|
501
|
+
try {
|
|
502
|
+
const raw = this.storage.getItem(this.key(name));
|
|
503
|
+
return raw ? JSON.parse(raw) : null;
|
|
504
|
+
} catch {
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
readTokens() {
|
|
509
|
+
const t = this.readJson("tokens");
|
|
510
|
+
return t && typeof t.accessToken === "string" && typeof t.expiresAt === "number" ? t : null;
|
|
511
|
+
}
|
|
512
|
+
saveTokens(tokens) {
|
|
513
|
+
this.storage.setItem(this.key("tokens"), JSON.stringify(tokens));
|
|
514
|
+
}
|
|
515
|
+
readCachedUser() {
|
|
516
|
+
const u = this.readJson("user");
|
|
517
|
+
return u && typeof u.sub === "string" ? u : null;
|
|
518
|
+
}
|
|
519
|
+
readPending() {
|
|
520
|
+
const p = this.readJson("pending");
|
|
521
|
+
return p && typeof p.state === "string" && typeof p.verifier === "string" && typeof p.nonce === "string" ? p : null;
|
|
522
|
+
}
|
|
523
|
+
writePending(pending) {
|
|
524
|
+
this.storage.setItem(this.key("pending"), JSON.stringify(pending));
|
|
525
|
+
}
|
|
526
|
+
clearPending() {
|
|
527
|
+
this.storage.removeItem(this.key("pending"));
|
|
528
|
+
}
|
|
529
|
+
clearSession() {
|
|
530
|
+
this.storage.removeItem(this.key("tokens"));
|
|
531
|
+
this.storage.removeItem(this.key("user"));
|
|
532
|
+
this.clearPending();
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
// src/react/provider.tsx
|
|
537
|
+
import { jsx } from "react/jsx-runtime";
|
|
538
|
+
var ZenAuthContext = createContext(null);
|
|
539
|
+
var REDIRECT_PARAMS = ["code", "state", "error", "error_description", "iss"];
|
|
540
|
+
function ZenAuthProvider({ children, clientId, redirectUri, issuer, scope, storage }) {
|
|
541
|
+
const client = useMemo(() => new ZenAuthClient({ clientId, redirectUri, issuer, scope, storage }), [clientId, redirectUri, issuer, scope]);
|
|
542
|
+
const state = useSyncExternalStore(client.subscribe, client.getState, client.getServerState);
|
|
543
|
+
useEffect(() => {
|
|
544
|
+
let cancelled = false;
|
|
545
|
+
void client.initialize(window.location.href).then(({ handledRedirect, returnTo }) => {
|
|
546
|
+
if (cancelled || !handledRedirect) return;
|
|
547
|
+
const url = new URL(window.location.href);
|
|
548
|
+
REDIRECT_PARAMS.forEach((p) => url.searchParams.delete(p));
|
|
549
|
+
const target = returnTo ?? `${url.pathname}${url.search}${url.hash}`;
|
|
550
|
+
window.history.replaceState(window.history.state, "", target);
|
|
551
|
+
});
|
|
552
|
+
return () => {
|
|
553
|
+
cancelled = true;
|
|
554
|
+
};
|
|
555
|
+
}, [client]);
|
|
556
|
+
const value = useMemo(
|
|
557
|
+
() => ({
|
|
558
|
+
...state,
|
|
559
|
+
isLoading: state.status === "loading",
|
|
560
|
+
isAuthenticated: state.status === "authenticated",
|
|
561
|
+
signIn: (options) => client.signIn(options),
|
|
562
|
+
signInWithPassword: (credentials, options) => client.signInWithPassword(credentials, options),
|
|
563
|
+
sendEmailCode: (email) => client.sendEmailCode(email),
|
|
564
|
+
signInWithEmailCode: (input, options) => client.signInWithEmailCode(input, options),
|
|
565
|
+
verifyMfa: (input, options) => client.verifyMfa(input, options),
|
|
566
|
+
signUp: (input) => client.signUp(input),
|
|
567
|
+
forgotPassword: (input) => client.forgotPassword(input),
|
|
568
|
+
resetPassword: (input) => client.resetPassword(input),
|
|
569
|
+
verifyEmail: (token) => client.verifyEmail(token),
|
|
570
|
+
signInWithProvider: (provider, options) => client.signInWithProvider(provider, options),
|
|
571
|
+
signOut: (options) => client.signOut(options),
|
|
572
|
+
getAccessToken: () => client.getAccessToken()
|
|
573
|
+
}),
|
|
574
|
+
[client, state]
|
|
575
|
+
);
|
|
576
|
+
return /* @__PURE__ */ jsx(ZenAuthContext.Provider, { value, children });
|
|
577
|
+
}
|
|
578
|
+
function useZenAuth() {
|
|
579
|
+
const ctx = useContext(ZenAuthContext);
|
|
580
|
+
if (!ctx) throw new Error("useZenAuth must be used inside <ZenAuthProvider>");
|
|
581
|
+
return ctx;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// src/react/components.tsx
|
|
585
|
+
import { useEffect as useEffect2, useId, useRef, useState } from "react";
|
|
586
|
+
|
|
587
|
+
// src/react/styles.ts
|
|
588
|
+
import { useInsertionEffect } from "react";
|
|
589
|
+
var STYLE_ID = "zenauth-react-styles";
|
|
590
|
+
var CSS = `
|
|
591
|
+
.zenauth-btn{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;height:2.5rem;padding:0 1.1rem;border:0;border-radius:.65rem;
|
|
592
|
+
font:600 .9rem/1 system-ui,-apple-system,"Segoe UI",sans-serif;color:#fff;cursor:pointer;
|
|
593
|
+
background:linear-gradient(105deg,#fb923c,#f97316 45%,#ea580c);box-shadow:inset 0 1px 0 rgb(255 255 255/.28),0 8px 22px -10px rgb(234 88 12/.75);
|
|
594
|
+
transition:transform .12s ease,box-shadow .2s ease,opacity .2s}
|
|
595
|
+
.zenauth-btn:hover:not(:disabled){transform:translateY(-1px);box-shadow:inset 0 1px 0 rgb(255 255 255/.32),0 12px 28px -10px rgb(234 88 12/.85)}
|
|
596
|
+
.zenauth-btn:active:not(:disabled){transform:translateY(1px) scale(.985)}
|
|
597
|
+
.zenauth-btn:disabled{opacity:.6;cursor:not-allowed}
|
|
598
|
+
.zenauth-btn:focus-visible,.zenauth-avatar:focus-visible,.zenauth-item:focus-visible{outline:2px solid #f97316;outline-offset:2px}
|
|
599
|
+
|
|
600
|
+
.zenauth-user{position:relative;display:inline-block;font:400 .875rem/1.4 system-ui,-apple-system,"Segoe UI",sans-serif;color:#18181b}
|
|
601
|
+
.zenauth-avatar{display:grid;place-items:center;width:2.25rem;height:2.25rem;padding:0;border:2px solid rgb(249 115 22/.55);border-radius:9999px;cursor:pointer;
|
|
602
|
+
background:linear-gradient(135deg,#fb923c,#ea580c);color:#fff;font:700 .8rem/1 system-ui,sans-serif;transition:box-shadow .2s,transform .12s}
|
|
603
|
+
.zenauth-avatar:hover{box-shadow:0 0 0 4px rgb(249 115 22/.18)}
|
|
604
|
+
.zenauth-menu{position:absolute;right:0;top:calc(100% + .5rem);z-index:50;min-width:14.5rem;padding:.4rem;border:1px solid #e4e4e7;border-radius:.9rem;
|
|
605
|
+
background:#fff;color:#18181b;box-shadow:0 18px 50px -12px rgb(0 0 0/.35);animation:zenauth-pop .14s ease-out}
|
|
606
|
+
.zenauth-head{padding:.6rem .7rem .7rem;border-bottom:1px solid #e4e4e7;margin-bottom:.35rem}
|
|
607
|
+
.zenauth-name{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
608
|
+
.zenauth-email{color:#71717a;font-size:.8rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
609
|
+
.zenauth-item{display:block;width:100%;box-sizing:border-box;padding:.55rem .7rem;border:0;border-radius:.55rem;background:none;color:inherit;text-align:left;
|
|
610
|
+
font:inherit;text-decoration:none;cursor:pointer}
|
|
611
|
+
.zenauth-item:hover{background:#f4f4f5}
|
|
612
|
+
@keyframes zenauth-pop{from{opacity:0;transform:translateY(-4px) scale(.98)}to{opacity:1;transform:none}}
|
|
613
|
+
|
|
614
|
+
.zenauth-form{--_primary:var(--zenauth-primary,#f97316);--_muted:var(--zenauth-muted,color-mix(in srgb,currentColor 60%,transparent));
|
|
615
|
+
--_border:var(--zenauth-border,color-mix(in srgb,currentColor 22%,transparent));--_radius:var(--zenauth-radius,.6rem);--_danger:var(--zenauth-danger,#dc2626);
|
|
616
|
+
display:flex;flex-direction:column;gap:1rem;width:100%;box-sizing:border-box;color:var(--zenauth-fg,inherit);font:400 .9rem/1.45 var(--zenauth-font,inherit)}
|
|
617
|
+
.zenauth-form *{box-sizing:border-box}
|
|
618
|
+
.zenauth-form-title{margin:0;font-size:1.4rem;font-weight:650;letter-spacing:-.01em}
|
|
619
|
+
.zenauth-form-subtitle{margin:.25rem 0 0;color:var(--_muted)}
|
|
620
|
+
.zenauth-form form{display:flex;flex-direction:column;gap:.9rem}
|
|
621
|
+
.zenauth-field{display:flex;flex-direction:column;gap:.35rem}
|
|
622
|
+
.zenauth-label-row{display:flex;justify-content:space-between;align-items:baseline}
|
|
623
|
+
.zenauth-label{font-weight:550;font-size:.84rem}
|
|
624
|
+
.zenauth-input{width:100%;height:2.6rem;padding:0 .8rem;border:1px solid var(--_border);border-radius:var(--_radius);background:var(--zenauth-input-bg,transparent);
|
|
625
|
+
color:inherit;font:inherit;transition:border-color .15s,box-shadow .15s}
|
|
626
|
+
.zenauth-input:focus{outline:none;border-color:var(--_primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--_primary) 25%,transparent)}
|
|
627
|
+
.zenauth-password{position:relative}
|
|
628
|
+
.zenauth-password .zenauth-input{padding-right:3.6rem}
|
|
629
|
+
.zenauth-reveal{position:absolute;right:.35rem;top:50%;transform:translateY(-50%);padding:.25rem .5rem;border:0;border-radius:.4rem;background:none;color:var(--_muted);font:inherit;font-size:.78rem;cursor:pointer}
|
|
630
|
+
.zenauth-reveal:hover{color:inherit}
|
|
631
|
+
.zenauth-link{padding:0;border:0;background:none;color:var(--_primary);font:inherit;font-size:.82rem;text-decoration:none;cursor:pointer}
|
|
632
|
+
.zenauth-link:hover{text-decoration:underline}
|
|
633
|
+
.zenauth-submit,.zenauth-provider{display:inline-flex;align-items:center;justify-content:center;width:100%;height:2.6rem;border-radius:var(--_radius);font:inherit;font-weight:600;cursor:pointer;
|
|
634
|
+
transition:opacity .15s,transform .12s,background-color .15s}
|
|
635
|
+
.zenauth-submit{border:0;background:var(--_primary);color:var(--zenauth-primary-fg,#fff)}
|
|
636
|
+
.zenauth-provider{border:1px solid var(--_border);background:var(--zenauth-input-bg,transparent);color:inherit}
|
|
637
|
+
.zenauth-provider:hover:not(:disabled){background:color-mix(in srgb,currentColor 6%,transparent)}
|
|
638
|
+
.zenauth-submit:hover:not(:disabled){opacity:.92}
|
|
639
|
+
.zenauth-submit:active:not(:disabled),.zenauth-provider:active:not(:disabled){transform:scale(.985)}
|
|
640
|
+
.zenauth-submit:disabled,.zenauth-provider:disabled{opacity:.55;cursor:not-allowed}
|
|
641
|
+
.zenauth-submit:focus-visible,.zenauth-provider:focus-visible,.zenauth-link:focus-visible,.zenauth-reveal:focus-visible{outline:2px solid var(--_primary);outline-offset:2px}
|
|
642
|
+
.zenauth-providers{display:flex;flex-direction:column;gap:.5rem}
|
|
643
|
+
.zenauth-divider{display:flex;align-items:center;gap:.75rem;color:var(--_muted);font-size:.8rem}
|
|
644
|
+
.zenauth-divider::before,.zenauth-divider::after{content:"";flex:1;height:1px;background:var(--_border)}
|
|
645
|
+
.zenauth-error{margin:0;padding:.6rem .75rem;border-radius:var(--_radius);border:1px solid color-mix(in srgb,var(--_danger) 40%,transparent);
|
|
646
|
+
background:color-mix(in srgb,var(--_danger) 10%,transparent);color:var(--_danger);font-size:.84rem}
|
|
647
|
+
.zenauth-notice{margin:0;padding:.6rem .75rem;border-radius:var(--_radius);border:1px solid var(--_border);
|
|
648
|
+
background:color-mix(in srgb,var(--_primary) 8%,transparent);font-size:.84rem}
|
|
649
|
+
.zenauth-row{display:flex;justify-content:space-between;gap:1rem}
|
|
650
|
+
.zenauth-link:disabled{opacity:.5;cursor:not-allowed}
|
|
651
|
+
.zenauth-captcha{min-height:65px}
|
|
652
|
+
.zenauth-form-footer{text-align:center;color:var(--_muted);font-size:.85rem}
|
|
653
|
+
@media (prefers-reduced-motion:reduce){.zenauth-submit,.zenauth-input{transition:none}}
|
|
654
|
+
|
|
655
|
+
@media (prefers-color-scheme:dark){
|
|
656
|
+
.zenauth-user{color:#fafafa}
|
|
657
|
+
.zenauth-menu{background:#18181b;color:#fafafa;border-color:#3f3f46}
|
|
658
|
+
.zenauth-head{border-color:#3f3f46}
|
|
659
|
+
.zenauth-email{color:#a1a1aa}
|
|
660
|
+
.zenauth-item:hover{background:#27272a}
|
|
661
|
+
}
|
|
662
|
+
@media (prefers-reduced-motion:reduce){.zenauth-menu{animation:none}.zenauth-btn{transition:none}}
|
|
663
|
+
`;
|
|
664
|
+
function useZenAuthStyles() {
|
|
665
|
+
useInsertionEffect(() => {
|
|
666
|
+
if (typeof document === "undefined" || document.getElementById(STYLE_ID)) return;
|
|
667
|
+
const el = document.createElement("style");
|
|
668
|
+
el.id = STYLE_ID;
|
|
669
|
+
el.textContent = CSS;
|
|
670
|
+
document.head.appendChild(el);
|
|
671
|
+
}, []);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// src/react/components.tsx
|
|
675
|
+
import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
676
|
+
function SignedIn({ children }) {
|
|
677
|
+
const { isAuthenticated } = useZenAuth();
|
|
678
|
+
return isAuthenticated ? /* @__PURE__ */ jsx2(Fragment, { children }) : null;
|
|
679
|
+
}
|
|
680
|
+
function SignedOut({ children }) {
|
|
681
|
+
const { status } = useZenAuth();
|
|
682
|
+
return status === "unauthenticated" ? /* @__PURE__ */ jsx2(Fragment, { children }) : null;
|
|
683
|
+
}
|
|
684
|
+
function SignIn({ children = "Sign in with ZenAuth", className, returnTo }) {
|
|
685
|
+
useZenAuthStyles();
|
|
686
|
+
const { signIn, isLoading, error } = useZenAuth();
|
|
687
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
688
|
+
/* @__PURE__ */ jsx2(
|
|
689
|
+
"button",
|
|
690
|
+
{
|
|
691
|
+
type: "button",
|
|
692
|
+
className: className ?? "zenauth-btn",
|
|
693
|
+
disabled: isLoading,
|
|
694
|
+
onClick: () => void signIn({ returnTo }),
|
|
695
|
+
children
|
|
696
|
+
}
|
|
697
|
+
),
|
|
698
|
+
error && /* @__PURE__ */ jsx2("p", { role: "alert", style: { margin: ".5rem 0 0", color: "#dc2626", fontSize: ".85rem" }, children: error })
|
|
699
|
+
] });
|
|
700
|
+
}
|
|
701
|
+
var initialsOf = (name, email) => {
|
|
702
|
+
const source = (name?.trim() || email?.split("@")[0] || "?").trim();
|
|
703
|
+
const parts = source.split(/\s+/).filter(Boolean);
|
|
704
|
+
const letters = parts.length > 1 ? `${parts[0][0]}${parts[parts.length - 1][0]}` : source.slice(0, 2);
|
|
705
|
+
return letters.toUpperCase();
|
|
706
|
+
};
|
|
707
|
+
function UserButton({ accountUrl, afterSignOutUrl }) {
|
|
708
|
+
useZenAuthStyles();
|
|
709
|
+
const { user, isAuthenticated, signOut } = useZenAuth();
|
|
710
|
+
const [open, setOpen] = useState(false);
|
|
711
|
+
const rootRef = useRef(null);
|
|
712
|
+
const menuId = useId();
|
|
713
|
+
useEffect2(() => {
|
|
714
|
+
if (!open) return;
|
|
715
|
+
const onPointerDown = (e) => {
|
|
716
|
+
if (!rootRef.current?.contains(e.target)) setOpen(false);
|
|
717
|
+
};
|
|
718
|
+
const onKeyDown = (e) => {
|
|
719
|
+
if (e.key === "Escape") setOpen(false);
|
|
720
|
+
};
|
|
721
|
+
document.addEventListener("pointerdown", onPointerDown);
|
|
722
|
+
document.addEventListener("keydown", onKeyDown);
|
|
723
|
+
return () => {
|
|
724
|
+
document.removeEventListener("pointerdown", onPointerDown);
|
|
725
|
+
document.removeEventListener("keydown", onKeyDown);
|
|
726
|
+
};
|
|
727
|
+
}, [open]);
|
|
728
|
+
if (!isAuthenticated || !user) return null;
|
|
729
|
+
const handleSignOut = async () => {
|
|
730
|
+
setOpen(false);
|
|
731
|
+
await signOut();
|
|
732
|
+
if (afterSignOutUrl) window.location.assign(afterSignOutUrl);
|
|
733
|
+
};
|
|
734
|
+
return /* @__PURE__ */ jsxs("div", { className: "zenauth-user", ref: rootRef, children: [
|
|
735
|
+
/* @__PURE__ */ jsx2(
|
|
736
|
+
"button",
|
|
737
|
+
{
|
|
738
|
+
type: "button",
|
|
739
|
+
className: "zenauth-avatar",
|
|
740
|
+
"aria-label": "Account menu",
|
|
741
|
+
"aria-haspopup": "menu",
|
|
742
|
+
"aria-expanded": open,
|
|
743
|
+
"aria-controls": open ? menuId : void 0,
|
|
744
|
+
onClick: () => setOpen((v) => !v),
|
|
745
|
+
children: initialsOf(user.name, user.email)
|
|
746
|
+
}
|
|
747
|
+
),
|
|
748
|
+
open && /* @__PURE__ */ jsxs("div", { id: menuId, role: "menu", className: "zenauth-menu", children: [
|
|
749
|
+
/* @__PURE__ */ jsxs("div", { className: "zenauth-head", children: [
|
|
750
|
+
user.name && /* @__PURE__ */ jsx2("div", { className: "zenauth-name", children: user.name }),
|
|
751
|
+
user.email && /* @__PURE__ */ jsx2("div", { className: "zenauth-email", children: user.email })
|
|
752
|
+
] }),
|
|
753
|
+
accountUrl && /* @__PURE__ */ jsx2("a", { role: "menuitem", className: "zenauth-item", href: accountUrl, target: "_blank", rel: "noreferrer", children: "Manage account" }),
|
|
754
|
+
/* @__PURE__ */ jsx2("button", { type: "button", role: "menuitem", className: "zenauth-item", onClick: () => void handleSignOut(), children: "Sign out" })
|
|
755
|
+
] })
|
|
756
|
+
] });
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// src/react/sign-in-form.tsx
|
|
760
|
+
import { useId as useId3, useState as useState3 } from "react";
|
|
761
|
+
|
|
762
|
+
// src/react/form-utils.tsx
|
|
763
|
+
import { useEffect as useEffect3, useId as useId2, useRef as useRef2, useState as useState2 } from "react";
|
|
764
|
+
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
765
|
+
var cx = (...parts) => parts.filter(Boolean).join(" ");
|
|
766
|
+
var cssVariables = (v) => {
|
|
767
|
+
const map = {
|
|
768
|
+
"--zenauth-primary": v?.primary,
|
|
769
|
+
"--zenauth-primary-fg": v?.primaryForeground,
|
|
770
|
+
"--zenauth-fg": v?.foreground,
|
|
771
|
+
"--zenauth-muted": v?.muted,
|
|
772
|
+
"--zenauth-input-bg": v?.inputBackground,
|
|
773
|
+
"--zenauth-border": v?.border,
|
|
774
|
+
"--zenauth-danger": v?.danger,
|
|
775
|
+
"--zenauth-radius": v?.radius,
|
|
776
|
+
"--zenauth-font": v?.fontFamily
|
|
777
|
+
};
|
|
778
|
+
return Object.fromEntries(Object.entries(map).filter(([, value]) => value));
|
|
779
|
+
};
|
|
780
|
+
var errorMessage = (err) => err instanceof Error ? err.message : "Something went wrong. Please try again.";
|
|
781
|
+
function Field({ label, value, onChange, type = "text", appearance, aside, describedBy, ...rest }) {
|
|
782
|
+
const id = useId2();
|
|
783
|
+
const cls = appearance?.classNames ?? {};
|
|
784
|
+
return /* @__PURE__ */ jsxs2("div", { className: cx("zenauth-field", cls.field), children: [
|
|
785
|
+
/* @__PURE__ */ jsxs2("div", { className: "zenauth-label-row", children: [
|
|
786
|
+
/* @__PURE__ */ jsx3("label", { htmlFor: id, className: cx("zenauth-label", cls.label), children: label }),
|
|
787
|
+
aside
|
|
788
|
+
] }),
|
|
789
|
+
/* @__PURE__ */ jsx3(
|
|
790
|
+
"input",
|
|
791
|
+
{
|
|
792
|
+
id,
|
|
793
|
+
className: cx("zenauth-input", cls.input),
|
|
794
|
+
type,
|
|
795
|
+
required: true,
|
|
796
|
+
value,
|
|
797
|
+
onChange: (e) => onChange(e.target.value),
|
|
798
|
+
"aria-describedby": describedBy,
|
|
799
|
+
autoCapitalize: "none",
|
|
800
|
+
spellCheck: false,
|
|
801
|
+
...rest
|
|
802
|
+
}
|
|
803
|
+
)
|
|
804
|
+
] });
|
|
805
|
+
}
|
|
806
|
+
function PasswordField({
|
|
807
|
+
label = "Password",
|
|
808
|
+
autoComplete = "current-password",
|
|
809
|
+
appearance,
|
|
810
|
+
aside,
|
|
811
|
+
describedBy,
|
|
812
|
+
value,
|
|
813
|
+
onChange
|
|
814
|
+
}) {
|
|
815
|
+
const id = useId2();
|
|
816
|
+
const [show, setShow] = useState2(false);
|
|
817
|
+
const cls = appearance?.classNames ?? {};
|
|
818
|
+
return /* @__PURE__ */ jsxs2("div", { className: cx("zenauth-field", cls.field), children: [
|
|
819
|
+
/* @__PURE__ */ jsxs2("div", { className: "zenauth-label-row", children: [
|
|
820
|
+
/* @__PURE__ */ jsx3("label", { htmlFor: id, className: cx("zenauth-label", cls.label), children: label }),
|
|
821
|
+
aside
|
|
822
|
+
] }),
|
|
823
|
+
/* @__PURE__ */ jsxs2("div", { className: "zenauth-password", children: [
|
|
824
|
+
/* @__PURE__ */ jsx3(
|
|
825
|
+
"input",
|
|
826
|
+
{
|
|
827
|
+
id,
|
|
828
|
+
className: cx("zenauth-input", cls.input),
|
|
829
|
+
type: show ? "text" : "password",
|
|
830
|
+
autoComplete,
|
|
831
|
+
required: true,
|
|
832
|
+
value,
|
|
833
|
+
onChange: (e) => onChange(e.target.value),
|
|
834
|
+
"aria-describedby": describedBy
|
|
835
|
+
}
|
|
836
|
+
),
|
|
837
|
+
/* @__PURE__ */ jsx3(
|
|
838
|
+
"button",
|
|
839
|
+
{
|
|
840
|
+
type: "button",
|
|
841
|
+
className: "zenauth-reveal",
|
|
842
|
+
onClick: () => setShow((s) => !s),
|
|
843
|
+
"aria-label": show ? "Hide password" : "Show password",
|
|
844
|
+
"aria-pressed": show,
|
|
845
|
+
children: show ? "Hide" : "Show"
|
|
846
|
+
}
|
|
847
|
+
)
|
|
848
|
+
] })
|
|
849
|
+
] });
|
|
850
|
+
}
|
|
851
|
+
var TURNSTILE_SRC = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
|
852
|
+
var turnstileLoading;
|
|
853
|
+
var loadTurnstile = () => {
|
|
854
|
+
if (typeof window === "undefined") return Promise.reject(new Error("Turnstile needs a browser"));
|
|
855
|
+
if (window.turnstile) return Promise.resolve();
|
|
856
|
+
turnstileLoading ??= new Promise((resolve, reject) => {
|
|
857
|
+
const script = document.createElement("script");
|
|
858
|
+
script.src = TURNSTILE_SRC;
|
|
859
|
+
script.async = true;
|
|
860
|
+
script.onload = () => resolve();
|
|
861
|
+
script.onerror = () => {
|
|
862
|
+
turnstileLoading = void 0;
|
|
863
|
+
reject(new Error("Could not load the anti-bot check."));
|
|
864
|
+
};
|
|
865
|
+
document.head.appendChild(script);
|
|
866
|
+
});
|
|
867
|
+
return turnstileLoading;
|
|
868
|
+
};
|
|
869
|
+
function useTurnstile(siteKey) {
|
|
870
|
+
const ref = useRef2(null);
|
|
871
|
+
const widgetId = useRef2(void 0);
|
|
872
|
+
const [token, setToken] = useState2(null);
|
|
873
|
+
const [failed, setFailed] = useState2(null);
|
|
874
|
+
useEffect3(() => {
|
|
875
|
+
if (!siteKey) return;
|
|
876
|
+
let cancelled = false;
|
|
877
|
+
loadTurnstile().then(() => {
|
|
878
|
+
if (cancelled || !ref.current || !window.turnstile) return;
|
|
879
|
+
widgetId.current = window.turnstile.render(ref.current, {
|
|
880
|
+
sitekey: siteKey,
|
|
881
|
+
callback: (t) => setToken(t),
|
|
882
|
+
"expired-callback": () => setToken(null),
|
|
883
|
+
"error-callback": () => setFailed("The anti-bot check failed to load. Refresh and try again.")
|
|
884
|
+
});
|
|
885
|
+
}).catch((err) => setFailed(err.message));
|
|
886
|
+
return () => {
|
|
887
|
+
cancelled = true;
|
|
888
|
+
if (widgetId.current) window.turnstile?.remove(widgetId.current);
|
|
889
|
+
widgetId.current = void 0;
|
|
890
|
+
};
|
|
891
|
+
}, [siteKey]);
|
|
892
|
+
const reset = () => {
|
|
893
|
+
setToken(null);
|
|
894
|
+
if (widgetId.current) window.turnstile?.reset(widgetId.current);
|
|
895
|
+
};
|
|
896
|
+
return { ref, token, failed, reset };
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// src/react/sign-in-form.tsx
|
|
900
|
+
import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
901
|
+
var PROVIDER_LABELS = { google: "Google", github: "GitHub" };
|
|
902
|
+
function SignInForm({
|
|
903
|
+
returnTo,
|
|
904
|
+
onSuccess,
|
|
905
|
+
getAuthContext,
|
|
906
|
+
providers = [],
|
|
907
|
+
emailCode = false,
|
|
908
|
+
title = "Sign in",
|
|
909
|
+
subtitle,
|
|
910
|
+
submitLabel = "Continue",
|
|
911
|
+
forgotPasswordHref,
|
|
912
|
+
footer,
|
|
913
|
+
appearance
|
|
914
|
+
}) {
|
|
915
|
+
useZenAuthStyles();
|
|
916
|
+
const { signInWithPassword, signInWithEmailCode, sendEmailCode, verifyMfa, signInWithProvider } = useZenAuth();
|
|
917
|
+
const errorId = useId3();
|
|
918
|
+
const cls = appearance?.classNames ?? {};
|
|
919
|
+
const backend = Boolean(getAuthContext);
|
|
920
|
+
const [step, setStep] = useState3("credentials");
|
|
921
|
+
const [mode, setMode] = useState3("password");
|
|
922
|
+
const [identifier, setIdentifier] = useState3("");
|
|
923
|
+
const [password, setPassword] = useState3("");
|
|
924
|
+
const [code, setCode] = useState3("");
|
|
925
|
+
const [mfa, setMfa] = useState3(null);
|
|
926
|
+
const [pending, setPending] = useState3(null);
|
|
927
|
+
const [error, setError] = useState3(null);
|
|
928
|
+
const [notice, setNotice] = useState3(null);
|
|
929
|
+
const run = async (kind, task) => {
|
|
930
|
+
setError(null);
|
|
931
|
+
setNotice(null);
|
|
932
|
+
setPending(kind);
|
|
933
|
+
try {
|
|
934
|
+
await task();
|
|
935
|
+
} catch (err) {
|
|
936
|
+
setError(errorMessage(err));
|
|
937
|
+
setPending(null);
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
const handleResult = (result) => {
|
|
941
|
+
if (result.status === "mfa_required") {
|
|
942
|
+
setMfa({ token: result.mfaToken, context: result.context });
|
|
943
|
+
setCode("");
|
|
944
|
+
setStep("mfa");
|
|
945
|
+
setPending(null);
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (!backend) {
|
|
949
|
+
setPending(null);
|
|
950
|
+
onSuccess?.(result.returnTo);
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
const credentialsFor = (value) => value.includes("@") ? { email: value } : { username: value };
|
|
954
|
+
const submitPassword = (e) => {
|
|
955
|
+
e.preventDefault();
|
|
956
|
+
if (pending) return;
|
|
957
|
+
void run("submit", async () => {
|
|
958
|
+
const context = getAuthContext ? await getAuthContext() : void 0;
|
|
959
|
+
handleResult(
|
|
960
|
+
await signInWithPassword({ ...credentialsFor(identifier.trim()), password }, { returnTo, context })
|
|
961
|
+
);
|
|
962
|
+
});
|
|
963
|
+
};
|
|
964
|
+
const requestCode = (e) => {
|
|
965
|
+
e?.preventDefault();
|
|
966
|
+
if (pending) return;
|
|
967
|
+
void run("submit", async () => {
|
|
968
|
+
await sendEmailCode(identifier.trim());
|
|
969
|
+
setCode("");
|
|
970
|
+
setStep("code");
|
|
971
|
+
setNotice(`If an account exists for ${identifier.trim()}, we sent a 6-digit code to it.`);
|
|
972
|
+
setPending(null);
|
|
973
|
+
});
|
|
974
|
+
};
|
|
975
|
+
const submitCode = (e) => {
|
|
976
|
+
e.preventDefault();
|
|
977
|
+
if (pending) return;
|
|
978
|
+
void run("submit", async () => {
|
|
979
|
+
const context = getAuthContext ? await getAuthContext() : void 0;
|
|
980
|
+
handleResult(await signInWithEmailCode({ email: identifier.trim(), code: code.trim() }, { returnTo, context }));
|
|
981
|
+
});
|
|
982
|
+
};
|
|
983
|
+
const submitMfa = (e) => {
|
|
984
|
+
e.preventDefault();
|
|
985
|
+
if (pending || !mfa) return;
|
|
986
|
+
void run("submit", async () => {
|
|
987
|
+
handleResult(await verifyMfa({ mfaToken: mfa.token, code, context: mfa.context }, { returnTo, backend }));
|
|
988
|
+
});
|
|
989
|
+
};
|
|
990
|
+
const social = (provider) => void run(provider, async () => {
|
|
991
|
+
const context = getAuthContext ? await getAuthContext() : void 0;
|
|
992
|
+
await signInWithProvider(provider, { returnTo, context });
|
|
993
|
+
});
|
|
994
|
+
const back = () => {
|
|
995
|
+
setStep("credentials");
|
|
996
|
+
setMfa(null);
|
|
997
|
+
setCode("");
|
|
998
|
+
setError(null);
|
|
999
|
+
setNotice(null);
|
|
1000
|
+
};
|
|
1001
|
+
const errorBlock = error && /* @__PURE__ */ jsx4("p", { id: errorId, role: "alert", className: cx("zenauth-error", cls.error), children: error });
|
|
1002
|
+
const noticeBlock = notice && /* @__PURE__ */ jsx4("p", { role: "status", className: cx("zenauth-notice", cls.success), children: notice });
|
|
1003
|
+
const busy = pending !== null;
|
|
1004
|
+
if (step === "mfa") {
|
|
1005
|
+
return /* @__PURE__ */ jsxs3("div", { className: cx("zenauth-form", cls.root), style: cssVariables(appearance?.variables), "data-zenauth": "sign-in-mfa", children: [
|
|
1006
|
+
/* @__PURE__ */ jsxs3("header", { children: [
|
|
1007
|
+
/* @__PURE__ */ jsx4("h2", { className: cx("zenauth-form-title", cls.title), children: "Two-step verification" }),
|
|
1008
|
+
/* @__PURE__ */ jsx4("p", { className: cx("zenauth-form-subtitle", cls.subtitle), children: "Enter the 6-digit code from your authenticator app, or one of your 8-character backup codes." })
|
|
1009
|
+
] }),
|
|
1010
|
+
/* @__PURE__ */ jsxs3("form", { onSubmit: submitMfa, noValidate: true, children: [
|
|
1011
|
+
/* @__PURE__ */ jsx4(
|
|
1012
|
+
Field,
|
|
1013
|
+
{
|
|
1014
|
+
label: "Authentication code",
|
|
1015
|
+
value: code,
|
|
1016
|
+
onChange: setCode,
|
|
1017
|
+
autoComplete: "one-time-code",
|
|
1018
|
+
inputMode: "text",
|
|
1019
|
+
maxLength: 8,
|
|
1020
|
+
describedBy: error ? errorId : void 0,
|
|
1021
|
+
appearance,
|
|
1022
|
+
autoFocus: true
|
|
1023
|
+
}
|
|
1024
|
+
),
|
|
1025
|
+
errorBlock,
|
|
1026
|
+
/* @__PURE__ */ jsx4("button", { type: "submit", className: cx("zenauth-submit", cls.button), disabled: busy || code.trim().length < 6, children: busy ? "Verifying\u2026" : "Verify" }),
|
|
1027
|
+
/* @__PURE__ */ jsx4("button", { type: "button", className: cx("zenauth-link", cls.link), onClick: back, children: "Back to sign in" })
|
|
1028
|
+
] })
|
|
1029
|
+
] });
|
|
1030
|
+
}
|
|
1031
|
+
if (step === "code") {
|
|
1032
|
+
return /* @__PURE__ */ jsxs3("div", { className: cx("zenauth-form", cls.root), style: cssVariables(appearance?.variables), "data-zenauth": "sign-in-code", children: [
|
|
1033
|
+
/* @__PURE__ */ jsxs3("header", { children: [
|
|
1034
|
+
/* @__PURE__ */ jsx4("h2", { className: cx("zenauth-form-title", cls.title), children: "Check your email" }),
|
|
1035
|
+
/* @__PURE__ */ jsx4("p", { className: cx("zenauth-form-subtitle", cls.subtitle), children: "Enter the 6-digit code we sent you." })
|
|
1036
|
+
] }),
|
|
1037
|
+
/* @__PURE__ */ jsxs3("form", { onSubmit: submitCode, noValidate: true, children: [
|
|
1038
|
+
/* @__PURE__ */ jsx4(
|
|
1039
|
+
Field,
|
|
1040
|
+
{
|
|
1041
|
+
label: "Sign-in code",
|
|
1042
|
+
value: code,
|
|
1043
|
+
onChange: (v) => setCode(v.replace(/\D/g, "")),
|
|
1044
|
+
autoComplete: "one-time-code",
|
|
1045
|
+
inputMode: "numeric",
|
|
1046
|
+
maxLength: 6,
|
|
1047
|
+
describedBy: error ? errorId : void 0,
|
|
1048
|
+
appearance,
|
|
1049
|
+
autoFocus: true
|
|
1050
|
+
}
|
|
1051
|
+
),
|
|
1052
|
+
noticeBlock,
|
|
1053
|
+
errorBlock,
|
|
1054
|
+
/* @__PURE__ */ jsx4("button", { type: "submit", className: cx("zenauth-submit", cls.button), disabled: busy || code.length !== 6, children: busy ? "Signing in\u2026" : "Sign in" }),
|
|
1055
|
+
/* @__PURE__ */ jsxs3("div", { className: "zenauth-row", children: [
|
|
1056
|
+
/* @__PURE__ */ jsx4("button", { type: "button", className: cx("zenauth-link", cls.link), disabled: busy, onClick: () => requestCode(), children: "Resend code" }),
|
|
1057
|
+
/* @__PURE__ */ jsx4("button", { type: "button", className: cx("zenauth-link", cls.link), onClick: back, children: "Use a different method" })
|
|
1058
|
+
] })
|
|
1059
|
+
] })
|
|
1060
|
+
] });
|
|
1061
|
+
}
|
|
1062
|
+
const passwordless = mode === "code";
|
|
1063
|
+
return /* @__PURE__ */ jsxs3("div", { className: cx("zenauth-form", cls.root), style: cssVariables(appearance?.variables), "data-zenauth": "sign-in", children: [
|
|
1064
|
+
(title || subtitle) && /* @__PURE__ */ jsxs3("header", { children: [
|
|
1065
|
+
title && /* @__PURE__ */ jsx4("h2", { className: cx("zenauth-form-title", cls.title), children: title }),
|
|
1066
|
+
subtitle && /* @__PURE__ */ jsx4("p", { className: cx("zenauth-form-subtitle", cls.subtitle), children: subtitle })
|
|
1067
|
+
] }),
|
|
1068
|
+
providers.length > 0 && /* @__PURE__ */ jsxs3(Fragment2, { children: [
|
|
1069
|
+
/* @__PURE__ */ jsx4("div", { className: "zenauth-providers", children: providers.map((p) => /* @__PURE__ */ jsx4(
|
|
1070
|
+
"button",
|
|
1071
|
+
{
|
|
1072
|
+
type: "button",
|
|
1073
|
+
className: cx("zenauth-provider", cls.providerButton),
|
|
1074
|
+
disabled: busy,
|
|
1075
|
+
onClick: () => social(p),
|
|
1076
|
+
children: pending === p ? "Redirecting\u2026" : `Continue with ${PROVIDER_LABELS[p] ?? p}`
|
|
1077
|
+
},
|
|
1078
|
+
p
|
|
1079
|
+
)) }),
|
|
1080
|
+
/* @__PURE__ */ jsx4("div", { className: cx("zenauth-divider", cls.divider), role: "separator", children: /* @__PURE__ */ jsx4("span", { children: "or" }) })
|
|
1081
|
+
] }),
|
|
1082
|
+
/* @__PURE__ */ jsxs3("form", { onSubmit: passwordless ? requestCode : submitPassword, noValidate: true, children: [
|
|
1083
|
+
/* @__PURE__ */ jsx4(
|
|
1084
|
+
Field,
|
|
1085
|
+
{
|
|
1086
|
+
label: "Email address",
|
|
1087
|
+
value: identifier,
|
|
1088
|
+
onChange: setIdentifier,
|
|
1089
|
+
autoComplete: "username",
|
|
1090
|
+
inputMode: "email",
|
|
1091
|
+
describedBy: error ? errorId : void 0,
|
|
1092
|
+
appearance
|
|
1093
|
+
}
|
|
1094
|
+
),
|
|
1095
|
+
!passwordless && /* @__PURE__ */ jsx4(
|
|
1096
|
+
PasswordField,
|
|
1097
|
+
{
|
|
1098
|
+
value: password,
|
|
1099
|
+
onChange: setPassword,
|
|
1100
|
+
describedBy: error ? errorId : void 0,
|
|
1101
|
+
appearance,
|
|
1102
|
+
aside: forgotPasswordHref && /* @__PURE__ */ jsx4("a", { href: forgotPasswordHref, className: cx("zenauth-link", cls.link), children: "Forgot password?" })
|
|
1103
|
+
}
|
|
1104
|
+
),
|
|
1105
|
+
errorBlock,
|
|
1106
|
+
/* @__PURE__ */ jsx4(
|
|
1107
|
+
"button",
|
|
1108
|
+
{
|
|
1109
|
+
type: "submit",
|
|
1110
|
+
className: cx("zenauth-submit", cls.button),
|
|
1111
|
+
disabled: busy || !identifier || !passwordless && !password,
|
|
1112
|
+
children: busy ? passwordless ? "Sending\u2026" : "Signing in\u2026" : passwordless ? "Email me a code" : submitLabel
|
|
1113
|
+
}
|
|
1114
|
+
),
|
|
1115
|
+
emailCode && /* @__PURE__ */ jsx4(
|
|
1116
|
+
"button",
|
|
1117
|
+
{
|
|
1118
|
+
type: "button",
|
|
1119
|
+
className: cx("zenauth-link", cls.link),
|
|
1120
|
+
onClick: () => {
|
|
1121
|
+
setMode(passwordless ? "password" : "code");
|
|
1122
|
+
setError(null);
|
|
1123
|
+
},
|
|
1124
|
+
children: passwordless ? "Use your password instead" : "Email me a sign-in code instead"
|
|
1125
|
+
}
|
|
1126
|
+
)
|
|
1127
|
+
] }),
|
|
1128
|
+
footer && /* @__PURE__ */ jsx4("div", { className: "zenauth-form-footer", children: footer })
|
|
1129
|
+
] });
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// src/react/sign-up-form.tsx
|
|
1133
|
+
import { useId as useId4, useState as useState4 } from "react";
|
|
1134
|
+
import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
|
|
1135
|
+
function SignUpForm({
|
|
1136
|
+
turnstileSiteKey,
|
|
1137
|
+
onSuccess,
|
|
1138
|
+
title = "Create your account",
|
|
1139
|
+
subtitle,
|
|
1140
|
+
submitLabel = "Create account",
|
|
1141
|
+
footer,
|
|
1142
|
+
appearance
|
|
1143
|
+
}) {
|
|
1144
|
+
useZenAuthStyles();
|
|
1145
|
+
const { signUp } = useZenAuth();
|
|
1146
|
+
const errorId = useId4();
|
|
1147
|
+
const cls = appearance?.classNames ?? {};
|
|
1148
|
+
const captcha = useTurnstile(turnstileSiteKey);
|
|
1149
|
+
const [name, setName] = useState4("");
|
|
1150
|
+
const [email, setEmail] = useState4("");
|
|
1151
|
+
const [password, setPassword] = useState4("");
|
|
1152
|
+
const [pending, setPending] = useState4(false);
|
|
1153
|
+
const [error, setError] = useState4(null);
|
|
1154
|
+
const [done, setDone] = useState4(null);
|
|
1155
|
+
const submit = async (e) => {
|
|
1156
|
+
e.preventDefault();
|
|
1157
|
+
if (pending) return;
|
|
1158
|
+
setError(null);
|
|
1159
|
+
setPending(true);
|
|
1160
|
+
try {
|
|
1161
|
+
const message = await signUp({
|
|
1162
|
+
name: name.trim(),
|
|
1163
|
+
email: email.trim(),
|
|
1164
|
+
password,
|
|
1165
|
+
captchaToken: captcha.token ?? void 0
|
|
1166
|
+
});
|
|
1167
|
+
setDone(message);
|
|
1168
|
+
onSuccess?.(message);
|
|
1169
|
+
} catch (err) {
|
|
1170
|
+
setError(errorMessage(err));
|
|
1171
|
+
captcha.reset();
|
|
1172
|
+
} finally {
|
|
1173
|
+
setPending(false);
|
|
1174
|
+
}
|
|
1175
|
+
};
|
|
1176
|
+
const style = cssVariables(appearance?.variables);
|
|
1177
|
+
if (done) {
|
|
1178
|
+
return /* @__PURE__ */ jsxs4("div", { className: cx("zenauth-form", cls.root), style, "data-zenauth": "sign-up-done", children: [
|
|
1179
|
+
/* @__PURE__ */ jsx5("header", { children: /* @__PURE__ */ jsx5("h2", { className: cx("zenauth-form-title", cls.title), children: "Check your email" }) }),
|
|
1180
|
+
/* @__PURE__ */ jsx5("p", { role: "status", className: cx("zenauth-notice", cls.success), children: done }),
|
|
1181
|
+
footer && /* @__PURE__ */ jsx5("div", { className: "zenauth-form-footer", children: footer })
|
|
1182
|
+
] });
|
|
1183
|
+
}
|
|
1184
|
+
const needsCaptcha = Boolean(turnstileSiteKey);
|
|
1185
|
+
return /* @__PURE__ */ jsxs4("div", { className: cx("zenauth-form", cls.root), style, "data-zenauth": "sign-up", children: [
|
|
1186
|
+
(title || subtitle) && /* @__PURE__ */ jsxs4("header", { children: [
|
|
1187
|
+
title && /* @__PURE__ */ jsx5("h2", { className: cx("zenauth-form-title", cls.title), children: title }),
|
|
1188
|
+
subtitle && /* @__PURE__ */ jsx5("p", { className: cx("zenauth-form-subtitle", cls.subtitle), children: subtitle })
|
|
1189
|
+
] }),
|
|
1190
|
+
/* @__PURE__ */ jsxs4("form", { onSubmit: (e) => void submit(e), noValidate: true, children: [
|
|
1191
|
+
/* @__PURE__ */ jsx5(Field, { label: "Full name", value: name, onChange: setName, autoComplete: "name", appearance }),
|
|
1192
|
+
/* @__PURE__ */ jsx5(
|
|
1193
|
+
Field,
|
|
1194
|
+
{
|
|
1195
|
+
label: "Email address",
|
|
1196
|
+
value: email,
|
|
1197
|
+
onChange: setEmail,
|
|
1198
|
+
autoComplete: "email",
|
|
1199
|
+
inputMode: "email",
|
|
1200
|
+
describedBy: error ? errorId : void 0,
|
|
1201
|
+
appearance
|
|
1202
|
+
}
|
|
1203
|
+
),
|
|
1204
|
+
/* @__PURE__ */ jsx5(
|
|
1205
|
+
PasswordField,
|
|
1206
|
+
{
|
|
1207
|
+
label: "Password",
|
|
1208
|
+
autoComplete: "new-password",
|
|
1209
|
+
value: password,
|
|
1210
|
+
onChange: setPassword,
|
|
1211
|
+
describedBy: error ? errorId : void 0,
|
|
1212
|
+
appearance
|
|
1213
|
+
}
|
|
1214
|
+
),
|
|
1215
|
+
needsCaptcha && /* @__PURE__ */ jsx5("div", { ref: captcha.ref, className: "zenauth-captcha" }),
|
|
1216
|
+
(error || captcha.failed) && /* @__PURE__ */ jsx5("p", { id: errorId, role: "alert", className: cx("zenauth-error", cls.error), children: error ?? captcha.failed }),
|
|
1217
|
+
/* @__PURE__ */ jsx5(
|
|
1218
|
+
"button",
|
|
1219
|
+
{
|
|
1220
|
+
type: "submit",
|
|
1221
|
+
className: cx("zenauth-submit", cls.button),
|
|
1222
|
+
disabled: pending || !name || !email || !password || needsCaptcha && !captcha.token,
|
|
1223
|
+
children: pending ? "Creating account\u2026" : submitLabel
|
|
1224
|
+
}
|
|
1225
|
+
)
|
|
1226
|
+
] }),
|
|
1227
|
+
footer && /* @__PURE__ */ jsx5("div", { className: "zenauth-form-footer", children: footer })
|
|
1228
|
+
] });
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// src/react/account-forms.tsx
|
|
1232
|
+
import { useEffect as useEffect4, useId as useId5, useRef as useRef3, useState as useState5 } from "react";
|
|
1233
|
+
import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
|
|
1234
|
+
function Shell({
|
|
1235
|
+
title,
|
|
1236
|
+
subtitle,
|
|
1237
|
+
footer,
|
|
1238
|
+
appearance,
|
|
1239
|
+
kind,
|
|
1240
|
+
children
|
|
1241
|
+
}) {
|
|
1242
|
+
const cls = appearance?.classNames ?? {};
|
|
1243
|
+
return /* @__PURE__ */ jsxs5("div", { className: cx("zenauth-form", cls.root), style: cssVariables(appearance?.variables), "data-zenauth": kind, children: [
|
|
1244
|
+
(title || subtitle) && /* @__PURE__ */ jsxs5("header", { children: [
|
|
1245
|
+
title && /* @__PURE__ */ jsx6("h2", { className: cx("zenauth-form-title", cls.title), children: title }),
|
|
1246
|
+
subtitle && /* @__PURE__ */ jsx6("p", { className: cx("zenauth-form-subtitle", cls.subtitle), children: subtitle })
|
|
1247
|
+
] }),
|
|
1248
|
+
children,
|
|
1249
|
+
footer && /* @__PURE__ */ jsx6("div", { className: "zenauth-form-footer", children: footer })
|
|
1250
|
+
] });
|
|
1251
|
+
}
|
|
1252
|
+
function ForgotPasswordForm({
|
|
1253
|
+
turnstileSiteKey,
|
|
1254
|
+
submitLabel = "Send reset link",
|
|
1255
|
+
title = "Forgot your password?",
|
|
1256
|
+
subtitle = "Enter your email and we will send you a link to choose a new one.",
|
|
1257
|
+
footer,
|
|
1258
|
+
appearance
|
|
1259
|
+
}) {
|
|
1260
|
+
useZenAuthStyles();
|
|
1261
|
+
const { forgotPassword } = useZenAuth();
|
|
1262
|
+
const errorId = useId5();
|
|
1263
|
+
const cls = appearance?.classNames ?? {};
|
|
1264
|
+
const captcha = useTurnstile(turnstileSiteKey);
|
|
1265
|
+
const [email, setEmail] = useState5("");
|
|
1266
|
+
const [pending, setPending] = useState5(false);
|
|
1267
|
+
const [error, setError] = useState5(null);
|
|
1268
|
+
const [done, setDone] = useState5(null);
|
|
1269
|
+
const submit = async (e) => {
|
|
1270
|
+
e.preventDefault();
|
|
1271
|
+
if (pending) return;
|
|
1272
|
+
setError(null);
|
|
1273
|
+
setPending(true);
|
|
1274
|
+
try {
|
|
1275
|
+
setDone(await forgotPassword({ email: email.trim(), captchaToken: captcha.token ?? void 0 }));
|
|
1276
|
+
} catch (err) {
|
|
1277
|
+
setError(errorMessage(err));
|
|
1278
|
+
captcha.reset();
|
|
1279
|
+
} finally {
|
|
1280
|
+
setPending(false);
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1283
|
+
if (done) {
|
|
1284
|
+
return /* @__PURE__ */ jsx6(Shell, { title: "Check your email", footer, appearance, kind: "forgot-password-done", children: /* @__PURE__ */ jsx6("p", { role: "status", className: cx("zenauth-notice", cls.success), children: done }) });
|
|
1285
|
+
}
|
|
1286
|
+
const needsCaptcha = Boolean(turnstileSiteKey);
|
|
1287
|
+
return /* @__PURE__ */ jsx6(Shell, { title, subtitle, footer, appearance, kind: "forgot-password", children: /* @__PURE__ */ jsxs5("form", { onSubmit: (e) => void submit(e), noValidate: true, children: [
|
|
1288
|
+
/* @__PURE__ */ jsx6(
|
|
1289
|
+
Field,
|
|
1290
|
+
{
|
|
1291
|
+
label: "Email address",
|
|
1292
|
+
value: email,
|
|
1293
|
+
onChange: setEmail,
|
|
1294
|
+
autoComplete: "email",
|
|
1295
|
+
inputMode: "email",
|
|
1296
|
+
describedBy: error ? errorId : void 0,
|
|
1297
|
+
appearance
|
|
1298
|
+
}
|
|
1299
|
+
),
|
|
1300
|
+
needsCaptcha && /* @__PURE__ */ jsx6("div", { ref: captcha.ref, className: "zenauth-captcha" }),
|
|
1301
|
+
(error || captcha.failed) && /* @__PURE__ */ jsx6("p", { id: errorId, role: "alert", className: cx("zenauth-error", cls.error), children: error ?? captcha.failed }),
|
|
1302
|
+
/* @__PURE__ */ jsx6(
|
|
1303
|
+
"button",
|
|
1304
|
+
{
|
|
1305
|
+
type: "submit",
|
|
1306
|
+
className: cx("zenauth-submit", cls.button),
|
|
1307
|
+
disabled: pending || !email || needsCaptcha && !captcha.token,
|
|
1308
|
+
children: pending ? "Sending\u2026" : submitLabel
|
|
1309
|
+
}
|
|
1310
|
+
)
|
|
1311
|
+
] }) });
|
|
1312
|
+
}
|
|
1313
|
+
function ResetPasswordForm({
|
|
1314
|
+
token,
|
|
1315
|
+
onSuccess,
|
|
1316
|
+
submitLabel = "Update password",
|
|
1317
|
+
title = "Choose a new password",
|
|
1318
|
+
subtitle,
|
|
1319
|
+
footer,
|
|
1320
|
+
successFooter,
|
|
1321
|
+
appearance
|
|
1322
|
+
}) {
|
|
1323
|
+
useZenAuthStyles();
|
|
1324
|
+
const { resetPassword } = useZenAuth();
|
|
1325
|
+
const errorId = useId5();
|
|
1326
|
+
const cls = appearance?.classNames ?? {};
|
|
1327
|
+
const [password, setPassword] = useState5("");
|
|
1328
|
+
const [confirm, setConfirm] = useState5("");
|
|
1329
|
+
const [pending, setPending] = useState5(false);
|
|
1330
|
+
const [error, setError] = useState5(null);
|
|
1331
|
+
const [done, setDone] = useState5(null);
|
|
1332
|
+
if (!token) {
|
|
1333
|
+
return /* @__PURE__ */ jsx6(Shell, { title: "This link is not valid", footer, appearance, kind: "reset-password-invalid", children: /* @__PURE__ */ jsx6("p", { role: "alert", className: cx("zenauth-error", cls.error), children: "The reset link is missing its token. Request a new one and use the link from the latest email." }) });
|
|
1334
|
+
}
|
|
1335
|
+
const mismatch = confirm.length > 0 && confirm !== password;
|
|
1336
|
+
const submit = async (e) => {
|
|
1337
|
+
e.preventDefault();
|
|
1338
|
+
if (pending || password !== confirm) return;
|
|
1339
|
+
setError(null);
|
|
1340
|
+
setPending(true);
|
|
1341
|
+
try {
|
|
1342
|
+
setDone(await resetPassword({ token, password }));
|
|
1343
|
+
onSuccess?.();
|
|
1344
|
+
} catch (err) {
|
|
1345
|
+
setError(errorMessage(err));
|
|
1346
|
+
} finally {
|
|
1347
|
+
setPending(false);
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
if (done) {
|
|
1351
|
+
return /* @__PURE__ */ jsx6(Shell, { title: "Password updated", footer: successFooter ?? footer, appearance, kind: "reset-password-done", children: /* @__PURE__ */ jsx6("p", { role: "status", className: cx("zenauth-notice", cls.success), children: done }) });
|
|
1352
|
+
}
|
|
1353
|
+
return /* @__PURE__ */ jsx6(Shell, { title, subtitle, footer, appearance, kind: "reset-password", children: /* @__PURE__ */ jsxs5("form", { onSubmit: (e) => void submit(e), noValidate: true, children: [
|
|
1354
|
+
/* @__PURE__ */ jsx6(
|
|
1355
|
+
PasswordField,
|
|
1356
|
+
{
|
|
1357
|
+
label: "New password",
|
|
1358
|
+
autoComplete: "new-password",
|
|
1359
|
+
value: password,
|
|
1360
|
+
onChange: setPassword,
|
|
1361
|
+
describedBy: error ? errorId : void 0,
|
|
1362
|
+
appearance
|
|
1363
|
+
}
|
|
1364
|
+
),
|
|
1365
|
+
/* @__PURE__ */ jsx6(
|
|
1366
|
+
PasswordField,
|
|
1367
|
+
{
|
|
1368
|
+
label: "Confirm new password",
|
|
1369
|
+
autoComplete: "new-password",
|
|
1370
|
+
value: confirm,
|
|
1371
|
+
onChange: setConfirm,
|
|
1372
|
+
describedBy: error ? errorId : void 0,
|
|
1373
|
+
appearance
|
|
1374
|
+
}
|
|
1375
|
+
),
|
|
1376
|
+
(error || mismatch) && /* @__PURE__ */ jsx6("p", { id: errorId, role: "alert", className: cx("zenauth-error", cls.error), children: error ?? "The two passwords do not match." }),
|
|
1377
|
+
/* @__PURE__ */ jsx6(
|
|
1378
|
+
"button",
|
|
1379
|
+
{
|
|
1380
|
+
type: "submit",
|
|
1381
|
+
className: cx("zenauth-submit", cls.button),
|
|
1382
|
+
disabled: pending || !password || password !== confirm,
|
|
1383
|
+
children: pending ? "Updating\u2026" : submitLabel
|
|
1384
|
+
}
|
|
1385
|
+
)
|
|
1386
|
+
] }) });
|
|
1387
|
+
}
|
|
1388
|
+
function VerifyEmail({ token, onVerified, title, footer, successFooter, appearance }) {
|
|
1389
|
+
useZenAuthStyles();
|
|
1390
|
+
const { verifyEmail } = useZenAuth();
|
|
1391
|
+
const cls = appearance?.classNames ?? {};
|
|
1392
|
+
const [state, setState] = useState5({
|
|
1393
|
+
status: token ? "verifying" : "error",
|
|
1394
|
+
message: token ? void 0 : "The verification link is missing its token."
|
|
1395
|
+
});
|
|
1396
|
+
const started = useRef3(false);
|
|
1397
|
+
useEffect4(() => {
|
|
1398
|
+
if (!token || started.current) return;
|
|
1399
|
+
started.current = true;
|
|
1400
|
+
verifyEmail(token).then((message) => {
|
|
1401
|
+
setState({ status: "done", message });
|
|
1402
|
+
onVerified?.();
|
|
1403
|
+
}).catch((err) => setState({ status: "error", message: errorMessage(err) }));
|
|
1404
|
+
}, [token]);
|
|
1405
|
+
if (state.status === "verifying") {
|
|
1406
|
+
return /* @__PURE__ */ jsx6(Shell, { title: title ?? "Verifying your email\u2026", appearance, kind: "verify-email", children: /* @__PURE__ */ jsx6("p", { role: "status", className: cx("zenauth-notice", cls.success), children: "Just a moment." }) });
|
|
1407
|
+
}
|
|
1408
|
+
if (state.status === "done") {
|
|
1409
|
+
return /* @__PURE__ */ jsx6(Shell, { title: title ?? "Email verified", footer: successFooter ?? footer, appearance, kind: "verify-email-done", children: /* @__PURE__ */ jsx6("p", { role: "status", className: cx("zenauth-notice", cls.success), children: state.message }) });
|
|
1410
|
+
}
|
|
1411
|
+
return /* @__PURE__ */ jsx6(Shell, { title: title ?? "We could not verify your email", footer, appearance, kind: "verify-email-error", children: /* @__PURE__ */ jsx6("p", { role: "alert", className: cx("zenauth-error", cls.error), children: state.message }) });
|
|
1412
|
+
}
|
|
1413
|
+
export {
|
|
1414
|
+
ForgotPasswordForm,
|
|
1415
|
+
ResetPasswordForm,
|
|
1416
|
+
SignIn,
|
|
1417
|
+
SignInForm,
|
|
1418
|
+
SignUpForm,
|
|
1419
|
+
SignedIn,
|
|
1420
|
+
SignedOut,
|
|
1421
|
+
UserButton,
|
|
1422
|
+
VerifyEmail,
|
|
1423
|
+
ZenAuthClient,
|
|
1424
|
+
ZenAuthError,
|
|
1425
|
+
ZenAuthProvider,
|
|
1426
|
+
createMemoryStorage,
|
|
1427
|
+
useZenAuth
|
|
1428
|
+
};
|
|
1429
|
+
//# sourceMappingURL=index.js.map
|