cauthy-auth 0.8.0 → 0.9.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/dist/client.d.mts CHANGED
@@ -95,6 +95,15 @@ interface AccountSession {
95
95
  * The signed-in person's own account. What weakens it — the password, the
96
96
  * second step, its recovery codes — asks for the current password again.
97
97
  */
98
+ /** A provider the account can also sign in with. */
99
+ interface LinkedIdentity {
100
+ provider: string;
101
+ /** The address the provider has for the person, when it said. */
102
+ email: string;
103
+ name: string;
104
+ /** When it was linked, in UTC (ISO 8601). */
105
+ linkedAt: string;
106
+ }
98
107
  interface AccountClient {
99
108
  /** The account, or null when nobody is signed in. */
100
109
  get(): Promise<Account | null>;
@@ -134,6 +143,34 @@ interface AccountClient {
134
143
  recoveryCodes: string[];
135
144
  }>>;
136
145
  };
146
+ /**
147
+ * Asks to sign in with another address. Nothing changes yet: the new address
148
+ * is mailed a link to confirm it, and once it is confirmed the old one is
149
+ * told, with a link that undoes it. Both open Cauthy's own page.
150
+ */
151
+ changeEmail(form: {
152
+ email: string;
153
+ password: string;
154
+ }): Promise<AuthResult<'sent', {
155
+ email: string;
156
+ }>>;
157
+ /** The providers (Google…) the account can also sign in with. */
158
+ identities(): Promise<LinkedIdentity[]>;
159
+ /**
160
+ * Sends the browser to the provider, to link it to the account; it comes back
161
+ * at `returnTo` with `?linked=<provider>`, or `?auth_error=<code>`.
162
+ */
163
+ link(provider: string, options?: {
164
+ returnTo?: string;
165
+ }): void;
166
+ /** Where `link` sends the browser, for a plain link. */
167
+ linkUrl(provider: string, options?: {
168
+ returnTo?: string;
169
+ }): string;
170
+ /** The account stops signing in with that provider. Refused when it would be left with no way to sign in. */
171
+ unlink(provider: string): Promise<AuthResult<'unlinked', {
172
+ provider: string;
173
+ }>>;
137
174
  /** Where the account is signed in. */
138
175
  sessions(): Promise<AccountSession[]>;
139
176
  /** Signs the account out everywhere, here too. */
@@ -233,4 +270,4 @@ interface AuthClientOptions {
233
270
  }
234
271
  declare function createAuthClient(options?: AuthClientOptions): AuthClient;
235
272
 
236
- export { type Account, type AccountClient, type AccountSession, type AuthClient, type AuthClientOptions, type AuthError, AuthField, type AuthMethods, type AuthResult, type SessionState, type SessionStore, type SessionStoreOptions, createAuthClient, createSessionStore };
273
+ export { type Account, type AccountClient, type AccountSession, type AuthClient, type AuthClientOptions, type AuthError, AuthField, type AuthMethods, type AuthResult, type LinkedIdentity, type SessionState, type SessionStore, type SessionStoreOptions, createAuthClient, createSessionStore };
package/dist/client.d.ts CHANGED
@@ -95,6 +95,15 @@ interface AccountSession {
95
95
  * The signed-in person's own account. What weakens it — the password, the
96
96
  * second step, its recovery codes — asks for the current password again.
97
97
  */
98
+ /** A provider the account can also sign in with. */
99
+ interface LinkedIdentity {
100
+ provider: string;
101
+ /** The address the provider has for the person, when it said. */
102
+ email: string;
103
+ name: string;
104
+ /** When it was linked, in UTC (ISO 8601). */
105
+ linkedAt: string;
106
+ }
98
107
  interface AccountClient {
99
108
  /** The account, or null when nobody is signed in. */
100
109
  get(): Promise<Account | null>;
@@ -134,6 +143,34 @@ interface AccountClient {
134
143
  recoveryCodes: string[];
135
144
  }>>;
136
145
  };
146
+ /**
147
+ * Asks to sign in with another address. Nothing changes yet: the new address
148
+ * is mailed a link to confirm it, and once it is confirmed the old one is
149
+ * told, with a link that undoes it. Both open Cauthy's own page.
150
+ */
151
+ changeEmail(form: {
152
+ email: string;
153
+ password: string;
154
+ }): Promise<AuthResult<'sent', {
155
+ email: string;
156
+ }>>;
157
+ /** The providers (Google…) the account can also sign in with. */
158
+ identities(): Promise<LinkedIdentity[]>;
159
+ /**
160
+ * Sends the browser to the provider, to link it to the account; it comes back
161
+ * at `returnTo` with `?linked=<provider>`, or `?auth_error=<code>`.
162
+ */
163
+ link(provider: string, options?: {
164
+ returnTo?: string;
165
+ }): void;
166
+ /** Where `link` sends the browser, for a plain link. */
167
+ linkUrl(provider: string, options?: {
168
+ returnTo?: string;
169
+ }): string;
170
+ /** The account stops signing in with that provider. Refused when it would be left with no way to sign in. */
171
+ unlink(provider: string): Promise<AuthResult<'unlinked', {
172
+ provider: string;
173
+ }>>;
137
174
  /** Where the account is signed in. */
138
175
  sessions(): Promise<AccountSession[]>;
139
176
  /** Signs the account out everywhere, here too. */
@@ -233,4 +270,4 @@ interface AuthClientOptions {
233
270
  }
234
271
  declare function createAuthClient(options?: AuthClientOptions): AuthClient;
235
272
 
236
- export { type Account, type AccountClient, type AccountSession, type AuthClient, type AuthClientOptions, type AuthError, AuthField, type AuthMethods, type AuthResult, type SessionState, type SessionStore, type SessionStoreOptions, createAuthClient, createSessionStore };
273
+ export { type Account, type AccountClient, type AccountSession, type AuthClient, type AuthClientOptions, type AuthError, AuthField, type AuthMethods, type AuthResult, type LinkedIdentity, type SessionState, type SessionStore, type SessionStoreOptions, createAuthClient, createSessionStore };
package/dist/client.js CHANGED
@@ -242,6 +242,7 @@ function createAuthClient(options = {}) {
242
242
  return null;
243
243
  }
244
244
  }
245
+ const linkUrl = (provider, o = {}) => `${base}/me/identities/link/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ""}`;
245
246
  const socialUrl = (provider, o = {}) => `${base}/sign-in/social/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ""}`;
246
247
  const passkeyUrl = (o = {}) => {
247
248
  const q = new URLSearchParams({ method: "passkey" });
@@ -288,6 +289,16 @@ function createAuthClient(options = {}) {
288
289
  disable: (f) => post("/me/mfa/disable", { password: f.password }, null),
289
290
  recoveryCodes: (f) => post("/me/mfa/recovery-codes", { password: f.password }, null)
290
291
  },
292
+ changeEmail: (f) => post("/me/email", { email: f.email, password: f.password }, checkEmail(f.email)),
293
+ async identities() {
294
+ const body = await read("/me/identities");
295
+ return body && Array.isArray(body.identities) ? body.identities : [];
296
+ },
297
+ linkUrl,
298
+ link(provider, o) {
299
+ window.location.assign(linkUrl(provider, o));
300
+ },
301
+ unlink: (provider) => post("/me/identities/unlink", { provider }, null),
291
302
  async sessions() {
292
303
  const body = await read("/me/sessions");
293
304
  return body && Array.isArray(body.sessions) ? body.sessions : [];
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/theme.ts","../src/validate.ts","../src/store.ts"],"sourcesContent":["// The application's own sign-in screens, in the browser.\n//\n// const auth = createAuthClient()\n// const r = await auth.signIn.email({ email, password })\n// if (!r.ok) show(r.error.message) // r.error.field says which input\n// else if (r.status === 'mfa_required') askForTheCode()\n//\n// Every call goes to the application's own server (`/api/auth/*`), never to\n// Cauthy: the browser holds no token, before or after. A form is checked here\n// before it is sent, with the rules the server checks again.\n\nimport { fromWire, type CauthyTheme } from './theme'\nimport type { PublicSession } from './types'\nimport { checkCode, checkEmail, checkName, checkNewPassword, checkPassword, firstProblem, type AuthField, type FieldProblem } from './validate'\n\nexport { checkCode, checkEmail, checkName, checkNewPassword, checkPassword, MIN_PASSWORD, type AuthField, type FieldProblem } from './validate'\n\n/** What went wrong, in a form the screen can show. */\nexport interface AuthError {\n /** Stable, for translating: `invalid_credentials`, `invalid_email`, `too_short`, `email_taken`, `unavailable`… */\n code: string\n message: string\n /** The input it is about, when it is about one. */\n field?: AuthField\n}\n\nexport type AuthResult<S extends string, More = unknown> = ({ ok: true; status: S } & More) | { ok: false; error: AuthError }\n\n/** What the screen may offer. */\nexport interface AuthMethods {\n /** The providers the workspace signs people in with: `{ id: 'google', name: 'Google' }`. */\n providers: { id: string; name: string }[]\n /** Whether people may create an account themselves. */\n signUp: boolean\n magicLink: boolean\n /** Whether to offer a passkey. It is asked for on Cauthy's page: the person goes there for that step and comes back signed in. */\n passkey: boolean\n}\n\n/** A person's own account, as their account screen shows it. */\nexport interface Account {\n id: string\n email: string\n name: string\n emailVerified: boolean\n /** False for an account that only signs in through a provider: it has no current password to ask for. */\n hasPassword: boolean\n mfaEnabled: boolean\n}\n\n/** Somewhere the person is signed in. Moments are UTC. */\nexport interface AccountSession {\n /** \"Mac · Chrome\", or \"\" when the browser did not say. */\n device: string\n ip: string\n createdAt: string\n expiresAt: string\n}\n\n/**\n * The signed-in person's own account. What weakens it — the password, the\n * second step, its recovery codes — asks for the current password again.\n */\nexport interface AccountClient {\n /** The account, or null when nobody is signed in. */\n get(): Promise<Account | null>\n update(form: { name: string }): Promise<AuthResult<'saved', { account: Account }>>\n /** Ends every other session of the account; this one stays signed in. */\n changePassword(form: { password: string; newPassword: string }): Promise<AuthResult<'changed', { signedIn: boolean }>>\n mfa: {\n /** Starts turning the second step on: show `secret` (or `otpauthUri` as a QR code) to add to an authenticator app, then call `verify`. */\n setup(form: { password: string }): Promise<AuthResult<'started', { secret: string; otpauthUri: string }>>\n /** Turns it on with a code from the app. `recoveryCodes` are shown this once. */\n verify(form: { code: string }): Promise<AuthResult<'enabled', { recoveryCodes: string[] }>>\n disable(form: { password: string }): Promise<AuthResult<'disabled'>>\n /** New recovery codes; the earlier ones stop working. */\n recoveryCodes(form: { password: string }): Promise<AuthResult<'renewed', { recoveryCodes: string[] }>>\n }\n /** Where the account is signed in. */\n sessions(): Promise<AccountSession[]>\n /** Signs the account out everywhere, here too. */\n signOutEverywhere(): Promise<AuthResult<'signed_out'>>\n}\n\nexport interface AuthClient {\n signIn: {\n /** With address and password. `mfa_required`: ask for the code and call `signIn.mfa`. */\n email(form: { email: string; password: string }): Promise<AuthResult<'signed_in', { session: PublicSession }> | AuthResult<'mfa_required'>>\n /** The second step: the code of the authenticator app, or a recovery code. */\n mfa(form: { code: string }): Promise<AuthResult<'signed_in', { session: PublicSession }>>\n /** Mails a link that signs the person in. The answer is the same whether or not the address has an account. */\n magicLink(form: { email: string }): Promise<AuthResult<'sent'>>\n /** Signs in with the token the mailed link opened the page with (`ml_token`). */\n magicLinkVerify(form: { token: string }): Promise<AuthResult<'signed_in', { session: PublicSession }>>\n /** Signs in with the code that came in the same mail as the link, for somebody reading it on another device. */\n emailCode(form: { code: string }): Promise<AuthResult<'signed_in', { session: PublicSession }>>\n /** Sends the browser to Cauthy's page to use a passkey; it comes back signed in, at `returnTo`. */\n passkey(options?: { returnTo?: string; locale?: string }): void\n /** Where `passkey` sends the browser, for a plain link. */\n passkeyUrl(options?: { returnTo?: string; locale?: string }): string\n /** Sends the browser to the provider; it comes back signed in, at `returnTo`. */\n social(provider: string, options?: { returnTo?: string }): void\n /** Where `social` sends the browser, for a plain link. */\n socialUrl(provider: string, options?: { returnTo?: string }): string\n }\n signUp: {\n /** `verification_required`: the account exists and must open the link Cauthy mailed before it can sign in. */\n email(form: { email: string; password: string; name?: string }): Promise<AuthResult<'signed_in', { session: PublicSession }> | AuthResult<'verification_required', { email: string }>>\n }\n /** Mails a link to choose a new password. The answer is the same whether or not the address has an account. */\n forgotPassword(form: { email: string }): Promise<AuthResult<'sent'>>\n /** Sets the new password, with the token the mailed link opened the page with (`token`). */\n resetPassword(form: { token: string; password: string }): Promise<AuthResult<'changed'>>\n /** Confirms the address, with the token the mailed link opened the page with (`token`). */\n verifyEmail(form: { token: string }): Promise<AuthResult<'verified'>>\n signOut(): Promise<AuthResult<'signed_out'>>\n /** The signed-in person's own account. */\n account: AccountClient\n /** Who is signed in, or null. */\n getSession(): Promise<PublicSession | null>\n methods(): Promise<AuthMethods>\n /**\n * How the workspace's forms look — colours, corners, typeface — as a person\n * set it in Cauthy's dashboard. Read once per page; null when Cauthy cannot say.\n */\n look(): Promise<CauthyTheme | null>\n}\n\nexport interface AuthClientOptions {\n /** Where the server mounted the routes. Default: `/api/auth`. */\n basePath?: string\n fetch?: typeof fetch\n}\n\nconst UNAVAILABLE: AuthError = { code: 'unavailable', message: 'Sign-in is unavailable right now. Try again in a moment.' }\n\nexport function createAuthClient(options: AuthClientOptions = {}): AuthClient {\n const base = (options.basePath ?? '/api/auth').replace(/\\/+$/, '')\n const doFetch: typeof fetch = (...args) => (options.fetch ?? fetch)(...args)\n\n async function post(path: string, form: Record<string, unknown>, bad: FieldProblem | null): Promise<any> {\n if (bad) return { ok: false, error: { code: bad.code, message: bad.message, field: bad.field } }\n try {\n const res = await doFetch(`${base}${path}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify(form),\n })\n const body = (await res.json().catch(() => null)) as any\n if (res.ok && body && typeof body.status === 'string') return { ok: true, ...body }\n const e = body?.error\n return { ok: false, error: e && typeof e.code === 'string' ? { code: e.code, message: String(e.message ?? ''), ...(e.field ? { field: e.field } : {}) } : UNAVAILABLE }\n } catch {\n return { ok: false, error: UNAVAILABLE }\n }\n }\n\n let looked: Promise<CauthyTheme | null> | undefined\n\n async function read(path: string): Promise<any> {\n try {\n const res = await doFetch(`${base}${path}`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n return res.ok ? await res.json() : null\n } catch {\n return null\n }\n }\n\n const socialUrl = (provider: string, o: { returnTo?: string } = {}) =>\n `${base}/sign-in/social/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ''}`\n\n const passkeyUrl = (o: { returnTo?: string; locale?: string } = {}) => {\n const q = new URLSearchParams({ method: 'passkey' })\n if (o.returnTo) q.set('return_to', o.returnTo)\n if (o.locale) q.set('locale', o.locale)\n return `${base}/login?${q}`\n }\n\n return {\n signIn: {\n email: (f) => post('/sign-in/email', { email: f.email, password: f.password }, firstProblem(checkEmail(f.email), checkPassword(f.password))),\n mfa: (f) => post('/sign-in/mfa', { code: f.code }, checkCode(f.code)),\n magicLink: (f) => post('/sign-in/magic-link', { email: f.email }, checkEmail(f.email)),\n magicLinkVerify: (f) => post('/sign-in/magic-link/verify', { token: f.token }, null),\n emailCode: (f) => post('/sign-in/email-code', { code: f.code }, checkCode(f.code)),\n passkeyUrl,\n passkey(o) {\n window.location.assign(passkeyUrl(o))\n },\n socialUrl,\n social(provider, o) {\n window.location.assign(socialUrl(provider, o))\n },\n },\n signUp: {\n email: (f) => post('/sign-up/email', { email: f.email, password: f.password, name: f.name }, firstProblem(checkName(f.name), checkEmail(f.email), checkNewPassword(f.password))),\n },\n forgotPassword: (f) => post('/forgot-password', { email: f.email }, checkEmail(f.email)),\n resetPassword: (f) => post('/reset-password', { token: f.token, password: f.password }, checkNewPassword(f.password)),\n verifyEmail: (f) => post('/verify-email', { token: f.token }, null),\n signOut: () => post('/sign-out', {}, null),\n account: {\n async get() {\n const body = await read('/me')\n return body && typeof body.account === 'object' ? (body.account as Account) : null\n },\n update: (f) => post('/me', { name: f.name }, checkName(f.name)),\n changePassword: (f) => {\n const bad = checkNewPassword(f.newPassword)\n return post('/me/password', { password: f.password, newPassword: f.newPassword }, bad ? { ...bad, field: 'newPassword' } : null)\n },\n mfa: {\n setup: (f) => post('/me/mfa/setup', { password: f.password }, null),\n verify: (f) => post('/me/mfa/verify', { code: f.code }, checkCode(f.code)),\n disable: (f) => post('/me/mfa/disable', { password: f.password }, null),\n recoveryCodes: (f) => post('/me/mfa/recovery-codes', { password: f.password }, null),\n },\n async sessions() {\n const body = await read('/me/sessions')\n return body && Array.isArray(body.sessions) ? (body.sessions as AccountSession[]) : []\n },\n signOutEverywhere: () => post('/me/sessions/end', {}, null),\n },\n async getSession() {\n try {\n const res = await doFetch(`${base}/session`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n if (!res.ok) return null\n return ((await res.json()) as { session: PublicSession | null }).session\n } catch {\n return null\n }\n },\n look() {\n looked ??= read('/look').then((wire) => (wire && typeof wire === 'object' ? fromWire(wire) : null))\n return looked\n },\n async methods() {\n try {\n const res = await doFetch(`${base}/methods`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n if (res.ok) return (await res.json()) as AuthMethods\n } catch {\n // falls through\n }\n return { providers: [], signUp: true, magicLink: false, passkey: false }\n },\n }\n}\n\nexport { createSessionStore, type SessionState, type SessionStore, type SessionStoreOptions } from './store'\n","// An application's look, for Cauthy's hosted pages.\n//\n// Cauthy's pages — sign-in, sign-up, the account page — can take the colours,\n// corners, typeface and logo of the application that sends its people there,\n// so signing in reads as a page of the application. A theme is a short list of\n// values, which Cauthy checks one by one; it is never CSS.\n//\n// An application built with Stackmyth already has those values, as its\n// `--sm-*` tokens. `themeFromStackmyth` reads them out of its stylesheets.\n\n/** How an application looks on Cauthy's hosted pages. Every value is optional. */\n/** One font file the application serves: a family in one weight (or a range) and one style. */\nexport interface ThemeFont {\n family: string\n /** An https address of a `.woff2` file. It must answer with `Access-Control-Allow-Origin` for Cauthy's origin. */\n url: string\n /** `400`, or `\"100 900\"` for a variable font. Default: 400. */\n weight?: number | string\n style?: 'normal' | 'italic'\n}\n\n/** What an application says on its sign-in page, in one language. */\nexport interface ThemeTexts {\n /** Replaces \"Sign in\". */\n heading?: string\n /** Replaces \"to continue to …\". */\n subheading?: string\n /** The messages of the split layout's panel, shown one at a time (up to 5). */\n panel?: string[]\n /** Links at the foot of the split layout: privacy, terms (up to 4). */\n links?: { label: string; url: string }[]\n}\n\nexport interface CauthyTheme {\n /** The page. Colours are `#rrggbb` or `rgba(r, g, b, a)`. */\n background?: string\n /** The card, and inputs. */\n surface?: string\n /** Headings and what is typed. */\n text?: string\n /** Paragraphs, labels, small print. */\n textMuted?: string\n border?: string\n /** The fields and the secondary buttons, when they are not the card's colours. */\n inputBackground?: string\n inputBorder?: string\n /** The main button, and what is written on it. */\n primary?: string\n primaryText?: string\n /** Links, and the focus ring. */\n accent?: string\n error?: string\n errorBackground?: string\n success?: string\n successBackground?: string\n /** Corners of cards and inputs, in pixels (0–40). */\n radius?: number\n /** Corners of buttons, in pixels (0–40). */\n buttonRadius?: number\n /** A CSS font-family list: the application's typeface first, a system font after it. */\n fontFamily?: string\n /** The files of the typefaces `fontFamily` names, for people who do not have them installed. */\n fonts?: ThemeFont[]\n /** An image shown where \"Cauthy\" is, over https. */\n logoUrl?: string\n /**\n * How the sign-in pages are laid out: `card` (the default, one card in the\n * middle) or `split` (the form on one side, a panel that presents the\n * application on the other).\n */\n layout?: 'card' | 'split'\n /** The colours the split layout's backdrop blends, one to four. */\n panelColors?: string[]\n /** The colour of what is written on the panel. */\n panelText?: string\n /** An https image shown over the panel's messages. */\n panelIconUrl?: string\n /** The application's own words on the sign-in page, by language (`en`, `es`). */\n texts?: Record<string, ThemeTexts>\n /**\n * The application's Stackmyth tokens (`--sm-*`), from `tokensFromStackmyth`.\n * Cauthy's pages are drawn with Stackmyth's components, so these make its\n * buttons and fields the application's own. They are laid over the named values.\n */\n tokens?: Record<string, string>\n}\n\nexport interface StackmythThemeOptions {\n /**\n * The named theme to read, when the stylesheet keeps several under\n * `[data-theme=…]` (`\"vennet\"`). Without it only what applies to every\n * page (`:root`) is read.\n */\n theme?: string\n /** Which of the application's two modes to take. Default: `light`. */\n mode?: 'light' | 'dark'\n logoUrl?: string\n}\n\nexport interface ImportedTheme {\n theme: CauthyTheme\n /** Tokens that were there and could not be carried over, and why. */\n warnings: string[]\n}\n\nconst MAX_RADIUS = 40\n\n// ── Reading custom properties out of CSS ───────────────────────────────────\n\ninterface Declaration {\n name: string\n value: string\n /** The selectors and at-rules it sits inside, outermost first. */\n within: string[]\n}\n\nfunction declarations(css: string): Declaration[] {\n const text = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n const out: Declaration[] = []\n const within: string[] = []\n let chunk = ''\n let quote = ''\n let depth = 0 // parentheses, so a `;` inside url(…) does not end anything\n const flush = () => {\n const m = /^\\s*(--[\\w-]+)\\s*:\\s*([\\s\\S]+?)\\s*$/.exec(chunk)\n if (m) out.push({ name: m[1], value: m[2].replace(/\\s+/g, ' ').replace(/\\s*!important$/, ''), within: [...within] })\n chunk = ''\n }\n for (const ch of text) {\n if (quote) {\n chunk += ch\n if (ch === quote) quote = ''\n continue\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch\n chunk += ch\n } else if (ch === '(') {\n depth++\n chunk += ch\n } else if (ch === ')') {\n depth = Math.max(0, depth - 1)\n chunk += ch\n } else if (ch === '{' && depth === 0) {\n within.push(chunk.trim().replace(/\\s+/g, ' '))\n chunk = ''\n } else if (ch === '}' && depth === 0) {\n flush()\n within.pop()\n } else if (ch === ';' && depth === 0) {\n flush()\n } else {\n chunk += ch\n }\n }\n return out\n}\n\nconst DARK = /prefers-color-scheme:\\s*dark|data-(mode|theme|color-scheme)=[\"']?dark|\\.dark\\b/i\nconst LIGHT = /prefers-color-scheme:\\s*light|data-(mode|theme|color-scheme)=[\"']?light|\\.light\\b/i\nconst NAMED = /data-theme=[\"']?([\\w-]+)/i\n\n/** Whether a declaration applies to the page being themed. */\nfunction applies(d: Declaration, o: Required<Pick<StackmythThemeOptions, 'mode'>> & { theme?: string }): boolean {\n for (const scope of d.within) {\n if (o.mode === 'light' && DARK.test(scope)) return false\n if (o.mode === 'dark' && LIGHT.test(scope)) return false\n const named = NAMED.exec(scope)\n if (named && !/^(dark|light)$/i.test(named[1]) && named[1] !== o.theme) return false\n // Component-level rules (`.btn { --sm-… }`) are not the page's theme;\n // the class a mode is switched with (`.dark`, as shadcn/ui does) is.\n if (!scope.startsWith('@') && !/:root|^html\\b|^body\\b|\\[data-|^\\*$|:host|^\\.(dark|light)\\b/.test(scope)) return false\n }\n return true\n}\n\n// ── Tokens ─────────────────────────────────────────────────────────────────\n\n/** What a token's value may be written with, as Cauthy checks it. */\nconst TOKEN_CHARS = /^[A-Za-z0-9 #%.,()/'\"_+*-]+$/\nconst TOKEN_FUNCS = new Set(['var', 'calc', 'min', 'max', 'clamp', 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color',\n 'color-mix', 'light-dark', 'cubic-bezier', 'steps', 'linear', 'linear-gradient', 'radial-gradient', 'conic-gradient',\n 'repeating-linear-gradient', 'repeating-radial-gradient', 'drop-shadow', 'blur', 'translate', 'translatex', 'translatey', 'scale', 'rotate'])\n\nfunction tokenValue(value: string): string | null {\n const v = value.replace(/\\s+/g, ' ').trim()\n if (v === '' || v.length > 400 || !TOKEN_CHARS.test(v)) return null\n for (const m of v.matchAll(/([A-Za-z-]+)\\(/g)) if (!TOKEN_FUNCS.has(m[1].toLowerCase())) return null\n if (/^\\(|[ ,(]\\(/.test(v)) return null\n return v\n}\n\n/** A scope that is the page's theme itself: the root, or the theme and mode attributes — never a component inside it. */\nconst THEME_SCOPE = /^(?:\\s*(?::root|html|body|\\[data-(?:theme|mode|color-scheme)(?:=[\"']?[\\w-]+[\"']?)?\\])\\s*,?)+$/i\n\nexport interface StackmythTokens {\n /** Every `--sm-*` token the stylesheets set for the page, ready for `theme.tokens`. */\n tokens: Record<string, string>\n /** Tokens that were there and Cauthy would not take, and why. */\n warnings: string[]\n}\n\n/**\n * Reads an application's Stackmyth tokens out of its stylesheets: every\n * `--sm-*` custom property its theme sets, in the order the sheets are given\n * (a later one wins). Its own names — a brand palette the tokens point at —\n * are written in, so what comes out stands on Stackmyth's names alone.\n *\n * Cauthy's sign-in pages are drawn with Stackmyth's components: these tokens\n * are what makes them look like the application.\n */\nexport function tokensFromStackmyth(css: string | string[], options: StackmythThemeOptions = {}): StackmythTokens {\n const mode = options.mode ?? 'light'\n const all = (Array.isArray(css) ? css : [css]).flatMap(declarations)\n const named = options.theme ?? all.map((d) => d.within.map((w) => NAMED.exec(w)?.[1]).find((n) => n && !/^(dark|light)$/i.test(n))).find(Boolean)\n const vars = new Map<string, string>()\n for (const d of all) {\n if (!applies(d, { mode, theme: named })) continue\n if (!d.within.every((w) => w.startsWith('@') || THEME_SCOPE.test(w))) continue\n vars.set(d.name, d.value)\n }\n // The application's own names are written in; Stackmyth's are left as references.\n const inline = (value: string, depth = 0): string | null => {\n if (depth > 16) return null\n let failed = false\n let out = value\n for (let guard = 0; guard < 64; guard++) {\n const next = out.replace(/var\\(\\s*(--(?!sm-)[\\w-]+)\\s*(?:,\\s*([^()]*(?:\\([^()]*\\)[^()]*)*))?\\)/, (_m, name: string, fallback?: string) => {\n const known = vars.get(name)\n const got = known !== undefined ? inline(known, depth + 1) : fallback !== undefined ? inline(fallback.trim(), depth + 1) : null\n if (got === null) failed = true\n return got ?? ''\n })\n if (failed) return null\n if (next === out) break\n out = next\n }\n return out\n }\n const tokens: Record<string, string> = {}\n const warnings: string[] = []\n for (const [name, raw] of vars) {\n if (!/^--sm-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) continue\n const written = inline(raw)\n const value = written === null ? null : tokenValue(written)\n if (value === null) warnings.push(`${name}: \"${raw.length > 60 ? raw.slice(0, 57) + '…' : raw}\" is not a value Cauthy takes`)\n else tokens[name] = value\n }\n if (Object.keys(tokens).length === 0) warnings.push('no --sm-* token was found in these stylesheets')\n return { tokens, warnings }\n}\n\n// ── Values ─────────────────────────────────────────────────────────────────\n\nfunction resolve(value: string, vars: Map<string, string>, seen = 0): string | null {\n if (seen > 16) return null\n let unresolved = false\n // Innermost var() first: fallbacks may hold another var().\n let out = value\n for (let guard = 0; guard < 32 && /var\\(/.test(out); guard++) {\n out = out.replace(/var\\(\\s*(--[\\w-]+)\\s*(?:,\\s*([^()]*(?:\\([^()]*\\)[^()]*)*))?\\)/, (_m, name: string, fallback?: string) => {\n const known = vars.get(name)\n const next = known !== undefined ? resolve(known, vars, seen + 1) : fallback !== undefined ? resolve(fallback.trim(), vars, seen + 1) : null\n if (next === null) unresolved = true\n return next ?? ''\n })\n if (unresolved) return null\n }\n return /var\\(/.test(out) ? null : out.trim()\n}\n\nconst clamp01 = (n: number) => Math.min(1, Math.max(0, n))\nconst hex2 = (n: number) => Math.round(clamp01(n) * 255).toString(16).padStart(2, '0')\nconst gamma = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055)\n\nfunction out(r: number, g: number, b: number, a = 1): string {\n if (a >= 1) return `#${hex2(r)}${hex2(g)}${hex2(b)}`\n return `rgba(${Math.round(clamp01(r) * 255)}, ${Math.round(clamp01(g) * 255)}, ${Math.round(clamp01(b) * 255)}, ${Math.round(clamp01(a) * 1000) / 1000})`\n}\n\nconst alpha = (s: string | undefined) => (s === undefined ? 1 : s.endsWith('%') ? parseFloat(s) / 100 : parseFloat(s))\n\nconst KEYWORDS: Record<string, string> = { white: '#ffffff', black: '#000000' }\n\n/** A colour as Cauthy takes it — `#rrggbb` or `rgba(…)` — or null when it is none it can read. */\nexport function toColor(value: string): string | null {\n const v = value.trim().toLowerCase()\n if (KEYWORDS[v]) return KEYWORDS[v]\n if (/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(v)) return v\n let m = /^rgba?\\(\\s*([\\d.]+%?)[\\s,]+([\\d.]+%?)[\\s,]+([\\d.]+%?)(?:\\s*[,/]\\s*([\\d.]+%?))?\\s*\\)$/.exec(v)\n if (m) {\n const ch = (s: string) => (s.endsWith('%') ? parseFloat(s) / 100 : parseFloat(s) / 255)\n return out(ch(m[1]), ch(m[2]), ch(m[3]), alpha(m[4]))\n }\n m = /^hsla?\\(\\s*([\\d.]+)(?:deg)?[\\s,]+([\\d.]+)%[\\s,]+([\\d.]+)%(?:\\s*[,/]\\s*([\\d.]+%?))?\\s*\\)$/.exec(v)\n if (m) {\n const h = ((parseFloat(m[1]) % 360) + 360) % 360\n const s = parseFloat(m[2]) / 100\n const l = parseFloat(m[3]) / 100\n const f = (n: number) => {\n const k = (n + h / 30) % 12\n return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1))\n }\n return out(f(0), f(8), f(4), alpha(m[4]))\n }\n m = /^oklch\\(\\s*([\\d.]+%?)\\s+([\\d.]+%?)\\s+([\\d.]+)(?:deg)?(?:\\s*\\/\\s*([\\d.]+%?))?\\s*\\)$/.exec(v)\n if (m) {\n const L = m[1].endsWith('%') ? parseFloat(m[1]) / 100 : parseFloat(m[1])\n const C = m[2].endsWith('%') ? (parseFloat(m[2]) / 100) * 0.4 : parseFloat(m[2])\n const H = (parseFloat(m[3]) * Math.PI) / 180\n const a = C * Math.cos(H)\n const b = C * Math.sin(H)\n const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3)\n const mm = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3)\n const s = Math.pow(L - 0.0894841775 * a - 1.291485548 * b, 3)\n return out(\n gamma(4.0767416621 * l - 3.3077115913 * mm + 0.2309699292 * s),\n gamma(-1.2684380046 * l + 2.6097574011 * mm - 0.3413193965 * s),\n gamma(-0.0041960863 * l - 0.7034186147 * mm + 1.707614701 * s),\n alpha(m[4]),\n )\n }\n return null\n}\n\n/** A length in pixels, within what Cauthy takes, or null. */\nfunction toRadius(value: string): number | null {\n const m = /^([\\d.]+)(px|rem|em)?$/.exec(value.trim())\n if (!m) return null\n const px = parseFloat(m[1]) * (m[2] === 'rem' || m[2] === 'em' ? 16 : 1)\n return Number.isFinite(px) ? Math.min(MAX_RADIUS, Math.max(0, Math.round(px))) : null\n}\n\n/** A font list as Cauthy takes it, or null. */\nfunction toFont(value: string): string | null {\n const v = value.trim()\n return /^[A-Za-z0-9 ,'\"_-]{1,200}$/.test(v) && (v.match(/\"/g)?.length ?? 0) % 2 === 0 && (v.match(/'/g)?.length ?? 0) % 2 === 0 ? v : null\n}\n\n// ── Stackmyth ──────────────────────────────────────────────────────────────\n\n/** Which Stackmyth token each value of a theme is read from, first found wins. */\nconst COLORS: [keyof CauthyTheme, string[]][] = [\n ['background', ['--sm-bg-surface', '--sm-surface']],\n ['surface', ['--sm-bg-surface-raised', '--sm-surface-raised']],\n ['text', ['--sm-text-primary', '--sm-surface-text']],\n ['textMuted', ['--sm-text-secondary']],\n ['border', ['--sm-border-default', '--sm-surface-border']],\n ['primary', ['--sm-primary', '--sm-bg-interactive']],\n ['primaryText', ['--sm-primary-text', '--sm-text-inverse']],\n ['accent', ['--sm-text-brand', '--sm-border-focus', '--sm-accent']],\n ['error', ['--sm-error-soft-text', '--sm-error']],\n ['errorBackground', ['--sm-error-soft']],\n ['success', ['--sm-success-soft-text', '--sm-success']],\n ['successBackground', ['--sm-success-soft']],\n]\n\n/**\n * Reads an application's Stackmyth theme out of its stylesheets.\n *\n * Give it the CSS that declares the tokens, in the order the application\n * loads it — Stackmyth's own (`@stackmyth/core/core.vars.css`, or a theme\n * file) and then the application's brand file that re-points them. Tokens\n * that point at the application's own variables are followed. The\n * application's dark mode is left out unless asked for.\n */\nexport function themeFromStackmyth(css: string | string[], options: StackmythThemeOptions = {}): ImportedTheme {\n const o = { mode: options.mode ?? 'light', theme: options.theme }\n const vars = new Map<string, string>()\n for (const sheet of Array.isArray(css) ? css : [css]) {\n for (const d of declarations(sheet)) if (applies(d, o)) vars.set(d.name, d.value)\n }\n const theme: CauthyTheme = {}\n const warnings: string[] = []\n\n const read = <T>(tokens: string[], to: (v: string) => T | null, what: string): T | undefined => {\n for (const token of tokens) {\n const raw = vars.get(token)\n if (raw === undefined) continue\n const value = resolve(raw, vars)\n const got = value === null ? null : to(value)\n if (got !== null) return got\n warnings.push(`${token}: \"${raw}\" is not ${what} Cauthy can take`)\n }\n return undefined\n }\n\n for (const [field, tokens] of COLORS) {\n const c = read(tokens, toColor, 'a colour')\n if (c !== undefined) (theme as Record<string, unknown>)[field] = c\n }\n const radius = read(['--sm-radius-container', '--sm-radius-md'], toRadius, 'a length')\n if (radius !== undefined) theme.radius = radius\n const button = read(['--sm-radius-interactive', '--sm-radius-sm'], toRadius, 'a length')\n if (button !== undefined) theme.buttonRadius = button\n const font = read(['--sm-font-family'], toFont, 'a font list')\n if (font !== undefined) theme.fontFamily = font\n if (options.logoUrl) theme.logoUrl = options.logoUrl\n\n if (vars.size === 0) warnings.push('no custom properties were found: is this the stylesheet that declares the --sm-* tokens?')\n else if (![...vars.keys()].some((k) => k.startsWith('--sm-'))) warnings.push('no --sm-* token was found in these stylesheets')\n return { theme, warnings }\n}\n\n// ── Any stylesheet ─────────────────────────────────────────────────────────\n\n/** The values of a theme a stylesheet can say. */\nexport type ThemeField =\n | 'background' | 'surface' | 'text' | 'textMuted' | 'border' | 'inputBackground' | 'inputBorder'\n | 'primary' | 'primaryText' | 'accent' | 'error' | 'errorBackground' | 'success' | 'successBackground'\n | 'radius' | 'buttonRadius' | 'fontFamily'\n\n/** How a stylesheet names its look: Stackmyth's tokens, shadcn/ui's (and Tailwind's), or the application's own. */\nexport type CssFormat = 'stackmyth' | 'shadcn' | 'custom'\n\nexport interface CssThemeOptions {\n /** Which names to read. Default: `auto`, told from the stylesheet itself. */\n format?: CssFormat | 'auto'\n /** Which of the application's two modes to take. Default: `light`. */\n mode?: 'light' | 'dark'\n /** The named theme to read, when the stylesheet keeps several under `[data-theme=…]`. */\n theme?: string\n /** For `custom`: the variable each value is read from, `{ primary: '--brand' }`. */\n map?: Partial<Record<ThemeField, string>>\n}\n\nexport interface CssImportedTheme extends ImportedTheme {\n /** The names that were read. */\n format: CssFormat\n}\n\nconst RADII: ThemeField[] = ['radius', 'buttonRadius']\n\n/** shadcn/ui's names, as Tailwind 3 (`--primary`) and Tailwind 4 (`--color-primary`) write them. */\nconst SHADCN: [ThemeField, string[]][] = [\n ['background', ['--background', '--color-background']],\n ['surface', ['--card', '--color-card', '--popover', '--color-popover']],\n ['text', ['--foreground', '--color-foreground']],\n ['textMuted', ['--muted-foreground', '--color-muted-foreground']],\n ['border', ['--border', '--color-border']],\n ['inputBorder', ['--input', '--color-input']],\n ['primary', ['--primary', '--color-primary']],\n ['primaryText', ['--primary-foreground', '--color-primary-foreground']],\n ['accent', ['--ring', '--color-ring', '--primary', '--color-primary']],\n ['error', ['--destructive', '--color-destructive']],\n ['radius', ['--radius']],\n ['buttonRadius', ['--radius']],\n ['fontFamily', ['--font-sans', '--font-family']],\n]\n\n/** A colour as shadcn/ui writes it on Tailwind 3 — `222.2 84% 4.9%`, the inside of hsl() — or any other. */\nfunction shadcnColor(value: string): string | null {\n return /^[\\d.]+(?:deg)?\\s+[\\d.]+%\\s+[\\d.]+%(?:\\s*\\/\\s*[\\d.]+%?)?$/.test(value.trim()) ? toColor(`hsl(${value.trim()})`) : toColor(value)\n}\n\n/** Every custom property a stylesheet sets for the page, the last one winning. */\nfunction pageVariables(css: string | string[], mode: 'light' | 'dark', theme?: string): Map<string, string> {\n const vars = new Map<string, string>()\n for (const sheet of Array.isArray(css) ? css : [css]) {\n for (const d of declarations(sheet)) if (applies(d, { mode, theme })) vars.set(d.name, d.value)\n }\n return vars\n}\n\n/** The custom properties a stylesheet sets for the page, by name: what a person picks from to map their own. */\nexport function cssVariables(css: string | string[], options: Pick<CssThemeOptions, 'mode' | 'theme'> = {}): string[] {\n return [...pageVariables(css, options.mode ?? 'light', options.theme).keys()].sort()\n}\n\n/**\n * Reads an application's look out of its stylesheets, whatever names it uses:\n * Stackmyth's tokens, shadcn/ui's (`--primary`, `--radius`, on Tailwind 3 or\n * 4), or the application's own variables given in `map`. What comes out is a\n * theme of named values, never CSS.\n */\nexport function themeFromCss(css: string | string[], options: CssThemeOptions = {}): CssImportedTheme {\n const mode = options.mode ?? 'light'\n const vars = pageVariables(css, mode, options.theme)\n const names = [...vars.keys()]\n let format: CssFormat\n if (options.format && options.format !== 'auto') format = options.format\n else if (options.map && Object.keys(options.map).length > 0) format = 'custom'\n else if (names.some((n) => n.startsWith('--sm-'))) format = 'stackmyth'\n else if (names.some((n) => /^--(color-)?(primary|background|foreground)$/.test(n))) format = 'shadcn'\n else format = 'custom'\n\n if (format === 'stackmyth') return { ...themeFromStackmyth(css, { mode, theme: options.theme }), format }\n\n const spec: [ThemeField, string[]][] = format === 'shadcn'\n ? SHADCN\n : Object.entries(options.map ?? {}).filter(([, v]) => v).map(([k, v]) => [k as ThemeField, [String(v).startsWith('--') ? String(v) : `--${v}`]])\n const theme: CauthyTheme = {}\n const warnings: string[] = []\n for (const [field, tokens] of spec) {\n for (const token of tokens) {\n const raw = vars.get(token)\n if (raw === undefined) continue\n const value = resolve(raw, vars)\n const got = value === null ? null\n : RADII.includes(field) ? toRadius(value)\n : field === 'fontFamily' ? toFont(value)\n : format === 'shadcn' ? shadcnColor(value) : toColor(value)\n if (got !== null) {\n (theme as Record<string, unknown>)[field] = got\n break\n }\n warnings.push(`${token}: \"${raw.length > 60 ? raw.slice(0, 57) + '…' : raw}\" is not ${RADII.includes(field) ? 'a length' : field === 'fontFamily' ? 'a font list' : 'a colour'} Cauthy can take`)\n }\n }\n if (vars.size === 0) warnings.push('no custom properties were found in these stylesheets')\n else if (format === 'custom' && spec.length === 0) warnings.push('these stylesheets use names of their own: say which variable each value is read from')\n return { theme, warnings, format }\n}\n\n// ── On the application's own screens ───────────────────────────────────────\n\n/**\n * A theme as the CSS variables of `cauthy-auth/styles.css` (`--cauthy-*`), for\n * the forms an application shows on its own pages. The page's own background,\n * the layout and the words are Cauthy's pages' matter, and left out.\n */\nexport function themeVariables(theme: CauthyTheme): Record<string, string> {\n const vars: Record<string, string> = {}\n const put = (name: string, v: string | number | undefined) => {\n if (v === undefined || v === '') return\n vars[`--cauthy-${name}`] = typeof v === 'number' ? `${v}px` : v\n }\n put('surface', theme.surface)\n put('text', theme.text)\n put('text-muted', theme.textMuted)\n put('border', theme.border)\n put('input-background', theme.inputBackground)\n put('input-border', theme.inputBorder)\n put('primary', theme.primary)\n put('primary-text', theme.primaryText)\n put('accent', theme.accent)\n put('error', theme.error)\n put('error-background', theme.errorBackground)\n put('success', theme.success)\n put('success-background', theme.successBackground)\n put('radius', theme.radius)\n put('button-radius', theme.buttonRadius)\n put('font', theme.fontFamily)\n return vars\n}\n\n// ── Sending it to Cauthy ───────────────────────────────────────────────────\n\n/** A theme as Cauthy's API names its values. */\nexport function toWire(theme: CauthyTheme): Record<string, unknown> {\n const names: Record<keyof CauthyTheme, string> = {\n background: 'background', surface: 'surface', text: 'text', textMuted: 'text_muted', border: 'border',\n primary: 'primary', primaryText: 'primary_text', accent: 'accent', error: 'error', errorBackground: 'error_background',\n success: 'success', successBackground: 'success_background', radius: 'radius', buttonRadius: 'button_radius',\n fontFamily: 'font_family', logoUrl: 'logo_url', fonts: 'fonts', layout: 'layout', panelColors: 'panel_colors',\n panelText: 'panel_text', panelIconUrl: 'panel_icon_url', texts: 'texts', inputBackground: 'input_background', inputBorder: 'input_border', tokens: 'tokens',\n }\n const wire: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(theme)) {\n if (v === undefined || v === '' || (Array.isArray(v) && v.length === 0)) continue\n wire[names[k as keyof CauthyTheme]] = v\n }\n return wire\n}\n\n/** A theme as Cauthy answers it, in this package's names. */\nexport function fromWire(wire: Record<string, unknown>): CauthyTheme {\n const names: Record<string, keyof CauthyTheme> = {\n background: 'background', surface: 'surface', text: 'text', text_muted: 'textMuted', border: 'border',\n primary: 'primary', primary_text: 'primaryText', accent: 'accent', error: 'error', error_background: 'errorBackground',\n success: 'success', success_background: 'successBackground', radius: 'radius', button_radius: 'buttonRadius',\n font_family: 'fontFamily', logo_url: 'logoUrl', fonts: 'fonts', layout: 'layout', panel_colors: 'panelColors',\n panel_text: 'panelText', panel_icon_url: 'panelIconUrl', texts: 'texts', input_background: 'inputBackground', input_border: 'inputBorder', tokens: 'tokens',\n }\n const theme: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(wire ?? {})) if (names[k] && v !== undefined && v !== null && v !== '') theme[names[k]] = v\n return theme as CauthyTheme\n}\n\nexport interface PushThemeOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The application's client id. Default: `CAUTHY_CLIENT_ID`. */\n clientId?: string\n /** The workspace's slug. Default: `CAUTHY_TENANT`. */\n tenant?: string\n /**\n * A personal access token with `oauth_clients:manage`. Default:\n * `CAUTHY_TOKEN`. It belongs in the deploy pipeline, never in the application.\n */\n token?: string\n theme: CauthyTheme\n fetch?: typeof fetch\n}\n\n/**\n * Gives the application its look on Cauthy's pages. It replaces the theme: a\n * value left out goes back to Cauthy's own. Run it when the brand changes —\n * from a script or the deploy — not on every request.\n */\nexport async function pushTheme(o: PushThemeOptions): Promise<void> {\n const env = (n: string) => (typeof process !== 'undefined' ? process.env?.[n] : undefined)\n const issuer = (o.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n const clientId = o.clientId ?? env('CAUTHY_CLIENT_ID') ?? ''\n const tenant = o.tenant ?? env('CAUTHY_TENANT') ?? ''\n const token = o.token ?? env('CAUTHY_TOKEN') ?? ''\n for (const [name, v] of Object.entries({ CAUTHY_ISSUER: issuer, CAUTHY_CLIENT_ID: clientId, CAUTHY_TENANT: tenant, CAUTHY_TOKEN: token })) {\n if (v === '') throw new Error(`cauthy-auth: ${name} is required to push a theme`)\n }\n const res = await (o.fetch ?? fetch)(`${issuer}/v1/oauth/clients/${encodeURIComponent(clientId)}/theme`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${token}`, 'x-tenant-key': tenant, 'content-type': 'application/json' },\n body: JSON.stringify(toWire(o.theme)),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { errors?: { message?: string }[] } | null\n throw new Error(`cauthy-auth: Cauthy refused the theme (${res.status}): ${body?.errors?.[0]?.message ?? res.statusText}`)\n }\n}\n","// What a sign-in or sign-up form is checked for before anything is sent, in\n// the browser and again on the server: the same rules in both places, so the\n// form says what the server would.\n\nexport type AuthField = 'email' | 'password' | 'newPassword' | 'name' | 'code'\n\n/** A value of a form that cannot be sent as it is. */\nexport interface FieldProblem {\n field: AuthField\n /** Stable, for translating: `required`, `invalid_email`, `too_short`, `too_long`. */\n code: 'required' | 'invalid_email' | 'too_short' | 'too_long'\n message: string\n}\n\n/** The shortest password Cauthy takes for a new account. */\nexport const MIN_PASSWORD = 8\nconst MAX_PASSWORD = 256\nconst MAX_NAME = 120\n\n// One @, something on each side, a dot in the domain, no spaces: what catches\n// a typo. Whether the address exists is Cauthy's to find out.\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nexport function checkEmail(value: unknown): FieldProblem | null {\n const v = typeof value === 'string' ? value.trim() : ''\n if (v === '') return { field: 'email', code: 'required', message: 'Enter your email address.' }\n if (v.length > 254 || !EMAIL.test(v)) return { field: 'email', code: 'invalid_email', message: 'That does not look like an email address.' }\n return null\n}\n\n/** A password being typed to sign in: only that there is one. */\nexport function checkPassword(value: unknown): FieldProblem | null {\n if (typeof value !== 'string' || value === '') return { field: 'password', code: 'required', message: 'Enter your password.' }\n if (value.length > MAX_PASSWORD) return { field: 'password', code: 'too_long', message: 'That password is too long.' }\n return null\n}\n\n/** A password being chosen for a new account. */\nexport function checkNewPassword(value: unknown): FieldProblem | null {\n const basic = checkPassword(value)\n if (basic) return basic\n if ((value as string).length < MIN_PASSWORD) {\n return { field: 'password', code: 'too_short', message: `Use at least ${MIN_PASSWORD} characters.` }\n }\n return null\n}\n\nexport function checkName(value: unknown): FieldProblem | null {\n if (value === undefined || value === null || value === '') return null\n if (typeof value !== 'string' || value.trim().length > MAX_NAME) return { field: 'name', code: 'too_long', message: `Use at most ${MAX_NAME} characters.` }\n return null\n}\n\nexport function checkCode(value: unknown): FieldProblem | null {\n const v = typeof value === 'string' ? value.trim() : ''\n if (v === '') return { field: 'code', code: 'required', message: 'Enter the code.' }\n if (v.length > 40) return { field: 'code', code: 'too_long', message: 'That is not a code.' }\n return null\n}\n\n/** The first problem of a form, or null when it can be sent. */\nexport function firstProblem(...checks: (FieldProblem | null)[]): FieldProblem | null {\n return checks.find((c) => c !== null) ?? null\n}\n","// Who is signed in, kept for the browser: the same thing <CauthyProvider>\n// keeps for React, with no framework in it. `cauthy-auth/vue` and\n// `cauthy-auth/svelte` are this store in each one's own terms, and anything\n// else (Solid, Angular, a page with no framework) can use it as it is.\n//\n// const store = createSessionStore()\n// const stop = store.subscribe(({ session, status }) => render(session))\n// await store.auth.signIn.email({ email, password }) // subscribers hear the new session\n//\n// While somebody listens it asks the server who is signed in, asks again\n// shortly before the session's token runs out, and when the tab is looked at\n// again. With nobody listening it does nothing.\n\nimport { createAuthClient, type AuthClient, type AuthClientOptions } from './client'\nimport type { PublicSession } from './types'\n\nexport interface SessionState {\n /** The signed-in person and their organizations, or null. */\n session: PublicSession | null\n status: 'loading' | 'authenticated' | 'unauthenticated'\n}\n\nexport interface SessionStoreOptions extends AuthClientOptions {\n /**\n * The session the server already read while rendering (SSR): the first\n * paint is then right, with no \"loading\". `null` means \"nobody\"; leave it\n * out when the server did not look.\n */\n initialSession?: PublicSession | null\n}\n\nexport interface SessionStore {\n /** What is known now. */\n get(): SessionState\n /** Calls `listener` now and on every change. Answers how to stop. */\n subscribe(listener: (state: SessionState) => void): () => void\n /** Asks the server again who is signed in. */\n refresh(): Promise<PublicSession | null>\n /** Sends the browser to Cauthy's page to sign in, and back to `returnTo` (default: where it is now). */\n signIn(options?: { returnTo?: string; locale?: string; prompt?: 'login' }): void\n /** Signs out of this application and of Cauthy in this browser. */\n signOut(): void\n /** Where the person looks after their account on Cauthy's page. */\n accountUrl(returnTo?: string): string\n /**\n * The functions of an application's own screens. They are\n * `createAuthClient()`'s, and what changes who is signed in is heard by the\n * subscribers with no reload.\n */\n auth: AuthClient\n /** Where the server mounted the routes. */\n basePath: string\n}\n\n/** Ask again this long before the session's token runs out. */\nconst AHEAD_MS = 60_000\n\nexport function createSessionStore(options: SessionStoreOptions = {}): SessionStore {\n const base = (options.basePath ?? '/api/auth').replace(/\\/+$/, '')\n const doFetch: typeof fetch = (...args) => (options.fetch ?? fetch)(...args)\n const first = options.initialSession\n let state: SessionState = { session: first ?? null, status: first === undefined ? 'loading' : first === null ? 'unauthenticated' : 'authenticated' }\n const listeners = new Set<(state: SessionState) => void>()\n let asking: Promise<PublicSession | null> | null = null\n let timer: ReturnType<typeof setTimeout> | undefined\n let asked = first !== undefined\n\n const set = (next: SessionState) => {\n if (next.session === state.session && next.status === state.status) return\n state = next\n schedule()\n for (const l of [...listeners]) l(state)\n }\n\n function schedule(): void {\n clearTimeout(timer)\n timer = undefined\n if (listeners.size === 0 || state.session === null) return\n const wait = Math.max(new Date(state.session.expiresAt).getTime() - Date.now() - AHEAD_MS, 5_000)\n timer = setTimeout(() => void refresh(), wait)\n }\n\n function refresh(): Promise<PublicSession | null> {\n asked = true\n asking ??= (async () => {\n try {\n const res = await doFetch(`${base}/session`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n if (!res.ok) throw new Error(String(res.status))\n const body = (await res.json()) as { session: PublicSession | null; status: string }\n // \"expired\" is the server unable to reach Cauthy: what is on screen\n // stays, and the next ask settles it.\n if (body.status !== 'expired') set({ session: body.session, status: body.session ? 'authenticated' : 'unauthenticated' })\n return body.session\n } catch {\n if (state.status === 'loading') set({ session: null, status: 'unauthenticated' })\n return null\n } finally {\n asking = null\n }\n })()\n return asking\n }\n\n const onVisible = () => {\n if (document.visibilityState === 'visible') void refresh()\n }\n const inBrowser = () => typeof document !== 'undefined'\n\n const client = createAuthClient({ basePath: base, fetch: options.fetch })\n const then = async <T,>(running: Promise<T>): Promise<T> => {\n const r = await running\n await refresh()\n return r\n }\n\n return {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener)\n if (listeners.size === 1 && inBrowser()) {\n document.addEventListener('visibilitychange', onVisible)\n schedule()\n if (!asked) void refresh()\n }\n listener(state)\n return () => {\n listeners.delete(listener)\n if (listeners.size === 0) {\n clearTimeout(timer)\n timer = undefined\n if (inBrowser()) document.removeEventListener('visibilitychange', onVisible)\n }\n }\n },\n refresh,\n signIn(o = {}) {\n const q = new URLSearchParams({ return_to: o.returnTo ?? window.location.pathname + window.location.search })\n if (o.locale) q.set('locale', o.locale)\n if (o.prompt) q.set('prompt', o.prompt)\n window.location.assign(`${base}/login?${q}`)\n },\n signOut() {\n window.location.assign(`${base}/logout`)\n },\n accountUrl(returnTo) {\n const back = returnTo ?? (typeof window === 'undefined' ? '/' : window.location.pathname + window.location.search)\n return `${base}/account?return_to=${encodeURIComponent(back)}`\n },\n auth: {\n ...client,\n signIn: {\n ...client.signIn,\n email: (f) => then(client.signIn.email(f)),\n mfa: (f) => then(client.signIn.mfa(f)),\n magicLinkVerify: (f) => then(client.signIn.magicLinkVerify(f)),\n emailCode: (f) => then(client.signIn.emailCode(f)),\n },\n signUp: { email: (f) => then(client.signUp.email(f)) },\n signOut: () => then(client.signOut()),\n account: {\n ...client.account,\n update: (f) => then(client.account.update(f)),\n changePassword: (f) => then(client.account.changePassword(f)),\n signOutEverywhere: () => then(client.account.signOutEverywhere()),\n },\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AAA,IAC5D;AAAA,IACA,MAAM,aAAa;AACjB,UAAI;AACF,cAAM,MAAM,MAAM,QAAQ,GAAG,IAAI,YAAY,EAAE,aAAa,eAAe,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC;AACpH,YAAI,CAAC,IAAI,GAAI,QAAO;AACpB,gBAAS,MAAM,IAAI,KAAK,GAAyC;AAAA,MACnE,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,OAAO;AACL,iBAAW,KAAK,OAAO,EAAE,KAAK,CAAC,SAAU,QAAQ,OAAO,SAAS,WAAW,SAAS,IAAI,IAAI,IAAK;AAClG,aAAO;AAAA,IACT;AAAA,IACA,MAAM,UAAU;AACd,UAAI;AACF,cAAM,MAAM,MAAM,QAAQ,GAAG,IAAI,YAAY,EAAE,aAAa,eAAe,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC;AACpH,YAAI,IAAI,GAAI,QAAQ,MAAM,IAAI,KAAK;AAAA,MACrC,QAAQ;AAAA,MAER;AACA,aAAO,EAAE,WAAW,CAAC,GAAG,QAAQ,MAAM,WAAW,OAAO,SAAS,MAAM;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/client.ts","../src/theme.ts","../src/validate.ts","../src/store.ts"],"sourcesContent":["// The application's own sign-in screens, in the browser.\n//\n// const auth = createAuthClient()\n// const r = await auth.signIn.email({ email, password })\n// if (!r.ok) show(r.error.message) // r.error.field says which input\n// else if (r.status === 'mfa_required') askForTheCode()\n//\n// Every call goes to the application's own server (`/api/auth/*`), never to\n// Cauthy: the browser holds no token, before or after. A form is checked here\n// before it is sent, with the rules the server checks again.\n\nimport { fromWire, type CauthyTheme } from './theme'\nimport type { PublicSession } from './types'\nimport { checkCode, checkEmail, checkName, checkNewPassword, checkPassword, firstProblem, type AuthField, type FieldProblem } from './validate'\n\nexport { checkCode, checkEmail, checkName, checkNewPassword, checkPassword, MIN_PASSWORD, type AuthField, type FieldProblem } from './validate'\n\n/** What went wrong, in a form the screen can show. */\nexport interface AuthError {\n /** Stable, for translating: `invalid_credentials`, `invalid_email`, `too_short`, `email_taken`, `unavailable`… */\n code: string\n message: string\n /** The input it is about, when it is about one. */\n field?: AuthField\n}\n\nexport type AuthResult<S extends string, More = unknown> = ({ ok: true; status: S } & More) | { ok: false; error: AuthError }\n\n/** What the screen may offer. */\nexport interface AuthMethods {\n /** The providers the workspace signs people in with: `{ id: 'google', name: 'Google' }`. */\n providers: { id: string; name: string }[]\n /** Whether people may create an account themselves. */\n signUp: boolean\n magicLink: boolean\n /** Whether to offer a passkey. It is asked for on Cauthy's page: the person goes there for that step and comes back signed in. */\n passkey: boolean\n}\n\n/** A person's own account, as their account screen shows it. */\nexport interface Account {\n id: string\n email: string\n name: string\n emailVerified: boolean\n /** False for an account that only signs in through a provider: it has no current password to ask for. */\n hasPassword: boolean\n mfaEnabled: boolean\n}\n\n/** Somewhere the person is signed in. Moments are UTC. */\nexport interface AccountSession {\n /** \"Mac · Chrome\", or \"\" when the browser did not say. */\n device: string\n ip: string\n createdAt: string\n expiresAt: string\n}\n\n/**\n * The signed-in person's own account. What weakens it — the password, the\n * second step, its recovery codes — asks for the current password again.\n */\n/** A provider the account can also sign in with. */\nexport interface LinkedIdentity {\n provider: string\n /** The address the provider has for the person, when it said. */\n email: string\n name: string\n /** When it was linked, in UTC (ISO 8601). */\n linkedAt: string\n}\n\nexport interface AccountClient {\n /** The account, or null when nobody is signed in. */\n get(): Promise<Account | null>\n update(form: { name: string }): Promise<AuthResult<'saved', { account: Account }>>\n /** Ends every other session of the account; this one stays signed in. */\n changePassword(form: { password: string; newPassword: string }): Promise<AuthResult<'changed', { signedIn: boolean }>>\n mfa: {\n /** Starts turning the second step on: show `secret` (or `otpauthUri` as a QR code) to add to an authenticator app, then call `verify`. */\n setup(form: { password: string }): Promise<AuthResult<'started', { secret: string; otpauthUri: string }>>\n /** Turns it on with a code from the app. `recoveryCodes` are shown this once. */\n verify(form: { code: string }): Promise<AuthResult<'enabled', { recoveryCodes: string[] }>>\n disable(form: { password: string }): Promise<AuthResult<'disabled'>>\n /** New recovery codes; the earlier ones stop working. */\n recoveryCodes(form: { password: string }): Promise<AuthResult<'renewed', { recoveryCodes: string[] }>>\n }\n /**\n * Asks to sign in with another address. Nothing changes yet: the new address\n * is mailed a link to confirm it, and once it is confirmed the old one is\n * told, with a link that undoes it. Both open Cauthy's own page.\n */\n changeEmail(form: { email: string; password: string }): Promise<AuthResult<'sent', { email: string }>>\n /** The providers (Google…) the account can also sign in with. */\n identities(): Promise<LinkedIdentity[]>\n /**\n * Sends the browser to the provider, to link it to the account; it comes back\n * at `returnTo` with `?linked=<provider>`, or `?auth_error=<code>`.\n */\n link(provider: string, options?: { returnTo?: string }): void\n /** Where `link` sends the browser, for a plain link. */\n linkUrl(provider: string, options?: { returnTo?: string }): string\n /** The account stops signing in with that provider. Refused when it would be left with no way to sign in. */\n unlink(provider: string): Promise<AuthResult<'unlinked', { provider: string }>>\n /** Where the account is signed in. */\n sessions(): Promise<AccountSession[]>\n /** Signs the account out everywhere, here too. */\n signOutEverywhere(): Promise<AuthResult<'signed_out'>>\n}\n\nexport interface AuthClient {\n signIn: {\n /** With address and password. `mfa_required`: ask for the code and call `signIn.mfa`. */\n email(form: { email: string; password: string }): Promise<AuthResult<'signed_in', { session: PublicSession }> | AuthResult<'mfa_required'>>\n /** The second step: the code of the authenticator app, or a recovery code. */\n mfa(form: { code: string }): Promise<AuthResult<'signed_in', { session: PublicSession }>>\n /** Mails a link that signs the person in. The answer is the same whether or not the address has an account. */\n magicLink(form: { email: string }): Promise<AuthResult<'sent'>>\n /** Signs in with the token the mailed link opened the page with (`ml_token`). */\n magicLinkVerify(form: { token: string }): Promise<AuthResult<'signed_in', { session: PublicSession }>>\n /** Signs in with the code that came in the same mail as the link, for somebody reading it on another device. */\n emailCode(form: { code: string }): Promise<AuthResult<'signed_in', { session: PublicSession }>>\n /** Sends the browser to Cauthy's page to use a passkey; it comes back signed in, at `returnTo`. */\n passkey(options?: { returnTo?: string; locale?: string }): void\n /** Where `passkey` sends the browser, for a plain link. */\n passkeyUrl(options?: { returnTo?: string; locale?: string }): string\n /** Sends the browser to the provider; it comes back signed in, at `returnTo`. */\n social(provider: string, options?: { returnTo?: string }): void\n /** Where `social` sends the browser, for a plain link. */\n socialUrl(provider: string, options?: { returnTo?: string }): string\n }\n signUp: {\n /** `verification_required`: the account exists and must open the link Cauthy mailed before it can sign in. */\n email(form: { email: string; password: string; name?: string }): Promise<AuthResult<'signed_in', { session: PublicSession }> | AuthResult<'verification_required', { email: string }>>\n }\n /** Mails a link to choose a new password. The answer is the same whether or not the address has an account. */\n forgotPassword(form: { email: string }): Promise<AuthResult<'sent'>>\n /** Sets the new password, with the token the mailed link opened the page with (`token`). */\n resetPassword(form: { token: string; password: string }): Promise<AuthResult<'changed'>>\n /** Confirms the address, with the token the mailed link opened the page with (`token`). */\n verifyEmail(form: { token: string }): Promise<AuthResult<'verified'>>\n signOut(): Promise<AuthResult<'signed_out'>>\n /** The signed-in person's own account. */\n account: AccountClient\n /** Who is signed in, or null. */\n getSession(): Promise<PublicSession | null>\n methods(): Promise<AuthMethods>\n /**\n * How the workspace's forms look — colours, corners, typeface — as a person\n * set it in Cauthy's dashboard. Read once per page; null when Cauthy cannot say.\n */\n look(): Promise<CauthyTheme | null>\n}\n\nexport interface AuthClientOptions {\n /** Where the server mounted the routes. Default: `/api/auth`. */\n basePath?: string\n fetch?: typeof fetch\n}\n\nconst UNAVAILABLE: AuthError = { code: 'unavailable', message: 'Sign-in is unavailable right now. Try again in a moment.' }\n\nexport function createAuthClient(options: AuthClientOptions = {}): AuthClient {\n const base = (options.basePath ?? '/api/auth').replace(/\\/+$/, '')\n const doFetch: typeof fetch = (...args) => (options.fetch ?? fetch)(...args)\n\n async function post(path: string, form: Record<string, unknown>, bad: FieldProblem | null): Promise<any> {\n if (bad) return { ok: false, error: { code: bad.code, message: bad.message, field: bad.field } }\n try {\n const res = await doFetch(`${base}${path}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify(form),\n })\n const body = (await res.json().catch(() => null)) as any\n if (res.ok && body && typeof body.status === 'string') return { ok: true, ...body }\n const e = body?.error\n return { ok: false, error: e && typeof e.code === 'string' ? { code: e.code, message: String(e.message ?? ''), ...(e.field ? { field: e.field } : {}) } : UNAVAILABLE }\n } catch {\n return { ok: false, error: UNAVAILABLE }\n }\n }\n\n let looked: Promise<CauthyTheme | null> | undefined\n\n async function read(path: string): Promise<any> {\n try {\n const res = await doFetch(`${base}${path}`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n return res.ok ? await res.json() : null\n } catch {\n return null\n }\n }\n\n const linkUrl = (provider: string, o: { returnTo?: string } = {}) =>\n `${base}/me/identities/link/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ''}`\n const socialUrl = (provider: string, o: { returnTo?: string } = {}) =>\n `${base}/sign-in/social/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ''}`\n\n const passkeyUrl = (o: { returnTo?: string; locale?: string } = {}) => {\n const q = new URLSearchParams({ method: 'passkey' })\n if (o.returnTo) q.set('return_to', o.returnTo)\n if (o.locale) q.set('locale', o.locale)\n return `${base}/login?${q}`\n }\n\n return {\n signIn: {\n email: (f) => post('/sign-in/email', { email: f.email, password: f.password }, firstProblem(checkEmail(f.email), checkPassword(f.password))),\n mfa: (f) => post('/sign-in/mfa', { code: f.code }, checkCode(f.code)),\n magicLink: (f) => post('/sign-in/magic-link', { email: f.email }, checkEmail(f.email)),\n magicLinkVerify: (f) => post('/sign-in/magic-link/verify', { token: f.token }, null),\n emailCode: (f) => post('/sign-in/email-code', { code: f.code }, checkCode(f.code)),\n passkeyUrl,\n passkey(o) {\n window.location.assign(passkeyUrl(o))\n },\n socialUrl,\n social(provider, o) {\n window.location.assign(socialUrl(provider, o))\n },\n },\n signUp: {\n email: (f) => post('/sign-up/email', { email: f.email, password: f.password, name: f.name }, firstProblem(checkName(f.name), checkEmail(f.email), checkNewPassword(f.password))),\n },\n forgotPassword: (f) => post('/forgot-password', { email: f.email }, checkEmail(f.email)),\n resetPassword: (f) => post('/reset-password', { token: f.token, password: f.password }, checkNewPassword(f.password)),\n verifyEmail: (f) => post('/verify-email', { token: f.token }, null),\n signOut: () => post('/sign-out', {}, null),\n account: {\n async get() {\n const body = await read('/me')\n return body && typeof body.account === 'object' ? (body.account as Account) : null\n },\n update: (f) => post('/me', { name: f.name }, checkName(f.name)),\n changePassword: (f) => {\n const bad = checkNewPassword(f.newPassword)\n return post('/me/password', { password: f.password, newPassword: f.newPassword }, bad ? { ...bad, field: 'newPassword' } : null)\n },\n mfa: {\n setup: (f) => post('/me/mfa/setup', { password: f.password }, null),\n verify: (f) => post('/me/mfa/verify', { code: f.code }, checkCode(f.code)),\n disable: (f) => post('/me/mfa/disable', { password: f.password }, null),\n recoveryCodes: (f) => post('/me/mfa/recovery-codes', { password: f.password }, null),\n },\n changeEmail: (f) => post('/me/email', { email: f.email, password: f.password }, checkEmail(f.email)),\n async identities() {\n const body = await read('/me/identities')\n return body && Array.isArray(body.identities) ? (body.identities as LinkedIdentity[]) : []\n },\n linkUrl,\n link(provider, o) {\n window.location.assign(linkUrl(provider, o))\n },\n unlink: (provider) => post('/me/identities/unlink', { provider }, null),\n async sessions() {\n const body = await read('/me/sessions')\n return body && Array.isArray(body.sessions) ? (body.sessions as AccountSession[]) : []\n },\n signOutEverywhere: () => post('/me/sessions/end', {}, null),\n },\n async getSession() {\n try {\n const res = await doFetch(`${base}/session`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n if (!res.ok) return null\n return ((await res.json()) as { session: PublicSession | null }).session\n } catch {\n return null\n }\n },\n look() {\n looked ??= read('/look').then((wire) => (wire && typeof wire === 'object' ? fromWire(wire) : null))\n return looked\n },\n async methods() {\n try {\n const res = await doFetch(`${base}/methods`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n if (res.ok) return (await res.json()) as AuthMethods\n } catch {\n // falls through\n }\n return { providers: [], signUp: true, magicLink: false, passkey: false }\n },\n }\n}\n\nexport { createSessionStore, type SessionState, type SessionStore, type SessionStoreOptions } from './store'\n","// An application's look, for Cauthy's hosted pages.\n//\n// Cauthy's pages — sign-in, sign-up, the account page — can take the colours,\n// corners, typeface and logo of the application that sends its people there,\n// so signing in reads as a page of the application. A theme is a short list of\n// values, which Cauthy checks one by one; it is never CSS.\n//\n// An application built with Stackmyth already has those values, as its\n// `--sm-*` tokens. `themeFromStackmyth` reads them out of its stylesheets.\n\n/** How an application looks on Cauthy's hosted pages. Every value is optional. */\n/** One font file the application serves: a family in one weight (or a range) and one style. */\nexport interface ThemeFont {\n family: string\n /** An https address of a `.woff2` file. It must answer with `Access-Control-Allow-Origin` for Cauthy's origin. */\n url: string\n /** `400`, or `\"100 900\"` for a variable font. Default: 400. */\n weight?: number | string\n style?: 'normal' | 'italic'\n}\n\n/** What an application says on its sign-in page, in one language. */\nexport interface ThemeTexts {\n /** Replaces \"Sign in\". */\n heading?: string\n /** Replaces \"to continue to …\". */\n subheading?: string\n /** The messages of the split layout's panel, shown one at a time (up to 5). */\n panel?: string[]\n /** Links at the foot of the split layout: privacy, terms (up to 4). */\n links?: { label: string; url: string }[]\n}\n\nexport interface CauthyTheme {\n /** The page. Colours are `#rrggbb` or `rgba(r, g, b, a)`. */\n background?: string\n /** The card, and inputs. */\n surface?: string\n /** Headings and what is typed. */\n text?: string\n /** Paragraphs, labels, small print. */\n textMuted?: string\n border?: string\n /** The fields and the secondary buttons, when they are not the card's colours. */\n inputBackground?: string\n inputBorder?: string\n /** The main button, and what is written on it. */\n primary?: string\n primaryText?: string\n /** Links, and the focus ring. */\n accent?: string\n error?: string\n errorBackground?: string\n success?: string\n successBackground?: string\n /** Corners of cards and inputs, in pixels (0–40). */\n radius?: number\n /** Corners of buttons, in pixels (0–40). */\n buttonRadius?: number\n /** A CSS font-family list: the application's typeface first, a system font after it. */\n fontFamily?: string\n /** The files of the typefaces `fontFamily` names, for people who do not have them installed. */\n fonts?: ThemeFont[]\n /** An image shown where \"Cauthy\" is, over https. */\n logoUrl?: string\n /**\n * How the sign-in pages are laid out: `card` (the default, one card in the\n * middle) or `split` (the form on one side, a panel that presents the\n * application on the other).\n */\n layout?: 'card' | 'split'\n /** The colours the split layout's backdrop blends, one to four. */\n panelColors?: string[]\n /** The colour of what is written on the panel. */\n panelText?: string\n /** An https image shown over the panel's messages. */\n panelIconUrl?: string\n /** The application's own words on the sign-in page, by language (`en`, `es`). */\n texts?: Record<string, ThemeTexts>\n /**\n * The application's Stackmyth tokens (`--sm-*`), from `tokensFromStackmyth`.\n * Cauthy's pages are drawn with Stackmyth's components, so these make its\n * buttons and fields the application's own. They are laid over the named values.\n */\n tokens?: Record<string, string>\n}\n\nexport interface StackmythThemeOptions {\n /**\n * The named theme to read, when the stylesheet keeps several under\n * `[data-theme=…]` (`\"vennet\"`). Without it only what applies to every\n * page (`:root`) is read.\n */\n theme?: string\n /** Which of the application's two modes to take. Default: `light`. */\n mode?: 'light' | 'dark'\n logoUrl?: string\n}\n\nexport interface ImportedTheme {\n theme: CauthyTheme\n /** Tokens that were there and could not be carried over, and why. */\n warnings: string[]\n}\n\nconst MAX_RADIUS = 40\n\n// ── Reading custom properties out of CSS ───────────────────────────────────\n\ninterface Declaration {\n name: string\n value: string\n /** The selectors and at-rules it sits inside, outermost first. */\n within: string[]\n}\n\nfunction declarations(css: string): Declaration[] {\n const text = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n const out: Declaration[] = []\n const within: string[] = []\n let chunk = ''\n let quote = ''\n let depth = 0 // parentheses, so a `;` inside url(…) does not end anything\n const flush = () => {\n const m = /^\\s*(--[\\w-]+)\\s*:\\s*([\\s\\S]+?)\\s*$/.exec(chunk)\n if (m) out.push({ name: m[1], value: m[2].replace(/\\s+/g, ' ').replace(/\\s*!important$/, ''), within: [...within] })\n chunk = ''\n }\n for (const ch of text) {\n if (quote) {\n chunk += ch\n if (ch === quote) quote = ''\n continue\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch\n chunk += ch\n } else if (ch === '(') {\n depth++\n chunk += ch\n } else if (ch === ')') {\n depth = Math.max(0, depth - 1)\n chunk += ch\n } else if (ch === '{' && depth === 0) {\n within.push(chunk.trim().replace(/\\s+/g, ' '))\n chunk = ''\n } else if (ch === '}' && depth === 0) {\n flush()\n within.pop()\n } else if (ch === ';' && depth === 0) {\n flush()\n } else {\n chunk += ch\n }\n }\n return out\n}\n\nconst DARK = /prefers-color-scheme:\\s*dark|data-(mode|theme|color-scheme)=[\"']?dark|\\.dark\\b/i\nconst LIGHT = /prefers-color-scheme:\\s*light|data-(mode|theme|color-scheme)=[\"']?light|\\.light\\b/i\nconst NAMED = /data-theme=[\"']?([\\w-]+)/i\n\n/** Whether a declaration applies to the page being themed. */\nfunction applies(d: Declaration, o: Required<Pick<StackmythThemeOptions, 'mode'>> & { theme?: string }): boolean {\n for (const scope of d.within) {\n if (o.mode === 'light' && DARK.test(scope)) return false\n if (o.mode === 'dark' && LIGHT.test(scope)) return false\n const named = NAMED.exec(scope)\n if (named && !/^(dark|light)$/i.test(named[1]) && named[1] !== o.theme) return false\n // Component-level rules (`.btn { --sm-… }`) are not the page's theme;\n // the class a mode is switched with (`.dark`, as shadcn/ui does) is.\n if (!scope.startsWith('@') && !/:root|^html\\b|^body\\b|\\[data-|^\\*$|:host|^\\.(dark|light)\\b/.test(scope)) return false\n }\n return true\n}\n\n// ── Tokens ─────────────────────────────────────────────────────────────────\n\n/** What a token's value may be written with, as Cauthy checks it. */\nconst TOKEN_CHARS = /^[A-Za-z0-9 #%.,()/'\"_+*-]+$/\nconst TOKEN_FUNCS = new Set(['var', 'calc', 'min', 'max', 'clamp', 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color',\n 'color-mix', 'light-dark', 'cubic-bezier', 'steps', 'linear', 'linear-gradient', 'radial-gradient', 'conic-gradient',\n 'repeating-linear-gradient', 'repeating-radial-gradient', 'drop-shadow', 'blur', 'translate', 'translatex', 'translatey', 'scale', 'rotate'])\n\nfunction tokenValue(value: string): string | null {\n const v = value.replace(/\\s+/g, ' ').trim()\n if (v === '' || v.length > 400 || !TOKEN_CHARS.test(v)) return null\n for (const m of v.matchAll(/([A-Za-z-]+)\\(/g)) if (!TOKEN_FUNCS.has(m[1].toLowerCase())) return null\n if (/^\\(|[ ,(]\\(/.test(v)) return null\n return v\n}\n\n/** A scope that is the page's theme itself: the root, or the theme and mode attributes — never a component inside it. */\nconst THEME_SCOPE = /^(?:\\s*(?::root|html|body|\\[data-(?:theme|mode|color-scheme)(?:=[\"']?[\\w-]+[\"']?)?\\])\\s*,?)+$/i\n\nexport interface StackmythTokens {\n /** Every `--sm-*` token the stylesheets set for the page, ready for `theme.tokens`. */\n tokens: Record<string, string>\n /** Tokens that were there and Cauthy would not take, and why. */\n warnings: string[]\n}\n\n/**\n * Reads an application's Stackmyth tokens out of its stylesheets: every\n * `--sm-*` custom property its theme sets, in the order the sheets are given\n * (a later one wins). Its own names — a brand palette the tokens point at —\n * are written in, so what comes out stands on Stackmyth's names alone.\n *\n * Cauthy's sign-in pages are drawn with Stackmyth's components: these tokens\n * are what makes them look like the application.\n */\nexport function tokensFromStackmyth(css: string | string[], options: StackmythThemeOptions = {}): StackmythTokens {\n const mode = options.mode ?? 'light'\n const all = (Array.isArray(css) ? css : [css]).flatMap(declarations)\n const named = options.theme ?? all.map((d) => d.within.map((w) => NAMED.exec(w)?.[1]).find((n) => n && !/^(dark|light)$/i.test(n))).find(Boolean)\n const vars = new Map<string, string>()\n for (const d of all) {\n if (!applies(d, { mode, theme: named })) continue\n if (!d.within.every((w) => w.startsWith('@') || THEME_SCOPE.test(w))) continue\n vars.set(d.name, d.value)\n }\n // The application's own names are written in; Stackmyth's are left as references.\n const inline = (value: string, depth = 0): string | null => {\n if (depth > 16) return null\n let failed = false\n let out = value\n for (let guard = 0; guard < 64; guard++) {\n const next = out.replace(/var\\(\\s*(--(?!sm-)[\\w-]+)\\s*(?:,\\s*([^()]*(?:\\([^()]*\\)[^()]*)*))?\\)/, (_m, name: string, fallback?: string) => {\n const known = vars.get(name)\n const got = known !== undefined ? inline(known, depth + 1) : fallback !== undefined ? inline(fallback.trim(), depth + 1) : null\n if (got === null) failed = true\n return got ?? ''\n })\n if (failed) return null\n if (next === out) break\n out = next\n }\n return out\n }\n const tokens: Record<string, string> = {}\n const warnings: string[] = []\n for (const [name, raw] of vars) {\n if (!/^--sm-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) continue\n const written = inline(raw)\n const value = written === null ? null : tokenValue(written)\n if (value === null) warnings.push(`${name}: \"${raw.length > 60 ? raw.slice(0, 57) + '…' : raw}\" is not a value Cauthy takes`)\n else tokens[name] = value\n }\n if (Object.keys(tokens).length === 0) warnings.push('no --sm-* token was found in these stylesheets')\n return { tokens, warnings }\n}\n\n// ── Values ─────────────────────────────────────────────────────────────────\n\nfunction resolve(value: string, vars: Map<string, string>, seen = 0): string | null {\n if (seen > 16) return null\n let unresolved = false\n // Innermost var() first: fallbacks may hold another var().\n let out = value\n for (let guard = 0; guard < 32 && /var\\(/.test(out); guard++) {\n out = out.replace(/var\\(\\s*(--[\\w-]+)\\s*(?:,\\s*([^()]*(?:\\([^()]*\\)[^()]*)*))?\\)/, (_m, name: string, fallback?: string) => {\n const known = vars.get(name)\n const next = known !== undefined ? resolve(known, vars, seen + 1) : fallback !== undefined ? resolve(fallback.trim(), vars, seen + 1) : null\n if (next === null) unresolved = true\n return next ?? ''\n })\n if (unresolved) return null\n }\n return /var\\(/.test(out) ? null : out.trim()\n}\n\nconst clamp01 = (n: number) => Math.min(1, Math.max(0, n))\nconst hex2 = (n: number) => Math.round(clamp01(n) * 255).toString(16).padStart(2, '0')\nconst gamma = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055)\n\nfunction out(r: number, g: number, b: number, a = 1): string {\n if (a >= 1) return `#${hex2(r)}${hex2(g)}${hex2(b)}`\n return `rgba(${Math.round(clamp01(r) * 255)}, ${Math.round(clamp01(g) * 255)}, ${Math.round(clamp01(b) * 255)}, ${Math.round(clamp01(a) * 1000) / 1000})`\n}\n\nconst alpha = (s: string | undefined) => (s === undefined ? 1 : s.endsWith('%') ? parseFloat(s) / 100 : parseFloat(s))\n\nconst KEYWORDS: Record<string, string> = { white: '#ffffff', black: '#000000' }\n\n/** A colour as Cauthy takes it — `#rrggbb` or `rgba(…)` — or null when it is none it can read. */\nexport function toColor(value: string): string | null {\n const v = value.trim().toLowerCase()\n if (KEYWORDS[v]) return KEYWORDS[v]\n if (/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(v)) return v\n let m = /^rgba?\\(\\s*([\\d.]+%?)[\\s,]+([\\d.]+%?)[\\s,]+([\\d.]+%?)(?:\\s*[,/]\\s*([\\d.]+%?))?\\s*\\)$/.exec(v)\n if (m) {\n const ch = (s: string) => (s.endsWith('%') ? parseFloat(s) / 100 : parseFloat(s) / 255)\n return out(ch(m[1]), ch(m[2]), ch(m[3]), alpha(m[4]))\n }\n m = /^hsla?\\(\\s*([\\d.]+)(?:deg)?[\\s,]+([\\d.]+)%[\\s,]+([\\d.]+)%(?:\\s*[,/]\\s*([\\d.]+%?))?\\s*\\)$/.exec(v)\n if (m) {\n const h = ((parseFloat(m[1]) % 360) + 360) % 360\n const s = parseFloat(m[2]) / 100\n const l = parseFloat(m[3]) / 100\n const f = (n: number) => {\n const k = (n + h / 30) % 12\n return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1))\n }\n return out(f(0), f(8), f(4), alpha(m[4]))\n }\n m = /^oklch\\(\\s*([\\d.]+%?)\\s+([\\d.]+%?)\\s+([\\d.]+)(?:deg)?(?:\\s*\\/\\s*([\\d.]+%?))?\\s*\\)$/.exec(v)\n if (m) {\n const L = m[1].endsWith('%') ? parseFloat(m[1]) / 100 : parseFloat(m[1])\n const C = m[2].endsWith('%') ? (parseFloat(m[2]) / 100) * 0.4 : parseFloat(m[2])\n const H = (parseFloat(m[3]) * Math.PI) / 180\n const a = C * Math.cos(H)\n const b = C * Math.sin(H)\n const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3)\n const mm = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3)\n const s = Math.pow(L - 0.0894841775 * a - 1.291485548 * b, 3)\n return out(\n gamma(4.0767416621 * l - 3.3077115913 * mm + 0.2309699292 * s),\n gamma(-1.2684380046 * l + 2.6097574011 * mm - 0.3413193965 * s),\n gamma(-0.0041960863 * l - 0.7034186147 * mm + 1.707614701 * s),\n alpha(m[4]),\n )\n }\n return null\n}\n\n/** A length in pixels, within what Cauthy takes, or null. */\nfunction toRadius(value: string): number | null {\n const m = /^([\\d.]+)(px|rem|em)?$/.exec(value.trim())\n if (!m) return null\n const px = parseFloat(m[1]) * (m[2] === 'rem' || m[2] === 'em' ? 16 : 1)\n return Number.isFinite(px) ? Math.min(MAX_RADIUS, Math.max(0, Math.round(px))) : null\n}\n\n/** A font list as Cauthy takes it, or null. */\nfunction toFont(value: string): string | null {\n const v = value.trim()\n return /^[A-Za-z0-9 ,'\"_-]{1,200}$/.test(v) && (v.match(/\"/g)?.length ?? 0) % 2 === 0 && (v.match(/'/g)?.length ?? 0) % 2 === 0 ? v : null\n}\n\n// ── Stackmyth ──────────────────────────────────────────────────────────────\n\n/** Which Stackmyth token each value of a theme is read from, first found wins. */\nconst COLORS: [keyof CauthyTheme, string[]][] = [\n ['background', ['--sm-bg-surface', '--sm-surface']],\n ['surface', ['--sm-bg-surface-raised', '--sm-surface-raised']],\n ['text', ['--sm-text-primary', '--sm-surface-text']],\n ['textMuted', ['--sm-text-secondary']],\n ['border', ['--sm-border-default', '--sm-surface-border']],\n ['primary', ['--sm-primary', '--sm-bg-interactive']],\n ['primaryText', ['--sm-primary-text', '--sm-text-inverse']],\n ['accent', ['--sm-text-brand', '--sm-border-focus', '--sm-accent']],\n ['error', ['--sm-error-soft-text', '--sm-error']],\n ['errorBackground', ['--sm-error-soft']],\n ['success', ['--sm-success-soft-text', '--sm-success']],\n ['successBackground', ['--sm-success-soft']],\n]\n\n/**\n * Reads an application's Stackmyth theme out of its stylesheets.\n *\n * Give it the CSS that declares the tokens, in the order the application\n * loads it — Stackmyth's own (`@stackmyth/core/core.vars.css`, or a theme\n * file) and then the application's brand file that re-points them. Tokens\n * that point at the application's own variables are followed. The\n * application's dark mode is left out unless asked for.\n */\nexport function themeFromStackmyth(css: string | string[], options: StackmythThemeOptions = {}): ImportedTheme {\n const o = { mode: options.mode ?? 'light', theme: options.theme }\n const vars = new Map<string, string>()\n for (const sheet of Array.isArray(css) ? css : [css]) {\n for (const d of declarations(sheet)) if (applies(d, o)) vars.set(d.name, d.value)\n }\n const theme: CauthyTheme = {}\n const warnings: string[] = []\n\n const read = <T>(tokens: string[], to: (v: string) => T | null, what: string): T | undefined => {\n for (const token of tokens) {\n const raw = vars.get(token)\n if (raw === undefined) continue\n const value = resolve(raw, vars)\n const got = value === null ? null : to(value)\n if (got !== null) return got\n warnings.push(`${token}: \"${raw}\" is not ${what} Cauthy can take`)\n }\n return undefined\n }\n\n for (const [field, tokens] of COLORS) {\n const c = read(tokens, toColor, 'a colour')\n if (c !== undefined) (theme as Record<string, unknown>)[field] = c\n }\n const radius = read(['--sm-radius-container', '--sm-radius-md'], toRadius, 'a length')\n if (radius !== undefined) theme.radius = radius\n const button = read(['--sm-radius-interactive', '--sm-radius-sm'], toRadius, 'a length')\n if (button !== undefined) theme.buttonRadius = button\n const font = read(['--sm-font-family'], toFont, 'a font list')\n if (font !== undefined) theme.fontFamily = font\n if (options.logoUrl) theme.logoUrl = options.logoUrl\n\n if (vars.size === 0) warnings.push('no custom properties were found: is this the stylesheet that declares the --sm-* tokens?')\n else if (![...vars.keys()].some((k) => k.startsWith('--sm-'))) warnings.push('no --sm-* token was found in these stylesheets')\n return { theme, warnings }\n}\n\n// ── Any stylesheet ─────────────────────────────────────────────────────────\n\n/** The values of a theme a stylesheet can say. */\nexport type ThemeField =\n | 'background' | 'surface' | 'text' | 'textMuted' | 'border' | 'inputBackground' | 'inputBorder'\n | 'primary' | 'primaryText' | 'accent' | 'error' | 'errorBackground' | 'success' | 'successBackground'\n | 'radius' | 'buttonRadius' | 'fontFamily'\n\n/** How a stylesheet names its look: Stackmyth's tokens, shadcn/ui's (and Tailwind's), or the application's own. */\nexport type CssFormat = 'stackmyth' | 'shadcn' | 'custom'\n\nexport interface CssThemeOptions {\n /** Which names to read. Default: `auto`, told from the stylesheet itself. */\n format?: CssFormat | 'auto'\n /** Which of the application's two modes to take. Default: `light`. */\n mode?: 'light' | 'dark'\n /** The named theme to read, when the stylesheet keeps several under `[data-theme=…]`. */\n theme?: string\n /** For `custom`: the variable each value is read from, `{ primary: '--brand' }`. */\n map?: Partial<Record<ThemeField, string>>\n}\n\nexport interface CssImportedTheme extends ImportedTheme {\n /** The names that were read. */\n format: CssFormat\n}\n\nconst RADII: ThemeField[] = ['radius', 'buttonRadius']\n\n/** shadcn/ui's names, as Tailwind 3 (`--primary`) and Tailwind 4 (`--color-primary`) write them. */\nconst SHADCN: [ThemeField, string[]][] = [\n ['background', ['--background', '--color-background']],\n ['surface', ['--card', '--color-card', '--popover', '--color-popover']],\n ['text', ['--foreground', '--color-foreground']],\n ['textMuted', ['--muted-foreground', '--color-muted-foreground']],\n ['border', ['--border', '--color-border']],\n ['inputBorder', ['--input', '--color-input']],\n ['primary', ['--primary', '--color-primary']],\n ['primaryText', ['--primary-foreground', '--color-primary-foreground']],\n ['accent', ['--ring', '--color-ring', '--primary', '--color-primary']],\n ['error', ['--destructive', '--color-destructive']],\n ['radius', ['--radius']],\n ['buttonRadius', ['--radius']],\n ['fontFamily', ['--font-sans', '--font-family']],\n]\n\n/** A colour as shadcn/ui writes it on Tailwind 3 — `222.2 84% 4.9%`, the inside of hsl() — or any other. */\nfunction shadcnColor(value: string): string | null {\n return /^[\\d.]+(?:deg)?\\s+[\\d.]+%\\s+[\\d.]+%(?:\\s*\\/\\s*[\\d.]+%?)?$/.test(value.trim()) ? toColor(`hsl(${value.trim()})`) : toColor(value)\n}\n\n/** Every custom property a stylesheet sets for the page, the last one winning. */\nfunction pageVariables(css: string | string[], mode: 'light' | 'dark', theme?: string): Map<string, string> {\n const vars = new Map<string, string>()\n for (const sheet of Array.isArray(css) ? css : [css]) {\n for (const d of declarations(sheet)) if (applies(d, { mode, theme })) vars.set(d.name, d.value)\n }\n return vars\n}\n\n/** The custom properties a stylesheet sets for the page, by name: what a person picks from to map their own. */\nexport function cssVariables(css: string | string[], options: Pick<CssThemeOptions, 'mode' | 'theme'> = {}): string[] {\n return [...pageVariables(css, options.mode ?? 'light', options.theme).keys()].sort()\n}\n\n/**\n * Reads an application's look out of its stylesheets, whatever names it uses:\n * Stackmyth's tokens, shadcn/ui's (`--primary`, `--radius`, on Tailwind 3 or\n * 4), or the application's own variables given in `map`. What comes out is a\n * theme of named values, never CSS.\n */\nexport function themeFromCss(css: string | string[], options: CssThemeOptions = {}): CssImportedTheme {\n const mode = options.mode ?? 'light'\n const vars = pageVariables(css, mode, options.theme)\n const names = [...vars.keys()]\n let format: CssFormat\n if (options.format && options.format !== 'auto') format = options.format\n else if (options.map && Object.keys(options.map).length > 0) format = 'custom'\n else if (names.some((n) => n.startsWith('--sm-'))) format = 'stackmyth'\n else if (names.some((n) => /^--(color-)?(primary|background|foreground)$/.test(n))) format = 'shadcn'\n else format = 'custom'\n\n if (format === 'stackmyth') return { ...themeFromStackmyth(css, { mode, theme: options.theme }), format }\n\n const spec: [ThemeField, string[]][] = format === 'shadcn'\n ? SHADCN\n : Object.entries(options.map ?? {}).filter(([, v]) => v).map(([k, v]) => [k as ThemeField, [String(v).startsWith('--') ? String(v) : `--${v}`]])\n const theme: CauthyTheme = {}\n const warnings: string[] = []\n for (const [field, tokens] of spec) {\n for (const token of tokens) {\n const raw = vars.get(token)\n if (raw === undefined) continue\n const value = resolve(raw, vars)\n const got = value === null ? null\n : RADII.includes(field) ? toRadius(value)\n : field === 'fontFamily' ? toFont(value)\n : format === 'shadcn' ? shadcnColor(value) : toColor(value)\n if (got !== null) {\n (theme as Record<string, unknown>)[field] = got\n break\n }\n warnings.push(`${token}: \"${raw.length > 60 ? raw.slice(0, 57) + '…' : raw}\" is not ${RADII.includes(field) ? 'a length' : field === 'fontFamily' ? 'a font list' : 'a colour'} Cauthy can take`)\n }\n }\n if (vars.size === 0) warnings.push('no custom properties were found in these stylesheets')\n else if (format === 'custom' && spec.length === 0) warnings.push('these stylesheets use names of their own: say which variable each value is read from')\n return { theme, warnings, format }\n}\n\n// ── On the application's own screens ───────────────────────────────────────\n\n/**\n * A theme as the CSS variables of `cauthy-auth/styles.css` (`--cauthy-*`), for\n * the forms an application shows on its own pages. The page's own background,\n * the layout and the words are Cauthy's pages' matter, and left out.\n */\nexport function themeVariables(theme: CauthyTheme): Record<string, string> {\n const vars: Record<string, string> = {}\n const put = (name: string, v: string | number | undefined) => {\n if (v === undefined || v === '') return\n vars[`--cauthy-${name}`] = typeof v === 'number' ? `${v}px` : v\n }\n put('surface', theme.surface)\n put('text', theme.text)\n put('text-muted', theme.textMuted)\n put('border', theme.border)\n put('input-background', theme.inputBackground)\n put('input-border', theme.inputBorder)\n put('primary', theme.primary)\n put('primary-text', theme.primaryText)\n put('accent', theme.accent)\n put('error', theme.error)\n put('error-background', theme.errorBackground)\n put('success', theme.success)\n put('success-background', theme.successBackground)\n put('radius', theme.radius)\n put('button-radius', theme.buttonRadius)\n put('font', theme.fontFamily)\n return vars\n}\n\n// ── Sending it to Cauthy ───────────────────────────────────────────────────\n\n/** A theme as Cauthy's API names its values. */\nexport function toWire(theme: CauthyTheme): Record<string, unknown> {\n const names: Record<keyof CauthyTheme, string> = {\n background: 'background', surface: 'surface', text: 'text', textMuted: 'text_muted', border: 'border',\n primary: 'primary', primaryText: 'primary_text', accent: 'accent', error: 'error', errorBackground: 'error_background',\n success: 'success', successBackground: 'success_background', radius: 'radius', buttonRadius: 'button_radius',\n fontFamily: 'font_family', logoUrl: 'logo_url', fonts: 'fonts', layout: 'layout', panelColors: 'panel_colors',\n panelText: 'panel_text', panelIconUrl: 'panel_icon_url', texts: 'texts', inputBackground: 'input_background', inputBorder: 'input_border', tokens: 'tokens',\n }\n const wire: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(theme)) {\n if (v === undefined || v === '' || (Array.isArray(v) && v.length === 0)) continue\n wire[names[k as keyof CauthyTheme]] = v\n }\n return wire\n}\n\n/** A theme as Cauthy answers it, in this package's names. */\nexport function fromWire(wire: Record<string, unknown>): CauthyTheme {\n const names: Record<string, keyof CauthyTheme> = {\n background: 'background', surface: 'surface', text: 'text', text_muted: 'textMuted', border: 'border',\n primary: 'primary', primary_text: 'primaryText', accent: 'accent', error: 'error', error_background: 'errorBackground',\n success: 'success', success_background: 'successBackground', radius: 'radius', button_radius: 'buttonRadius',\n font_family: 'fontFamily', logo_url: 'logoUrl', fonts: 'fonts', layout: 'layout', panel_colors: 'panelColors',\n panel_text: 'panelText', panel_icon_url: 'panelIconUrl', texts: 'texts', input_background: 'inputBackground', input_border: 'inputBorder', tokens: 'tokens',\n }\n const theme: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(wire ?? {})) if (names[k] && v !== undefined && v !== null && v !== '') theme[names[k]] = v\n return theme as CauthyTheme\n}\n\nexport interface PushThemeOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The application's client id. Default: `CAUTHY_CLIENT_ID`. */\n clientId?: string\n /** The workspace's slug. Default: `CAUTHY_TENANT`. */\n tenant?: string\n /**\n * A personal access token with `oauth_clients:manage`. Default:\n * `CAUTHY_TOKEN`. It belongs in the deploy pipeline, never in the application.\n */\n token?: string\n theme: CauthyTheme\n fetch?: typeof fetch\n}\n\n/**\n * Gives the application its look on Cauthy's pages. It replaces the theme: a\n * value left out goes back to Cauthy's own. Run it when the brand changes —\n * from a script or the deploy — not on every request.\n */\nexport async function pushTheme(o: PushThemeOptions): Promise<void> {\n const env = (n: string) => (typeof process !== 'undefined' ? process.env?.[n] : undefined)\n const issuer = (o.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n const clientId = o.clientId ?? env('CAUTHY_CLIENT_ID') ?? ''\n const tenant = o.tenant ?? env('CAUTHY_TENANT') ?? ''\n const token = o.token ?? env('CAUTHY_TOKEN') ?? ''\n for (const [name, v] of Object.entries({ CAUTHY_ISSUER: issuer, CAUTHY_CLIENT_ID: clientId, CAUTHY_TENANT: tenant, CAUTHY_TOKEN: token })) {\n if (v === '') throw new Error(`cauthy-auth: ${name} is required to push a theme`)\n }\n const res = await (o.fetch ?? fetch)(`${issuer}/v1/oauth/clients/${encodeURIComponent(clientId)}/theme`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${token}`, 'x-tenant-key': tenant, 'content-type': 'application/json' },\n body: JSON.stringify(toWire(o.theme)),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { errors?: { message?: string }[] } | null\n throw new Error(`cauthy-auth: Cauthy refused the theme (${res.status}): ${body?.errors?.[0]?.message ?? res.statusText}`)\n }\n}\n","// What a sign-in or sign-up form is checked for before anything is sent, in\n// the browser and again on the server: the same rules in both places, so the\n// form says what the server would.\n\nexport type AuthField = 'email' | 'password' | 'newPassword' | 'name' | 'code'\n\n/** A value of a form that cannot be sent as it is. */\nexport interface FieldProblem {\n field: AuthField\n /** Stable, for translating: `required`, `invalid_email`, `too_short`, `too_long`. */\n code: 'required' | 'invalid_email' | 'too_short' | 'too_long'\n message: string\n}\n\n/** The shortest password Cauthy takes for a new account. */\nexport const MIN_PASSWORD = 8\nconst MAX_PASSWORD = 256\nconst MAX_NAME = 120\n\n// One @, something on each side, a dot in the domain, no spaces: what catches\n// a typo. Whether the address exists is Cauthy's to find out.\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nexport function checkEmail(value: unknown): FieldProblem | null {\n const v = typeof value === 'string' ? value.trim() : ''\n if (v === '') return { field: 'email', code: 'required', message: 'Enter your email address.' }\n if (v.length > 254 || !EMAIL.test(v)) return { field: 'email', code: 'invalid_email', message: 'That does not look like an email address.' }\n return null\n}\n\n/** A password being typed to sign in: only that there is one. */\nexport function checkPassword(value: unknown): FieldProblem | null {\n if (typeof value !== 'string' || value === '') return { field: 'password', code: 'required', message: 'Enter your password.' }\n if (value.length > MAX_PASSWORD) return { field: 'password', code: 'too_long', message: 'That password is too long.' }\n return null\n}\n\n/** A password being chosen for a new account. */\nexport function checkNewPassword(value: unknown): FieldProblem | null {\n const basic = checkPassword(value)\n if (basic) return basic\n if ((value as string).length < MIN_PASSWORD) {\n return { field: 'password', code: 'too_short', message: `Use at least ${MIN_PASSWORD} characters.` }\n }\n return null\n}\n\nexport function checkName(value: unknown): FieldProblem | null {\n if (value === undefined || value === null || value === '') return null\n if (typeof value !== 'string' || value.trim().length > MAX_NAME) return { field: 'name', code: 'too_long', message: `Use at most ${MAX_NAME} characters.` }\n return null\n}\n\nexport function checkCode(value: unknown): FieldProblem | null {\n const v = typeof value === 'string' ? value.trim() : ''\n if (v === '') return { field: 'code', code: 'required', message: 'Enter the code.' }\n if (v.length > 40) return { field: 'code', code: 'too_long', message: 'That is not a code.' }\n return null\n}\n\n/** The first problem of a form, or null when it can be sent. */\nexport function firstProblem(...checks: (FieldProblem | null)[]): FieldProblem | null {\n return checks.find((c) => c !== null) ?? null\n}\n","// Who is signed in, kept for the browser: the same thing <CauthyProvider>\n// keeps for React, with no framework in it. `cauthy-auth/vue` and\n// `cauthy-auth/svelte` are this store in each one's own terms, and anything\n// else (Solid, Angular, a page with no framework) can use it as it is.\n//\n// const store = createSessionStore()\n// const stop = store.subscribe(({ session, status }) => render(session))\n// await store.auth.signIn.email({ email, password }) // subscribers hear the new session\n//\n// While somebody listens it asks the server who is signed in, asks again\n// shortly before the session's token runs out, and when the tab is looked at\n// again. With nobody listening it does nothing.\n\nimport { createAuthClient, type AuthClient, type AuthClientOptions } from './client'\nimport type { PublicSession } from './types'\n\nexport interface SessionState {\n /** The signed-in person and their organizations, or null. */\n session: PublicSession | null\n status: 'loading' | 'authenticated' | 'unauthenticated'\n}\n\nexport interface SessionStoreOptions extends AuthClientOptions {\n /**\n * The session the server already read while rendering (SSR): the first\n * paint is then right, with no \"loading\". `null` means \"nobody\"; leave it\n * out when the server did not look.\n */\n initialSession?: PublicSession | null\n}\n\nexport interface SessionStore {\n /** What is known now. */\n get(): SessionState\n /** Calls `listener` now and on every change. Answers how to stop. */\n subscribe(listener: (state: SessionState) => void): () => void\n /** Asks the server again who is signed in. */\n refresh(): Promise<PublicSession | null>\n /** Sends the browser to Cauthy's page to sign in, and back to `returnTo` (default: where it is now). */\n signIn(options?: { returnTo?: string; locale?: string; prompt?: 'login' }): void\n /** Signs out of this application and of Cauthy in this browser. */\n signOut(): void\n /** Where the person looks after their account on Cauthy's page. */\n accountUrl(returnTo?: string): string\n /**\n * The functions of an application's own screens. They are\n * `createAuthClient()`'s, and what changes who is signed in is heard by the\n * subscribers with no reload.\n */\n auth: AuthClient\n /** Where the server mounted the routes. */\n basePath: string\n}\n\n/** Ask again this long before the session's token runs out. */\nconst AHEAD_MS = 60_000\n\nexport function createSessionStore(options: SessionStoreOptions = {}): SessionStore {\n const base = (options.basePath ?? '/api/auth').replace(/\\/+$/, '')\n const doFetch: typeof fetch = (...args) => (options.fetch ?? fetch)(...args)\n const first = options.initialSession\n let state: SessionState = { session: first ?? null, status: first === undefined ? 'loading' : first === null ? 'unauthenticated' : 'authenticated' }\n const listeners = new Set<(state: SessionState) => void>()\n let asking: Promise<PublicSession | null> | null = null\n let timer: ReturnType<typeof setTimeout> | undefined\n let asked = first !== undefined\n\n const set = (next: SessionState) => {\n if (next.session === state.session && next.status === state.status) return\n state = next\n schedule()\n for (const l of [...listeners]) l(state)\n }\n\n function schedule(): void {\n clearTimeout(timer)\n timer = undefined\n if (listeners.size === 0 || state.session === null) return\n const wait = Math.max(new Date(state.session.expiresAt).getTime() - Date.now() - AHEAD_MS, 5_000)\n timer = setTimeout(() => void refresh(), wait)\n }\n\n function refresh(): Promise<PublicSession | null> {\n asked = true\n asking ??= (async () => {\n try {\n const res = await doFetch(`${base}/session`, { credentials: 'same-origin', headers: { accept: 'application/json' } })\n if (!res.ok) throw new Error(String(res.status))\n const body = (await res.json()) as { session: PublicSession | null; status: string }\n // \"expired\" is the server unable to reach Cauthy: what is on screen\n // stays, and the next ask settles it.\n if (body.status !== 'expired') set({ session: body.session, status: body.session ? 'authenticated' : 'unauthenticated' })\n return body.session\n } catch {\n if (state.status === 'loading') set({ session: null, status: 'unauthenticated' })\n return null\n } finally {\n asking = null\n }\n })()\n return asking\n }\n\n const onVisible = () => {\n if (document.visibilityState === 'visible') void refresh()\n }\n const inBrowser = () => typeof document !== 'undefined'\n\n const client = createAuthClient({ basePath: base, fetch: options.fetch })\n const then = async <T,>(running: Promise<T>): Promise<T> => {\n const r = await running\n await refresh()\n return r\n }\n\n return {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener)\n if (listeners.size === 1 && inBrowser()) {\n document.addEventListener('visibilitychange', onVisible)\n schedule()\n if (!asked) void refresh()\n }\n listener(state)\n return () => {\n listeners.delete(listener)\n if (listeners.size === 0) {\n clearTimeout(timer)\n timer = undefined\n if (inBrowser()) document.removeEventListener('visibilitychange', onVisible)\n }\n }\n },\n refresh,\n signIn(o = {}) {\n const q = new URLSearchParams({ return_to: o.returnTo ?? window.location.pathname + window.location.search })\n if (o.locale) q.set('locale', o.locale)\n if (o.prompt) q.set('prompt', o.prompt)\n window.location.assign(`${base}/login?${q}`)\n },\n signOut() {\n window.location.assign(`${base}/logout`)\n },\n accountUrl(returnTo) {\n const back = returnTo ?? (typeof window === 'undefined' ? '/' : window.location.pathname + window.location.search)\n return `${base}/account?return_to=${encodeURIComponent(back)}`\n },\n auth: {\n ...client,\n signIn: {\n ...client.signIn,\n email: (f) => then(client.signIn.email(f)),\n mfa: (f) => then(client.signIn.mfa(f)),\n magicLinkVerify: (f) => then(client.signIn.magicLinkVerify(f)),\n emailCode: (f) => then(client.signIn.emailCode(f)),\n },\n signUp: { email: (f) => then(client.signUp.email(f)) },\n signOut: () => then(client.signOut()),\n account: {\n ...client.account,\n update: (f) => then(client.account.update(f)),\n changePassword: (f) => then(client.account.changePassword(f)),\n signOutEverywhere: () => then(client.account.signOutEverywhere()),\n },\n },\n basePath: base,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsjBO,SAAS,SAAS,MAA4C;AACnE,QAAM,QAA2C;AAAA,IAC/C,YAAY;AAAA,IAAc,SAAS;AAAA,IAAW,MAAM;AAAA,IAAQ,YAAY;AAAA,IAAa,QAAQ;AAAA,IAC7F,SAAS;AAAA,IAAW,cAAc;AAAA,IAAe,QAAQ;AAAA,IAAU,OAAO;AAAA,IAAS,kBAAkB;AAAA,IACrG,SAAS;AAAA,IAAW,oBAAoB;AAAA,IAAqB,QAAQ;AAAA,IAAU,eAAe;AAAA,IAC9F,aAAa;AAAA,IAAc,UAAU;AAAA,IAAW,OAAO;AAAA,IAAS,QAAQ;AAAA,IAAU,cAAc;AAAA,IAChG,YAAY;AAAA,IAAa,gBAAgB;AAAA,IAAgB,OAAO;AAAA,IAAS,kBAAkB;AAAA,IAAmB,cAAc;AAAA,IAAe,QAAQ;AAAA,EACrJ;AACA,QAAM,QAAiC,CAAC;AACxC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,CAAC,EAAG,KAAI,MAAM,CAAC,KAAK,MAAM,UAAa,MAAM,QAAQ,MAAM,GAAI,OAAM,MAAM,CAAC,CAAC,IAAI;AAC9H,SAAO;AACT;;;ACljBO,IAAM,eAAe;AAC5B,IAAM,eAAe;AACrB,IAAM,WAAW;A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QAAQ,OAAO,SAAS,WAAW,SAAS,IAAI,IAAI,IAAK;AAClG,aAAO;AAAA,IACT;AAAA,IACA,MAAM,UAAU;AACd,UAAI;AACF,cAAM,MAAM,MAAM,QAAQ,GAAG,IAAI,YAAY,EAAE,aAAa,eAAe,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC;AACpH,YAAI,IAAI,GAAI,QAAQ,MAAM,IAAI,KAAK;AAAA,MACrC,QAAQ;AAAA,MAER;AACA,aAAO,EAAE,WAAW,CAAC,GAAG,QAAQ,MAAM,WAAW,OAAO,SAAS,MAAM;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
package/dist/client.mjs CHANGED
@@ -209,6 +209,7 @@ function createAuthClient(options = {}) {
209
209
  return null;
210
210
  }
211
211
  }
212
+ const linkUrl = (provider, o = {}) => `${base}/me/identities/link/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ""}`;
212
213
  const socialUrl = (provider, o = {}) => `${base}/sign-in/social/${encodeURIComponent(provider)}${o.returnTo ? `?return_to=${encodeURIComponent(o.returnTo)}` : ""}`;
213
214
  const passkeyUrl = (o = {}) => {
214
215
  const q = new URLSearchParams({ method: "passkey" });
@@ -255,6 +256,16 @@ function createAuthClient(options = {}) {
255
256
  disable: (f) => post("/me/mfa/disable", { password: f.password }, null),
256
257
  recoveryCodes: (f) => post("/me/mfa/recovery-codes", { password: f.password }, null)
257
258
  },
259
+ changeEmail: (f) => post("/me/email", { email: f.email, password: f.password }, checkEmail(f.email)),
260
+ async identities() {
261
+ const body = await read("/me/identities");
262
+ return body && Array.isArray(body.identities) ? body.identities : [];
263
+ },
264
+ linkUrl,
265
+ link(provider, o) {
266
+ window.location.assign(linkUrl(provider, o));
267
+ },
268
+ unlink: (provider) => post("/me/identities/unlink", { provider }, null),
258
269
  async sessions() {
259
270
  const body = await read("/me/sessions");
260
271
  return body && Array.isArray(body.sessions) ? body.sessions : [];