create-pet-adopt 0.0.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +120 -0
- package/index.js +920 -0
- package/package.json +43 -1
- package/template/.env.example +136 -0
- package/template/.pet-adopt/template.json +581 -0
- package/template/LICENSE +21 -0
- package/template/README.md +109 -0
- package/template/_gitignore +28 -0
- package/template/_pnpm-lock.yaml +9251 -0
- package/template/assets/sample-pet.png +0 -0
- package/template/components.json +25 -0
- package/template/docker-compose.yml +110 -0
- package/template/drizzle/pg/0000_initial.sql +176 -0
- package/template/drizzle/pg/0001_greedy_the_renegades.sql +1 -0
- package/template/drizzle/pg/0002_fuzzy_the_renegades.sql +1 -0
- package/template/drizzle/pg/0003_thin_multiple_man.sql +1 -0
- package/template/drizzle/pg/0004_boring_norman_osborn.sql +15 -0
- package/template/drizzle/pg/0005_bitter_proemial_gods.sql +3 -0
- package/template/drizzle/pg/0006_friendly_black_knight.sql +2 -0
- package/template/drizzle/pg/0007_wise_ozymandias.sql +11 -0
- package/template/drizzle/pg/0008_messy_human_fly.sql +2 -0
- package/template/drizzle/pg/0009_amused_lady_bullseye.sql +1 -0
- package/template/drizzle/pg/0010_cute_mauler.sql +7 -0
- package/template/drizzle/pg/0011_clear_purple_man.sql +3 -0
- package/template/drizzle/pg/0012_tiresome_gunslinger.sql +2 -0
- package/template/drizzle/pg/0013_awesome_wong.sql +18 -0
- package/template/drizzle/pg/0014_fantastic_sumo.sql +12 -0
- package/template/drizzle/pg/0015_pink_carnage.sql +12 -0
- package/template/drizzle/pg/0016_sloppy_king_bedlam.sql +2 -0
- package/template/drizzle/pg/0017_steep_warhawk.sql +15 -0
- package/template/drizzle/pg/0018_mixed_otto_octavius.sql +4 -0
- package/template/drizzle/pg/0019_talented_rocket_raccoon.sql +1 -0
- package/template/drizzle/pg/0020_worthless_zodiak.sql +19 -0
- package/template/drizzle/pg/0021_adorable_squadron_supreme.sql +1 -0
- package/template/drizzle/pg/0022_soft_pixie.sql +5 -0
- package/template/drizzle/pg/0023_fluffy_quasar.sql +1 -0
- package/template/drizzle/pg/0024_uneven_ken_ellis.sql +2 -0
- package/template/drizzle/pg/0025_rich_white_queen.sql +3 -0
- package/template/drizzle/pg/0026_spooky_komodo.sql +16 -0
- package/template/drizzle/pg/0027_big_thunderbolts.sql +2 -0
- package/template/drizzle/pg/meta/0000_snapshot.json +1265 -0
- package/template/drizzle/pg/meta/0001_snapshot.json +1272 -0
- package/template/drizzle/pg/meta/0002_snapshot.json +1278 -0
- package/template/drizzle/pg/meta/0003_snapshot.json +1284 -0
- package/template/drizzle/pg/meta/0004_snapshot.json +1401 -0
- package/template/drizzle/pg/meta/0005_snapshot.json +1401 -0
- package/template/drizzle/pg/meta/0006_snapshot.json +1414 -0
- package/template/drizzle/pg/meta/0007_snapshot.json +1485 -0
- package/template/drizzle/pg/meta/0008_snapshot.json +1504 -0
- package/template/drizzle/pg/meta/0009_snapshot.json +1510 -0
- package/template/drizzle/pg/meta/0010_snapshot.json +1556 -0
- package/template/drizzle/pg/meta/0011_snapshot.json +1574 -0
- package/template/drizzle/pg/meta/0012_snapshot.json +1586 -0
- package/template/drizzle/pg/meta/0013_snapshot.json +1730 -0
- package/template/drizzle/pg/meta/0014_snapshot.json +1805 -0
- package/template/drizzle/pg/meta/0015_snapshot.json +1883 -0
- package/template/drizzle/pg/meta/0016_snapshot.json +1897 -0
- package/template/drizzle/pg/meta/0017_snapshot.json +2013 -0
- package/template/drizzle/pg/meta/0018_snapshot.json +1988 -0
- package/template/drizzle/pg/meta/0019_snapshot.json +1994 -0
- package/template/drizzle/pg/meta/0020_snapshot.json +2108 -0
- package/template/drizzle/pg/meta/0021_snapshot.json +2114 -0
- package/template/drizzle/pg/meta/0022_snapshot.json +2126 -0
- package/template/drizzle/pg/meta/0023_snapshot.json +2132 -0
- package/template/drizzle/pg/meta/0024_snapshot.json +2151 -0
- package/template/drizzle/pg/meta/0025_snapshot.json +2169 -0
- package/template/drizzle/pg/meta/0026_snapshot.json +2294 -0
- package/template/drizzle/pg/meta/0027_snapshot.json +2330 -0
- package/template/drizzle/pg/meta/_journal.json +202 -0
- package/template/drizzle/sqlite/0000_initial.sql +176 -0
- package/template/drizzle/sqlite/0001_easy_sebastian_shaw.sql +1 -0
- package/template/drizzle/sqlite/0002_past_king_cobra.sql +1 -0
- package/template/drizzle/sqlite/0003_organic_masked_marvel.sql +1 -0
- package/template/drizzle/sqlite/0004_panoramic_inhumans.sql +15 -0
- package/template/drizzle/sqlite/0005_small_sunset_bain.sql +19 -0
- package/template/drizzle/sqlite/0006_narrow_medusa.sql +2 -0
- package/template/drizzle/sqlite/0007_gray_grandmaster.sql +10 -0
- package/template/drizzle/sqlite/0008_chief_toxin.sql +1 -0
- package/template/drizzle/sqlite/0009_vengeful_tag.sql +1 -0
- package/template/drizzle/sqlite/0010_kind_klaw.sql +7 -0
- package/template/drizzle/sqlite/0011_overrated_meltdown.sql +3 -0
- package/template/drizzle/sqlite/0012_robust_next_avengers.sql +2 -0
- package/template/drizzle/sqlite/0013_melodic_kitty_pryde.sql +18 -0
- package/template/drizzle/sqlite/0014_stormy_cyclops.sql +12 -0
- package/template/drizzle/sqlite/0015_parallel_mongu.sql +11 -0
- package/template/drizzle/sqlite/0016_grey_quicksilver.sql +2 -0
- package/template/drizzle/sqlite/0017_daily_psylocke.sql +15 -0
- package/template/drizzle/sqlite/0018_whole_redwing.sql +4 -0
- package/template/drizzle/sqlite/0019_spotty_mandroid.sql +1 -0
- package/template/drizzle/sqlite/0020_wild_wendell_rand.sql +19 -0
- package/template/drizzle/sqlite/0021_calm_lockheed.sql +1 -0
- package/template/drizzle/sqlite/0022_lonely_emma_frost.sql +5 -0
- package/template/drizzle/sqlite/0023_elite_tony_stark.sql +1 -0
- package/template/drizzle/sqlite/0024_little_lily_hollister.sql +1 -0
- package/template/drizzle/sqlite/0025_tough_shotgun.sql +3 -0
- package/template/drizzle/sqlite/0026_faithful_mephistopheles.sql +16 -0
- package/template/drizzle/sqlite/0027_rapid_arclight.sql +2 -0
- package/template/drizzle/sqlite/meta/0000_snapshot.json +1237 -0
- package/template/drizzle/sqlite/meta/0001_snapshot.json +1245 -0
- package/template/drizzle/sqlite/meta/0002_snapshot.json +1252 -0
- package/template/drizzle/sqlite/meta/0003_snapshot.json +1259 -0
- package/template/drizzle/sqlite/meta/0004_snapshot.json +1369 -0
- package/template/drizzle/sqlite/meta/0005_snapshot.json +1369 -0
- package/template/drizzle/sqlite/meta/0006_snapshot.json +1384 -0
- package/template/drizzle/sqlite/meta/0007_snapshot.json +1459 -0
- package/template/drizzle/sqlite/meta/0008_snapshot.json +1479 -0
- package/template/drizzle/sqlite/meta/0009_snapshot.json +1486 -0
- package/template/drizzle/sqlite/meta/0010_snapshot.json +1533 -0
- package/template/drizzle/sqlite/meta/0011_snapshot.json +1554 -0
- package/template/drizzle/sqlite/meta/0012_snapshot.json +1568 -0
- package/template/drizzle/sqlite/meta/0013_snapshot.json +1687 -0
- package/template/drizzle/sqlite/meta/0014_snapshot.json +1769 -0
- package/template/drizzle/sqlite/meta/0015_snapshot.json +1852 -0
- package/template/drizzle/sqlite/meta/0016_snapshot.json +1867 -0
- package/template/drizzle/sqlite/meta/0017_snapshot.json +1973 -0
- package/template/drizzle/sqlite/meta/0018_snapshot.json +1944 -0
- package/template/drizzle/sqlite/meta/0019_snapshot.json +1951 -0
- package/template/drizzle/sqlite/meta/0020_snapshot.json +2077 -0
- package/template/drizzle/sqlite/meta/0021_snapshot.json +2084 -0
- package/template/drizzle/sqlite/meta/0022_snapshot.json +2098 -0
- package/template/drizzle/sqlite/meta/0023_snapshot.json +2105 -0
- package/template/drizzle/sqlite/meta/0024_snapshot.json +2125 -0
- package/template/drizzle/sqlite/meta/0025_snapshot.json +2146 -0
- package/template/drizzle/sqlite/meta/0026_snapshot.json +2265 -0
- package/template/drizzle/sqlite/meta/0027_snapshot.json +2280 -0
- package/template/drizzle/sqlite/meta/_journal.json +202 -0
- package/template/drizzle.pg.config.ts +8 -0
- package/template/drizzle.sqlite.config.ts +8 -0
- package/template/eslint.config.mjs +22 -0
- package/template/next.config.ts +153 -0
- package/template/package.json +102 -0
- package/template/pet-adopt.blocks.ts +9 -0
- package/template/pet-adopt.config.ts +17 -0
- package/template/pnpm-workspace.yaml +19 -0
- package/template/postcss.config.mjs +5 -0
- package/template/scripts/check-routes.ts +405 -0
- package/template/scripts/check-schemas.ts +58 -0
- package/template/scripts/migrate-all.ts +25 -0
- package/template/scripts/migrate-on-build.ts +71 -0
- package/template/scripts/migrate.ts +20 -0
- package/template/scripts/plugin-generate.ts +92 -0
- package/template/scripts/reset-password.ts +45 -0
- package/template/scripts/reset-two-factor.ts +53 -0
- package/template/scripts/seed.ts +79 -0
- package/template/scripts/setup-env.ts +91 -0
- package/template/scripts/storage-check.ts +53 -0
- package/template/src/app/(admin)/admin/account/AccountForms.tsx +194 -0
- package/template/src/app/(admin)/admin/account/page.tsx +59 -0
- package/template/src/app/(admin)/admin/activity/page.tsx +76 -0
- package/template/src/app/(admin)/admin/authentication/archived/page.tsx +24 -0
- package/template/src/app/(admin)/admin/authentication/layout.tsx +20 -0
- package/template/src/app/(admin)/admin/authentication/page.tsx +36 -0
- package/template/src/app/(admin)/admin/authentication/providers/page.tsx +33 -0
- package/template/src/app/(admin)/admin/email/layout.tsx +21 -0
- package/template/src/app/(admin)/admin/email/page.tsx +43 -0
- package/template/src/app/(admin)/admin/email/templates/page.tsx +38 -0
- package/template/src/app/(admin)/admin/error.tsx +36 -0
- package/template/src/app/(admin)/admin/layout.tsx +26 -0
- package/template/src/app/(admin)/admin/loading.tsx +9 -0
- package/template/src/app/(admin)/admin/media/[id]/page.tsx +97 -0
- package/template/src/app/(admin)/admin/media/page.tsx +34 -0
- package/template/src/app/(admin)/admin/media/search-params.ts +16 -0
- package/template/src/app/(admin)/admin/page.tsx +79 -0
- package/template/src/app/(admin)/admin/pages/PageForm.tsx +604 -0
- package/template/src/app/(admin)/admin/pages/[id]/page.tsx +51 -0
- package/template/src/app/(admin)/admin/pages/new/page.tsx +19 -0
- package/template/src/app/(admin)/admin/pages/page.tsx +49 -0
- package/template/src/app/(admin)/admin/pets/PetForm.tsx +437 -0
- package/template/src/app/(admin)/admin/pets/[id]/page.tsx +41 -0
- package/template/src/app/(admin)/admin/pets/new/page.tsx +26 -0
- package/template/src/app/(admin)/admin/pets/page.tsx +70 -0
- package/template/src/app/(admin)/admin/pets/search-params.ts +16 -0
- package/template/src/app/(admin)/admin/plugins/[plugin]/[[...path]]/page.tsx +73 -0
- package/template/src/app/(admin)/admin/plugins/page.tsx +66 -0
- package/template/src/app/(admin)/admin/settings/SettingsForm.tsx +644 -0
- package/template/src/app/(admin)/admin/settings/email/page.tsx +9 -0
- package/template/src/app/(admin)/admin/settings/page.tsx +40 -0
- package/template/src/app/(admin)/admin/settings/templates/page.tsx +9 -0
- package/template/src/app/(admin)/admin/theme/[id]/page.tsx +28 -0
- package/template/src/app/(admin)/admin/theme/page.tsx +30 -0
- package/template/src/app/(admin)/admin/users/page.tsx +33 -0
- package/template/src/app/(admin)/layout.tsx +75 -0
- package/template/src/app/(admin)/providers.tsx +42 -0
- package/template/src/app/(auth)/admin/confirm-email/page.tsx +40 -0
- package/template/src/app/(auth)/admin/invite/page.tsx +38 -0
- package/template/src/app/(auth)/admin/login/DemoSignIn.tsx +69 -0
- package/template/src/app/(auth)/admin/login/page.tsx +83 -0
- package/template/src/app/(auth)/admin/reset-password/page.tsx +73 -0
- package/template/src/app/(auth)/error.tsx +9 -0
- package/template/src/app/(auth)/layout.tsx +71 -0
- package/template/src/app/(editor)/EditorToast.tsx +43 -0
- package/template/src/app/(editor)/edit/[id]/PageEditor.tsx +586 -0
- package/template/src/app/(editor)/edit/[id]/actions.ts +139 -0
- package/template/src/app/(editor)/edit/[id]/page.tsx +76 -0
- package/template/src/app/(editor)/edit/[id]/preview/page.tsx +81 -0
- package/template/src/app/(editor)/edit/email/[id]/EmailEditor.tsx +236 -0
- package/template/src/app/(editor)/edit/email/[id]/page.tsx +64 -0
- package/template/src/app/(editor)/edit/theme-preview/page.tsx +94 -0
- package/template/src/app/(editor)/editor.css +223 -0
- package/template/src/app/(editor)/error.tsx +32 -0
- package/template/src/app/(editor)/layout.tsx +67 -0
- package/template/src/app/(frontend)/[slug]/page.tsx +53 -0
- package/template/src/app/(frontend)/fonts.ts +8 -0
- package/template/src/app/(frontend)/layout.tsx +107 -0
- package/template/src/app/(frontend)/not-found.tsx +16 -0
- package/template/src/app/(frontend)/page.tsx +42 -0
- package/template/src/app/(frontend)/pets/[slug]/page.tsx +92 -0
- package/template/src/app/(frontend)/pets/page.tsx +42 -0
- package/template/src/app/(frontend)/styles.css +537 -0
- package/template/src/app/(setup)/error.tsx +9 -0
- package/template/src/app/(setup)/layout.tsx +41 -0
- package/template/src/app/(setup)/setup/page.tsx +105 -0
- package/template/src/app/(setup)/setup/storage-check.ts +43 -0
- package/template/src/app/api/auth/[...all]/route.ts +144 -0
- package/template/src/app/health/route.ts +9 -0
- package/template/src/app/media/[...path]/route.ts +45 -0
- package/template/src/app/media/email/[name]/route.ts +60 -0
- package/template/src/app/robots.ts +19 -0
- package/template/src/app/sitemap.ts +24 -0
- package/template/src/components/admin/AdminNav.tsx +153 -0
- package/template/src/components/admin/AdminShell.tsx +107 -0
- package/template/src/components/admin/DemoNotice.tsx +31 -0
- package/template/src/components/admin/EmailConfirmBanner.tsx +44 -0
- package/template/src/components/admin/EmptyState.tsx +10 -0
- package/template/src/components/admin/ErrorSummary.tsx +72 -0
- package/template/src/components/admin/MediaDetails.tsx +218 -0
- package/template/src/components/admin/MediaGrid.tsx +307 -0
- package/template/src/components/admin/MediaLibrary.tsx +103 -0
- package/template/src/components/admin/MediaPager.tsx +66 -0
- package/template/src/components/admin/PageHeader.tsx +22 -0
- package/template/src/components/admin/PhoneInput.tsx +128 -0
- package/template/src/components/admin/PluginWidgetBoundary.tsx +38 -0
- package/template/src/components/admin/PluginWidgets.tsx +51 -0
- package/template/src/components/admin/RemountOnNavigate.tsx +37 -0
- package/template/src/components/admin/StatusBadge.tsx +16 -0
- package/template/src/components/admin/UploadPhotosDialog.tsx +387 -0
- package/template/src/components/admin/UserAvatar.tsx +18 -0
- package/template/src/components/admin/UserMenu.tsx +118 -0
- package/template/src/components/admin/ViewSiteLink.tsx +24 -0
- package/template/src/components/admin/account/ConnectedProviders.tsx +91 -0
- package/template/src/components/admin/account/DeleteAccountCard.tsx +136 -0
- package/template/src/components/admin/account/EmailCard.tsx +137 -0
- package/template/src/components/admin/account/ProfilePicture.tsx +159 -0
- package/template/src/components/admin/activity/ActivityFilters.tsx +146 -0
- package/template/src/components/admin/activity/ActivityLog.tsx +159 -0
- package/template/src/components/admin/activity/RecentActivity.tsx +52 -0
- package/template/src/components/admin/demo-mode.tsx +17 -0
- package/template/src/components/admin/nav-items.ts +47 -0
- package/template/src/components/admin/pages/PageDetails.tsx +198 -0
- package/template/src/components/admin/pages/PageVersions.tsx +296 -0
- package/template/src/components/admin/pages/PagesTable.tsx +467 -0
- package/template/src/components/admin/pets/FilterBar.tsx +154 -0
- package/template/src/components/admin/pets/PetCard.tsx +170 -0
- package/template/src/components/admin/pets/PetList.tsx +112 -0
- package/template/src/components/admin/pets/PetListSkeleton.tsx +84 -0
- package/template/src/components/admin/pets/PetPagination.tsx +91 -0
- package/template/src/components/admin/pets/form/AgeFields.tsx +132 -0
- package/template/src/components/admin/pets/form/LocationFields.tsx +231 -0
- package/template/src/components/admin/pets/form/MediaPickerDialog.tsx +359 -0
- package/template/src/components/admin/pets/form/PhotosField.tsx +176 -0
- package/template/src/components/admin/pets/form/RichTextField.tsx +438 -0
- package/template/src/components/admin/pets/form/SeoImageField.tsx +87 -0
- package/template/src/components/admin/pets/form/SeoPreview.tsx +142 -0
- package/template/src/components/admin/pets/form/fields.tsx +434 -0
- package/template/src/components/admin/pets/form/rich-text-extensions.ts +45 -0
- package/template/src/components/admin/pets/timeline/PetTimeline.tsx +297 -0
- package/template/src/components/admin/pets/timeline/TimelineEntryForm.tsx +289 -0
- package/template/src/components/admin/pets/timeline/TimelinePhotosField.tsx +173 -0
- package/template/src/components/admin/plugins/PluginNotReady.tsx +28 -0
- package/template/src/components/admin/plugins/PluginOverview.tsx +121 -0
- package/template/src/components/admin/plugins/SendTestEmail.tsx +70 -0
- package/template/src/components/admin/settings/AuthProviders.tsx +373 -0
- package/template/src/components/admin/settings/AuthenticationNav.tsx +42 -0
- package/template/src/components/admin/settings/EmailNav.tsx +40 -0
- package/template/src/components/admin/settings/EmailSettingsForm.tsx +325 -0
- package/template/src/components/admin/settings/EmailTemplates.tsx +551 -0
- package/template/src/components/admin/settings/RegionFields.tsx +203 -0
- package/template/src/components/admin/site-time.tsx +26 -0
- package/template/src/components/admin/theme/ThemeEditor.tsx +467 -0
- package/template/src/components/admin/theme/ThemeLibrary.tsx +339 -0
- package/template/src/components/admin/theme/ThemeSwatches.tsx +30 -0
- package/template/src/components/admin/theme/theme-utils.ts +32 -0
- package/template/src/components/admin/two-factor/BackupCodeList.tsx +54 -0
- package/template/src/components/admin/two-factor/TwoFactorCard.tsx +237 -0
- package/template/src/components/admin/two-factor/TwoFactorRequired.tsx +52 -0
- package/template/src/components/admin/two-factor/TwoFactorSetup.tsx +180 -0
- package/template/src/components/admin/use-unsaved-changes.tsx +101 -0
- package/template/src/components/admin/users/ArchivedAccounts.tsx +159 -0
- package/template/src/components/admin/users/InviteDialogs.tsx +131 -0
- package/template/src/components/admin/users/TwoFactorRoles.tsx +80 -0
- package/template/src/components/admin/users/UserDialogs.tsx +681 -0
- package/template/src/components/admin/users/UsersTable.tsx +374 -0
- package/template/src/components/admin/view-only.tsx +43 -0
- package/template/src/components/auth/AcceptInviteForm.tsx +123 -0
- package/template/src/components/auth/AuthNav.tsx +80 -0
- package/template/src/components/auth/ConfirmEmailForm.tsx +73 -0
- package/template/src/components/auth/LoginForm.tsx +250 -0
- package/template/src/components/auth/PageError.tsx +37 -0
- package/template/src/components/auth/ProviderSignIn.tsx +53 -0
- package/template/src/components/auth/ResetPasswordForm.tsx +267 -0
- package/template/src/components/demo/DemoBanner.tsx +38 -0
- package/template/src/components/demo/SiteDemoBanner.tsx +22 -0
- package/template/src/components/demo/wording.ts +21 -0
- package/template/src/components/setup/SetupAccountForm.tsx +93 -0
- package/template/src/components/setup/SetupDone.tsx +95 -0
- package/template/src/components/setup/SetupNav.tsx +49 -0
- package/template/src/components/setup/SetupSampleContent.tsx +67 -0
- package/template/src/components/setup/SetupSiteForm.tsx +104 -0
- package/template/src/components/setup/SetupThemePicker.tsx +73 -0
- package/template/src/components/setup/SkipSetup.tsx +35 -0
- package/template/src/components/site/BuilderContent.tsx +46 -0
- package/template/src/components/site/CopyButton.tsx +28 -0
- package/template/src/components/site/ImageCarousel.tsx +52 -0
- package/template/src/components/site/PetCard.tsx +32 -0
- package/template/src/components/site/PetCatalog.tsx +106 -0
- package/template/src/components/site/PetGallery.tsx +75 -0
- package/template/src/components/site/PetTimeline.tsx +82 -0
- package/template/src/components/site/RemountOnNavigate.tsx +13 -0
- package/template/src/components/site/RichText.tsx +56 -0
- package/template/src/components/site/SmartLink.tsx +37 -0
- package/template/src/components/site/SocialIcons.tsx +26 -0
- package/template/src/components/site/ThemePreviewBridge.tsx +29 -0
- package/template/src/components/site/ThemeStyle.tsx +22 -0
- package/template/src/components/site/ThemeToggle.tsx +36 -0
- package/template/src/components/site/WhatsAppButton.tsx +27 -0
- package/template/src/components/site/timeline-format.ts +20 -0
- package/template/src/db/client.ts +702 -0
- package/template/src/db/compare-tables.ts +41 -0
- package/template/src/db/migrate.ts +28 -0
- package/template/src/db/plugin-migrations.ts +167 -0
- package/template/src/db/schema/pg.ts +484 -0
- package/template/src/db/schema/sqlite.ts +492 -0
- package/template/src/instrumentation.ts +110 -0
- package/template/src/lib/activity.ts +29 -0
- package/template/src/lib/admin/call-action.ts +19 -0
- package/template/src/lib/admin/initials.ts +9 -0
- package/template/src/lib/admin/media-cache.ts +16 -0
- package/template/src/lib/admin/media-page.ts +3 -0
- package/template/src/lib/admin/pet-form.ts +242 -0
- package/template/src/lib/admin/pets-cache.ts +22 -0
- package/template/src/lib/admin/unwrap-client.ts +11 -0
- package/template/src/lib/admin/unwrap.ts +38 -0
- package/template/src/lib/admin/use-media-list.ts +41 -0
- package/template/src/lib/admin/use-pet-list.ts +58 -0
- package/template/src/lib/age.ts +117 -0
- package/template/src/lib/auth-provider-errors.ts +38 -0
- package/template/src/lib/cache.ts +69 -0
- package/template/src/lib/color-mode.ts +48 -0
- package/template/src/lib/demo.ts +78 -0
- package/template/src/lib/email-address.ts +9 -0
- package/template/src/lib/email-template.ts +691 -0
- package/template/src/lib/links.ts +78 -0
- package/template/src/lib/mail-error.ts +38 -0
- package/template/src/lib/media-name.ts +31 -0
- package/template/src/lib/options.ts +134 -0
- package/template/src/lib/pagination.ts +28 -0
- package/template/src/lib/pet-placeholders.ts +34 -0
- package/template/src/lib/pet-seo.ts +40 -0
- package/template/src/lib/pet-timeline.ts +62 -0
- package/template/src/lib/phone.ts +129 -0
- package/template/src/lib/places.ts +84 -0
- package/template/src/lib/queries.ts +549 -0
- package/template/src/lib/revalidate.ts +32 -0
- package/template/src/lib/rich-text.ts +215 -0
- package/template/src/lib/seo.ts +121 -0
- package/template/src/lib/slugify.ts +11 -0
- package/template/src/lib/theme.ts +546 -0
- package/template/src/lib/utils.ts +2 -0
- package/template/src/lib/whatsapp.ts +29 -0
- package/template/src/lib/zod-schema/auth.ts +56 -0
- package/template/src/lib/zod-schema/page.ts +57 -0
- package/template/src/lib/zod-schema/pet-timeline.ts +118 -0
- package/template/src/lib/zod-schema/pet.ts +172 -0
- package/template/src/lib/zod-schema/settings.ts +162 -0
- package/template/src/plugins/host.ts +117 -0
- package/template/src/plugins/icon.ts +89 -0
- package/template/src/plugins/registry.ts +369 -0
- package/template/src/plugins/storage-rules.ts +87 -0
- package/template/src/plugins/storage.ts +184 -0
- package/template/src/puck/actions.ts +46 -0
- package/template/src/puck/config.tsx +1693 -0
- package/template/src/puck/data.ts +196 -0
- package/template/src/puck/demo-mode.tsx +20 -0
- package/template/src/puck/email-config.tsx +267 -0
- package/template/src/puck/icons.tsx +76 -0
- package/template/src/puck/media-picker.tsx +273 -0
- package/template/src/puck/padding.tsx +71 -0
- package/template/src/puck/pet-page-config.tsx +511 -0
- package/template/src/puck/pet-picker.tsx +40 -0
- package/template/src/puck/plugin-block-data.ts +91 -0
- package/template/src/puck/plugin-blocks.tsx +235 -0
- package/template/src/puck/plugin-choice-field.tsx +87 -0
- package/template/src/puck/sanitize.ts +107 -0
- package/template/src/puck/server.ts +36 -0
- package/template/src/puck/types.ts +41 -0
- package/template/src/server/actions/activity.ts +48 -0
- package/template/src/server/actions/auth-providers.ts +171 -0
- package/template/src/server/actions/auth.ts +217 -0
- package/template/src/server/actions/demo.ts +30 -0
- package/template/src/server/actions/email-change.ts +80 -0
- package/template/src/server/actions/email-templates.ts +144 -0
- package/template/src/server/actions/email.ts +70 -0
- package/template/src/server/actions/media.ts +127 -0
- package/template/src/server/actions/pages.ts +159 -0
- package/template/src/server/actions/password-reset.ts +80 -0
- package/template/src/server/actions/pet-timeline.ts +75 -0
- package/template/src/server/actions/pets.ts +74 -0
- package/template/src/server/actions/places.ts +36 -0
- package/template/src/server/actions/settings.ts +29 -0
- package/template/src/server/actions/setup.ts +72 -0
- package/template/src/server/actions/themes.ts +80 -0
- package/template/src/server/actions/two-factor.ts +306 -0
- package/template/src/server/actions/users.ts +200 -0
- package/template/src/server/activity.ts +409 -0
- package/template/src/server/auth-errors.ts +17 -0
- package/template/src/server/auth-providers.ts +359 -0
- package/template/src/server/auth.ts +266 -0
- package/template/src/server/avatars.ts +263 -0
- package/template/src/server/demo-site.ts +169 -0
- package/template/src/server/email-change.ts +278 -0
- package/template/src/server/email-templates.ts +350 -0
- package/template/src/server/email.ts +442 -0
- package/template/src/server/invites.ts +143 -0
- package/template/src/server/media-url.ts +20 -0
- package/template/src/server/media.ts +236 -0
- package/template/src/server/pages.ts +812 -0
- package/template/src/server/password-reset.ts +158 -0
- package/template/src/server/pending-links.ts +46 -0
- package/template/src/server/pet-timeline.ts +181 -0
- package/template/src/server/pets.ts +555 -0
- package/template/src/server/places.ts +113 -0
- package/template/src/server/privacy.ts +21 -0
- package/template/src/server/provider-endpoints.ts +94 -0
- package/template/src/server/provider-guard.ts +157 -0
- package/template/src/server/result.ts +280 -0
- package/template/src/server/sample-content.ts +368 -0
- package/template/src/server/search-text.ts +43 -0
- package/template/src/server/secret-box.ts +38 -0
- package/template/src/server/session.ts +154 -0
- package/template/src/server/settings.ts +361 -0
- package/template/src/server/setup.ts +110 -0
- package/template/src/server/sitemap.ts +88 -0
- package/template/src/server/storage.ts +267 -0
- package/template/src/server/strip-metadata.ts +357 -0
- package/template/src/server/themes.ts +195 -0
- package/template/src/server/throttle.ts +258 -0
- package/template/src/server/two-factor-codes.ts +32 -0
- package/template/src/server/two-factor.ts +158 -0
- package/template/src/server/types.ts +198 -0
- package/template/src/server/uploads.ts +137 -0
- package/template/src/server/users.ts +500 -0
- package/template/tsconfig.json +44 -0
- package/template/ui/components.json +25 -0
- package/template/ui/package.json +12 -0
- package/template/ui/src/components/alert-dialog.tsx +187 -0
- package/template/ui/src/components/avatar.tsx +108 -0
- package/template/ui/src/components/badge.tsx +51 -0
- package/template/ui/src/components/button.tsx +57 -0
- package/template/ui/src/components/card.tsx +102 -0
- package/template/ui/src/components/carousel.tsx +245 -0
- package/template/ui/src/components/checkbox.tsx +27 -0
- package/template/ui/src/components/combobox.tsx +297 -0
- package/template/ui/src/components/dialog.tsx +159 -0
- package/template/ui/src/components/dropdown-menu.tsx +265 -0
- package/template/ui/src/components/field.tsx +238 -0
- package/template/ui/src/components/input-group.tsx +158 -0
- package/template/ui/src/components/input.tsx +19 -0
- package/template/ui/src/components/label.tsx +19 -0
- package/template/ui/src/components/pagination.tsx +127 -0
- package/template/ui/src/components/popover.tsx +89 -0
- package/template/ui/src/components/radio-group.tsx +37 -0
- package/template/ui/src/components/select.tsx +200 -0
- package/template/ui/src/components/separator.tsx +24 -0
- package/template/ui/src/components/sheet.tsx +138 -0
- package/template/ui/src/components/sidebar.tsx +723 -0
- package/template/ui/src/components/skeleton.tsx +13 -0
- package/template/ui/src/components/switch.tsx +31 -0
- package/template/ui/src/components/table.tsx +115 -0
- package/template/ui/src/components/tabs.tsx +81 -0
- package/template/ui/src/components/textarea.tsx +17 -0
- package/template/ui/src/components/toggle.tsx +44 -0
- package/template/ui/src/components/tooltip.tsx +65 -0
- package/template/ui/src/hooks/use-mobile.ts +21 -0
- package/template/ui/src/lib/utils.ts +2 -0
- package/template/ui/src/styles/globals.css +145 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Owners' own themes. Each is a built-in preset (`base`) with customisations laid over it, in the
|
|
2
|
+
// same shape as the settings' customTheme, and validated by the same rules (settings.ts). One of
|
|
3
|
+
// them, or a built-in preset, is in use: site_settings.active_theme_id, laid over the theme fields
|
|
4
|
+
// by getSettings. Text must stay readable (contrastProblem), as for the settings.
|
|
5
|
+
import { foldText } from '@pet-adopt/plugin-sdk'
|
|
6
|
+
import { asc, eq, sql } from 'drizzle-orm'
|
|
7
|
+
|
|
8
|
+
import { getDatabase } from '@/db/client'
|
|
9
|
+
import { TAGS } from '@/lib/cache'
|
|
10
|
+
import { safeRevalidate } from '@/lib/revalidate'
|
|
11
|
+
import { PRESET_OPTIONS, contrastProblem, type ThemeSettings } from '@/lib/theme'
|
|
12
|
+
|
|
13
|
+
import { asRecord, Fields, UserError, ValidationError, type FieldErrors } from './result'
|
|
14
|
+
import { MODES, parseCustomTheme } from './settings'
|
|
15
|
+
import type { ThemeRecord } from './types'
|
|
16
|
+
|
|
17
|
+
type CustomTheme = NonNullable<ThemeSettings['customTheme']>
|
|
18
|
+
|
|
19
|
+
const SETTINGS_ID = 1
|
|
20
|
+
const MAX_THEMES = 50
|
|
21
|
+
|
|
22
|
+
function toTheme(row: { id: number; name: string; base: string; settings: unknown; createdAt: Date; updatedAt: Date }): ThemeRecord {
|
|
23
|
+
return {
|
|
24
|
+
id: row.id,
|
|
25
|
+
name: row.name,
|
|
26
|
+
base: row.base,
|
|
27
|
+
settings: (row.settings ?? {}) as CustomTheme,
|
|
28
|
+
createdAt: row.createdAt,
|
|
29
|
+
updatedAt: row.updatedAt,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Keys that were cleared (null) are left out, so a stored theme only holds what was changed. */
|
|
34
|
+
function compact(value: Record<string, unknown>): CustomTheme {
|
|
35
|
+
const out: Record<string, unknown> = {}
|
|
36
|
+
for (const [key, v] of Object.entries(value)) {
|
|
37
|
+
if (v === null || v === undefined) continue
|
|
38
|
+
if (typeof v === 'object' && !Array.isArray(v)) {
|
|
39
|
+
const inner = Object.fromEntries(Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== null && x !== undefined))
|
|
40
|
+
if (Object.keys(inner).length) out[key] = inner
|
|
41
|
+
} else {
|
|
42
|
+
out[key] = v
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out as CustomTheme
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Readable text on the background and on cards, in both modes, for this base and customisations. */
|
|
49
|
+
function checkContrast(base: string, customTheme: CustomTheme, errors: FieldErrors) {
|
|
50
|
+
const effective: ThemeSettings = { theme: base, customize: true, customTheme }
|
|
51
|
+
for (const mode of MODES) {
|
|
52
|
+
const problem = contrastProblem(effective, mode)
|
|
53
|
+
if (problem) errors[`customTheme.${mode}.text`] ??= problem
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function assertNameFree(name: string, exceptId?: number) {
|
|
58
|
+
const { db, t } = await getDatabase()
|
|
59
|
+
// At most MAX_THEMES rows: compared here, folded, so case and accents match on every database.
|
|
60
|
+
const rows = await db.select({ id: t.themes.id, name: t.themes.name }).from(t.themes)
|
|
61
|
+
if (rows.some((row) => row.id !== exceptId && foldText(row.name) === foldText(name))) throw new ValidationError({ name: 'Another theme already has this name.' })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function listThemes(): Promise<{ themes: ThemeRecord[]; activeThemeId: number | null; preset: string }> {
|
|
65
|
+
const { db, t } = await getDatabase()
|
|
66
|
+
const rows = await db.select().from(t.themes).orderBy(asc(t.themes.name))
|
|
67
|
+
const [settings] = await db
|
|
68
|
+
.select({ activeThemeId: t.siteSettings.activeThemeId, theme: t.siteSettings.theme })
|
|
69
|
+
.from(t.siteSettings)
|
|
70
|
+
.where(eq(t.siteSettings.id, SETTINGS_ID))
|
|
71
|
+
.limit(1)
|
|
72
|
+
return { themes: rows.map(toTheme), activeThemeId: settings?.activeThemeId ?? null, preset: settings?.theme ?? 'sunrise' }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function getTheme(id: number): Promise<ThemeRecord | null> {
|
|
76
|
+
const { db, t } = await getDatabase()
|
|
77
|
+
const [row] = await db.select().from(t.themes).where(eq(t.themes.id, id)).limit(1)
|
|
78
|
+
return row ? toTheme(row) : null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* `{ name, preset }` starts from a built-in preset with no changes; `{ name, fromThemeId }`
|
|
83
|
+
* duplicates one of the owner's themes.
|
|
84
|
+
*/
|
|
85
|
+
export async function createTheme(raw: unknown): Promise<{ id: number }> {
|
|
86
|
+
const input = asRecord(raw)
|
|
87
|
+
const f = new Fields(input, true)
|
|
88
|
+
const name = f.requiredText('name', 60)
|
|
89
|
+
const preset = input.fromThemeId === undefined ? f.oneOf('preset', PRESET_OPTIONS, { required: true }) : undefined
|
|
90
|
+
const fromThemeId = input.fromThemeId !== undefined ? f.id('fromThemeId') : undefined
|
|
91
|
+
f.done()
|
|
92
|
+
|
|
93
|
+
const { db, t } = await getDatabase()
|
|
94
|
+
const [{ n }] = await db.select({ n: sql<number>`count(*)` }).from(t.themes)
|
|
95
|
+
if (Number(n) >= MAX_THEMES) throw new UserError(`You can keep up to ${MAX_THEMES} themes. Delete one first.`)
|
|
96
|
+
await assertNameFree(name as string)
|
|
97
|
+
|
|
98
|
+
let base = preset as string | undefined
|
|
99
|
+
let settings: CustomTheme = {}
|
|
100
|
+
if (fromThemeId) {
|
|
101
|
+
const source = await getTheme(fromThemeId)
|
|
102
|
+
if (!source) throw new UserError('That theme no longer exists.')
|
|
103
|
+
base = source.base
|
|
104
|
+
settings = source.settings
|
|
105
|
+
}
|
|
106
|
+
const now = new Date()
|
|
107
|
+
const [row] = await db
|
|
108
|
+
.insert(t.themes)
|
|
109
|
+
.values({ name: name as string, base: base ?? 'sunrise', settings: settings as never, createdAt: now, updatedAt: now })
|
|
110
|
+
.returning({ id: t.themes.id })
|
|
111
|
+
return { id: row.id }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* `{ name?, base?, customTheme? }`. `customTheme` replaces the stored customisations as a whole
|
|
116
|
+
* (the editor sends everything); a key set to null falls back to the base preset.
|
|
117
|
+
*/
|
|
118
|
+
export async function updateTheme(id: number, raw: unknown): Promise<ThemeRecord> {
|
|
119
|
+
const input = asRecord(raw)
|
|
120
|
+
const existing = await getTheme(id)
|
|
121
|
+
if (!existing) throw new UserError('That theme no longer exists.')
|
|
122
|
+
|
|
123
|
+
const f = new Fields(input)
|
|
124
|
+
const name = f.requiredText('name', 60)
|
|
125
|
+
const base = f.oneOf('base', PRESET_OPTIONS) ?? undefined
|
|
126
|
+
const errors: FieldErrors = { ...f.errors }
|
|
127
|
+
const customTheme =
|
|
128
|
+
input.customTheme === undefined ? existing.settings : compact(parseCustomTheme(input.customTheme ?? {}, errors))
|
|
129
|
+
checkContrast(base ?? existing.base, customTheme, errors)
|
|
130
|
+
if (Object.keys(errors).length) throw new ValidationError(errors)
|
|
131
|
+
if (name) await assertNameFree(name, id)
|
|
132
|
+
|
|
133
|
+
const { db, t } = await getDatabase()
|
|
134
|
+
const [row] = await db
|
|
135
|
+
.update(t.themes)
|
|
136
|
+
.set({
|
|
137
|
+
...(name ? { name } : {}),
|
|
138
|
+
...(base ? { base } : {}),
|
|
139
|
+
settings: customTheme as never,
|
|
140
|
+
updatedAt: new Date(),
|
|
141
|
+
})
|
|
142
|
+
.where(eq(t.themes.id, id))
|
|
143
|
+
.returning()
|
|
144
|
+
if (!row) throw new UserError('That theme no longer exists.')
|
|
145
|
+
await revalidateIfActive(id)
|
|
146
|
+
return toTheme(row)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The theme in use cannot be deleted: switch to another one first. */
|
|
150
|
+
export async function deleteTheme(id: number): Promise<void> {
|
|
151
|
+
const { db, t } = await getDatabase()
|
|
152
|
+
const [settings] = await db
|
|
153
|
+
.select({ activeThemeId: t.siteSettings.activeThemeId })
|
|
154
|
+
.from(t.siteSettings)
|
|
155
|
+
.where(eq(t.siteSettings.id, SETTINGS_ID))
|
|
156
|
+
.limit(1)
|
|
157
|
+
if (settings?.activeThemeId === id) throw new UserError('This theme is in use. Switch to another theme before deleting it.')
|
|
158
|
+
const [row] = await db.delete(t.themes).where(eq(t.themes.id, id)).returning({ id: t.themes.id })
|
|
159
|
+
if (!row) throw new UserError('That theme no longer exists.')
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** `{ themeId }` uses one of the owner's themes; `{ preset }` goes back to a built-in preset as it is. */
|
|
163
|
+
export async function activateTheme(raw: unknown): Promise<void> {
|
|
164
|
+
const input = asRecord(raw)
|
|
165
|
+
const f = new Fields(input)
|
|
166
|
+
const themeId = input.themeId !== undefined ? f.id('themeId') : undefined
|
|
167
|
+
const preset = input.preset !== undefined ? f.oneOf('preset', PRESET_OPTIONS) : undefined
|
|
168
|
+
f.done()
|
|
169
|
+
if (!themeId && !preset) throw new ValidationError({ themeId: 'Choose a theme.' })
|
|
170
|
+
|
|
171
|
+
const { db, t } = await getDatabase()
|
|
172
|
+
await db.insert(t.siteSettings).values({ id: SETTINGS_ID }).onConflictDoNothing()
|
|
173
|
+
if (themeId) {
|
|
174
|
+
if (!(await getTheme(themeId))) throw new UserError('That theme no longer exists.')
|
|
175
|
+
await db.update(t.siteSettings).set({ activeThemeId: themeId, updatedAt: new Date() }).where(eq(t.siteSettings.id, SETTINGS_ID))
|
|
176
|
+
} else {
|
|
177
|
+
// A built-in preset exactly as designed: no saved theme, no old customisations or brand colour.
|
|
178
|
+
await db
|
|
179
|
+
.update(t.siteSettings)
|
|
180
|
+
.set({ activeThemeId: null, theme: preset as string, customize: false, primaryColor: null, updatedAt: new Date() })
|
|
181
|
+
.where(eq(t.siteSettings.id, SETTINGS_ID))
|
|
182
|
+
}
|
|
183
|
+
// getSettings lays the active theme over the settings, so its cached copy changes too.
|
|
184
|
+
safeRevalidate([['/', 'layout']], [TAGS.settings])
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function revalidateIfActive(id: number) {
|
|
188
|
+
const { db, t } = await getDatabase()
|
|
189
|
+
const [settings] = await db
|
|
190
|
+
.select({ activeThemeId: t.siteSettings.activeThemeId })
|
|
191
|
+
.from(t.siteSettings)
|
|
192
|
+
.where(eq(t.siteSettings.id, SETTINGS_ID))
|
|
193
|
+
.limit(1)
|
|
194
|
+
if (settings?.activeThemeId === id) safeRevalidate([['/', 'layout']], [TAGS.settings])
|
|
195
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// Sign-in and password-change throttling.
|
|
2
|
+
//
|
|
3
|
+
// Better Auth rate-limits requests that arrive through its HTTP handler by address, but it knows
|
|
4
|
+
// nothing about accounts, and server actions skip that layer entirely. So every sign-in path (the
|
|
5
|
+
// server action and the HTTP route) goes through `guardSignIn`.
|
|
6
|
+
//
|
|
7
|
+
// How a sign-in attempt is limited (all counted BEFORE the password is checked, in one atomic
|
|
8
|
+
// upsert each, so a burst of parallel guesses cannot slip past a check-then-record gap):
|
|
9
|
+
// 1. per client address 30 per 10 minutes (stops one machine trying many accounts)
|
|
10
|
+
// 2. per email + client address 5 per 10 minutes (the everyday lockout for fumbled passwords)
|
|
11
|
+
// 3. per email, from anywhere 100 per hour (caps guessing spread over many addresses)
|
|
12
|
+
// The pair key is what makes a lockout hard to abuse: someone typing an owner's email from their own
|
|
13
|
+
// machine locks only themselves out, not the owner. The per-email ceiling is high enough that this
|
|
14
|
+
// stays impractical without making a distributed attack free; `pnpm admin:reset-password` exists
|
|
15
|
+
// for the rare case where an owner is locked out anyway.
|
|
16
|
+
//
|
|
17
|
+
// A lockout does not extend while it is active: it ends `windowMs` after the attempt that reached
|
|
18
|
+
// the limit. Emails are hashed before they become keys, so the table never holds an attacker-sized
|
|
19
|
+
// string and no address list is stored in clear. A success clears that email's counters.
|
|
20
|
+
// Counts live in Better Auth's own `rate_limits` table, so they are shared across instances.
|
|
21
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
22
|
+
import { isIP } from 'node:net'
|
|
23
|
+
|
|
24
|
+
import { and, lt, like, or, sql } from 'drizzle-orm'
|
|
25
|
+
import { eq } from 'drizzle-orm'
|
|
26
|
+
|
|
27
|
+
import { getDatabase } from '@/db/client'
|
|
28
|
+
|
|
29
|
+
import { isUserError, logError, UserError } from './result'
|
|
30
|
+
|
|
31
|
+
export type Throttle = { max: number; windowMs: number }
|
|
32
|
+
|
|
33
|
+
export const PAIR_RULE: Throttle = { max: 5, windowMs: 10 * 60 * 1000 }
|
|
34
|
+
export const EMAIL_RULE: Throttle = { max: 100, windowMs: 60 * 60 * 1000 }
|
|
35
|
+
export const CLIENT_RULE: Throttle = { max: 30, windowMs: 10 * 60 * 1000 }
|
|
36
|
+
/** Guessing the current password through "change password" with a stolen session. */
|
|
37
|
+
export const PASSWORD_CHANGE_RULE: Throttle = { max: 5, windowMs: 10 * 60 * 1000 }
|
|
38
|
+
/** "Email me a reset link": per client, and per email overall so nobody can flood an inbox. */
|
|
39
|
+
export const RESET_CLIENT_RULE: Throttle = { max: 10, windowMs: 15 * 60 * 1000 }
|
|
40
|
+
export const RESET_EMAIL_RULE: Throttle = { max: 3, windowMs: 60 * 60 * 1000 }
|
|
41
|
+
/** Using a reset or invite link (signed out): per client, because each try may hash a password. */
|
|
42
|
+
export const LINK_USE_RULE: Throttle = { max: 10, windowMs: 15 * 60 * 1000 }
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The header your reverse proxy sets to the real client address (default `x-forwarded-for`, or for
|
|
46
|
+
* example `cf-connecting-ip` behind Cloudflare). Only run the site behind a proxy you control: a
|
|
47
|
+
* client can send any header it likes when nothing in front overwrites it.
|
|
48
|
+
*/
|
|
49
|
+
export const CLIENT_IP_HEADER = (process.env.CLIENT_IP_HEADER || 'x-forwarded-for').trim().toLowerCase()
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* How many proxies between the internet and this app each append to the header. With one proxy
|
|
53
|
+
* (the usual case) the client address is the last entry; with a CDN in front of a proxy it is the
|
|
54
|
+
* second to last, and so on. Entries to the left of that are whatever the client sent.
|
|
55
|
+
*/
|
|
56
|
+
export const TRUSTED_PROXY_HOPS = Math.max(Math.floor(Number(process.env.TRUSTED_PROXY_HOPS)) || 1, 1)
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Whoever holds an IPv6 network usually holds a whole /64 (about 18 quintillion addresses) and can
|
|
60
|
+
* hop between them freely, so one address is the wrong unit to limit. IPv6 clients are counted by
|
|
61
|
+
* their /64 prefix instead. IPv4 addresses, and IPv4 written as IPv6 (`::ffff:1.2.3.4`), are
|
|
62
|
+
* counted individually.
|
|
63
|
+
*/
|
|
64
|
+
export function ipv6Prefix64(address: string): string {
|
|
65
|
+
const withoutZone = address.split('%')[0]
|
|
66
|
+
const mapped = withoutZone.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i)
|
|
67
|
+
if (mapped) return mapped[1]
|
|
68
|
+
const [head, tail] = withoutZone.split('::')
|
|
69
|
+
const front = head ? head.split(':') : []
|
|
70
|
+
const back = tail ? tail.split(':') : []
|
|
71
|
+
// "::" stands for as many zero groups as it takes to make eight.
|
|
72
|
+
const groups = withoutZone.includes('::') ? [...front, ...Array(Math.max(8 - front.length - back.length, 0)).fill('0'), ...back] : front
|
|
73
|
+
return `${groups
|
|
74
|
+
.slice(0, 4)
|
|
75
|
+
.map((group) => group.toLowerCase().replace(/^0+(?=.)/, ''))
|
|
76
|
+
.join(':')}::/64`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The client address, or null when it cannot be determined (no header, or not an IP address). */
|
|
80
|
+
export function clientAddress(headers: Headers): string | null {
|
|
81
|
+
const value = headers.get(CLIENT_IP_HEADER)
|
|
82
|
+
if (!value) return null
|
|
83
|
+
const entries = value
|
|
84
|
+
.split(',')
|
|
85
|
+
.map((entry) => entry.trim())
|
|
86
|
+
.filter(Boolean)
|
|
87
|
+
const candidate = entries[Math.max(entries.length - TRUSTED_PROXY_HOPS, 0)]
|
|
88
|
+
const version = candidate ? isIP(candidate) : 0
|
|
89
|
+
if (version === 4) return candidate
|
|
90
|
+
if (version === 6) return ipv6Prefix64(candidate)
|
|
91
|
+
return null
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let warnedAboutMissingAddress = false
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Counts one attempt on `key` and throws a UserError once the limit is passed. The window restarts
|
|
98
|
+
* once it has fully elapsed. While a key is over the limit its timestamp is left alone, so
|
|
99
|
+
* hammering a locked key cannot keep it locked beyond `windowMs` after the limit was reached.
|
|
100
|
+
*/
|
|
101
|
+
export async function consumeAttempt(key: string, rule: Throttle): Promise<void> {
|
|
102
|
+
const { db, t } = await getDatabase()
|
|
103
|
+
const now = Date.now()
|
|
104
|
+
const cutoff = now - rule.windowMs
|
|
105
|
+
const [row] = await db
|
|
106
|
+
.insert(t.rateLimits)
|
|
107
|
+
.values({ id: randomUUID(), key, count: 1, lastRequest: now })
|
|
108
|
+
.onConflictDoUpdate({
|
|
109
|
+
target: t.rateLimits.key,
|
|
110
|
+
set: {
|
|
111
|
+
// One statement, so concurrent attempts cannot interleave. Every expression reads the OLD
|
|
112
|
+
// row: an expired window restarts at 1; otherwise the count goes up by 1, and the
|
|
113
|
+
// timestamp only moves while the key is still under the limit.
|
|
114
|
+
count: sql`CASE WHEN ${t.rateLimits.lastRequest} < ${cutoff} THEN 1 ELSE ${t.rateLimits.count} + 1 END`,
|
|
115
|
+
lastRequest: sql`CASE WHEN ${t.rateLimits.lastRequest} < ${cutoff} THEN ${now} WHEN ${t.rateLimits.count} >= ${rule.max} THEN ${t.rateLimits.lastRequest} ELSE ${now} END`,
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
.returning({ count: t.rateLimits.count, lastRequest: t.rateLimits.lastRequest })
|
|
119
|
+
|
|
120
|
+
if (row.count > rule.max) {
|
|
121
|
+
const minutes = Math.max(Math.ceil((row.lastRequest + rule.windowMs - now) / 60_000), 1)
|
|
122
|
+
throw new UserError(`Too many attempts. Try again in about ${minutes} minute${minutes === 1 ? '' : 's'}.`)
|
|
123
|
+
}
|
|
124
|
+
void purgeExpired().catch((error) => logError(error, 'could not purge expired attempt counters'))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Now and then, remove counters nobody will read again, so the table cannot grow without bound. */
|
|
128
|
+
async function purgeExpired(): Promise<void> {
|
|
129
|
+
if (Math.random() > 0.02) return
|
|
130
|
+
const { db, t } = await getDatabase()
|
|
131
|
+
// Our keys only (every prefix consumeAttempt is called with). The site's own windows are at most
|
|
132
|
+
// an hour; a plugin's rule longer than two hours is cut short here (the SDK says so).
|
|
133
|
+
// Better Auth's own rows ("<ip>|<path>") are not ours to delete.
|
|
134
|
+
await db
|
|
135
|
+
.delete(t.rateLimits)
|
|
136
|
+
.where(
|
|
137
|
+
and(
|
|
138
|
+
or(
|
|
139
|
+
like(t.rateLimits.key, 'login:%'),
|
|
140
|
+
like(t.rateLimits.key, 'chpw:%'),
|
|
141
|
+
like(t.rateLimits.key, 'pwreset:%'),
|
|
142
|
+
like(t.rateLimits.key, 'linkuse:%'),
|
|
143
|
+
like(t.rateLimits.key, 'emailtest:%'),
|
|
144
|
+
like(t.rateLimits.key, 'emailchange:%'),
|
|
145
|
+
like(t.rateLimits.key, 'oauth:%'),
|
|
146
|
+
like(t.rateLimits.key, 'plugin:%'),
|
|
147
|
+
),
|
|
148
|
+
lt(t.rateLimits.lastRequest, Date.now() - 2 * 60 * 60 * 1000),
|
|
149
|
+
),
|
|
150
|
+
)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function clearAttempts(keys: string | string[]): Promise<void> {
|
|
154
|
+
const { db, t } = await getDatabase()
|
|
155
|
+
for (const key of Array.isArray(keys) ? keys : [keys]) {
|
|
156
|
+
await db.delete(t.rateLimits).where(eq(t.rateLimits.key, key))
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Lifts every lockout on an email, for every client. Used by `pnpm admin:reset-password`. */
|
|
161
|
+
export async function clearLockoutsFor(email: string): Promise<void> {
|
|
162
|
+
const { db, t } = await getDatabase()
|
|
163
|
+
const digest = emailDigest(email)
|
|
164
|
+
await db
|
|
165
|
+
.delete(t.rateLimits)
|
|
166
|
+
.where(or(eq(t.rateLimits.key, `login:email:${digest}`), like(t.rateLimits.key, `login:pair:${digest}|%`)))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex')
|
|
170
|
+
|
|
171
|
+
/** Lower-cased and bounded, so any input becomes one short fixed-size key. */
|
|
172
|
+
/** Forgets every attempt counter about an account (its deletion): per user and per email. */
|
|
173
|
+
export async function forgetAttemptsOf(userId: string, email: string): Promise<void> {
|
|
174
|
+
const { db, t } = await getDatabase()
|
|
175
|
+
const digest = emailDigest(email)
|
|
176
|
+
await db
|
|
177
|
+
.delete(t.rateLimits)
|
|
178
|
+
.where(
|
|
179
|
+
or(
|
|
180
|
+
like(t.rateLimits.key, `%${userId}%`),
|
|
181
|
+
eq(t.rateLimits.key, `login:email:${digest}`),
|
|
182
|
+
like(t.rateLimits.key, `login:pair:${digest}|%`),
|
|
183
|
+
eq(t.rateLimits.key, `pwreset:email:${digest}`),
|
|
184
|
+
),
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function emailDigest(email: unknown): string {
|
|
189
|
+
const normalized = typeof email === 'string' ? email.trim().toLowerCase() : ''
|
|
190
|
+
return sha256(normalized && normalized.length <= 254 ? normalized : 'invalid')
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Call before checking a password. Throws a UserError when the client, or the email from this
|
|
195
|
+
* client, or the email overall, is locked out. Returns the keys to pass to `clearAttempts` after a
|
|
196
|
+
* successful sign-in.
|
|
197
|
+
*/
|
|
198
|
+
export async function guardSignIn(email: unknown, headers: Headers): Promise<{ keys: string[] }> {
|
|
199
|
+
const digest = emailDigest(email)
|
|
200
|
+
const address = clientAddress(headers)
|
|
201
|
+
if (address) {
|
|
202
|
+
// First, so junk requests are stopped by the client limit before they can add more rows.
|
|
203
|
+
await consumeAttempt(`login:ip:${address}`, CLIENT_RULE)
|
|
204
|
+
} else if (process.env.NODE_ENV === 'production' && !warnedAboutMissingAddress) {
|
|
205
|
+
warnedAboutMissingAddress = true
|
|
206
|
+
console.warn(
|
|
207
|
+
`Sign-in throttling cannot tell clients apart: no valid address in the "${CLIENT_IP_HEADER}" header, so wrong guesses from anyone can lock an email out. ` +
|
|
208
|
+
'Run the site behind a reverse proxy and set CLIENT_IP_HEADER / TRUSTED_PROXY_HOPS to match it.',
|
|
209
|
+
)
|
|
210
|
+
}
|
|
211
|
+
// Without a client address every attempt on an email counts against one shared pair ("none"), so
|
|
212
|
+
// the everyday limit becomes a plain per-email limit: wrong guesses from anywhere can lock that
|
|
213
|
+
// email out for a while. That is deliberate. The other choice, skipping this limit, would leave
|
|
214
|
+
// only the hourly cap (100 guesses an hour) on a site that is already misconfigured; a locked-out
|
|
215
|
+
// owner has `pnpm admin:reset-password`, a guessed password has no remedy.
|
|
216
|
+
const pairKey = `login:pair:${digest}|${address ?? 'none'}`
|
|
217
|
+
const emailKey = `login:email:${digest}`
|
|
218
|
+
await consumeAttempt(pairKey, PAIR_RULE)
|
|
219
|
+
await consumeAttempt(emailKey, EMAIL_RULE)
|
|
220
|
+
return { keys: [pairKey, emailKey] }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Call before checking the current password in "change password". Returns the key to clear on success. */
|
|
224
|
+
export async function guardPasswordChange(userId: string): Promise<{ keys: string[] }> {
|
|
225
|
+
const key = `chpw:${userId}`
|
|
226
|
+
await consumeAttempt(key, PASSWORD_CHANGE_RULE)
|
|
227
|
+
return { keys: [key] }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Call before using a reset or invite link (someone signed out sets a password). Throws a UserError
|
|
232
|
+
* when this client tried too often: each try can cost a deliberately slow password hash. Without a
|
|
233
|
+
* client address there is nothing to count by (as for reset requests); the token check before the
|
|
234
|
+
* hash still keeps made-up links cheap.
|
|
235
|
+
*/
|
|
236
|
+
export async function guardLinkUse(headers: Headers): Promise<void> {
|
|
237
|
+
const address = clientAddress(headers)
|
|
238
|
+
if (address) await consumeAttempt(`linkuse:ip:${address}`, LINK_USE_RULE)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Call before sending a reset email. Throws a UserError when this client asked too often. Returns
|
|
243
|
+
* whether an email may still go to this address: false once the address has had its share for the
|
|
244
|
+
* hour, whoever asked. That case is NOT an error: anyone can type anyone's address, so refusing
|
|
245
|
+
* would let a stranger show the owner "too many attempts" (and would tell them the count). The
|
|
246
|
+
* caller answers as usual and sends nothing. Counted whether or not the account exists.
|
|
247
|
+
*/
|
|
248
|
+
export async function guardResetRequest(email: unknown, headers: Headers): Promise<boolean> {
|
|
249
|
+
const address = clientAddress(headers)
|
|
250
|
+
if (address) await consumeAttempt(`pwreset:ip:${address}`, RESET_CLIENT_RULE)
|
|
251
|
+
try {
|
|
252
|
+
await consumeAttempt(`pwreset:email:${emailDigest(email)}`, RESET_EMAIL_RULE)
|
|
253
|
+
return true
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (isUserError(error)) return false
|
|
256
|
+
throw error
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Backup codes for two-factor sign-in: the format, the generator Better Auth uses
|
|
2
|
+
// (src/server/auth.ts) and the clean-up of what people type. No database here, so auth.ts can
|
|
3
|
+
// import it without a cycle.
|
|
4
|
+
import { randomInt } from 'node:crypto'
|
|
5
|
+
|
|
6
|
+
/** Lower case and digits without look-alikes (no 0/o, 1/l/i), so a code copied by hand still works. */
|
|
7
|
+
export const BACKUP_CODE_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789'
|
|
8
|
+
export const BACKUP_CODE_COUNT = 10
|
|
9
|
+
const HALF = 5
|
|
10
|
+
|
|
11
|
+
/** Ten codes like `k7m2p-x9qrt` (about 50 bits each), from the system's secure random source. */
|
|
12
|
+
export function generateBackupCodes(count = BACKUP_CODE_COUNT): string[] {
|
|
13
|
+
const part = () => Array.from({ length: HALF }, () => BACKUP_CODE_ALPHABET[randomInt(BACKUP_CODE_ALPHABET.length)]).join('')
|
|
14
|
+
return Array.from({ length: count }, () => `${part()}-${part()}`)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A typed backup code in the stored form, or null when it cannot be one: spaces and dashes are
|
|
19
|
+
* ignored and case does not matter, so `K7M2 PX9QRT` becomes `k7m2p-x9qrt`.
|
|
20
|
+
*/
|
|
21
|
+
export function normalizeBackupCode(input: string): string | null {
|
|
22
|
+
const compact = input.toLowerCase().replace(/[\s-]/g, '')
|
|
23
|
+
if (compact.length !== HALF * 2) return null
|
|
24
|
+
for (const char of compact) if (!BACKUP_CODE_ALPHABET.includes(char)) return null
|
|
25
|
+
return `${compact.slice(0, HALF)}-${compact.slice(HALF)}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A typed authenticator code (6 digits, spaces allowed: `123 456`), or null. */
|
|
29
|
+
export function normalizeTotpCode(input: string): string | null {
|
|
30
|
+
const compact = input.replace(/\s/g, '')
|
|
31
|
+
return /^\d{6}$/.test(compact) ? compact : null
|
|
32
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// Two-factor sign-in: the rules around Better Auth's twoFactor plugin (src/server/auth.ts), which
|
|
2
|
+
// itself stores the encrypted secret and backup codes, checks the codes and locks the code step
|
|
3
|
+
// after 10 wrong codes in a row. Agreed with the owner:
|
|
4
|
+
// - an authenticator app (TOTP) plus ten one-time backup codes; no email codes;
|
|
5
|
+
// - optional for everyone, and an admin can require it for chosen roles (`two_factor_roles` in
|
|
6
|
+
// site_settings, set on the Users screen). Someone whose role requires it and who has not set it
|
|
7
|
+
// up is shown the setup screen instead of the admin, and every action that needs a permission
|
|
8
|
+
// refuses (requirePermission in session.ts);
|
|
9
|
+
// - "Trust this device" skips the code on that browser for 30 days;
|
|
10
|
+
// - lost phone and codes: an admin turns it off for that account (Users), or, for the last admin,
|
|
11
|
+
// `pnpm admin:reset-2fa <email>`. A password reset does not turn it off (whoever can read the
|
|
12
|
+
// mailbox would get past the second step).
|
|
13
|
+
import { asRole, ROLES } from '@pet-adopt/plugin-sdk'
|
|
14
|
+
import { and, eq, like } from 'drizzle-orm'
|
|
15
|
+
import { cookies } from 'next/headers'
|
|
16
|
+
import { cache } from 'react'
|
|
17
|
+
|
|
18
|
+
import { getDatabase } from '@/db/client'
|
|
19
|
+
|
|
20
|
+
import { getAuth } from './auth'
|
|
21
|
+
import { cancelPendingLinks } from './pending-links'
|
|
22
|
+
import { logError, UserError, ValidationError } from './result'
|
|
23
|
+
import { open, seal } from './secret-box'
|
|
24
|
+
import type { Role, SessionUser } from './types'
|
|
25
|
+
|
|
26
|
+
const SETTINGS_ID = 1
|
|
27
|
+
/** Same as Better Auth's own code-step cookie (twoFactorCookieMaxAge in auth.ts). */
|
|
28
|
+
const PENDING_SECONDS = 600
|
|
29
|
+
const PENDING_COOKIE = 'pet-adopt.2fa-pending'
|
|
30
|
+
const PENDING_PURPOSE = 'two-factor-pending'
|
|
31
|
+
/** Better Auth names each trusted-device record `trust-device-<random>`, valued with the user id. */
|
|
32
|
+
const TRUSTED_DEVICE_PREFIX = 'trust-device-'
|
|
33
|
+
|
|
34
|
+
function cleanRoles(value: unknown): Role[] {
|
|
35
|
+
if (!Array.isArray(value)) return []
|
|
36
|
+
return ROLES.filter((role) => value.includes(role))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The roles that must use two-factor sign-in, in the usual role order. Read once per request. */
|
|
40
|
+
export const getTwoFactorRoles = cache(async (): Promise<Role[]> => {
|
|
41
|
+
const { db, t } = await getDatabase()
|
|
42
|
+
const [row] = await db.select({ roles: t.siteSettings.twoFactorRoles }).from(t.siteSettings).where(eq(t.siteSettings.id, SETTINGS_ID)).limit(1)
|
|
43
|
+
return cleanRoles(row?.roles)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
/** Whether this role must use two-factor sign-in. */
|
|
47
|
+
export async function roleRequiresTwoFactor(role: Role): Promise<boolean> {
|
|
48
|
+
return (await getTwoFactorRoles()).includes(role)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* True when the person's role requires two-factor and they have not set it up yet. A session from a
|
|
53
|
+
* sign-in provider counts as two-factor (agreed with the owner: the provider does its own checks).
|
|
54
|
+
*/
|
|
55
|
+
export async function needsTwoFactorSetup(user: SessionUser): Promise<boolean> {
|
|
56
|
+
if (user.twoFactorEnabled || user.signInMethod.startsWith('provider:')) return false
|
|
57
|
+
return roleRequiresTwoFactor(user.role)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Saves which roles must use two-factor. Returns the roles before and after, for the log. */
|
|
61
|
+
export async function saveTwoFactorRoles(input: unknown): Promise<{ before: Role[]; after: Role[] }> {
|
|
62
|
+
if (!Array.isArray(input) || input.some((role) => typeof role !== 'string' || !(ROLES as readonly string[]).includes(role))) {
|
|
63
|
+
throw new ValidationError({ roles: 'Pick roles from the list.' })
|
|
64
|
+
}
|
|
65
|
+
const after = cleanRoles(input)
|
|
66
|
+
const { db, t } = await getDatabase()
|
|
67
|
+
// Not getTwoFactorRoles(): it is cached for the request.
|
|
68
|
+
const [row] = await db.select({ roles: t.siteSettings.twoFactorRoles }).from(t.siteSettings).where(eq(t.siteSettings.id, SETTINGS_ID)).limit(1)
|
|
69
|
+
const before = cleanRoles(row?.roles)
|
|
70
|
+
await db.insert(t.siteSettings).values({ id: SETTINGS_ID }).onConflictDoNothing()
|
|
71
|
+
await db.update(t.siteSettings).set({ twoFactorRoles: after, updatedAt: new Date() }).where(eq(t.siteSettings.id, SETTINGS_ID))
|
|
72
|
+
return { before, after }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Forgets every browser this account marked "Trust this device", so each asks for a code again. */
|
|
76
|
+
export async function forgetTrustedDevices(userId: string): Promise<void> {
|
|
77
|
+
const { db, t } = await getDatabase()
|
|
78
|
+
await db.delete(t.verifications).where(and(like(t.verifications.identifier, `${TRUSTED_DEVICE_PREFIX}%`), eq(t.verifications.value, userId)))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Turns two-factor off for an account (an admin's reset, or the command line): removes the secret
|
|
83
|
+
* and backup codes and every trusted browser. The person keeps their sessions and their password;
|
|
84
|
+
* if their role requires two-factor they are asked to set it up again at once.
|
|
85
|
+
*/
|
|
86
|
+
export async function resetTwoFactor(userId: string): Promise<{ id: string; name: string; email: string; role: Role; wasEnabled: boolean }> {
|
|
87
|
+
const { t, withTransaction } = await getDatabase()
|
|
88
|
+
return withTransaction(async (tx) => {
|
|
89
|
+
const [user] = await tx
|
|
90
|
+
.select({ id: t.users.id, name: t.users.name, email: t.users.email, role: t.users.role, enabled: t.users.twoFactorEnabled })
|
|
91
|
+
.from(t.users)
|
|
92
|
+
.where(eq(t.users.id, userId))
|
|
93
|
+
.limit(1)
|
|
94
|
+
if (!user) throw new UserError('That account no longer exists.')
|
|
95
|
+
await tx.delete(t.twoFactors).where(eq(t.twoFactors.userId, userId))
|
|
96
|
+
await tx.update(t.users).set({ twoFactorEnabled: false }).where(eq(t.users.id, userId))
|
|
97
|
+
await tx.delete(t.verifications).where(and(like(t.verifications.identifier, `${TRUSTED_DEVICE_PREFIX}%`), eq(t.verifications.value, userId)))
|
|
98
|
+
// A recovery step, like a new password: an email change asked for before it stops working.
|
|
99
|
+
await cancelPendingLinks(tx, t, userId, ['email-change'])
|
|
100
|
+
return { id: user.id, name: user.name, email: user.email, role: asRole(user.role), wasEnabled: Boolean(user.enabled) }
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** How many unused backup codes an account has left, or null when two-factor is not set up. */
|
|
105
|
+
export async function backupCodesLeft(userId: string): Promise<number | null> {
|
|
106
|
+
const { db, t } = await getDatabase()
|
|
107
|
+
const [row] = await db.select({ verified: t.twoFactors.verified }).from(t.twoFactors).where(eq(t.twoFactors.userId, userId)).limit(1)
|
|
108
|
+
if (!row || row.verified === false) return null
|
|
109
|
+
const auth = await getAuth()
|
|
110
|
+
try {
|
|
111
|
+
const { backupCodes } = await auth.api.viewBackupCodes({ body: { userId } })
|
|
112
|
+
return backupCodes.length
|
|
113
|
+
} catch (error) {
|
|
114
|
+
// Codes that cannot be opened (another BETTER_AUTH_SECRET) count as none left. Logged, because
|
|
115
|
+
// the same failure also hides a database or Better Auth problem.
|
|
116
|
+
logError(error, 'could not read backup codes')
|
|
117
|
+
return 0
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// --- The code step of a sign-in ------------------------------------------------------------
|
|
122
|
+
// Better Auth keeps the account of a half-finished sign-in behind its own signed cookie and does not
|
|
123
|
+
// tell us who it is. This sealed cookie remembers it, only so a wrong code can be logged against
|
|
124
|
+
// that account; it is never used to decide who may sign in.
|
|
125
|
+
|
|
126
|
+
/** Remembers, for 10 minutes on this browser, which account is at the code step. */
|
|
127
|
+
export async function rememberPendingSignIn(userId: string): Promise<void> {
|
|
128
|
+
const value = seal(JSON.stringify({ id: userId, until: Date.now() + PENDING_SECONDS * 1000 }), PENDING_PURPOSE)
|
|
129
|
+
;(await cookies()).set(PENDING_COOKIE, value, {
|
|
130
|
+
httpOnly: true,
|
|
131
|
+
sameSite: 'lax',
|
|
132
|
+
secure: process.env.NODE_ENV === 'production',
|
|
133
|
+
path: '/',
|
|
134
|
+
maxAge: PENDING_SECONDS,
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The account at the code step on this browser, or null (none, expired or tampered with). */
|
|
139
|
+
export async function pendingSignIn(): Promise<{ id: string; name: string } | null> {
|
|
140
|
+
const raw = open((await cookies()).get(PENDING_COOKIE)?.value, PENDING_PURPOSE)
|
|
141
|
+
if (!raw) return null
|
|
142
|
+
let parsed: unknown
|
|
143
|
+
try {
|
|
144
|
+
parsed = JSON.parse(raw)
|
|
145
|
+
} catch {
|
|
146
|
+
return null
|
|
147
|
+
}
|
|
148
|
+
const { id, until } = (parsed ?? {}) as { id?: unknown; until?: unknown }
|
|
149
|
+
if (typeof id !== 'string' || typeof until !== 'number' || until < Date.now()) return null
|
|
150
|
+
const { db, t } = await getDatabase()
|
|
151
|
+
const [user] = await db.select({ id: t.users.id, name: t.users.name }).from(t.users).where(eq(t.users.id, id)).limit(1)
|
|
152
|
+
return user ?? null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Ends the code step on this browser (signed in, or sent back to the password). */
|
|
156
|
+
export async function forgetPendingSignIn(): Promise<void> {
|
|
157
|
+
;(await cookies()).delete(PENDING_COOKIE)
|
|
158
|
+
}
|