@xk2800/nextjs-template 0.7.1-beta.3 → 0.7.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/components/auth/deviceCheck.tsx +47 -6
- package/components/auth/oneTap.tsx +5 -5
- package/components/dashboard/admin/adminUserConsentCard.tsx +79 -0
- package/components/dashboard/admin/adminUserDevicesCard.tsx +80 -0
- package/components/dashboard/admin/systemSettingsForm.tsx +33 -0
- package/components/dashboard/admin/systemSettingsSection.tsx +8 -2
- package/components/site/cookie-banner.tsx +109 -7
- package/dist/activity/logger.js +30 -0
- package/dist/activity/logger.js.map +1 -1
- package/dist/activity/logger.mjs +3 -3
- package/dist/activity/queries.d.mts +1 -1
- package/dist/activity/queries.d.ts +1 -1
- package/dist/activity/queries.js +30 -0
- package/dist/activity/queries.js.map +1 -1
- package/dist/activity/queries.mjs +2 -2
- package/dist/admin/queries.d.mts +19 -1
- package/dist/admin/queries.d.ts +19 -1
- package/dist/admin/queries.js +58 -0
- package/dist/admin/queries.js.map +1 -1
- package/dist/admin/queries.mjs +25 -4
- package/dist/admin/queries.mjs.map +1 -1
- package/dist/api/feedback.js +46 -2
- package/dist/api/feedback.js.map +1 -1
- package/dist/api/feedback.mjs +7 -7
- package/dist/auth/helpers.js +44 -0
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/helpers.mjs +6 -6
- package/dist/auth/index.js +44 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/index.mjs +6 -6
- package/dist/{chunk-XWVAJXAG.mjs → chunk-4GGLYS5R.mjs} +20 -8
- package/dist/chunk-4GGLYS5R.mjs.map +1 -0
- package/dist/{chunk-KAEA35OC.mjs → chunk-6KTSULA5.mjs} +4 -4
- package/dist/{chunk-KAEA35OC.mjs.map → chunk-6KTSULA5.mjs.map} +1 -1
- package/dist/{chunk-N6ECRCHY.mjs → chunk-6OAHCEDJ.mjs} +4 -3
- package/dist/chunk-6OAHCEDJ.mjs.map +1 -0
- package/dist/{chunk-3MGEAGHU.mjs → chunk-F776DQAM.mjs} +10 -5
- package/dist/chunk-F776DQAM.mjs.map +1 -0
- package/dist/{chunk-WZDAMCUX.mjs → chunk-F7CG5CA3.mjs} +3 -3
- package/dist/{chunk-WZDAMCUX.mjs.map → chunk-F7CG5CA3.mjs.map} +1 -1
- package/dist/{chunk-VQ5B4MA7.mjs → chunk-FVLMSLTX.mjs} +4 -4
- package/dist/{chunk-VQ5B4MA7.mjs.map → chunk-FVLMSLTX.mjs.map} +1 -1
- package/dist/{chunk-ZQCALTKB.mjs → chunk-TR5XFBTD.mjs} +34 -4
- package/dist/chunk-TR5XFBTD.mjs.map +1 -0
- package/dist/db/index.d.mts +1 -1
- package/dist/db/index.d.ts +1 -1
- package/dist/db/index.js +30 -0
- package/dist/db/index.js.map +1 -1
- package/dist/db/index.mjs +2 -2
- package/dist/db/schema.d.mts +1 -1
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.js +30 -0
- package/dist/db/schema.js.map +1 -1
- package/dist/db/schema.mjs +1 -1
- package/dist/errors.js +30 -0
- package/dist/errors.js.map +1 -1
- package/dist/errors.mjs +3 -3
- package/dist/{schema-UuqxoOzS.d.mts → schema-CN_Y6EXv.d.mts} +148 -2
- package/dist/{schema-UuqxoOzS.d.ts → schema-CN_Y6EXv.d.ts} +148 -2
- package/dist/sessions/queries.js +30 -0
- package/dist/sessions/queries.js.map +1 -1
- package/dist/sessions/queries.mjs +2 -2
- package/dist/settings/queries.d.mts +4 -3
- package/dist/settings/queries.d.ts +4 -3
- package/dist/settings/queries.js +36 -0
- package/dist/settings/queries.js.map +1 -1
- package/dist/settings/queries.mjs +3 -3
- package/dist/users/queries.js +30 -0
- package/dist/users/queries.js.map +1 -1
- package/dist/users/queries.mjs +2 -2
- package/lib/cookie-consent.ts +72 -20
- package/lib/cookie-names.ts +47 -0
- package/lib/device-fingerprint.ts +66 -10
- package/package.json +7 -2
- package/dist/chunk-3MGEAGHU.mjs.map +0 -1
- package/dist/chunk-N6ECRCHY.mjs.map +0 -1
- package/dist/chunk-XWVAJXAG.mjs.map +0 -1
- package/dist/chunk-ZQCALTKB.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../server/db/schema.ts","../../lib/maintenance.ts","../../config/env-schema.ts","../../config/env.ts","../../server/db/index.ts","../../lib/user-queries.ts"],"names":["pgEnum","pgTable","text","createId","boolean","timestamp","integer","unique","check","sql","index","z","Pool","drizzlePg","neon","drizzle","eq","or","like","desc"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,IAAA,cAAA,GAAA,EAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,SAAA,EAAA,MAAA,SAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,cAAA,EAAA,MAAA,cAAA;AAAA,EAAA,UAAA,EAAA,MAAA,UAAA;AAAA,EAAA,KAAA,EAAA,MAAA,KAAA;AAAA,EAAA,aAAA,EAAA,MAAA;AAAA,CAAA,CAAA;;;ACIO,IAAM,gCAAA,GAAmC;AAAA,EAC9C,GAAA;AAAA,EACA,WAAA;AAAA,EACA,YAAA;AAAA,EACA,qBAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA;;;ADJO,IAAM,WAAWA,aAAA,CAAO,OAAA,EAAS,CAAC,MAAA,EAAQ,OAAA,EAAS,QAAQ,CAAC,CAAA;AAE5D,IAAM,kBAAA,GAAqBA,cAAO,kBAAA,EAAoB;AAAA,EAC3D,OAAA;AAAA,E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AE,KAAA,EAAOV,cAAAA,CAAAA,QAAAA,CAAAA,EAAuB,CAAA,CACvC,IAAA,CAAK,KAAK,CAAA,CACV,KAAA,CAAM,KAAK;AAAA,GACf,CAAA;AAED,EAAA,MAAM,KAAA,GAAQ,QAAO,EAAA,GAAA,CAAA,EAAA,GAAA,WAAA,CAAY,CAAC,MAAb,IAAA,GAAA,MAAA,GAAA,EAAA,CAAgB,KAAA,KAAhB,YAAyB,CAAC,CAAA;AAE/C,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,SAAA;AAAA,IACP,KAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA;AAAA,IACA,KAAA,EAAO,IAAA,CAAK,IAAA,CAAK,KAAA,GAAQ,KAAK;AAAA,GAChC;AACF;AAOA,IAAM,gBAAA,GAAmB,GAAA;AAEzB,eAAsB,iBAAA,CAAkB,EAAE,MAAA,GAAS,EAAA,EAAG,EAAsB;AAC1E,EAAA,MAAM,KAAA,GAAQ,gBAAgB,MAAM,CAAA;AAEpC,EAAA,OAAO,GACJ,MAAA,EAAO,CACP,IAAA,CAAK,KAAK,EACV,KAAA,CAAM,KAAK,CAAA,CACX,OAAA,CAAQU,gBAAK,KAAA,CAAM,SAAS,CAAC,CAAA,CAC7B,MAAM,gBAAgB,CAAA;AAC3B","file":"queries.js","sourcesContent":["import { boolean, check, index, integer, 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/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 // 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});\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 userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\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});\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 createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n}, (table) => [\n unique(\"device_fingerprint_user_visitor\").on(table.userId, table.visitorId),\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 whose window has elapsed are dead weight but harmless\n// (reset on the next attempt) — prune on a cron if the table ever grows.\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 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","// 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 \"/changelog-template\",\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 // Sender for every transactional email. Must be on a domain verified in\n // your Resend account.\n EMAIL_FROM: z.string().default('Acme <onboarding@xavierkhew.xyz>'),\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 // 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});\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","import 'server-only';\n\n// neon-http driver for production\nimport { neon } 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';\n\n// Import the query builder\nimport { PostgresJsDatabase } from 'drizzle-orm/postgres-js';\nimport { NeonHttpDatabase } from 'drizzle-orm/neon-http';\n\ntype DrizzleNeon = NeonHttpDatabase<typeof schema>;\ntype DrizzlePg = PostgresJsDatabase<typeof schema>;\n\nlet db: DrizzleNeon | DrizzlePg\n\n\nif (config.DB_DRIVER === 'pg') {\n const pool = new Pool({\n connectionString: config.DATABASE_URL!,\n ssl: config.DATABASE_SSL ? { rejectUnauthorized: false } : undefined,\n });\n db = drizzlePg(pool, {\n schema,\n logger: true,\n });\n\n console.log('🟡 Using PostgreSQL (pg) driver');\n\n} else if (config.DB_DRIVER === 'neon') {\n const sql = neon(config.DATABASE_URL!);\n db = drizzle(sql, { schema, logger: true });\n\n console.log('🟢 Using Neon (HTTP) driver');\n\n} else {\n console.log('Database connection not established, unknown DB_DRIVER:', config.DB_DRIVER);\n}\n// Note: In production, you might want to disable logging or use a more sophisticated logger.\n\nexport { db }","import \"server-only\"\nimport { db } from \"../server/db\"\nimport { users } from \"../server/db/schema\"\nimport { like, desc, or, eq, sql, type SQL } from \"drizzle-orm\"\n\nexport async function getUserById(id: string) {\n const result = await db\n .select()\n .from(users)\n .where(eq(users.id, id))\n .limit(1)\n\n return result[0] || null\n}\n\n// Recipients for security alerts (new-device sign-ins, etc.). Every admin.\nexport async function getAdminEmails(): Promise<string[]> {\n const rows = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.role, \"admin\"))\n\n return rows.map((r) => r.email)\n}\n\nexport interface UserFilters {\n search?: string\n page?: number\n limit?: number\n}\n\nfunction buildUsersWhere(search: string): SQL | undefined {\n return search.trim()\n ? (or(\n like(users.name, `%${search}%`),\n like(users.email, `%${search}%`)\n ) as SQL)\n : undefined\n}\n\nexport async function getUsersFiltered({ search = \"\", page = 1, limit = 10 }: UserFilters) {\n const offset = (page - 1) * limit\n\n const where = buildUsersWhere(search)\n\n const [usersList, countResult] = await Promise.all([\n db\n .select()\n .from(users)\n .where(where)\n .orderBy(desc(users.createdAt))\n .limit(limit)\n .offset(offset),\n db\n .select({ count: sql<number>`count(*)` })\n .from(users)\n .where(where),\n ])\n\n const total = Number(countResult[0]?.count ?? 0)\n\n return {\n users: usersList,\n total,\n page,\n limit,\n pages: Math.ceil(total / limit),\n }\n}\n\nexport interface UserExportFilters {\n search?: string\n}\n\n// Caps export size to keep the CSV response bounded on very large tables.\nconst EXPORT_ROW_LIMIT = 10_000\n\nexport async function getUsersForExport({ search = \"\" }: UserExportFilters) {\n const where = buildUsersWhere(search)\n\n return db\n .select()\n .from(users)\n .where(where)\n .orderBy(desc(users.createdAt))\n .limit(EXPORT_ROW_LIMIT)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../server/db/schema.ts","../../lib/maintenance.ts","../../config/env-schema.ts","../../config/env.ts","../../server/db/index.ts","../../lib/user-queries.ts"],"names":["pgEnum","pgTable","text","createId","boolean","timestamp","integer","jsonb","unique","index","check","sql","z","Pool","drizzlePg","neon","drizzle","eq","or","like","desc"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,IAAA,cAAA,GAAA,EAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,YAAA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,KAAA,CAAM,SAAS,CAAC,CAAA,CAC7B,MAAM,gBAAgB,CAAA;AAC3B","file":"queries.js","sourcesContent":["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/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 // 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});\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 userId: text(\"userId\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\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});\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","// 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 \"/changelog-template\",\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 // Sender for every transactional email. Must be on a domain verified in\n // your Resend account.\n EMAIL_FROM: z.string().default('Acme <onboarding@xavierkhew.xyz>'),\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 // 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});\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","import 'server-only';\n\n// neon-http driver for production\nimport { neon } 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';\n\n// Import the query builder\nimport { PostgresJsDatabase } from 'drizzle-orm/postgres-js';\nimport { NeonHttpDatabase } from 'drizzle-orm/neon-http';\n\ntype DrizzleNeon = NeonHttpDatabase<typeof schema>;\ntype DrizzlePg = PostgresJsDatabase<typeof schema>;\n\nlet db: DrizzleNeon | DrizzlePg\n\n\nif (config.DB_DRIVER === 'pg') {\n const pool = new Pool({\n connectionString: config.DATABASE_URL!,\n ssl: config.DATABASE_SSL ? { rejectUnauthorized: false } : undefined,\n });\n db = drizzlePg(pool, {\n schema,\n logger: true,\n });\n\n console.log('🟡 Using PostgreSQL (pg) driver');\n\n} else if (config.DB_DRIVER === 'neon') {\n const sql = neon(config.DATABASE_URL!);\n db = drizzle(sql, { schema, logger: true });\n\n console.log('🟢 Using Neon (HTTP) driver');\n\n} else {\n console.log('Database connection not established, unknown DB_DRIVER:', config.DB_DRIVER);\n}\n// Note: In production, you might want to disable logging or use a more sophisticated logger.\n\nexport { db }","import \"server-only\"\nimport { db } from \"../server/db\"\nimport { users } from \"../server/db/schema\"\nimport { like, desc, or, eq, sql, type SQL } from \"drizzle-orm\"\n\nexport async function getUserById(id: string) {\n const result = await db\n .select()\n .from(users)\n .where(eq(users.id, id))\n .limit(1)\n\n return result[0] || null\n}\n\n// Recipients for security alerts (new-device sign-ins, etc.). Every admin.\nexport async function getAdminEmails(): Promise<string[]> {\n const rows = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.role, \"admin\"))\n\n return rows.map((r) => r.email)\n}\n\nexport interface UserFilters {\n search?: string\n page?: number\n limit?: number\n}\n\nfunction buildUsersWhere(search: string): SQL | undefined {\n return search.trim()\n ? (or(\n like(users.name, `%${search}%`),\n like(users.email, `%${search}%`)\n ) as SQL)\n : undefined\n}\n\nexport async function getUsersFiltered({ search = \"\", page = 1, limit = 10 }: UserFilters) {\n const offset = (page - 1) * limit\n\n const where = buildUsersWhere(search)\n\n const [usersList, countResult] = await Promise.all([\n db\n .select()\n .from(users)\n .where(where)\n .orderBy(desc(users.createdAt))\n .limit(limit)\n .offset(offset),\n db\n .select({ count: sql<number>`count(*)` })\n .from(users)\n .where(where),\n ])\n\n const total = Number(countResult[0]?.count ?? 0)\n\n return {\n users: usersList,\n total,\n page,\n limit,\n pages: Math.ceil(total / limit),\n }\n}\n\nexport interface UserExportFilters {\n search?: string\n}\n\n// Caps export size to keep the CSV response bounded on very large tables.\nconst EXPORT_ROW_LIMIT = 10_000\n\nexport async function getUsersForExport({ search = \"\" }: UserExportFilters) {\n const where = buildUsersWhere(search)\n\n return db\n .select()\n .from(users)\n .where(where)\n .orderBy(desc(users.createdAt))\n .limit(EXPORT_ROW_LIMIT)\n}\n"]}
|
package/dist/users/queries.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { db } from '../chunk-
|
|
2
|
-
import { users } from '../chunk-
|
|
1
|
+
import { db } from '../chunk-F7CG5CA3.mjs';
|
|
2
|
+
import { users } from '../chunk-TR5XFBTD.mjs';
|
|
3
3
|
import '../chunk-TMJYAOC2.mjs';
|
|
4
4
|
import '../chunk-3465SI5N.mjs';
|
|
5
5
|
import 'server-only';
|
package/lib/cookie-consent.ts
CHANGED
|
@@ -1,45 +1,86 @@
|
|
|
1
1
|
import { useSyncExternalStore } from "react"
|
|
2
|
+
import {
|
|
3
|
+
COOKIE_CONSENT_COOKIE,
|
|
4
|
+
CONSENT_REQUIRED_COOKIE,
|
|
5
|
+
CONSENT_PURPOSES,
|
|
6
|
+
consentAllows,
|
|
7
|
+
type ConsentPurpose,
|
|
8
|
+
} from "./cookie-names"
|
|
9
|
+
|
|
10
|
+
// Server code (proxy.ts, route handlers) imports these from cookie-names.ts
|
|
11
|
+
// instead: this module uses a React hook, which server modules can't import.
|
|
12
|
+
export { COOKIE_CONSENT_COOKIE, CONSENT_REQUIRED_COOKIE, CONSENT_PURPOSES, type ConsentPurpose }
|
|
2
13
|
|
|
3
14
|
// Cookie-consent state, shared by the banner (components/site/cookie-banner.tsx)
|
|
4
|
-
// and everything that needs consent before it runs
|
|
5
|
-
// lib/device-fingerprint.ts
|
|
6
|
-
// "
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
15
|
+
// and everything that needs consent before it runs. One choice per purpose:
|
|
16
|
+
// "fingerprint" — FingerprintJS device id (lib/device-fingerprint.ts)
|
|
17
|
+
// "onetap" — Google One Tap (components/auth/oneTap.tsx)
|
|
18
|
+
// Gate on hasConsentFor() / useConsentFor(). useCookieConsent() summarises:
|
|
19
|
+
// "all" — every purpose accepted (gate your own analytics on this)
|
|
20
|
+
// "necessary" — none accepted
|
|
21
|
+
// "custom" — some, picked under "Customize"
|
|
10
22
|
//
|
|
11
23
|
// Stored in a first-party cookie, not localStorage, so a server component can
|
|
12
24
|
// read it too if a project ever needs to (cookies().get(COOKIE_CONSENT_COOKIE)).
|
|
13
|
-
|
|
14
|
-
|
|
25
|
+
//
|
|
26
|
+
// When consent isn't required (CONSENT_REQUIRED_COOKIE = "0") there's no
|
|
27
|
+
// banner and everything gated on consent runs as if the visitor accepted.
|
|
28
|
+
export type CookieConsent = "all" | "necessary" | "custom"
|
|
15
29
|
|
|
16
30
|
const CHANGE_EVENT = "cookie-consent-change"
|
|
17
31
|
const MAX_AGE = 60 * 60 * 24 * 365 // re-ask after a year
|
|
18
32
|
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
33
|
+
// Fallback when the consent_required cookie is missing (server render, or a
|
|
34
|
+
// project whose proxy.ts predates it): NEXT_PUBLIC_COOKIE_BANNER=false means
|
|
35
|
+
// consent isn't required.
|
|
22
36
|
export const COOKIE_BANNER_ENABLED = process.env.NEXT_PUBLIC_COOKIE_BANNER !== "false"
|
|
23
37
|
|
|
24
|
-
export function
|
|
25
|
-
if (
|
|
38
|
+
export function isConsentRequired(): boolean {
|
|
39
|
+
if (typeof document === "undefined") return COOKIE_BANNER_ENABLED
|
|
40
|
+
const match = document.cookie.match(new RegExp(`(?:^|; )${CONSENT_REQUIRED_COOKIE}=([01])`))
|
|
41
|
+
return match ? match[1] === "1" : COOKIE_BANNER_ENABLED
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// The raw cookie value, or null before a choice. "all" when consent isn't required.
|
|
45
|
+
export function readConsent(): string | null {
|
|
46
|
+
if (!isConsentRequired()) return "all"
|
|
26
47
|
if (typeof document === "undefined") return null
|
|
27
|
-
const match = document.cookie.match(new RegExp(`(?:^|; )${COOKIE_CONSENT_COOKIE}=(
|
|
28
|
-
return
|
|
48
|
+
const match = document.cookie.match(new RegExp(`(?:^|; )${COOKIE_CONSENT_COOKIE}=([a-z,]+)`))
|
|
49
|
+
return match?.[1] ?? null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function getCookieConsent(): CookieConsent | null {
|
|
53
|
+
const value = readConsent()
|
|
54
|
+
if (value === null) return null
|
|
55
|
+
if (value === "all" || value === "necessary") return value
|
|
56
|
+
return "custom"
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function hasConsentFor(purpose: ConsentPurpose): boolean {
|
|
60
|
+
return consentAllows(readConsent(), purpose)
|
|
29
61
|
}
|
|
30
62
|
|
|
63
|
+
// Every purpose accepted — what your own analytics etc. should gate on.
|
|
31
64
|
export function hasOptionalConsent(): boolean {
|
|
32
65
|
return getCookieConsent() === "all"
|
|
33
66
|
}
|
|
34
67
|
|
|
68
|
+
// "all" / "necessary", or the list of purposes ticked under "Customize".
|
|
35
69
|
// null clears the choice, which brings the banner back ("Cookie settings").
|
|
36
|
-
export function setCookieConsent(value:
|
|
37
|
-
|
|
38
|
-
?
|
|
70
|
+
export function setCookieConsent(value: "all" | "necessary" | ConsentPurpose[] | null) {
|
|
71
|
+
const stored = Array.isArray(value)
|
|
72
|
+
? value.length === 0
|
|
73
|
+
? "necessary"
|
|
74
|
+
: CONSENT_PURPOSES.every((p) => value.includes(p))
|
|
75
|
+
? "all"
|
|
76
|
+
: value.join(",")
|
|
77
|
+
: value
|
|
78
|
+
document.cookie = stored
|
|
79
|
+
? `${COOKIE_CONSENT_COOKIE}=${stored}; path=/; max-age=${MAX_AGE}; samesite=lax`
|
|
39
80
|
: `${COOKIE_CONSENT_COOKIE}=; path=/; max-age=0; samesite=lax`
|
|
40
|
-
//
|
|
81
|
+
// One Tap declined or withdrawn: drop Google's cooldown cookie. Its script
|
|
41
82
|
// can't be unloaded mid-page, but it won't be loaded again.
|
|
42
|
-
if (
|
|
83
|
+
if (stored && !consentAllows(stored, "onetap")) document.cookie = "g_state=; path=/; max-age=0"
|
|
43
84
|
window.dispatchEvent(new Event(CHANGE_EVENT))
|
|
44
85
|
}
|
|
45
86
|
|
|
@@ -52,3 +93,14 @@ function subscribe(onChange: () => void) {
|
|
|
52
93
|
export function useCookieConsent(): CookieConsent | null {
|
|
53
94
|
return useSyncExternalStore(subscribe, getCookieConsent, () => null)
|
|
54
95
|
}
|
|
96
|
+
|
|
97
|
+
// Live per-purpose consent. false on the server and until the visitor chooses.
|
|
98
|
+
export function useConsentFor(purpose: ConsentPurpose): boolean {
|
|
99
|
+
return useSyncExternalStore(subscribe, () => hasConsentFor(purpose), () => false)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// For UI that only exists in consent mode (banner, "Cookie settings" link).
|
|
103
|
+
// The env default on the server, the proxy-set cookie after hydration.
|
|
104
|
+
export function useConsentRequired(): boolean {
|
|
105
|
+
return useSyncExternalStore(subscribe, isConsentRequired, () => COOKIE_BANNER_ENABLED)
|
|
106
|
+
}
|
package/lib/cookie-names.ts
CHANGED
|
@@ -11,3 +11,50 @@ export const LOGIN_REFERRER_COOKIE = 'login_referrer'
|
|
|
11
11
|
// (see lib/auth-throttle.ts). A header, not a cookie, so it's only sent on
|
|
12
12
|
// the auth calls that need it, not every request.
|
|
13
13
|
export const DEVICE_FINGERPRINT_HEADER = 'x-device-fingerprint'
|
|
14
|
+
|
|
15
|
+
// The visitor's cookie choice (lib/cookie-consent.ts): "all", "necessary", or
|
|
16
|
+
// a comma list of the purposes they ticked under "Customize", e.g.
|
|
17
|
+
// "fingerprint" — one choice per purpose, as regulators like the CNIL expect.
|
|
18
|
+
export const COOKIE_CONSENT_COOKIE = 'cookie_consent'
|
|
19
|
+
|
|
20
|
+
// "fingerprint": FingerprintJS device id (new-device alerts, sign-in throttle,
|
|
21
|
+
// shared-device detection, admin Devices card). "onetap": Google One Tap,
|
|
22
|
+
// whose script may set Google's own cookies.
|
|
23
|
+
export type ConsentPurpose = 'fingerprint' | 'onetap'
|
|
24
|
+
export const CONSENT_PURPOSES: ConsentPurpose[] = ['fingerprint', 'onetap']
|
|
25
|
+
|
|
26
|
+
// Version of the consent wording (banner text + privacy page purposes),
|
|
27
|
+
// stored with each consent record (consent_log.version) so you can show which
|
|
28
|
+
// text a user agreed to. Bump it when that wording changes materially.
|
|
29
|
+
export const CONSENT_VERSION = 1
|
|
30
|
+
|
|
31
|
+
// A well-formed cookie_consent value: "all", "necessary", or a comma list of
|
|
32
|
+
// known purposes. Used to validate what the client sends to app/api/consent.
|
|
33
|
+
export function isValidConsent(value: unknown): value is string {
|
|
34
|
+
if (value === 'all' || value === 'necessary') return true
|
|
35
|
+
if (typeof value !== 'string' || !value) return false
|
|
36
|
+
const parts = value.split(',')
|
|
37
|
+
return new Set(parts).size === parts.length && parts.every((p) => (CONSENT_PURPOSES as string[]).includes(p))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Does a cookie_consent value allow this purpose? Plain function, no React,
|
|
41
|
+
// so route handlers can use it too (app/api/device-check).
|
|
42
|
+
export function consentAllows(value: string | null | undefined, purpose: ConsentPurpose): boolean {
|
|
43
|
+
if (value === 'all') return true
|
|
44
|
+
if (!value || value === 'necessary') return false
|
|
45
|
+
return value.split(',').includes(purpose)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Consent mode, set by proxy.ts from the admin's System Settings toggle
|
|
49
|
+
// ("1" = consent required, "0" = not). Read by lib/cookie-consent.ts.
|
|
50
|
+
export const CONSENT_REQUIRED_COOKIE = 'consent_required'
|
|
51
|
+
|
|
52
|
+
// FingerprintJS signals that are never sent or stored. Accessibility
|
|
53
|
+
// preferences can hint at a disability (GDPR Art. 9 health data); colorGamut
|
|
54
|
+
// mostly tracks display hardware but is read alongside them. Filtered on the
|
|
55
|
+
// client (lib/device-fingerprint.ts) and again on the server
|
|
56
|
+
// (app/api/device-check), since the client can't be trusted.
|
|
57
|
+
export const EXCLUDED_SIGNALS = new Set([
|
|
58
|
+
'reducedMotion', 'reducedTransparency', 'contrast', 'forcedColors',
|
|
59
|
+
'invertedColors', 'monochrome', 'colorGamut',
|
|
60
|
+
])
|
|
@@ -5,23 +5,79 @@
|
|
|
5
5
|
// If @fingerprintjs/fingerprintjs fails to load (e.g. it's blocked in the
|
|
6
6
|
// browser), this resolves to null and callers carry on without a fingerprint.
|
|
7
7
|
//
|
|
8
|
-
// Also resolves to null until the visitor
|
|
9
|
-
// lib/cookie-consent.ts) — not cached, so it starts working the
|
|
10
|
-
// do. Without it the sign-in throttle falls back to its per-IP cap.
|
|
11
|
-
import {
|
|
8
|
+
// Also resolves to null until the visitor consents to the "fingerprint"
|
|
9
|
+
// purpose (see lib/cookie-consent.ts) — not cached, so it starts working the
|
|
10
|
+
// moment they do. Without it the sign-in throttle falls back to its per-IP cap.
|
|
11
|
+
import { hasConsentFor } from "./cookie-consent"
|
|
12
|
+
import { EXCLUDED_SIGNALS } from "./cookie-names"
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
type Fingerprint = { visitorId: string; signals: Record<string, unknown> }
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
let cached: Promise<Fingerprint | null> | undefined
|
|
17
|
+
|
|
18
|
+
// The last computed id is also kept in localStorage (only while consent is
|
|
19
|
+
// given), so that when consent is withdrawn later — usually on another page
|
|
20
|
+
// load — deviceCheck.tsx can ask the server to delete that device's record
|
|
21
|
+
// without fingerprinting the browser again.
|
|
22
|
+
const STORAGE_KEY = "device-visitor-id"
|
|
23
|
+
|
|
24
|
+
// Canvas/WebGL/audio values run to tens of KB (canvas is image data URLs).
|
|
25
|
+
// Past this size a signal is stored as its hash — enough to compare devices,
|
|
26
|
+
// useless to read anyway.
|
|
27
|
+
const MAX_SIGNAL_CHARS = 500
|
|
28
|
+
|
|
29
|
+
function fingerprint(): Promise<Fingerprint | null> {
|
|
30
|
+
if (!hasConsentFor("fingerprint")) return Promise.resolve(null)
|
|
17
31
|
cached ??= (async () => {
|
|
18
32
|
try {
|
|
19
|
-
const FingerprintJS =
|
|
20
|
-
|
|
21
|
-
|
|
33
|
+
const FingerprintJS = await import("@fingerprintjs/fingerprintjs")
|
|
34
|
+
// monitoring: false — otherwise ~0.1% of loads ping openfpcdn.io for
|
|
35
|
+
// install stats, sending the visitor's IP to a third party.
|
|
36
|
+
const { visitorId, components } = await (await FingerprintJS.load({ monitoring: false })).get()
|
|
37
|
+
if (!visitorId) return null
|
|
38
|
+
try {
|
|
39
|
+
localStorage.setItem(STORAGE_KEY, visitorId)
|
|
40
|
+
} catch {
|
|
41
|
+
// No localStorage — withdrawal just can't clean up this device's row.
|
|
42
|
+
}
|
|
43
|
+
const signals: Record<string, unknown> = {}
|
|
44
|
+
for (const [name, component] of Object.entries(components)) {
|
|
45
|
+
if (EXCLUDED_SIGNALS.has(name)) continue
|
|
46
|
+
const value = "error" in component ? { error: String(component.error) } : component.value
|
|
47
|
+
const json = JSON.stringify(value) ?? "null"
|
|
48
|
+
signals[name] = json.length > MAX_SIGNAL_CHARS ? { hash: FingerprintJS.murmurX64Hash128(json) } : value
|
|
49
|
+
}
|
|
50
|
+
return { visitorId, signals }
|
|
22
51
|
} catch {
|
|
23
52
|
return null
|
|
24
53
|
}
|
|
25
54
|
})()
|
|
26
55
|
return cached
|
|
27
56
|
}
|
|
57
|
+
|
|
58
|
+
export async function getVisitorId(): Promise<string | null> {
|
|
59
|
+
return (await fingerprint())?.visitorId ?? null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// The raw signals behind the visitorId, for the admin user page (sent by
|
|
63
|
+
// deviceCheck.tsx). Same consent gate as getVisitorId().
|
|
64
|
+
export async function getDeviceSignals(): Promise<Record<string, unknown> | null> {
|
|
65
|
+
return (await fingerprint())?.signals ?? null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function getStoredVisitorId(): string | null {
|
|
69
|
+
try {
|
|
70
|
+
return localStorage.getItem(STORAGE_KEY)
|
|
71
|
+
} catch {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function clearStoredVisitorId() {
|
|
77
|
+
cached = undefined
|
|
78
|
+
try {
|
|
79
|
+
localStorage.removeItem(STORAGE_KEY)
|
|
80
|
+
} catch {
|
|
81
|
+
// ignore — nothing stored then
|
|
82
|
+
}
|
|
83
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xk2800/nextjs-template",
|
|
3
|
-
"version": "0.7.1-beta.
|
|
3
|
+
"version": "0.7.1-beta.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -143,6 +143,11 @@
|
|
|
143
143
|
"./lib/recalculate-columns": "./lib/recalculate-columns.ts",
|
|
144
144
|
"./lib/maintenance": "./lib/maintenance.ts",
|
|
145
145
|
"./lib/cookie-consent": "./lib/cookie-consent.ts",
|
|
146
|
+
"./lib/cookie-names": "./lib/cookie-names.ts",
|
|
147
|
+
"./lib/device-fingerprint": "./lib/device-fingerprint.ts",
|
|
148
|
+
"./lib/request-info": "./lib/request-info.ts",
|
|
149
|
+
"./hooks/use-dimensions": "./hooks/use-dimensions.ts",
|
|
150
|
+
"./hooks/use-mobile": "./hooks/use-mobile.ts",
|
|
146
151
|
"./styles/theme.css": "./styles/theme.css",
|
|
147
152
|
"./components/*": "./components/*.tsx"
|
|
148
153
|
},
|
|
@@ -203,7 +208,7 @@
|
|
|
203
208
|
"build": "npm run build:lib && next build",
|
|
204
209
|
"start": "next start",
|
|
205
210
|
"lint": "next lint",
|
|
206
|
-
"test": "bun lib/recalculate-columns.test.ts && bun lib/auth-throttle-limits.test.ts && bun lib/shared-devices.test.ts && bun lib/maintenance.test.ts && bun lib/install-target.test.ts && bun lib/file-upload-accept.test.ts && bun scripts/bump-version.test.ts",
|
|
211
|
+
"test": "bun lib/recalculate-columns.test.ts && bun lib/auth-throttle-limits.test.ts && bun lib/shared-devices.test.ts && bun lib/maintenance.test.ts && bun lib/install-target.test.ts && bun lib/file-upload-accept.test.ts && bun lib/cookie-names.test.ts && bun scripts/bump-version.test.ts",
|
|
207
212
|
"build:lib": "tsup",
|
|
208
213
|
"storybook": "storybook dev -p 6006",
|
|
209
214
|
"build-storybook": "storybook build",
|
|
@@ -1 +0,0 @@
|
|
|
1
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EAAA,EAAI,eAAe,CAAC,CAAA,CAC5C,SAAA,EAAU;AAEb,EAAA,6BAAA,EAA8B;AAC9B,EAAA,OAAO,OAAA;AACT;AAKA,eAAsB,qBAAA,GAAwB;AAC5C,EAAA,MAAM,QAAA,GAAW,MAAM,iBAAA,EAAkB;AACzC,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,MAAA,CAAO,kBAAA,IAAsB,QAAA,CAAS,gBAAA;AAAA,IAC9C,aAAA,EAAe,MAAA,CAAO,0BAAA,IAA8B,QAAA,CAAS,uBAAA;AAAA,IAC7D,MAAA,EAAQ,MAAA,CAAO,mBAAA,IAAuB,QAAA,CAAS;AAAA,GACjD;AACF;AAMO,SAAS,sBAAA,GAAyB;AACvC,EAAA,OAAO;AAAA,IACL,QAAQ,MAAA,CAAO,kBAAA;AAAA,IACf,eAAe,MAAA,CAAO,0BAAA;AAAA,IACtB,QAAQ,MAAA,CAAO;AAAA,GACjB;AACF","file":"chunk-3MGEAGHU.mjs","sourcesContent":["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 \"./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\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 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 return fallbackSettings() // not cached — retry next request\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'\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// The env-only half of the AND above. The System Settings page needs this\n// to explain *why* a toggle it controls isn't taking effect — flipping the\n// DB flag on can't do anything if the env var for that method is off, so\n// the UI should say so instead of looking like a silent no-op.\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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../lib/request-info.ts","../lib/auth-throttle-limits.ts"],"names":[],"mappings":";;;;;AAIA,IAAM,YAAA,GAAe,IAAI,IAAA,CAAK,YAAA,CAAa,CAAC,IAAI,CAAA,EAAG,EAAE,IAAA,EAAM,QAAA,EAAU,CAAA;AAmB9D,SAAS,YAAY,OAAA,EAAoD;AAvBhF,EAAA,IAAA,EAAA;AAwBE,EAAA,MAAM,YAAA,GAAe,mCAAS,GAAA,CAAI,iBAAA,CAAA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AA;AACjB,EAAA,IAAI,MAAM,GAAA,CAAI,WAAA,CAAY,OAAA,EAAQ,IAAK,WAAW,OAAO,KAAA;AACzD,EAAA,OAAO,IAAI,KAAA,IAAS,GAAA;AACtB","file":"chunk-N6ECRCHY.mjs","sourcesContent":["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 * First address in X-Forwarded-For is the original client — everything after\n * is intermediate proxies. Falls back to null (e.g. local dev with no proxy).\n */\nexport function getClientIp(headers: Headers | undefined | null): string | null {\n const forwardedFor = headers?.get(\"x-forwarded-for\")\n if (forwardedFor) return forwardedFor.split(\",\")[0].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","// 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// 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"]}
|