@xk2800/nextjs-template 0.7.2-beta.10 → 0.7.2-beta.11

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../components/email/security/passkey-changed.tsx","../../components/email/auth/reset-password.tsx","../../components/email/auth/verify-email.tsx","../../server/db/schema.ts","../../lib/config/maintenance.ts","../../config/env-schema.ts","../../config/env.ts","../../config/pg-ssl.ts","../../server/db/index.ts","../../node_modules/@better-auth/utils/dist/bytes.mjs","../../node_modules/@better-auth/utils/dist/base32.mjs","../../node_modules/@better-auth/utils/dist/index.mjs","../../node_modules/@better-auth/utils/dist/base64.mjs","../../node_modules/@noble/hashes/utils.js","../../node_modules/@better-auth/utils/dist/hex.mjs","../../node_modules/@better-auth/utils/dist/hmac.mjs","../../node_modules/@better-auth/utils/dist/otp.mjs","../../lib/auth/two-factor.ts","../../lib/security/activity-logger.ts","../../lib/utils/request-info.ts","../../lib/security/cookie-names.ts","../../lib/auth/base-url.ts","../../lib/auth/last-admin.ts","../../lib/auth/throttle-limits.ts","../../lib/auth/throttle.ts","../../lib/db/queries/settings.ts","../../lib/email/resend.ts","../../server/auth.ts"],"names":["Html","jsx","Head","Tailwind","Body","Container","jsxs","Section","Heading","Text","Button","Link","pgEnum","pgTable","text","createId","boolean","timestamp","index","integer","jsonb","unique","check","sql","z","Pool","drizzlePg","neonConfig","neon","drizzle","hex","getAlphabet","hmac","twoFactor","createAuthMiddleware","getSessionFromCtx","symmetricDecrypt","APIError","UAParser","geoip","eq","lt","EmailTemplatePasskeyChange","betterAuth","drizzleAdapter","EmailTemplateResetPassword","EmailTemplateVerifyEmail","_a","_b","_c","_d","_e","current","adminPlugin","passkey","oneTap"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,uBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,uBAAA,EAAA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xB,EAAA,IAAI,CAAC,KAAA,EAAO,KAAA,GAAQ,UAAA,EAAW;AAC/B,EAAA,OAAO,KAAA;AACT;AAEO,IAAM,IAAA,GAAO,IAAI,KAAA,CAAM,EAAC,EAAoC;AAAA,EACjE,GAAA,CAAI,SAAS,IAAA,EAAM;AACjB,IAAA,MAAM,WAAW,cAAA,EAAe;AAChC,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,QAAA,EAAU,IAAI,CAAA;AACxC,IAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAA,GAAI,KAAA;AAAA,EAC9D,CAAA;AAAA;AAAA;AAAA;AAAA,EAIA,GAAA,CAAI,SAAS,IAAA,EAAM;AACjB,IAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,cAAA,EAAe,EAAG,IAAI,CAAA;AAAA,EAC3C,CAAA;AAAA,EACA,QAAQ,OAAA,EAAS;AACf,IAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,cAAA,EAAgB,CAAA;AAAA,EACzC,CAAA;AAAA,EACA,wBAAA,CAAyB,SAAS,IAAA,EAAM;AACtC,IAAA,OAAO,OAAA,CAAQ,wBAAA,CAAyB,cAAA,EAAe,EAAG,IAAI,CAAA;AAAA,EAChE;AACF,CAAC","file":"index.js","sourcesContent":["import {\n Html,\n Head,\n Body,\n Container,\n Section,\n Text,\n Heading,\n Button,\n Tailwind,\n} from '@react-email/components';\n\ninterface EmailTemplatePasskeyChangeProps {\n firstName: string;\n action: 'added' | 'removed';\n device: string;\n location: string;\n ipAddress: string;\n when: string;\n manageUrl?: string;\n}\n\nexport function EmailTemplatePasskeyChange({\n firstName,\n action,\n device,\n location,\n ipAddress,\n when,\n manageUrl,\n}: EmailTemplatePasskeyChangeProps) {\n const verb = action === 'added' ? 'added to' : 'removed from';\n\n return (\n <Html>\n <Head />\n <Tailwind>\n <Body className=\"bg-white font-sans\">\n <Container className=\"mx-auto max-w-[560px] px-0 pt-5 pb-12\">\n <Section className=\"rounded-xl bg-[#f8f9fa] p-10\">\n <Heading className=\"mb-3 text-center text-2xl font-bold text-[#1a1a1a]\">\n A passkey was {action}\n </Heading>\n <Text className=\"mb-6 text-base leading-6 text-[#666666]\">\n Hi {firstName}, a passkey was just {verb} your account.\n </Text>\n <Section className=\"mb-6 rounded-lg bg-white p-5\">\n <Text className=\"m-0 mb-2 text-sm leading-5 text-[#1a1a1a]\">\n <strong>Device:</strong> {device}\n </Text>\n <Text className=\"m-0 mb-2 text-sm leading-5 text-[#1a1a1a]\">\n <strong>Approx. location:</strong> {location}\n </Text>\n <Text className=\"m-0 mb-2 text-sm leading-5 text-[#1a1a1a]\">\n <strong>IP address:</strong> {ipAddress}\n </Text>\n <Text className=\"m-0 text-sm leading-5 text-[#1a1a1a]\">\n <strong>When:</strong> {when}\n </Text>\n </Section>\n {manageUrl && (\n <Section className=\"mb-6 text-center\">\n <Button\n href={manageUrl}\n className=\"rounded-lg bg-[#1a1a1a] px-6 py-3 text-sm font-bold text-white no-underline\"\n >\n Review your passkeys\n </Button>\n </Section>\n )}\n <Text className=\"text-sm leading-[22px] text-[#666666]\">\n If this was you, no action is needed. If you don&apos;t recognize it, change\n your password now and review your passkeys and active sessions.\n </Text>\n </Section>\n </Container>\n </Body>\n </Tailwind>\n </Html>\n );\n}\n","import {\n Html,\n Head,\n Body,\n Container,\n Section,\n Text,\n Heading,\n Button,\n} from '@react-email/components';\n\ninterface EmailTemplateResetPasswordProps {\n firstName: string;\n url: string;\n}\n\nexport function EmailTemplateResetPassword({ firstName, url }: EmailTemplateResetPasswordProps) {\n return (\n <Html>\n <Head />\n <Body style={{ backgroundColor: '#ffffff', fontFamily: 'Arial, sans-serif' }}>\n <Container style={{ margin: '0 auto', padding: '20px 0 48px', maxWidth: '560px' }}>\n <Section style={{ backgroundColor: '#f8f9fa', borderRadius: '12px', padding: '40px', textAlign: 'center' as const }}>\n <Heading style={{ fontSize: '28px', fontWeight: 'bold', marginBottom: '12px', color: '#1a1a1a' }}>\n Reset your password\n </Heading>\n <Text style={{ fontSize: '16px', color: '#666666', marginBottom: '32px', lineHeight: '24px' }}>\n Hi {firstName}, we got a request to reset your password. This link expires in an hour\n — if you didn&apos;t ask for this, you can safely ignore this email.\n </Text>\n <Section style={{ marginBottom: '32px' }}>\n <Button\n href={url}\n style={{\n backgroundColor: '#000000',\n color: '#ffffff',\n padding: '12px 32px',\n borderRadius: '6px',\n textDecoration: 'none',\n fontSize: '16px',\n fontWeight: 'bold',\n }}\n >\n Reset password\n </Button>\n </Section>\n <Text style={{ fontSize: '13px', color: '#999999', lineHeight: '20px', wordBreak: 'break-all' as const }}>\n Or paste this link into your browser:<br />\n <a href={url} style={{ color: '#000000', textDecoration: 'underline' }}>{url}</a>\n </Text>\n </Section>\n </Container>\n </Body>\n </Html>\n );\n}\n","import {\n Html,\n Head,\n Body,\n Container,\n Section,\n Text,\n Heading,\n Button,\n Link,\n Tailwind,\n} from '@react-email/components';\n\ninterface EmailTemplateVerifyEmailProps {\n firstName: string;\n url: string;\n}\n\nexport function EmailTemplateVerifyEmail({ firstName, url }: EmailTemplateVerifyEmailProps) {\n return (\n <Html>\n <Head />\n <Tailwind>\n <Body className=\"bg-white font-sans\">\n <Container className=\"mx-auto max-w-[560px] px-0 pt-5 pb-12\">\n <Section className=\"rounded-xl bg-[#f8f9fa] p-10 text-center\">\n <Heading className=\"mb-3 text-[28px] font-bold text-[#1a1a1a]\">\n Confirm your email\n </Heading>\n <Text className=\"mb-8 text-base leading-6 text-[#666666]\">\n Hi {firstName}, click the button below to verify this email address. If you\n didn&apos;t create an account, you can safely ignore this email.\n </Text>\n <Section className=\"mb-8\">\n <Button\n href={url}\n className=\"rounded-md bg-black px-8 py-3 text-base font-bold text-white no-underline\"\n >\n Verify email\n </Button>\n </Section>\n <Text className=\"text-[13px] leading-5 break-all text-[#999999]\">\n Or paste this link into your browser:\n <br />\n <Link href={url} className=\"text-black underline\">\n {url}\n </Link>\n </Text>\n </Section>\n </Container>\n </Body>\n </Tailwind>\n </Html>\n );\n}\n","import { boolean, check, index, integer, jsonb, pgEnum, pgTable, text, timestamp, unique } from \"drizzle-orm/pg-core\";\nimport { sql } from \"drizzle-orm\";\nimport { createId } from '@paralleldrive/cuid2'\nimport { DEFAULT_MAINTENANCE_EXEMPT_PATHS } from \"../../lib/config/maintenance\";\n\n// 'tester' is a regular user account flagged for testing; apps can use it to\n// keep test accounts apart from real users. It has no admin access.\nexport const RoleEnum = pgEnum('roles', ['user', 'admin', 'tester'])\n\nexport const ActivityActionEnum = pgEnum('activity_actions', [\n 'login',\n 'logout',\n 'login_failed',\n 'password_changed',\n 'email_changed',\n 'profile_updated',\n 'session_revoked',\n 'user_deleted',\n 'user_banned',\n 'user_unbanned',\n 'role_changed',\n 'impersonation_started',\n 'impersonation_stopped',\n 'settings_changed',\n 'passkey_added',\n 'passkey_removed',\n])\n\nexport const users = pgTable(\"user\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n name: text('name').notNull(),\n email: text('email').notNull().unique(),\n password: text('password'),\n emailVerified: boolean(\"emailVerified\").notNull().default(false),\n image: text(\"image\"),\n role: RoleEnum('roles').default('user').notNull(),\n banned: boolean('banned').default(false).notNull(),\n bannedAt: timestamp('bannedAt'),\n bannedReason: text('bannedReason'),\n bannedBy: text('bannedBy'), // email of the admin who issued the ban\n // Required by better-auth's admin plugin schema (auto-expiring bans). We\n // never set this ourselves, so it stays null and bans behave as permanent,\n // same as before the plugin was added.\n banExpires: timestamp('banExpires'),\n lastLoginAt: timestamp('lastLoginAt'),\n lastActiveAt: timestamp('lastActiveAt'),\n // Set by better-auth's twoFactor plugin — true once the user has\n // completed TOTP setup (see twoFactor pgTable below for the secret /\n // backup codes themselves).\n twoFactorEnabled: boolean('twoFactorEnabled').notNull().default(false),\n createdAt: timestamp('createdAt').notNull().defaultNow(),\n updatedAt: timestamp('updatedAt').notNull().defaultNow(),\n});\n\nexport const sessions = pgTable(\"session\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n expiresAt: timestamp(\"expiresAt\").notNull(),\n token: text(\"token\").notNull().unique(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n ipAddress: text(\"ipAddress\"),\n userAgent: text(\"userAgent\"),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n // Set by better-auth's admin plugin while this session is an admin\n // impersonating another user; holds the impersonating admin's user id.\n impersonatedBy: text(\"impersonatedBy\"),\n}, (table) => [\n // Read by userId on every login (session count), ban/delete and the admin sessions view.\n index(\"session_user_idx\").on(table.userId),\n]);\n\nexport const accounts = pgTable(\"account\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n accountId: text(\"accountId\").notNull(),\n providerId: text(\"providerId\").notNull(),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n accessToken: text(\"accessToken\"),\n refreshToken: text(\"refreshToken\"),\n idToken: text(\"idToken\"),\n accessTokenExpiresAt: timestamp(\"accessTokenExpiresAt\"),\n refreshTokenExpiresAt: timestamp(\"refreshTokenExpiresAt\"),\n scope: text(\"scope\"),\n password: text(\"password\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n});\n\n// Better-auth's twoFactor plugin. One row per user (created on first\n// `enable`); secret and backupCodes are its own encrypted-at-rest strings,\n// field names/types must match its expectations exactly (drizzleAdapter in\n// server/auth.ts maps this table to the plugin's \"twoFactor\" model as-is).\nexport const twoFactors = pgTable(\"twoFactor\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n secret: text(\"secret\").notNull(),\n backupCodes: text(\"backupCodes\").notNull(),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n // Added in better-auth 1.7 (TOTP lockout). Defaults match the plugin's.\n verified: boolean(\"verified\").default(true),\n failedVerificationCount: integer(\"failedVerificationCount\").default(0),\n lockedUntil: timestamp(\"lockedUntil\"),\n});\n\n// Better-auth's passkey plugin — one row per registered WebAuthn credential.\nexport const passkeys = pgTable(\"passkey\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n name: text(\"name\"),\n publicKey: text(\"publicKey\").notNull(),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n credentialID: text(\"credentialID\").notNull().unique(),\n counter: integer(\"counter\").notNull(),\n deviceType: text(\"deviceType\").notNull(),\n backedUp: boolean(\"backedUp\").notNull(),\n transports: text(\"transports\"),\n createdAt: timestamp(\"createdAt\"),\n aaguid: text(\"aaguid\"),\n});\n\nexport const verifications = pgTable(\"verification\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n identifier: text(\"identifier\").notNull(),\n value: text(\"value\").notNull(),\n expiresAt: timestamp(\"expiresAt\").notNull(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n});\n\nexport const activityLogs = pgTable(\"activity_log\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n // SET NULL, not cascade: deleting an admin must not erase the audit trail of\n // what they did. actorEmail keeps who it was once the user row is gone.\n userId: text(\"userId\").references(() => users.id, { onDelete: \"set null\" }),\n actorEmail: text(\"actorEmail\"),\n action: ActivityActionEnum('action').notNull(),\n description: text('description').notNull(),\n ipAddress: text('ipAddress'),\n userAgent: text('userAgent'),\n metadata: text('metadata'),\n // Populated on 'login' events only (registration + sign-in) — parsed from\n // userAgent/ipAddress at write time so the record stays stable even if\n // the parsing library or geoip database changes later.\n referrerUrl: text('referrerUrl'),\n os: text('os'),\n browser: text('browser'),\n deviceType: text('deviceType'),\n country: text('country'),\n city: text('city'),\n createdAt: timestamp('createdAt').notNull().defaultNow(),\n}, (table) => [\n // Per-user history, and the admin log's newest-first ordering.\n index(\"activity_log_user_created_idx\").on(table.userId, table.createdAt),\n index(\"activity_log_created_idx\").on(table.createdAt),\n]);\n\n// One row per (user, device fingerprint) pair. Its only job is to answer\n// \"has this account signed in from this device before?\" — no matching row ⇒\n// send a new-device alert (see app/api/device-check/route.ts). visitorId is\n// FingerprintJS's identifier, computed client-side in\n// components/auth/deviceCheck.tsx. UA+IP are deliberately NOT the signal here:\n// they churn constantly on mobile and would alert on every other login.\nexport const deviceFingerprints = pgTable(\"device_fingerprint\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n visitorId: text(\"visitorId\").notNull(),\n // Context captured at first-seen time — for the admin panel's \"New devices\"\n // card and the alert email. Not part of the new-vs-known decision (that's\n // visitorId only), just so an admin can eyeball whether a sign-in looks like\n // a hijack. Nullable: an old row predates these columns, or geoip missed.\n ipAddress: text(\"ipAddress\"),\n userAgent: text(\"userAgent\"),\n country: text(\"country\"),\n city: text(\"city\"),\n // Latest FingerprintJS signals for this device (lib/device-fingerprint.ts\n // getDeviceSignals(): accessibility signals dropped, large values hashed),\n // shown on the admin user page. Null for rows from before this column.\n components: jsonb(\"components\").$type<Record<string, unknown>>(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n unique(\"device_fingerprint_user_visitor\").on(table.userId, table.visitorId),\n]);\n\n// Proof of cookie consent (GDPR Art. 7(1): the controller must be able to\n// demonstrate consent). One row per choice a signed-in user makes, written by\n// app/api/consent from the banner (components/site/cookie-banner.tsx).\n// Deliberately minimal — no IP/UA. Deleted with the account.\nexport const consentLog = pgTable(\"consent_log\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n // The cookie_consent value: \"all\", \"necessary\" or a comma list of purposes.\n choice: text(\"choice\").notNull(),\n // CONSENT_VERSION (lib/cookie-names.ts) at the time — which banner/policy\n // wording the user agreed to.\n version: integer(\"version\").notNull(),\n // id of the user's record this one follows (\"\" for their first). Unique per\n // user, so concurrent posts from several tabs that all saw the same latest\n // record can't each insert a duplicate — one wins, the rest conflict. Works\n // without transactions (neon-http has none). Null on rows from before it.\n previousId: text(\"previousId\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n index(\"consent_log_user_idx\").on(table.userId, table.createdAt),\n unique(\"consent_log_chain\").on(table.userId, table.previousId),\n]);\n\n// Per-device abuse throttle for /sign-in/email and /sign-up/email — one\n// fixed-window counter row per FingerprintJS visitorId (sent by the auth\n// forms as the x-device-fingerprint header; see lib/auth-throttle.ts).\n// Keyed by device, not IP: IP is shared behind corporate NAT / CGNAT / VPN,\n// so an IP counter throttles coworkers together while missing an abuser who\n// rotates IPs. Rows untouched for 30 days are deleted (RETENTION_MS in\n// lib/auth-throttle-limits.ts, swept by lib/auth-throttle.ts).\nexport const authThrottle = pgTable(\"auth_throttle\", {\n fingerprint: text(\"fingerprint\").notNull().primaryKey(),\n count: integer(\"count\").notNull().default(0),\n windowStart: timestamp(\"windowStart\").notNull().defaultNow(),\n // Blockable data points, overwritten on every attempt (last-write-wins) so\n // the admin panel can show who to block — by IP or by fingerprint — with no\n // join and no per-attempt history table. windowStart anchors the counter's\n // window; lastAttemptAt is just \"most recently seen\".\n lastAttemptAt: timestamp(\"lastAttemptAt\").notNull().defaultNow(),\n ipAddress: text(\"ipAddress\"),\n userAgent: text(\"userAgent\"),\n lastEmail: text(\"lastEmail\"),\n lastKind: text(\"lastKind\"), // 'signin' | 'signup'\n});\n\n// Singleton row (id is always 'default') holding admin-editable settings for\n// config that used to be env-var-only. See lib/settings-queries.ts for the\n// cached read path and lazy-seed-from-env behavior.\nexport const systemSettings = pgTable(\"system_settings\", {\n id: text(\"id\").primaryKey().default(\"default\"),\n maintenanceMode: boolean(\"maintenanceMode\").notNull().default(false),\n maintenanceMessage: text(\"maintenanceMessage\"),\n // Path prefixes that stay reachable while maintenance mode is on (see\n // lib/maintenance.ts — a few auth paths are always open on top of these).\n maintenanceExemptPaths: text(\"maintenanceExemptPaths\").array().notNull().default(DEFAULT_MAINTENANCE_EXEMPT_PATHS),\n authEnableGoogle: boolean(\"authEnableGoogle\").notNull().default(true),\n authEnableEmailPassword: boolean(\"authEnableEmailPassword\").notNull().default(true),\n authEnableOneTap: boolean(\"authEnableOneTap\").notNull().default(false),\n enableSessionRevocation: boolean(\"enableSessionRevocation\").notNull().default(true),\n // Attach the error a user hit to feedback they send from it (see\n // lib/feedback-route.ts). Off = only what the user typed is sent.\n feedbackAttachErrors: boolean(\"feedbackAttachErrors\").notNull().default(true),\n // GDPR/ePrivacy consent mode. On: cookie banner, FingerprintJS and One Tap\n // only after \"Accept all\", device record erased on withdrawal. Off (no EU/UK\n // users): no banner, treated as consented. Null = follow\n // NEXT_PUBLIC_COOKIE_BANNER (nullable so migrating never flips a deployed\n // banner on or off). proxy.ts mirrors the effective value into the\n // consent_required cookie for the client (lib/cookie-consent.ts).\n consentRequired: boolean(\"consentRequired\"),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n // Who last changed a setting. This row doesn't \"belong\" to that admin the\n // way sessions/activityLogs belong to their user, so deleting that admin's\n // account should null this out rather than cascade-delete the singleton row.\n updatedBy: text(\"updatedBy\").references(() => users.id, { onDelete: \"set null\" }),\n}, (table) => [\n check(\"system_settings_singleton\", sql`${table.id} = 'default'`),\n]);\n// Technical detail of unexpected errors, keyed by the short ref the user sees\n// (\"... (ref: K7Q2PX)\", see lib/errors.ts). Never sent to the browser: the\n// feedback route looks a ref up and attaches the detail to the report it\n// sends to Discord/email. Rows older than 30 days are pruned on insert.\nexport const errorRefs = pgTable(\"error_refs\", {\n ref: text(\"ref\").primaryKey(),\n message: text(\"message\").notNull(),\n detail: text(\"detail\").notNull(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n index(\"error_refs_created_at_idx\").on(table.createdAt),\n]);\n\n// One row per browser/device a user turned push notifications on for. Rows are\n// deleted when the push service reports the endpoint gone (404/410), see\n// lib/push.ts, and re-upserted whenever the app opens (components/site/push-notifications-card.tsx).\nexport const pushSubscriptions = pgTable(\"push_subscription\", {\n id: text(\"id\").primaryKey().$defaultFn(() => createId()),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n endpoint: text(\"endpoint\").notNull().unique(),\n p256dh: text(\"p256dh\").notNull(),\n auth: text(\"auth\").notNull(),\n userAgent: text(\"userAgent\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n index(\"push_subscription_user_idx\").on(table.userId),\n]);\n","// Pure path logic for maintenance mode — no DB / server-only imports, so it\n// can run in proxy.ts and in the admin form alike.\n\n// Default for the admin-editable exempt list: the public marketing pages.\nexport const DEFAULT_MAINTENANCE_EXEMPT_PATHS = [\n \"/\",\n \"/features\",\n \"/changelog\",\n \"/privacy\",\n \"/terms\",\n]\n\n// Always reachable, whatever the admin saves — otherwise an admin could\n// lock themselves out of the sign-in flow needed to turn maintenance off.\nexport const ALWAYS_OPEN_PATHS = [\n \"/maintenance\",\n \"/login\", // includes /login/2fa\n \"/forgot-password\",\n \"/reset-password\",\n \"/api/auth\",\n \"/api/settings/public\", // login page reads the One Tap flag from here\n]\n\n// `/foo` matches `/foo` and `/foo/...` but not `/foobar`; `/` matches only `/`.\nfunction matches(pathname: string, prefix: string) {\n const p = prefix.length > 1 ? prefix.replace(/\\/+$/, \"\") : prefix\n return pathname === p || (p !== \"/\" && pathname.startsWith(p + \"/\"))\n}\n\nexport function isMaintenanceExempt(pathname: string, exemptPaths: string[]) {\n return [...ALWAYS_OPEN_PATHS, ...exemptPaths].some((p) => matches(pathname, p))\n}\n","// No \"server-only\" guard here — this schema is also imported by scripts that\n// run outside Next.js's bundler (e.g. scripts/doctor.ts), where that guard\n// throws unconditionally. config/env.ts re-exports the parsed, guarded result\n// for app code; import this file directly only from non-Next scripts.\nimport { z } from 'zod';\n\nexport const envSchema = z.object({\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n PORT: z.string().default('3000').transform(Number),\n DATABASE_URL: z.string().default(''),\n RESEND_API_KEY: z.string().default(''),\n // Full access key for marketing broadcasts (admin Marketing email page).\n // Blank = use RESEND_API_KEY.\n RESEND_BROADCAST_API_KEY: z.string().default(''),\n // Resend segment users join from the dashboard \"Email updates\" toggle.\n // Blank = toggle hidden.\n RESEND_MARKETING_SEGMENT_ID: z.string().default(''),\n // Sender for every transactional email. Must be on a domain verified in\n // your Resend account.\n // Resend's shared sandbox sender: works without a verified domain but only\n // delivers to your own Resend account email. Set your verified domain for real use.\n EMAIL_FROM: z.string().default('Acme <onboarding@resend.dev>'),\n // Display name for this deployment — shown as the authenticator-app label\n // (2FA issuer) and the passkey relying-party name. Consuming projects set\n // this in their own .env; defaults to the template name.\n APP_NAME: z.string().default('Next.js Template'),\n // Where the dashboard feedback form delivers (app/api/feedback). Set either\n // or both; with neither, the Feedback button is hidden. FEEDBACK_EMAIL takes\n // a comma-separated list and sends through Resend (needs RESEND_API_KEY).\n FEEDBACK_DISCORD_WEBHOOK_URL: z.string().default(''),\n FEEDBACK_EMAIL: z.string().default(''),\n // Seconds between feedback messages per user (default 30, 0 = off). Read\n // straight from process.env in lib/feedback/route.ts; listed here for docs.\n FEEDBACK_COOLDOWN_SECONDS: z.string().default('30'),\n // Web Push (example, see lib/push.ts). Generate keys with\n // `bunx web-push generate-vapid-keys`. Blank = the notifications card is hidden.\n // The public key is also read in the browser as NEXT_PUBLIC_VAPID_PUBLIC_KEY.\n VAPID_PRIVATE_KEY: z.string().default(''),\n // mailto: or https: URL push services can contact you at.\n VAPID_SUBJECT: z.string().default(''),\n // Seed-only: the live value lives in the system_settings DB row (see\n // lib/settings-queries.ts) once it's been seeded on first read, and is\n // changed from the admin System Settings page, not by editing this var.\n ENABLE_SESSION_REVOCATION: z.string().default('true').transform(val => val === 'true'),\n AUTH_ENABLE_GOOGLE: z.string().default('true').transform(val => val === 'true'),\n AUTH_ENABLE_EMAIL_PASSWORD: z.string().default('true').transform(val => val === 'true'),\n AUTH_ENABLE_ONE_TAP: z.string().default('false').transform(val => val === 'true'),\n DB_DRIVER: z.enum(['pg', 'neon']).default('pg'),\n // Only relevant when DB_DRIVER=pg — whether the target Postgres server has SSL\n // enabled. Self-hosted Postgres (e.g. via Docker/Dokploy) typically does not.\n DATABASE_SSL: z.string().default('false').transform(val => val === 'true'),\n // With DATABASE_SSL=true the server certificate is verified. Set the CA (PEM,\n // \"\\n\" for newlines) for a self-signed or private CA; DATABASE_SSL_INSECURE=true\n // skips verification (encrypts only). Both are read in config/pg-ssl.ts.\n DATABASE_SSL_CA: z.string().default(''),\n DATABASE_SSL_INSECURE: z.string().default('false'),\n});\n","import \"server-only\";\nimport { envSchema } from './env-schema';\n\nconst results = envSchema.safeParse(process.env);\n\nif (results.success && (results.data.NODE_ENV === 'development')) {\n console.log('Environment variables loaded:', Object.keys(results.data));\n}\n\nif (!results.success) {\n console.error('Invalid environment variables:', results.error.format());\n throw new Error('Invalid environment variables');\n}\n\nexport const config = results.data;\n","// TLS options for the pg driver when DATABASE_SSL=true. Reads process.env\n// directly (not config/env) so the doctor script and apps whose local\n// env-schema predates these keys behave the same.\n//\n// Default: verify the server certificate (blocks a man-in-the-middle).\n// - DATABASE_SSL_CA: PEM of the CA that signed the server cert (use \"\\n\" for\n// newlines in a single-line env var), for self-signed or provider-private CAs.\n// - DATABASE_SSL_INSECURE=true: encrypt only, don't verify. Last resort.\nexport function pgSslOptions() {\n if (process.env.DATABASE_SSL_INSECURE === \"true\") return { rejectUnauthorized: false }\n const ca = process.env.DATABASE_SSL_CA?.replace(/\\\\n/g, \"\\n\")\n return { rejectUnauthorized: true, ...(ca ? { ca } : {}) }\n}\n","import 'server-only';\n\n// neon-http driver for production\nimport { neon, neonConfig } from '@neondatabase/serverless';\nimport { drizzle } from 'drizzle-orm/neon-http';\n\n// postgres driver for local development\nimport { drizzle as drizzlePg } from 'drizzle-orm/node-postgres';\nimport { Pool } from 'pg';\n\nimport * as schema from './schema';\nimport { config } from '../../config/env';\nimport { pgSslOptions } from '../../config/pg-ssl';\n\nimport type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';\n\n// Both drivers are PgDatabase; typing as the shared base keeps query-builder\n// calls (e.g. .returning(...)) well-typed instead of a driver union.\nlet db: PgDatabase<PgQueryResultHKT, typeof schema>\n\nif (config.DB_DRIVER === 'pg') {\n const pool = new Pool({\n connectionString: config.DATABASE_URL!,\n ssl: config.DATABASE_SSL ? pgSslOptions() : undefined,\n // pg waits forever by default; a hung DB would otherwise freeze every request (proxy reads settings).\n connectionTimeoutMillis: 5000,\n query_timeout: 15000, // roomy enough for the 10k-row exports\n });\n db = drizzlePg(pool, {\n schema,\n logger: process.env.NODE_ENV === 'development',\n });\n\n console.log('🟡 Using PostgreSQL (pg) driver');\n\n} else {\n // Fresh 15s signal (same as pg query_timeout) per request (a static signal passed to neon() would expire for good).\n // Global-only option, fine here: this is the only Neon client in the app.\n neonConfig.fetchFunction = (url: string, init?: RequestInit) =>\n fetch(url, { ...init, signal: AbortSignal.timeout(15_000) });\n const sql = neon(config.DATABASE_URL!);\n db = drizzle(sql, { schema, logger: process.env.NODE_ENV === 'development' });\n\n console.log('🟢 Using Neon (HTTP) driver');\n}\n// Query logging prints parameters (session/reset tokens, hashes): development only.\n\nexport { db }","//#region src/bytes.ts\nfunction toBufferSource(data) {\n\tif (typeof data === \"string\") return new TextEncoder().encode(data);\n\tif (!ArrayBuffer.isView(data)) return data;\n\tif (data.buffer instanceof ArrayBuffer) return data;\n\treturn new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();\n}\n/**\n* Converts strings and binary data into a `Uint8Array`.\n*\n* `ArrayBuffer` inputs share memory with the returned view, while number-based\n* `TypedArray` inputs are copied according to native constructor semantics.\n*\n* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#buffer | ArrayBuffer constructor behavior}\n* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray | TypedArray constructor behavior}\n*/\nfunction toUint8Array(data) {\n\tif (typeof data === \"string\") return new TextEncoder().encode(data);\n\treturn new Uint8Array(data);\n}\n//#endregion\nexport { toBufferSource, toUint8Array };\n","import { toUint8Array } from \"./bytes.mjs\";\n//#region src/base32.ts\n/**\n* Returns the Base32 alphabet based on the encoding type.\n* @param hex - Whether to use the hexadecimal Base32 alphabet.\n* @returns The appropriate Base32 alphabet.\n*/\nfunction getAlphabet(hex) {\n\treturn hex ? \"0123456789ABCDEFGHIJKLMNOPQRSTUV\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n}\n/**\n* Creates a decode map for the given alphabet.\n* @param alphabet - The Base32 alphabet.\n* @returns A map of characters to their corresponding values.\n*/\nfunction createDecodeMap(alphabet) {\n\tconst decodeMap = /* @__PURE__ */ new Map();\n\tfor (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i);\n\treturn decodeMap;\n}\n/**\n* Encodes a Uint8Array into a Base32 string.\n* @param data - The data to encode.\n* @param alphabet - The Base32 alphabet to use.\n* @param padding - Whether to include padding.\n* @returns The Base32 encoded string.\n*/\nfunction base32Encode(data, alphabet, padding) {\n\tlet result = \"\";\n\tlet buffer = 0;\n\tlet shift = 0;\n\tfor (const byte of data) {\n\t\tbuffer = buffer << 8 | byte;\n\t\tshift += 8;\n\t\twhile (shift >= 5) {\n\t\t\tshift -= 5;\n\t\t\tresult += alphabet[buffer >> shift & 31];\n\t\t}\n\t}\n\tif (shift > 0) result += alphabet[buffer << 5 - shift & 31];\n\tif (padding) {\n\t\tconst padCount = (8 - result.length % 8) % 8;\n\t\tresult += \"=\".repeat(padCount);\n\t}\n\treturn result;\n}\n/**\n* Decodes a Base32 string into a Uint8Array.\n* @param data - The Base32 encoded string.\n* @param alphabet - The Base32 alphabet to use.\n* @returns The decoded Uint8Array.\n*/\nfunction base32Decode(data, alphabet) {\n\tconst decodeMap = createDecodeMap(alphabet);\n\tconst result = [];\n\tlet buffer = 0;\n\tlet bitsCollected = 0;\n\tfor (const char of data) {\n\t\tif (char === \"=\") break;\n\t\tconst value = decodeMap.get(char);\n\t\tif (value === void 0) throw new Error(`Invalid Base32 character: ${char}`);\n\t\tbuffer = buffer << 5 | value;\n\t\tbitsCollected += 5;\n\t\twhile (bitsCollected >= 8) {\n\t\t\tbitsCollected -= 8;\n\t\t\tresult.push(buffer >> bitsCollected & 255);\n\t\t}\n\t}\n\treturn Uint8Array.from(result);\n}\n/**\n* Base32 encoding and decoding utility.\n*/\nconst base32 = {\n\t/**\n\t* Encodes data into a Base32 string.\n\t* @param data - The data to encode (ArrayBuffer, number-based TypedArray, or string).\n\t* @param options - Encoding options.\n\t* @returns The Base32 encoded string.\n\t*/\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(false);\n\t\treturn base32Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\t/**\n\t* Decodes a Base32 string into a Uint8Array.\n\t* @param data - The Base32 encoded string or ArrayBuffer/TypedArray.\n\t* @returns The decoded Uint8Array.\n\t*/\n\tdecode(data) {\n\t\tif (typeof data !== \"string\") data = new TextDecoder().decode(data);\n\t\tconst alphabet = getAlphabet(false);\n\t\treturn base32Decode(data, alphabet);\n\t}\n};\n/**\n* Base32hex encoding and decoding utility.\n*/\nconst base32hex = {\n\t/**\n\t* Encodes data into a Base32hex string.\n\t* @param data - The data to encode (ArrayBuffer, number-based TypedArray, or string).\n\t* @param options - Encoding options.\n\t* @returns The Base32hex encoded string.\n\t*/\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(true);\n\t\treturn base32Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\t/**\n\t* Decodes a Base32hex string into a Uint8Array.\n\t* @param data - The Base32hex encoded string.\n\t* @returns The decoded Uint8Array.\n\t*/\n\tdecode(data) {\n\t\treturn base32Decode(data, getAlphabet(true));\n\t}\n};\n//#endregion\nexport { base32, base32hex };\n","//#region src/index.ts\nfunction getWebcryptoSubtle() {\n\tconst cr = typeof globalThis !== \"undefined\" && globalThis.crypto;\n\tif (cr && typeof cr.subtle === \"object\" && cr.subtle != null) return cr.subtle;\n\tthrow new Error(\"crypto.subtle must be defined\");\n}\n//#endregion\nexport { getWebcryptoSubtle };\n","import { toUint8Array } from \"./bytes.mjs\";\n//#region src/base64.ts\nfunction getAlphabet(urlSafe) {\n\treturn urlSafe ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n}\nfunction base64Encode(data, alphabet, padding) {\n\tlet result = \"\";\n\tlet buffer = 0;\n\tlet shift = 0;\n\tfor (const byte of data) {\n\t\tbuffer = buffer << 8 | byte;\n\t\tshift += 8;\n\t\twhile (shift >= 6) {\n\t\t\tshift -= 6;\n\t\t\tresult += alphabet[buffer >> shift & 63];\n\t\t}\n\t}\n\tif (shift > 0) result += alphabet[buffer << 6 - shift & 63];\n\tif (padding) {\n\t\tconst padCount = (4 - result.length % 4) % 4;\n\t\tresult += \"=\".repeat(padCount);\n\t}\n\treturn result;\n}\nfunction base64Decode(data, alphabet) {\n\tconst decodeMap = /* @__PURE__ */ new Map();\n\tfor (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i);\n\tconst result = [];\n\tlet buffer = 0;\n\tlet bitsCollected = 0;\n\tfor (const char of data) {\n\t\tif (char === \"=\") break;\n\t\tconst value = decodeMap.get(char);\n\t\tif (value === void 0) throw new Error(`Invalid Base64 character: ${char}`);\n\t\tbuffer = buffer << 6 | value;\n\t\tbitsCollected += 6;\n\t\tif (bitsCollected >= 8) {\n\t\t\tbitsCollected -= 8;\n\t\t\tresult.push(buffer >> bitsCollected & 255);\n\t\t}\n\t}\n\treturn Uint8Array.from(result);\n}\nconst base64 = {\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(false);\n\t\treturn base64Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\tdecode(data) {\n\t\tif (typeof data !== \"string\") data = new TextDecoder().decode(data);\n\t\tconst alphabet = getAlphabet(data.includes(\"-\") || data.includes(\"_\"));\n\t\treturn base64Decode(data, alphabet);\n\t}\n};\nconst base64Url = {\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(true);\n\t\treturn base64Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\tdecode(data) {\n\t\treturn base64Decode(data, getAlphabet(data.includes(\"-\") || data.includes(\"_\")));\n\t}\n};\n//#endregion\nexport { base64, base64Url };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","import { toUint8Array } from \"./bytes.mjs\";\nimport { hexToBytes } from \"@noble/hashes/utils.js\";\n//#region src/hex.ts\nconst toBytes = (data) => hexToBytes(data);\nconst hex = {\n\tencode: (data) => {\n\t\tconst buffer = toUint8Array(data);\n\t\tif (buffer.byteLength === 0) return \"\";\n\t\tlet result = \"\";\n\t\tfor (const byte of buffer) result += byte.toString(16).padStart(2, \"0\");\n\t\treturn result;\n\t},\n\tdecode: (data) => {\n\t\tif (!data) return \"\";\n\t\tif (typeof data === \"string\") return new TextDecoder().decode(toBytes(data));\n\t\treturn new TextDecoder().decode(data);\n\t},\n\ttoBytes\n};\n//#endregion\nexport { hex };\n","import { getWebcryptoSubtle } from \"./index.mjs\";\nimport { toBufferSource } from \"./bytes.mjs\";\nimport { base64, base64Url } from \"./base64.mjs\";\nimport { hex } from \"./hex.mjs\";\n//#region src/hmac.ts\nconst createHMAC = (algorithm = \"SHA-256\", encoding = \"none\") => {\n\tconst hmac = {\n\t\timportKey: async (key, keyUsage) => {\n\t\t\treturn getWebcryptoSubtle().importKey(\"raw\", toBufferSource(key), {\n\t\t\t\tname: \"HMAC\",\n\t\t\t\thash: { name: algorithm }\n\t\t\t}, false, [keyUsage]);\n\t\t},\n\t\tsign: async (hmacKey, data) => {\n\t\t\tif (typeof hmacKey === \"string\") hmacKey = await hmac.importKey(hmacKey, \"sign\");\n\t\t\tconst signature = await getWebcryptoSubtle().sign(\"HMAC\", hmacKey, toBufferSource(data));\n\t\t\tif (encoding === \"hex\") return hex.encode(signature);\n\t\t\tif (encoding === \"base64\") return base64.encode(signature);\n\t\t\tif (encoding === \"base64url\" || encoding === \"base64urlnopad\") return base64Url.encode(signature, { padding: encoding !== \"base64urlnopad\" });\n\t\t\treturn signature;\n\t\t},\n\t\tverify: async (hmacKey, data, signature) => {\n\t\t\tif (typeof hmacKey === \"string\") hmacKey = await hmac.importKey(hmacKey, \"verify\");\n\t\t\tif (encoding === \"hex\") signature = typeof signature === \"string\" ? hex.toBytes(signature) : signature;\n\t\t\tif (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") signature = await base64.decode(signature);\n\t\t\treturn getWebcryptoSubtle().verify(\"HMAC\", hmacKey, toBufferSource(signature), toBufferSource(data));\n\t\t}\n\t};\n\treturn hmac;\n};\n//#endregion\nexport { createHMAC };\n","import { base32 } from \"./base32.mjs\";\nimport { createHMAC } from \"./hmac.mjs\";\n//#region src/otp.ts\nconst defaultPeriod = 30;\nconst defaultDigits = 6;\nconst hmac = createHMAC(\"SHA-1\");\n/**\n* loops over `expected.length` so timing never depends on input length\n*\n* @internal\n*/\nfunction constantTimeEqualOTP(input, expected) {\n\tlet difference = input.length ^ expected.length;\n\tfor (let i = 0; i < expected.length; i++) difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);\n\treturn difference === 0;\n}\nasync function generateHOTP(key, { counter, digits }) {\n\tconst _digits = digits ?? defaultDigits;\n\tif (_digits < 1 || _digits > 8) throw new TypeError(\"Digits must be between 1 and 8\");\n\tconst buffer = /* @__PURE__ */ new ArrayBuffer(8);\n\tnew DataView(buffer).setBigUint64(0, BigInt(counter), false);\n\tconst bytes = new Uint8Array(buffer);\n\tconst signature = await hmac.sign(key, bytes);\n\tconst hmacResult = new Uint8Array(signature);\n\tconst offset = hmacResult[hmacResult.length - 1] & 15;\n\treturn (((hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255) % 10 ** _digits).toString().padStart(_digits, \"0\");\n}\nasync function generateTOTP(key, options) {\n\tconst digits = options?.digits ?? defaultDigits;\n\tconst milliseconds = (options?.period ?? defaultPeriod) * 1e3;\n\treturn await generateHOTP(key, {\n\t\tcounter: Math.floor(Date.now() / milliseconds),\n\t\tdigits\n\t});\n}\nasync function verifyTOTP(otp, { window = 1, digits = defaultDigits, key, period = defaultPeriod }) {\n\tconst milliseconds = period * 1e3;\n\tconst counter = Math.floor(Date.now() / milliseconds);\n\tlet matched = false;\n\tfor (let i = -window; i <= window; i++) matched = constantTimeEqualOTP(otp, await generateHOTP(key, {\n\t\tcounter: counter + i,\n\t\tdigits\n\t})) || matched;\n\treturn matched;\n}\n/**\n* Generate a QR code URL for the OTP secret\n*/\nfunction generateQRCode({ issuer, account, secret, digits = defaultDigits, period = defaultPeriod }) {\n\tconst baseURI = `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`;\n\tconst params = new URLSearchParams({\n\t\tsecret: base32.encode(secret, { padding: false }),\n\t\tissuer\n\t});\n\tif (digits !== void 0) params.set(\"digits\", digits.toString());\n\tif (period !== void 0) params.set(\"period\", period.toString());\n\treturn `${baseURI}?${params.toString()}`;\n}\n/**\n* Strings are used as UTF-8 bytes.\n* Decode encoded secrets, such as Base32, before passing them in.\n*/\nconst createOTP = (secret, opts) => {\n\tconst digits = opts?.digits ?? defaultDigits;\n\tconst period = opts?.period ?? defaultPeriod;\n\treturn {\n\t\thotp: async (counter) => {\n\t\t\treturn generateHOTP(await hmac.importKey(secret, \"sign\"), {\n\t\t\t\tcounter,\n\t\t\t\tdigits\n\t\t\t});\n\t\t},\n\t\ttotp: async () => {\n\t\t\treturn generateTOTP(await hmac.importKey(secret, \"sign\"), {\n\t\t\t\tdigits,\n\t\t\t\tperiod\n\t\t\t});\n\t\t},\n\t\tverify: async (otp, options) => {\n\t\t\treturn verifyTOTP(otp, {\n\t\t\t\tkey: await hmac.importKey(secret, \"sign\"),\n\t\t\t\tdigits,\n\t\t\t\tperiod,\n\t\t\t\t...options\n\t\t\t});\n\t\t},\n\t\turl: (issuer, account) => {\n\t\t\treturn generateQRCode({\n\t\t\t\tissuer,\n\t\t\t\taccount,\n\t\t\t\tsecret,\n\t\t\t\tdigits,\n\t\t\t\tperiod\n\t\t\t});\n\t\t}\n\t};\n};\n//#endregion\nexport { createOTP };\n","import type { BetterAuthPlugin } from \"better-auth\"\nimport { APIError, createAuthMiddleware, getSessionFromCtx } from \"better-auth/api\"\nimport { symmetricDecrypt } from \"better-auth/crypto\"\nimport { twoFactor } from \"better-auth/plugins\"\nimport { createOTP } from \"@better-auth/utils/otp\"\n\n// better-auth only challenges 2FA after password sign-ins (/sign-in/email etc.), so a\n// user with TOTP on who signs in with Google or One Tap skips it. With challengeAfterOAuth\n// these paths get the challenge too. Passkey sign-in isn't: a passkey is already two factors.\nconst CHALLENGED_PATHS = [\"/callback/:id\", \"/one-tap/callback\"]\nconst CODE_REQUIRED_PATHS = [\"/two-factor/disable\", \"/two-factor/generate-backup-codes\"]\n\nexport type TwoFactorOptions = {\n /** Shown as the account label in authenticator apps. */\n issuer: string\n /**\n * For apps whose users may have no password (OAuth-only). Enabling 2FA then needs no\n * password, and disabling it or regenerating backup codes needs a current TOTP code\n * (sent as `code` in the body) instead. Default false: the password is required.\n */\n passwordless?: boolean\n /**\n * Also ask for the code after Google and One Tap sign-in, not just password sign-in.\n * The Google callback then redirects to /login/2fa?callbackUrl=…, so the app needs\n * that page. Default false (stock better-auth behaviour).\n */\n challengeAfterOAuth?: boolean\n}\n\n/**\n * TOTP 2FA, optionally passwordless and/or also enforced after Google and One Tap sign-in.\n * Returns two plugins; keep them together and in this order in `plugins`.\n */\nexport function twoFactorPlugins(\n baseURL: string,\n { issuer, passwordless = false, challengeAfterOAuth = false }: TwoFactorOptions,\n) {\n const plugin = twoFactor({ issuer, allowPasswordless: passwordless })\n\n // Reuse the plugin's own challenge hook (drop the new session, set the short-lived\n // 2FA cookie) on the extra paths instead of reimplementing it.\n if (challengeAfterOAuth) {\n const [challenge] = plugin.hooks.after\n plugin.hooks.after = [{\n ...challenge,\n matcher: (ctx) => challenge.matcher(ctx) || CHALLENGED_PATHS.includes(ctx.path ?? \"\"),\n }]\n }\n\n const extras = {\n id: \"two-factor-extras\",\n hooks: {\n // allowPasswordless lets disable / regenerate-backup-codes run on a session alone,\n // so anyone at an unlocked, signed-in browser could switch 2FA off. Require a\n // current authenticator code instead of the password the user doesn't have.\n before: passwordless ? [{\n matcher: (ctx) => CODE_REQUIRED_PATHS.includes(ctx.path ?? \"\"),\n handler: createAuthMiddleware(async (ctx) => {\n const session = await getSessionFromCtx(ctx)\n if (!session) return // the endpoint rejects it\n const code = (ctx.body as { code?: unknown } | undefined)?.code\n const row = await ctx.context.adapter.findOne<{ secret: string }>({\n model: \"twoFactor\",\n where: [{ field: \"userId\", value: session.user.id }],\n })\n const valid =\n typeof code === \"string\" && !!row &&\n (await createOTP(await symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret })).verify(code))\n if (!valid) throw new APIError(\"UNAUTHORIZED\", { message: \"Enter the current code from your authenticator app\" })\n }),\n }] : [],\n // The challenge answers with JSON ({ twoFactorRedirect: true }), which One Tap's\n // caller handles. The Google callback is a browser redirect, so turn it into a\n // redirect to /login/2fa, keeping where the user was headed (same-origin only).\n after: challengeAfterOAuth ? [{\n matcher: (ctx) => ctx.path === \"/callback/:id\",\n handler: createAuthMiddleware(async (ctx) => {\n const returned = ctx.context.returned as { twoFactorRedirect?: boolean } | undefined\n if (!returned?.twoFactorRedirect) return\n const target = new URL(ctx.context.responseHeaders?.get(\"location\") ?? \"/dashboard\", baseURL)\n const callbackUrl =\n target.origin === new URL(baseURL).origin ? target.pathname + target.search : \"/dashboard\"\n throw ctx.redirect(`/login/2fa?callbackUrl=${encodeURIComponent(callbackUrl)}`)\n }),\n }] : [],\n },\n } satisfies BetterAuthPlugin\n\n return [plugin, extras] as const\n}\n","import \"server-only\"\nimport { sql } from \"drizzle-orm\"\nimport { db } from \"../../server/db\"\nimport { activityLogs } from \"../../server/db/schema\"\n\nexport type ActivityAction =\n | 'login'\n | 'logout'\n | 'login_failed'\n | 'password_changed'\n | 'email_changed'\n | 'profile_updated'\n | 'session_revoked'\n | 'user_deleted'\n | 'user_banned'\n | 'user_unbanned'\n | 'role_changed'\n | 'impersonation_started'\n | 'impersonation_stopped'\n | 'settings_changed'\n | 'passkey_added'\n | 'passkey_removed'\n\nexport interface LogActivityParams {\n userId: string\n action: ActivityAction\n description: string\n ipAddress?: string | null\n userAgent?: string | null\n metadata?: Record<string, any>\n // Populated on 'login' events only — see server/auth.ts's session.create hook.\n referrerUrl?: string | null\n os?: string | null\n browser?: string | null\n deviceType?: string | null\n country?: string | null\n city?: string | null\n}\n\n/** Signature for createAuth({ logActivity }): an app-supplied writer for these entries. */\nexport type ActivityLogger = (entry: LogActivityParams) => Promise<void>\n\nexport async function logActivity({\n userId,\n action,\n description,\n ipAddress,\n userAgent,\n metadata,\n referrerUrl,\n os,\n browser,\n deviceType,\n country,\n city,\n}: LogActivityParams) {\n try {\n await db.insert(activityLogs).values({\n userId,\n // Snapshot the email at write time; survives deletion of the user row.\n actorEmail: sql`(select \"email\" from \"user\" where \"id\" = ${userId})`,\n action,\n description,\n ipAddress: ipAddress || null,\n userAgent: userAgent || null,\n metadata: metadata ? JSON.stringify(metadata) : null,\n referrerUrl: referrerUrl || null,\n os: os || null,\n browser: browser || null,\n deviceType: deviceType || null,\n country: country || null,\n city: city || null,\n })\n } catch (error) {\n console.error('Failed to log activity:', error)\n // Don't throw - activity logging should not break the app\n }\n}\n","import \"server-only\"\nimport { UAParser } from \"ua-parser-js\"\nimport geoip from \"geoip-lite\"\n\nconst countryNames = new Intl.DisplayNames([\"en\"], { type: \"region\" })\n\nexport type DeviceType = \"desktop\" | \"mobile\" | \"tablet\"\n\nexport interface DeviceInfo {\n os: string | null\n browser: string | null\n deviceType: DeviceType\n}\n\nexport interface GeoInfo {\n country: string | null\n city: string | null\n}\n\n/**\n * Proxies append the address they saw to X-Forwarded-For, so the LAST entry\n * is the one our own proxy added; earlier entries are caller-supplied and\n * spoofable (they'd let an attacker dodge or frame an IP in the throttle).\n * Falls back to x-real-ip, then null (local dev with no proxy).\n * shortcut: assumes exactly one trusted proxy hop, so behind a CDN plus a\n * proxy the last entry is the CDN's address; revisit if you stack proxies.\n */\nexport function getClientIp(headers: Headers | undefined | null): string | null {\n const forwardedFor = headers?.get(\"x-forwarded-for\")\n if (forwardedFor) return forwardedFor.split(\",\").at(-1)!.trim()\n\n return headers?.get(\"x-real-ip\") ?? null\n}\n\nexport function parseUserAgent(userAgent: string | null | undefined): DeviceInfo {\n if (!userAgent) {\n return { os: null, browser: null, deviceType: \"desktop\" }\n }\n\n const { os, browser, device } = new UAParser(userAgent).getResult()\n\n return {\n os: os.name ? [os.name, os.version].filter(Boolean).join(\" \") : null,\n browser: browser.name ?? null,\n deviceType: device.type === \"mobile\" || device.type === \"tablet\" ? device.type : \"desktop\",\n }\n}\n\n/**\n * Offline lookup (geoip-lite ships its own IP-range database, no network\n * call) — resolves to nulls for private/local addresses like 127.0.0.1.\n */\nexport function lookupGeoLocation(ipAddress: string | null | undefined): GeoInfo {\n if (!ipAddress) return { country: null, city: null }\n\n const geo = geoip.lookup(ipAddress)\n if (!geo) return { country: null, city: null }\n\n let country: string | null = geo.country || null\n if (country) {\n try {\n country = countryNames.of(country) ?? country\n } catch {\n // Unrecognized region code — keep the raw code rather than losing it.\n }\n }\n\n return { country, city: geo.city || null }\n}\n\nexport function formatDeviceInfo({ os, browser, deviceType }: DeviceInfo): string {\n const label = [browser, os].filter(Boolean).join(\" on \")\n const typeLabel = deviceType === \"mobile\" ? \"Mobile\" : deviceType === \"tablet\" ? \"Tablet\" : \"Desktop\"\n\n return label ? `${label} · ${typeLabel}` : `Unknown device · ${typeLabel}`\n}\n\nexport function formatLocation({ country, city }: GeoInfo): string {\n if (!country && !city) return \"Unknown\"\n\n return [city, country].filter(Boolean).join(\", \")\n}\n","// Shared cookie/header names used by both client components and server/auth.ts\n// — no \"server-only\" guard, since both sides need them.\n\n// Stashes the page a social sign-in was initiated from, so the login-activity\n// log shows the real referrer instead of the OAuth provider's own domain\n// (e.g. accounts.google.com) once the browser redirects back.\nexport const LOGIN_REFERRER_COOKIE = 'login_referrer'\n\n// Carries the client's FingerprintJS visitorId on /sign-in/email and\n// /sign-up/email requests — the key for the per-device abuse throttle\n// (see lib/auth-throttle.ts). A header, not a cookie, so it's only sent on\n// the auth calls that need it, not every request.\nexport const DEVICE_FINGERPRINT_HEADER = 'x-device-fingerprint'\n\n// The visitor's cookie choice (lib/cookie-consent.ts): \"all\", \"necessary\", or\n// a comma list of the purposes they ticked under \"Customize\", e.g.\n// \"fingerprint\" — one choice per purpose, as regulators like the CNIL expect.\nexport const COOKIE_CONSENT_COOKIE = 'cookie_consent'\n\n// \"fingerprint\": FingerprintJS device id (new-device alerts, sign-in throttle,\n// shared-device detection, admin Devices card). \"onetap\": Google One Tap,\n// whose script may set Google's own cookies.\nexport type ConsentPurpose = 'fingerprint' | 'onetap'\nexport const CONSENT_PURPOSES: ConsentPurpose[] = ['fingerprint', 'onetap']\n\n// Version of the consent wording (banner text + privacy page purposes),\n// stored with each consent record (consent_log.version) so you can show which\n// text a user agreed to. Bump it when that wording changes materially.\nexport const CONSENT_VERSION = 1\n\n// A well-formed cookie_consent value: \"all\", \"necessary\", or a comma list of\n// known purposes. Used to validate what the client sends to app/api/consent.\nexport function isValidConsent(value: unknown): value is string {\n if (value === 'all' || value === 'necessary') return true\n if (typeof value !== 'string' || !value) return false\n const parts = value.split(',')\n return new Set(parts).size === parts.length && parts.every((p) => (CONSENT_PURPOSES as string[]).includes(p))\n}\n\n// Does a cookie_consent value allow this purpose? Plain function, no React,\n// so route handlers can use it too (app/api/device-check).\nexport function consentAllows(value: string | null | undefined, purpose: ConsentPurpose): boolean {\n if (value === 'all') return true\n if (!value || value === 'necessary') return false\n return value.split(',').includes(purpose)\n}\n\n// Consent mode, set by proxy.ts from the admin's System Settings toggle\n// (\"1\" = consent required, \"0\" = not). Read by lib/cookie-consent.ts.\nexport const CONSENT_REQUIRED_COOKIE = 'consent_required'\n\n// FingerprintJS signals that are never sent or stored. Accessibility\n// preferences can hint at a disability (GDPR Art. 9 health data); colorGamut\n// mostly tracks display hardware but is read alongside them. Filtered on the\n// client (lib/device-fingerprint.ts) and again on the server\n// (app/api/device-check), since the client can't be trusted.\nexport const EXCLUDED_SIGNALS = new Set([\n 'reducedMotion', 'reducedTransparency', 'contrast', 'forcedColors',\n 'invertedColors', 'monochrome', 'colorGamut',\n])\n","// The one place the site's base URL is decided (auth callbacks, passkey\n// origin, email links, redirect guard). BETTER_AUTH_URL wins because that's\n// the variable the setup docs, doctor and scaffolder fill in; the others are\n// legacy/fallback. No server-only imports, so tests can use it.\nexport function getBaseUrl(): string {\n const url =\n process.env.BETTER_AUTH_URL ||\n process.env.NEXTAUTH_URL ||\n process.env.NEXT_PUBLIC_APP_URL ||\n \"http://localhost:3000\"\n return url.replace(/\\/+$/, \"\")\n}\n","import { sql } from \"drizzle-orm\"\nimport { users } from \"../../server/db/schema\"\n\n/**\n * SQL condition: \"after removing `excludeIds` (delete, demote or ban), at least\n * one other active (admin, not banned) account remains\". Put it in the WHERE of\n * the write itself so check and write are one statement. The subquery row-locks\n * every active admin, so two admins banning/demoting/deleting each other at\n * once serialize: the second re-reads after the first commits and is refused.\n * One statement also works on the neon-http driver (no transactions).\n * Callers treat \"0 rows written\" as the last-admin refusal.\n */\nexport function otherActiveAdminExists(excludeIds: string[]) {\n const ids = sql.join(excludeIds.map((id) => sql`${id}`), sql`, `)\n return sql`(select count(*) from (select ${users.id} as id from ${users} where ${users.role} = 'admin' and ${users.banned} = false for update) a where a.id not in (${ids})) > 0`\n}\n","// Pure throttle policy — no DB, no `server-only`, so it stays unit-testable.\n// Consumed by lib/auth-throttle.ts (the DB plumbing) and its test.\n\n// Tune per deployment, or lift to env vars if you need it configurable.\nexport const WINDOW_MS = 15 * 60 * 1000 // how long attempts accumulate\nexport const MAX = 10 // failed sign-ins / sign-ups per window before a 429, per fingerprint\n\n// Backstop cap keyed by IP instead of fingerprint — the fingerprint header is\n// client-supplied and unsigned, so it's trivial to omit or randomize per\n// request (see server/auth.ts before-hook). Higher than MAX because an IP can\n// be shared behind NAT/CGNAT/VPN.\n// ponytail: flat multiplier, not a real per-deployment tuning — revisit if\n// legitimate shared-IP traffic ever gets caught in it.\nexport const MAX_IP = MAX * 3\n\n// Rows untouched this long are deleted (lib/auth-throttle.ts). They hold IP,\n// user agent and the last email typed — often for people with no account — so\n// GDPR storage limitation says don't keep them past their use.\nexport const RETENTION_MS = 30 * 24 * 60 * 60 * 1000\n\n// A row whose window has already elapsed counts as \"no row\" — it resets on\n// the next attempt (see recordDeviceAttempt), so the device isn't blocked in\n// the meantime.\nexport function isOverLimit(\n row: { count: number; windowStart: Date } | undefined,\n now: number,\n max: number = MAX,\n): boolean {\n if (!row) return false\n if (now - row.windowStart.getTime() >= WINDOW_MS) return false\n return row.count >= max\n}\n","import \"server-only\"\nimport { eq, lt, sql } from \"drizzle-orm\"\nimport { db } from \"../../server/db\"\nimport { authThrottle } from \"../../server/db/schema\"\nimport { RETENTION_MS, WINDOW_MS, isOverLimit } from \"./throttle-limits\"\n\n// Is this key (device fingerprint, or \"ip:<address>\" backstop) currently over\n// the cap? Read-only — the caller (server/auth.ts before-hook) decides\n// whether to 429.\nexport async function isDeviceThrottled(fingerprint: string, max?: number): Promise<boolean> {\n try {\n const [row] = await db\n .select({ count: authThrottle.count, windowStart: authThrottle.windowStart })\n .from(authThrottle)\n .where(eq(authThrottle.fingerprint, fingerprint))\n .limit(1)\n return isOverLimit(row, Date.now(), max)\n } catch (error) {\n // Fail open — a throttle-store hiccup must never lock everyone out of sign-in.\n console.error(\"auth-throttle read failed, allowing request\", error)\n return false\n }\n}\n\nexport type AttemptMeta = {\n ipAddress: string | null\n userAgent: string | null\n email: string | null\n kind: \"signin\" | \"signup\"\n}\n\n// Atomic upsert: new row at 1, +1 within the live window, or reset to 1 when\n// the previous window has elapsed. One statement, so a device hammering the\n// endpoint (the whole point) can't race its own counter. The meta fields are\n// overwritten every time — they're \"last seen from this device\", for the\n// admin panel's block-list view (lib/admin-queries.ts).\nexport async function recordDeviceAttempt(fingerprint: string, meta: AttemptMeta): Promise<void> {\n const now = new Date()\n const cutoff = new Date(now.getTime() - WINDOW_MS)\n const seen = {\n lastAttemptAt: now,\n ipAddress: meta.ipAddress,\n userAgent: meta.userAgent,\n lastEmail: meta.email,\n lastKind: meta.kind,\n }\n try {\n await db\n .insert(authThrottle)\n .values({ fingerprint, count: 1, windowStart: now, ...seen })\n .onConflictDoUpdate({\n target: authThrottle.fingerprint,\n set: {\n // ISO strings, not Dates: pg sends a raw Date as server-local time, which a\n // tz-less `timestamp` column (stored as UTC) misreads on any non-UTC host.\n count: sql`case when ${authThrottle.windowStart} < ${cutoff.toISOString()} then 1 else ${authThrottle.count} + 1 end`,\n windowStart: sql`case when ${authThrottle.windowStart} < ${cutoff.toISOString()} then ${now.toISOString()} else ${authThrottle.windowStart} end`,\n ...seen,\n },\n })\n } catch (error) {\n console.error(\"auth-throttle write failed\", error)\n }\n await pruneStaleRows(now)\n}\n\n// Retention sweep piggybacked on the write path, so no cron is needed.\n// ponytail: runs at most hourly per server instance, and only when someone\n// attempts a sign-in — a site with zero attempts keeps stale rows until the\n// next one. Call pruneStaleRows() from a cron if you need a hard guarantee.\nconst PRUNE_EVERY_MS = 60 * 60 * 1000\nlet lastPrune = 0\n\nexport async function pruneStaleRows(now = new Date()): Promise<void> {\n if (now.getTime() - lastPrune < PRUNE_EVERY_MS) return\n lastPrune = now.getTime()\n try {\n await db\n .delete(authThrottle)\n .where(lt(authThrottle.lastAttemptAt, new Date(now.getTime() - RETENTION_MS)))\n } catch (error) {\n console.error(\"auth-throttle prune failed\", error)\n }\n}\n","import \"server-only\"\nimport { db } from \"../../../server/db\"\nimport { systemSettings } from \"../../../server/db/schema\"\nimport { config } from \"../../../config/env\"\nimport { eq } from \"drizzle-orm\"\nimport { DEFAULT_MAINTENANCE_EXEMPT_PATHS } from \"../../config/maintenance\"\n\nconst SETTINGS_ROW_ID = \"default\"\n// Short TTL: cheap reads (no DB round trip on every request), while an\n// admin's change is guaranteed live within this window even for a reader\n// that isn't the one who just saved (invalidateSystemSettingsCache() makes\n// it instant for that request's own process).\nconst CACHE_TTL_MS = 10_000\nconst FAILURE_CACHE_TTL_MS = 5_000\n\nexport type SystemSettings = typeof systemSettings.$inferSelect\n\nlet cached: { value: SystemSettings; expiresAt: number } | null = null\n\n// Fail-open shape if the DB is unreachable: auth flags fall back to their\n// config/env.ts defaults (unchanged behavior), maintenance mode is always\n// off — a DB hiccup must never lock out the whole site, including admins.\nfunction fallbackSettings(): SystemSettings {\n return {\n id: SETTINGS_ROW_ID,\n maintenanceMode: false,\n maintenanceMessage: null,\n maintenanceExemptPaths: DEFAULT_MAINTENANCE_EXEMPT_PATHS,\n authEnableGoogle: config.AUTH_ENABLE_GOOGLE,\n authEnableEmailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,\n authEnableOneTap: config.AUTH_ENABLE_ONE_TAP,\n enableSessionRevocation: config.ENABLE_SESSION_REVOCATION,\n feedbackAttachErrors: true,\n consentRequired: null,\n updatedAt: new Date(0),\n updatedBy: null,\n }\n}\n\nasync function loadOrSeed(): Promise<SystemSettings> {\n const existing = await db\n .select()\n .from(systemSettings)\n .where(eq(systemSettings.id, SETTINGS_ROW_ID))\n .limit(1)\n if (existing[0]) return existing[0]\n\n // Lazy-seed on first read, from the *current* env config — not the\n // schema's hardcoded column defaults — so turning this feature on never\n // silently flips an already-deployed flag (e.g. a prod deploy that\n // already set AUTH_ENABLE_GOOGLE=false).\n const seeded = await db\n .insert(systemSettings)\n .values({\n id: SETTINGS_ROW_ID,\n maintenanceMode: false,\n authEnableGoogle: config.AUTH_ENABLE_GOOGLE,\n authEnableEmailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,\n authEnableOneTap: config.AUTH_ENABLE_ONE_TAP,\n enableSessionRevocation: config.ENABLE_SESSION_REVOCATION,\n })\n .onConflictDoNothing()\n .returning()\n\n if (seeded[0]) return seeded[0]\n\n // Lost the seed race to a concurrent first-reader.\n const retry = await db\n .select()\n .from(systemSettings)\n .where(eq(systemSettings.id, SETTINGS_ROW_ID))\n .limit(1)\n return retry[0] ?? fallbackSettings()\n}\n\nexport async function getSystemSettings(): Promise<SystemSettings> {\n const now = Date.now()\n if (cached && cached.expiresAt > now) return cached.value\n\n try {\n const value = await loadOrSeed()\n cached = { value, expiresAt: now + CACHE_TTL_MS }\n return value\n } catch (error) {\n console.error(\"Failed to load system settings, failing open:\", error)\n // Cache the fallback briefly so a down DB isn't retried (and waited on) by every request.\n const value = fallbackSettings()\n cached = { value, expiresAt: now + FAILURE_CACHE_TTL_MS }\n return value\n }\n}\n\nexport function invalidateSystemSettingsCache() {\n cached = null\n}\n\nexport type SystemSettingsPatch = Partial<Pick<SystemSettings,\n | 'maintenanceMode' | 'maintenanceMessage' | 'maintenanceExemptPaths'\n | 'authEnableGoogle' | 'authEnableEmailPassword' | 'authEnableOneTap'\n | 'enableSessionRevocation' | 'feedbackAttachErrors' | 'consentRequired'\n>>\n\nexport async function updateSystemSettings(\n patch: SystemSettingsPatch,\n updatedBy: string\n): Promise<SystemSettings> {\n await loadOrSeed() // ensure the row exists even if nobody's read it yet\n\n const [updated] = await db\n .update(systemSettings)\n .set({ ...patch, updatedAt: new Date(), updatedBy })\n .where(eq(systemSettings.id, SETTINGS_ROW_ID))\n .returning()\n\n invalidateSystemSettingsCache()\n return updated\n}\n\n// Effective auth-method visibility = deploy-time \"configured\" (env, decides\n// whether the provider is even registered with better-auth — see\n// server/auth.ts's createAuth()) AND runtime \"offered\" (this DB flag).\nexport async function getEffectiveAuthFlags() {\n const settings = await getSystemSettings()\n return {\n google: config.AUTH_ENABLE_GOOGLE && settings.authEnableGoogle,\n emailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD && settings.authEnableEmailPassword,\n oneTap: config.AUTH_ENABLE_ONE_TAP && settings.authEnableOneTap,\n }\n}\n\n// Consent mode: the admin's choice if they've made one, else the\n// NEXT_PUBLIC_COOKIE_BANNER default (banner on unless it's \"false\").\nexport function isConsentRequired(settings: Pick<SystemSettings, 'consentRequired'>): boolean {\n return settings.consentRequired ?? process.env.NEXT_PUBLIC_COOKIE_BANNER !== \"false\"\n}\n\n// What each admin-settings control needs from the environment before its\n// toggle can do anything. Add an entry here when you add a control that depends\n// on env vars; the System Settings page then shows it disabled, with a badge and\n// the reason, until the deployment provides them. Controls with no entry\n// are always usable.\n// flag: an AUTH_ENABLE_*-style switch that must be on\n// keys: every group must be satisfied; within a group any one variable is enough\n// (aliases, or \"this or that\"). The first name in a group is the one shown.\n// Read lazily so NEXT_PUBLIC_* / env values are looked at when the page renders.\ntype Requirement = { flag?: [name: string, on: boolean]; keys?: string[][] }\n\nconst CONTROL_REQUIREMENTS: Record<string, () => Requirement> = {\n authEnableGoogle: () => ({\n flag: [\"AUTH_ENABLE_GOOGLE\", config.AUTH_ENABLE_GOOGLE],\n keys: [[\"AUTH_GOOGLE_ID\", \"GOOGLE_CLIENT_ID\"], [\"AUTH_GOOGLE_SECRET\", \"GOOGLE_CLIENT_SECRET\"]],\n }),\n authEnableEmailPassword: () => ({\n flag: [\"AUTH_ENABLE_EMAIL_PASSWORD\", config.AUTH_ENABLE_EMAIL_PASSWORD],\n }),\n authEnableOneTap: () => ({\n flag: [\"AUTH_ENABLE_ONE_TAP\", config.AUTH_ENABLE_ONE_TAP],\n keys: [[\"NEXT_PUBLIC_GOOGLE_CLIENT_ID\"], [\"NEXT_PUBLIC_AUTH_ENABLE_ONE_TAP=true\"]],\n }),\n // The toggle only matters once feedback has somewhere to go.\n feedbackAttachErrors: () => ({\n keys: [[\"FEEDBACK_DISCORD_WEBHOOK_URL\", \"FEEDBACK_EMAIL\"]],\n }),\n}\n\nexport type ControlStatus =\n | { ok: true }\n | { ok: false; kind: \"flag\" | \"keys\"; reason: string }\n\nexport function getControlStatuses(): Record<string, ControlStatus> {\n const isSet = (name: string) =>\n name.includes(\"=\") ? process.env[name.split(\"=\")[0]] === name.split(\"=\")[1] : Boolean(process.env[name])\n const out: Record<string, ControlStatus> = {}\n for (const [key, build] of Object.entries(CONTROL_REQUIREMENTS)) {\n const req = build()\n if (req.flag && !req.flag[1]) {\n out[key] = { ok: false, kind: \"flag\", reason: `Not configured for this deployment. Set ${req.flag[0]}=true to unlock this toggle.` }\n continue\n }\n const missing = (req.keys ?? []).filter((group) => !group.some(isSet)).map((group) => group.join(\" or \"))\n out[key] = missing.length\n ? {\n ok: false,\n kind: \"keys\",\n reason: `Missing environment variable${missing.length > 1 ? \"s\" : \"\"}: ${missing.join(\", \")}. Add ${missing.length > 1 ? \"them\" : \"it\"} and redeploy to unlock this toggle (NEXT_PUBLIC_ values need a rebuild).`,\n }\n : { ok: true }\n }\n return out\n}\n\nexport function getConfiguredAuthFlags() {\n return {\n google: config.AUTH_ENABLE_GOOGLE,\n emailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,\n oneTap: config.AUTH_ENABLE_ONE_TAP,\n }\n}\n","import \"server-only\"\nimport type { Resend } from \"resend\"\nimport { config } from \"@/config/env\"\n\n// From env, not hardcoded: scaffolded apps run this module from the package's\n// bundled auth, so a local edit here would never reach their auth emails.\nexport const EMAIL_FROM = config.EMAIL_FROM\n\n// Loaded on first send, so projects that never send email don't pay for it\n// at startup.\nlet resend: Resend | undefined\nexport async function getResend() {\n if (!resend) {\n const { Resend } = await import(\"resend\")\n resend = new Resend(config.RESEND_API_KEY)\n }\n return resend\n}\n\n// Broadcasts need a full access key, so they can use their own and leave\n// RESEND_API_KEY as a sending-only key.\nexport const BROADCAST_API_KEY = config.RESEND_BROADCAST_API_KEY || config.RESEND_API_KEY\n\nlet broadcastResend: Resend | undefined\nexport async function getBroadcastResend() {\n if (!broadcastResend) {\n const { Resend } = await import(\"resend\")\n broadcastResend = new Resend(BROADCAST_API_KEY)\n }\n return broadcastResend\n}\n","import \"server-only\"\nimport { betterAuth, type BetterAuthOptions, type BetterAuthPlugin } from \"better-auth\"\nimport { drizzleAdapter } from \"better-auth/adapters/drizzle\"\nimport { createId } from \"@paralleldrive/cuid2\"\nimport { eq, sql } from \"drizzle-orm\"\nimport { db } from \"./db\"\nimport { users, accounts, sessions, verifications, twoFactors, passkeys } from \"./db/schema\"\nimport { config } from \"@/config/env\"\nimport { oneTap, admin as adminPlugin } from \"better-auth/plugins\";\nimport { twoFactorPlugins } from \"@/lib/auth/two-factor\"\nimport { passkey } from \"@better-auth/passkey\";\nimport { createAuthMiddleware, getSessionFromCtx, APIError } from \"better-auth/api\"\nimport { logActivity, type ActivityLogger } from \"@/lib/security/activity-logger\"\nimport { getClientIp, parseUserAgent, lookupGeoLocation, formatDeviceInfo, formatLocation } from \"@/lib/utils/request-info\"\nimport { LOGIN_REFERRER_COOKIE, DEVICE_FINGERPRINT_HEADER } from \"@/lib/security/cookie-names\"\nimport { getBaseUrl } from \"@/lib/auth/base-url\"\nimport { otherActiveAdminExists } from \"@/lib/auth/last-admin\"\nimport { isDeviceThrottled, recordDeviceAttempt } from \"@/lib/auth/throttle\"\nimport { MAX_IP } from \"@/lib/auth/throttle-limits\"\nimport { getEffectiveAuthFlags } from \"@/lib/db/queries/settings\"\nimport { getResend, EMAIL_FROM } from \"@/lib/email/resend\"\n// Email templates are imported lazily where they're sent, so\n// @react-email/components only loads when an email goes out.\n\ntype AuthMiddleware = ReturnType<typeof createAuthMiddleware>\ntype DatabaseHooks = NonNullable<BetterAuthOptions[\"databaseHooks\"]>\ntype CreateAfter<M extends \"user\" | \"session\"> = NonNullable<NonNullable<NonNullable<DatabaseHooks[M]>[\"create\"]>[\"after\"]>\n\nexport type AuthOverrides = {\n // Merged with (not replacing) the default `google` provider below, so\n // consuming projects can add e.g. `apple` without forking this file.\n socialProviders?: BetterAuthOptions[\"socialProviders\"]\n /** App hooks. They run after the package's own hooks, so its guards still apply. */\n hooks?: { before?: AuthMiddleware; after?: AuthMiddleware }\n /** App database hooks, run after the package's own (e.g. start a trial on signup). */\n databaseHooks?: {\n user?: { create?: { after?: CreateAfter<\"user\"> } }\n session?: { create?: { after?: CreateAfter<\"session\"> } }\n }\n /** Extra better-auth plugins, appended after the package's. */\n plugins?: BetterAuthPlugin[]\n /** e.g. crossSubDomainCookies when login and marketing live on different subdomains. */\n advanced?: Pick<NonNullable<BetterAuthOptions[\"advanced\"]>, \"crossSubDomainCookies\">\n /** better-auth's rate limiter (off outside production by default). */\n rateLimit?: BetterAuthOptions[\"rateLimit\"]\n twoFactor?: {\n /**\n * For apps whose users have no password (OAuth-only). Enabling 2FA needs no\n * password; disabling it or regenerating backup codes needs a current TOTP `code`.\n */\n passwordless?: boolean\n /**\n * Also ask for the code after Google and One Tap sign-in (stock better-auth only\n * asks after email/password). Needs the /login/2fa page. Default false.\n */\n challengeAfterOAuth?: boolean\n }\n /** Admins can sign in as a user (\"impersonate\"). Default true. */\n impersonation?: boolean\n /** Self-service \"Delete account\" (better-auth's /delete-user). Default true. */\n deleteUser?: boolean\n /**\n * Writes the package's auth activity entries (login, failed login, passkey added /\n * removed, impersonation) instead of its own logger. Use it when your activity table\n * needs your own connection, e.g. it has row-level security the package's `db` can't pass.\n */\n logActivity?: ActivityLogger\n}\n\n// A failed credential sign-in, written to the activity feed — but only when\n// the attempted email maps to a real account (activityLogs.userId is NOT\n// NULL, and a miss has no user to attribute the row to). Best-effort: runs\n// in an after-hook and must never disturb the sign-in response.\nasync function logFailedLogin(ctx: { body?: unknown; headers?: Headers | null }, log: ActivityLogger) {\n try {\n const raw = (ctx.body as { email?: unknown } | undefined)?.email\n const email = typeof raw === \"string\" ? raw.toLowerCase() : null\n if (!email) return\n\n const [user] = await db\n .select({ id: users.id })\n .from(users)\n .where(eq(users.email, email))\n .limit(1)\n if (!user) return\n\n await log({\n userId: user.id,\n action: \"login_failed\",\n description: \"Failed login attempt\",\n ipAddress: getClientIp(ctx.headers),\n userAgent: ctx.headers?.get(\"user-agent\") ?? null,\n })\n } catch (error) {\n console.error(\"Failed to log login_failed activity\", error)\n }\n}\n\n// Email the account owner that a passkey was added or removed. Runs from the\n// auth `after` hook on a successful /passkey/verify-registration or\n// /passkey/delete-passkey; best-effort — a mail failure must not fail the\n// endpoint. Also written to the activity feed. Self-disables when Resend\n// isn't configured.\nasync function notifyPasskeyChange(\n ctx: Parameters<Parameters<typeof createAuthMiddleware>[0]>[0],\n action: \"added\" | \"removed\",\n log: ActivityLogger,\n) {\n try {\n const session = await getSessionFromCtx(ctx)\n const user = session?.user\n if (!user) return\n\n const ip = getClientIp(ctx.headers)\n\n await log({\n userId: user.id,\n action: action === \"added\" ? \"passkey_added\" : \"passkey_removed\",\n description: `Passkey ${action}`,\n ipAddress: ip,\n userAgent: ctx.headers?.get(\"user-agent\") ?? null,\n })\n\n if (!config.RESEND_API_KEY) return\n\n const { EmailTemplatePasskeyChange } = await import(\"@/components/email/security/passkey-changed\")\n await (await getResend()).emails.send({\n from: EMAIL_FROM,\n to: [user.email],\n subject: action === \"added\" ? \"A passkey was added to your account\" : \"A passkey was removed from your account\",\n react: EmailTemplatePasskeyChange({\n firstName: user.name || \"there\",\n action,\n device: formatDeviceInfo(parseUserAgent(ctx.headers?.get(\"user-agent\") ?? null)),\n location: formatLocation(lookupGeoLocation(ip)),\n ipAddress: ip || \"Unknown\",\n when: new Date().toUTCString(),\n manageUrl: `${getBaseUrl()}/dashboard/settings`,\n }),\n })\n } catch (error) {\n console.error(\"Failed to send passkey-change notification\", error)\n }\n}\n\n// The package's own sign-in bookkeeping: last-login time and the login activity entry.\n// Every new session row corresponds to a sign-in (credential or OAuth) — use that as\n// the \"last logged in\" signal rather than session updates, which also fire on\n// cookie-cache refresh / expiry extension.\nasync function packageSessionCreated(log: ActivityLogger, ...[session, context]: Parameters<CreateAfter<\"session\">>) {\n // Impersonation sessions (created by the admin plugin's\n // impersonateUser endpoint) also go through session.create —\n // don't let \"an admin looked at this account\" show up as the\n // user's own last login, and log it as an audit event instead.\n const impersonatedBy = (session as { impersonatedBy?: string | null }).impersonatedBy\n if (impersonatedBy) {\n const target = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.id, session.userId))\n .limit(1)\n\n await log({\n userId: impersonatedBy,\n action: 'impersonation_started',\n description: `Admin started impersonating ${target[0]?.email ?? session.userId}`,\n metadata: { impersonatedUserId: session.userId },\n })\n return\n }\n\n try {\n await db\n .update(users)\n .set({ lastLoginAt: new Date() })\n .where(eq(users.id, session.userId))\n } catch (error) {\n console.error(\"Failed to update lastLoginAt\", error)\n }\n\n try {\n const headers = context?.headers\n const ipAddress = getClientIp(headers)\n const userAgent = headers?.get('user-agent') ?? null\n // For OAuth, the live referer header on this request is the\n // provider's own callback page (e.g. accounts.google.com), not\n // the page the user actually came from — socialLogin.tsx stashes\n // the real page in a cookie right before the redirect, which\n // survives the round trip since it's set on our own origin.\n // Falls back to the live header for email/password sign-in,\n // where this request *is* the originating request.\n const referrerUrl = context?.getCookie?.(LOGIN_REFERRER_COOKIE)\n || headers?.get('referer')\n || null\n const device = parseUserAgent(userAgent)\n const geo = lookupGeoLocation(ipAddress)\n\n // Every session row for this user, including the one just\n // created — count === 1 means signup just auto-signed them in\n // (better-auth's default), anything higher is a returning login.\n const [{ count }] = await db\n .select({ count: sql<number>`count(*)` })\n .from(sessions)\n .where(eq(sessions.userId, session.userId))\n const isFirstSession = Number(count) <= 1\n\n await log({\n userId: session.userId,\n action: 'login',\n description: isFirstSession\n ? 'New account registered and signed in'\n : 'User logged in',\n ipAddress,\n userAgent,\n referrerUrl,\n os: device.os,\n browser: device.browser,\n deviceType: device.deviceType,\n country: geo.country,\n city: geo.city,\n })\n } catch (error) {\n console.error(\"Failed to log login activity\", error)\n }\n}\n\n// First admin: ADMIN_EMAIL (set by create-nextjs) bootstraps the first admin only.\n// Called on signup (provider-verified, e.g. Google) and from afterEmailVerification\n// (the user actually clicked the link) — never on generic user updates, so a stale\n// emailVerified flag can't trigger it. No-op once any admin exists, so a demoted\n// account stays demoted and a later owner of the address gets nothing.\nasync function promoteFirstAdmin(user: { id: string; email: string; emailVerified?: boolean | null; role?: unknown }) {\n const adminEmail = process.env.ADMIN_EMAIL?.trim().toLowerCase()\n if (!adminEmail || !user.emailVerified || user.email.toLowerCase() !== adminEmail) return\n const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.role, \"admin\")).limit(1)\n if (existing) return\n await db.update(users).set({ role: \"admin\" }).where(eq(users.id, user.id))\n // better-auth builds the first session (and its cookie cache) from this same object,\n // so without this the first dashboard load shows \"user\" until the next sign-in.\n user.role = \"admin\"\n}\n\nexport function createAuth(overrides: AuthOverrides = {}) {\n const socialProviders: NonNullable<BetterAuthOptions[\"socialProviders\"]> = {\n ...(config.AUTH_ENABLE_GOOGLE ? {\n google: {\n clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || \"\",\n clientSecret: process.env.AUTH_GOOGLE_SECRET || process.env.GOOGLE_CLIENT_SECRET || \"\",\n },\n } : {}),\n ...overrides.socialProviders,\n }\n const emailAndPasswordEnabled = config.AUTH_ENABLE_EMAIL_PASSWORD\n\n // Guard on the *final* merged config, after overrides.socialProviders is applied —\n // this only fails when there's truly no way to sign in. A project that disables both\n // built-ins via AUTH_ENABLE_GOOGLE=false / AUTH_ENABLE_EMAIL_PASSWORD=false but adds\n // its own provider (e.g. apple) here is a valid config and won't trip this.\n const hasEnabledSocialProvider = Object.values(socialProviders).some(Boolean)\n\n if (!hasEnabledSocialProvider && !emailAndPasswordEnabled) {\n throw new Error(\n \"No auth provider is enabled — every social provider is off and emailAndPassword.enabled is false. \" +\n \"Enable AUTH_ENABLE_GOOGLE / AUTH_ENABLE_EMAIL_PASSWORD, or pass your own provider via createAuth({ socialProviders: {...} }).\"\n )\n }\n\n // Shared by the `baseURL` field below and the passkey plugin's rpID/origin\n // — WebAuthn credentials are bound to this exact origin, so it must never\n // fall back to better-auth's own \"localhost\" passkey default in production.\n const baseURL = getBaseUrl()\n\n const log = overrides.logActivity ?? logActivity\n\n // TOTP (+ backup codes); see lib/two-factor.ts for the options.\n const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {\n issuer: config.APP_NAME,\n passwordless: overrides.twoFactor?.passwordless,\n challengeAfterOAuth: overrides.twoFactor?.challengeAfterOAuth,\n })\n\n // The app's own hooks ride in a plugin: plugin hooks run after the top-level ones\n // below, in plugin order, so the package's guards always run first.\n const appHooks = {\n id: \"app-hooks\",\n hooks: {\n before: overrides.hooks?.before ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],\n after: overrides.hooks?.after ? [{ matcher: () => true, handler: overrides.hooks.after }] : [],\n },\n } satisfies BetterAuthPlugin\n\n return betterAuth({\n database: drizzleAdapter(db, {\n provider: \"pg\",\n schema: {\n user: users,\n account: accounts,\n session: sessions,\n verification: verifications,\n twoFactor: twoFactors,\n passkey: passkeys,\n },\n }),\n\n // Session configuration (30 days expiration matching previous NextAuth setup)\n session: {\n expiresIn: 60 * 60 * 24 * 30, // 30 days\n updateAge: 60 * 60 * 24, // Update session every 24 hours\n cookieCache: {\n enabled: true, // Enable hybrid session caching for performance\n maxAge: 5 * 60, // 5 minutes\n }\n },\n\n // Email & Password Authentication (replaces Credentials provider)\n // Toggle per-project via AUTH_ENABLE_EMAIL_PASSWORD in that project's own .env.*\n emailAndPassword: {\n enabled: emailAndPasswordEnabled,\n requireEmailVerification: false,\n // `url` is fully composed by better-auth (baseURL + verification token +\n // callbackURL) — see app/(auth)/forgot-password and reset-password for\n // the pages this points at.\n async sendResetPassword({ user, url }) {\n const { EmailTemplateResetPassword } = await import(\"@/components/email/auth/reset-password\")\n await (await getResend()).emails.send({\n from: EMAIL_FROM,\n to: [user.email],\n subject: \"Reset your password\",\n react: EmailTemplateResetPassword({ firstName: user.name || \"there\", url }),\n })\n },\n },\n\n // Email verification. `requireEmailVerification` above stays false, so this\n // is opt-in: users trigger it from the dashboard via\n // authClient.sendVerificationEmail(). better-auth composes `url`\n // (baseURL + token + callbackURL) and serves the /api/auth/verify-email\n // callback that flips users.emailVerified on click.\n emailVerification: {\n autoSignInAfterVerification: true,\n async afterEmailVerification(user) {\n await promoteFirstAdmin(user)\n },\n async sendVerificationEmail({ user, url }) {\n const { EmailTemplateVerifyEmail } = await import(\"@/components/email/auth/verify-email\")\n await (await getResend()).emails.send({\n from: EMAIL_FROM,\n to: [user.email],\n subject: \"Confirm your email\",\n react: EmailTemplateVerifyEmail({ firstName: user.name || \"there\", url }),\n })\n },\n },\n\n // Social Providers — google is included by default; toggle per-project via\n // AUTH_ENABLE_GOOGLE. overrides.socialProviders can still add more (or replace it).\n socialProviders,\n\n // User schema configuration\n user: {\n additionalFields: {\n role: {\n type: \"string\",\n required: false,\n defaultValue: \"user\",\n input: false, // Prevent users from setting their own role\n },\n },\n // Self-service \"Delete account\" (dashboard Settings → Danger zone).\n // Credential users confirm with their password; OAuth-only users have\n // no password, so better-auth instead requires a session younger than\n // `freshAge` (default 1 day). Every user-owned table cascades on delete.\n // Impersonation and last-admin guards live in hooks.before below.\n deleteUser: { enabled: overrides.deleteUser ?? true },\n },\n\n // Advanced options\n advanced: {\n ...overrides.advanced,\n database: {\n generateId: () => createId(),\n },\n },\n\n rateLimit: overrides.rateLimit,\n\n databaseHooks: {\n user: {\n create: {\n async after(user, context) {\n await promoteFirstAdmin(user)\n await overrides.databaseHooks?.user?.create?.after?.(user, context)\n },\n },\n },\n session: {\n create: {\n async after(session, context) {\n await packageSessionCreated(log, session, context)\n await overrides.databaseHooks?.session?.create?.after?.(session, context)\n },\n },\n },\n },\n // better-auth's admin plugin ends impersonation by deleting the\n // impersonation session and restoring the admin's original session\n // straight from a signed cookie — it never runs session.create, so\n // there's no databaseHooks entry point to log the stop event from.\n // Reading the session here (before the endpoint deletes it) is the only\n // point where both the admin id and the impersonated user id are still\n // available together.\n hooks: {\n before: createAuthMiddleware(async (ctx) => {\n // Per-device abuse throttle for the two credential entry points.\n // Primarily keyed by the client's FingerprintJS visitorId\n // (x-device-fingerprint header, set in emailPasswordLogin/Signup), but\n // that header is client-supplied and unsigned — omitting it or\n // randomizing it per request bypasses a fingerprint-only check\n // entirely. IP is a lower-ceiling-tolerant backstop (shared behind\n // NAT/CGNAT/VPN, so it uses MAX_IP, not MAX) that still applies when\n // the header is missing or spoofed.\n if (ctx.path === \"/sign-in/email\" || ctx.path === \"/sign-up/email\") {\n const fingerprint = ctx.headers?.get(DEVICE_FINGERPRINT_HEADER)\n const ip = getClientIp(ctx.headers)\n const throttled =\n (fingerprint && (await isDeviceThrottled(fingerprint))) ||\n (ip && (await isDeviceThrottled(`ip:${ip}`, MAX_IP)))\n if (throttled) {\n throw new APIError(\"TOO_MANY_REQUESTS\", {\n message: \"Too many attempts from this device. Try again in a few minutes.\",\n })\n }\n }\n\n // Live kill-switch for the two built-in sign-in methods, on top of\n // the (untouched) provider registration above — lets an admin\n // disable a method from the System Settings page and have it take\n // effect immediately, even for a client that already has the button\n // rendered, instead of only on next deploy.\n if (ctx.path === \"/sign-in/social\") {\n // Scoped to \"google\" specifically since overrides.socialProviders\n // can register other providers (e.g. apple) this flag shouldn't gate.\n if (ctx.body?.provider === \"google\") {\n const flags = await getEffectiveAuthFlags()\n if (!flags.google) {\n throw new APIError(\"FORBIDDEN\", { message: \"Google sign-in is currently disabled.\" })\n }\n }\n return\n }\n\n if (ctx.path === \"/sign-in/email\") {\n const flags = await getEffectiveAuthFlags()\n if (!flags.emailPassword) {\n throw new APIError(\"FORBIDDEN\", { message: \"Email/password sign-in is currently disabled.\" })\n }\n return\n }\n\n // One Tap isn't a separate identity, it's a UI shortcut into the\n // same Google account — its plugin hits its own endpoint entirely\n // (not /sign-in/social), so it needs its own guard, and it needs\n // both flags: Google itself must still be allowed, and the One Tap\n // prompt specifically must be enabled.\n if (ctx.path === \"/one-tap/callback\") {\n const flags = await getEffectiveAuthFlags()\n if (!flags.google || !flags.oneTap) {\n throw new APIError(\"FORBIDDEN\", { message: \"Google One Tap is currently disabled.\" })\n }\n return\n }\n\n // The plugin's other /admin/* endpoints (set-user-password, set-role, ban-user,\n // remove-user, create-user...) would bypass our audit log and last-admin guard.\n // Block them over HTTP only (ctx.request is unset for server-side auth.api calls,\n // e.g. the invite route's createUser).\n if (\n ctx.request &&\n ctx.path?.startsWith(\"/admin/\") &&\n ctx.path !== \"/admin/impersonate-user\" &&\n ctx.path !== \"/admin/stop-impersonating\"\n ) {\n throw new APIError(\"FORBIDDEN\", { message: \"Use the dashboard to manage users.\" })\n }\n\n // The admin plugin stays registered either way (dropping it changes the\n // inferred session type); with impersonation off, its endpoint is closed here.\n if (ctx.path === \"/admin/impersonate-user\" && overrides.impersonation === false) {\n throw new APIError(\"FORBIDDEN\", { message: \"Impersonation is turned off.\" })\n }\n\n if (ctx.path === \"/delete-user\") {\n const current = await getSessionFromCtx(ctx, { disableCookieCache: true })\n if (!current) return // better-auth's own session check rejects it\n // An admin \"viewing as\" a user must not be able to destroy their account.\n if (current.session.impersonatedBy) {\n throw new APIError(\"FORBIDDEN\", { message: \"Stop impersonating before deleting an account.\" })\n }\n // Deleting the last admin would leave nobody able to reach the admin dashboard.\n if ((current.user as { role?: string }).role === \"admin\") {\n // Same rule as the admin routes: another *active* (unbanned) admin must remain.\n const [other] = await db\n .select({ n: sql`1` })\n .from(users)\n .where(otherActiveAdminExists([current.user.id]))\n .limit(1)\n if (!other) {\n throw new APIError(\"FORBIDDEN\", { message: \"You're the only admin. Promote another user to admin first.\" })\n }\n }\n return\n }\n\n if (ctx.path !== \"/admin/stop-impersonating\") return\n\n const current = await getSessionFromCtx(ctx, { disableCookieCache: true })\n if (current?.session.impersonatedBy) {\n const target = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.id, current.session.userId))\n .limit(1)\n\n await log({\n userId: current.session.impersonatedBy,\n action: 'impersonation_stopped',\n description: `Admin stopped impersonating ${target[0]?.email ?? current.session.userId}`,\n metadata: { impersonatedUserId: current.session.userId },\n })\n }\n }),\n after: createAuthMiddleware(async (ctx) => {\n // Passkey add/remove is a security-sensitive change to how the account\n // can be signed into — email the user whenever one lands, the same way\n // new-device sign-ins are surfaced. Best-effort: never disturb the\n // endpoint's own response.\n if (ctx.path === \"/passkey/verify-registration\" || ctx.path === \"/passkey/delete-passkey\") {\n if (ctx.context.returned instanceof APIError) return\n await notifyPasskeyChange(\n ctx,\n ctx.path === \"/passkey/verify-registration\" ? \"added\" : \"removed\",\n log,\n )\n return\n }\n\n if (ctx.path !== \"/sign-in/email\" && ctx.path !== \"/sign-up/email\") return\n\n const fingerprint = ctx.headers?.get(DEVICE_FINGERPRINT_HEADER)\n const ip = getClientIp(ctx.headers)\n const ipKey = ip ? `ip:${ip}` : null\n if (!fingerprint && !ipKey) return\n\n const failed = ctx.context.returned instanceof APIError\n const rawEmail = (ctx.body as { email?: unknown } | undefined)?.email\n const meta = {\n ipAddress: ip,\n userAgent: ctx.headers?.get(\"user-agent\") ?? null,\n email: typeof rawEmail === \"string\" ? rawEmail.toLowerCase() : null,\n }\n const keys = [fingerprint, ipKey].filter((k): k is string => !!k)\n\n // Sign-up abuse is mass account creation — the *successful* ones are\n // the problem — so every sign-up from this device counts.\n if (ctx.path === \"/sign-up/email\") {\n await Promise.all(keys.map((key) => recordDeviceAttempt(key, { ...meta, kind: \"signup\" })))\n return\n }\n\n // /sign-in/email: count failures. A success does NOT clear the\n // counter (an attacker with their own account could log in between\n // guesses to reset it); it expires with the window.\n if (failed) {\n await Promise.all(keys.map((key) => recordDeviceAttempt(key, { ...meta, kind: \"signin\" })))\n await logFailedLogin(ctx, log)\n }\n }),\n },\n\n // Base URL for callbacks\n baseURL,\n\n // Secret for signing cookies and tokens\n secret: process.env.AUTH_SECRET!,\n\n // The OAuth `state` is a one-time verification row: the callback consumes\n // and deletes it. When the same callback URL gets hit twice (browser\n // prefetch / bfcache / double nav — common on a repeat Google sign-in\n // where Google auto-redirects with no consent screen), the first hit\n // logs the user in and the second finds no `state` row and throws\n // `please_restart_the_process`. Default sends that to better-auth's bare\n // error page; point it at /login instead, which already bounces an\n // authenticated user straight to their callbackUrl — so the losing race\n // just lands them logged in. See better-auth#5658 / #6544.\n onAPIError: {\n errorURL: \"/login\",\n },\n\n plugins: [\n // Registered for impersonation (auth.api.impersonateUser / stopImpersonating)\n // only — role/ban/delete stay on our own custom routes above. adminRoles\n // matches our existing role column so the plugin's own permission checks\n // line up with hasRole(role, 'admin'). banReason is remapped onto our\n // existing bannedReason column instead of adding a duplicate field.\n adminPlugin({\n adminRoles: [\"admin\"],\n schema: {\n user: {\n fields: {\n banReason: \"bannedReason\",\n },\n },\n },\n }),\n // TOTP second factor + encrypted backup codes (see lib/two-factor.ts).\n // Listed individually, not spread: see the note on the spread below.\n twoFactorPlugin,\n twoFactorExtras,\n // WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a\n // passwordless sign-in method. rpID must be the bare host and origin\n // the full URL — both derived from baseURL above.\n passkey({\n rpID: new URL(baseURL).hostname,\n rpName: config.APP_NAME,\n origin: baseURL,\n }),\n // checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.\n // Keep this spread last: a leading spread turns `plugins` from a tuple into a plain\n // array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).\n ...(config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [oneTap()] : []),\n appHooks,\n ...(overrides.plugins ?? []),\n ]\n })\n}\n\n// Lazy: constructing the default instance validates config and throws if no\n// provider is enabled (see the guard above). Building it eagerly at module\n// load would mean a downstream project that only imports `createAuth` to\n// build its *own* customized instance (README §5) still pays that throw —\n// merely importing this module would run it, regardless of whether the\n// consuming project ever touches this default export. Deferring construction\n// to first property access means the throw only fires for code that actually\n// uses the package's own unconfigured `auth` singleton.\nlet _auth: ReturnType<typeof createAuth> | undefined\nfunction getDefaultAuth() {\n if (!_auth) _auth = createAuth()\n return _auth\n}\n\nexport const auth = new Proxy({} as ReturnType<typeof createAuth>, {\n get(_target, prop) {\n const instance = getDefaultAuth()\n const value = Reflect.get(instance, prop)\n return typeof value === \"function\" ? value.bind(instance) : value\n },\n // \"prop\" in auth (e.g. better-auth's toNextJsHandler does `\"handler\" in auth`)\n // must also see the real instance — without this it checks the empty\n // placeholder target and always reports false.\n has(_target, prop) {\n return Reflect.has(getDefaultAuth(), prop)\n },\n ownKeys(_target) {\n return Reflect.ownKeys(getDefaultAuth())\n },\n getOwnPropertyDescriptor(_target, prop) {\n return Reflect.getOwnPropertyDescriptor(getDefaultAuth(), prop)\n },\n})\n"]}
1
+ {"version":3,"sources":["../../components/email/security/passkey-changed.tsx","../../components/email/auth/reset-password.tsx","../../components/email/auth/verify-email.tsx","../../server/db/schema.ts","../../lib/config/maintenance.ts","../../config/env-schema.ts","../../config/env.ts","../../config/pg-ssl.ts","../../server/db/index.ts","../../node_modules/@better-auth/utils/dist/bytes.mjs","../../node_modules/@better-auth/utils/dist/base32.mjs","../../node_modules/@better-auth/utils/dist/index.mjs","../../node_modules/@better-auth/utils/dist/base64.mjs","../../node_modules/@noble/hashes/utils.js","../../node_modules/@better-auth/utils/dist/hex.mjs","../../node_modules/@better-auth/utils/dist/hmac.mjs","../../node_modules/@better-auth/utils/dist/otp.mjs","../../lib/auth/two-factor.ts","../../lib/security/activity-logger.ts","../../lib/utils/request-info.ts","../../lib/security/cookie-names.ts","../../lib/auth/base-url.ts","../../lib/auth/last-admin.ts","../../lib/auth/throttle-limits.ts","../../lib/auth/throttle.ts","../../lib/db/queries/settings.ts","../../lib/email/resend.ts","../../server/auth.ts"],"names":["Html","jsx","Head","Tailwind","Body","Container","jsxs","Section","Heading","Text","Button","Link","pgEnum","pgTable","text","createId","boolean","timestamp","index","integer","jsonb","unique","check","sql","z","Pool","drizzlePg","neonConfig","neon","drizzle","hex","getAlphabet","hmac","twoFactor","createAuthMiddleware","getSessionFromCtx","symmetricDecrypt","APIError","UAParser","geoip","eq","lt","join","existsSync","execFile","EmailTemplatePasskeyChange","betterAuth","drizzleAdapter","EmailTemplateResetPassword","EmailTemplateVerifyEmail","_a","_b","_c","_d","_e","current","adminPlugin","passkey","oneTap"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,uBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,uBAAA,EAAA;AAAA,EAAA,0BAAA,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AA,CAAQ,cAAA,EAAgB,CAAA;AAAA,EACzC,CAAA;AAAA,EACA,wBAAA,CAAyB,SAAS,IAAA,EAAM;AACtC,IAAA,OAAO,OAAA,CAAQ,wBAAA,CAAyB,cAAA,EAAe,EAAG,IAAI,CAAA;AAAA,EAChE;AACF,CAAC","file":"index.js","sourcesContent":["import {\n Html,\n Head,\n Body,\n Container,\n Section,\n Text,\n Heading,\n Button,\n Tailwind,\n} from '@react-email/components';\n\ninterface EmailTemplatePasskeyChangeProps {\n firstName: string;\n action: 'added' | 'removed';\n device: string;\n location: string;\n ipAddress: string;\n when: string;\n manageUrl?: string;\n}\n\nexport function EmailTemplatePasskeyChange({\n firstName,\n action,\n device,\n location,\n ipAddress,\n when,\n manageUrl,\n}: EmailTemplatePasskeyChangeProps) {\n const verb = action === 'added' ? 'added to' : 'removed from';\n\n return (\n <Html>\n <Head />\n <Tailwind>\n <Body className=\"bg-white font-sans\">\n <Container className=\"mx-auto max-w-[560px] px-0 pt-5 pb-12\">\n <Section className=\"rounded-xl bg-[#f8f9fa] p-10\">\n <Heading className=\"mb-3 text-center text-2xl font-bold text-[#1a1a1a]\">\n A passkey was {action}\n </Heading>\n <Text className=\"mb-6 text-base leading-6 text-[#666666]\">\n Hi {firstName}, a passkey was just {verb} your account.\n </Text>\n <Section className=\"mb-6 rounded-lg bg-white p-5\">\n <Text className=\"m-0 mb-2 text-sm leading-5 text-[#1a1a1a]\">\n <strong>Device:</strong> {device}\n </Text>\n <Text className=\"m-0 mb-2 text-sm leading-5 text-[#1a1a1a]\">\n <strong>Approx. location:</strong> {location}\n </Text>\n <Text className=\"m-0 mb-2 text-sm leading-5 text-[#1a1a1a]\">\n <strong>IP address:</strong> {ipAddress}\n </Text>\n <Text className=\"m-0 text-sm leading-5 text-[#1a1a1a]\">\n <strong>When:</strong> {when}\n </Text>\n </Section>\n {manageUrl && (\n <Section className=\"mb-6 text-center\">\n <Button\n href={manageUrl}\n className=\"rounded-lg bg-[#1a1a1a] px-6 py-3 text-sm font-bold text-white no-underline\"\n >\n Review your passkeys\n </Button>\n </Section>\n )}\n <Text className=\"text-sm leading-[22px] text-[#666666]\">\n If this was you, no action is needed. If you don&apos;t recognize it, change\n your password now and review your passkeys and active sessions.\n </Text>\n </Section>\n </Container>\n </Body>\n </Tailwind>\n </Html>\n );\n}\n","import {\n Html,\n Head,\n Body,\n Container,\n Section,\n Text,\n Heading,\n Button,\n} from '@react-email/components';\n\ninterface EmailTemplateResetPasswordProps {\n firstName: string;\n url: string;\n}\n\nexport function EmailTemplateResetPassword({ firstName, url }: EmailTemplateResetPasswordProps) {\n return (\n <Html>\n <Head />\n <Body style={{ backgroundColor: '#ffffff', fontFamily: 'Arial, sans-serif' }}>\n <Container style={{ margin: '0 auto', padding: '20px 0 48px', maxWidth: '560px' }}>\n <Section style={{ backgroundColor: '#f8f9fa', borderRadius: '12px', padding: '40px', textAlign: 'center' as const }}>\n <Heading style={{ fontSize: '28px', fontWeight: 'bold', marginBottom: '12px', color: '#1a1a1a' }}>\n Reset your password\n </Heading>\n <Text style={{ fontSize: '16px', color: '#666666', marginBottom: '32px', lineHeight: '24px' }}>\n Hi {firstName}, we got a request to reset your password. This link expires in an hour\n — if you didn&apos;t ask for this, you can safely ignore this email.\n </Text>\n <Section style={{ marginBottom: '32px' }}>\n <Button\n href={url}\n style={{\n backgroundColor: '#000000',\n color: '#ffffff',\n padding: '12px 32px',\n borderRadius: '6px',\n textDecoration: 'none',\n fontSize: '16px',\n fontWeight: 'bold',\n }}\n >\n Reset password\n </Button>\n </Section>\n <Text style={{ fontSize: '13px', color: '#999999', lineHeight: '20px', wordBreak: 'break-all' as const }}>\n Or paste this link into your browser:<br />\n <a href={url} style={{ color: '#000000', textDecoration: 'underline' }}>{url}</a>\n </Text>\n </Section>\n </Container>\n </Body>\n </Html>\n );\n}\n","import {\n Html,\n Head,\n Body,\n Container,\n Section,\n Text,\n Heading,\n Button,\n Link,\n Tailwind,\n} from '@react-email/components';\n\ninterface EmailTemplateVerifyEmailProps {\n firstName: string;\n url: string;\n}\n\nexport function EmailTemplateVerifyEmail({ firstName, url }: EmailTemplateVerifyEmailProps) {\n return (\n <Html>\n <Head />\n <Tailwind>\n <Body className=\"bg-white font-sans\">\n <Container className=\"mx-auto max-w-[560px] px-0 pt-5 pb-12\">\n <Section className=\"rounded-xl bg-[#f8f9fa] p-10 text-center\">\n <Heading className=\"mb-3 text-[28px] font-bold text-[#1a1a1a]\">\n Confirm your email\n </Heading>\n <Text className=\"mb-8 text-base leading-6 text-[#666666]\">\n Hi {firstName}, click the button below to verify this email address. If you\n didn&apos;t create an account, you can safely ignore this email.\n </Text>\n <Section className=\"mb-8\">\n <Button\n href={url}\n className=\"rounded-md bg-black px-8 py-3 text-base font-bold text-white no-underline\"\n >\n Verify email\n </Button>\n </Section>\n <Text className=\"text-[13px] leading-5 break-all text-[#999999]\">\n Or paste this link into your browser:\n <br />\n <Link href={url} className=\"text-black underline\">\n {url}\n </Link>\n </Text>\n </Section>\n </Container>\n </Body>\n </Tailwind>\n </Html>\n );\n}\n","import { boolean, check, index, integer, jsonb, pgEnum, pgTable, text, timestamp, unique } from \"drizzle-orm/pg-core\";\nimport { sql } from \"drizzle-orm\";\nimport { createId } from '@paralleldrive/cuid2'\nimport { DEFAULT_MAINTENANCE_EXEMPT_PATHS } from \"../../lib/config/maintenance\";\n\n// 'tester' is a regular user account flagged for testing; apps can use it to\n// keep test accounts apart from real users. It has no admin access.\nexport const RoleEnum = pgEnum('roles', ['user', 'admin', 'tester'])\n\nexport const ActivityActionEnum = pgEnum('activity_actions', [\n 'login',\n 'logout',\n 'login_failed',\n 'password_changed',\n 'email_changed',\n 'profile_updated',\n 'session_revoked',\n 'user_deleted',\n 'user_banned',\n 'user_unbanned',\n 'role_changed',\n 'impersonation_started',\n 'impersonation_stopped',\n 'settings_changed',\n 'passkey_added',\n 'passkey_removed',\n])\n\nexport const users = pgTable(\"user\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n name: text('name').notNull(),\n email: text('email').notNull().unique(),\n password: text('password'),\n emailVerified: boolean(\"emailVerified\").notNull().default(false),\n image: text(\"image\"),\n role: RoleEnum('roles').default('user').notNull(),\n banned: boolean('banned').default(false).notNull(),\n bannedAt: timestamp('bannedAt'),\n bannedReason: text('bannedReason'),\n bannedBy: text('bannedBy'), // email of the admin who issued the ban\n // Required by better-auth's admin plugin schema (auto-expiring bans). We\n // never set this ourselves, so it stays null and bans behave as permanent,\n // same as before the plugin was added.\n banExpires: timestamp('banExpires'),\n lastLoginAt: timestamp('lastLoginAt'),\n lastActiveAt: timestamp('lastActiveAt'),\n // Set by better-auth's twoFactor plugin — true once the user has\n // completed TOTP setup (see twoFactor pgTable below for the secret /\n // backup codes themselves).\n twoFactorEnabled: boolean('twoFactorEnabled').notNull().default(false),\n createdAt: timestamp('createdAt').notNull().defaultNow(),\n updatedAt: timestamp('updatedAt').notNull().defaultNow(),\n});\n\nexport const sessions = pgTable(\"session\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n expiresAt: timestamp(\"expiresAt\").notNull(),\n token: text(\"token\").notNull().unique(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n ipAddress: text(\"ipAddress\"),\n userAgent: text(\"userAgent\"),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n // Set by better-auth's admin plugin while this session is an admin\n // impersonating another user; holds the impersonating admin's user id.\n impersonatedBy: text(\"impersonatedBy\"),\n}, (table) => [\n // Read by userId on every login (session count), ban/delete and the admin sessions view.\n index(\"session_user_idx\").on(table.userId),\n]);\n\nexport const accounts = pgTable(\"account\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n accountId: text(\"accountId\").notNull(),\n providerId: text(\"providerId\").notNull(),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n accessToken: text(\"accessToken\"),\n refreshToken: text(\"refreshToken\"),\n idToken: text(\"idToken\"),\n accessTokenExpiresAt: timestamp(\"accessTokenExpiresAt\"),\n refreshTokenExpiresAt: timestamp(\"refreshTokenExpiresAt\"),\n scope: text(\"scope\"),\n password: text(\"password\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n});\n\n// Better-auth's twoFactor plugin. One row per user (created on first\n// `enable`); secret and backupCodes are its own encrypted-at-rest strings,\n// field names/types must match its expectations exactly (drizzleAdapter in\n// server/auth.ts maps this table to the plugin's \"twoFactor\" model as-is).\nexport const twoFactors = pgTable(\"twoFactor\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n secret: text(\"secret\").notNull(),\n backupCodes: text(\"backupCodes\").notNull(),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n // Added in better-auth 1.7 (TOTP lockout). Defaults match the plugin's.\n verified: boolean(\"verified\").default(true),\n failedVerificationCount: integer(\"failedVerificationCount\").default(0),\n lockedUntil: timestamp(\"lockedUntil\"),\n});\n\n// Better-auth's passkey plugin — one row per registered WebAuthn credential.\nexport const passkeys = pgTable(\"passkey\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n name: text(\"name\"),\n publicKey: text(\"publicKey\").notNull(),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n credentialID: text(\"credentialID\").notNull().unique(),\n counter: integer(\"counter\").notNull(),\n deviceType: text(\"deviceType\").notNull(),\n backedUp: boolean(\"backedUp\").notNull(),\n transports: text(\"transports\"),\n createdAt: timestamp(\"createdAt\"),\n aaguid: text(\"aaguid\"),\n});\n\nexport const verifications = pgTable(\"verification\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n identifier: text(\"identifier\").notNull(),\n value: text(\"value\").notNull(),\n expiresAt: timestamp(\"expiresAt\").notNull(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n});\n\nexport const activityLogs = pgTable(\"activity_log\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n // SET NULL, not cascade: deleting an admin must not erase the audit trail of\n // what they did. actorEmail keeps who it was once the user row is gone.\n userId: text(\"userId\").references(() => users.id, { onDelete: \"set null\" }),\n actorEmail: text(\"actorEmail\"),\n action: ActivityActionEnum('action').notNull(),\n description: text('description').notNull(),\n ipAddress: text('ipAddress'),\n userAgent: text('userAgent'),\n metadata: text('metadata'),\n // Populated on 'login' events only (registration + sign-in) — parsed from\n // userAgent/ipAddress at write time so the record stays stable even if\n // the parsing library or geoip database changes later.\n referrerUrl: text('referrerUrl'),\n os: text('os'),\n browser: text('browser'),\n deviceType: text('deviceType'),\n country: text('country'),\n city: text('city'),\n createdAt: timestamp('createdAt').notNull().defaultNow(),\n}, (table) => [\n // Per-user history, and the admin log's newest-first ordering.\n index(\"activity_log_user_created_idx\").on(table.userId, table.createdAt),\n index(\"activity_log_created_idx\").on(table.createdAt),\n]);\n\n// One row per (user, device fingerprint) pair. Its only job is to answer\n// \"has this account signed in from this device before?\" — no matching row ⇒\n// send a new-device alert (see app/api/device-check/route.ts). visitorId is\n// FingerprintJS's identifier, computed client-side in\n// components/auth/deviceCheck.tsx. UA+IP are deliberately NOT the signal here:\n// they churn constantly on mobile and would alert on every other login.\nexport const deviceFingerprints = pgTable(\"device_fingerprint\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n visitorId: text(\"visitorId\").notNull(),\n // Context captured at first-seen time — for the admin panel's \"New devices\"\n // card and the alert email. Not part of the new-vs-known decision (that's\n // visitorId only), just so an admin can eyeball whether a sign-in looks like\n // a hijack. Nullable: an old row predates these columns, or geoip missed.\n ipAddress: text(\"ipAddress\"),\n userAgent: text(\"userAgent\"),\n country: text(\"country\"),\n city: text(\"city\"),\n // Latest FingerprintJS signals for this device (lib/device-fingerprint.ts\n // getDeviceSignals(): accessibility signals dropped, large values hashed),\n // shown on the admin user page. Null for rows from before this column.\n components: jsonb(\"components\").$type<Record<string, unknown>>(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n unique(\"device_fingerprint_user_visitor\").on(table.userId, table.visitorId),\n]);\n\n// Proof of cookie consent (GDPR Art. 7(1): the controller must be able to\n// demonstrate consent). One row per choice a signed-in user makes, written by\n// app/api/consent from the banner (components/site/cookie-banner.tsx).\n// Deliberately minimal — no IP/UA. Deleted with the account.\nexport const consentLog = pgTable(\"consent_log\", {\n id: text(\"id\").notNull().primaryKey().$defaultFn(() => createId()),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n // The cookie_consent value: \"all\", \"necessary\" or a comma list of purposes.\n choice: text(\"choice\").notNull(),\n // CONSENT_VERSION (lib/cookie-names.ts) at the time — which banner/policy\n // wording the user agreed to.\n version: integer(\"version\").notNull(),\n // id of the user's record this one follows (\"\" for their first). Unique per\n // user, so concurrent posts from several tabs that all saw the same latest\n // record can't each insert a duplicate — one wins, the rest conflict. Works\n // without transactions (neon-http has none). Null on rows from before it.\n previousId: text(\"previousId\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n index(\"consent_log_user_idx\").on(table.userId, table.createdAt),\n unique(\"consent_log_chain\").on(table.userId, table.previousId),\n]);\n\n// Per-device abuse throttle for /sign-in/email and /sign-up/email — one\n// fixed-window counter row per FingerprintJS visitorId (sent by the auth\n// forms as the x-device-fingerprint header; see lib/auth-throttle.ts).\n// Keyed by device, not IP: IP is shared behind corporate NAT / CGNAT / VPN,\n// so an IP counter throttles coworkers together while missing an abuser who\n// rotates IPs. Rows untouched for 30 days are deleted (RETENTION_MS in\n// lib/auth-throttle-limits.ts, swept by lib/auth-throttle.ts).\nexport const authThrottle = pgTable(\"auth_throttle\", {\n fingerprint: text(\"fingerprint\").notNull().primaryKey(),\n count: integer(\"count\").notNull().default(0),\n windowStart: timestamp(\"windowStart\").notNull().defaultNow(),\n // Blockable data points, overwritten on every attempt (last-write-wins) so\n // the admin panel can show who to block — by IP or by fingerprint — with no\n // join and no per-attempt history table. windowStart anchors the counter's\n // window; lastAttemptAt is just \"most recently seen\".\n lastAttemptAt: timestamp(\"lastAttemptAt\").notNull().defaultNow(),\n ipAddress: text(\"ipAddress\"),\n userAgent: text(\"userAgent\"),\n lastEmail: text(\"lastEmail\"),\n lastKind: text(\"lastKind\"), // 'signin' | 'signup'\n});\n\n// Singleton row (id is always 'default') holding admin-editable settings for\n// config that used to be env-var-only. See lib/settings-queries.ts for the\n// cached read path and lazy-seed-from-env behavior.\nexport const systemSettings = pgTable(\"system_settings\", {\n id: text(\"id\").primaryKey().default(\"default\"),\n maintenanceMode: boolean(\"maintenanceMode\").notNull().default(false),\n maintenanceMessage: text(\"maintenanceMessage\"),\n // Path prefixes that stay reachable while maintenance mode is on (see\n // lib/maintenance.ts — a few auth paths are always open on top of these).\n maintenanceExemptPaths: text(\"maintenanceExemptPaths\").array().notNull().default(DEFAULT_MAINTENANCE_EXEMPT_PATHS),\n authEnableGoogle: boolean(\"authEnableGoogle\").notNull().default(true),\n authEnableEmailPassword: boolean(\"authEnableEmailPassword\").notNull().default(true),\n authEnableOneTap: boolean(\"authEnableOneTap\").notNull().default(false),\n enableSessionRevocation: boolean(\"enableSessionRevocation\").notNull().default(true),\n // Attach the error a user hit to feedback they send from it (see\n // lib/feedback-route.ts). Off = only what the user typed is sent.\n feedbackAttachErrors: boolean(\"feedbackAttachErrors\").notNull().default(true),\n // GDPR/ePrivacy consent mode. On: cookie banner, FingerprintJS and One Tap\n // only after \"Accept all\", device record erased on withdrawal. Off (no EU/UK\n // users): no banner, treated as consented. Null = follow\n // NEXT_PUBLIC_COOKIE_BANNER (nullable so migrating never flips a deployed\n // banner on or off). proxy.ts mirrors the effective value into the\n // consent_required cookie for the client (lib/cookie-consent.ts).\n consentRequired: boolean(\"consentRequired\"),\n updatedAt: timestamp(\"updatedAt\").notNull().defaultNow(),\n // Who last changed a setting. This row doesn't \"belong\" to that admin the\n // way sessions/activityLogs belong to their user, so deleting that admin's\n // account should null this out rather than cascade-delete the singleton row.\n updatedBy: text(\"updatedBy\").references(() => users.id, { onDelete: \"set null\" }),\n}, (table) => [\n check(\"system_settings_singleton\", sql`${table.id} = 'default'`),\n]);\n// Technical detail of unexpected errors, keyed by the short ref the user sees\n// (\"... (ref: K7Q2PX)\", see lib/errors.ts). Never sent to the browser: the\n// feedback route looks a ref up and attaches the detail to the report it\n// sends to Discord/email. Rows older than 30 days are pruned on insert.\nexport const errorRefs = pgTable(\"error_refs\", {\n ref: text(\"ref\").primaryKey(),\n message: text(\"message\").notNull(),\n detail: text(\"detail\").notNull(),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n index(\"error_refs_created_at_idx\").on(table.createdAt),\n]);\n\n// One row per browser/device a user turned push notifications on for. Rows are\n// deleted when the push service reports the endpoint gone (404/410), see\n// lib/push.ts, and re-upserted whenever the app opens (components/site/push-notifications-card.tsx).\nexport const pushSubscriptions = pgTable(\"push_subscription\", {\n id: text(\"id\").primaryKey().$defaultFn(() => createId()),\n userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n endpoint: text(\"endpoint\").notNull().unique(),\n p256dh: text(\"p256dh\").notNull(),\n auth: text(\"auth\").notNull(),\n userAgent: text(\"userAgent\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n index(\"push_subscription_user_idx\").on(table.userId),\n]);\n","// Pure path logic for maintenance mode — no DB / server-only imports, so it\n// can run in proxy.ts and in the admin form alike.\n\n// Default for the admin-editable exempt list: the public marketing pages.\nexport const DEFAULT_MAINTENANCE_EXEMPT_PATHS = [\n \"/\",\n \"/features\",\n \"/changelog\",\n \"/privacy\",\n \"/terms\",\n]\n\n// Always reachable, whatever the admin saves — otherwise an admin could\n// lock themselves out of the sign-in flow needed to turn maintenance off.\nexport const ALWAYS_OPEN_PATHS = [\n \"/maintenance\",\n \"/login\", // includes /login/2fa\n \"/forgot-password\",\n \"/reset-password\",\n \"/api/auth\",\n \"/api/settings/public\", // login page reads the One Tap flag from here\n]\n\n// `/foo` matches `/foo` and `/foo/...` but not `/foobar`; `/` matches only `/`.\nfunction matches(pathname: string, prefix: string) {\n const p = prefix.length > 1 ? prefix.replace(/\\/+$/, \"\") : prefix\n return pathname === p || (p !== \"/\" && pathname.startsWith(p + \"/\"))\n}\n\nexport function isMaintenanceExempt(pathname: string, exemptPaths: string[]) {\n return [...ALWAYS_OPEN_PATHS, ...exemptPaths].some((p) => matches(pathname, p))\n}\n","// No \"server-only\" guard here — this schema is also imported by scripts that\n// run outside Next.js's bundler (e.g. scripts/doctor.ts), where that guard\n// throws unconditionally. config/env.ts re-exports the parsed, guarded result\n// for app code; import this file directly only from non-Next scripts.\nimport { z } from 'zod';\n\nexport const envSchema = z.object({\n NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),\n PORT: z.string().default('3000').transform(Number),\n DATABASE_URL: z.string().default(''),\n RESEND_API_KEY: z.string().default(''),\n // Full access key for marketing broadcasts (admin Marketing email page).\n // Blank = use RESEND_API_KEY.\n RESEND_BROADCAST_API_KEY: z.string().default(''),\n // Resend segment users join from the dashboard \"Email updates\" toggle.\n // Blank = toggle hidden.\n RESEND_MARKETING_SEGMENT_ID: z.string().default(''),\n // Sender for every transactional email. Must be on a domain verified in\n // your Resend account.\n // Resend's shared sandbox sender: works without a verified domain but only\n // delivers to your own Resend account email. Set your verified domain for real use.\n EMAIL_FROM: z.string().default('Acme <onboarding@resend.dev>'),\n // Display name for this deployment — shown as the authenticator-app label\n // (2FA issuer) and the passkey relying-party name. Consuming projects set\n // this in their own .env; defaults to the template name.\n APP_NAME: z.string().default('Next.js Template'),\n // Where the dashboard feedback form delivers (app/api/feedback). Set either\n // or both; with neither, the Feedback button is hidden. FEEDBACK_EMAIL takes\n // a comma-separated list and sends through Resend (needs RESEND_API_KEY).\n FEEDBACK_DISCORD_WEBHOOK_URL: z.string().default(''),\n FEEDBACK_EMAIL: z.string().default(''),\n // Seconds between feedback messages per user (default 30, 0 = off). Read\n // straight from process.env in lib/feedback/route.ts; listed here for docs.\n FEEDBACK_COOLDOWN_SECONDS: z.string().default('30'),\n // Web Push (example, see lib/push.ts). Generate keys with\n // `bunx web-push generate-vapid-keys`. Blank = the notifications card is hidden.\n // The public key is also read in the browser as NEXT_PUBLIC_VAPID_PUBLIC_KEY.\n VAPID_PRIVATE_KEY: z.string().default(''),\n // mailto: or https: URL push services can contact you at.\n VAPID_SUBJECT: z.string().default(''),\n // Seed-only: the live value lives in the system_settings DB row (see\n // lib/settings-queries.ts) once it's been seeded on first read, and is\n // changed from the admin System Settings page, not by editing this var.\n ENABLE_SESSION_REVOCATION: z.string().default('true').transform(val => val === 'true'),\n AUTH_ENABLE_GOOGLE: z.string().default('true').transform(val => val === 'true'),\n AUTH_ENABLE_EMAIL_PASSWORD: z.string().default('true').transform(val => val === 'true'),\n AUTH_ENABLE_ONE_TAP: z.string().default('false').transform(val => val === 'true'),\n DB_DRIVER: z.enum(['pg', 'neon']).default('pg'),\n // Only relevant when DB_DRIVER=pg — whether the target Postgres server has SSL\n // enabled. Self-hosted Postgres (e.g. via Docker/Dokploy) typically does not.\n DATABASE_SSL: z.string().default('false').transform(val => val === 'true'),\n // With DATABASE_SSL=true the server certificate is verified. Set the CA (PEM,\n // \"\\n\" for newlines) for a self-signed or private CA; DATABASE_SSL_INSECURE=true\n // skips verification (encrypts only). Both are read in config/pg-ssl.ts.\n DATABASE_SSL_CA: z.string().default(''),\n DATABASE_SSL_INSECURE: z.string().default('false'),\n});\n","import \"server-only\";\nimport { envSchema } from './env-schema';\n\nconst results = envSchema.safeParse(process.env);\n\nif (results.success && (results.data.NODE_ENV === 'development')) {\n console.log('Environment variables loaded:', Object.keys(results.data));\n}\n\nif (!results.success) {\n console.error('Invalid environment variables:', results.error.format());\n throw new Error('Invalid environment variables');\n}\n\nexport const config = results.data;\n","// TLS options for the pg driver when DATABASE_SSL=true. Reads process.env\n// directly (not config/env) so the doctor script and apps whose local\n// env-schema predates these keys behave the same.\n//\n// Default: verify the server certificate (blocks a man-in-the-middle).\n// - DATABASE_SSL_CA: PEM of the CA that signed the server cert (use \"\\n\" for\n// newlines in a single-line env var), for self-signed or provider-private CAs.\n// - DATABASE_SSL_INSECURE=true: encrypt only, don't verify. Last resort.\nexport function pgSslOptions() {\n if (process.env.DATABASE_SSL_INSECURE === \"true\") return { rejectUnauthorized: false }\n const ca = process.env.DATABASE_SSL_CA?.replace(/\\\\n/g, \"\\n\")\n return { rejectUnauthorized: true, ...(ca ? { ca } : {}) }\n}\n","import 'server-only';\n\n// neon-http driver for production\nimport { neon, neonConfig } from '@neondatabase/serverless';\nimport { drizzle } from 'drizzle-orm/neon-http';\n\n// postgres driver for local development\nimport { drizzle as drizzlePg } from 'drizzle-orm/node-postgres';\nimport { Pool } from 'pg';\n\nimport * as schema from './schema';\nimport { config } from '../../config/env';\nimport { pgSslOptions } from '../../config/pg-ssl';\n\nimport type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';\n\n// Both drivers are PgDatabase; typing as the shared base keeps query-builder\n// calls (e.g. .returning(...)) well-typed instead of a driver union.\nlet db: PgDatabase<PgQueryResultHKT, typeof schema>\n\nif (config.DB_DRIVER === 'pg') {\n const pool = new Pool({\n connectionString: config.DATABASE_URL!,\n ssl: config.DATABASE_SSL ? pgSslOptions() : undefined,\n // pg waits forever by default; a hung DB would otherwise freeze every request (proxy reads settings).\n connectionTimeoutMillis: 5000,\n query_timeout: 15000, // roomy enough for the 10k-row exports\n });\n db = drizzlePg(pool, {\n schema,\n logger: process.env.NODE_ENV === 'development',\n });\n\n console.log('🟡 Using PostgreSQL (pg) driver');\n\n} else {\n // Fresh 15s signal (same as pg query_timeout) per request (a static signal passed to neon() would expire for good).\n // Global-only option, fine here: this is the only Neon client in the app.\n neonConfig.fetchFunction = (url: string, init?: RequestInit) =>\n fetch(url, { ...init, signal: AbortSignal.timeout(15_000) });\n const sql = neon(config.DATABASE_URL!);\n db = drizzle(sql, { schema, logger: process.env.NODE_ENV === 'development' });\n\n console.log('🟢 Using Neon (HTTP) driver');\n}\n// Query logging prints parameters (session/reset tokens, hashes): development only.\n\nexport { db }","//#region src/bytes.ts\nfunction toBufferSource(data) {\n\tif (typeof data === \"string\") return new TextEncoder().encode(data);\n\tif (!ArrayBuffer.isView(data)) return data;\n\tif (data.buffer instanceof ArrayBuffer) return data;\n\treturn new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();\n}\n/**\n* Converts strings and binary data into a `Uint8Array`.\n*\n* `ArrayBuffer` inputs share memory with the returned view, while number-based\n* `TypedArray` inputs are copied according to native constructor semantics.\n*\n* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#buffer | ArrayBuffer constructor behavior}\n* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray | TypedArray constructor behavior}\n*/\nfunction toUint8Array(data) {\n\tif (typeof data === \"string\") return new TextEncoder().encode(data);\n\treturn new Uint8Array(data);\n}\n//#endregion\nexport { toBufferSource, toUint8Array };\n","import { toUint8Array } from \"./bytes.mjs\";\n//#region src/base32.ts\n/**\n* Returns the Base32 alphabet based on the encoding type.\n* @param hex - Whether to use the hexadecimal Base32 alphabet.\n* @returns The appropriate Base32 alphabet.\n*/\nfunction getAlphabet(hex) {\n\treturn hex ? \"0123456789ABCDEFGHIJKLMNOPQRSTUV\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n}\n/**\n* Creates a decode map for the given alphabet.\n* @param alphabet - The Base32 alphabet.\n* @returns A map of characters to their corresponding values.\n*/\nfunction createDecodeMap(alphabet) {\n\tconst decodeMap = /* @__PURE__ */ new Map();\n\tfor (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i);\n\treturn decodeMap;\n}\n/**\n* Encodes a Uint8Array into a Base32 string.\n* @param data - The data to encode.\n* @param alphabet - The Base32 alphabet to use.\n* @param padding - Whether to include padding.\n* @returns The Base32 encoded string.\n*/\nfunction base32Encode(data, alphabet, padding) {\n\tlet result = \"\";\n\tlet buffer = 0;\n\tlet shift = 0;\n\tfor (const byte of data) {\n\t\tbuffer = buffer << 8 | byte;\n\t\tshift += 8;\n\t\twhile (shift >= 5) {\n\t\t\tshift -= 5;\n\t\t\tresult += alphabet[buffer >> shift & 31];\n\t\t}\n\t}\n\tif (shift > 0) result += alphabet[buffer << 5 - shift & 31];\n\tif (padding) {\n\t\tconst padCount = (8 - result.length % 8) % 8;\n\t\tresult += \"=\".repeat(padCount);\n\t}\n\treturn result;\n}\n/**\n* Decodes a Base32 string into a Uint8Array.\n* @param data - The Base32 encoded string.\n* @param alphabet - The Base32 alphabet to use.\n* @returns The decoded Uint8Array.\n*/\nfunction base32Decode(data, alphabet) {\n\tconst decodeMap = createDecodeMap(alphabet);\n\tconst result = [];\n\tlet buffer = 0;\n\tlet bitsCollected = 0;\n\tfor (const char of data) {\n\t\tif (char === \"=\") break;\n\t\tconst value = decodeMap.get(char);\n\t\tif (value === void 0) throw new Error(`Invalid Base32 character: ${char}`);\n\t\tbuffer = buffer << 5 | value;\n\t\tbitsCollected += 5;\n\t\twhile (bitsCollected >= 8) {\n\t\t\tbitsCollected -= 8;\n\t\t\tresult.push(buffer >> bitsCollected & 255);\n\t\t}\n\t}\n\treturn Uint8Array.from(result);\n}\n/**\n* Base32 encoding and decoding utility.\n*/\nconst base32 = {\n\t/**\n\t* Encodes data into a Base32 string.\n\t* @param data - The data to encode (ArrayBuffer, number-based TypedArray, or string).\n\t* @param options - Encoding options.\n\t* @returns The Base32 encoded string.\n\t*/\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(false);\n\t\treturn base32Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\t/**\n\t* Decodes a Base32 string into a Uint8Array.\n\t* @param data - The Base32 encoded string or ArrayBuffer/TypedArray.\n\t* @returns The decoded Uint8Array.\n\t*/\n\tdecode(data) {\n\t\tif (typeof data !== \"string\") data = new TextDecoder().decode(data);\n\t\tconst alphabet = getAlphabet(false);\n\t\treturn base32Decode(data, alphabet);\n\t}\n};\n/**\n* Base32hex encoding and decoding utility.\n*/\nconst base32hex = {\n\t/**\n\t* Encodes data into a Base32hex string.\n\t* @param data - The data to encode (ArrayBuffer, number-based TypedArray, or string).\n\t* @param options - Encoding options.\n\t* @returns The Base32hex encoded string.\n\t*/\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(true);\n\t\treturn base32Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\t/**\n\t* Decodes a Base32hex string into a Uint8Array.\n\t* @param data - The Base32hex encoded string.\n\t* @returns The decoded Uint8Array.\n\t*/\n\tdecode(data) {\n\t\treturn base32Decode(data, getAlphabet(true));\n\t}\n};\n//#endregion\nexport { base32, base32hex };\n","//#region src/index.ts\nfunction getWebcryptoSubtle() {\n\tconst cr = typeof globalThis !== \"undefined\" && globalThis.crypto;\n\tif (cr && typeof cr.subtle === \"object\" && cr.subtle != null) return cr.subtle;\n\tthrow new Error(\"crypto.subtle must be defined\");\n}\n//#endregion\nexport { getWebcryptoSubtle };\n","import { toUint8Array } from \"./bytes.mjs\";\n//#region src/base64.ts\nfunction getAlphabet(urlSafe) {\n\treturn urlSafe ? \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\" : \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n}\nfunction base64Encode(data, alphabet, padding) {\n\tlet result = \"\";\n\tlet buffer = 0;\n\tlet shift = 0;\n\tfor (const byte of data) {\n\t\tbuffer = buffer << 8 | byte;\n\t\tshift += 8;\n\t\twhile (shift >= 6) {\n\t\t\tshift -= 6;\n\t\t\tresult += alphabet[buffer >> shift & 63];\n\t\t}\n\t}\n\tif (shift > 0) result += alphabet[buffer << 6 - shift & 63];\n\tif (padding) {\n\t\tconst padCount = (4 - result.length % 4) % 4;\n\t\tresult += \"=\".repeat(padCount);\n\t}\n\treturn result;\n}\nfunction base64Decode(data, alphabet) {\n\tconst decodeMap = /* @__PURE__ */ new Map();\n\tfor (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i);\n\tconst result = [];\n\tlet buffer = 0;\n\tlet bitsCollected = 0;\n\tfor (const char of data) {\n\t\tif (char === \"=\") break;\n\t\tconst value = decodeMap.get(char);\n\t\tif (value === void 0) throw new Error(`Invalid Base64 character: ${char}`);\n\t\tbuffer = buffer << 6 | value;\n\t\tbitsCollected += 6;\n\t\tif (bitsCollected >= 8) {\n\t\t\tbitsCollected -= 8;\n\t\t\tresult.push(buffer >> bitsCollected & 255);\n\t\t}\n\t}\n\treturn Uint8Array.from(result);\n}\nconst base64 = {\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(false);\n\t\treturn base64Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\tdecode(data) {\n\t\tif (typeof data !== \"string\") data = new TextDecoder().decode(data);\n\t\tconst alphabet = getAlphabet(data.includes(\"-\") || data.includes(\"_\"));\n\t\treturn base64Decode(data, alphabet);\n\t}\n};\nconst base64Url = {\n\tencode(data, options = {}) {\n\t\tconst alphabet = getAlphabet(true);\n\t\treturn base64Encode(toUint8Array(data), alphabet, options.padding ?? true);\n\t},\n\tdecode(data) {\n\t\treturn base64Decode(data, getAlphabet(data.includes(\"-\") || data.includes(\"_\")));\n\t}\n};\n//#endregion\nexport { base64, base64Url };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","import { toUint8Array } from \"./bytes.mjs\";\nimport { hexToBytes } from \"@noble/hashes/utils.js\";\n//#region src/hex.ts\nconst toBytes = (data) => hexToBytes(data);\nconst hex = {\n\tencode: (data) => {\n\t\tconst buffer = toUint8Array(data);\n\t\tif (buffer.byteLength === 0) return \"\";\n\t\tlet result = \"\";\n\t\tfor (const byte of buffer) result += byte.toString(16).padStart(2, \"0\");\n\t\treturn result;\n\t},\n\tdecode: (data) => {\n\t\tif (!data) return \"\";\n\t\tif (typeof data === \"string\") return new TextDecoder().decode(toBytes(data));\n\t\treturn new TextDecoder().decode(data);\n\t},\n\ttoBytes\n};\n//#endregion\nexport { hex };\n","import { getWebcryptoSubtle } from \"./index.mjs\";\nimport { toBufferSource } from \"./bytes.mjs\";\nimport { base64, base64Url } from \"./base64.mjs\";\nimport { hex } from \"./hex.mjs\";\n//#region src/hmac.ts\nconst createHMAC = (algorithm = \"SHA-256\", encoding = \"none\") => {\n\tconst hmac = {\n\t\timportKey: async (key, keyUsage) => {\n\t\t\treturn getWebcryptoSubtle().importKey(\"raw\", toBufferSource(key), {\n\t\t\t\tname: \"HMAC\",\n\t\t\t\thash: { name: algorithm }\n\t\t\t}, false, [keyUsage]);\n\t\t},\n\t\tsign: async (hmacKey, data) => {\n\t\t\tif (typeof hmacKey === \"string\") hmacKey = await hmac.importKey(hmacKey, \"sign\");\n\t\t\tconst signature = await getWebcryptoSubtle().sign(\"HMAC\", hmacKey, toBufferSource(data));\n\t\t\tif (encoding === \"hex\") return hex.encode(signature);\n\t\t\tif (encoding === \"base64\") return base64.encode(signature);\n\t\t\tif (encoding === \"base64url\" || encoding === \"base64urlnopad\") return base64Url.encode(signature, { padding: encoding !== \"base64urlnopad\" });\n\t\t\treturn signature;\n\t\t},\n\t\tverify: async (hmacKey, data, signature) => {\n\t\t\tif (typeof hmacKey === \"string\") hmacKey = await hmac.importKey(hmacKey, \"verify\");\n\t\t\tif (encoding === \"hex\") signature = typeof signature === \"string\" ? hex.toBytes(signature) : signature;\n\t\t\tif (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") signature = await base64.decode(signature);\n\t\t\treturn getWebcryptoSubtle().verify(\"HMAC\", hmacKey, toBufferSource(signature), toBufferSource(data));\n\t\t}\n\t};\n\treturn hmac;\n};\n//#endregion\nexport { createHMAC };\n","import { base32 } from \"./base32.mjs\";\nimport { createHMAC } from \"./hmac.mjs\";\n//#region src/otp.ts\nconst defaultPeriod = 30;\nconst defaultDigits = 6;\nconst hmac = createHMAC(\"SHA-1\");\n/**\n* loops over `expected.length` so timing never depends on input length\n*\n* @internal\n*/\nfunction constantTimeEqualOTP(input, expected) {\n\tlet difference = input.length ^ expected.length;\n\tfor (let i = 0; i < expected.length; i++) difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);\n\treturn difference === 0;\n}\nasync function generateHOTP(key, { counter, digits }) {\n\tconst _digits = digits ?? defaultDigits;\n\tif (_digits < 1 || _digits > 8) throw new TypeError(\"Digits must be between 1 and 8\");\n\tconst buffer = /* @__PURE__ */ new ArrayBuffer(8);\n\tnew DataView(buffer).setBigUint64(0, BigInt(counter), false);\n\tconst bytes = new Uint8Array(buffer);\n\tconst signature = await hmac.sign(key, bytes);\n\tconst hmacResult = new Uint8Array(signature);\n\tconst offset = hmacResult[hmacResult.length - 1] & 15;\n\treturn (((hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255) % 10 ** _digits).toString().padStart(_digits, \"0\");\n}\nasync function generateTOTP(key, options) {\n\tconst digits = options?.digits ?? defaultDigits;\n\tconst milliseconds = (options?.period ?? defaultPeriod) * 1e3;\n\treturn await generateHOTP(key, {\n\t\tcounter: Math.floor(Date.now() / milliseconds),\n\t\tdigits\n\t});\n}\nasync function verifyTOTP(otp, { window = 1, digits = defaultDigits, key, period = defaultPeriod }) {\n\tconst milliseconds = period * 1e3;\n\tconst counter = Math.floor(Date.now() / milliseconds);\n\tlet matched = false;\n\tfor (let i = -window; i <= window; i++) matched = constantTimeEqualOTP(otp, await generateHOTP(key, {\n\t\tcounter: counter + i,\n\t\tdigits\n\t})) || matched;\n\treturn matched;\n}\n/**\n* Generate a QR code URL for the OTP secret\n*/\nfunction generateQRCode({ issuer, account, secret, digits = defaultDigits, period = defaultPeriod }) {\n\tconst baseURI = `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`;\n\tconst params = new URLSearchParams({\n\t\tsecret: base32.encode(secret, { padding: false }),\n\t\tissuer\n\t});\n\tif (digits !== void 0) params.set(\"digits\", digits.toString());\n\tif (period !== void 0) params.set(\"period\", period.toString());\n\treturn `${baseURI}?${params.toString()}`;\n}\n/**\n* Strings are used as UTF-8 bytes.\n* Decode encoded secrets, such as Base32, before passing them in.\n*/\nconst createOTP = (secret, opts) => {\n\tconst digits = opts?.digits ?? defaultDigits;\n\tconst period = opts?.period ?? defaultPeriod;\n\treturn {\n\t\thotp: async (counter) => {\n\t\t\treturn generateHOTP(await hmac.importKey(secret, \"sign\"), {\n\t\t\t\tcounter,\n\t\t\t\tdigits\n\t\t\t});\n\t\t},\n\t\ttotp: async () => {\n\t\t\treturn generateTOTP(await hmac.importKey(secret, \"sign\"), {\n\t\t\t\tdigits,\n\t\t\t\tperiod\n\t\t\t});\n\t\t},\n\t\tverify: async (otp, options) => {\n\t\t\treturn verifyTOTP(otp, {\n\t\t\t\tkey: await hmac.importKey(secret, \"sign\"),\n\t\t\t\tdigits,\n\t\t\t\tperiod,\n\t\t\t\t...options\n\t\t\t});\n\t\t},\n\t\turl: (issuer, account) => {\n\t\t\treturn generateQRCode({\n\t\t\t\tissuer,\n\t\t\t\taccount,\n\t\t\t\tsecret,\n\t\t\t\tdigits,\n\t\t\t\tperiod\n\t\t\t});\n\t\t}\n\t};\n};\n//#endregion\nexport { createOTP };\n","import type { BetterAuthPlugin } from \"better-auth\"\nimport { APIError, createAuthMiddleware, getSessionFromCtx } from \"better-auth/api\"\nimport { symmetricDecrypt } from \"better-auth/crypto\"\nimport { twoFactor } from \"better-auth/plugins\"\nimport { createOTP } from \"@better-auth/utils/otp\"\n\n// better-auth only challenges 2FA after password sign-ins (/sign-in/email etc.), so a\n// user with TOTP on who signs in with Google or One Tap skips it. With challengeAfterOAuth\n// these paths get the challenge too. Passkey sign-in isn't: a passkey is already two factors.\nconst CHALLENGED_PATHS = [\"/callback/:id\", \"/one-tap/callback\"]\nconst CODE_REQUIRED_PATHS = [\"/two-factor/disable\", \"/two-factor/generate-backup-codes\"]\n\nexport type TwoFactorOptions = {\n /** Shown as the account label in authenticator apps. */\n issuer: string\n /**\n * For apps whose users may have no password (OAuth-only). Enabling 2FA then needs no\n * password, and disabling it or regenerating backup codes needs a current TOTP code\n * (sent as `code` in the body) instead. Default false: the password is required.\n */\n passwordless?: boolean\n /**\n * Also ask for the code after Google and One Tap sign-in, not just password sign-in.\n * The Google callback then redirects to /login/2fa?callbackUrl=…, so the app needs\n * that page. Default false (stock better-auth behaviour).\n */\n challengeAfterOAuth?: boolean\n}\n\n/**\n * TOTP 2FA, optionally passwordless and/or also enforced after Google and One Tap sign-in.\n * Returns two plugins; keep them together and in this order in `plugins`.\n */\nexport function twoFactorPlugins(\n baseURL: string,\n { issuer, passwordless = false, challengeAfterOAuth = false }: TwoFactorOptions,\n) {\n const plugin = twoFactor({ issuer, allowPasswordless: passwordless })\n\n // Reuse the plugin's own challenge hook (drop the new session, set the short-lived\n // 2FA cookie) on the extra paths instead of reimplementing it.\n if (challengeAfterOAuth) {\n const [challenge] = plugin.hooks.after\n plugin.hooks.after = [{\n ...challenge,\n matcher: (ctx) => challenge.matcher(ctx) || CHALLENGED_PATHS.includes(ctx.path ?? \"\"),\n }]\n }\n\n const extras = {\n id: \"two-factor-extras\",\n hooks: {\n // allowPasswordless lets disable / regenerate-backup-codes run on a session alone,\n // so anyone at an unlocked, signed-in browser could switch 2FA off. Require a\n // current authenticator code instead of the password the user doesn't have.\n before: passwordless ? [{\n matcher: (ctx) => CODE_REQUIRED_PATHS.includes(ctx.path ?? \"\"),\n handler: createAuthMiddleware(async (ctx) => {\n const session = await getSessionFromCtx(ctx)\n if (!session) return // the endpoint rejects it\n const code = (ctx.body as { code?: unknown } | undefined)?.code\n const row = await ctx.context.adapter.findOne<{ secret: string }>({\n model: \"twoFactor\",\n where: [{ field: \"userId\", value: session.user.id }],\n })\n const valid =\n typeof code === \"string\" && !!row &&\n (await createOTP(await symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret })).verify(code))\n if (!valid) throw new APIError(\"UNAUTHORIZED\", { message: \"Enter the current code from your authenticator app\" })\n }),\n }] : [],\n // The challenge answers with JSON ({ twoFactorRedirect: true }), which One Tap's\n // caller handles. The Google callback is a browser redirect, so turn it into a\n // redirect to /login/2fa, keeping where the user was headed (same-origin only).\n after: challengeAfterOAuth ? [{\n matcher: (ctx) => ctx.path === \"/callback/:id\",\n handler: createAuthMiddleware(async (ctx) => {\n const returned = ctx.context.returned as { twoFactorRedirect?: boolean } | undefined\n if (!returned?.twoFactorRedirect) return\n const target = new URL(ctx.context.responseHeaders?.get(\"location\") ?? \"/dashboard\", baseURL)\n const callbackUrl =\n target.origin === new URL(baseURL).origin ? target.pathname + target.search : \"/dashboard\"\n throw ctx.redirect(`/login/2fa?callbackUrl=${encodeURIComponent(callbackUrl)}`)\n }),\n }] : [],\n },\n } satisfies BetterAuthPlugin\n\n return [plugin, extras] as const\n}\n","import \"server-only\"\nimport { sql } from \"drizzle-orm\"\nimport { db } from \"../../server/db\"\nimport { activityLogs } from \"../../server/db/schema\"\n\nexport type ActivityAction =\n | 'login'\n | 'logout'\n | 'login_failed'\n | 'password_changed'\n | 'email_changed'\n | 'profile_updated'\n | 'session_revoked'\n | 'user_deleted'\n | 'user_banned'\n | 'user_unbanned'\n | 'role_changed'\n | 'impersonation_started'\n | 'impersonation_stopped'\n | 'settings_changed'\n | 'passkey_added'\n | 'passkey_removed'\n\nexport interface LogActivityParams {\n userId: string\n action: ActivityAction\n description: string\n ipAddress?: string | null\n userAgent?: string | null\n metadata?: Record<string, any>\n // Populated on 'login' events only — see server/auth.ts's session.create hook.\n referrerUrl?: string | null\n os?: string | null\n browser?: string | null\n deviceType?: string | null\n country?: string | null\n city?: string | null\n}\n\n/** Signature for createAuth({ logActivity }): an app-supplied writer for these entries. */\nexport type ActivityLogger = (entry: LogActivityParams) => Promise<void>\n\nexport async function logActivity({\n userId,\n action,\n description,\n ipAddress,\n userAgent,\n metadata,\n referrerUrl,\n os,\n browser,\n deviceType,\n country,\n city,\n}: LogActivityParams) {\n try {\n await db.insert(activityLogs).values({\n userId,\n // Snapshot the email at write time; survives deletion of the user row.\n actorEmail: sql`(select \"email\" from \"user\" where \"id\" = ${userId})`,\n action,\n description,\n ipAddress: ipAddress || null,\n userAgent: userAgent || null,\n metadata: metadata ? JSON.stringify(metadata) : null,\n referrerUrl: referrerUrl || null,\n os: os || null,\n browser: browser || null,\n deviceType: deviceType || null,\n country: country || null,\n city: city || null,\n })\n } catch (error) {\n console.error('Failed to log activity:', error)\n // Don't throw - activity logging should not break the app\n }\n}\n","import \"server-only\"\nimport { UAParser } from \"ua-parser-js\"\nimport geoip from \"geoip-lite\"\n\nconst countryNames = new Intl.DisplayNames([\"en\"], { type: \"region\" })\n\nexport type DeviceType = \"desktop\" | \"mobile\" | \"tablet\"\n\nexport interface DeviceInfo {\n os: string | null\n browser: string | null\n deviceType: DeviceType\n}\n\nexport interface GeoInfo {\n country: string | null\n city: string | null\n}\n\n/**\n * Proxies append the address they saw to X-Forwarded-For, so the LAST entry\n * is the one our own proxy added; earlier entries are caller-supplied and\n * spoofable (they'd let an attacker dodge or frame an IP in the throttle).\n * Falls back to x-real-ip, then null (local dev with no proxy).\n * shortcut: assumes exactly one trusted proxy hop, so behind a CDN plus a\n * proxy the last entry is the CDN's address; revisit if you stack proxies.\n */\nexport function getClientIp(headers: Headers | undefined | null): string | null {\n const forwardedFor = headers?.get(\"x-forwarded-for\")\n if (forwardedFor) return forwardedFor.split(\",\").at(-1)!.trim()\n\n return headers?.get(\"x-real-ip\") ?? null\n}\n\nexport function parseUserAgent(userAgent: string | null | undefined): DeviceInfo {\n if (!userAgent) {\n return { os: null, browser: null, deviceType: \"desktop\" }\n }\n\n const { os, browser, device } = new UAParser(userAgent).getResult()\n\n return {\n os: os.name ? [os.name, os.version].filter(Boolean).join(\" \") : null,\n browser: browser.name ?? null,\n deviceType: device.type === \"mobile\" || device.type === \"tablet\" ? device.type : \"desktop\",\n }\n}\n\n/**\n * Offline lookup (geoip-lite ships its own IP-range database, no network\n * call) — resolves to nulls for private/local addresses like 127.0.0.1.\n */\nexport function lookupGeoLocation(ipAddress: string | null | undefined): GeoInfo {\n if (!ipAddress) return { country: null, city: null }\n\n const geo = geoip.lookup(ipAddress)\n if (!geo) return { country: null, city: null }\n\n let country: string | null = geo.country || null\n if (country) {\n try {\n country = countryNames.of(country) ?? country\n } catch {\n // Unrecognized region code — keep the raw code rather than losing it.\n }\n }\n\n return { country, city: geo.city || null }\n}\n\nexport function formatDeviceInfo({ os, browser, deviceType }: DeviceInfo): string {\n const label = [browser, os].filter(Boolean).join(\" on \")\n const typeLabel = deviceType === \"mobile\" ? \"Mobile\" : deviceType === \"tablet\" ? \"Tablet\" : \"Desktop\"\n\n return label ? `${label} · ${typeLabel}` : `Unknown device · ${typeLabel}`\n}\n\nexport function formatLocation({ country, city }: GeoInfo): string {\n if (!country && !city) return \"Unknown\"\n\n return [city, country].filter(Boolean).join(\", \")\n}\n","// Shared cookie/header names used by both client components and server/auth.ts\n// — no \"server-only\" guard, since both sides need them.\n\n// Stashes the page a social sign-in was initiated from, so the login-activity\n// log shows the real referrer instead of the OAuth provider's own domain\n// (e.g. accounts.google.com) once the browser redirects back.\nexport const LOGIN_REFERRER_COOKIE = 'login_referrer'\n\n// Carries the client's FingerprintJS visitorId on /sign-in/email and\n// /sign-up/email requests — the key for the per-device abuse throttle\n// (see lib/auth-throttle.ts). A header, not a cookie, so it's only sent on\n// the auth calls that need it, not every request.\nexport const DEVICE_FINGERPRINT_HEADER = 'x-device-fingerprint'\n\n// The visitor's cookie choice (lib/cookie-consent.ts): \"all\", \"necessary\", or\n// a comma list of the purposes they ticked under \"Customize\", e.g.\n// \"fingerprint\" — one choice per purpose, as regulators like the CNIL expect.\nexport const COOKIE_CONSENT_COOKIE = 'cookie_consent'\n\n// \"fingerprint\": FingerprintJS device id (new-device alerts, sign-in throttle,\n// shared-device detection, admin Devices card). \"onetap\": Google One Tap,\n// whose script may set Google's own cookies.\nexport type ConsentPurpose = 'fingerprint' | 'onetap'\nexport const CONSENT_PURPOSES: ConsentPurpose[] = ['fingerprint', 'onetap']\n\n// Version of the consent wording (banner text + privacy page purposes),\n// stored with each consent record (consent_log.version) so you can show which\n// text a user agreed to. Bump it when that wording changes materially.\nexport const CONSENT_VERSION = 1\n\n// A well-formed cookie_consent value: \"all\", \"necessary\", or a comma list of\n// known purposes. Used to validate what the client sends to app/api/consent.\nexport function isValidConsent(value: unknown): value is string {\n if (value === 'all' || value === 'necessary') return true\n if (typeof value !== 'string' || !value) return false\n const parts = value.split(',')\n return new Set(parts).size === parts.length && parts.every((p) => (CONSENT_PURPOSES as string[]).includes(p))\n}\n\n// Does a cookie_consent value allow this purpose? Plain function, no React,\n// so route handlers can use it too (app/api/device-check).\nexport function consentAllows(value: string | null | undefined, purpose: ConsentPurpose): boolean {\n if (value === 'all') return true\n if (!value || value === 'necessary') return false\n return value.split(',').includes(purpose)\n}\n\n// Consent mode, set by proxy.ts from the admin's System Settings toggle\n// (\"1\" = consent required, \"0\" = not). Read by lib/cookie-consent.ts.\nexport const CONSENT_REQUIRED_COOKIE = 'consent_required'\n\n// FingerprintJS signals that are never sent or stored. Accessibility\n// preferences can hint at a disability (GDPR Art. 9 health data); colorGamut\n// mostly tracks display hardware but is read alongside them. Filtered on the\n// client (lib/device-fingerprint.ts) and again on the server\n// (app/api/device-check), since the client can't be trusted.\nexport const EXCLUDED_SIGNALS = new Set([\n 'reducedMotion', 'reducedTransparency', 'contrast', 'forcedColors',\n 'invertedColors', 'monochrome', 'colorGamut',\n])\n","// The one place the site's base URL is decided (auth callbacks, passkey\n// origin, email links, redirect guard). BETTER_AUTH_URL wins because that's\n// the variable the setup docs, doctor and scaffolder fill in; the others are\n// legacy/fallback. No server-only imports, so tests can use it.\nexport function getBaseUrl(): string {\n const url =\n process.env.BETTER_AUTH_URL ||\n process.env.NEXTAUTH_URL ||\n process.env.NEXT_PUBLIC_APP_URL ||\n \"http://localhost:3000\"\n return url.replace(/\\/+$/, \"\")\n}\n","import { sql } from \"drizzle-orm\"\nimport { users } from \"../../server/db/schema\"\n\n/**\n * SQL condition: \"after removing `excludeIds` (delete, demote or ban), at least\n * one other active (admin, not banned) account remains\". Put it in the WHERE of\n * the write itself so check and write are one statement. The subquery row-locks\n * every active admin, so two admins banning/demoting/deleting each other at\n * once serialize: the second re-reads after the first commits and is refused.\n * One statement also works on the neon-http driver (no transactions).\n * Callers treat \"0 rows written\" as the last-admin refusal.\n */\nexport function otherActiveAdminExists(excludeIds: string[]) {\n const ids = sql.join(excludeIds.map((id) => sql`${id}`), sql`, `)\n return sql`(select count(*) from (select ${users.id} as id from ${users} where ${users.role} = 'admin' and ${users.banned} = false for update) a where a.id not in (${ids})) > 0`\n}\n","// Pure throttle policy — no DB, no `server-only`, so it stays unit-testable.\n// Consumed by lib/auth-throttle.ts (the DB plumbing) and its test.\n\n// Tune per deployment, or lift to env vars if you need it configurable.\nexport const WINDOW_MS = 15 * 60 * 1000 // how long attempts accumulate\nexport const MAX = 10 // failed sign-ins / sign-ups per window before a 429, per fingerprint\n\n// Backstop cap keyed by IP instead of fingerprint — the fingerprint header is\n// client-supplied and unsigned, so it's trivial to omit or randomize per\n// request (see server/auth.ts before-hook). Higher than MAX because an IP can\n// be shared behind NAT/CGNAT/VPN.\n// ponytail: flat multiplier, not a real per-deployment tuning — revisit if\n// legitimate shared-IP traffic ever gets caught in it.\nexport const MAX_IP = MAX * 3\n\n// Rows untouched this long are deleted (lib/auth-throttle.ts). They hold IP,\n// user agent and the last email typed — often for people with no account — so\n// GDPR storage limitation says don't keep them past their use.\nexport const RETENTION_MS = 30 * 24 * 60 * 60 * 1000\n\n// A row whose window has already elapsed counts as \"no row\" — it resets on\n// the next attempt (see recordDeviceAttempt), so the device isn't blocked in\n// the meantime.\nexport function isOverLimit(\n row: { count: number; windowStart: Date } | undefined,\n now: number,\n max: number = MAX,\n): boolean {\n if (!row) return false\n if (now - row.windowStart.getTime() >= WINDOW_MS) return false\n return row.count >= max\n}\n","import \"server-only\"\nimport { eq, lt, sql } from \"drizzle-orm\"\nimport { db } from \"../../server/db\"\nimport { authThrottle } from \"../../server/db/schema\"\nimport { RETENTION_MS, WINDOW_MS, isOverLimit } from \"./throttle-limits\"\n\n// Is this key (device fingerprint, or \"ip:<address>\" backstop) currently over\n// the cap? Read-only — the caller (server/auth.ts before-hook) decides\n// whether to 429.\nexport async function isDeviceThrottled(fingerprint: string, max?: number): Promise<boolean> {\n try {\n const [row] = await db\n .select({ count: authThrottle.count, windowStart: authThrottle.windowStart })\n .from(authThrottle)\n .where(eq(authThrottle.fingerprint, fingerprint))\n .limit(1)\n return isOverLimit(row, Date.now(), max)\n } catch (error) {\n // Fail open — a throttle-store hiccup must never lock everyone out of sign-in.\n console.error(\"auth-throttle read failed, allowing request\", error)\n return false\n }\n}\n\nexport type AttemptMeta = {\n ipAddress: string | null\n userAgent: string | null\n email: string | null\n kind: \"signin\" | \"signup\"\n}\n\n// Atomic upsert: new row at 1, +1 within the live window, or reset to 1 when\n// the previous window has elapsed. One statement, so a device hammering the\n// endpoint (the whole point) can't race its own counter. The meta fields are\n// overwritten every time — they're \"last seen from this device\", for the\n// admin panel's block-list view (lib/admin-queries.ts).\nexport async function recordDeviceAttempt(fingerprint: string, meta: AttemptMeta): Promise<void> {\n const now = new Date()\n const cutoff = new Date(now.getTime() - WINDOW_MS)\n const seen = {\n lastAttemptAt: now,\n ipAddress: meta.ipAddress,\n userAgent: meta.userAgent,\n lastEmail: meta.email,\n lastKind: meta.kind,\n }\n try {\n await db\n .insert(authThrottle)\n .values({ fingerprint, count: 1, windowStart: now, ...seen })\n .onConflictDoUpdate({\n target: authThrottle.fingerprint,\n set: {\n // ISO strings, not Dates: pg sends a raw Date as server-local time, which a\n // tz-less `timestamp` column (stored as UTC) misreads on any non-UTC host.\n count: sql`case when ${authThrottle.windowStart} < ${cutoff.toISOString()} then 1 else ${authThrottle.count} + 1 end`,\n windowStart: sql`case when ${authThrottle.windowStart} < ${cutoff.toISOString()} then ${now.toISOString()} else ${authThrottle.windowStart} end`,\n ...seen,\n },\n })\n } catch (error) {\n console.error(\"auth-throttle write failed\", error)\n }\n await pruneStaleRows(now)\n}\n\n// Retention sweep piggybacked on the write path, so no cron is needed.\n// ponytail: runs at most hourly per server instance, and only when someone\n// attempts a sign-in — a site with zero attempts keeps stale rows until the\n// next one. Call pruneStaleRows() from a cron if you need a hard guarantee.\nconst PRUNE_EVERY_MS = 60 * 60 * 1000\nlet lastPrune = 0\n\nexport async function pruneStaleRows(now = new Date()): Promise<void> {\n if (now.getTime() - lastPrune < PRUNE_EVERY_MS) return\n lastPrune = now.getTime()\n try {\n await db\n .delete(authThrottle)\n .where(lt(authThrottle.lastAttemptAt, new Date(now.getTime() - RETENTION_MS)))\n } catch (error) {\n console.error(\"auth-throttle prune failed\", error)\n }\n}\n","import \"server-only\"\nimport { db } from \"../../../server/db\"\nimport { systemSettings } from \"../../../server/db/schema\"\nimport { config } from \"../../../config/env\"\nimport { eq } from \"drizzle-orm\"\nimport { DEFAULT_MAINTENANCE_EXEMPT_PATHS } from \"../../config/maintenance\"\n\nconst SETTINGS_ROW_ID = \"default\"\n// Short TTL: cheap reads (no DB round trip on every request), while an\n// admin's change is guaranteed live within this window even for a reader\n// that isn't the one who just saved (invalidateSystemSettingsCache() makes\n// it instant for that request's own process).\nconst CACHE_TTL_MS = 10_000\nconst FAILURE_CACHE_TTL_MS = 5_000\n\nexport type SystemSettings = typeof systemSettings.$inferSelect\n\nlet cached: { value: SystemSettings; expiresAt: number } | null = null\n\n// Fail-open shape if the DB is unreachable: auth flags fall back to their\n// config/env.ts defaults (unchanged behavior), maintenance mode is always\n// off — a DB hiccup must never lock out the whole site, including admins.\nfunction fallbackSettings(): SystemSettings {\n return {\n id: SETTINGS_ROW_ID,\n maintenanceMode: false,\n maintenanceMessage: null,\n maintenanceExemptPaths: DEFAULT_MAINTENANCE_EXEMPT_PATHS,\n authEnableGoogle: config.AUTH_ENABLE_GOOGLE,\n authEnableEmailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,\n authEnableOneTap: config.AUTH_ENABLE_ONE_TAP,\n enableSessionRevocation: config.ENABLE_SESSION_REVOCATION,\n feedbackAttachErrors: true,\n consentRequired: null,\n updatedAt: new Date(0),\n updatedBy: null,\n }\n}\n\nasync function loadOrSeed(): Promise<SystemSettings> {\n const existing = await db\n .select()\n .from(systemSettings)\n .where(eq(systemSettings.id, SETTINGS_ROW_ID))\n .limit(1)\n if (existing[0]) return existing[0]\n\n // Lazy-seed on first read, from the *current* env config — not the\n // schema's hardcoded column defaults — so turning this feature on never\n // silently flips an already-deployed flag (e.g. a prod deploy that\n // already set AUTH_ENABLE_GOOGLE=false).\n const seeded = await db\n .insert(systemSettings)\n .values({\n id: SETTINGS_ROW_ID,\n maintenanceMode: false,\n authEnableGoogle: config.AUTH_ENABLE_GOOGLE,\n authEnableEmailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,\n authEnableOneTap: config.AUTH_ENABLE_ONE_TAP,\n enableSessionRevocation: config.ENABLE_SESSION_REVOCATION,\n })\n .onConflictDoNothing()\n .returning()\n\n if (seeded[0]) return seeded[0]\n\n // Lost the seed race to a concurrent first-reader.\n const retry = await db\n .select()\n .from(systemSettings)\n .where(eq(systemSettings.id, SETTINGS_ROW_ID))\n .limit(1)\n return retry[0] ?? fallbackSettings()\n}\n\nexport async function getSystemSettings(): Promise<SystemSettings> {\n const now = Date.now()\n if (cached && cached.expiresAt > now) return cached.value\n\n try {\n const value = await loadOrSeed()\n cached = { value, expiresAt: now + CACHE_TTL_MS }\n return value\n } catch (error) {\n console.error(\"Failed to load system settings, failing open:\", error)\n // Cache the fallback briefly so a down DB isn't retried (and waited on) by every request.\n const value = fallbackSettings()\n cached = { value, expiresAt: now + FAILURE_CACHE_TTL_MS }\n return value\n }\n}\n\nexport function invalidateSystemSettingsCache() {\n cached = null\n}\n\nexport type SystemSettingsPatch = Partial<Pick<SystemSettings,\n | 'maintenanceMode' | 'maintenanceMessage' | 'maintenanceExemptPaths'\n | 'authEnableGoogle' | 'authEnableEmailPassword' | 'authEnableOneTap'\n | 'enableSessionRevocation' | 'feedbackAttachErrors' | 'consentRequired'\n>>\n\nexport async function updateSystemSettings(\n patch: SystemSettingsPatch,\n updatedBy: string\n): Promise<SystemSettings> {\n await loadOrSeed() // ensure the row exists even if nobody's read it yet\n\n const [updated] = await db\n .update(systemSettings)\n .set({ ...patch, updatedAt: new Date(), updatedBy })\n .where(eq(systemSettings.id, SETTINGS_ROW_ID))\n .returning()\n\n invalidateSystemSettingsCache()\n return updated\n}\n\n// Effective auth-method visibility = deploy-time \"configured\" (env, decides\n// whether the provider is even registered with better-auth — see\n// server/auth.ts's createAuth()) AND runtime \"offered\" (this DB flag).\nexport async function getEffectiveAuthFlags() {\n const settings = await getSystemSettings()\n return {\n google: config.AUTH_ENABLE_GOOGLE && settings.authEnableGoogle,\n emailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD && settings.authEnableEmailPassword,\n oneTap: config.AUTH_ENABLE_ONE_TAP && settings.authEnableOneTap,\n }\n}\n\n// Consent mode: the admin's choice if they've made one, else the\n// NEXT_PUBLIC_COOKIE_BANNER default (banner on unless it's \"false\").\nexport function isConsentRequired(settings: Pick<SystemSettings, 'consentRequired'>): boolean {\n return settings.consentRequired ?? process.env.NEXT_PUBLIC_COOKIE_BANNER !== \"false\"\n}\n\n// What each admin-settings control needs from the environment before its\n// toggle can do anything. Add an entry here when you add a control that depends\n// on env vars; the System Settings page then shows it disabled, with a badge and\n// the reason, until the deployment provides them. Controls with no entry\n// are always usable.\n// flag: an AUTH_ENABLE_*-style switch that must be on\n// keys: every group must be satisfied; within a group any one variable is enough\n// (aliases, or \"this or that\"). The first name in a group is the one shown.\n// Read lazily so NEXT_PUBLIC_* / env values are looked at when the page renders.\ntype Requirement = { flag?: [name: string, on: boolean]; keys?: string[][] }\n\nconst CONTROL_REQUIREMENTS: Record<string, () => Requirement> = {\n authEnableGoogle: () => ({\n flag: [\"AUTH_ENABLE_GOOGLE\", config.AUTH_ENABLE_GOOGLE],\n keys: [[\"AUTH_GOOGLE_ID\", \"GOOGLE_CLIENT_ID\"], [\"AUTH_GOOGLE_SECRET\", \"GOOGLE_CLIENT_SECRET\"]],\n }),\n authEnableEmailPassword: () => ({\n flag: [\"AUTH_ENABLE_EMAIL_PASSWORD\", config.AUTH_ENABLE_EMAIL_PASSWORD],\n }),\n authEnableOneTap: () => ({\n flag: [\"AUTH_ENABLE_ONE_TAP\", config.AUTH_ENABLE_ONE_TAP],\n keys: [[\"NEXT_PUBLIC_GOOGLE_CLIENT_ID\"], [\"NEXT_PUBLIC_AUTH_ENABLE_ONE_TAP=true\"]],\n }),\n // The toggle only matters once feedback has somewhere to go.\n feedbackAttachErrors: () => ({\n keys: [[\"FEEDBACK_DISCORD_WEBHOOK_URL\", \"FEEDBACK_EMAIL\"]],\n }),\n}\n\nexport type ControlStatus =\n | { ok: true }\n | { ok: false; kind: \"flag\" | \"keys\"; reason: string }\n\nexport function getControlStatuses(): Record<string, ControlStatus> {\n const isSet = (name: string) =>\n name.includes(\"=\") ? process.env[name.split(\"=\")[0]] === name.split(\"=\")[1] : Boolean(process.env[name])\n const out: Record<string, ControlStatus> = {}\n for (const [key, build] of Object.entries(CONTROL_REQUIREMENTS)) {\n const req = build()\n if (req.flag && !req.flag[1]) {\n out[key] = { ok: false, kind: \"flag\", reason: `Not configured for this deployment. Set ${req.flag[0]}=true to unlock this toggle.` }\n continue\n }\n const missing = (req.keys ?? []).filter((group) => !group.some(isSet)).map((group) => group.join(\" or \"))\n out[key] = missing.length\n ? {\n ok: false,\n kind: \"keys\",\n reason: `Missing environment variable${missing.length > 1 ? \"s\" : \"\"}: ${missing.join(\", \")}. Add ${missing.length > 1 ? \"them\" : \"it\"} and redeploy to unlock this toggle (NEXT_PUBLIC_ values need a rebuild).`,\n }\n : { ok: true }\n }\n return out\n}\n\nexport function getConfiguredAuthFlags() {\n return {\n google: config.AUTH_ENABLE_GOOGLE,\n emailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,\n oneTap: config.AUTH_ENABLE_ONE_TAP,\n }\n}\n","import \"server-only\"\nimport type { Resend } from \"resend\"\nimport { config } from \"@/config/env\"\n\n// From env, not hardcoded: scaffolded apps run this module from the package's\n// bundled auth, so a local edit here would never reach their auth emails.\nexport const EMAIL_FROM = config.EMAIL_FROM\n\n// Loaded on first send, so projects that never send email don't pay for it\n// at startup.\nlet resend: Resend | undefined\nexport async function getResend() {\n if (!resend) {\n const { Resend } = await import(\"resend\")\n resend = new Resend(config.RESEND_API_KEY)\n }\n return resend\n}\n\n// Broadcasts need a full access key, so they can use their own and leave\n// RESEND_API_KEY as a sending-only key.\nexport const BROADCAST_API_KEY = config.RESEND_BROADCAST_API_KEY || config.RESEND_API_KEY\n\nlet broadcastResend: Resend | undefined\nexport async function getBroadcastResend() {\n if (!broadcastResend) {\n const { Resend } = await import(\"resend\")\n broadcastResend = new Resend(BROADCAST_API_KEY)\n }\n return broadcastResend\n}\n","import \"server-only\"\nimport { execFile } from \"node:child_process\"\nimport { existsSync } from \"node:fs\"\nimport { join } from \"node:path\"\nimport { betterAuth, type BetterAuthOptions, type BetterAuthPlugin } from \"better-auth\"\nimport { drizzleAdapter } from \"better-auth/adapters/drizzle\"\nimport { createId } from \"@paralleldrive/cuid2\"\nimport { eq, sql } from \"drizzle-orm\"\nimport { db } from \"./db\"\nimport { users, accounts, sessions, verifications, twoFactors, passkeys } from \"./db/schema\"\nimport { config } from \"@/config/env\"\nimport { oneTap, admin as adminPlugin } from \"better-auth/plugins\";\nimport { twoFactorPlugins } from \"@/lib/auth/two-factor\"\nimport { passkey } from \"@better-auth/passkey\";\nimport { createAuthMiddleware, getSessionFromCtx, APIError } from \"better-auth/api\"\nimport { logActivity, type ActivityLogger } from \"@/lib/security/activity-logger\"\nimport { getClientIp, parseUserAgent, lookupGeoLocation, formatDeviceInfo, formatLocation } from \"@/lib/utils/request-info\"\nimport { LOGIN_REFERRER_COOKIE, DEVICE_FINGERPRINT_HEADER } from \"@/lib/security/cookie-names\"\nimport { getBaseUrl } from \"@/lib/auth/base-url\"\nimport { otherActiveAdminExists } from \"@/lib/auth/last-admin\"\nimport { isDeviceThrottled, recordDeviceAttempt } from \"@/lib/auth/throttle\"\nimport { MAX_IP } from \"@/lib/auth/throttle-limits\"\nimport { getEffectiveAuthFlags } from \"@/lib/db/queries/settings\"\nimport { getResend, EMAIL_FROM } from \"@/lib/email/resend\"\n// Email templates are imported lazily where they're sent, so\n// @react-email/components only loads when an email goes out.\n\n// Lists the app's outdated packages in the `next dev` terminal. It lives here because Bun blocks a\n// package's own install scripts and every app imports this module, so a version bump needs no setup.\nfunction checkDepsOnce() {\n const flag = globalThis as { __xkDepsChecked?: boolean } // survives HMR and duplicate bundles\n if (process.env.NODE_ENV !== \"development\" || flag.__xkDepsChecked) return\n flag.__xkDepsChecked = true\n const script = join(/*turbopackIgnore: true*/ process.cwd(), \"node_modules/@xk2800/nextjs-template/scripts/check-deps.mjs\")\n if (!existsSync(script)) return // the template repo itself\n // A child process, so the script isn't bundled and a failure can't reach the app.\n execFile(process.execPath, [script], (_err, stdout) => {\n if (stdout?.trim()) console.log(stdout)\n })\n}\ncheckDepsOnce()\n\ntype AuthMiddleware = ReturnType<typeof createAuthMiddleware>\ntype DatabaseHooks = NonNullable<BetterAuthOptions[\"databaseHooks\"]>\ntype CreateAfter<M extends \"user\" | \"session\"> = NonNullable<NonNullable<NonNullable<DatabaseHooks[M]>[\"create\"]>[\"after\"]>\n\nexport type AuthOverrides = {\n // Merged with (not replacing) the default `google` provider below, so\n // consuming projects can add e.g. `apple` without forking this file.\n socialProviders?: BetterAuthOptions[\"socialProviders\"]\n /** App hooks. They run after the package's own hooks, so its guards still apply. */\n hooks?: { before?: AuthMiddleware; after?: AuthMiddleware }\n /** App database hooks, run after the package's own (e.g. start a trial on signup). */\n databaseHooks?: {\n user?: { create?: { after?: CreateAfter<\"user\"> } }\n session?: { create?: { after?: CreateAfter<\"session\"> } }\n }\n /** Extra better-auth plugins, appended after the package's. */\n plugins?: BetterAuthPlugin[]\n /** e.g. crossSubDomainCookies when login and marketing live on different subdomains. */\n advanced?: Pick<NonNullable<BetterAuthOptions[\"advanced\"]>, \"crossSubDomainCookies\">\n /** better-auth's rate limiter (off outside production by default). */\n rateLimit?: BetterAuthOptions[\"rateLimit\"]\n twoFactor?: {\n /**\n * For apps whose users have no password (OAuth-only). Enabling 2FA needs no\n * password; disabling it or regenerating backup codes needs a current TOTP `code`.\n */\n passwordless?: boolean\n /**\n * Also ask for the code after Google and One Tap sign-in (stock better-auth only\n * asks after email/password). Needs the /login/2fa page. Default false.\n */\n challengeAfterOAuth?: boolean\n }\n /** Admins can sign in as a user (\"impersonate\"). Default true. */\n impersonation?: boolean\n /** Self-service \"Delete account\" (better-auth's /delete-user). Default true. */\n deleteUser?: boolean\n /**\n * Writes the package's auth activity entries (login, failed login, passkey added /\n * removed, impersonation) instead of its own logger. Use it when your activity table\n * needs your own connection, e.g. it has row-level security the package's `db` can't pass.\n */\n logActivity?: ActivityLogger\n}\n\n// A failed credential sign-in, written to the activity feed — but only when\n// the attempted email maps to a real account (activityLogs.userId is NOT\n// NULL, and a miss has no user to attribute the row to). Best-effort: runs\n// in an after-hook and must never disturb the sign-in response.\nasync function logFailedLogin(ctx: { body?: unknown; headers?: Headers | null }, log: ActivityLogger) {\n try {\n const raw = (ctx.body as { email?: unknown } | undefined)?.email\n const email = typeof raw === \"string\" ? raw.toLowerCase() : null\n if (!email) return\n\n const [user] = await db\n .select({ id: users.id })\n .from(users)\n .where(eq(users.email, email))\n .limit(1)\n if (!user) return\n\n await log({\n userId: user.id,\n action: \"login_failed\",\n description: \"Failed login attempt\",\n ipAddress: getClientIp(ctx.headers),\n userAgent: ctx.headers?.get(\"user-agent\") ?? null,\n })\n } catch (error) {\n console.error(\"Failed to log login_failed activity\", error)\n }\n}\n\n// Email the account owner that a passkey was added or removed. Runs from the\n// auth `after` hook on a successful /passkey/verify-registration or\n// /passkey/delete-passkey; best-effort — a mail failure must not fail the\n// endpoint. Also written to the activity feed. Self-disables when Resend\n// isn't configured.\nasync function notifyPasskeyChange(\n ctx: Parameters<Parameters<typeof createAuthMiddleware>[0]>[0],\n action: \"added\" | \"removed\",\n log: ActivityLogger,\n) {\n try {\n const session = await getSessionFromCtx(ctx)\n const user = session?.user\n if (!user) return\n\n const ip = getClientIp(ctx.headers)\n\n await log({\n userId: user.id,\n action: action === \"added\" ? \"passkey_added\" : \"passkey_removed\",\n description: `Passkey ${action}`,\n ipAddress: ip,\n userAgent: ctx.headers?.get(\"user-agent\") ?? null,\n })\n\n if (!config.RESEND_API_KEY) return\n\n const { EmailTemplatePasskeyChange } = await import(\"@/components/email/security/passkey-changed\")\n await (await getResend()).emails.send({\n from: EMAIL_FROM,\n to: [user.email],\n subject: action === \"added\" ? \"A passkey was added to your account\" : \"A passkey was removed from your account\",\n react: EmailTemplatePasskeyChange({\n firstName: user.name || \"there\",\n action,\n device: formatDeviceInfo(parseUserAgent(ctx.headers?.get(\"user-agent\") ?? null)),\n location: formatLocation(lookupGeoLocation(ip)),\n ipAddress: ip || \"Unknown\",\n when: new Date().toUTCString(),\n manageUrl: `${getBaseUrl()}/dashboard/settings`,\n }),\n })\n } catch (error) {\n console.error(\"Failed to send passkey-change notification\", error)\n }\n}\n\n// The package's own sign-in bookkeeping: last-login time and the login activity entry.\n// Every new session row corresponds to a sign-in (credential or OAuth) — use that as\n// the \"last logged in\" signal rather than session updates, which also fire on\n// cookie-cache refresh / expiry extension.\nasync function packageSessionCreated(log: ActivityLogger, ...[session, context]: Parameters<CreateAfter<\"session\">>) {\n // Impersonation sessions (created by the admin plugin's\n // impersonateUser endpoint) also go through session.create —\n // don't let \"an admin looked at this account\" show up as the\n // user's own last login, and log it as an audit event instead.\n const impersonatedBy = (session as { impersonatedBy?: string | null }).impersonatedBy\n if (impersonatedBy) {\n const target = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.id, session.userId))\n .limit(1)\n\n await log({\n userId: impersonatedBy,\n action: 'impersonation_started',\n description: `Admin started impersonating ${target[0]?.email ?? session.userId}`,\n metadata: { impersonatedUserId: session.userId },\n })\n return\n }\n\n try {\n await db\n .update(users)\n .set({ lastLoginAt: new Date() })\n .where(eq(users.id, session.userId))\n } catch (error) {\n console.error(\"Failed to update lastLoginAt\", error)\n }\n\n try {\n const headers = context?.headers\n const ipAddress = getClientIp(headers)\n const userAgent = headers?.get('user-agent') ?? null\n // For OAuth, the live referer header on this request is the\n // provider's own callback page (e.g. accounts.google.com), not\n // the page the user actually came from — socialLogin.tsx stashes\n // the real page in a cookie right before the redirect, which\n // survives the round trip since it's set on our own origin.\n // Falls back to the live header for email/password sign-in,\n // where this request *is* the originating request.\n const referrerUrl = context?.getCookie?.(LOGIN_REFERRER_COOKIE)\n || headers?.get('referer')\n || null\n const device = parseUserAgent(userAgent)\n const geo = lookupGeoLocation(ipAddress)\n\n // Every session row for this user, including the one just\n // created — count === 1 means signup just auto-signed them in\n // (better-auth's default), anything higher is a returning login.\n const [{ count }] = await db\n .select({ count: sql<number>`count(*)` })\n .from(sessions)\n .where(eq(sessions.userId, session.userId))\n const isFirstSession = Number(count) <= 1\n\n await log({\n userId: session.userId,\n action: 'login',\n description: isFirstSession\n ? 'New account registered and signed in'\n : 'User logged in',\n ipAddress,\n userAgent,\n referrerUrl,\n os: device.os,\n browser: device.browser,\n deviceType: device.deviceType,\n country: geo.country,\n city: geo.city,\n })\n } catch (error) {\n console.error(\"Failed to log login activity\", error)\n }\n}\n\n// First admin: ADMIN_EMAIL (set by create-nextjs) bootstraps the first admin only.\n// Called on signup (provider-verified, e.g. Google) and from afterEmailVerification\n// (the user actually clicked the link) — never on generic user updates, so a stale\n// emailVerified flag can't trigger it. No-op once any admin exists, so a demoted\n// account stays demoted and a later owner of the address gets nothing.\nasync function promoteFirstAdmin(user: { id: string; email: string; emailVerified?: boolean | null; role?: unknown }) {\n const adminEmail = process.env.ADMIN_EMAIL?.trim().toLowerCase()\n if (!adminEmail || !user.emailVerified || user.email.toLowerCase() !== adminEmail) return\n const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.role, \"admin\")).limit(1)\n if (existing) return\n await db.update(users).set({ role: \"admin\" }).where(eq(users.id, user.id))\n // better-auth builds the first session (and its cookie cache) from this same object,\n // so without this the first dashboard load shows \"user\" until the next sign-in.\n user.role = \"admin\"\n}\n\nexport function createAuth(overrides: AuthOverrides = {}) {\n const socialProviders: NonNullable<BetterAuthOptions[\"socialProviders\"]> = {\n ...(config.AUTH_ENABLE_GOOGLE ? {\n google: {\n clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || \"\",\n clientSecret: process.env.AUTH_GOOGLE_SECRET || process.env.GOOGLE_CLIENT_SECRET || \"\",\n },\n } : {}),\n ...overrides.socialProviders,\n }\n const emailAndPasswordEnabled = config.AUTH_ENABLE_EMAIL_PASSWORD\n\n // Guard on the *final* merged config, after overrides.socialProviders is applied —\n // this only fails when there's truly no way to sign in. A project that disables both\n // built-ins via AUTH_ENABLE_GOOGLE=false / AUTH_ENABLE_EMAIL_PASSWORD=false but adds\n // its own provider (e.g. apple) here is a valid config and won't trip this.\n const hasEnabledSocialProvider = Object.values(socialProviders).some(Boolean)\n\n if (!hasEnabledSocialProvider && !emailAndPasswordEnabled) {\n throw new Error(\n \"No auth provider is enabled — every social provider is off and emailAndPassword.enabled is false. \" +\n \"Enable AUTH_ENABLE_GOOGLE / AUTH_ENABLE_EMAIL_PASSWORD, or pass your own provider via createAuth({ socialProviders: {...} }).\"\n )\n }\n\n // Shared by the `baseURL` field below and the passkey plugin's rpID/origin\n // — WebAuthn credentials are bound to this exact origin, so it must never\n // fall back to better-auth's own \"localhost\" passkey default in production.\n const baseURL = getBaseUrl()\n\n const log = overrides.logActivity ?? logActivity\n\n // TOTP (+ backup codes); see lib/two-factor.ts for the options.\n const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {\n issuer: config.APP_NAME,\n passwordless: overrides.twoFactor?.passwordless,\n challengeAfterOAuth: overrides.twoFactor?.challengeAfterOAuth,\n })\n\n // The app's own hooks ride in a plugin: plugin hooks run after the top-level ones\n // below, in plugin order, so the package's guards always run first.\n const appHooks = {\n id: \"app-hooks\",\n hooks: {\n before: overrides.hooks?.before ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],\n after: overrides.hooks?.after ? [{ matcher: () => true, handler: overrides.hooks.after }] : [],\n },\n } satisfies BetterAuthPlugin\n\n return betterAuth({\n database: drizzleAdapter(db, {\n provider: \"pg\",\n schema: {\n user: users,\n account: accounts,\n session: sessions,\n verification: verifications,\n twoFactor: twoFactors,\n passkey: passkeys,\n },\n }),\n\n // Session configuration (30 days expiration matching previous NextAuth setup)\n session: {\n expiresIn: 60 * 60 * 24 * 30, // 30 days\n updateAge: 60 * 60 * 24, // Update session every 24 hours\n cookieCache: {\n enabled: true, // Enable hybrid session caching for performance\n maxAge: 5 * 60, // 5 minutes\n }\n },\n\n // Email & Password Authentication (replaces Credentials provider)\n // Toggle per-project via AUTH_ENABLE_EMAIL_PASSWORD in that project's own .env.*\n emailAndPassword: {\n enabled: emailAndPasswordEnabled,\n requireEmailVerification: false,\n // `url` is fully composed by better-auth (baseURL + verification token +\n // callbackURL) — see app/(auth)/forgot-password and reset-password for\n // the pages this points at.\n async sendResetPassword({ user, url }) {\n const { EmailTemplateResetPassword } = await import(\"@/components/email/auth/reset-password\")\n await (await getResend()).emails.send({\n from: EMAIL_FROM,\n to: [user.email],\n subject: \"Reset your password\",\n react: EmailTemplateResetPassword({ firstName: user.name || \"there\", url }),\n })\n },\n },\n\n // Email verification. `requireEmailVerification` above stays false, so this\n // is opt-in: users trigger it from the dashboard via\n // authClient.sendVerificationEmail(). better-auth composes `url`\n // (baseURL + token + callbackURL) and serves the /api/auth/verify-email\n // callback that flips users.emailVerified on click.\n emailVerification: {\n autoSignInAfterVerification: true,\n async afterEmailVerification(user) {\n await promoteFirstAdmin(user)\n },\n async sendVerificationEmail({ user, url }) {\n const { EmailTemplateVerifyEmail } = await import(\"@/components/email/auth/verify-email\")\n await (await getResend()).emails.send({\n from: EMAIL_FROM,\n to: [user.email],\n subject: \"Confirm your email\",\n react: EmailTemplateVerifyEmail({ firstName: user.name || \"there\", url }),\n })\n },\n },\n\n // Social Providers — google is included by default; toggle per-project via\n // AUTH_ENABLE_GOOGLE. overrides.socialProviders can still add more (or replace it).\n socialProviders,\n\n // User schema configuration\n user: {\n additionalFields: {\n role: {\n type: \"string\",\n required: false,\n defaultValue: \"user\",\n input: false, // Prevent users from setting their own role\n },\n },\n // Self-service \"Delete account\" (dashboard Settings → Danger zone).\n // Credential users confirm with their password; OAuth-only users have\n // no password, so better-auth instead requires a session younger than\n // `freshAge` (default 1 day). Every user-owned table cascades on delete.\n // Impersonation and last-admin guards live in hooks.before below.\n deleteUser: { enabled: overrides.deleteUser ?? true },\n },\n\n // Advanced options\n advanced: {\n ...overrides.advanced,\n database: {\n generateId: () => createId(),\n },\n },\n\n rateLimit: overrides.rateLimit,\n\n databaseHooks: {\n user: {\n create: {\n async after(user, context) {\n await promoteFirstAdmin(user)\n await overrides.databaseHooks?.user?.create?.after?.(user, context)\n },\n },\n },\n session: {\n create: {\n async after(session, context) {\n await packageSessionCreated(log, session, context)\n await overrides.databaseHooks?.session?.create?.after?.(session, context)\n },\n },\n },\n },\n // better-auth's admin plugin ends impersonation by deleting the\n // impersonation session and restoring the admin's original session\n // straight from a signed cookie — it never runs session.create, so\n // there's no databaseHooks entry point to log the stop event from.\n // Reading the session here (before the endpoint deletes it) is the only\n // point where both the admin id and the impersonated user id are still\n // available together.\n hooks: {\n before: createAuthMiddleware(async (ctx) => {\n // Per-device abuse throttle for the two credential entry points.\n // Primarily keyed by the client's FingerprintJS visitorId\n // (x-device-fingerprint header, set in emailPasswordLogin/Signup), but\n // that header is client-supplied and unsigned — omitting it or\n // randomizing it per request bypasses a fingerprint-only check\n // entirely. IP is a lower-ceiling-tolerant backstop (shared behind\n // NAT/CGNAT/VPN, so it uses MAX_IP, not MAX) that still applies when\n // the header is missing or spoofed.\n if (ctx.path === \"/sign-in/email\" || ctx.path === \"/sign-up/email\") {\n const fingerprint = ctx.headers?.get(DEVICE_FINGERPRINT_HEADER)\n const ip = getClientIp(ctx.headers)\n const throttled =\n (fingerprint && (await isDeviceThrottled(fingerprint))) ||\n (ip && (await isDeviceThrottled(`ip:${ip}`, MAX_IP)))\n if (throttled) {\n throw new APIError(\"TOO_MANY_REQUESTS\", {\n message: \"Too many attempts from this device. Try again in a few minutes.\",\n })\n }\n }\n\n // Live kill-switch for the two built-in sign-in methods, on top of\n // the (untouched) provider registration above — lets an admin\n // disable a method from the System Settings page and have it take\n // effect immediately, even for a client that already has the button\n // rendered, instead of only on next deploy.\n if (ctx.path === \"/sign-in/social\") {\n // Scoped to \"google\" specifically since overrides.socialProviders\n // can register other providers (e.g. apple) this flag shouldn't gate.\n if (ctx.body?.provider === \"google\") {\n const flags = await getEffectiveAuthFlags()\n if (!flags.google) {\n throw new APIError(\"FORBIDDEN\", { message: \"Google sign-in is currently disabled.\" })\n }\n }\n return\n }\n\n if (ctx.path === \"/sign-in/email\") {\n const flags = await getEffectiveAuthFlags()\n if (!flags.emailPassword) {\n throw new APIError(\"FORBIDDEN\", { message: \"Email/password sign-in is currently disabled.\" })\n }\n return\n }\n\n // One Tap isn't a separate identity, it's a UI shortcut into the\n // same Google account — its plugin hits its own endpoint entirely\n // (not /sign-in/social), so it needs its own guard, and it needs\n // both flags: Google itself must still be allowed, and the One Tap\n // prompt specifically must be enabled.\n if (ctx.path === \"/one-tap/callback\") {\n const flags = await getEffectiveAuthFlags()\n if (!flags.google || !flags.oneTap) {\n throw new APIError(\"FORBIDDEN\", { message: \"Google One Tap is currently disabled.\" })\n }\n return\n }\n\n // The plugin's other /admin/* endpoints (set-user-password, set-role, ban-user,\n // remove-user, create-user...) would bypass our audit log and last-admin guard.\n // Block them over HTTP only (ctx.request is unset for server-side auth.api calls,\n // e.g. the invite route's createUser).\n if (\n ctx.request &&\n ctx.path?.startsWith(\"/admin/\") &&\n ctx.path !== \"/admin/impersonate-user\" &&\n ctx.path !== \"/admin/stop-impersonating\"\n ) {\n throw new APIError(\"FORBIDDEN\", { message: \"Use the dashboard to manage users.\" })\n }\n\n // The admin plugin stays registered either way (dropping it changes the\n // inferred session type); with impersonation off, its endpoint is closed here.\n if (ctx.path === \"/admin/impersonate-user\" && overrides.impersonation === false) {\n throw new APIError(\"FORBIDDEN\", { message: \"Impersonation is turned off.\" })\n }\n\n if (ctx.path === \"/delete-user\") {\n const current = await getSessionFromCtx(ctx, { disableCookieCache: true })\n if (!current) return // better-auth's own session check rejects it\n // An admin \"viewing as\" a user must not be able to destroy their account.\n if (current.session.impersonatedBy) {\n throw new APIError(\"FORBIDDEN\", { message: \"Stop impersonating before deleting an account.\" })\n }\n // Deleting the last admin would leave nobody able to reach the admin dashboard.\n if ((current.user as { role?: string }).role === \"admin\") {\n // Same rule as the admin routes: another *active* (unbanned) admin must remain.\n const [other] = await db\n .select({ n: sql`1` })\n .from(users)\n .where(otherActiveAdminExists([current.user.id]))\n .limit(1)\n if (!other) {\n throw new APIError(\"FORBIDDEN\", { message: \"You're the only admin. Promote another user to admin first.\" })\n }\n }\n return\n }\n\n if (ctx.path !== \"/admin/stop-impersonating\") return\n\n const current = await getSessionFromCtx(ctx, { disableCookieCache: true })\n if (current?.session.impersonatedBy) {\n const target = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.id, current.session.userId))\n .limit(1)\n\n await log({\n userId: current.session.impersonatedBy,\n action: 'impersonation_stopped',\n description: `Admin stopped impersonating ${target[0]?.email ?? current.session.userId}`,\n metadata: { impersonatedUserId: current.session.userId },\n })\n }\n }),\n after: createAuthMiddleware(async (ctx) => {\n // Passkey add/remove is a security-sensitive change to how the account\n // can be signed into — email the user whenever one lands, the same way\n // new-device sign-ins are surfaced. Best-effort: never disturb the\n // endpoint's own response.\n if (ctx.path === \"/passkey/verify-registration\" || ctx.path === \"/passkey/delete-passkey\") {\n if (ctx.context.returned instanceof APIError) return\n await notifyPasskeyChange(\n ctx,\n ctx.path === \"/passkey/verify-registration\" ? \"added\" : \"removed\",\n log,\n )\n return\n }\n\n if (ctx.path !== \"/sign-in/email\" && ctx.path !== \"/sign-up/email\") return\n\n const fingerprint = ctx.headers?.get(DEVICE_FINGERPRINT_HEADER)\n const ip = getClientIp(ctx.headers)\n const ipKey = ip ? `ip:${ip}` : null\n if (!fingerprint && !ipKey) return\n\n const failed = ctx.context.returned instanceof APIError\n const rawEmail = (ctx.body as { email?: unknown } | undefined)?.email\n const meta = {\n ipAddress: ip,\n userAgent: ctx.headers?.get(\"user-agent\") ?? null,\n email: typeof rawEmail === \"string\" ? rawEmail.toLowerCase() : null,\n }\n const keys = [fingerprint, ipKey].filter((k): k is string => !!k)\n\n // Sign-up abuse is mass account creation — the *successful* ones are\n // the problem — so every sign-up from this device counts.\n if (ctx.path === \"/sign-up/email\") {\n await Promise.all(keys.map((key) => recordDeviceAttempt(key, { ...meta, kind: \"signup\" })))\n return\n }\n\n // /sign-in/email: count failures. A success does NOT clear the\n // counter (an attacker with their own account could log in between\n // guesses to reset it); it expires with the window.\n if (failed) {\n await Promise.all(keys.map((key) => recordDeviceAttempt(key, { ...meta, kind: \"signin\" })))\n await logFailedLogin(ctx, log)\n }\n }),\n },\n\n // Base URL for callbacks\n baseURL,\n\n // Secret for signing cookies and tokens\n secret: process.env.AUTH_SECRET!,\n\n // The OAuth `state` is a one-time verification row: the callback consumes\n // and deletes it. When the same callback URL gets hit twice (browser\n // prefetch / bfcache / double nav — common on a repeat Google sign-in\n // where Google auto-redirects with no consent screen), the first hit\n // logs the user in and the second finds no `state` row and throws\n // `please_restart_the_process`. Default sends that to better-auth's bare\n // error page; point it at /login instead, which already bounces an\n // authenticated user straight to their callbackUrl — so the losing race\n // just lands them logged in. See better-auth#5658 / #6544.\n onAPIError: {\n errorURL: \"/login\",\n },\n\n plugins: [\n // Registered for impersonation (auth.api.impersonateUser / stopImpersonating)\n // only — role/ban/delete stay on our own custom routes above. adminRoles\n // matches our existing role column so the plugin's own permission checks\n // line up with hasRole(role, 'admin'). banReason is remapped onto our\n // existing bannedReason column instead of adding a duplicate field.\n adminPlugin({\n adminRoles: [\"admin\"],\n schema: {\n user: {\n fields: {\n banReason: \"bannedReason\",\n },\n },\n },\n }),\n // TOTP second factor + encrypted backup codes (see lib/two-factor.ts).\n // Listed individually, not spread: see the note on the spread below.\n twoFactorPlugin,\n twoFactorExtras,\n // WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a\n // passwordless sign-in method. rpID must be the bare host and origin\n // the full URL — both derived from baseURL above.\n passkey({\n rpID: new URL(baseURL).hostname,\n rpName: config.APP_NAME,\n origin: baseURL,\n }),\n // checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.\n // Keep this spread last: a leading spread turns `plugins` from a tuple into a plain\n // array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).\n ...(config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [oneTap()] : []),\n appHooks,\n ...(overrides.plugins ?? []),\n ]\n })\n}\n\n// Lazy: constructing the default instance validates config and throws if no\n// provider is enabled (see the guard above). Building it eagerly at module\n// load would mean a downstream project that only imports `createAuth` to\n// build its *own* customized instance (README §5) still pays that throw —\n// merely importing this module would run it, regardless of whether the\n// consuming project ever touches this default export. Deferring construction\n// to first property access means the throw only fires for code that actually\n// uses the package's own unconfigured `auth` singleton.\nlet _auth: ReturnType<typeof createAuth> | undefined\nfunction getDefaultAuth() {\n if (!_auth) _auth = createAuth()\n return _auth\n}\n\nexport const auth = new Proxy({} as ReturnType<typeof createAuth>, {\n get(_target, prop) {\n const instance = getDefaultAuth()\n const value = Reflect.get(instance, prop)\n return typeof value === \"function\" ? value.bind(instance) : value\n },\n // \"prop\" in auth (e.g. better-auth's toNextJsHandler does `\"handler\" in auth`)\n // must also see the real instance — without this it checks the empty\n // placeholder target and always reports false.\n has(_target, prop) {\n return Reflect.has(getDefaultAuth(), prop)\n },\n ownKeys(_target) {\n return Reflect.ownKeys(getDefaultAuth())\n },\n getOwnPropertyDescriptor(_target, prop) {\n return Reflect.getOwnPropertyDescriptor(getDefaultAuth(), prop)\n },\n})\n"]}