@lalternative/auth 0.12.0 → 0.13.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/README.md +22 -0
- package/dist/{chunk-HTQRNUIF.js → chunk-MZZTQ66T.js} +18 -2
- package/dist/chunk-MZZTQ66T.js.map +1 -0
- package/dist/client.d.ts +3 -3
- package/dist/client.js +3 -1
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +3 -3
- package/dist/server.js +28 -6
- package/dist/server.js.map +1 -1
- package/dist/{invitation-miBKXoxz.d.ts → sso-profile-Dkbi4TA4.d.ts} +24 -2
- package/dist/{types-Ct0Kt36S.d.ts → types-ioL47w7k.d.ts} +28 -1
- package/package.json +1 -1
- package/dist/chunk-HTQRNUIF.js.map +0 -1
package/README.md
CHANGED
|
@@ -36,6 +36,28 @@ export const authClient = createPlatformAuthClient({ baseURL })
|
|
|
36
36
|
import { LoginForm, RegisterForm, SocialButtons, VerifyEmailForm, ForgotPasswordForm, ResetPasswordForm, AuthLayout, useSession, useLogout } from "@lalternative/auth"
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
+
### Single sign-on (urbangate)
|
|
40
|
+
|
|
41
|
+
Passing `sso` mounts an OIDC client of the suite's identity provider. A person
|
|
42
|
+
whose `roles` claim carries `adminRole` signs in as admin, anyone else as a
|
|
43
|
+
plain user, and the role is recomputed on every sign-in.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
export const auth = createPlatformAuth({
|
|
47
|
+
// …
|
|
48
|
+
sso: {
|
|
49
|
+
issuer: "https://id.urbangate.dev",
|
|
50
|
+
clientId: "tornade-admin",
|
|
51
|
+
clientSecret: process.env.URBANGATE_CLIENT_SECRET!,
|
|
52
|
+
adminRole: "tornade:admin",
|
|
53
|
+
},
|
|
54
|
+
})
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The callback is `/api/auth/oauth2/callback/urbangate`; register it on the
|
|
58
|
+
Hydra client. On the client, `authClient.signIn.oauth2({ providerId: "urbangate", callbackURL: "/admin" })`
|
|
59
|
+
starts the redirect.
|
|
60
|
+
|
|
39
61
|
### Magic link
|
|
40
62
|
|
|
41
63
|
Passwordless sign-in by emailed link. Off unless `magicLink` is passed — the
|
|
@@ -97,6 +97,21 @@ function isInvitationFailure(outcome) {
|
|
|
97
97
|
return outcome === "expired" || outcome === "claimed" || outcome === "unknown";
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
+
// src/sso-profile.ts
|
|
101
|
+
function rolesOf(profile) {
|
|
102
|
+
return Array.isArray(profile.roles) ? profile.roles.filter((r) => typeof r === "string") : [];
|
|
103
|
+
}
|
|
104
|
+
function mapSsoProfile(profile, adminRole) {
|
|
105
|
+
const email = (profile.email ?? "").trim().toLowerCase();
|
|
106
|
+
return {
|
|
107
|
+
email,
|
|
108
|
+
emailVerified: profile.email_verified === true,
|
|
109
|
+
name: profile.name?.trim() || email.split("@")[0] || "",
|
|
110
|
+
...profile.picture ? { image: profile.picture } : {},
|
|
111
|
+
role: rolesOf(profile).includes(adminRole) ? "admin" : "user"
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
100
115
|
export {
|
|
101
116
|
withSignUpName,
|
|
102
117
|
claimInvitation,
|
|
@@ -106,6 +121,7 @@ export {
|
|
|
106
121
|
releaseInviteTokenCookie,
|
|
107
122
|
completesSignup,
|
|
108
123
|
invitationOutcomeCookie,
|
|
109
|
-
isInvitationFailure
|
|
124
|
+
isInvitationFailure,
|
|
125
|
+
mapSsoProfile
|
|
110
126
|
};
|
|
111
|
-
//# sourceMappingURL=chunk-
|
|
127
|
+
//# sourceMappingURL=chunk-MZZTQ66T.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/signup-name.ts","../src/invitation.ts","../src/sso-profile.ts"],"sourcesContent":["/**\n * Fills in the display name of an account signed up without one.\n *\n * The sign-up form treats the name as optional and omits the key when it is\n * left blank, but Better Auth's user schema requires it and rejects the\n * request with `[body.name] Invalid input`. Naming the account is the server's\n * call, so the default is applied here rather than invented by the client.\n *\n * The local part of the address is the closest thing to a name the person has\n * actually given us. It is only a starting label: they can change it later,\n * and nothing keys off it.\n */\nexport function withSignUpName<T extends { email?: unknown; name?: unknown }>(\n body: T,\n): T & { name: string } {\n const name = typeof body.name === \"string\" ? body.name.trim() : \"\"\n if (name) return { ...body, name }\n\n const email = typeof body.email === \"string\" ? body.email.trim() : \"\"\n const at = email.lastIndexOf(\"@\")\n const localPart = at > 0 ? email.slice(0, at) : email\n\n return { ...body, name: localPart }\n}\n","import type { InvitationFailure } from \"./types\"\n\n/**\n * What became of a claim, in terms the invitee can be told.\n *\n * 'expired' and 'claimed' are kept apart from 'unknown' because only they say\n * the offer was real, which is what tells someone that asking for a new link is\n * worth it rather than doubting the address they were invited at. The three\n * failures match InvitationFailure, so an outcome feeds InvitationNotice\n * directly.\n */\nexport type ClaimOutcome = \"granted\" | InvitationFailure | \"failed\"\n\nconst OUTCOME_BY_STATUS: Record<number, ClaimOutcome> = {\n 404: \"unknown\",\n 409: \"claimed\",\n 410: \"expired\",\n}\n\nexport interface ClaimInvitationOptions {\n /** Absolute URL of the endpoint that redeems a token. */\n endpoint: string\n token: string\n /** The account the app just created, which the grant is attached to. */\n externalUserId: string\n /** Sent as the Authorization bearer — typically the app's API key. */\n apiKey?: string\n /** Merged into the request body, for backends wanting more than the token. */\n extra?: Record<string, unknown>\n /** Headers merged last, so a caller can pass a cookie-based credential. */\n headers?: Record<string, string>\n /** Bounds the call so a slow API never stalls the sign-in response. */\n timeoutMs?: number\n}\n\n/**\n * Redeems an invitation token for a user who has just signed in, turning the\n * offer into a grant on their account.\n *\n * Why this belongs on the SERVER, on the auth callback rather than in the page:\n * the invitation link lands on /register?invite=<token>, but the sign-up that\n * follows can complete through any of three flows (password + OTP, OAuth\n * redirect, email verification), and only two of them return to the page that\n * held the token. Claiming where the session is established covers every flow\n * with one code path.\n *\n * Best-effort by design: a sign-in must never fail because an invitation could\n * not be redeemed. A failed claim leaves the invitation unclaimed and the user\n * on their default tier — recoverable by following the link again, since a\n * refused claim consumes nothing.\n */\nexport async function claimInvitation({\n endpoint,\n token,\n externalUserId,\n apiKey,\n extra,\n headers,\n timeoutMs = 5000,\n}: ClaimInvitationOptions): Promise<ClaimOutcome> {\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),\n ...headers,\n },\n body: JSON.stringify({\n token,\n external_user_id: externalUserId,\n ...extra,\n }),\n signal: AbortSignal.timeout(timeoutMs),\n })\n\n if (res.ok) return \"granted\"\n return OUTCOME_BY_STATUS[res.status] ?? \"failed\"\n } catch {\n return \"failed\"\n }\n}\n\n/**\n * Extracts the invitation token from an auth request.\n *\n * The token lives on the page the invitee landed on (/register?invite=…), never\n * on the auth endpoints themselves, so it has to be recovered from the request\n * that completes the sign-up. Three sources, in order of trust:\n *\n * - the URL, for a callback reached through a redirect whose query string\n * the app controls;\n * - the cookie held since the link was opened, which is the only one that\n * survives an OAuth round trip or an OTP screen that never carried the\n * token (see holdInviteTokenCookie);\n * - the Referer, for the password flow, whose XHR is issued BY the page\n * holding it.\n *\n * The Referer stays last and stays supported: it covers a caller that never\n * held the cookie. It is attacker-controlled input on a best-effort path, so a\n * malformed one is ignored rather than thrown on.\n */\nexport function inviteTokenFrom(\n request: Request,\n param = \"invite\",\n): string | null {\n const direct = new URL(request.url).searchParams.get(param)\n if (direct && direct.trim() !== \"\") return direct\n\n const held = inviteTokenCookie(request)\n if (held) return held\n\n const referer = request.headers.get(\"referer\")\n if (!referer) return null\n try {\n const token = new URL(referer).searchParams.get(param)\n return token && token.trim() !== \"\" ? token : null\n } catch {\n return null\n }\n}\n\n/** Name of the cookie holding the token between the link and the claim. */\nconst INVITE_TOKEN_COOKIE = \"invite_token\"\n\n/**\n * Pins the token onto the browser the first time a request carries it, so the\n * rest of the sign-up can find it.\n *\n * Called on every auth request, not only the ones completing a sign-up: the\n * token is legible on the FIRST call of a flow (the page holding it issues that\n * XHR, so the Referer still has it) and gone by the last (verified from a\n * screen that never held it, or returned from Google). Waiting for the moment\n * the account exists is waiting one request too long.\n *\n * Returns null when there is nothing to pin — no token in the request, or one\n * already held — so a caller can skip the Set-Cookie entirely.\n */\nexport function pinInviteToken(\n request: Request,\n param = \"invite\",\n): string | null {\n if (inviteTokenCookie(request)) return null\n const token = inviteTokenFrom(request, param)\n return token ? holdInviteTokenCookie(token) : null\n}\n\n/**\n * Holds the token from the moment the link is opened until the account exists.\n *\n * The URL and the Referer each cover only part of the ground: the OTP flow\n * verifies from a screen that never carried the token, and an OAuth sign-up\n * comes back from Google with no Referer of ours at all. Both lose it, and the\n * invitee lands on the default tier with the offer still pending.\n *\n * SameSite=Lax rather than Strict: the return from Google is a cross-site\n * top-level navigation, which Strict would refuse — the one case this exists\n * for. HttpOnly because the page has no reason to read it, and short-lived\n * because signing up takes minutes: a single-use invitation has no business\n * sitting in a browser for longer.\n */\nexport function holdInviteTokenCookie(\n token: string,\n maxAgeSeconds = 1800,\n): string {\n return `${INVITE_TOKEN_COOKIE}=${encodeURIComponent(token)}; Path=/; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Lax`\n}\n\n/**\n * Clears the held token. Sent once the claim has been attempted: the token is\n * single-use, so keeping it would only replay a call that can no longer\n * succeed.\n */\nexport function releaseInviteTokenCookie(): string {\n return `${INVITE_TOKEN_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`\n}\n\nfunction inviteTokenCookie(request: Request): string | null {\n const header = request.headers.get(\"cookie\")\n if (!header) return null\n for (const part of header.split(\";\")) {\n const [name, ...rest] = part.trim().split(\"=\")\n if (name !== INVITE_TOKEN_COOKIE) continue\n const value = decodeURIComponent(rest.join(\"=\")).trim()\n return value === \"\" ? null : value\n }\n return null\n}\n\n/**\n * BetterAuth paths that complete a sign-up. Email/password returns the user\n * straight from sign-up/email; the OTP and OAuth flows only produce a usable\n * account once the verification/callback succeeds, so those are the moments\n * worth reacting to.\n */\nconst SIGNUP_COMPLETING = [\n \"/sign-up/email\",\n \"/sign-in/email-otp\",\n \"/email-otp/verify-email\",\n \"/callback/\",\n]\n\n/**\n * Whether this request is the one that just created a usable account — the\n * moment to provision, claim an invitation, or greet someone. Matching on the\n * path rather than on a response body keeps it flow-agnostic: the three\n * sign-up flows return three different shapes.\n */\nexport function completesSignup(pathname: string): boolean {\n return SIGNUP_COMPLETING.some((p) => pathname.includes(p))\n}\n\n/**\n * Carries a failed claim to the next page. The claim happens inside an auth\n * response nobody renders, so its result would otherwise reach only the server\n * log — leaving an invitee on the default tier with no idea their link had\n * lapsed. Short-lived and readable by the page, which reports it and clears it.\n */\nexport function invitationOutcomeCookie(\n outcome: ClaimOutcome,\n name = \"invite_claim\",\n): string {\n return `${name}=${outcome}; Path=/; Max-Age=120; SameSite=Lax`\n}\n\n/**\n * Whether an outcome is one the invitee should be shown a reason for.\n * 'failed' is excluded: it means the call did not complete, so the offer may\n * still be good and telling someone their invitation is invalid would be wrong.\n */\nexport function isInvitationFailure(\n outcome: ClaimOutcome,\n): outcome is InvitationFailure {\n return outcome === \"expired\" || outcome === \"claimed\" || outcome === \"unknown\"\n}\n","export interface SsoProfile {\n sub?: string\n email?: string\n email_verified?: boolean\n name?: string\n picture?: string\n roles?: unknown\n}\n\nexport interface SsoMappedUser {\n email: string\n emailVerified: boolean\n name: string\n image?: string\n role: \"admin\" | \"user\"\n}\n\nexport function rolesOf(profile: SsoProfile): string[] {\n return Array.isArray(profile.roles)\n ? profile.roles.filter((r): r is string => typeof r === \"string\")\n : []\n}\n\n/**\n * Maps the identity provider's claims onto the local user. The admin role is\n * recomputed from the roles claim on every sign-in, so a role removed at the\n * provider is removed here the next time the person signs in.\n */\nexport function mapSsoProfile(profile: SsoProfile, adminRole: string): SsoMappedUser {\n const email = (profile.email ?? \"\").trim().toLowerCase()\n return {\n email,\n emailVerified: profile.email_verified === true,\n name: profile.name?.trim() || email.split(\"@\")[0] || \"\",\n ...(profile.picture ? { image: profile.picture } : {}),\n role: rolesOf(profile).includes(adminRole) ? \"admin\" : \"user\",\n }\n}\n"],"mappings":";AAYO,SAAS,eACd,MACsB;AACtB,QAAM,OAAO,OAAO,KAAK,SAAS,WAAW,KAAK,KAAK,KAAK,IAAI;AAChE,MAAI,KAAM,QAAO,EAAE,GAAG,MAAM,KAAK;AAEjC,QAAM,QAAQ,OAAO,KAAK,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI;AACnE,QAAM,KAAK,MAAM,YAAY,GAAG;AAChC,QAAM,YAAY,KAAK,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI;AAEhD,SAAO,EAAE,GAAG,MAAM,MAAM,UAAU;AACpC;;;ACVA,IAAM,oBAAkD;AAAA,EACtD,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAkCA,eAAsB,gBAAgB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AACd,GAAkD;AAChD,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,UAAU;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAI,SAAS,EAAE,eAAe,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,QACtD,GAAG;AAAA,MACL;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,kBAAkB;AAAA,QAClB,GAAG;AAAA,MACL,CAAC;AAAA,MACD,QAAQ,YAAY,QAAQ,SAAS;AAAA,IACvC,CAAC;AAED,QAAI,IAAI,GAAI,QAAO;AACnB,WAAO,kBAAkB,IAAI,MAAM,KAAK;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAqBO,SAAS,gBACd,SACA,QAAQ,UACO;AACf,QA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AO,kBAAkB,KAAK,CAAC,MAAM,SAAS,SAAS,CAAC,CAAC;AAC3D;AAQO,SAAS,wBACd,SACA,OAAO,gBACC;AACR,SAAO,GAAG,IAAI,IAAI,OAAO;AAC3B;AAOO,SAAS,oBACd,SAC8B;AAC9B,SAAO,YAAY,aAAa,YAAY,aAAa,YAAY;AACvE;;;ACzNO,SAAS,QAAQ,SAA+B;AACrD,SAAO,MAAM,QAAQ,QAAQ,KAAK,IAC9B,QAAQ,MAAM,OAAO,CAAC,MAAmB,OAAO,MAAM,QAAQ,IAC9D,CAAC;AACP;AAOO,SAAS,cAAc,SAAqB,WAAkC;AACnF,QAAM,SAAS,QAAQ,SAAS,IAAI,KAAK,EAAE,YAAY;AACvD,SAAO;AAAA,IACL;AAAA,IACA,eAAe,QAAQ,mBAAmB;AAAA,IAC1C,MAAM,QAAQ,MAAM,KAAK,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,KAAK;AAAA,IACrD,GAAI,QAAQ,UAAU,EAAE,OAAO,QAAQ,QAAQ,IAAI,CAAC;AAAA,IACpD,MAAM,QAAQ,OAAO,EAAE,SAAS,SAAS,IAAI,UAAU;AAAA,EACzD;AACF;","names":[]}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createAuthClient } from 'better-auth/react';
|
|
2
|
-
import { f as AuthClientSurface, l as MagicLinkClientSurface, d as AdminClientSurface, T as TwoFactorClientSurface, P as PlatformAuthClientConfig } from './types-
|
|
2
|
+
import { f as AuthClientSurface, l as MagicLinkClientSurface, S as SsoClientSurface, d as AdminClientSurface, T as TwoFactorClientSurface, P as PlatformAuthClientConfig } from './types-ioL47w7k.js';
|
|
3
3
|
import 'better-auth';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -19,10 +19,10 @@ import 'better-auth';
|
|
|
19
19
|
* back-office calling admin.listUsers() off it must not have to widen the type.
|
|
20
20
|
*/
|
|
21
21
|
type PlatformAuthClient = Omit<AuthClientSurface, "signIn" | "admin"> & {
|
|
22
|
-
signIn: AuthClientSurface["signIn"] & MagicLinkClientSurface["signIn"];
|
|
22
|
+
signIn: AuthClientSurface["signIn"] & MagicLinkClientSurface["signIn"] & SsoClientSurface["signIn"];
|
|
23
23
|
admin: AdminClientSurface;
|
|
24
24
|
twoFactor: TwoFactorClientSurface;
|
|
25
|
-
} & Omit<ReturnType<typeof createAuthClient>, keyof AuthClientSurface | keyof MagicLinkClientSurface | "twoFactor">;
|
|
25
|
+
} & Omit<ReturnType<typeof createAuthClient>, keyof AuthClientSurface | keyof MagicLinkClientSurface | keyof SsoClientSurface | "twoFactor">;
|
|
26
26
|
/**
|
|
27
27
|
* Creates a Better Auth client for React usage.
|
|
28
28
|
* Provides useSession() and the email-OTP / magic-link / admin plugin methods.
|
package/dist/client.js
CHANGED
|
@@ -4,7 +4,8 @@ import {
|
|
|
4
4
|
emailOTPClient,
|
|
5
5
|
adminClient,
|
|
6
6
|
magicLinkClient,
|
|
7
|
-
twoFactorClient
|
|
7
|
+
twoFactorClient,
|
|
8
|
+
genericOAuthClient
|
|
8
9
|
} from "better-auth/client/plugins";
|
|
9
10
|
function createPlatformAuthClient(config) {
|
|
10
11
|
return createAuthClient({
|
|
@@ -14,6 +15,7 @@ function createPlatformAuthClient(config) {
|
|
|
14
15
|
magicLinkClient(),
|
|
15
16
|
adminClient(),
|
|
16
17
|
twoFactorClient(),
|
|
18
|
+
genericOAuthClient(),
|
|
17
19
|
...config?.plugins ?? []
|
|
18
20
|
]
|
|
19
21
|
});
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import { createAuthClient } from \"better-auth/react\"\nimport {\n emailOTPClient,\n adminClient,\n magicLinkClient,\n twoFactorClient,\n} from \"better-auth/client/plugins\"\nimport type {\n AdminClientSurface,\n AuthClientSurface,\n MagicLinkClientSurface,\n PlatformAuthClientConfig,\n TwoFactorClientSurface,\n} from \"./types\"\n\n/**\n * A Better Auth React client carrying the platform plugins.\n *\n * The concrete inferred type cannot be named in a published .d.ts (TS2742 — it\n * reaches into zod's internals), so the surface the auth screens call is\n * declared by hand in AuthClientSurface and intersected with the rest of the\n * client. Keep it in sync with the plugins enabled below.\n *\n * signIn carries both halves: the client always mounts magicLinkClient, since\n * which methods exist client-side costs nothing — whether the route answers is\n * decided server-side by passing `magicLink` to createPlatformAuth.\n *\n * admin is optional on AuthClientSurface, whose job is to type the prop the\n * forms take, and required here: this client always mounts adminClient(), so a\n * back-office calling admin.listUsers() off it must not have to widen the type.\n */\nexport type PlatformAuthClient = Omit<AuthClientSurface, \"signIn\" | \"admin\"> & {\n signIn: AuthClientSurface[\"signIn\"]
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import { createAuthClient } from \"better-auth/react\"\nimport {\n emailOTPClient,\n adminClient,\n magicLinkClient,\n twoFactorClient,\n genericOAuthClient,\n} from \"better-auth/client/plugins\"\nimport type {\n AdminClientSurface,\n AuthClientSurface,\n MagicLinkClientSurface,\n PlatformAuthClientConfig,\n SsoClientSurface,\n TwoFactorClientSurface,\n} from \"./types\"\n\n/**\n * A Better Auth React client carrying the platform plugins.\n *\n * The concrete inferred type cannot be named in a published .d.ts (TS2742 — it\n * reaches into zod's internals), so the surface the auth screens call is\n * declared by hand in AuthClientSurface and intersected with the rest of the\n * client. Keep it in sync with the plugins enabled below.\n *\n * signIn carries both halves: the client always mounts magicLinkClient, since\n * which methods exist client-side costs nothing — whether the route answers is\n * decided server-side by passing `magicLink` to createPlatformAuth.\n *\n * admin is optional on AuthClientSurface, whose job is to type the prop the\n * forms take, and required here: this client always mounts adminClient(), so a\n * back-office calling admin.listUsers() off it must not have to widen the type.\n */\nexport type PlatformAuthClient = Omit<AuthClientSurface, \"signIn\" | \"admin\"> & {\n signIn: AuthClientSurface[\"signIn\"] &\n MagicLinkClientSurface[\"signIn\"] &\n SsoClientSurface[\"signIn\"]\n admin: AdminClientSurface\n twoFactor: TwoFactorClientSurface\n} & Omit<\n ReturnType<typeof createAuthClient>,\n | keyof AuthClientSurface\n | keyof MagicLinkClientSurface\n | keyof SsoClientSurface\n | \"twoFactor\"\n >\n\n/**\n * Creates a Better Auth client for React usage.\n * Provides useSession() and the email-OTP / magic-link / admin plugin methods.\n */\nexport function createPlatformAuthClient(\n config?: PlatformAuthClientConfig,\n): PlatformAuthClient {\n return createAuthClient({\n baseURL:\n config?.baseURL ??\n (typeof window !== \"undefined\"\n ? window.location.origin\n : \"http://localhost:3000\"),\n plugins: [\n emailOTPClient(),\n magicLinkClient(),\n adminClient(),\n twoFactorClient(),\n genericOAuthClient(),\n ...(config?.plugins ?? []),\n ],\n }) as unknown as PlatformAuthClient\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA4CA,SAAS,yBACd,QACoB;AACpB,SAAO,iBAAiB;AAAA,IACtB,SACE,QAAQ,YACP,OAAO,WAAW,cACf,OAAO,SAAS,SAChB;AAAA,IACN,SAAS;AAAA,MACP,eAAe;AAAA,MACf,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,MACnB,GAAI,QAAQ,WAAW,CAAC;AAAA,IAC1B;AAAA,EACF,CAAC;AACH;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { L as LoginFormProps, R as RegisterFormProps, V as VerifyEmailFormProps, F as ForgotPasswordFormProps, M as MagicLinkFormProps, a as ResetPasswordFormProps, A as AuthLayoutProps, I as InvitationNoticeProps, b as AuthClientResult, c as LinkComponent } from './types-
|
|
2
|
-
export { d as AdminClientSurface, e as AuthClientDataResult, f as AuthClientSurface, g as AuthInviteProps, h as AuthNavProps, i as AuthThemeProps, j as InvitationFailure, k as LoginFormLabels, l as MagicLinkClientSurface, m as MagicLinkConfig, n as MagicLinkFormLabels, P as PlatformAuthClientConfig, o as PlatformAuthConfig, p as PlatformAuthMailer, q as PlatformAuthMailerArgs, r as PlatformAuthMailerType, s as PlatformRateLimitConfig, t as PlatformRateLimitRule, u as PlatformSession, v as PlatformSessionData, w as
|
|
1
|
+
import { L as LoginFormProps, R as RegisterFormProps, V as VerifyEmailFormProps, F as ForgotPasswordFormProps, M as MagicLinkFormProps, a as ResetPasswordFormProps, A as AuthLayoutProps, I as InvitationNoticeProps, b as AuthClientResult, c as LinkComponent } from './types-ioL47w7k.js';
|
|
2
|
+
export { d as AdminClientSurface, e as AuthClientDataResult, f as AuthClientSurface, g as AuthInviteProps, h as AuthNavProps, i as AuthThemeProps, j as InvitationFailure, k as LoginFormLabels, l as MagicLinkClientSurface, m as MagicLinkConfig, n as MagicLinkFormLabels, P as PlatformAuthClientConfig, o as PlatformAuthConfig, p as PlatformAuthMailer, q as PlatformAuthMailerArgs, r as PlatformAuthMailerType, s as PlatformRateLimitConfig, t as PlatformRateLimitRule, u as PlatformSession, v as PlatformSessionData, w as PlatformSsoConfig, x as PlatformTwoFactorConfig, y as PlatformUser, z as RegisterFormLabels, S as SsoClientSurface, T as TwoFactorClientSurface } from './types-ioL47w7k.js';
|
|
3
3
|
import * as better_auth_react from 'better-auth/react';
|
|
4
4
|
import * as better_auth from 'better-auth';
|
|
5
5
|
import { PlatformAuthClient } from './client.js';
|
|
6
6
|
import * as react from 'react';
|
|
7
7
|
import { InputHTMLAttributes, ReactNode } from 'react';
|
|
8
|
-
export { C as ClaimOutcome, i as isInvitationFailure } from './
|
|
8
|
+
export { C as ClaimOutcome, S as SsoMappedUser, a as SsoProfile, i as isInvitationFailure, m as mapSsoProfile } from './sso-profile-Dkbi4TA4.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Returns a useSession hook bound to the given auth client.
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isInvitationFailure,
|
|
3
|
+
mapSsoProfile,
|
|
3
4
|
withSignUpName
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-MZZTQ66T.js";
|
|
5
6
|
|
|
6
7
|
// src/hooks/use-session.ts
|
|
7
8
|
function useSession(authClient) {
|
|
@@ -1531,6 +1532,7 @@ export {
|
|
|
1531
1532
|
isMagicLinkError,
|
|
1532
1533
|
magicLinkErrorCallback,
|
|
1533
1534
|
magicLinkErrorMessage,
|
|
1535
|
+
mapSsoProfile,
|
|
1534
1536
|
normalizeInviteToken,
|
|
1535
1537
|
oauthErrorCallback,
|
|
1536
1538
|
oauthErrorMessage,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-session.ts","../src/components/auth-field.tsx","../src/components/auth-submit.tsx","../src/components/login-form.tsx","../src/email-not-verified.ts","../src/components/auth-alert.tsx","../src/components/social-buttons.tsx","../src/components/auth-link.tsx","../src/invite-token.ts","../src/oauth-error.ts","../src/components/register-form.tsx","../src/components/verify-email-form.tsx","../src/components/auth-otp-field.tsx","../src/components/forgot-password-form.tsx","../src/components/magic-link-form.tsx","../src/magic-link-error.ts","../src/components/reset-password-form.tsx","../src/components/auth-heading.tsx","../src/components/auth-layout.tsx","../src/components/invitation-notice.tsx"],"sourcesContent":["import type { PlatformAuthClient } from \"../client\"\n\n/**\n * Returns a useSession hook bound to the given auth client.\n * Usage: const { data: session, isPending } = useSession(authClient)\n */\nexport function useSession(authClient: PlatformAuthClient) {\n return authClient.useSession()\n}\n\n/**\n * Returns a logout function bound to the given auth client.\n * Usage: const logout = useLogout(authClient)\n */\nexport function useLogout(authClient: PlatformAuthClient) {\n const signOut = async () => {\n await authClient.signOut()\n }\n return signOut\n}\n","import { useId, useState, type InputHTMLAttributes, type ReactNode } from \"react\"\n\ntype NativeProps = Omit<InputHTMLAttributes<HTMLInputElement>, \"id\" | \"className\">\n\nexport interface AuthFieldProps extends NativeProps {\n label: string\n /** Rendered on the right of the label row — typically a \"forgot password\" link */\n hint?: ReactNode\n /** Persistent helper text under the field, tied to it for screen readers */\n description?: string\n invalid?: boolean\n /** Replaces the default border and background utilities */\n fieldClassName?: string\n}\n\n/**\n * A single credential field.\n *\n * The label is a real <label>, always visible, never a placeholder standing in\n * for one: a placeholder disappears the moment someone types, which is exactly\n * when a person double-checking a long password needs to know what the box is.\n *\n * Touch targets are 52px tall on mobile and 44px from sm up. Below ~48px,\n * thumbs miss; on a pointer device the same height reads as oversized, so the\n * two are not one compromise value.\n *\n * The focus ring is a ring rather than an outline so it follows the rounded\n * corners exactly, and the border darkens at the same time — the border is what\n * survives forced-colors mode, where the ring is dropped.\n */\nexport function AuthField({\n label,\n hint,\n description,\n invalid = false,\n fieldClassName = \"border-foreground/30 bg-background\",\n ...props\n}: AuthFieldProps) {\n const id = useId()\n const descriptionId = description ? `${id}-description` : undefined\n const [revealed, setRevealed] = useState(false)\n\n const isPassword = props.type === \"password\"\n const type = isPassword && revealed ? \"text\" : props.type\n\n return (\n <div className=\"space-y-2\">\n <div className=\"flex items-baseline justify-between gap-3\">\n {/* Small caps with wide tracking: at this size the label reads as a\n field marker rather than as prose competing with the heading. */}\n <label\n htmlFor={id}\n className=\"text-[0.6875rem] font-semibold uppercase leading-none tracking-[0.09em] text-foreground/70\"\n >\n {label}\n </label>\n {hint}\n </div>\n\n <div className=\"relative\">\n <input\n {...props}\n id={id}\n type={type}\n aria-invalid={invalid || undefined}\n aria-describedby={descriptionId}\n className={[\n \"h-[52px] w-full rounded-md border px-3.5 text-base\",\n \"sm:h-[46px] sm:text-[0.9375rem]\",\n isPassword ? \"pr-12\" : \"\",\n \"text-foreground placeholder:text-muted-foreground/60\",\n // Focus reads as the border committing rather than as a halo\n // appearing beside it: the ring is tight and the border darkens to\n // full ink in the same 180ms, so the field answers the caret.\n \"transition-[border-color,box-shadow] duration-200 ease-out\",\n \"focus-visible:outline-none focus-visible:ring-2\",\n invalid\n ? \"border-destructive bg-background focus-visible:border-destructive focus-visible:ring-destructive/15\"\n // The default border is foreground/30, not border-input: the\n // latter against a white card lands near 1.3:1, well under the\n // 3:1 WCAG 1.4.11 asks of a control's boundary — the field reads\n // as a faint tint rather than as something to type in.\n : `${fieldClassName} focus-visible:border-foreground focus-visible:ring-foreground/10`,\n \"disabled:cursor-not-allowed disabled:opacity-60\",\n ]\n .filter(Boolean)\n .join(\" \")}\n />\n\n {isPassword && (\n <button\n type=\"button\"\n onClick={() => setRevealed((v) => !v)}\n disabled={props.disabled}\n aria-pressed={revealed}\n aria-label={\n revealed ? \"Masquer le mot de passe\" : \"Afficher le mot de passe\"\n }\n className=\"absolute inset-y-0 right-0 flex w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-60\"\n >\n <EyeIcon open={revealed} />\n </button>\n )}\n </div>\n\n {description && (\n <p id={descriptionId} className=\"text-xs text-muted-foreground\">\n {description}\n </p>\n )}\n </div>\n )\n}\n\n// Inline rather than from lucide-react: the package would gain a dependency\n// consumers already have at a different version, for two paths.\nfunction EyeIcon({ open }: { open: boolean }) {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.75\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M2.06 12.35a1 1 0 0 1 0-.7 10.75 10.75 0 0 1 19.88 0 1 1 0 0 1 0 .7 10.75 10.75 0 0 1-19.88 0Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n {!open && <path d=\"m3 3 18 18\" />}\n </svg>\n )\n}\n","import type { ReactNode } from \"react\"\n\ninterface AuthSubmitProps {\n pending?: boolean\n disabled?: boolean\n pendingLabel: string\n children: ReactNode\n /** Replaces the default `bg-primary text-primary-foreground hover:bg-primary/90` */\n className?: string\n /**\n * Adds the step that detaches the action from the fields above it. The\n * inputs sit on a tighter rhythm so they read as one block to fill in; the\n * button is what you do once that block is done, and an even gap would put\n * it on the same footing as another field.\n */\n spacedAbove?: boolean\n}\n\n/**\n * The primary action of an auth screen.\n *\n * The label swaps to its pending form in place, with the spinner absolutely\n * positioned: a spinner inserted into the flow would widen the row and shift\n * the text sideways at the exact moment the person is watching it.\n *\n * The press feedback is a 1px translate rather than a scale — scaling a\n * full-width button visibly blurs its text mid-transform.\n */\nexport function AuthSubmit({\n pending = false,\n disabled = false,\n pendingLabel,\n children,\n className = \"bg-primary text-primary-foreground hover:bg-primary/90\",\n spacedAbove = false,\n}: AuthSubmitProps) {\n return (\n <button\n type=\"submit\"\n disabled={disabled || pending}\n aria-busy={pending || undefined}\n className={[\n spacedAbove ? \"!mt-7\" : \"\",\n \"relative flex h-[52px] w-full items-center justify-center rounded-md sm:h-[46px]\",\n // Slightly tracked at this weight: a wide solid button set in plain\n // medium reads as a slab, and the letterspacing is what makes it read\n // as typeset rather than filled in.\n \"text-[0.9375rem] font-medium tracking-[0.01em]\",\n className,\n \"transition-[background-color,transform,box-shadow] duration-200 ease-out\",\n \"shadow-[0_1px_2px_rgba(0,0,0,0.08)] hover:shadow-[0_2px_8px_rgba(0,0,0,0.12)]\",\n \"active:translate-y-px active:shadow-[0_1px_2px_rgba(0,0,0,0.08)]\",\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n \"disabled:pointer-events-none disabled:opacity-55\",\n ].join(\" \")}\n >\n {pending && (\n <span\n aria-hidden=\"true\"\n className=\"absolute left-4 size-4 animate-spin rounded-full border-2 border-current border-t-transparent opacity-70 motion-reduce:animate-none\"\n />\n )}\n {pending ? pendingLabel : children}\n </button>\n )\n}\n","import { useState, type FormEvent } from \"react\"\nimport type { LoginFormLabels, LoginFormProps } from \"../types\"\nimport { isEmailNotVerified } from \"../email-not-verified\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\nimport { SocialButtons } from \"./social-buttons\"\nimport { AUTH_HINT_LINK_CLASS, AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport { withInviteToken } from \"../invite-token\"\nimport { oauthErrorCallback } from \"../oauth-error\"\n\nconst DEFAULTS: Required<LoginFormLabels> = {\n title: \"Connexion\",\n subtitle: \"Content de te revoir. Entre tes identifiants pour continuer.\",\n emailPlaceholder: \"Adresse e-mail\",\n passwordPlaceholder: \"Mot de passe\",\n forgotPassword: \"Mot de passe oublié ?\",\n submit: \"Se connecter\",\n submitPending: \"Connexion…\",\n noAccount: \"Pas encore de compte ?\",\n register: \"Créer un compte\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n passwordRequired: \"Renseigne ton mot de passe\",\n invalidCredentials: \"Adresse e-mail ou mot de passe incorrect\",\n emailNotVerified:\n \"Ton adresse e-mail n'est pas encore confirmée. Vérifie ta boîte de réception.\",\n // accountLinking is disabled in createPlatformAuth, so a social sign-in on an\n // address already registered with a password is refused with this code.\n // Without a message the button reads as broken rather than as a rejection.\n accountNotLinked:\n \"Cette adresse est déjà associée à un mot de passe. Connecte-toi avec ton mot de passe.\",\n socialCancelled: \"Connexion annulée.\",\n socialFailed: \"La connexion a échoué. Réessaie.\",\n}\n\nexport function LoginForm({\n onSuccess,\n onEmailNotVerified,\n registerUrl = \"/register\",\n forgotPasswordUrl = \"/forgot-password\",\n socialCallbackUrl = \"/\",\n errorCallbackUrl,\n socialProviders = [],\n coreTokenUrl = \"/api/auth/core-token\",\n labels,\n submitClassName,\n fieldClassName,\n error: externalError,\n linkComponent,\n invite,\n authClient,\n}: LoginFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [email, setEmail] = useState(\"\")\n const [password, setPassword] = useState(\"\")\n const [ownError, setOwnError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n\n // What the person just did outranks what happened before they arrived.\n const error = ownError ?? externalError\n const setError = setOwnError\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setError(t.emailRequired)\n return\n }\n if (!password) {\n setError(t.passwordRequired)\n return\n }\n setError(undefined)\n setIsPending(true)\n try {\n const res = await authClient.signIn.email({\n email: email.trim(),\n password,\n })\n if (res?.error) {\n if (isEmailNotVerified(res.error) && onEmailNotVerified) {\n onEmailNotVerified(email.trim())\n return\n }\n setError(\n isEmailNotVerified(res.error)\n ? t.emailNotVerified\n : (res.error.message ?? t.invalidCredentials),\n )\n return\n }\n // The better-auth session cookie alone does not authenticate a Go core:\n // it verifies the EdDSA JWT minted here against the issuer's JWKS.\n // Skipped when the app sets the token itself, or has no core at all.\n if (coreTokenUrl) {\n await fetch(coreTokenUrl, { credentials: \"include\" })\n }\n onSuccess?.()\n } catch (err) {\n setError(err instanceof Error ? err.message : t.invalidCredentials)\n } finally {\n setIsPending(false)\n }\n }\n\n const handleSocial = async (provider: \"google\" | \"github\") => {\n setError(undefined)\n try {\n await authClient.signIn.social({\n provider,\n // The invitation rides the callback: an OAuth sign-up leaves the\n // browser, and the auth handler redeems the token on the way back.\n callbackURL: withInviteToken(socialCallbackUrl, invite),\n // Resolved here rather than at render: the default is the current page,\n // and this runs in the browser, where there is one.\n errorCallbackURL: oauthErrorCallback(\n errorCallbackUrl,\n \"/login\",\n typeof window !== \"undefined\" ? window.location.pathname : undefined,\n ),\n })\n } catch (err) {\n setError(err instanceof Error ? err.message : t.socialFailed)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n invalid={!!error}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.passwordPlaceholder}\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"current-password\"\n invalid={!!error}\n fieldClassName={fieldClassName}\n hint={\n <AuthLink\n to={forgotPasswordUrl}\n as={linkComponent}\n className={AUTH_HINT_LINK_CLASS}\n >\n {t.forgotPassword}\n </AuthLink>\n }\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n disabled={!email.trim() || !password}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <SocialButtons\n providers={socialProviders}\n onSelect={handleSocial}\n disabled={isPending}\n />\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.noAccount}{\" \"}\n <AuthLink\n to={withInviteToken(registerUrl, invite)}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.register}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// The heading lives in AuthLayout, above the card, so the screen — not the\n// form — passes the copy. Exposing the defaults here keeps the wording in one\n// place: `<AuthLayout {...LoginForm.defaults}>` renders what the form used to.\nLoginForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","import type { AuthClientResult } from \"./types\"\n\n/**\n * Whether a failed sign-in was refused for want of a confirmed address.\n *\n * Better Auth answers an unverified sign-in with EMAIL_NOT_VERIFIED, but only\n * when built with its error codes exposed; otherwise the refusal arrives as a\n * bare 403. No other credential failure on this route uses that status — a\n * wrong password is a 401 — so the status alone is a safe fallback.\n */\nexport function isEmailNotVerified(\n error: AuthClientResult[\"error\"],\n): boolean {\n if (!error) return false\n return error.code === \"EMAIL_NOT_VERIFIED\" || error.status === 403\n}\n","interface AuthAlertProps {\n children?: string\n tone?: \"error\" | \"success\"\n}\n\n/**\n * Inline feedback for an auth screen.\n *\n * `role=\"alert\"` on the wrapper is not enough on its own: the node has to be\n * in the tree before the text lands in it for the live region to fire, which\n * is why the element renders empty rather than being mounted with its message.\n *\n * The success tone uses the theme's own tokens rather than a fixed green,\n * which would sit on a dark surface as an unreadable pale block.\n */\nexport function AuthAlert({ children, tone = \"error\" }: AuthAlertProps) {\n return (\n <div\n role={tone === \"error\" ? \"alert\" : \"status\"}\n aria-live={tone === \"error\" ? \"assertive\" : \"polite\"}\n className={\n children\n ? [\n \"rounded-lg border px-3.5 py-3 text-sm leading-snug\",\n \"motion-safe:animate-[auth-alert-in_180ms_ease-out]\",\n tone === \"error\"\n ? \"border-destructive/25 bg-destructive/10 text-destructive\"\n : \"border-emerald-500/25 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400\",\n ].join(\" \")\n : // Empty it must stay in the tree for the live region to fire, but\n // it must not stay in the layout: a `space-y` counts an empty\n // child as a row, which pushed the first field down by a full step\n // on every screen with no message to show.\n \"hidden\"\n }\n >\n {children}\n </div>\n )\n}\n","const LABELS: Record<string, string> = {\n google: \"Continuer avec Google\",\n github: \"Continuer avec GitHub\",\n}\n\ninterface SocialButtonsProps {\n providers: Array<\"google\" | \"github\">\n onSelect: (provider: \"google\" | \"github\") => void | Promise<void>\n disabled?: boolean\n /** Divider text between the password form and the providers */\n separator?: string\n /** Per-provider button copy, merged over the French defaults */\n labels?: Partial<Record<\"google\" | \"github\", string>>\n}\n\nexport function SocialButtons({\n providers,\n onSelect,\n disabled = false,\n separator = \"ou\",\n labels,\n}: SocialButtonsProps) {\n if (providers.length === 0) return null\n\n const copy = { ...LABELS, ...labels }\n\n return (\n <div className=\"space-y-4\">\n {/* The rule is two flex segments rather than a line behind an opaque\n label: an opaque background only hides the rule when it matches the\n surface behind it, which breaks the moment this sits on a card. */}\n <div aria-hidden=\"true\" className=\"flex items-center gap-3\">\n <span className=\"h-px flex-1 bg-border\" />\n <span className=\"text-[11px] uppercase tracking-[0.14em] text-muted-foreground\">\n {separator}\n </span>\n <span className=\"h-px flex-1 bg-border\" />\n </div>\n\n {/* One per row while there is space for the wording, side by side once\n there are several: in a half-card the full label no longer fits, and\n a truncated \"Continuer avec…\" says less than the mark alone. The\n wording stays as the accessible name either way. */}\n <div\n className={\n providers.length > 1\n ? \"grid gap-2.5 sm:grid-cols-2\"\n : \"grid gap-2.5\"\n }\n >\n {providers.map((provider) => (\n <button\n key={provider}\n type=\"button\"\n onClick={() => onSelect(provider)}\n disabled={disabled}\n aria-label={copy[provider] ?? provider}\n className={[\n \"flex h-[52px] w-full items-center justify-center gap-2.5 rounded-lg sm:h-11\",\n \"border border-foreground/25 bg-background text-base font-medium text-foreground sm:text-sm\",\n \"transition-[background-color,border-color,transform] duration-150 ease-out\",\n \"hover:border-foreground/20 hover:bg-accent active:translate-y-px\",\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n \"disabled:pointer-events-none disabled:opacity-55\",\n ].join(\" \")}\n >\n <ProviderMark provider={provider} />\n <span className={providers.length > 1 ? \"sm:hidden\" : \"\"}>\n {copy[provider] ?? provider}\n </span>\n </button>\n ))}\n </div>\n </div>\n )\n}\n\n// Brand marks are inlined: they must keep their own colors (Google's mark is\n// unusable in monochrome) and adding an icon dependency to this package would\n// duplicate one every consumer already ships.\nfunction ProviderMark({ provider }: { provider: \"google\" | \"github\" }) {\n if (provider === \"google\") {\n return (\n <svg width=\"17\" height=\"17\" viewBox=\"0 0 18 18\" aria-hidden=\"true\">\n <path\n fill=\"#4285F4\"\n d=\"M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62Z\"\n />\n <path\n fill=\"#34A853\"\n d=\"M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.02-3.7H.96v2.33A9 9 0 0 0 9 18Z\"\n />\n <path\n fill=\"#FBBC05\"\n d=\"M3.98 10.72a5.4 5.4 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.02-2.33Z\"\n />\n <path\n fill=\"#EA4335\"\n d=\"M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.46.9 11.43 0 9 0A9 9 0 0 0 .96 4.95l3.02 2.33C4.68 5.16 6.66 3.58 9 3.58Z\"\n />\n </svg>\n )\n }\n return (\n <svg width=\"17\" height=\"17\" viewBox=\"0 0 16 16\" fill=\"currentColor\" aria-hidden=\"true\">\n <path d=\"M8 0a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38l-.01-1.49c-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.4 7.4 0 0 1 4 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48l-.01 2.2c0 .21.15.46.55.38A8 8 0 0 0 8 0Z\" />\n </svg>\n )\n}\n","import type { ReactNode } from \"react\"\nimport type { LinkComponent } from \"../types\"\n\ninterface AuthLinkProps {\n to: string\n as?: LinkComponent\n className?: string\n children: ReactNode\n}\n\n/**\n * A link between auth screens.\n *\n * Falls back to an anchor, which is right for an app without a router and wrong\n * for every app with one: the full page load it triggers restarts the app and\n * loses whatever the URL was carrying.\n */\nexport function AuthLink({ to, as: Link, className, children }: AuthLinkProps) {\n if (Link) {\n return (\n <Link to={to} className={className}>\n {children}\n </Link>\n )\n }\n return (\n <a href={to} className={className}>\n {children}\n </a>\n )\n}\n\nexport const AUTH_LINK_CLASS =\n \"rounded font-medium text-foreground underline underline-offset-4 decoration-foreground/25 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n\nexport const AUTH_HINT_LINK_CLASS =\n \"rounded text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n","/**\n * An invitation token as it may appear in a URL, reduced to something safe to\n * carry through a route search schema.\n *\n * Callers pass raw search params (`Route.validateSearch`), so the input is\n * whatever the address bar held: an array when the param repeats, a number, or\n * a string long enough to be an attack rather than a token. Anything that is\n * not one plausible token collapses to undefined, which reads as \"no\n * invitation\" everywhere downstream.\n */\nconst MAX_TOKEN_LENGTH = 128\n\nexport function normalizeInviteToken(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined\n const trimmed = value.trim()\n if (!trimmed || trimmed.length > MAX_TOKEN_LENGTH) return undefined\n return trimmed\n}\n\n/**\n * Appends the invitation to a link between auth screens.\n *\n * An invitee who lands on /register and clicks through to /login must keep the\n * offer: the token lives only in the URL, so a plain href to the sibling screen\n * silently drops it and the account is created on the default tier.\n */\nexport function withInviteToken(href: string, token?: string): string {\n if (!token) return href\n const separator = href.includes(\"?\") ? \"&\" : \"?\"\n return `${href}${separator}invite=${encodeURIComponent(token)}`\n}\n","export type OAuthErrorLabels = {\n accountNotLinked: string\n socialCancelled: string\n socialFailed: string\n}\n\n/**\n * Turns Better Auth's machine-readable OAuth failure code into something an\n * invitee can act on.\n *\n * `account_not_linked` is the one worth naming: createPlatformAuth disables\n * account linking on purpose, so \"Continue with Google\" on an address already\n * registered with a password is REFUSED. Better Auth's default error route\n * bounces the browser back with nothing shown, so without this the button\n * simply looks broken.\n */\nexport function oauthErrorMessage(\n code: string | null | undefined,\n labels: OAuthErrorLabels,\n): string {\n switch (code) {\n case \"account_not_linked\":\n return labels.accountNotLinked\n case \"access_denied\":\n return labels.socialCancelled\n default:\n return labels.socialFailed\n }\n}\n\n/**\n * Reads the failure Better Auth redirected back with.\n *\n * A social sign-in leaves the app entirely, so component state does not survive\n * it: the only carrier left when the browser returns is the `?error=` Better\n * Auth appends to the errorCallbackURL. Read from the address bar rather than\n * from a typed route search, because the auth routes deliberately declare no\n * search schema — adding one would make `search` required on every navigate to\n * them across the app.\n */\nexport function initialOAuthError(\n labels: OAuthErrorLabels,\n param = \"error\",\n): string | undefined {\n if (typeof window === \"undefined\") return undefined\n const code = new URLSearchParams(window.location.search).get(param)\n if (!code) return undefined\n return oauthErrorMessage(code, labels)\n}\n\n/**\n * Where a refused social sign-in should send the browser back to.\n *\n * Falls back to the page the form is on, which is the one that reads `?error=`\n * and renders it. Better Auth would otherwise keep the browser on its own\n * error route, where nothing shows the code and the button reads as broken.\n * `fallback` covers the server render, where there is no current page to name.\n */\nexport function oauthErrorCallback(\n explicit: string | undefined,\n fallback: string,\n currentPath: string | undefined,\n): string {\n return explicit ?? currentPath ?? fallback\n}\n\n/**\n * Drops the failure from the address bar once it has been shown.\n *\n * Without this the message comes back on every reload, and outlives the retry\n * that succeeded. replaceState rather than a router navigate: these screens\n * have no typed search to navigate against, and the entry being rewritten is\n * the one the OAuth provider pushed, not one the person chose.\n */\nexport function clearOAuthError(param = \"error\"): void {\n if (typeof window === \"undefined\") return\n const url = new URL(window.location.href)\n if (!url.searchParams.has(param)) return\n url.searchParams.delete(param)\n window.history.replaceState({}, \"\", url.toString())\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport { withInviteToken } from \"../invite-token\"\nimport { withSignUpName } from \"../signup-name\"\nimport { oauthErrorCallback } from \"../oauth-error\"\nimport type { RegisterFormLabels, RegisterFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\nimport { SocialButtons } from \"./social-buttons\"\n\nconst MIN_PASSWORD_LENGTH = 8\n\nconst DEFAULTS: Required<RegisterFormLabels> = {\n title: \"Créer un compte\",\n subtitle: \"Nous t'enverrons un code pour confirmer ton adresse e-mail.\",\n namePlaceholder: \"Nom complet\",\n optional: \"facultatif\",\n emailPlaceholder: \"Adresse e-mail\",\n emailLocked: \"Ton invitation est liée à cette adresse.\",\n passwordPlaceholder: \"Mot de passe\",\n passwordHint: `Au moins ${MIN_PASSWORD_LENGTH} caractères.`,\n confirmPlaceholder: \"Confirme le mot de passe\",\n passwordMismatch: \"Les deux mots de passe ne correspondent pas\",\n submit: \"Créer mon compte\",\n submitPending: \"Création…\",\n haveAccount: \"Tu as déjà un compte ?\",\n login: \"Se connecter\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n passwordTooShort: `Le mot de passe doit faire au moins ${MIN_PASSWORD_LENGTH} caractères`,\n signUpFailed: \"La création du compte a échoué\",\n // accountLinking is disabled in createPlatformAuth, so signing up with Google\n // on an address already registered is refused rather than folded into the\n // existing account.\n accountNotLinked:\n \"Cette adresse a déjà un compte. Connecte-toi avec ton mot de passe.\",\n socialCancelled: \"Inscription annulée.\",\n socialFailed: \"La création du compte a échoué. Réessaie.\",\n}\n\nexport function RegisterForm({\n lockedEmail,\n onSuccess,\n loginUrl = \"/login\",\n legal,\n socialCallbackUrl = \"/\",\n errorCallbackUrl,\n socialProviders = [],\n labels,\n submitClassName,\n fieldClassName,\n error: externalError,\n linkComponent,\n invite,\n collectName = true,\n authClient,\n}: RegisterFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [name, setName] = useState(\"\")\n const [typedEmail, setTypedEmail] = useState(\"\")\n const email = lockedEmail ?? typedEmail\n const [password, setPassword] = useState(\"\")\n const [confirmPassword, setConfirmPassword] = useState(\"\")\n const [ownError, setOwnError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n\n // What the person just did outranks what happened before they arrived.\n const error = ownError ?? externalError\n const setError = setOwnError\n\n const tooShort = password.length > 0 && password.length < MIN_PASSWORD_LENGTH\n const mismatch = confirmPassword.length > 0 && confirmPassword !== password\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setError(t.emailRequired)\n return\n }\n if (password.length < MIN_PASSWORD_LENGTH) {\n setError(t.passwordTooShort)\n return\n }\n if (password !== confirmPassword) {\n setError(t.passwordMismatch)\n return\n }\n setError(undefined)\n setIsPending(true)\n try {\n // `name` is always sent: Better Auth types it as a required string and\n // its schema rejects the request before any hook runs, so omitting the\n // key when the field is blank fails with `[body.name] Invalid input`.\n const res = await authClient.signUp.email(\n withSignUpName({ name, email: email.trim(), password }),\n )\n if (res?.error) {\n setError(res.error.message ?? t.signUpFailed)\n return\n }\n // createPlatformAuth sets requireEmailVerification, so sign-up leaves the\n // account unverified and without a session: the caller routes to the OTP\n // step rather than into the app.\n onSuccess?.(email.trim())\n } catch (err) {\n setError(err instanceof Error ? err.message : t.signUpFailed)\n } finally {\n setIsPending(false)\n }\n }\n\n const handleSocial = async (provider: \"google\" | \"github\") => {\n setError(undefined)\n try {\n await authClient.signIn.social({\n provider,\n // The invitation rides the callback: an OAuth sign-up leaves the\n // browser, and the auth handler redeems the token on the way back.\n callbackURL: withInviteToken(socialCallbackUrl, invite),\n // Resolved here rather than at render: the default is the current page,\n // and this runs in the browser, where there is one.\n errorCallbackURL: oauthErrorCallback(\n errorCallbackUrl,\n \"/register\",\n typeof window !== \"undefined\" ? window.location.pathname : undefined,\n ),\n })\n } catch (err) {\n setError(err instanceof Error ? err.message : t.socialFailed)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n {collectName && (\n <AuthField\n label={t.namePlaceholder}\n type=\"text\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n disabled={isPending}\n autoComplete=\"name\"\n fieldClassName={fieldClassName}\n hint={\n <span className=\"text-xs text-muted-foreground\">\n {t.optional}\n </span>\n }\n />\n )}\n\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => setTypedEmail(e.target.value)}\n required\n // readOnly rather than disabled: a disabled field is skipped by the\n // tab order and drops out of the accessibility tree, so the address\n // the account is being created for would go unread.\n readOnly={!!lockedEmail}\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n description={lockedEmail ? t.emailLocked : undefined}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.passwordPlaceholder}\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"new-password\"\n description={t.passwordHint}\n // Only once they have typed something: flagging an untouched field\n // red would scold someone for not having started yet.\n invalid={tooShort}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.confirmPlaceholder}\n type=\"password\"\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"new-password\"\n invalid={mismatch}\n fieldClassName={fieldClassName}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n\n {legal && (\n <p className=\"text-center text-xs leading-relaxed text-muted-foreground\">\n {legal}\n </p>\n )}\n </form>\n\n <SocialButtons\n providers={socialProviders}\n onSelect={handleSocial}\n disabled={isPending}\n />\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.haveAccount}{\" \"}\n <AuthLink\n to={withInviteToken(loginUrl, invite)}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nRegisterForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport type { VerifyEmailFormLabels, VerifyEmailFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthOtpField, OTP_LENGTH } from \"./auth-otp-field\"\nimport { AuthSubmit } from \"./auth-submit\"\n\nconst DEFAULTS: Required<VerifyEmailFormLabels> = {\n title: \"Vérifie ton adresse\",\n subtitle: \"Entre le code à 6 chiffres envoyé à\",\n subtitleNoEmail: \"Entre le code à 6 chiffres reçu par e-mail.\",\n codePlaceholder: \"Code de vérification\",\n submit: \"Vérifier\",\n submitPending: \"Vérification…\",\n resend: \"Renvoyer le code\",\n resendPending: \"Envoi…\",\n resent: \"Un nouveau code vient de t'être envoyé.\",\n alreadyVerified: \"Adresse déjà vérifiée ?\",\n login: \"Se connecter\",\n codeRequired: \"Entre le code à 6 chiffres\",\n invalidCode: \"Code invalide. Réessaie.\",\n resendFailed: \"L'envoi du code a échoué\",\n missingEmail: \"Adresse e-mail introuvable. Recommence l'inscription.\",\n}\n\nexport function VerifyEmailForm({\n email,\n onSuccess,\n loginUrl = \"/login\",\n labels,\n submitClassName,\n fieldClassName,\n linkComponent,\n authClient,\n}: VerifyEmailFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [otp, setOtp] = useState(\"\")\n const [isVerifying, setIsVerifying] = useState(false)\n const [isResending, setIsResending] = useState(false)\n const [resendMessage, setResendMessage] = useState<string | undefined>()\n const [error, setError] = useState<string | undefined>()\n\n const handleVerify = async (e: FormEvent) => {\n e.preventDefault()\n if (otp.length < OTP_LENGTH) {\n setError(t.codeRequired)\n return\n }\n setError(undefined)\n setResendMessage(undefined)\n setIsVerifying(true)\n try {\n const res = await authClient.emailOtp.verifyEmail({ email, otp })\n if (res?.error) {\n setError(res.error.message ?? t.invalidCode)\n return\n }\n onSuccess?.()\n } catch (err) {\n setError(err instanceof Error ? err.message : t.invalidCode)\n } finally {\n setIsVerifying(false)\n }\n }\n\n const handleResend = async () => {\n if (!email) {\n setError(t.missingEmail)\n return\n }\n setError(undefined)\n setResendMessage(undefined)\n setIsResending(true)\n try {\n await authClient.emailOtp.sendVerificationOtp({\n email,\n type: \"email-verification\",\n })\n setResendMessage(t.resent)\n } catch (err) {\n setError(err instanceof Error ? err.message : t.resendFailed)\n } finally {\n setIsResending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n <AuthAlert tone=\"success\">{resendMessage}</AuthAlert>\n\n <form onSubmit={handleVerify} className=\"space-y-[1.125rem]\" noValidate>\n <AuthOtpField\n id=\"verify-email-otp\"\n label={t.codePlaceholder}\n value={otp}\n onChange={setOtp}\n disabled={isVerifying}\n fieldClassName={fieldClassName}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isVerifying}\n disabled={otp.length < OTP_LENGTH}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <div className=\"space-y-4 text-center text-sm text-muted-foreground\">\n <button\n type=\"button\"\n onClick={handleResend}\n disabled={isResending}\n className=\"rounded font-medium text-foreground underline underline-offset-4 decoration-foreground/25 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-55\"\n >\n {isResending ? t.resendPending : t.resend}\n </button>\n\n <p>\n {t.alreadyVerified}{\" \"}\n <AuthLink\n to={loginUrl}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nVerifyEmailForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","interface AuthOtpFieldProps {\n label: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n invalid?: boolean\n id: string\n /** Replaces the default border and background utilities */\n fieldClassName?: string\n}\n\nexport const OTP_LENGTH = 6\n\n/**\n * The 6-digit code field.\n *\n * Not an AuthField: the value is a code being read off another screen, so it\n * is spaced and monospaced to be checked digit by digit, and non-digits are\n * dropped on the way in — pasting a code from a mail client routinely carries\n * a trailing space.\n */\nexport function AuthOtpField({\n label,\n value,\n onChange,\n disabled = false,\n invalid = false,\n id,\n fieldClassName = \"border-foreground/25 bg-background\",\n}: AuthOtpFieldProps) {\n return (\n <div className=\"space-y-2\">\n <label\n htmlFor={id}\n className=\"block text-[0.6875rem] font-semibold uppercase leading-none tracking-[0.09em] text-foreground/70\"\n >\n {label}\n </label>\n <input\n id={id}\n type=\"text\"\n inputMode=\"numeric\"\n pattern=\"[0-9]*\"\n maxLength={OTP_LENGTH}\n value={value}\n onChange={(e) => onChange(e.target.value.replace(/\\D/g, \"\"))}\n required\n disabled={disabled}\n autoComplete=\"one-time-code\"\n aria-invalid={invalid || undefined}\n className={[\n \"h-[52px] w-full rounded-lg border px-4 sm:h-11\",\n \"text-center font-mono text-lg tracking-[0.4em]\",\n \"text-foreground\",\n \"transition-[border-color,box-shadow] duration-150 ease-out\",\n \"focus-visible:outline-none focus-visible:ring-[3px]\",\n invalid\n ? \"border-destructive bg-background focus-visible:border-destructive focus-visible:ring-destructive/20\"\n : `${fieldClassName} focus-visible:border-ring focus-visible:ring-ring/15`,\n \"disabled:cursor-not-allowed disabled:opacity-60\",\n ].join(\" \")}\n />\n </div>\n )\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport type {\n ForgotPasswordFormLabels,\n ForgotPasswordFormProps,\n} from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\n\nconst DEFAULTS: Required<ForgotPasswordFormLabels> = {\n title: \"Mot de passe oublié ?\",\n subtitle:\n \"Entre ton adresse e-mail et nous t'enverrons un code pour le réinitialiser.\",\n emailPlaceholder: \"Adresse e-mail\",\n submit: \"Envoyer le code\",\n submitPending: \"Envoi…\",\n rememberPassword: \"Tu t'en souviens finalement ?\",\n login: \"Se connecter\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n sendFailed: \"L'envoi du code a échoué\",\n}\n\nexport function ForgotPasswordForm({\n onSuccess,\n loginUrl = \"/login\",\n labels,\n submitClassName,\n fieldClassName,\n linkComponent,\n authClient,\n}: ForgotPasswordFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [email, setEmail] = useState(\"\")\n const [error, setError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setError(t.emailRequired)\n return\n }\n setError(undefined)\n setIsPending(true)\n try {\n const res = await authClient.emailOtp.sendVerificationOtp({\n email: email.trim(),\n type: \"forget-password\",\n })\n if (res?.error) {\n setError(res.error.message ?? t.sendFailed)\n return\n }\n onSuccess?.(email.trim())\n } catch (err) {\n setError(err instanceof Error ? err.message : t.sendFailed)\n } finally {\n setIsPending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n invalid={!!error}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n disabled={!email.trim()}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.rememberPassword}{\" \"}\n <AuthLink\n to={loginUrl}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nForgotPasswordForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","import { useState, type FormEvent } from \"react\"\nimport type { MagicLinkFormLabels, MagicLinkFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport { withInviteToken } from \"../invite-token\"\nimport { magicLinkErrorCallback } from \"../magic-link-error\"\n\n/**\n * Sign-in by emailed link.\n *\n * The confirmation says a link was sent, never that an account exists: Better\n * Auth answers the send the same way either way, and only refuses at the\n * /magic-link/verify hop. That is deliberate on its part — a form that\n * distinguished the two would tell an anonymous caller which addresses are\n * registered. Every failure past the send therefore comes back as a `?error=`\n * on the errorCallbackURL, which is what magicLinkErrorMessage reads — and\n * which defaults to this page, since asking for another link is the fix.\n */\n\nconst DEFAULTS: Required<MagicLinkFormLabels> = {\n title: \"Connexion par lien\",\n subtitle:\n \"Entre ton adresse e-mail et nous t'enverrons un lien pour te connecter, sans mot de passe.\",\n emailPlaceholder: \"Adresse e-mail\",\n submit: \"Envoyer le lien\",\n submitPending: \"Envoi…\",\n sent: \"Lien envoyé. Ouvre ta boîte de réception pour te connecter — il expire dans 5 minutes.\",\n resend: \"Renvoyer le lien\",\n usePassword: \"Tu préfères ton mot de passe ?\",\n login: \"Se connecter\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n sendFailed: \"L'envoi du lien a échoué\",\n}\n\nexport function MagicLinkForm({\n onSuccess,\n loginUrl = \"/login\",\n callbackUrl = \"/\",\n newUserCallbackUrl,\n errorCallbackUrl,\n labels,\n submitClassName,\n fieldClassName,\n error: externalError,\n linkComponent,\n invite,\n authClient,\n}: MagicLinkFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [email, setEmail] = useState(\"\")\n const [ownError, setOwnError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n const [isSent, setIsSent] = useState(false)\n\n const error = ownError ?? externalError\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setOwnError(t.emailRequired)\n return\n }\n setOwnError(undefined)\n setIsPending(true)\n try {\n const res = await authClient.signIn.magicLink({\n email: email.trim(),\n // The invitation rides the callback: following the link leaves the\n // browser on the mail client, so the auth handler redeems the token on\n // the way back, as it does for OAuth.\n callbackURL: withInviteToken(callbackUrl, invite),\n ...(newUserCallbackUrl\n ? { newUserCallbackURL: withInviteToken(newUserCallbackUrl, invite) }\n : {}),\n // Resolved here rather than at render: the default is the current page,\n // and this runs in the browser, where there is one.\n errorCallbackURL: withInviteToken(\n magicLinkErrorCallback(\n errorCallbackUrl,\n loginUrl,\n typeof window !== \"undefined\"\n ? window.location.pathname\n : undefined,\n ),\n invite,\n ),\n })\n if (res?.error) {\n setOwnError(res.error.message ?? t.sendFailed)\n return\n }\n setIsSent(true)\n onSuccess?.(email.trim())\n } catch (err) {\n setOwnError(err instanceof Error ? err.message : t.sendFailed)\n } finally {\n setIsPending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n {/* Kept out of the error alert's node so the two live regions stay\n distinct — a success replacing an error in the same node is announced\n as a change to the error. */}\n <AuthAlert tone=\"success\">{!error && isSent ? t.sent : undefined}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => {\n setEmail(e.target.value)\n // Editing the address invalidates what was said about the last\n // one: the confirmation named an inbox this is no longer it.\n setIsSent(false)\n }}\n required\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n invalid={!!error}\n fieldClassName={fieldClassName}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n disabled={!email.trim()}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {isSent ? t.resend : t.submit}\n </AuthSubmit>\n </form>\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.usePassword}{\" \"}\n <AuthLink\n to={withInviteToken(loginUrl, invite)}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nMagicLinkForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","/**\n * Where a link that did not work should send the browser back to.\n *\n * Falls back to the current page rather than to Better Auth's own default,\n * which is the success callback: that is a signed-in destination, so an auth\n * guard bounces the visitor and drops the `?error=` on the way, and an expired\n * link ends up looking like nothing happened. `fallback` covers the server\n * render, where there is no current page to name.\n */\nexport function magicLinkErrorCallback(\n explicit: string | undefined,\n fallback: string,\n currentPath: string | undefined,\n): string {\n return explicit ?? currentPath ?? fallback\n}\n\nexport type MagicLinkErrorLabels = {\n invalidToken: string\n signUpDisabled: string\n failed: string\n}\n\nexport const MAGIC_LINK_ERROR_DEFAULTS: MagicLinkErrorLabels = {\n invalidToken:\n \"Ce lien n'est plus valide. Il expire après 5 minutes et ne fonctionne qu'une fois — demandes-en un nouveau.\",\n signUpDisabled:\n \"Aucun compte n'existe pour cette adresse. Crée-en un d'abord.\",\n failed: \"La connexion par lien a échoué. Réessaie.\",\n}\n\n/**\n * Turns the failure a followed magic link redirected back with into something\n * the person can act on.\n *\n * Every way the flow can fail lands here rather than on the send: Better Auth\n * consumes the token at /magic-link/verify, and any refusal there is thrown as\n * a redirect to the errorCallbackURL. `INVALID_TOKEN` covers expiry and reuse\n * alike — the token is consumed atomically on first use, so a link followed\n * twice is indistinguishable from one that timed out, and the copy names both.\n */\nexport function magicLinkErrorMessage(\n code: string | null | undefined,\n labels: Partial<MagicLinkErrorLabels> = {},\n): string {\n const t = { ...MAGIC_LINK_ERROR_DEFAULTS, ...labels }\n switch (code) {\n case \"INVALID_TOKEN\":\n return t.invalidToken\n case \"new_user_signup_disabled\":\n return t.signUpDisabled\n default:\n return t.failed\n }\n}\n\n/** Codes this module recognises, so a shared handler can tell them apart. */\nconst MAGIC_LINK_ERROR_CODES = new Set([\n \"INVALID_TOKEN\",\n \"new_user_signup_disabled\",\n \"failed_to_create_user\",\n \"failed_to_create_session\",\n])\n\n/**\n * Whether a `?error=` came from a magic link rather than from OAuth.\n *\n * Both flows return to the same screens through the same parameter, so a page\n * offering the two needs to know which vocabulary to read the code against —\n * otherwise an expired link is reported as a failed social sign-in.\n */\nexport function isMagicLinkError(code: string | null | undefined): boolean {\n return !!code && MAGIC_LINK_ERROR_CODES.has(code)\n}\n\n/**\n * Reads the failure a followed link redirected back with.\n *\n * Following a link leaves the app entirely, so no component state survives it;\n * the address bar is the only carrier left. Mirrors initialOAuthError, down to\n * reading `window.location` rather than a typed route search — the auth routes\n * declare none on purpose.\n */\nexport function initialMagicLinkError(\n labels: Partial<MagicLinkErrorLabels> = {},\n param = \"error\",\n): string | undefined {\n if (typeof window === \"undefined\") return undefined\n const code = new URLSearchParams(window.location.search).get(param)\n if (!isMagicLinkError(code)) return undefined\n return magicLinkErrorMessage(code, labels)\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport type { ResetPasswordFormLabels, ResetPasswordFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthOtpField, OTP_LENGTH } from \"./auth-otp-field\"\nimport { AuthSubmit } from \"./auth-submit\"\n\nconst MIN_PASSWORD_LENGTH = 8\n\nconst DEFAULTS: Required<ResetPasswordFormLabels> = {\n title: \"Nouveau mot de passe\",\n subtitle: \"Entre le code à 6 chiffres reçu par e-mail et ton nouveau mot de passe.\",\n codePlaceholder: \"Code de vérification\",\n passwordPlaceholder: \"Nouveau mot de passe\",\n passwordHint: `Au moins ${MIN_PASSWORD_LENGTH} caractères.`,\n confirmPlaceholder: \"Confirme le mot de passe\",\n submit: \"Réinitialiser\",\n submitPending: \"Réinitialisation…\",\n resend: \"Renvoyer le code\",\n resendPending: \"Envoi…\",\n resent: \"Un nouveau code vient de t'être envoyé.\",\n rememberPassword: \"Tu t'en souviens finalement ?\",\n login: \"Se connecter\",\n codeRequired: \"Entre le code à 6 chiffres\",\n passwordTooShort: `Le mot de passe doit faire au moins ${MIN_PASSWORD_LENGTH} caractères`,\n passwordMismatch: \"Les deux mots de passe ne correspondent pas\",\n resetFailed: \"La réinitialisation a échoué\",\n resendFailed: \"L'envoi du code a échoué\",\n}\n\nexport function ResetPasswordForm({\n email,\n onSuccess,\n loginUrl = \"/login\",\n labels,\n submitClassName,\n fieldClassName,\n linkComponent,\n authClient,\n}: ResetPasswordFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [otp, setOtp] = useState(\"\")\n const [password, setPassword] = useState(\"\")\n const [confirmPassword, setConfirmPassword] = useState(\"\")\n const [error, setError] = useState<string | undefined>()\n const [isResetting, setIsResetting] = useState(false)\n const [isResending, setIsResending] = useState(false)\n const [resendMessage, setResendMessage] = useState<string | undefined>()\n\n const tooShort = password.length > 0 && password.length < MIN_PASSWORD_LENGTH\n const mismatch = confirmPassword.length > 0 && confirmPassword !== password\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (otp.length < OTP_LENGTH) {\n setError(t.codeRequired)\n return\n }\n if (password.length < MIN_PASSWORD_LENGTH) {\n setError(t.passwordTooShort)\n return\n }\n if (password !== confirmPassword) {\n setError(t.passwordMismatch)\n return\n }\n setError(undefined)\n setResendMessage(undefined)\n setIsResetting(true)\n try {\n const res = await fetch(\"/api/auth/email-otp/reset-password\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, otp, password }),\n })\n if (!res.ok) {\n const body = await res.json().catch(() => null)\n setError(body?.message ?? t.resetFailed)\n return\n }\n onSuccess?.()\n } catch (err) {\n setError(err instanceof Error ? err.message : t.resetFailed)\n } finally {\n setIsResetting(false)\n }\n }\n\n const handleResend = async () => {\n setError(undefined)\n setResendMessage(undefined)\n setIsResending(true)\n try {\n await authClient.emailOtp.sendVerificationOtp({\n email,\n type: \"forget-password\",\n })\n setResendMessage(t.resent)\n } catch (err) {\n setError(err instanceof Error ? err.message : t.resendFailed)\n } finally {\n setIsResending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n <AuthAlert tone=\"success\">{resendMessage}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthOtpField\n id=\"reset-password-otp\"\n label={t.codePlaceholder}\n value={otp}\n onChange={setOtp}\n disabled={isResetting}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.passwordPlaceholder}\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n disabled={isResetting}\n autoComplete=\"new-password\"\n description={t.passwordHint}\n invalid={tooShort}\n />\n\n <AuthField\n label={t.confirmPlaceholder}\n type=\"password\"\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n required\n disabled={isResetting}\n autoComplete=\"new-password\"\n invalid={mismatch}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isResetting}\n disabled={otp.length < OTP_LENGTH || !password || !confirmPassword}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <div className=\"space-y-4 text-center text-sm text-muted-foreground\">\n <button\n type=\"button\"\n onClick={handleResend}\n disabled={isResending}\n className=\"rounded font-medium text-foreground underline underline-offset-4 decoration-foreground/25 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-55\"\n >\n {isResending ? t.resendPending : t.resend}\n </button>\n\n <p>\n {t.rememberPassword}{\" \"}\n <AuthLink\n to={loginUrl}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nResetPasswordForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","interface AuthHeadingProps {\n title: string\n subtitle?: string\n /** Replaces the default size and weight — pass the whole look */\n titleClassName?: string\n}\n\n/**\n * The heading of an auth screen.\n *\n * This screen is the only one someone sees before they have any reason to\n * trust the product, so the type carries it: the title is the screen's centre\n * of gravity, set large and tightly tracked, with the subtitle stepping well\n * back rather than competing.\n *\n * Optical sizing matters at this weight — `text-balance` keeps a two-line\n * subtitle from breaking into a lonely last word, which reads as an accident\n * where everything else is deliberate.\n */\nexport function AuthHeading({\n title,\n subtitle,\n titleClassName = \"text-[2rem] font-semibold leading-[1.1] tracking-[-0.03em] sm:text-[2.25rem]\",\n}: AuthHeadingProps) {\n return (\n <header className=\"space-y-2.5 text-center\">\n <h1 className={titleClassName}>{title}</h1>\n {subtitle && (\n <p className=\"text-balance text-[0.9375rem] leading-relaxed text-muted-foreground\">\n {subtitle}\n </p>\n )}\n </header>\n )\n}\n","import type { AuthLayoutProps } from \"../types\"\nimport { AuthHeading } from \"./auth-heading\"\n\n/**\n * The frame every auth screen sits in. It owns the ground, the heading and the\n * app's own marks (logo, illustration, legal footer); the card holds only the\n * fields and their actions.\n *\n * The heading sits ABOVE the card rather than inside it: the card is then\n * exactly the thing you fill in, and the mark reads as the app's rather than\n * as the form's first row.\n *\n * Mobile and desktop are two layouts, not one scaled down. On a phone the form\n * IS the page: no card, no border, edge-to-edge padding, top-aligned so the\n * fields stay above the keyboard instead of being pushed under it by vertical\n * centering. From sm up it becomes a bounded card on a tinted ground — a\n * full-width form on a 1440px display is unreadable.\n *\n * A `panel` is an app-supplied illustration and nothing else: without one the\n * card stays a single column rather than inventing decoration to fill a half\n * it has no content for. When given, it takes the LEFT half from md up and is\n * dropped below that width — a decorative half-screen above a form costs a\n * full swipe before the first field.\n *\n * min-h-dvh rather than min-h-screen: on mobile browsers 100vh includes the\n * retracting URL bar, so a screen-height container overflows by its height.\n */\nexport function AuthLayout({\n logo,\n panel,\n title,\n subtitle,\n titleClassName,\n children,\n footer,\n}: AuthLayoutProps) {\n return (\n <div\n className={[\n \"relative flex min-h-dvh flex-col px-5 pb-12 pt-14 sm:items-center sm:px-6 sm:py-20\",\n // With a panel the colour IS the mobile ground and the card sits on\n // it; the split card only exists once there is width for two columns.\n panel\n ? \"bg-transparent md:bg-muted/30\"\n : \"bg-background sm:bg-muted/30\",\n ].join(\" \")}\n >\n {panel && (\n // A band, not a full ground: the card below reaches the bottom of the\n // screen, so the colour only has to sit behind the heading. Covering\n // the whole height would leave the panel's own copy showing under the\n // card, which reads as a second, half-hidden screen.\n <div\n aria-hidden=\"true\"\n className=\"absolute inset-x-0 top-0 -z-10 h-64 overflow-hidden md:hidden [&>*]:h-full [&>*]:w-full [&>img]:object-cover\"\n >\n {panel}\n </div>\n )}\n\n <div className={`mx-auto w-full ${panel ? \"max-w-4xl\" : \"max-w-[440px]\"}`}>\n {(logo || title) && (\n // The mark sits tight above the title so the two read as one block\n // rather than as a stray label; the gap down to the card is the\n // largest on the screen — that step is what separates \"who this is\"\n // from \"what you do here\".\n <div\n className={[\n \"mb-8 space-y-3\",\n // Over the colour field the heading is on the panel, not on the\n // page, so it takes the panel's ink until the split puts it back\n // on a light ground.\n panel\n ? \"text-white [&_p]:text-white/75 md:text-foreground md:[&_p]:text-muted-foreground\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {logo && <div className=\"flex justify-center\">{logo}</div>}\n {title && (\n <AuthHeading\n title={title}\n subtitle={subtitle}\n titleClassName={titleClassName}\n />\n )}\n </div>\n )}\n\n <div\n className={[\n \"sm:rounded-xl sm:border sm:border-foreground/[0.08] sm:bg-card\",\n \"sm:shadow-[0_1px_2px_rgba(0,0,0,0.04),0_8px_24px_-12px_rgba(0,0,0,0.10)]\",\n // On the colour band the card is a sheet rising from the bottom of\n // the screen: rounded at the top only, and stretched past the\n // viewport so no ground shows beneath it however short the form.\n panel\n ? \"-mx-5 -mb-12 min-h-[60vh] rounded-t-2xl bg-card shadow-[0_-8px_32px_-12px_rgba(0,0,0,0.18)] sm:mx-0 sm:mb-0 sm:min-h-0 sm:overflow-hidden sm:rounded-xl md:grid md:grid-cols-2\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {panel && (\n // Decorative: it must never carry information the form does not,\n // so it is hidden from assistive tech rather than described.\n <div\n aria-hidden=\"true\"\n className=\"relative hidden overflow-hidden bg-muted md:block [&>*]:absolute [&>*]:inset-0 [&>*]:h-full [&>*]:w-full [&>img]:object-cover\"\n >\n {panel}\n </div>\n )}\n\n <div className={panel ? \"px-5 pb-12 pt-7 sm:p-7\" : \"sm:p-7\"}>\n {children}\n </div>\n </div>\n\n {footer && (\n <div className=\"mt-8 text-center text-xs leading-relaxed text-muted-foreground\">\n {footer}\n </div>\n )}\n </div>\n </div>\n )\n}\n","import type { InvitationNoticeProps } from \"../types\"\n\n/**\n * Every app is reachable at contact@ its own apex domain, so the address is\n * derived rather than configured. Sub-domains are stripped because the app is\n * routinely served from app./admin. while the mailbox lives on the apex;\n * multi-part public suffixes (.co.uk) would need a real suffix list and no app\n * using this is on one.\n */\nfunction defaultSupportEmail(): string | undefined {\n if (typeof window === \"undefined\") return undefined\n const host = window.location.hostname\n if (!host || host === \"localhost\" || /^[\\d.]+$/.test(host)) return undefined\n const apex = host.split(\".\").slice(-2).join(\".\")\n return `contact@${apex}`\n}\n\nconst REASON_MESSAGE: Record<string, string> = {\n expired: \"Cette invitation a expiré.\",\n claimed: \"Cette invitation a déjà été utilisée.\",\n unknown: \"Ce lien d'invitation n'est pas valide.\",\n}\n\n/**\n * What an invitee sees when their link does not work.\n *\n * It names the reason instead of merging the cases into one message: \"expired\"\n * tells someone their link was real and that asking for another one is worth\n * it, which \"invalid\" does not. Short TTLs make that distinction routine.\n *\n * The only way forward offered is a mailto, deliberately. A self-service\n * \"request a new invitation\" form would mean a public endpoint accepting dead\n * tokens, a queue to moderate, and a way to probe which tokens once existed —\n * for a flow where the operator already knows the person by name.\n */\nexport function InvitationNotice({\n reason = \"unknown\",\n supportEmail,\n title = \"Invitation indisponible\",\n action,\n}: InvitationNoticeProps) {\n const contact = supportEmail ?? defaultSupportEmail()\n\n return (\n <div className=\"space-y-8\">\n <div>\n <h1 className=\"text-2xl font-bold tracking-tight\">{title}</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n {REASON_MESSAGE[reason] ?? REASON_MESSAGE.unknown}\n </p>\n </div>\n\n {contact ? (\n <p className=\"text-sm text-muted-foreground\">\n Écrivez-nous à{\" \"}\n <a\n href={`mailto:${contact}`}\n className=\"font-medium text-foreground underline underline-offset-4 hover:text-foreground/80\"\n >\n {contact}\n </a>{\" \"}\n pour en recevoir une nouvelle.\n </p>\n ) : null}\n\n {action}\n </div>\n )\n}\n"],"mappings":";;;;;;AAMO,SAAS,WAAW,YAAgC;AACzD,SAAO,WAAW,WAAW;AAC/B;AAMO,SAAS,UAAU,YAAgC;AACxD,QAAM,UAAU,YAAY;AAC1B,UAAM,WAAW,QAAQ;AAAA,EAC3B;AACA,SAAO;AACT;;;ACnBA,SAAS,OAAO,gBAA0D;AA+CpE,SAGE,KAHF;AAjBC,SAAS,UAAU;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,GAAG;AACL,GAAmB;AACjB,QAAM,KAAK,MAAM;AACjB,QAAM,gBAAgB,cAAc,GAAG,EAAE,iBAAiB;AAC1D,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS,KAAK;AAE9C,QAAM,aAAa,MAAM,SAAS;AAClC,QAAM,OAAO,cAAc,WAAW,SAAS,MAAM;AAErD,SACE,qBAAC,SAAI,WAAU,aACb;AAAA,yBAAC,SAAI,WAAU,6CAGb;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,SAAS;AAAA,UACT,WAAU;AAAA,UAET;AAAA;AAAA,MACH;AAAA,MACC;AAAA,OACH;AAAA,IAEA,qBAAC,SAAI,WAAU,YACb;AAAA;AAAA,QAAC;AAAA;AAAA,UACE,GAAG;AAAA,UACJ;AAAA,UACA;AAAA,UACA,gBAAc,WAAW;AAAA,UACzB,oBAAkB;AAAA,UAClB,WAAW;AAAA,YACT;AAAA,YACA;AAAA,YACA,aAAa,UAAU;AAAA,YACvB;AAAA;AAAA;AAAA;AAAA,YAIA;AAAA,YACA;AAAA,YACA,UACI,wGAKA,GAAG,cAAc;AAAA,YACrB;AAAA,UACF,EACG,OAAO,OAAO,EACd,KAAK,GAAG;AAAA;AAAA,MACb;AAAA,MAEC,cACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UAC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AAU,kEACZ,kBACH;AAAA,WAEJ;AAAA;AAAA;AAAA,EACF;AAEJ;;;ACnFM,SACE,OAAAE,OADF,QAAAC,cAAA;AApCN,SAAS,sBAA0C;AACjD,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,OAAO,OAAO,SAAS;AAC7B,MAAI,CAAC,QAAQ,SAAS,eAAe,WAAW,KAAK,IAAI,EAAG,QAAO;AACnE,QAAM,OAAO,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,EAAE,KAAK,GAAG;AAC/C,SAAO,WAAW,IAAI;AACxB;AAEA,IAAM,iBAAyC;AAAA,EAC7C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AACX;AAcO,SAAS,iBAAiB;AAAA,EAC/B,SAAS;AAAA,EACT;AAAA,EACA,QAAQ;AAAA,EACR;AACF,GAA0B;AACxB,QAAM,UAAU,gBAAgB,oBAAoB;AAEpD,SACE,gBAAAA,OAAC,SAAI,WAAU,aACb;AAAA,oBAAAA,OAAC,SACC;AAAA,sBAAAD,MAAC,QAAG,WAAU,qCAAqC,iBAAM;AAAA,MACzD,gBAAAA,MAAC,OAAE,WAAU,sCACV,yBAAe,MAAM,KAAK,eAAe,SAC5C;AAAA,OACF;AAAA,IAEC,UACC,gBAAAC,OAAC,OAAE,WAAU,iCAAgC;AAAA;AAAA,MAC5B;AAAA,MACf,gBAAAD;AAAA,QAAC;AAAA;AAAA,UACC,MAAM,UAAU,OAAO;AAAA,UACvB,WAAU;AAAA,UAET;AAAA;AAAA,MACH;AAAA,MAAK;AAAA,MAAI;AAAA,OAEX,IACE;AAAA,IAEH;AAAA,KACH;AAEJ;","names":["jsx","jsxs","useState","jsx","jsx","jsxs","jsx","jsx","jsxs","useState","useState","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","MIN_PASSWORD_LENGTH","DEFAULTS","useState","jsx","jsxs","jsx","jsxs","jsx","jsxs"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-session.ts","../src/components/auth-field.tsx","../src/components/auth-submit.tsx","../src/components/login-form.tsx","../src/email-not-verified.ts","../src/components/auth-alert.tsx","../src/components/social-buttons.tsx","../src/components/auth-link.tsx","../src/invite-token.ts","../src/oauth-error.ts","../src/components/register-form.tsx","../src/components/verify-email-form.tsx","../src/components/auth-otp-field.tsx","../src/components/forgot-password-form.tsx","../src/components/magic-link-form.tsx","../src/magic-link-error.ts","../src/components/reset-password-form.tsx","../src/components/auth-heading.tsx","../src/components/auth-layout.tsx","../src/components/invitation-notice.tsx"],"sourcesContent":["import type { PlatformAuthClient } from \"../client\"\n\n/**\n * Returns a useSession hook bound to the given auth client.\n * Usage: const { data: session, isPending } = useSession(authClient)\n */\nexport function useSession(authClient: PlatformAuthClient) {\n return authClient.useSession()\n}\n\n/**\n * Returns a logout function bound to the given auth client.\n * Usage: const logout = useLogout(authClient)\n */\nexport function useLogout(authClient: PlatformAuthClient) {\n const signOut = async () => {\n await authClient.signOut()\n }\n return signOut\n}\n","import { useId, useState, type InputHTMLAttributes, type ReactNode } from \"react\"\n\ntype NativeProps = Omit<InputHTMLAttributes<HTMLInputElement>, \"id\" | \"className\">\n\nexport interface AuthFieldProps extends NativeProps {\n label: string\n /** Rendered on the right of the label row — typically a \"forgot password\" link */\n hint?: ReactNode\n /** Persistent helper text under the field, tied to it for screen readers */\n description?: string\n invalid?: boolean\n /** Replaces the default border and background utilities */\n fieldClassName?: string\n}\n\n/**\n * A single credential field.\n *\n * The label is a real <label>, always visible, never a placeholder standing in\n * for one: a placeholder disappears the moment someone types, which is exactly\n * when a person double-checking a long password needs to know what the box is.\n *\n * Touch targets are 52px tall on mobile and 44px from sm up. Below ~48px,\n * thumbs miss; on a pointer device the same height reads as oversized, so the\n * two are not one compromise value.\n *\n * The focus ring is a ring rather than an outline so it follows the rounded\n * corners exactly, and the border darkens at the same time — the border is what\n * survives forced-colors mode, where the ring is dropped.\n */\nexport function AuthField({\n label,\n hint,\n description,\n invalid = false,\n fieldClassName = \"border-foreground/30 bg-background\",\n ...props\n}: AuthFieldProps) {\n const id = useId()\n const descriptionId = description ? `${id}-description` : undefined\n const [revealed, setRevealed] = useState(false)\n\n const isPassword = props.type === \"password\"\n const type = isPassword && revealed ? \"text\" : props.type\n\n return (\n <div className=\"space-y-2\">\n <div className=\"flex items-baseline justify-between gap-3\">\n {/* Small caps with wide tracking: at this size the label reads as a\n field marker rather than as prose competing with the heading. */}\n <label\n htmlFor={id}\n className=\"text-[0.6875rem] font-semibold uppercase leading-none tracking-[0.09em] text-foreground/70\"\n >\n {label}\n </label>\n {hint}\n </div>\n\n <div className=\"relative\">\n <input\n {...props}\n id={id}\n type={type}\n aria-invalid={invalid || undefined}\n aria-describedby={descriptionId}\n className={[\n \"h-[52px] w-full rounded-md border px-3.5 text-base\",\n \"sm:h-[46px] sm:text-[0.9375rem]\",\n isPassword ? \"pr-12\" : \"\",\n \"text-foreground placeholder:text-muted-foreground/60\",\n // Focus reads as the border committing rather than as a halo\n // appearing beside it: the ring is tight and the border darkens to\n // full ink in the same 180ms, so the field answers the caret.\n \"transition-[border-color,box-shadow] duration-200 ease-out\",\n \"focus-visible:outline-none focus-visible:ring-2\",\n invalid\n ? \"border-destructive bg-background focus-visible:border-destructive focus-visible:ring-destructive/15\"\n // The default border is foreground/30, not border-input: the\n // latter against a white card lands near 1.3:1, well under the\n // 3:1 WCAG 1.4.11 asks of a control's boundary — the field reads\n // as a faint tint rather than as something to type in.\n : `${fieldClassName} focus-visible:border-foreground focus-visible:ring-foreground/10`,\n \"disabled:cursor-not-allowed disabled:opacity-60\",\n ]\n .filter(Boolean)\n .join(\" \")}\n />\n\n {isPassword && (\n <button\n type=\"button\"\n onClick={() => setRevealed((v) => !v)}\n disabled={props.disabled}\n aria-pressed={revealed}\n aria-label={\n revealed ? \"Masquer le mot de passe\" : \"Afficher le mot de passe\"\n }\n className=\"absolute inset-y-0 right-0 flex w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-60\"\n >\n <EyeIcon open={revealed} />\n </button>\n )}\n </div>\n\n {description && (\n <p id={descriptionId} className=\"text-xs text-muted-foreground\">\n {description}\n </p>\n )}\n </div>\n )\n}\n\n// Inline rather than from lucide-react: the package would gain a dependency\n// consumers already have at a different version, for two paths.\nfunction EyeIcon({ open }: { open: boolean }) {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.75\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M2.06 12.35a1 1 0 0 1 0-.7 10.75 10.75 0 0 1 19.88 0 1 1 0 0 1 0 .7 10.75 10.75 0 0 1-19.88 0Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n {!open && <path d=\"m3 3 18 18\" />}\n </svg>\n )\n}\n","import type { ReactNode } from \"react\"\n\ninterface AuthSubmitProps {\n pending?: boolean\n disabled?: boolean\n pendingLabel: string\n children: ReactNode\n /** Replaces the default `bg-primary text-primary-foreground hover:bg-primary/90` */\n className?: string\n /**\n * Adds the step that detaches the action from the fields above it. The\n * inputs sit on a tighter rhythm so they read as one block to fill in; the\n * button is what you do once that block is done, and an even gap would put\n * it on the same footing as another field.\n */\n spacedAbove?: boolean\n}\n\n/**\n * The primary action of an auth screen.\n *\n * The label swaps to its pending form in place, with the spinner absolutely\n * positioned: a spinner inserted into the flow would widen the row and shift\n * the text sideways at the exact moment the person is watching it.\n *\n * The press feedback is a 1px translate rather than a scale — scaling a\n * full-width button visibly blurs its text mid-transform.\n */\nexport function AuthSubmit({\n pending = false,\n disabled = false,\n pendingLabel,\n children,\n className = \"bg-primary text-primary-foreground hover:bg-primary/90\",\n spacedAbove = false,\n}: AuthSubmitProps) {\n return (\n <button\n type=\"submit\"\n disabled={disabled || pending}\n aria-busy={pending || undefined}\n className={[\n spacedAbove ? \"!mt-7\" : \"\",\n \"relative flex h-[52px] w-full items-center justify-center rounded-md sm:h-[46px]\",\n // Slightly tracked at this weight: a wide solid button set in plain\n // medium reads as a slab, and the letterspacing is what makes it read\n // as typeset rather than filled in.\n \"text-[0.9375rem] font-medium tracking-[0.01em]\",\n className,\n \"transition-[background-color,transform,box-shadow] duration-200 ease-out\",\n \"shadow-[0_1px_2px_rgba(0,0,0,0.08)] hover:shadow-[0_2px_8px_rgba(0,0,0,0.12)]\",\n \"active:translate-y-px active:shadow-[0_1px_2px_rgba(0,0,0,0.08)]\",\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n \"disabled:pointer-events-none disabled:opacity-55\",\n ].join(\" \")}\n >\n {pending && (\n <span\n aria-hidden=\"true\"\n className=\"absolute left-4 size-4 animate-spin rounded-full border-2 border-current border-t-transparent opacity-70 motion-reduce:animate-none\"\n />\n )}\n {pending ? pendingLabel : children}\n </button>\n )\n}\n","import { useState, type FormEvent } from \"react\"\nimport type { LoginFormLabels, LoginFormProps } from \"../types\"\nimport { isEmailNotVerified } from \"../email-not-verified\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\nimport { SocialButtons } from \"./social-buttons\"\nimport { AUTH_HINT_LINK_CLASS, AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport { withInviteToken } from \"../invite-token\"\nimport { oauthErrorCallback } from \"../oauth-error\"\n\nconst DEFAULTS: Required<LoginFormLabels> = {\n title: \"Connexion\",\n subtitle: \"Content de te revoir. Entre tes identifiants pour continuer.\",\n emailPlaceholder: \"Adresse e-mail\",\n passwordPlaceholder: \"Mot de passe\",\n forgotPassword: \"Mot de passe oublié ?\",\n submit: \"Se connecter\",\n submitPending: \"Connexion…\",\n noAccount: \"Pas encore de compte ?\",\n register: \"Créer un compte\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n passwordRequired: \"Renseigne ton mot de passe\",\n invalidCredentials: \"Adresse e-mail ou mot de passe incorrect\",\n emailNotVerified:\n \"Ton adresse e-mail n'est pas encore confirmée. Vérifie ta boîte de réception.\",\n // accountLinking is disabled in createPlatformAuth, so a social sign-in on an\n // address already registered with a password is refused with this code.\n // Without a message the button reads as broken rather than as a rejection.\n accountNotLinked:\n \"Cette adresse est déjà associée à un mot de passe. Connecte-toi avec ton mot de passe.\",\n socialCancelled: \"Connexion annulée.\",\n socialFailed: \"La connexion a échoué. Réessaie.\",\n}\n\nexport function LoginForm({\n onSuccess,\n onEmailNotVerified,\n registerUrl = \"/register\",\n forgotPasswordUrl = \"/forgot-password\",\n socialCallbackUrl = \"/\",\n errorCallbackUrl,\n socialProviders = [],\n coreTokenUrl = \"/api/auth/core-token\",\n labels,\n submitClassName,\n fieldClassName,\n error: externalError,\n linkComponent,\n invite,\n authClient,\n}: LoginFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [email, setEmail] = useState(\"\")\n const [password, setPassword] = useState(\"\")\n const [ownError, setOwnError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n\n // What the person just did outranks what happened before they arrived.\n const error = ownError ?? externalError\n const setError = setOwnError\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setError(t.emailRequired)\n return\n }\n if (!password) {\n setError(t.passwordRequired)\n return\n }\n setError(undefined)\n setIsPending(true)\n try {\n const res = await authClient.signIn.email({\n email: email.trim(),\n password,\n })\n if (res?.error) {\n if (isEmailNotVerified(res.error) && onEmailNotVerified) {\n onEmailNotVerified(email.trim())\n return\n }\n setError(\n isEmailNotVerified(res.error)\n ? t.emailNotVerified\n : (res.error.message ?? t.invalidCredentials),\n )\n return\n }\n // The better-auth session cookie alone does not authenticate a Go core:\n // it verifies the EdDSA JWT minted here against the issuer's JWKS.\n // Skipped when the app sets the token itself, or has no core at all.\n if (coreTokenUrl) {\n await fetch(coreTokenUrl, { credentials: \"include\" })\n }\n onSuccess?.()\n } catch (err) {\n setError(err instanceof Error ? err.message : t.invalidCredentials)\n } finally {\n setIsPending(false)\n }\n }\n\n const handleSocial = async (provider: \"google\" | \"github\") => {\n setError(undefined)\n try {\n await authClient.signIn.social({\n provider,\n // The invitation rides the callback: an OAuth sign-up leaves the\n // browser, and the auth handler redeems the token on the way back.\n callbackURL: withInviteToken(socialCallbackUrl, invite),\n // Resolved here rather than at render: the default is the current page,\n // and this runs in the browser, where there is one.\n errorCallbackURL: oauthErrorCallback(\n errorCallbackUrl,\n \"/login\",\n typeof window !== \"undefined\" ? window.location.pathname : undefined,\n ),\n })\n } catch (err) {\n setError(err instanceof Error ? err.message : t.socialFailed)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n invalid={!!error}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.passwordPlaceholder}\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"current-password\"\n invalid={!!error}\n fieldClassName={fieldClassName}\n hint={\n <AuthLink\n to={forgotPasswordUrl}\n as={linkComponent}\n className={AUTH_HINT_LINK_CLASS}\n >\n {t.forgotPassword}\n </AuthLink>\n }\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n disabled={!email.trim() || !password}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <SocialButtons\n providers={socialProviders}\n onSelect={handleSocial}\n disabled={isPending}\n />\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.noAccount}{\" \"}\n <AuthLink\n to={withInviteToken(registerUrl, invite)}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.register}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// The heading lives in AuthLayout, above the card, so the screen — not the\n// form — passes the copy. Exposing the defaults here keeps the wording in one\n// place: `<AuthLayout {...LoginForm.defaults}>` renders what the form used to.\nLoginForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","import type { AuthClientResult } from \"./types\"\n\n/**\n * Whether a failed sign-in was refused for want of a confirmed address.\n *\n * Better Auth answers an unverified sign-in with EMAIL_NOT_VERIFIED, but only\n * when built with its error codes exposed; otherwise the refusal arrives as a\n * bare 403. No other credential failure on this route uses that status — a\n * wrong password is a 401 — so the status alone is a safe fallback.\n */\nexport function isEmailNotVerified(\n error: AuthClientResult[\"error\"],\n): boolean {\n if (!error) return false\n return error.code === \"EMAIL_NOT_VERIFIED\" || error.status === 403\n}\n","interface AuthAlertProps {\n children?: string\n tone?: \"error\" | \"success\"\n}\n\n/**\n * Inline feedback for an auth screen.\n *\n * `role=\"alert\"` on the wrapper is not enough on its own: the node has to be\n * in the tree before the text lands in it for the live region to fire, which\n * is why the element renders empty rather than being mounted with its message.\n *\n * The success tone uses the theme's own tokens rather than a fixed green,\n * which would sit on a dark surface as an unreadable pale block.\n */\nexport function AuthAlert({ children, tone = \"error\" }: AuthAlertProps) {\n return (\n <div\n role={tone === \"error\" ? \"alert\" : \"status\"}\n aria-live={tone === \"error\" ? \"assertive\" : \"polite\"}\n className={\n children\n ? [\n \"rounded-lg border px-3.5 py-3 text-sm leading-snug\",\n \"motion-safe:animate-[auth-alert-in_180ms_ease-out]\",\n tone === \"error\"\n ? \"border-destructive/25 bg-destructive/10 text-destructive\"\n : \"border-emerald-500/25 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400\",\n ].join(\" \")\n : // Empty it must stay in the tree for the live region to fire, but\n // it must not stay in the layout: a `space-y` counts an empty\n // child as a row, which pushed the first field down by a full step\n // on every screen with no message to show.\n \"hidden\"\n }\n >\n {children}\n </div>\n )\n}\n","const LABELS: Record<string, string> = {\n google: \"Continuer avec Google\",\n github: \"Continuer avec GitHub\",\n}\n\ninterface SocialButtonsProps {\n providers: Array<\"google\" | \"github\">\n onSelect: (provider: \"google\" | \"github\") => void | Promise<void>\n disabled?: boolean\n /** Divider text between the password form and the providers */\n separator?: string\n /** Per-provider button copy, merged over the French defaults */\n labels?: Partial<Record<\"google\" | \"github\", string>>\n}\n\nexport function SocialButtons({\n providers,\n onSelect,\n disabled = false,\n separator = \"ou\",\n labels,\n}: SocialButtonsProps) {\n if (providers.length === 0) return null\n\n const copy = { ...LABELS, ...labels }\n\n return (\n <div className=\"space-y-4\">\n {/* The rule is two flex segments rather than a line behind an opaque\n label: an opaque background only hides the rule when it matches the\n surface behind it, which breaks the moment this sits on a card. */}\n <div aria-hidden=\"true\" className=\"flex items-center gap-3\">\n <span className=\"h-px flex-1 bg-border\" />\n <span className=\"text-[11px] uppercase tracking-[0.14em] text-muted-foreground\">\n {separator}\n </span>\n <span className=\"h-px flex-1 bg-border\" />\n </div>\n\n {/* One per row while there is space for the wording, side by side once\n there are several: in a half-card the full label no longer fits, and\n a truncated \"Continuer avec…\" says less than the mark alone. The\n wording stays as the accessible name either way. */}\n <div\n className={\n providers.length > 1\n ? \"grid gap-2.5 sm:grid-cols-2\"\n : \"grid gap-2.5\"\n }\n >\n {providers.map((provider) => (\n <button\n key={provider}\n type=\"button\"\n onClick={() => onSelect(provider)}\n disabled={disabled}\n aria-label={copy[provider] ?? provider}\n className={[\n \"flex h-[52px] w-full items-center justify-center gap-2.5 rounded-lg sm:h-11\",\n \"border border-foreground/25 bg-background text-base font-medium text-foreground sm:text-sm\",\n \"transition-[background-color,border-color,transform] duration-150 ease-out\",\n \"hover:border-foreground/20 hover:bg-accent active:translate-y-px\",\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n \"disabled:pointer-events-none disabled:opacity-55\",\n ].join(\" \")}\n >\n <ProviderMark provider={provider} />\n <span className={providers.length > 1 ? \"sm:hidden\" : \"\"}>\n {copy[provider] ?? provider}\n </span>\n </button>\n ))}\n </div>\n </div>\n )\n}\n\n// Brand marks are inlined: they must keep their own colors (Google's mark is\n// unusable in monochrome) and adding an icon dependency to this package would\n// duplicate one every consumer already ships.\nfunction ProviderMark({ provider }: { provider: \"google\" | \"github\" }) {\n if (provider === \"google\") {\n return (\n <svg width=\"17\" height=\"17\" viewBox=\"0 0 18 18\" aria-hidden=\"true\">\n <path\n fill=\"#4285F4\"\n d=\"M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.62Z\"\n />\n <path\n fill=\"#34A853\"\n d=\"M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.02-3.7H.96v2.33A9 9 0 0 0 9 18Z\"\n />\n <path\n fill=\"#FBBC05\"\n d=\"M3.98 10.72a5.4 5.4 0 0 1 0-3.44V4.95H.96a9 9 0 0 0 0 8.1l3.02-2.33Z\"\n />\n <path\n fill=\"#EA4335\"\n d=\"M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.46.9 11.43 0 9 0A9 9 0 0 0 .96 4.95l3.02 2.33C4.68 5.16 6.66 3.58 9 3.58Z\"\n />\n </svg>\n )\n }\n return (\n <svg width=\"17\" height=\"17\" viewBox=\"0 0 16 16\" fill=\"currentColor\" aria-hidden=\"true\">\n <path d=\"M8 0a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38l-.01-1.49c-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.4 7.4 0 0 1 4 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48l-.01 2.2c0 .21.15.46.55.38A8 8 0 0 0 8 0Z\" />\n </svg>\n )\n}\n","import type { ReactNode } from \"react\"\nimport type { LinkComponent } from \"../types\"\n\ninterface AuthLinkProps {\n to: string\n as?: LinkComponent\n className?: string\n children: ReactNode\n}\n\n/**\n * A link between auth screens.\n *\n * Falls back to an anchor, which is right for an app without a router and wrong\n * for every app with one: the full page load it triggers restarts the app and\n * loses whatever the URL was carrying.\n */\nexport function AuthLink({ to, as: Link, className, children }: AuthLinkProps) {\n if (Link) {\n return (\n <Link to={to} className={className}>\n {children}\n </Link>\n )\n }\n return (\n <a href={to} className={className}>\n {children}\n </a>\n )\n}\n\nexport const AUTH_LINK_CLASS =\n \"rounded font-medium text-foreground underline underline-offset-4 decoration-foreground/25 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n\nexport const AUTH_HINT_LINK_CLASS =\n \"rounded text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n","/**\n * An invitation token as it may appear in a URL, reduced to something safe to\n * carry through a route search schema.\n *\n * Callers pass raw search params (`Route.validateSearch`), so the input is\n * whatever the address bar held: an array when the param repeats, a number, or\n * a string long enough to be an attack rather than a token. Anything that is\n * not one plausible token collapses to undefined, which reads as \"no\n * invitation\" everywhere downstream.\n */\nconst MAX_TOKEN_LENGTH = 128\n\nexport function normalizeInviteToken(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined\n const trimmed = value.trim()\n if (!trimmed || trimmed.length > MAX_TOKEN_LENGTH) return undefined\n return trimmed\n}\n\n/**\n * Appends the invitation to a link between auth screens.\n *\n * An invitee who lands on /register and clicks through to /login must keep the\n * offer: the token lives only in the URL, so a plain href to the sibling screen\n * silently drops it and the account is created on the default tier.\n */\nexport function withInviteToken(href: string, token?: string): string {\n if (!token) return href\n const separator = href.includes(\"?\") ? \"&\" : \"?\"\n return `${href}${separator}invite=${encodeURIComponent(token)}`\n}\n","export type OAuthErrorLabels = {\n accountNotLinked: string\n socialCancelled: string\n socialFailed: string\n}\n\n/**\n * Turns Better Auth's machine-readable OAuth failure code into something an\n * invitee can act on.\n *\n * `account_not_linked` is the one worth naming: createPlatformAuth disables\n * account linking on purpose, so \"Continue with Google\" on an address already\n * registered with a password is REFUSED. Better Auth's default error route\n * bounces the browser back with nothing shown, so without this the button\n * simply looks broken.\n */\nexport function oauthErrorMessage(\n code: string | null | undefined,\n labels: OAuthErrorLabels,\n): string {\n switch (code) {\n case \"account_not_linked\":\n return labels.accountNotLinked\n case \"access_denied\":\n return labels.socialCancelled\n default:\n return labels.socialFailed\n }\n}\n\n/**\n * Reads the failure Better Auth redirected back with.\n *\n * A social sign-in leaves the app entirely, so component state does not survive\n * it: the only carrier left when the browser returns is the `?error=` Better\n * Auth appends to the errorCallbackURL. Read from the address bar rather than\n * from a typed route search, because the auth routes deliberately declare no\n * search schema — adding one would make `search` required on every navigate to\n * them across the app.\n */\nexport function initialOAuthError(\n labels: OAuthErrorLabels,\n param = \"error\",\n): string | undefined {\n if (typeof window === \"undefined\") return undefined\n const code = new URLSearchParams(window.location.search).get(param)\n if (!code) return undefined\n return oauthErrorMessage(code, labels)\n}\n\n/**\n * Where a refused social sign-in should send the browser back to.\n *\n * Falls back to the page the form is on, which is the one that reads `?error=`\n * and renders it. Better Auth would otherwise keep the browser on its own\n * error route, where nothing shows the code and the button reads as broken.\n * `fallback` covers the server render, where there is no current page to name.\n */\nexport function oauthErrorCallback(\n explicit: string | undefined,\n fallback: string,\n currentPath: string | undefined,\n): string {\n return explicit ?? currentPath ?? fallback\n}\n\n/**\n * Drops the failure from the address bar once it has been shown.\n *\n * Without this the message comes back on every reload, and outlives the retry\n * that succeeded. replaceState rather than a router navigate: these screens\n * have no typed search to navigate against, and the entry being rewritten is\n * the one the OAuth provider pushed, not one the person chose.\n */\nexport function clearOAuthError(param = \"error\"): void {\n if (typeof window === \"undefined\") return\n const url = new URL(window.location.href)\n if (!url.searchParams.has(param)) return\n url.searchParams.delete(param)\n window.history.replaceState({}, \"\", url.toString())\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport { withInviteToken } from \"../invite-token\"\nimport { withSignUpName } from \"../signup-name\"\nimport { oauthErrorCallback } from \"../oauth-error\"\nimport type { RegisterFormLabels, RegisterFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\nimport { SocialButtons } from \"./social-buttons\"\n\nconst MIN_PASSWORD_LENGTH = 8\n\nconst DEFAULTS: Required<RegisterFormLabels> = {\n title: \"Créer un compte\",\n subtitle: \"Nous t'enverrons un code pour confirmer ton adresse e-mail.\",\n namePlaceholder: \"Nom complet\",\n optional: \"facultatif\",\n emailPlaceholder: \"Adresse e-mail\",\n emailLocked: \"Ton invitation est liée à cette adresse.\",\n passwordPlaceholder: \"Mot de passe\",\n passwordHint: `Au moins ${MIN_PASSWORD_LENGTH} caractères.`,\n confirmPlaceholder: \"Confirme le mot de passe\",\n passwordMismatch: \"Les deux mots de passe ne correspondent pas\",\n submit: \"Créer mon compte\",\n submitPending: \"Création…\",\n haveAccount: \"Tu as déjà un compte ?\",\n login: \"Se connecter\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n passwordTooShort: `Le mot de passe doit faire au moins ${MIN_PASSWORD_LENGTH} caractères`,\n signUpFailed: \"La création du compte a échoué\",\n // accountLinking is disabled in createPlatformAuth, so signing up with Google\n // on an address already registered is refused rather than folded into the\n // existing account.\n accountNotLinked:\n \"Cette adresse a déjà un compte. Connecte-toi avec ton mot de passe.\",\n socialCancelled: \"Inscription annulée.\",\n socialFailed: \"La création du compte a échoué. Réessaie.\",\n}\n\nexport function RegisterForm({\n lockedEmail,\n onSuccess,\n loginUrl = \"/login\",\n legal,\n socialCallbackUrl = \"/\",\n errorCallbackUrl,\n socialProviders = [],\n labels,\n submitClassName,\n fieldClassName,\n error: externalError,\n linkComponent,\n invite,\n collectName = true,\n authClient,\n}: RegisterFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [name, setName] = useState(\"\")\n const [typedEmail, setTypedEmail] = useState(\"\")\n const email = lockedEmail ?? typedEmail\n const [password, setPassword] = useState(\"\")\n const [confirmPassword, setConfirmPassword] = useState(\"\")\n const [ownError, setOwnError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n\n // What the person just did outranks what happened before they arrived.\n const error = ownError ?? externalError\n const setError = setOwnError\n\n const tooShort = password.length > 0 && password.length < MIN_PASSWORD_LENGTH\n const mismatch = confirmPassword.length > 0 && confirmPassword !== password\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setError(t.emailRequired)\n return\n }\n if (password.length < MIN_PASSWORD_LENGTH) {\n setError(t.passwordTooShort)\n return\n }\n if (password !== confirmPassword) {\n setError(t.passwordMismatch)\n return\n }\n setError(undefined)\n setIsPending(true)\n try {\n // `name` is always sent: Better Auth types it as a required string and\n // its schema rejects the request before any hook runs, so omitting the\n // key when the field is blank fails with `[body.name] Invalid input`.\n const res = await authClient.signUp.email(\n withSignUpName({ name, email: email.trim(), password }),\n )\n if (res?.error) {\n setError(res.error.message ?? t.signUpFailed)\n return\n }\n // createPlatformAuth sets requireEmailVerification, so sign-up leaves the\n // account unverified and without a session: the caller routes to the OTP\n // step rather than into the app.\n onSuccess?.(email.trim())\n } catch (err) {\n setError(err instanceof Error ? err.message : t.signUpFailed)\n } finally {\n setIsPending(false)\n }\n }\n\n const handleSocial = async (provider: \"google\" | \"github\") => {\n setError(undefined)\n try {\n await authClient.signIn.social({\n provider,\n // The invitation rides the callback: an OAuth sign-up leaves the\n // browser, and the auth handler redeems the token on the way back.\n callbackURL: withInviteToken(socialCallbackUrl, invite),\n // Resolved here rather than at render: the default is the current page,\n // and this runs in the browser, where there is one.\n errorCallbackURL: oauthErrorCallback(\n errorCallbackUrl,\n \"/register\",\n typeof window !== \"undefined\" ? window.location.pathname : undefined,\n ),\n })\n } catch (err) {\n setError(err instanceof Error ? err.message : t.socialFailed)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n {collectName && (\n <AuthField\n label={t.namePlaceholder}\n type=\"text\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n disabled={isPending}\n autoComplete=\"name\"\n fieldClassName={fieldClassName}\n hint={\n <span className=\"text-xs text-muted-foreground\">\n {t.optional}\n </span>\n }\n />\n )}\n\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => setTypedEmail(e.target.value)}\n required\n // readOnly rather than disabled: a disabled field is skipped by the\n // tab order and drops out of the accessibility tree, so the address\n // the account is being created for would go unread.\n readOnly={!!lockedEmail}\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n description={lockedEmail ? t.emailLocked : undefined}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.passwordPlaceholder}\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"new-password\"\n description={t.passwordHint}\n // Only once they have typed something: flagging an untouched field\n // red would scold someone for not having started yet.\n invalid={tooShort}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.confirmPlaceholder}\n type=\"password\"\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"new-password\"\n invalid={mismatch}\n fieldClassName={fieldClassName}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n\n {legal && (\n <p className=\"text-center text-xs leading-relaxed text-muted-foreground\">\n {legal}\n </p>\n )}\n </form>\n\n <SocialButtons\n providers={socialProviders}\n onSelect={handleSocial}\n disabled={isPending}\n />\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.haveAccount}{\" \"}\n <AuthLink\n to={withInviteToken(loginUrl, invite)}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nRegisterForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport type { VerifyEmailFormLabels, VerifyEmailFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthOtpField, OTP_LENGTH } from \"./auth-otp-field\"\nimport { AuthSubmit } from \"./auth-submit\"\n\nconst DEFAULTS: Required<VerifyEmailFormLabels> = {\n title: \"Vérifie ton adresse\",\n subtitle: \"Entre le code à 6 chiffres envoyé à\",\n subtitleNoEmail: \"Entre le code à 6 chiffres reçu par e-mail.\",\n codePlaceholder: \"Code de vérification\",\n submit: \"Vérifier\",\n submitPending: \"Vérification…\",\n resend: \"Renvoyer le code\",\n resendPending: \"Envoi…\",\n resent: \"Un nouveau code vient de t'être envoyé.\",\n alreadyVerified: \"Adresse déjà vérifiée ?\",\n login: \"Se connecter\",\n codeRequired: \"Entre le code à 6 chiffres\",\n invalidCode: \"Code invalide. Réessaie.\",\n resendFailed: \"L'envoi du code a échoué\",\n missingEmail: \"Adresse e-mail introuvable. Recommence l'inscription.\",\n}\n\nexport function VerifyEmailForm({\n email,\n onSuccess,\n loginUrl = \"/login\",\n labels,\n submitClassName,\n fieldClassName,\n linkComponent,\n authClient,\n}: VerifyEmailFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [otp, setOtp] = useState(\"\")\n const [isVerifying, setIsVerifying] = useState(false)\n const [isResending, setIsResending] = useState(false)\n const [resendMessage, setResendMessage] = useState<string | undefined>()\n const [error, setError] = useState<string | undefined>()\n\n const handleVerify = async (e: FormEvent) => {\n e.preventDefault()\n if (otp.length < OTP_LENGTH) {\n setError(t.codeRequired)\n return\n }\n setError(undefined)\n setResendMessage(undefined)\n setIsVerifying(true)\n try {\n const res = await authClient.emailOtp.verifyEmail({ email, otp })\n if (res?.error) {\n setError(res.error.message ?? t.invalidCode)\n return\n }\n onSuccess?.()\n } catch (err) {\n setError(err instanceof Error ? err.message : t.invalidCode)\n } finally {\n setIsVerifying(false)\n }\n }\n\n const handleResend = async () => {\n if (!email) {\n setError(t.missingEmail)\n return\n }\n setError(undefined)\n setResendMessage(undefined)\n setIsResending(true)\n try {\n await authClient.emailOtp.sendVerificationOtp({\n email,\n type: \"email-verification\",\n })\n setResendMessage(t.resent)\n } catch (err) {\n setError(err instanceof Error ? err.message : t.resendFailed)\n } finally {\n setIsResending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n <AuthAlert tone=\"success\">{resendMessage}</AuthAlert>\n\n <form onSubmit={handleVerify} className=\"space-y-[1.125rem]\" noValidate>\n <AuthOtpField\n id=\"verify-email-otp\"\n label={t.codePlaceholder}\n value={otp}\n onChange={setOtp}\n disabled={isVerifying}\n fieldClassName={fieldClassName}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isVerifying}\n disabled={otp.length < OTP_LENGTH}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <div className=\"space-y-4 text-center text-sm text-muted-foreground\">\n <button\n type=\"button\"\n onClick={handleResend}\n disabled={isResending}\n className=\"rounded font-medium text-foreground underline underline-offset-4 decoration-foreground/25 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-55\"\n >\n {isResending ? t.resendPending : t.resend}\n </button>\n\n <p>\n {t.alreadyVerified}{\" \"}\n <AuthLink\n to={loginUrl}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nVerifyEmailForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","interface AuthOtpFieldProps {\n label: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n invalid?: boolean\n id: string\n /** Replaces the default border and background utilities */\n fieldClassName?: string\n}\n\nexport const OTP_LENGTH = 6\n\n/**\n * The 6-digit code field.\n *\n * Not an AuthField: the value is a code being read off another screen, so it\n * is spaced and monospaced to be checked digit by digit, and non-digits are\n * dropped on the way in — pasting a code from a mail client routinely carries\n * a trailing space.\n */\nexport function AuthOtpField({\n label,\n value,\n onChange,\n disabled = false,\n invalid = false,\n id,\n fieldClassName = \"border-foreground/25 bg-background\",\n}: AuthOtpFieldProps) {\n return (\n <div className=\"space-y-2\">\n <label\n htmlFor={id}\n className=\"block text-[0.6875rem] font-semibold uppercase leading-none tracking-[0.09em] text-foreground/70\"\n >\n {label}\n </label>\n <input\n id={id}\n type=\"text\"\n inputMode=\"numeric\"\n pattern=\"[0-9]*\"\n maxLength={OTP_LENGTH}\n value={value}\n onChange={(e) => onChange(e.target.value.replace(/\\D/g, \"\"))}\n required\n disabled={disabled}\n autoComplete=\"one-time-code\"\n aria-invalid={invalid || undefined}\n className={[\n \"h-[52px] w-full rounded-lg border px-4 sm:h-11\",\n \"text-center font-mono text-lg tracking-[0.4em]\",\n \"text-foreground\",\n \"transition-[border-color,box-shadow] duration-150 ease-out\",\n \"focus-visible:outline-none focus-visible:ring-[3px]\",\n invalid\n ? \"border-destructive bg-background focus-visible:border-destructive focus-visible:ring-destructive/20\"\n : `${fieldClassName} focus-visible:border-ring focus-visible:ring-ring/15`,\n \"disabled:cursor-not-allowed disabled:opacity-60\",\n ].join(\" \")}\n />\n </div>\n )\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport type {\n ForgotPasswordFormLabels,\n ForgotPasswordFormProps,\n} from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\n\nconst DEFAULTS: Required<ForgotPasswordFormLabels> = {\n title: \"Mot de passe oublié ?\",\n subtitle:\n \"Entre ton adresse e-mail et nous t'enverrons un code pour le réinitialiser.\",\n emailPlaceholder: \"Adresse e-mail\",\n submit: \"Envoyer le code\",\n submitPending: \"Envoi…\",\n rememberPassword: \"Tu t'en souviens finalement ?\",\n login: \"Se connecter\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n sendFailed: \"L'envoi du code a échoué\",\n}\n\nexport function ForgotPasswordForm({\n onSuccess,\n loginUrl = \"/login\",\n labels,\n submitClassName,\n fieldClassName,\n linkComponent,\n authClient,\n}: ForgotPasswordFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [email, setEmail] = useState(\"\")\n const [error, setError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setError(t.emailRequired)\n return\n }\n setError(undefined)\n setIsPending(true)\n try {\n const res = await authClient.emailOtp.sendVerificationOtp({\n email: email.trim(),\n type: \"forget-password\",\n })\n if (res?.error) {\n setError(res.error.message ?? t.sendFailed)\n return\n }\n onSuccess?.(email.trim())\n } catch (err) {\n setError(err instanceof Error ? err.message : t.sendFailed)\n } finally {\n setIsPending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n required\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n invalid={!!error}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n disabled={!email.trim()}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.rememberPassword}{\" \"}\n <AuthLink\n to={loginUrl}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nForgotPasswordForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","import { useState, type FormEvent } from \"react\"\nimport type { MagicLinkFormLabels, MagicLinkFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthSubmit } from \"./auth-submit\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport { withInviteToken } from \"../invite-token\"\nimport { magicLinkErrorCallback } from \"../magic-link-error\"\n\n/**\n * Sign-in by emailed link.\n *\n * The confirmation says a link was sent, never that an account exists: Better\n * Auth answers the send the same way either way, and only refuses at the\n * /magic-link/verify hop. That is deliberate on its part — a form that\n * distinguished the two would tell an anonymous caller which addresses are\n * registered. Every failure past the send therefore comes back as a `?error=`\n * on the errorCallbackURL, which is what magicLinkErrorMessage reads — and\n * which defaults to this page, since asking for another link is the fix.\n */\n\nconst DEFAULTS: Required<MagicLinkFormLabels> = {\n title: \"Connexion par lien\",\n subtitle:\n \"Entre ton adresse e-mail et nous t'enverrons un lien pour te connecter, sans mot de passe.\",\n emailPlaceholder: \"Adresse e-mail\",\n submit: \"Envoyer le lien\",\n submitPending: \"Envoi…\",\n sent: \"Lien envoyé. Ouvre ta boîte de réception pour te connecter — il expire dans 5 minutes.\",\n resend: \"Renvoyer le lien\",\n usePassword: \"Tu préfères ton mot de passe ?\",\n login: \"Se connecter\",\n emailRequired: \"Renseigne ton adresse e-mail\",\n sendFailed: \"L'envoi du lien a échoué\",\n}\n\nexport function MagicLinkForm({\n onSuccess,\n loginUrl = \"/login\",\n callbackUrl = \"/\",\n newUserCallbackUrl,\n errorCallbackUrl,\n labels,\n submitClassName,\n fieldClassName,\n error: externalError,\n linkComponent,\n invite,\n authClient,\n}: MagicLinkFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [email, setEmail] = useState(\"\")\n const [ownError, setOwnError] = useState<string | undefined>()\n const [isPending, setIsPending] = useState(false)\n const [isSent, setIsSent] = useState(false)\n\n const error = ownError ?? externalError\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (!email.trim()) {\n setOwnError(t.emailRequired)\n return\n }\n setOwnError(undefined)\n setIsPending(true)\n try {\n const res = await authClient.signIn.magicLink({\n email: email.trim(),\n // The invitation rides the callback: following the link leaves the\n // browser on the mail client, so the auth handler redeems the token on\n // the way back, as it does for OAuth.\n callbackURL: withInviteToken(callbackUrl, invite),\n ...(newUserCallbackUrl\n ? { newUserCallbackURL: withInviteToken(newUserCallbackUrl, invite) }\n : {}),\n // Resolved here rather than at render: the default is the current page,\n // and this runs in the browser, where there is one.\n errorCallbackURL: withInviteToken(\n magicLinkErrorCallback(\n errorCallbackUrl,\n loginUrl,\n typeof window !== \"undefined\"\n ? window.location.pathname\n : undefined,\n ),\n invite,\n ),\n })\n if (res?.error) {\n setOwnError(res.error.message ?? t.sendFailed)\n return\n }\n setIsSent(true)\n onSuccess?.(email.trim())\n } catch (err) {\n setOwnError(err instanceof Error ? err.message : t.sendFailed)\n } finally {\n setIsPending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n {/* Kept out of the error alert's node so the two live regions stay\n distinct — a success replacing an error in the same node is announced\n as a change to the error. */}\n <AuthAlert tone=\"success\">{!error && isSent ? t.sent : undefined}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthField\n label={t.emailPlaceholder}\n type=\"email\"\n inputMode=\"email\"\n value={email}\n onChange={(e) => {\n setEmail(e.target.value)\n // Editing the address invalidates what was said about the last\n // one: the confirmation named an inbox this is no longer it.\n setIsSent(false)\n }}\n required\n disabled={isPending}\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n spellCheck={false}\n invalid={!!error}\n fieldClassName={fieldClassName}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isPending}\n disabled={!email.trim()}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {isSent ? t.resend : t.submit}\n </AuthSubmit>\n </form>\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {t.usePassword}{\" \"}\n <AuthLink\n to={withInviteToken(loginUrl, invite)}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nMagicLinkForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","/**\n * Where a link that did not work should send the browser back to.\n *\n * Falls back to the current page rather than to Better Auth's own default,\n * which is the success callback: that is a signed-in destination, so an auth\n * guard bounces the visitor and drops the `?error=` on the way, and an expired\n * link ends up looking like nothing happened. `fallback` covers the server\n * render, where there is no current page to name.\n */\nexport function magicLinkErrorCallback(\n explicit: string | undefined,\n fallback: string,\n currentPath: string | undefined,\n): string {\n return explicit ?? currentPath ?? fallback\n}\n\nexport type MagicLinkErrorLabels = {\n invalidToken: string\n signUpDisabled: string\n failed: string\n}\n\nexport const MAGIC_LINK_ERROR_DEFAULTS: MagicLinkErrorLabels = {\n invalidToken:\n \"Ce lien n'est plus valide. Il expire après 5 minutes et ne fonctionne qu'une fois — demandes-en un nouveau.\",\n signUpDisabled:\n \"Aucun compte n'existe pour cette adresse. Crée-en un d'abord.\",\n failed: \"La connexion par lien a échoué. Réessaie.\",\n}\n\n/**\n * Turns the failure a followed magic link redirected back with into something\n * the person can act on.\n *\n * Every way the flow can fail lands here rather than on the send: Better Auth\n * consumes the token at /magic-link/verify, and any refusal there is thrown as\n * a redirect to the errorCallbackURL. `INVALID_TOKEN` covers expiry and reuse\n * alike — the token is consumed atomically on first use, so a link followed\n * twice is indistinguishable from one that timed out, and the copy names both.\n */\nexport function magicLinkErrorMessage(\n code: string | null | undefined,\n labels: Partial<MagicLinkErrorLabels> = {},\n): string {\n const t = { ...MAGIC_LINK_ERROR_DEFAULTS, ...labels }\n switch (code) {\n case \"INVALID_TOKEN\":\n return t.invalidToken\n case \"new_user_signup_disabled\":\n return t.signUpDisabled\n default:\n return t.failed\n }\n}\n\n/** Codes this module recognises, so a shared handler can tell them apart. */\nconst MAGIC_LINK_ERROR_CODES = new Set([\n \"INVALID_TOKEN\",\n \"new_user_signup_disabled\",\n \"failed_to_create_user\",\n \"failed_to_create_session\",\n])\n\n/**\n * Whether a `?error=` came from a magic link rather than from OAuth.\n *\n * Both flows return to the same screens through the same parameter, so a page\n * offering the two needs to know which vocabulary to read the code against —\n * otherwise an expired link is reported as a failed social sign-in.\n */\nexport function isMagicLinkError(code: string | null | undefined): boolean {\n return !!code && MAGIC_LINK_ERROR_CODES.has(code)\n}\n\n/**\n * Reads the failure a followed link redirected back with.\n *\n * Following a link leaves the app entirely, so no component state survives it;\n * the address bar is the only carrier left. Mirrors initialOAuthError, down to\n * reading `window.location` rather than a typed route search — the auth routes\n * declare none on purpose.\n */\nexport function initialMagicLinkError(\n labels: Partial<MagicLinkErrorLabels> = {},\n param = \"error\",\n): string | undefined {\n if (typeof window === \"undefined\") return undefined\n const code = new URLSearchParams(window.location.search).get(param)\n if (!isMagicLinkError(code)) return undefined\n return magicLinkErrorMessage(code, labels)\n}\n","import { useState, type FormEvent } from \"react\"\nimport { AUTH_LINK_CLASS, AuthLink } from \"./auth-link\"\nimport type { ResetPasswordFormLabels, ResetPasswordFormProps } from \"../types\"\nimport { AuthAlert } from \"./auth-alert\"\nimport { AuthField } from \"./auth-field\"\nimport { AuthOtpField, OTP_LENGTH } from \"./auth-otp-field\"\nimport { AuthSubmit } from \"./auth-submit\"\n\nconst MIN_PASSWORD_LENGTH = 8\n\nconst DEFAULTS: Required<ResetPasswordFormLabels> = {\n title: \"Nouveau mot de passe\",\n subtitle: \"Entre le code à 6 chiffres reçu par e-mail et ton nouveau mot de passe.\",\n codePlaceholder: \"Code de vérification\",\n passwordPlaceholder: \"Nouveau mot de passe\",\n passwordHint: `Au moins ${MIN_PASSWORD_LENGTH} caractères.`,\n confirmPlaceholder: \"Confirme le mot de passe\",\n submit: \"Réinitialiser\",\n submitPending: \"Réinitialisation…\",\n resend: \"Renvoyer le code\",\n resendPending: \"Envoi…\",\n resent: \"Un nouveau code vient de t'être envoyé.\",\n rememberPassword: \"Tu t'en souviens finalement ?\",\n login: \"Se connecter\",\n codeRequired: \"Entre le code à 6 chiffres\",\n passwordTooShort: `Le mot de passe doit faire au moins ${MIN_PASSWORD_LENGTH} caractères`,\n passwordMismatch: \"Les deux mots de passe ne correspondent pas\",\n resetFailed: \"La réinitialisation a échoué\",\n resendFailed: \"L'envoi du code a échoué\",\n}\n\nexport function ResetPasswordForm({\n email,\n onSuccess,\n loginUrl = \"/login\",\n labels,\n submitClassName,\n fieldClassName,\n linkComponent,\n authClient,\n}: ResetPasswordFormProps) {\n const t = { ...DEFAULTS, ...labels }\n const [otp, setOtp] = useState(\"\")\n const [password, setPassword] = useState(\"\")\n const [confirmPassword, setConfirmPassword] = useState(\"\")\n const [error, setError] = useState<string | undefined>()\n const [isResetting, setIsResetting] = useState(false)\n const [isResending, setIsResending] = useState(false)\n const [resendMessage, setResendMessage] = useState<string | undefined>()\n\n const tooShort = password.length > 0 && password.length < MIN_PASSWORD_LENGTH\n const mismatch = confirmPassword.length > 0 && confirmPassword !== password\n\n const handleSubmit = async (e: FormEvent) => {\n e.preventDefault()\n if (otp.length < OTP_LENGTH) {\n setError(t.codeRequired)\n return\n }\n if (password.length < MIN_PASSWORD_LENGTH) {\n setError(t.passwordTooShort)\n return\n }\n if (password !== confirmPassword) {\n setError(t.passwordMismatch)\n return\n }\n setError(undefined)\n setResendMessage(undefined)\n setIsResetting(true)\n try {\n const res = await fetch(\"/api/auth/email-otp/reset-password\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, otp, password }),\n })\n if (!res.ok) {\n const body = await res.json().catch(() => null)\n setError(body?.message ?? t.resetFailed)\n return\n }\n onSuccess?.()\n } catch (err) {\n setError(err instanceof Error ? err.message : t.resetFailed)\n } finally {\n setIsResetting(false)\n }\n }\n\n const handleResend = async () => {\n setError(undefined)\n setResendMessage(undefined)\n setIsResending(true)\n try {\n await authClient.emailOtp.sendVerificationOtp({\n email,\n type: \"forget-password\",\n })\n setResendMessage(t.resent)\n } catch (err) {\n setError(err instanceof Error ? err.message : t.resendFailed)\n } finally {\n setIsResending(false)\n }\n }\n\n return (\n <div className=\"space-y-7\">\n <AuthAlert>{error}</AuthAlert>\n <AuthAlert tone=\"success\">{resendMessage}</AuthAlert>\n\n <form onSubmit={handleSubmit} className=\"space-y-[1.125rem]\" noValidate>\n <AuthOtpField\n id=\"reset-password-otp\"\n label={t.codePlaceholder}\n value={otp}\n onChange={setOtp}\n disabled={isResetting}\n fieldClassName={fieldClassName}\n />\n\n <AuthField\n label={t.passwordPlaceholder}\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n disabled={isResetting}\n autoComplete=\"new-password\"\n description={t.passwordHint}\n invalid={tooShort}\n />\n\n <AuthField\n label={t.confirmPlaceholder}\n type=\"password\"\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n required\n disabled={isResetting}\n autoComplete=\"new-password\"\n invalid={mismatch}\n />\n\n <AuthSubmit\n spacedAbove\n pending={isResetting}\n disabled={otp.length < OTP_LENGTH || !password || !confirmPassword}\n pendingLabel={t.submitPending}\n className={submitClassName}\n >\n {t.submit}\n </AuthSubmit>\n </form>\n\n <div className=\"space-y-4 text-center text-sm text-muted-foreground\">\n <button\n type=\"button\"\n onClick={handleResend}\n disabled={isResending}\n className=\"rounded font-medium text-foreground underline underline-offset-4 decoration-foreground/25 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-55\"\n >\n {isResending ? t.resendPending : t.resend}\n </button>\n\n <p>\n {t.rememberPassword}{\" \"}\n <AuthLink\n to={loginUrl}\n as={linkComponent}\n className={AUTH_LINK_CLASS}\n >\n {t.login}\n </AuthLink>\n </p>\n </div>\n </div>\n )\n}\n\n// See LoginForm.defaults.\nResetPasswordForm.defaults = {\n title: DEFAULTS.title,\n subtitle: DEFAULTS.subtitle,\n}\n","interface AuthHeadingProps {\n title: string\n subtitle?: string\n /** Replaces the default size and weight — pass the whole look */\n titleClassName?: string\n}\n\n/**\n * The heading of an auth screen.\n *\n * This screen is the only one someone sees before they have any reason to\n * trust the product, so the type carries it: the title is the screen's centre\n * of gravity, set large and tightly tracked, with the subtitle stepping well\n * back rather than competing.\n *\n * Optical sizing matters at this weight — `text-balance` keeps a two-line\n * subtitle from breaking into a lonely last word, which reads as an accident\n * where everything else is deliberate.\n */\nexport function AuthHeading({\n title,\n subtitle,\n titleClassName = \"text-[2rem] font-semibold leading-[1.1] tracking-[-0.03em] sm:text-[2.25rem]\",\n}: AuthHeadingProps) {\n return (\n <header className=\"space-y-2.5 text-center\">\n <h1 className={titleClassName}>{title}</h1>\n {subtitle && (\n <p className=\"text-balance text-[0.9375rem] leading-relaxed text-muted-foreground\">\n {subtitle}\n </p>\n )}\n </header>\n )\n}\n","import type { AuthLayoutProps } from \"../types\"\nimport { AuthHeading } from \"./auth-heading\"\n\n/**\n * The frame every auth screen sits in. It owns the ground, the heading and the\n * app's own marks (logo, illustration, legal footer); the card holds only the\n * fields and their actions.\n *\n * The heading sits ABOVE the card rather than inside it: the card is then\n * exactly the thing you fill in, and the mark reads as the app's rather than\n * as the form's first row.\n *\n * Mobile and desktop are two layouts, not one scaled down. On a phone the form\n * IS the page: no card, no border, edge-to-edge padding, top-aligned so the\n * fields stay above the keyboard instead of being pushed under it by vertical\n * centering. From sm up it becomes a bounded card on a tinted ground — a\n * full-width form on a 1440px display is unreadable.\n *\n * A `panel` is an app-supplied illustration and nothing else: without one the\n * card stays a single column rather than inventing decoration to fill a half\n * it has no content for. When given, it takes the LEFT half from md up and is\n * dropped below that width — a decorative half-screen above a form costs a\n * full swipe before the first field.\n *\n * min-h-dvh rather than min-h-screen: on mobile browsers 100vh includes the\n * retracting URL bar, so a screen-height container overflows by its height.\n */\nexport function AuthLayout({\n logo,\n panel,\n title,\n subtitle,\n titleClassName,\n children,\n footer,\n}: AuthLayoutProps) {\n return (\n <div\n className={[\n \"relative flex min-h-dvh flex-col px-5 pb-12 pt-14 sm:items-center sm:px-6 sm:py-20\",\n // With a panel the colour IS the mobile ground and the card sits on\n // it; the split card only exists once there is width for two columns.\n panel\n ? \"bg-transparent md:bg-muted/30\"\n : \"bg-background sm:bg-muted/30\",\n ].join(\" \")}\n >\n {panel && (\n // A band, not a full ground: the card below reaches the bottom of the\n // screen, so the colour only has to sit behind the heading. Covering\n // the whole height would leave the panel's own copy showing under the\n // card, which reads as a second, half-hidden screen.\n <div\n aria-hidden=\"true\"\n className=\"absolute inset-x-0 top-0 -z-10 h-64 overflow-hidden md:hidden [&>*]:h-full [&>*]:w-full [&>img]:object-cover\"\n >\n {panel}\n </div>\n )}\n\n <div className={`mx-auto w-full ${panel ? \"max-w-4xl\" : \"max-w-[440px]\"}`}>\n {(logo || title) && (\n // The mark sits tight above the title so the two read as one block\n // rather than as a stray label; the gap down to the card is the\n // largest on the screen — that step is what separates \"who this is\"\n // from \"what you do here\".\n <div\n className={[\n \"mb-8 space-y-3\",\n // Over the colour field the heading is on the panel, not on the\n // page, so it takes the panel's ink until the split puts it back\n // on a light ground.\n panel\n ? \"text-white [&_p]:text-white/75 md:text-foreground md:[&_p]:text-muted-foreground\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {logo && <div className=\"flex justify-center\">{logo}</div>}\n {title && (\n <AuthHeading\n title={title}\n subtitle={subtitle}\n titleClassName={titleClassName}\n />\n )}\n </div>\n )}\n\n <div\n className={[\n \"sm:rounded-xl sm:border sm:border-foreground/[0.08] sm:bg-card\",\n \"sm:shadow-[0_1px_2px_rgba(0,0,0,0.04),0_8px_24px_-12px_rgba(0,0,0,0.10)]\",\n // On the colour band the card is a sheet rising from the bottom of\n // the screen: rounded at the top only, and stretched past the\n // viewport so no ground shows beneath it however short the form.\n panel\n ? \"-mx-5 -mb-12 min-h-[60vh] rounded-t-2xl bg-card shadow-[0_-8px_32px_-12px_rgba(0,0,0,0.18)] sm:mx-0 sm:mb-0 sm:min-h-0 sm:overflow-hidden sm:rounded-xl md:grid md:grid-cols-2\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {panel && (\n // Decorative: it must never carry information the form does not,\n // so it is hidden from assistive tech rather than described.\n <div\n aria-hidden=\"true\"\n className=\"relative hidden overflow-hidden bg-muted md:block [&>*]:absolute [&>*]:inset-0 [&>*]:h-full [&>*]:w-full [&>img]:object-cover\"\n >\n {panel}\n </div>\n )}\n\n <div className={panel ? \"px-5 pb-12 pt-7 sm:p-7\" : \"sm:p-7\"}>\n {children}\n </div>\n </div>\n\n {footer && (\n <div className=\"mt-8 text-center text-xs leading-relaxed text-muted-foreground\">\n {footer}\n </div>\n )}\n </div>\n </div>\n )\n}\n","import type { InvitationNoticeProps } from \"../types\"\n\n/**\n * Every app is reachable at contact@ its own apex domain, so the address is\n * derived rather than configured. Sub-domains are stripped because the app is\n * routinely served from app./admin. while the mailbox lives on the apex;\n * multi-part public suffixes (.co.uk) would need a real suffix list and no app\n * using this is on one.\n */\nfunction defaultSupportEmail(): string | undefined {\n if (typeof window === \"undefined\") return undefined\n const host = window.location.hostname\n if (!host || host === \"localhost\" || /^[\\d.]+$/.test(host)) return undefined\n const apex = host.split(\".\").slice(-2).join(\".\")\n return `contact@${apex}`\n}\n\nconst REASON_MESSAGE: Record<string, string> = {\n expired: \"Cette invitation a expiré.\",\n claimed: \"Cette invitation a déjà été utilisée.\",\n unknown: \"Ce lien d'invitation n'est pas valide.\",\n}\n\n/**\n * What an invitee sees when their link does not work.\n *\n * It names the reason instead of merging the cases into one message: \"expired\"\n * tells someone their link was real and that asking for another one is worth\n * it, which \"invalid\" does not. Short TTLs make that distinction routine.\n *\n * The only way forward offered is a mailto, deliberately. A self-service\n * \"request a new invitation\" form would mean a public endpoint accepting dead\n * tokens, a queue to moderate, and a way to probe which tokens once existed —\n * for a flow where the operator already knows the person by name.\n */\nexport function InvitationNotice({\n reason = \"unknown\",\n supportEmail,\n title = \"Invitation indisponible\",\n action,\n}: InvitationNoticeProps) {\n const contact = supportEmail ?? defaultSupportEmail()\n\n return (\n <div className=\"space-y-8\">\n <div>\n <h1 className=\"text-2xl font-bold tracking-tight\">{title}</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n {REASON_MESSAGE[reason] ?? REASON_MESSAGE.unknown}\n </p>\n </div>\n\n {contact ? (\n <p className=\"text-sm text-muted-foreground\">\n Écrivez-nous à{\" \"}\n <a\n href={`mailto:${contact}`}\n className=\"font-medium text-foreground underline underline-offset-4 hover:text-foreground/80\"\n >\n {contact}\n </a>{\" \"}\n pour en recevoir une nouvelle.\n </p>\n ) : null}\n\n {action}\n </div>\n )\n}\n"],"mappings":";;;;;;;AAMO,SAAS,WAAW,YAAgC;AACzD,SAAO,WAAW,WAAW;AAC/B;AAMO,SAAS,UAAU,YAAgC;AACxD,QAAM,UAAU,YAAY;AAC1B,UAAM,WAAW,QAAQ;AAAA,EAC3B;AACA,SAAO;AACT;;;ACnBA,SAAS,OAAO,gBAA0D;AA+CpE,SAGE,KAHF;AAjBC,SAAS,UAAU;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AA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,iBAAyC;AAAA,EAC7C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AACX;AAcO,SAAS,iBAAiB;AAAA,EAC/B,SAAS;AAAA,EACT;AAAA,EACA,QAAQ;AAAA,EACR;AACF,GAA0B;AACxB,QAAM,UAAU,gBAAgB,oBAAoB;AAEpD,SACE,gBAAAA,OAAC,SAAI,WAAU,aACb;AAAA,oBAAAA,OAAC,SACC;AAAA,sBAAAD,MAAC,QAAG,WAAU,qCAAqC,iBAAM;AAAA,MACzD,gBAAAA,MAAC,OAAE,WAAU,sCACV,yBAAe,MAAM,KAAK,eAAe,SAC5C;AAAA,OACF;AAAA,IAEC,UACC,gBAAAC,OAAC,OAAE,WAAU,iCAAgC;AAAA;AAAA,MAC5B;AAAA,MACf,gBAAAD;AAAA,QAAC;AAAA;AAAA,UACC,MAAM,UAAU,OAAO;AAAA,UACvB,WAAU;AAAA,UAET;AAAA;AAAA,MACH;AAAA,MAAK;AAAA,MAAI;AAAA,OAEX,IACE;AAAA,IAEH;AAAA,KACH;AAEJ;","names":["jsx","jsxs","useState","jsx","jsx","jsxs","jsx","jsx","jsxs","useState","useState","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","DEFAULTS","useState","useState","jsx","jsxs","MIN_PASSWORD_LENGTH","DEFAULTS","useState","jsx","jsxs","jsx","jsxs","jsx","jsxs"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Auth, BetterAuthOptions } from 'better-auth';
|
|
2
|
-
import { o as PlatformAuthConfig } from './types-
|
|
3
|
-
export { s as PlatformRateLimitConfig, t as PlatformRateLimitRule, u as PlatformSession, v as PlatformSessionData,
|
|
4
|
-
export {
|
|
2
|
+
import { o as PlatformAuthConfig } from './types-ioL47w7k.js';
|
|
3
|
+
export { s as PlatformRateLimitConfig, t as PlatformRateLimitRule, u as PlatformSession, v as PlatformSessionData, x as PlatformTwoFactorConfig, y as PlatformUser } from './types-ioL47w7k.js';
|
|
4
|
+
export { b as ClaimInvitationOptions, C as ClaimOutcome, S as SsoMappedUser, a as SsoProfile, c as claimInvitation, d as completesSignup, h as holdInviteTokenCookie, e as invitationOutcomeCookie, f as inviteTokenFrom, i as isInvitationFailure, m as mapSsoProfile, p as pinInviteToken, r as releaseInviteTokenCookie } from './sso-profile-Dkbi4TA4.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Minimal Postgres pool contract this module needs — kept structural so the
|
package/dist/server.js
CHANGED
|
@@ -5,14 +5,15 @@ import {
|
|
|
5
5
|
invitationOutcomeCookie,
|
|
6
6
|
inviteTokenFrom,
|
|
7
7
|
isInvitationFailure,
|
|
8
|
+
mapSsoProfile,
|
|
8
9
|
pinInviteToken,
|
|
9
10
|
releaseInviteTokenCookie,
|
|
10
11
|
withSignUpName
|
|
11
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-MZZTQ66T.js";
|
|
12
13
|
|
|
13
14
|
// src/server.ts
|
|
14
15
|
import { betterAuth, APIError } from "better-auth";
|
|
15
|
-
import { emailOTP, admin, magicLink, twoFactor } from "better-auth/plugins";
|
|
16
|
+
import { emailOTP, admin, magicLink, twoFactor, genericOAuth } from "better-auth/plugins";
|
|
16
17
|
|
|
17
18
|
// src/google-defaults.ts
|
|
18
19
|
function withGoogleDefaults(google) {
|
|
@@ -125,8 +126,10 @@ function createPlatformAuth(config) {
|
|
|
125
126
|
magicLink: magicLinkConfig,
|
|
126
127
|
rateLimit,
|
|
127
128
|
twoFactor: twoFactorConfig,
|
|
128
|
-
trustedOrigins
|
|
129
|
+
trustedOrigins,
|
|
130
|
+
sso
|
|
129
131
|
} = config;
|
|
132
|
+
const ssoProviderId = sso?.providerId ?? "urbangate";
|
|
130
133
|
const subjects = { ...DEFAULT_EMAIL_SUBJECTS, ...emailSubjects };
|
|
131
134
|
const renderEmail = renderOtpEmail ?? defaultRenderOtpEmail;
|
|
132
135
|
return betterAuth({
|
|
@@ -144,10 +147,11 @@ function createPlatformAuth(config) {
|
|
|
144
147
|
// so signing in with Google/GitHub on an email already registered would fold
|
|
145
148
|
// that identity into the existing account. We keep each sign-in method its
|
|
146
149
|
// own account: a social login on a taken email is refused, not linked.
|
|
150
|
+
// The suite's own identity provider is the one exception: it verifies
|
|
151
|
+
// emails itself, and the same person must land on the same account
|
|
152
|
+
// whether they signed in here before the SSO existed or not.
|
|
147
153
|
account: {
|
|
148
|
-
accountLinking: {
|
|
149
|
-
enabled: false
|
|
150
|
-
}
|
|
154
|
+
accountLinking: sso ? { enabled: true, trustedProviders: [ssoProviderId] } : { enabled: false }
|
|
151
155
|
},
|
|
152
156
|
// Naming happens here rather than on /sign-up/email so that every way in
|
|
153
157
|
// is covered: a magic link that signs up bypasses the endpoint entirely
|
|
@@ -238,6 +242,23 @@ function createPlatformAuth(config) {
|
|
|
238
242
|
})
|
|
239
243
|
] : [],
|
|
240
244
|
admin(),
|
|
245
|
+
...sso ? [
|
|
246
|
+
genericOAuth({
|
|
247
|
+
config: [
|
|
248
|
+
{
|
|
249
|
+
providerId: ssoProviderId,
|
|
250
|
+
discoveryUrl: `${sso.issuer.replace(/\/$/, "")}/.well-known/openid-configuration`,
|
|
251
|
+
clientId: sso.clientId,
|
|
252
|
+
clientSecret: sso.clientSecret,
|
|
253
|
+
scopes: ["openid", "email", "profile", "offline_access"],
|
|
254
|
+
pkce: true,
|
|
255
|
+
overrideUserInfo: true,
|
|
256
|
+
disableSignUp: sso.allowSignUp === false,
|
|
257
|
+
mapProfileToUser: (profile) => mapSsoProfile(profile, sso.adminRole)
|
|
258
|
+
}
|
|
259
|
+
]
|
|
260
|
+
})
|
|
261
|
+
] : [],
|
|
241
262
|
...twoFactorConfig?.enabled ? [
|
|
242
263
|
twoFactor({
|
|
243
264
|
issuer: twoFactorConfig.issuer ?? appName,
|
|
@@ -272,6 +293,7 @@ export {
|
|
|
272
293
|
invitationOutcomeCookie,
|
|
273
294
|
inviteTokenFrom,
|
|
274
295
|
isInvitationFailure,
|
|
296
|
+
mapSsoProfile,
|
|
275
297
|
pinInviteToken,
|
|
276
298
|
releaseInviteTokenCookie
|
|
277
299
|
};
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/google-defaults.ts","../src/rate-limit.ts","../src/bootstrap-admin.ts"],"sourcesContent":["import { betterAuth, APIError, type Auth, type BetterAuthOptions } from \"better-auth\"\nimport { emailOTP, admin, magicLink, twoFactor } from \"better-auth/plugins\"\nimport type { PlatformAuthConfig, PlatformAuthMailerType } from \"./types\"\nimport { withGoogleDefaults } from \"./google-defaults\"\nimport { withSignUpName } from \"./signup-name\"\nimport { resolveRateLimit } from \"./rate-limit\"\n\nconst DEFAULT_EMAIL_SUBJECTS: Record<string, string> = {\n \"email-verification\": \"Verify your account\",\n \"forget-password\": \"Reset your password\",\n \"sign-in\": \"Your sign-in code\",\n}\n\nfunction defaultRenderOtpEmail(otp: string): string {\n return `\n <div style=\"font-family:sans-serif;max-width:480px;margin:0 auto;padding:32px\">\n <h2 style=\"font-size:20px;font-weight:600;margin-bottom:16px\">Your verification code</h2>\n <p style=\"color:#555;margin-bottom:24px\">Use the code below to continue. It expires in 5 minutes.</p>\n <div style=\"background:#f5f5f5;border-radius:8px;padding:24px;text-align:center;letter-spacing:8px;font-size:32px;font-weight:700\">\n ${otp}\n </div>\n <p style=\"color:#999;font-size:12px;margin-top:24px\">If you didn't request this, you can safely ignore this email.</p>\n </div>\n `\n}\n\nfunction defaultRenderMagicLinkEmail(url: string): string {\n return `\n <div style=\"font-family:sans-serif;max-width:480px;margin:0 auto;padding:32px\">\n <h2 style=\"font-size:20px;font-weight:600;margin-bottom:16px\">Your sign-in link</h2>\n <p style=\"color:#555;margin-bottom:24px\">Click the button below to sign in. The link expires in 5 minutes and works once.</p>\n <a href=\"${url}\" style=\"display:inline-block;background:#111;color:#fff;text-decoration:none;border-radius:8px;padding:14px 28px;font-weight:600\">Sign in</a>\n <p style=\"color:#999;font-size:12px;margin-top:24px;word-break:break-all\">Or paste this address into your browser:<br>${url}</p>\n <p style=\"color:#999;font-size:12px;margin-top:16px\">If you didn't request this, you can safely ignore this email.</p>\n </div>\n `\n}\n\n/**\n * Creates a Better Auth instance with platform defaults.\n * Each app calls this with its own config (DB, secret, providers, plugins).\n */\nexport function createPlatformAuth(\n config: PlatformAuthConfig,\n): Auth<BetterAuthOptions> {\n const {\n database,\n baseURL,\n secret,\n appName,\n mailer,\n google,\n github,\n plugins = [],\n databaseHooks,\n betaMode = false,\n isInvited,\n emailSubjects,\n renderOtpEmail,\n magicLink: magicLinkConfig,\n rateLimit,\n twoFactor: twoFactorConfig,\n trustedOrigins,\n } = config\n\n const subjects = { ...DEFAULT_EMAIL_SUBJECTS, ...emailSubjects }\n const renderEmail = renderOtpEmail ?? defaultRenderOtpEmail\n\n // The concrete instance type (with email-otp/admin plugins) is widened to\n // the base Auth type so the published .d.ts stays portable (inferring the\n // full plugin type triggers TS2742 — it can't be named without a zod ref).\n // The admin() plugin's user.role field is re-exposed via module augmentation\n // below, so consumers (e.g. transcript-web me.ts) still see session.user.role.\n return betterAuth({\n database,\n baseURL,\n secret,\n ...(trustedOrigins ? { trustedOrigins } : {}),\n rateLimit: resolveRateLimit(rateLimit),\n emailAndPassword: {\n enabled: true,\n requireEmailVerification: true,\n },\n // Never auto-merge a social identity into an existing account by matching\n // email. Better Auth links by default (email-verified providers are trusted),\n // so signing in with Google/GitHub on an email already registered would fold\n // that identity into the existing account. We keep each sign-in method its\n // own account: a social login on a taken email is refused, not linked.\n account: {\n accountLinking: {\n enabled: false,\n },\n },\n // Naming happens here rather than on /sign-up/email so that every way in\n // is covered: a magic link that signs up bypasses the endpoint entirely\n // and calls createUser straight, with `name: name || \"\"`.\n databaseHooks: {\n ...databaseHooks,\n user: {\n ...databaseHooks?.user,\n create: {\n ...databaseHooks?.user?.create,\n before: async (user: Record<string, unknown>, ctx: unknown) => {\n const named = withSignUpName(user)\n const appHook = databaseHooks?.user?.create?.before\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applied = await appHook?.(named as any, ctx as any)\n if (applied === false) return false\n if (applied && typeof applied === \"object\" && \"data\" in applied) {\n return { data: withSignUpName(applied.data) }\n }\n return { data: named }\n },\n },\n },\n },\n hooks: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n before: async (ctx: any) => {\n if (!betaMode) return\n if (ctx.path !== \"/sign-up/email\") return\n const body = ctx.body as { email?: string; inviteToken?: string } | undefined\n const email = body?.email\n const inviteToken = body?.inviteToken\n if (email && inviteToken && isInvited) {\n const ok = await isInvited(email, inviteToken)\n if (ok) return\n }\n throw new APIError(\"FORBIDDEN\", {\n message: \"Registration is invite-only during the private beta.\",\n })\n },\n },\n plugins: [\n emailOTP({\n async sendVerificationOTP({ email, otp, type }) {\n const subject = subjects[type]\n ? `${subjects[type]} - ${appName}`\n : `Your ${appName} code`\n const html = renderEmail(otp, type as PlatformAuthMailerType)\n\n if (mailer) {\n await mailer({\n to: email,\n subject,\n html,\n type: type as PlatformAuthMailerType,\n otp,\n })\n return\n }\n\n console.warn(\n `[EMAIL] No mailer configured — logging OTP to stdout for ${email} (${type}): ${otp}`,\n )\n },\n otpLength: 6,\n expiresIn: 300,\n overrideDefaultEmailVerification: true,\n }),\n ...(magicLinkConfig\n ? [\n magicLink({\n expiresIn: magicLinkConfig.expiresIn ?? 300,\n // A magic link that signs up walks past both gates the platform\n // puts on the front door: requireEmailVerification, and the\n // invite-only hook, which only guards /sign-up/email.\n disableSignUp: !magicLinkConfig.allowSignUp,\n async sendMagicLink({ email, url }) {\n const subject =\n magicLinkConfig.subject ?? `Your sign-in link - ${appName}`\n const html = (\n magicLinkConfig.render ?? defaultRenderMagicLinkEmail\n )(url, email)\n\n if (mailer) {\n await mailer({\n to: email,\n subject,\n html,\n type: \"magic-link\",\n url,\n })\n return\n }\n\n console.warn(\n `[EMAIL] No mailer configured — logging magic link to stdout for ${email}: ${url}`,\n )\n },\n }),\n ]\n : []),\n admin(),\n ...(twoFactorConfig?.enabled\n ? [\n twoFactor({\n issuer: twoFactorConfig.issuer ?? appName,\n skipVerificationOnEnable:\n twoFactorConfig.skipVerificationOnEnable ?? false,\n }),\n ]\n : []),\n ...plugins, // app-specific plugins (e.g. tanstackStartCookies)\n ],\n socialProviders: {\n // Spread as given rather than rebuilt field by field: anything Better\n // Auth accepts belongs to the app, and a config silently dropped on the\n // way through is how an app ends up writing a plugin to put it back.\n //\n // The two defaults below are the platform's, not Google's: without\n // accessType 'offline' Google never mints a refresh token, and without\n // 'consent' it stops minting one for an account that already consented.\n // A NULL refreshToken means deleting an account can revoke the access\n // token but cannot remove the app from myaccount.google.com/permissions,\n // so the grant outlives the account it belonged to.\n ...(google ? { google: withGoogleDefaults(google) } : {}),\n ...(github ? { github } : {}),\n },\n }) as unknown as Auth<BetterAuthOptions>\n}\n\nexport type PlatformAuth = ReturnType<typeof createPlatformAuth>\n\n// Re-export the session contract from /server so consumers that import the\n// auth factory can type api.getSession() without a second import path.\nexport type {\n PlatformUser,\n PlatformSession,\n PlatformSessionData,\n PlatformRateLimitConfig,\n PlatformRateLimitRule,\n PlatformTwoFactorConfig,\n} from \"./types\"\n\n// Invitation claiming runs on the auth callback, where the session is\n// established — the one place every sign-up flow passes through.\nexport {\n claimInvitation,\n completesSignup,\n holdInviteTokenCookie,\n invitationOutcomeCookie,\n inviteTokenFrom,\n isInvitationFailure,\n pinInviteToken,\n releaseInviteTokenCookie,\n} from \"./invitation\"\nexport type { ClaimOutcome, ClaimInvitationOptions } from \"./invitation\"\n\nexport { bootstrapFirstAdmin } from \"./bootstrap-admin\"\nexport type {\n BootstrapAdminPool,\n BootstrapAdminClient,\n BootstrapFirstAdminInput,\n BootstrapFirstAdminResult,\n} from \"./bootstrap-admin\"\n","import type { PlatformAuthConfig } from \"./types\"\n\n/**\n * Applies the platform's Google defaults without touching what the app set.\n *\n * Better Auth also accepts a function returning the options, which cannot be\n * amended without calling it — such a config is passed straight through and\n * owns its own defaults.\n */\nexport function withGoogleDefaults(\n google: NonNullable<PlatformAuthConfig[\"google\"]>,\n): NonNullable<PlatformAuthConfig[\"google\"]> {\n if (typeof google === \"function\") return google\n return {\n ...google,\n accessType: google.accessType ?? \"offline\",\n prompt: google.prompt ?? \"select_account consent\",\n }\n}\n\n","import type { PlatformRateLimitConfig, PlatformRateLimitRule } from \"./types\"\n\n// Better Auth keys its own rate limiter on NODE_ENV === \"production\", so a\n// deployment that forgets the variable serves sign-in with no brute-force\n// protection and nothing reports it. These are the platform's rules, applied\n// regardless of the environment.\nconst PLATFORM_RULES: Record<string, PlatformRateLimitRule> = {\n \"/sign-in/email\": { window: 60, max: 5 },\n \"/sign-up/email\": { window: 60, max: 5 },\n \"/email-otp/send-verification-otp\": { window: 60, max: 3 },\n \"/email-otp/verify-email\": { window: 60, max: 5 },\n \"/email-otp/reset-password\": { window: 60, max: 5 },\n \"/forget-password\": { window: 60, max: 3 },\n \"/reset-password\": { window: 60, max: 5 },\n \"/sign-in/magic-link\": { window: 60, max: 3 },\n \"/two-factor/verify-totp\": { window: 60, max: 5 },\n \"/two-factor/verify-otp\": { window: 60, max: 5 },\n \"/two-factor/verify-backup-code\": { window: 60, max: 5 },\n \"/two-factor/send-otp\": { window: 60, max: 3 },\n}\n\nexport interface ResolvedRateLimit {\n enabled: boolean\n window: number\n max: number\n storage?: \"memory\" | \"database\" | \"secondary-storage\"\n modelName?: string\n customRules: Record<string, PlatformRateLimitRule>\n}\n\nexport function resolveRateLimit(\n config?: PlatformRateLimitConfig,\n): ResolvedRateLimit {\n return {\n enabled: config?.enabled ?? true,\n window: config?.window ?? 10,\n max: config?.max ?? 100,\n ...(config?.storage ? { storage: config.storage } : {}),\n ...(config?.modelName ? { modelName: config.modelName } : {}),\n customRules: { ...PLATFORM_RULES, ...config?.customRules },\n }\n}\n\nexport { PLATFORM_RULES }\n","import type { PlatformAuth } from \"./server\"\n\n/**\n * Minimal Postgres pool contract this module needs — kept structural so the\n * package doesn't pull in `pg` as a dependency; any `pg.Pool` satisfies it.\n */\nexport interface BootstrapAdminPool {\n connect(): Promise<BootstrapAdminClient>\n}\n\nexport interface BootstrapAdminClient {\n query(text: string, values?: unknown[]): Promise<{ rowCount: number | null }>\n release(): void\n}\n\nexport interface BootstrapFirstAdminInput {\n email: string\n password: string\n name: string\n}\n\nexport type BootstrapFirstAdminResult =\n | { ok: true }\n | { ok: false; error: \"already_completed\" }\n\n// The admin() plugin's createUser endpoint isn't in PlatformAuth's published\n// type (see the widening note on createPlatformAuth in ./server), even though\n// it's mounted at runtime by every app that enables admin().\ninterface AuthWithAdminCreateUser {\n api: {\n createUser: (input: {\n body: {\n email: string\n password: string\n name: string\n role: string\n data?: Record<string, unknown>\n }\n }) => Promise<unknown>\n }\n}\n\n/**\n * Creates the very first admin for an app, before any admin exists — the one\n * case the admin() plugin's own `createUser` endpoint can't cover, since it\n * requires an already-authenticated admin session to call.\n *\n * Delegates the actual user/account creation to `auth.api.createUser` (called\n * server-side, with no request/session, so the plugin's own auth check is\n * skipped the same way a trusted server script would be) instead of inserting\n * `user`/`account` rows by hand — that keeps this in sync with whatever\n * Better Auth's internal adapter does (account.issuer, password hashing,\n * future schema changes) rather than re-deriving it and letting the two\n * drift apart.\n *\n * Serializes concurrent callers with a Postgres advisory lock: a plain\n * `WHERE NOT EXISTS` check on an empty `user` table lets two racing requests\n * both pass before either has inserted, minting two admins.\n *\n * Callers are expected to have already applied their own access gate (setup\n * token, allowed-emails list, etc.) — this function only enforces \"at most\n * one admin, ever\".\n */\nexport async function bootstrapFirstAdmin(\n auth: PlatformAuth,\n pool: BootstrapAdminPool,\n input: BootstrapFirstAdminInput,\n): Promise<BootstrapFirstAdminResult> {\n const client = await pool.connect()\n try {\n await client.query(\"SELECT pg_advisory_lock(hashtext($1))\", [\"admin-setup\"])\n\n const existing = await client.query(\n `SELECT 1 FROM \"user\" WHERE role = 'admin'`,\n )\n if (existing.rowCount && existing.rowCount > 0) {\n return { ok: false, error: \"already_completed\" }\n }\n\n const adminApi = (auth as unknown as AuthWithAdminCreateUser).api\n await adminApi.createUser({\n body: {\n email: input.email,\n password: input.password,\n name: input.name,\n role: \"admin\",\n data: { emailVerified: true },\n },\n })\n\n return { ok: true }\n } finally {\n await client.query(\"SELECT pg_advisory_unlock(hashtext($1))\", [\"admin-setup\"])\n client.release()\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,YAAY,gBAAmD;AACxE,SAAS,UAAU,OAAO,WAAW,iBAAiB;;;ACQ/C,SAAS,mBACd,QAC2C;AAC3C,MAAI,OAAO,WAAW,WAAY,QAAO;AACzC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY,OAAO,cAAc;AAAA,IACjC,QAAQ,OAAO,UAAU;AAAA,EAC3B;AACF;;;ACZA,IAAM,iBAAwD;AAAA,EAC5D,kBAAkB,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EACvC,kBAAkB,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EACvC,oCAAoC,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EACzD,2BAA2B,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EAChD,6BAA6B,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EAClD,oBAAoB,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EACzC,mBAAmB,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EACxC,uBAAuB,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EAC5C,2BAA2B,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EAChD,0BAA0B,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EAC/C,kCAAkC,EAAE,QAAQ,IAAI,KAAK,EAAE;AAAA,EACvD,wBAAwB,EAAE,QAAQ,IAAI,KAAK,EAAE;AAC/C;AAWO,SAAS,iBACd,QACmB;AACnB,SAAO;AAAA,I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gBACA;AAAA,gBACA,MAAM;AAAA,gBACN;AAAA,cACF,CAAC;AACD;AAAA,YACF;AAEA,oBAAQ;AAAA,cACN,wEAAmE,KAAK,KAAK,GAAG;AAAA,YAClF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,IACA,CAAC;AAAA,MACL,MAAM;AAAA,MACN,GAAI,iBAAiB,UACjB;AAAA,QACE,UAAU;AAAA,UACR,QAAQ,gBAAgB,UAAU;AAAA,UAClC,0BACE,gBAAgB,4BAA4B;AAAA,QAChD,CAAC;AAAA,MACH,IACA,CAAC;AAAA,MACL,GAAG;AAAA;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAWf,GAAI,SAAS,EAAE,QAAQ,mBAAmB,MAAM,EAAE,IAAI,CAAC;AAAA,MACvD,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC7B;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/google-defaults.ts","../src/rate-limit.ts","../src/bootstrap-admin.ts"],"sourcesContent":["import { betterAuth, APIError, type Auth, type BetterAuthOptions } from \"better-auth\"\nimport { emailOTP, admin, magicLink, twoFactor, genericOAuth } from \"better-auth/plugins\"\nimport type { PlatformAuthConfig, PlatformAuthMailerType } from \"./types\"\nimport { withGoogleDefaults } from \"./google-defaults\"\nimport { mapSsoProfile, type SsoProfile } from \"./sso-profile\"\nimport { withSignUpName } from \"./signup-name\"\nimport { resolveRateLimit } from \"./rate-limit\"\n\nconst DEFAULT_EMAIL_SUBJECTS: Record<string, string> = {\n \"email-verification\": \"Verify your account\",\n \"forget-password\": \"Reset your password\",\n \"sign-in\": \"Your sign-in code\",\n}\n\nfunction defaultRenderOtpEmail(otp: string): string {\n return `\n <div style=\"font-family:sans-serif;max-width:480px;margin:0 auto;padding:32px\">\n <h2 style=\"font-size:20px;font-weight:600;margin-bottom:16px\">Your verification code</h2>\n <p style=\"color:#555;margin-bottom:24px\">Use the code below to continue. It expires in 5 minutes.</p>\n <div style=\"background:#f5f5f5;border-radius:8px;padding:24px;text-align:center;letter-spacing:8px;font-size:32px;font-weight:700\">\n ${otp}\n </div>\n <p style=\"color:#999;font-size:12px;margin-top:24px\">If you didn't request this, you can safely ignore this email.</p>\n </div>\n `\n}\n\nfunction defaultRenderMagicLinkEmail(url: string): string {\n return `\n <div style=\"font-family:sans-serif;max-width:480px;margin:0 auto;padding:32px\">\n <h2 style=\"font-size:20px;font-weight:600;margin-bottom:16px\">Your sign-in link</h2>\n <p style=\"color:#555;margin-bottom:24px\">Click the button below to sign in. The link expires in 5 minutes and works once.</p>\n <a href=\"${url}\" style=\"display:inline-block;background:#111;color:#fff;text-decoration:none;border-radius:8px;padding:14px 28px;font-weight:600\">Sign in</a>\n <p style=\"color:#999;font-size:12px;margin-top:24px;word-break:break-all\">Or paste this address into your browser:<br>${url}</p>\n <p style=\"color:#999;font-size:12px;margin-top:16px\">If you didn't request this, you can safely ignore this email.</p>\n </div>\n `\n}\n\n/**\n * Creates a Better Auth instance with platform defaults.\n * Each app calls this with its own config (DB, secret, providers, plugins).\n */\nexport function createPlatformAuth(\n config: PlatformAuthConfig,\n): Auth<BetterAuthOptions> {\n const {\n database,\n baseURL,\n secret,\n appName,\n mailer,\n google,\n github,\n plugins = [],\n databaseHooks,\n betaMode = false,\n isInvited,\n emailSubjects,\n renderOtpEmail,\n magicLink: magicLinkConfig,\n rateLimit,\n twoFactor: twoFactorConfig,\n trustedOrigins,\n sso,\n } = config\n const ssoProviderId = sso?.providerId ?? \"urbangate\"\n\n const subjects = { ...DEFAULT_EMAIL_SUBJECTS, ...emailSubjects }\n const renderEmail = renderOtpEmail ?? defaultRenderOtpEmail\n\n // The concrete instance type (with email-otp/admin plugins) is widened to\n // the base Auth type so the published .d.ts stays portable (inferring the\n // full plugin type triggers TS2742 — it can't be named without a zod ref).\n // The admin() plugin's user.role field is re-exposed via module augmentation\n // below, so consumers (e.g. transcript-web me.ts) still see session.user.role.\n return betterAuth({\n database,\n baseURL,\n secret,\n ...(trustedOrigins ? { trustedOrigins } : {}),\n rateLimit: resolveRateLimit(rateLimit),\n emailAndPassword: {\n enabled: true,\n requireEmailVerification: true,\n },\n // Never auto-merge a social identity into an existing account by matching\n // email. Better Auth links by default (email-verified providers are trusted),\n // so signing in with Google/GitHub on an email already registered would fold\n // that identity into the existing account. We keep each sign-in method its\n // own account: a social login on a taken email is refused, not linked.\n // The suite's own identity provider is the one exception: it verifies\n // emails itself, and the same person must land on the same account\n // whether they signed in here before the SSO existed or not.\n account: {\n accountLinking: sso\n ? { enabled: true, trustedProviders: [ssoProviderId] }\n : { enabled: false },\n },\n // Naming happens here rather than on /sign-up/email so that every way in\n // is covered: a magic link that signs up bypasses the endpoint entirely\n // and calls createUser straight, with `name: name || \"\"`.\n databaseHooks: {\n ...databaseHooks,\n user: {\n ...databaseHooks?.user,\n create: {\n ...databaseHooks?.user?.create,\n before: async (user: Record<string, unknown>, ctx: unknown) => {\n const named = withSignUpName(user)\n const appHook = databaseHooks?.user?.create?.before\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applied = await appHook?.(named as any, ctx as any)\n if (applied === false) return false\n if (applied && typeof applied === \"object\" && \"data\" in applied) {\n return { data: withSignUpName(applied.data) }\n }\n return { data: named }\n },\n },\n },\n },\n hooks: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n before: async (ctx: any) => {\n if (!betaMode) return\n if (ctx.path !== \"/sign-up/email\") return\n const body = ctx.body as { email?: string; inviteToken?: string } | undefined\n const email = body?.email\n const inviteToken = body?.inviteToken\n if (email && inviteToken && isInvited) {\n const ok = await isInvited(email, inviteToken)\n if (ok) return\n }\n throw new APIError(\"FORBIDDEN\", {\n message: \"Registration is invite-only during the private beta.\",\n })\n },\n },\n plugins: [\n emailOTP({\n async sendVerificationOTP({ email, otp, type }) {\n const subject = subjects[type]\n ? `${subjects[type]} - ${appName}`\n : `Your ${appName} code`\n const html = renderEmail(otp, type as PlatformAuthMailerType)\n\n if (mailer) {\n await mailer({\n to: email,\n subject,\n html,\n type: type as PlatformAuthMailerType,\n otp,\n })\n return\n }\n\n console.warn(\n `[EMAIL] No mailer configured — logging OTP to stdout for ${email} (${type}): ${otp}`,\n )\n },\n otpLength: 6,\n expiresIn: 300,\n overrideDefaultEmailVerification: true,\n }),\n ...(magicLinkConfig\n ? [\n magicLink({\n expiresIn: magicLinkConfig.expiresIn ?? 300,\n // A magic link that signs up walks past both gates the platform\n // puts on the front door: requireEmailVerification, and the\n // invite-only hook, which only guards /sign-up/email.\n disableSignUp: !magicLinkConfig.allowSignUp,\n async sendMagicLink({ email, url }) {\n const subject =\n magicLinkConfig.subject ?? `Your sign-in link - ${appName}`\n const html = (\n magicLinkConfig.render ?? defaultRenderMagicLinkEmail\n )(url, email)\n\n if (mailer) {\n await mailer({\n to: email,\n subject,\n html,\n type: \"magic-link\",\n url,\n })\n return\n }\n\n console.warn(\n `[EMAIL] No mailer configured — logging magic link to stdout for ${email}: ${url}`,\n )\n },\n }),\n ]\n : []),\n admin(),\n ...(sso\n ? [\n genericOAuth({\n config: [\n {\n providerId: ssoProviderId,\n discoveryUrl: `${sso.issuer.replace(/\\/$/, \"\")}/.well-known/openid-configuration`,\n clientId: sso.clientId,\n clientSecret: sso.clientSecret,\n scopes: [\"openid\", \"email\", \"profile\", \"offline_access\"],\n pkce: true,\n overrideUserInfo: true,\n disableSignUp: sso.allowSignUp === false,\n mapProfileToUser: (profile) =>\n mapSsoProfile(profile as SsoProfile, sso.adminRole),\n },\n ],\n }),\n ]\n : []),\n ...(twoFactorConfig?.enabled\n ? [\n twoFactor({\n issuer: twoFactorConfig.issuer ?? appName,\n skipVerificationOnEnable:\n twoFactorConfig.skipVerificationOnEnable ?? false,\n }),\n ]\n : []),\n ...plugins, // app-specific plugins (e.g. tanstackStartCookies)\n ],\n socialProviders: {\n // Spread as given rather than rebuilt field by field: anything Better\n // Auth accepts belongs to the app, and a config silently dropped on the\n // way through is how an app ends up writing a plugin to put it back.\n //\n // The two defaults below are the platform's, not Google's: without\n // accessType 'offline' Google never mints a refresh token, and without\n // 'consent' it stops minting one for an account that already consented.\n // A NULL refreshToken means deleting an account can revoke the access\n // token but cannot remove the app from myaccount.google.com/permissions,\n // so the grant outlives the account it belonged to.\n ...(google ? { google: withGoogleDefaults(google) } : {}),\n ...(github ? { github } : {}),\n },\n }) as unknown as Auth<BetterAuthOptions>\n}\n\nexport type PlatformAuth = ReturnType<typeof createPlatformAuth>\n\n// Re-export the session contract from /server so consumers that import the\n// auth factory can type api.getSession() without a second import path.\nexport type {\n PlatformUser,\n PlatformSession,\n PlatformSessionData,\n PlatformRateLimitConfig,\n PlatformRateLimitRule,\n PlatformTwoFactorConfig,\n} from \"./types\"\n\n// Invitation claiming runs on the auth callback, where the session is\n// established — the one place every sign-up flow passes through.\nexport {\n claimInvitation,\n completesSignup,\n holdInviteTokenCookie,\n invitationOutcomeCookie,\n inviteTokenFrom,\n isInvitationFailure,\n pinInviteToken,\n releaseInviteTokenCookie,\n} from \"./invitation\"\nexport type { ClaimOutcome, ClaimInvitationOptions } from \"./invitation\"\n\nexport { mapSsoProfile } from \"./sso-profile\"\nexport type { SsoProfile, SsoMappedUser } from \"./sso-profile\"\n\nexport { bootstrapFirstAdmin } from \"./bootstrap-admin\"\nexport type {\n BootstrapAdminPool,\n BootstrapAdminClient,\n BootstrapFirstAdminInput,\n BootstrapFirstAdminResult,\n} from \"./bootstrap-admin\"\n","import type { PlatformAuthConfig } from \"./types\"\n\n/**\n * Applies the platform's Google defaults without touching what the app set.\n *\n * Better Auth also accepts a function returning the options, which cannot be\n * amended without calling it — such a config is passed straight through and\n * owns its own defaults.\n */\nexport function withGoogleDefaults(\n google: NonNullable<PlatformAuthConfig[\"google\"]>,\n): NonNullable<PlatformAuthConfig[\"google\"]> {\n if (typeof google === \"function\") return google\n return {\n ...google,\n accessType: google.accessType ?? \"offline\",\n prompt: google.prompt ?? \"select_account consent\",\n }\n}\n\n","import type { PlatformRateLimitConfig, PlatformRateLimitRule } from \"./types\"\n\n// Better Auth keys its own rate limiter on NODE_ENV === \"production\", so a\n// deployment that forgets the variable serves sign-in with no brute-force\n// protection and nothing reports it. These are the platform's rules, applied\n// regardless of the environment.\nconst PLATFORM_RULES: Record<string, PlatformRateLimitRule> = {\n \"/sign-in/email\": { window: 60, max: 5 },\n \"/sign-up/email\": { window: 60, max: 5 },\n \"/email-otp/send-verification-otp\": { window: 60, max: 3 },\n \"/email-otp/verify-email\": { window: 60, max: 5 },\n \"/email-otp/reset-password\": { window: 60, max: 5 },\n \"/forget-password\": { window: 60, max: 3 },\n \"/reset-password\": { window: 60, max: 5 },\n \"/sign-in/magic-link\": { window: 60, max: 3 },\n \"/two-factor/verify-totp\": { window: 60, max: 5 },\n \"/two-factor/verify-otp\": { window: 60, max: 5 },\n \"/two-factor/verify-backup-code\": { window: 60, max: 5 },\n \"/two-factor/send-otp\": { window: 60, max: 3 },\n}\n\nexport interface ResolvedRateLimit {\n enabled: boolean\n window: number\n max: number\n storage?: \"memory\" | \"database\" | \"secondary-storage\"\n modelName?: string\n customRules: Record<string, PlatformRateLimitRule>\n}\n\nexport function resolveRateLimit(\n config?: PlatformRateLimitConfig,\n): ResolvedRateLimit {\n return {\n enabled: config?.enabled ?? true,\n window: config?.window ?? 10,\n max: config?.max ?? 100,\n ...(config?.storage ? { storage: config.storage } : {}),\n ...(config?.modelName ? { modelName: config.modelName } : {}),\n customRules: { ...PLATFORM_RULES, ...config?.customRules },\n }\n}\n\nexport { PLATFORM_RULES }\n","import type { PlatformAuth } from \"./server\"\n\n/**\n * Minimal Postgres pool contract this module needs — kept structural so the\n * package doesn't pull in `pg` as a dependency; any `pg.Pool` satisfies it.\n */\nexport interface BootstrapAdminPool {\n connect(): Promise<BootstrapAdminClient>\n}\n\nexport interface BootstrapAdminClient {\n query(text: string, values?: unknown[]): Promise<{ rowCount: number | null }>\n release(): void\n}\n\nexport interface BootstrapFirstAdminInput {\n email: string\n password: string\n name: string\n}\n\nexport type BootstrapFirstAdminResult =\n | { ok: true }\n | { ok: false; error: \"already_completed\" }\n\n// The admin() plugin's createUser endpoint isn't in PlatformAuth's published\n// type (see the widening note on createPlatformAuth in ./server), even though\n// it's mounted at runtime by every app that enables admin().\ninterface AuthWithAdminCreateUser {\n api: {\n createUser: (input: {\n body: {\n email: string\n password: string\n name: string\n role: string\n data?: Record<string, unknown>\n }\n }) => Promise<unknown>\n }\n}\n\n/**\n * Creates the very first admin for an app, before any admin exists — the one\n * case the admin() plugin's own `createUser` endpoint can't cover, since it\n * requires an already-authenticated admin session to call.\n *\n * Delegates the actual user/account creation to `auth.api.createUser` (called\n * server-side, with no request/session, so the plugin's own auth check is\n * skipped the same way a trusted server script would be) instead of inserting\n * `user`/`account` rows by hand — that keeps this in sync with whatever\n * Better Auth's internal adapter does (account.issuer, password hashing,\n * future schema changes) rather than re-deriving it and letting the two\n * drift apart.\n *\n * Serializes concurrent callers with a Postgres advisory lock: a plain\n * `WHERE NOT EXISTS` check on an empty `user` table lets two racing requests\n * both pass before either has inserted, minting two admins.\n *\n * Callers are expected to have already applied their own access gate (setup\n * token, allowed-emails list, etc.) — this function only enforces \"at most\n * one admin, ever\".\n */\nexport async function bootstrapFirstAdmin(\n auth: PlatformAuth,\n pool: BootstrapAdminPool,\n input: BootstrapFirstAdminInput,\n): Promise<BootstrapFirstAdminResult> {\n const client = await pool.connect()\n try {\n await client.query(\"SELECT pg_advisory_lock(hashtext($1))\", [\"admin-setup\"])\n\n const existing = await client.query(\n `SELECT 1 FROM \"user\" WHERE role = 'admin'`,\n )\n if (existing.rowCount && existing.rowCount > 0) {\n return { ok: false, error: \"already_completed\" }\n }\n\n const adminApi = (auth as unknown as AuthWithAdminCreateUser).api\n await adminApi.createUser({\n body: {\n email: input.email,\n password: input.password,\n name: input.name,\n role: \"admin\",\n data: { emailVerified: true },\n },\n })\n\n return { ok: true }\n } finally {\n await client.query(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wEAAmE,KAAK,KAAK,GAAG;AAAA,YAClF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,IACA,CAAC;AAAA,MACL,MAAM;AAAA,MACN,GAAI,MACA;AAAA,QACE,aAAa;AAAA,UACX,QAAQ;AAAA,YACN;AAAA,cACE,YAAY;AAAA,cACZ,cAAc,GAAG,IAAI,OAAO,QAAQ,OAAO,EAAE,CAAC;AAAA,cAC9C,UAAU,IAAI;AAAA,cACd,cAAc,IAAI;AAAA,cAClB,QAAQ,CAAC,UAAU,SAAS,WAAW,gBAAgB;AAAA,cACvD,MAAM;AAAA,cACN,kBAAkB;AAAA,cAClB,eAAe,IAAI,gBAAgB;AAAA,cACnC,kBAAkB,CAAC,YACjB,cAAc,SAAuB,IAAI,SAAS;AAAA,YACtD;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,IACA,CAAC;AAAA,MACL,GAAI,iBAAiB,UACjB;AAAA,QACE,UAAU;AAAA,UACR,QAAQ,gBAAgB,UAAU;AAAA,UAClC,0BACE,gBAAgB,4BAA4B;AAAA,QAChD,CAAC;AAAA,MACH,IACA,CAAC;AAAA,MACL,GAAG;AAAA;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAWf,GAAI,SAAS,EAAE,QAAQ,mBAAmB,MAAM,EAAE,IAAI,CAAC;AAAA,MACvD,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC7B;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as InvitationFailure } from './types-
|
|
1
|
+
import { j as InvitationFailure } from './types-ioL47w7k.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* What became of a claim, in terms the invitee can be told.
|
|
@@ -118,4 +118,26 @@ declare function invitationOutcomeCookie(outcome: ClaimOutcome, name?: string):
|
|
|
118
118
|
*/
|
|
119
119
|
declare function isInvitationFailure(outcome: ClaimOutcome): outcome is InvitationFailure;
|
|
120
120
|
|
|
121
|
-
|
|
121
|
+
interface SsoProfile {
|
|
122
|
+
sub?: string;
|
|
123
|
+
email?: string;
|
|
124
|
+
email_verified?: boolean;
|
|
125
|
+
name?: string;
|
|
126
|
+
picture?: string;
|
|
127
|
+
roles?: unknown;
|
|
128
|
+
}
|
|
129
|
+
interface SsoMappedUser {
|
|
130
|
+
email: string;
|
|
131
|
+
emailVerified: boolean;
|
|
132
|
+
name: string;
|
|
133
|
+
image?: string;
|
|
134
|
+
role: "admin" | "user";
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Maps the identity provider's claims onto the local user. The admin role is
|
|
138
|
+
* recomputed from the roles claim on every sign-in, so a role removed at the
|
|
139
|
+
* provider is removed here the next time the person signs in.
|
|
140
|
+
*/
|
|
141
|
+
declare function mapSsoProfile(profile: SsoProfile, adminRole: string): SsoMappedUser;
|
|
142
|
+
|
|
143
|
+
export { type ClaimOutcome as C, type SsoMappedUser as S, type SsoProfile as a, type ClaimInvitationOptions as b, claimInvitation as c, completesSignup as d, invitationOutcomeCookie as e, inviteTokenFrom as f, holdInviteTokenCookie as h, isInvitationFailure as i, mapSsoProfile as m, pinInviteToken as p, releaseInviteTokenCookie as r };
|
|
@@ -129,6 +129,27 @@ interface PlatformTwoFactorConfig {
|
|
|
129
129
|
*/
|
|
130
130
|
skipVerificationOnEnable?: boolean;
|
|
131
131
|
}
|
|
132
|
+
interface PlatformSsoConfig {
|
|
133
|
+
/** The provider's issuer URL, e.g. https://id.urbangate.dev */
|
|
134
|
+
issuer: string;
|
|
135
|
+
clientId: string;
|
|
136
|
+
clientSecret: string;
|
|
137
|
+
/** The roles-claim value that grants this app's admin role, e.g. "tornade:admin". */
|
|
138
|
+
adminRole: string;
|
|
139
|
+
/** Better Auth provider id, in the callback path. Defaults to "urbangate". */
|
|
140
|
+
providerId?: string;
|
|
141
|
+
/** Lets a first visit create the local user. Defaults to true. */
|
|
142
|
+
allowSignUp?: boolean;
|
|
143
|
+
}
|
|
144
|
+
interface SsoClientSurface {
|
|
145
|
+
signIn: {
|
|
146
|
+
oauth2(args: {
|
|
147
|
+
providerId: string;
|
|
148
|
+
callbackURL?: string;
|
|
149
|
+
errorCallbackURL?: string;
|
|
150
|
+
}): Promise<AuthClientResult>;
|
|
151
|
+
};
|
|
152
|
+
}
|
|
132
153
|
interface PlatformAuthConfig {
|
|
133
154
|
/** PostgreSQL connection pool or connection string */
|
|
134
155
|
database: BetterAuthOptions["database"];
|
|
@@ -155,6 +176,12 @@ interface PlatformAuthConfig {
|
|
|
155
176
|
google?: SocialProviderOptions["google"];
|
|
156
177
|
/** GitHub OAuth config (omit to disable). Passed to Better Auth as given. */
|
|
157
178
|
github?: SocialProviderOptions["github"];
|
|
179
|
+
/**
|
|
180
|
+
* Single sign-on through the suite's identity provider (urbangate). Mounts
|
|
181
|
+
* an OIDC client; a person whose roles claim carries `adminRole` signs in
|
|
182
|
+
* as admin, anyone else as a plain user. Omit to leave it off.
|
|
183
|
+
*/
|
|
184
|
+
sso?: PlatformSsoConfig;
|
|
158
185
|
/**
|
|
159
186
|
* Override the OTP email subject line per verification type. Merged over
|
|
160
187
|
* the platform defaults — provide only the keys you want to change. The
|
|
@@ -702,4 +729,4 @@ interface AuthLayoutProps extends AuthHeadingProps {
|
|
|
702
729
|
footer?: React.ReactNode;
|
|
703
730
|
}
|
|
704
731
|
|
|
705
|
-
export type { AuthLayoutProps as A, ForgotPasswordFormProps as F, InvitationNoticeProps as I, LoginFormProps as L, MagicLinkFormProps as M, PlatformAuthClientConfig as P, RegisterFormProps as R, TwoFactorClientSurface as T, VerifyEmailFormProps as V, ResetPasswordFormProps as a, AuthClientResult as b, LinkComponent as c, AdminClientSurface as d, AuthClientDataResult as e, AuthClientSurface as f, AuthInviteProps as g, AuthNavProps as h, AuthThemeProps as i, InvitationFailure as j, LoginFormLabels as k, MagicLinkClientSurface as l, MagicLinkConfig as m, MagicLinkFormLabels as n, PlatformAuthConfig as o, PlatformAuthMailer as p, PlatformAuthMailerArgs as q, PlatformAuthMailerType as r, PlatformRateLimitConfig as s, PlatformRateLimitRule as t, PlatformSession as u, PlatformSessionData as v,
|
|
732
|
+
export type { AuthLayoutProps as A, ForgotPasswordFormProps as F, InvitationNoticeProps as I, LoginFormProps as L, MagicLinkFormProps as M, PlatformAuthClientConfig as P, RegisterFormProps as R, SsoClientSurface as S, TwoFactorClientSurface as T, VerifyEmailFormProps as V, ResetPasswordFormProps as a, AuthClientResult as b, LinkComponent as c, AdminClientSurface as d, AuthClientDataResult as e, AuthClientSurface as f, AuthInviteProps as g, AuthNavProps as h, AuthThemeProps as i, InvitationFailure as j, LoginFormLabels as k, MagicLinkClientSurface as l, MagicLinkConfig as m, MagicLinkFormLabels as n, PlatformAuthConfig as o, PlatformAuthMailer as p, PlatformAuthMailerArgs as q, PlatformAuthMailerType as r, PlatformRateLimitConfig as s, PlatformRateLimitRule as t, PlatformSession as u, PlatformSessionData as v, PlatformSsoConfig as w, PlatformTwoFactorConfig as x, PlatformUser as y, RegisterFormLabels as z };
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/signup-name.ts","../src/invitation.ts"],"sourcesContent":["/**\n * Fills in the display name of an account signed up without one.\n *\n * The sign-up form treats the name as optional and omits the key when it is\n * left blank, but Better Auth's user schema requires it and rejects the\n * request with `[body.name] Invalid input`. Naming the account is the server's\n * call, so the default is applied here rather than invented by the client.\n *\n * The local part of the address is the closest thing to a name the person has\n * actually given us. It is only a starting label: they can change it later,\n * and nothing keys off it.\n */\nexport function withSignUpName<T extends { email?: unknown; name?: unknown }>(\n body: T,\n): T & { name: string } {\n const name = typeof body.name === \"string\" ? body.name.trim() : \"\"\n if (name) return { ...body, name }\n\n const email = typeof body.email === \"string\" ? body.email.trim() : \"\"\n const at = email.lastIndexOf(\"@\")\n const localPart = at > 0 ? email.slice(0, at) : email\n\n return { ...body, name: localPart }\n}\n","import type { InvitationFailure } from \"./types\"\n\n/**\n * What became of a claim, in terms the invitee can be told.\n *\n * 'expired' and 'claimed' are kept apart from 'unknown' because only they say\n * the offer was real, which is what tells someone that asking for a new link is\n * worth it rather than doubting the address they were invited at. The three\n * failures match InvitationFailure, so an outcome feeds InvitationNotice\n * directly.\n */\nexport type ClaimOutcome = \"granted\" | InvitationFailure | \"failed\"\n\nconst OUTCOME_BY_STATUS: Record<number, ClaimOutcome> = {\n 404: \"unknown\",\n 409: \"claimed\",\n 410: \"expired\",\n}\n\nexport interface ClaimInvitationOptions {\n /** Absolute URL of the endpoint that redeems a token. */\n endpoint: string\n token: string\n /** The account the app just created, which the grant is attached to. */\n externalUserId: string\n /** Sent as the Authorization bearer — typically the app's API key. */\n apiKey?: string\n /** Merged into the request body, for backends wanting more than the token. */\n extra?: Record<string, unknown>\n /** Headers merged last, so a caller can pass a cookie-based credential. */\n headers?: Record<string, string>\n /** Bounds the call so a slow API never stalls the sign-in response. */\n timeoutMs?: number\n}\n\n/**\n * Redeems an invitation token for a user who has just signed in, turning the\n * offer into a grant on their account.\n *\n * Why this belongs on the SERVER, on the auth callback rather than in the page:\n * the invitation link lands on /register?invite=<token>, but the sign-up that\n * follows can complete through any of three flows (password + OTP, OAuth\n * redirect, email verification), and only two of them return to the page that\n * held the token. Claiming where the session is established covers every flow\n * with one code path.\n *\n * Best-effort by design: a sign-in must never fail because an invitation could\n * not be redeemed. A failed claim leaves the invitation unclaimed and the user\n * on their default tier — recoverable by following the link again, since a\n * refused claim consumes nothing.\n */\nexport async function claimInvitation({\n endpoint,\n token,\n externalUserId,\n apiKey,\n extra,\n headers,\n timeoutMs = 5000,\n}: ClaimInvitationOptions): Promise<ClaimOutcome> {\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),\n ...headers,\n },\n body: JSON.stringify({\n token,\n external_user_id: externalUserId,\n ...extra,\n }),\n signal: AbortSignal.timeout(timeoutMs),\n })\n\n if (res.ok) return \"granted\"\n return OUTCOME_BY_STATUS[res.status] ?? \"failed\"\n } catch {\n return \"failed\"\n }\n}\n\n/**\n * Extracts the invitation token from an auth request.\n *\n * The token lives on the page the invitee landed on (/register?invite=…), never\n * on the auth endpoints themselves, so it has to be recovered from the request\n * that completes the sign-up. Three sources, in order of trust:\n *\n * - the URL, for a callback reached through a redirect whose query string\n * the app controls;\n * - the cookie held since the link was opened, which is the only one that\n * survives an OAuth round trip or an OTP screen that never carried the\n * token (see holdInviteTokenCookie);\n * - the Referer, for the password flow, whose XHR is issued BY the page\n * holding it.\n *\n * The Referer stays last and stays supported: it covers a caller that never\n * held the cookie. It is attacker-controlled input on a best-effort path, so a\n * malformed one is ignored rather than thrown on.\n */\nexport function inviteTokenFrom(\n request: Request,\n param = \"invite\",\n): string | null {\n const direct = new URL(request.url).searchParams.get(param)\n if (direct && direct.trim() !== \"\") return direct\n\n const held = inviteTokenCookie(request)\n if (held) return held\n\n const referer = request.headers.get(\"referer\")\n if (!referer) return null\n try {\n const token = new URL(referer).searchParams.get(param)\n return token && token.trim() !== \"\" ? token : null\n } catch {\n return null\n }\n}\n\n/** Name of the cookie holding the token between the link and the claim. */\nconst INVITE_TOKEN_COOKIE = \"invite_token\"\n\n/**\n * Pins the token onto the browser the first time a request carries it, so the\n * rest of the sign-up can find it.\n *\n * Called on every auth request, not only the ones completing a sign-up: the\n * token is legible on the FIRST call of a flow (the page holding it issues that\n * XHR, so the Referer still has it) and gone by the last (verified from a\n * screen that never held it, or returned from Google). Waiting for the moment\n * the account exists is waiting one request too long.\n *\n * Returns null when there is nothing to pin — no token in the request, or one\n * already held — so a caller can skip the Set-Cookie entirely.\n */\nexport function pinInviteToken(\n request: Request,\n param = \"invite\",\n): string | null {\n if (inviteTokenCookie(request)) return null\n const token = inviteTokenFrom(request, param)\n return token ? holdInviteTokenCookie(token) : null\n}\n\n/**\n * Holds the token from the moment the link is opened until the account exists.\n *\n * The URL and the Referer each cover only part of the ground: the OTP flow\n * verifies from a screen that never carried the token, and an OAuth sign-up\n * comes back from Google with no Referer of ours at all. Both lose it, and the\n * invitee lands on the default tier with the offer still pending.\n *\n * SameSite=Lax rather than Strict: the return from Google is a cross-site\n * top-level navigation, which Strict would refuse — the one case this exists\n * for. HttpOnly because the page has no reason to read it, and short-lived\n * because signing up takes minutes: a single-use invitation has no business\n * sitting in a browser for longer.\n */\nexport function holdInviteTokenCookie(\n token: string,\n maxAgeSeconds = 1800,\n): string {\n return `${INVITE_TOKEN_COOKIE}=${encodeURIComponent(token)}; Path=/; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Lax`\n}\n\n/**\n * Clears the held token. Sent once the claim has been attempted: the token is\n * single-use, so keeping it would only replay a call that can no longer\n * succeed.\n */\nexport function releaseInviteTokenCookie(): string {\n return `${INVITE_TOKEN_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`\n}\n\nfunction inviteTokenCookie(request: Request): string | null {\n const header = request.headers.get(\"cookie\")\n if (!header) return null\n for (const part of header.split(\";\")) {\n const [name, ...rest] = part.trim().split(\"=\")\n if (name !== INVITE_TOKEN_COOKIE) continue\n const value = decodeURIComponent(rest.join(\"=\")).trim()\n return value === \"\" ? null : value\n }\n return null\n}\n\n/**\n * BetterAuth paths that complete a sign-up. Email/password returns the user\n * straight from sign-up/email; the OTP and OAuth flows only produce a usable\n * account once the verification/callback succeeds, so those are the moments\n * worth reacting to.\n */\nconst SIGNUP_COMPLETING = [\n \"/sign-up/email\",\n \"/sign-in/email-otp\",\n \"/email-otp/verify-email\",\n \"/callback/\",\n]\n\n/**\n * Whether this request is the one that just created a usable account — the\n * moment to provision, claim an invitation, or greet someone. Matching on the\n * path rather than on a response body keeps it flow-agnostic: the three\n * sign-up flows return three different shapes.\n */\nexport function completesSignup(pathname: string): boolean {\n return SIGNUP_COMPLETING.some((p) => pathname.includes(p))\n}\n\n/**\n * Carries a failed claim to the next page. The claim happens inside an auth\n * response nobody renders, so its result would otherwise reach only the server\n * log — leaving an invitee on the default tier with no idea their link had\n * lapsed. Short-lived and readable by the page, which reports it and clears it.\n */\nexport function invitationOutcomeCookie(\n outcome: ClaimOutcome,\n name = \"invite_claim\",\n): string {\n return `${name}=${outcome}; Path=/; Max-Age=120; SameSite=Lax`\n}\n\n/**\n * Whether an outcome is one the invitee should be shown a reason for.\n * 'failed' is excluded: it means the call did not complete, so the offer may\n * still be good and telling someone their invitation is invalid would be wrong.\n */\nexport function isInvitationFailure(\n outcome: ClaimOutcome,\n): outcome is InvitationFailure {\n return outcome === \"expired\" || outcome === \"claimed\" || outcome === \"unknown\"\n}\n"],"mappings":";AAYO,SAAS,eACd,MACsB;AACtB,QAAM,OAAO,OAAO,KAAK,SAAS,WAAW,KAAK,KAAK,KAAK,IAAI;AAChE,MAAI,KAAM,QAAO,EAAE,GAAG,MAAM,KAAK;AAEjC,QAAM,QAAQ,OAAO,KAAK,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI;AACnE,QAAM,KAAK,MAAM,YAAY,GAAG;AAChC,QAAM,YAAY,KAAK,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI;AAEhD,SAAO,EAAE,GAAG,MAAM,MAAM,UAAU;AACpC;;;ACVA,IAAM,oBAAkD;AAAA,EACtD,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAkCA,eAAsB,gBAAgB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AACd,GAAkD;AAChD,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,UAAU;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAI,SAAS,EAAE,eAAe,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,QACtD,GAAG;AAAA,MACL;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,kBAAkB;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