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,359 @@
|
|
|
1
|
+
// Sign-in providers: "bring your own" OAuth 2 / OpenID Connect (agreed with the owner). Admins add
|
|
2
|
+
// any number on Authentication > Sign-in providers; Better Auth's genericOAuth plugin is built from
|
|
3
|
+
// the enabled ones (src/server/auth.ts). Rules:
|
|
4
|
+
// - a provider never creates an account and never links one by matching email: each person
|
|
5
|
+
// connects it to their own account first, while signed in (Account page); after that it signs
|
|
6
|
+
// them in. So a provider that lets its users pick any email cannot take an account over;
|
|
7
|
+
// - a provider sign-in counts as two-factor (the provider does its own checks);
|
|
8
|
+
// - the client secret is stored only encrypted (secret-box) and never sent to a browser;
|
|
9
|
+
// - endpoints must be https (http only for a loopback host outside production, for local testing);
|
|
10
|
+
// - the slug (Better Auth's provider id, in the callback address) is fixed once created;
|
|
11
|
+
// - deleting a provider removes everyone's connection to it.
|
|
12
|
+
import { foldText } from '@pet-adopt/plugin-sdk'
|
|
13
|
+
import { and, count, eq, inArray, max } from 'drizzle-orm'
|
|
14
|
+
|
|
15
|
+
import { getDatabase } from '@/db/client'
|
|
16
|
+
|
|
17
|
+
import { getAuth, SITE_URL } from './auth'
|
|
18
|
+
import { DISCOVERY_UNREADABLE, discoveryProblem, endpointProblem } from './provider-endpoints'
|
|
19
|
+
import { isLoopbackHost } from './email'
|
|
20
|
+
import { asRecord, Fields, logError, UserError } from './result'
|
|
21
|
+
import { open, seal } from './secret-box'
|
|
22
|
+
|
|
23
|
+
export type ProviderKind = 'oidc' | 'oauth2'
|
|
24
|
+
export const PROVIDER_KINDS = [
|
|
25
|
+
{ value: 'oidc', label: 'OpenID Connect (discovery URL)' },
|
|
26
|
+
{ value: 'oauth2', label: 'OAuth 2 (endpoints by hand)' },
|
|
27
|
+
] as const satisfies readonly { value: ProviderKind; label: string }[]
|
|
28
|
+
|
|
29
|
+
export const DEFAULT_SCOPES: Record<ProviderKind, string> = { oidc: 'openid email profile', oauth2: 'email profile' }
|
|
30
|
+
|
|
31
|
+
/** What the admin screen sees. Never the secret. */
|
|
32
|
+
export type AuthProviderView = {
|
|
33
|
+
id: number
|
|
34
|
+
slug: string
|
|
35
|
+
name: string
|
|
36
|
+
kind: ProviderKind
|
|
37
|
+
discoveryUrl: string | null
|
|
38
|
+
authorizationUrl: string | null
|
|
39
|
+
tokenUrl: string | null
|
|
40
|
+
userInfoUrl: string | null
|
|
41
|
+
clientId: string
|
|
42
|
+
secretSet: boolean
|
|
43
|
+
scopes: string
|
|
44
|
+
enabled: boolean
|
|
45
|
+
/** The address to register at the provider. */
|
|
46
|
+
redirectUri: string
|
|
47
|
+
/** How many accounts have connected it. */
|
|
48
|
+
connected: number
|
|
49
|
+
updatedAt: Date
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What the sign-in page and the Account page need: no endpoints, no client id. */
|
|
53
|
+
export type PublicProvider = { slug: string; name: string }
|
|
54
|
+
|
|
55
|
+
const SECRET_PURPOSE = 'auth-provider-secret'
|
|
56
|
+
/** Better Auth's own account kinds: a provider slug must not collide with them. */
|
|
57
|
+
const RESERVED_SLUGS = ['credential', 'email', 'password', 'email-password', 'anonymous']
|
|
58
|
+
const SCOPE = /^[\x21\x23-\x5b\x5d-\x7e]+$/
|
|
59
|
+
|
|
60
|
+
/** The callback address Better Auth uses for a provider. */
|
|
61
|
+
export function redirectUriFor(slug: string): string {
|
|
62
|
+
return `${SITE_URL}/api/auth/callback/${slug}`
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* An endpoint the server will call: https (http only on a loopback host outside production). Where
|
|
67
|
+
* it points is checked separately, because that needs a lookup (provider-endpoints.ts).
|
|
68
|
+
*/
|
|
69
|
+
export function validateEndpoint(value: string): true | string {
|
|
70
|
+
let url: URL
|
|
71
|
+
try {
|
|
72
|
+
url = new URL(value)
|
|
73
|
+
} catch {
|
|
74
|
+
return 'Enter a full address, starting with https://.'
|
|
75
|
+
}
|
|
76
|
+
if (url.username || url.password) return 'The address must not contain a user name or password.'
|
|
77
|
+
if (url.hash) return 'Remove the # part.'
|
|
78
|
+
const local = isLoopbackHost(url.hostname) && process.env.NODE_ENV !== 'production'
|
|
79
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) return 'Use an https:// address.'
|
|
80
|
+
return true
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function slugFrom(name: string): string {
|
|
84
|
+
const base = foldText(name)
|
|
85
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
86
|
+
.replace(/^-+|-+$/g, '')
|
|
87
|
+
.slice(0, 40)
|
|
88
|
+
.replace(/-+$/, '')
|
|
89
|
+
return base && !RESERVED_SLUGS.includes(base) ? base : 'provider'
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
type Row = typeof import('@/db/schema/sqlite').authProviders.$inferSelect
|
|
93
|
+
|
|
94
|
+
function view(row: Row, connected: number): AuthProviderView {
|
|
95
|
+
return {
|
|
96
|
+
id: row.id,
|
|
97
|
+
slug: row.slug,
|
|
98
|
+
name: row.name,
|
|
99
|
+
kind: row.kind === 'oauth2' ? 'oauth2' : 'oidc',
|
|
100
|
+
discoveryUrl: row.discoveryUrl,
|
|
101
|
+
authorizationUrl: row.authorizationUrl,
|
|
102
|
+
tokenUrl: row.tokenUrl,
|
|
103
|
+
userInfoUrl: row.userInfoUrl,
|
|
104
|
+
clientId: row.clientId,
|
|
105
|
+
secretSet: Boolean(row.clientSecretEncrypted),
|
|
106
|
+
scopes: row.scopes,
|
|
107
|
+
enabled: row.enabled,
|
|
108
|
+
redirectUri: redirectUriFor(row.slug),
|
|
109
|
+
connected,
|
|
110
|
+
updatedAt: row.updatedAt,
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Every provider, in name order, with how many accounts connected it. */
|
|
115
|
+
export async function listAuthProviders(): Promise<AuthProviderView[]> {
|
|
116
|
+
const { db, t } = await getDatabase()
|
|
117
|
+
const rows = await db.select().from(t.authProviders)
|
|
118
|
+
const counts = rows.length
|
|
119
|
+
? await db
|
|
120
|
+
.select({ providerId: t.accounts.providerId, n: count() })
|
|
121
|
+
.from(t.accounts)
|
|
122
|
+
.where(inArray(t.accounts.providerId, rows.map((row) => row.slug)))
|
|
123
|
+
.groupBy(t.accounts.providerId)
|
|
124
|
+
: []
|
|
125
|
+
const connected = new Map(counts.map((c) => [c.providerId, c.n]))
|
|
126
|
+
return rows.map((row) => view(row, connected.get(row.slug) ?? 0)).sort((a, b) => foldText(a.name).localeCompare(foldText(b.name)))
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The enabled providers this server's Better Auth was built with, for the sign-in and Account pages.
|
|
131
|
+
* One providerConfigs left out (see `skipped`) is not offered: it could not sign anyone in.
|
|
132
|
+
*/
|
|
133
|
+
export async function listEnabledProviders(): Promise<PublicProvider[]> {
|
|
134
|
+
// Built first, so `skipped` describes the instance that would handle the sign-in.
|
|
135
|
+
await getAuth()
|
|
136
|
+
return (await listAuthProviders()).filter((p) => p.enabled && !skipped.has(p.slug)).map(({ slug, name }) => ({ slug, name }))
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Which providers this account has connected (Better Auth account rows, by provider id). */
|
|
140
|
+
export async function connectedProviders(userId: string): Promise<Set<string>> {
|
|
141
|
+
const { db, t } = await getDatabase()
|
|
142
|
+
const rows = await db.select({ providerId: t.accounts.providerId }).from(t.accounts).where(eq(t.accounts.userId, userId))
|
|
143
|
+
return new Set(rows.map((row) => row.providerId))
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Removes one account's connection to a provider (its Better Auth account row). */
|
|
147
|
+
export async function disconnectProvider(userId: string, slug: string): Promise<void> {
|
|
148
|
+
if (slug === 'credential') throw new UserError('That provider is not connected.')
|
|
149
|
+
const { db, t } = await getDatabase()
|
|
150
|
+
await db.delete(t.accounts).where(and(eq(t.accounts.userId, userId), eq(t.accounts.providerId, slug)))
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Creates (`id` null) or updates a provider: `{ name, kind, discoveryUrl | authorizationUrl,
|
|
155
|
+
* tokenUrl, userInfoUrl, clientId, clientSecret, clearSecret, scopes, enabled }`. A blank client
|
|
156
|
+
* secret keeps the stored one. Returns the provider and the names of the fields that changed.
|
|
157
|
+
*/
|
|
158
|
+
export async function saveAuthProvider(id: number | null, raw: unknown): Promise<{ provider: AuthProviderView; fields: string[] }> {
|
|
159
|
+
const input = asRecord(raw)
|
|
160
|
+
const creating = id === null
|
|
161
|
+
const f = new Fields(input, creating)
|
|
162
|
+
const name = f.requiredText('name', 60)
|
|
163
|
+
const kind = f.oneOf('kind', PROVIDER_KINDS, { required: creating })
|
|
164
|
+
const url = (key: string) => f.text(key, 500, { validate: validateEndpoint })
|
|
165
|
+
const discoveryUrl = url('discoveryUrl')
|
|
166
|
+
const authorizationUrl = url('authorizationUrl')
|
|
167
|
+
const tokenUrl = url('tokenUrl')
|
|
168
|
+
const userInfoUrl = url('userInfoUrl')
|
|
169
|
+
const clientId = f.requiredText('clientId', 500)
|
|
170
|
+
const secretRaw = input.clientSecret
|
|
171
|
+
if (secretRaw !== undefined && secretRaw !== null && typeof secretRaw !== 'string') f.fail_('clientSecret', 'Must be text.')
|
|
172
|
+
const clientSecret = typeof secretRaw === 'string' ? secretRaw.trim() : ''
|
|
173
|
+
if (clientSecret.length > 2000) f.fail_('clientSecret', 'Use at most 2000 characters.')
|
|
174
|
+
const clearSecret = f.flag('clearSecret')
|
|
175
|
+
const scopes = f.text('scopes', 500, {
|
|
176
|
+
collapse: true,
|
|
177
|
+
validate: (value) => value.split(' ').every((scope) => SCOPE.test(scope)) || 'Scopes are words separated by spaces.',
|
|
178
|
+
})
|
|
179
|
+
const enabled = f.flag('enabled')
|
|
180
|
+
|
|
181
|
+
const { db, t } = await getDatabase()
|
|
182
|
+
const [existing] = creating ? [] : await db.select().from(t.authProviders).where(eq(t.authProviders.id, id)).limit(1)
|
|
183
|
+
if (!creating && !existing) throw new UserError('That sign-in provider no longer exists.')
|
|
184
|
+
const effectiveKind: ProviderKind = (kind ?? existing?.kind) === 'oauth2' ? 'oauth2' : 'oidc'
|
|
185
|
+
const pick = <T,>(value: T | null | undefined, stored: T | null | undefined) => (value === undefined ? (stored ?? null) : value)
|
|
186
|
+
const next = {
|
|
187
|
+
discoveryUrl: pick(discoveryUrl, existing?.discoveryUrl),
|
|
188
|
+
authorizationUrl: pick(authorizationUrl, existing?.authorizationUrl),
|
|
189
|
+
tokenUrl: pick(tokenUrl, existing?.tokenUrl),
|
|
190
|
+
userInfoUrl: pick(userInfoUrl, existing?.userInfoUrl),
|
|
191
|
+
}
|
|
192
|
+
if (effectiveKind === 'oidc' && !next.discoveryUrl) f.fail_('discoveryUrl', 'Enter the discovery URL (it usually ends in /.well-known/openid-configuration).')
|
|
193
|
+
if (effectiveKind === 'oauth2') {
|
|
194
|
+
if (!next.authorizationUrl) f.fail_('authorizationUrl', 'Enter the authorization URL.')
|
|
195
|
+
if (!next.tokenUrl) f.fail_('tokenUrl', 'Enter the token URL.')
|
|
196
|
+
if (!next.userInfoUrl) f.fail_('userInfoUrl', 'Enter the user info URL (it must return an email).')
|
|
197
|
+
}
|
|
198
|
+
// The addresses the server itself will call must be public (see provider-endpoints.ts). The
|
|
199
|
+
// authorization address is only opened by the person's browser.
|
|
200
|
+
if (effectiveKind === 'oidc' && next.discoveryUrl) {
|
|
201
|
+
const problem = await discoveryProblem(next.discoveryUrl)
|
|
202
|
+
if (problem) f.fail_('discoveryUrl', problem)
|
|
203
|
+
}
|
|
204
|
+
if (effectiveKind === 'oauth2') {
|
|
205
|
+
for (const key of ['tokenUrl', 'userInfoUrl'] as const) {
|
|
206
|
+
const problem = next[key] ? await endpointProblem(next[key]) : null
|
|
207
|
+
if (problem) f.fail_(key, problem)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
f.done()
|
|
211
|
+
|
|
212
|
+
const secret = clearSecret ? null : clientSecret ? seal(clientSecret, SECRET_PURPOSE) : (existing?.clientSecretEncrypted ?? null)
|
|
213
|
+
const values = {
|
|
214
|
+
name: name ?? existing!.name,
|
|
215
|
+
kind: effectiveKind,
|
|
216
|
+
// Only the fields of the chosen kind are kept, so a switch leaves nothing stale behind.
|
|
217
|
+
discoveryUrl: effectiveKind === 'oidc' ? next.discoveryUrl : null,
|
|
218
|
+
authorizationUrl: effectiveKind === 'oauth2' ? next.authorizationUrl : null,
|
|
219
|
+
tokenUrl: effectiveKind === 'oauth2' ? next.tokenUrl : null,
|
|
220
|
+
userInfoUrl: effectiveKind === 'oauth2' ? next.userInfoUrl : null,
|
|
221
|
+
clientId: clientId ?? existing!.clientId,
|
|
222
|
+
clientSecretEncrypted: secret,
|
|
223
|
+
scopes: scopes ?? existing?.scopes ?? DEFAULT_SCOPES[effectiveKind],
|
|
224
|
+
enabled: enabled ?? existing?.enabled ?? false,
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let rowId = id
|
|
228
|
+
if (creating) {
|
|
229
|
+
// A slug nobody uses yet: "google", then "google-2"...
|
|
230
|
+
const base = slugFrom(values.name)
|
|
231
|
+
const taken = new Set((await db.select({ slug: t.authProviders.slug }).from(t.authProviders)).map((row) => row.slug))
|
|
232
|
+
let slug = base
|
|
233
|
+
for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`
|
|
234
|
+
const [row] = await db.insert(t.authProviders).values({ ...values, slug }).returning({ id: t.authProviders.id })
|
|
235
|
+
rowId = row.id
|
|
236
|
+
} else {
|
|
237
|
+
await db.update(t.authProviders).set({ ...values, updatedAt: new Date() }).where(eq(t.authProviders.id, id))
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const provider = (await listAuthProviders()).find((p) => p.id === rowId)!
|
|
241
|
+
const fields: string[] = creating
|
|
242
|
+
? []
|
|
243
|
+
: (Object.keys(values) as (keyof typeof values)[]).filter((key) => key !== 'clientSecretEncrypted' && values[key] !== existing![key])
|
|
244
|
+
if (!creating && secret !== existing!.clientSecretEncrypted) fields.push('clientSecret')
|
|
245
|
+
return { provider, fields }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Deletes a provider and everyone's connection to it. Returns its name and how many were connected. */
|
|
249
|
+
export async function deleteAuthProvider(id: number): Promise<{ name: string; slug: string; disconnected: number }> {
|
|
250
|
+
const { t, withTransaction } = await getDatabase()
|
|
251
|
+
return withTransaction(async (tx) => {
|
|
252
|
+
const [row] = await tx.select().from(t.authProviders).where(eq(t.authProviders.id, id)).limit(1)
|
|
253
|
+
if (!row) throw new UserError('That sign-in provider no longer exists.')
|
|
254
|
+
const links = await tx.delete(t.accounts).where(eq(t.accounts.providerId, row.slug)).returning({ id: t.accounts.id })
|
|
255
|
+
await tx.delete(t.authProviders).where(eq(t.authProviders.id, id))
|
|
256
|
+
return { name: row.name, slug: row.slug, disconnected: links.length }
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// A provider whose discovery document could not be read (a timeout, an error page, a network blip)
|
|
261
|
+
// is left out, but unlike one refused for a private address or a redirect it may work a moment
|
|
262
|
+
// later. So while one is left out, the version below changes once each retry falls due, and auth.ts
|
|
263
|
+
// rebuilds Better Auth then: first after 30 seconds, then twice as long each time up to 10 minutes,
|
|
264
|
+
// so a document that stays unreadable is not fetched on a live request every 30 seconds forever.
|
|
265
|
+
const RETRY_FIRST_MS = 30_000
|
|
266
|
+
const RETRY_MAX_MS = 10 * 60_000
|
|
267
|
+
const retry: { at: number | null; delay: number; round: number } = { at: null, delay: RETRY_FIRST_MS, round: 0 }
|
|
268
|
+
|
|
269
|
+
/** Enabled providers the last providerConfigs on this server left out, by slug, with the reason. */
|
|
270
|
+
const skipped = ((globalThis as { __petAdoptSkippedProviders?: Map<string, string> }).__petAdoptSkippedProviders ??= new Map())
|
|
271
|
+
|
|
272
|
+
// A skipped provider is logged at most once an hour for the same reason (a rebuild can run often).
|
|
273
|
+
const SKIP_LOG_MS = 60 * 60_000
|
|
274
|
+
const skipLogged = new Map<string, number>()
|
|
275
|
+
|
|
276
|
+
function logSkip(slug: string, problem: string): void {
|
|
277
|
+
const key = `${slug}\n${problem}`
|
|
278
|
+
const last = skipLogged.get(key)
|
|
279
|
+
if (last !== undefined && Date.now() - last < SKIP_LOG_MS) return
|
|
280
|
+
skipLogged.set(key, Date.now())
|
|
281
|
+
logError(new Error(problem), `sign-in provider "${slug}" skipped`)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Changes whenever a provider is added, changed or removed (auth.ts rebuilds Better Auth then), and
|
|
286
|
+
* when a retry of a provider left out for an unreadable discovery document falls due (see above).
|
|
287
|
+
*/
|
|
288
|
+
export async function providersVersion(): Promise<string> {
|
|
289
|
+
const { db, t } = await getDatabase()
|
|
290
|
+
const [row] = await db.select({ n: count(), latest: max(t.authProviders.updatedAt) }).from(t.authProviders)
|
|
291
|
+
const latest = row?.latest ? new Date(row.latest).getTime() : 0
|
|
292
|
+
// Claimed here, so the rebuild this starts (which reads the version too) sees the same round.
|
|
293
|
+
if (retry.at !== null && Date.now() >= retry.at) {
|
|
294
|
+
retry.round++
|
|
295
|
+
retry.at = Date.now() + retry.delay
|
|
296
|
+
}
|
|
297
|
+
return `${row?.n ?? 0}:${latest}:${retry.round}`
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The enabled providers as Better Auth genericOAuth configs. A secret that cannot be opened skips its provider. */
|
|
301
|
+
export async function providerConfigs() {
|
|
302
|
+
const { db, t } = await getDatabase()
|
|
303
|
+
const rows = await db.select().from(t.authProviders).where(eq(t.authProviders.enabled, true))
|
|
304
|
+
const configs = []
|
|
305
|
+
const left = new Map<string, string>()
|
|
306
|
+
let unreadable = false
|
|
307
|
+
for (const row of rows) {
|
|
308
|
+
let clientSecret: string | undefined
|
|
309
|
+
if (row.clientSecretEncrypted) {
|
|
310
|
+
const opened = open(row.clientSecretEncrypted, SECRET_PURPOSE)
|
|
311
|
+
if (opened === null) {
|
|
312
|
+
const problem = 'its client secret cannot be opened (was BETTER_AUTH_SECRET changed?)'
|
|
313
|
+
logSkip(row.slug, problem)
|
|
314
|
+
left.set(row.slug, problem)
|
|
315
|
+
continue
|
|
316
|
+
}
|
|
317
|
+
clientSecret = opened
|
|
318
|
+
}
|
|
319
|
+
// Checked again here, not only when saved: a host name can be pointed somewhere else later.
|
|
320
|
+
const problem =
|
|
321
|
+
row.kind === 'oauth2'
|
|
322
|
+
? ((row.tokenUrl ? await endpointProblem(row.tokenUrl) : null) ?? (row.userInfoUrl ? await endpointProblem(row.userInfoUrl) : null))
|
|
323
|
+
: row.discoveryUrl
|
|
324
|
+
? await discoveryProblem(row.discoveryUrl, { strict: true })
|
|
325
|
+
: null
|
|
326
|
+
if (problem) {
|
|
327
|
+
logSkip(row.slug, problem)
|
|
328
|
+
left.set(row.slug, problem)
|
|
329
|
+
// Only a document that could not be read is worth another try; a redirect or a private address is not.
|
|
330
|
+
if (problem === DISCOVERY_UNREADABLE) unreadable = true
|
|
331
|
+
continue
|
|
332
|
+
}
|
|
333
|
+
configs.push({
|
|
334
|
+
providerId: row.slug,
|
|
335
|
+
name: row.name,
|
|
336
|
+
...(row.kind === 'oauth2'
|
|
337
|
+
? { authorizationUrl: row.authorizationUrl ?? undefined, tokenUrl: row.tokenUrl ?? undefined, userInfoUrl: row.userInfoUrl ?? undefined }
|
|
338
|
+
: { discoveryUrl: row.discoveryUrl ?? undefined }),
|
|
339
|
+
clientId: row.clientId,
|
|
340
|
+
clientSecret,
|
|
341
|
+
scopes: row.scopes.split(' ').filter(Boolean),
|
|
342
|
+
pkce: true,
|
|
343
|
+
// Never an account from a provider; never a link by matching email (see the top of this file).
|
|
344
|
+
disableSignUp: true,
|
|
345
|
+
disableImplicitSignUp: true,
|
|
346
|
+
overrideUserInfo: false,
|
|
347
|
+
})
|
|
348
|
+
}
|
|
349
|
+
if (unreadable) {
|
|
350
|
+
retry.delay = retry.at === null ? RETRY_FIRST_MS : Math.min(retry.delay * 2, RETRY_MAX_MS)
|
|
351
|
+
retry.at = Date.now() + retry.delay
|
|
352
|
+
} else {
|
|
353
|
+
retry.at = null
|
|
354
|
+
retry.delay = RETRY_FIRST_MS
|
|
355
|
+
}
|
|
356
|
+
skipped.clear()
|
|
357
|
+
for (const [slug, problem] of left) skipped.set(slug, problem)
|
|
358
|
+
return configs
|
|
359
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Authentication with Better Auth, on this app's own Drizzle database.
|
|
2
|
+
//
|
|
3
|
+
// - Only the owners sign in; there is no public sign-up. Accounts are created by an admin
|
|
4
|
+
// (src/server/users.ts, with a password or an email invite), by the first-time setup
|
|
5
|
+
// (src/server/setup.ts), or from SEED_ADMIN_EMAIL / SEED_ADMIN_PASSWORD on first start.
|
|
6
|
+
// - Roles (admin, editor, developer, audit) are our own: a `role` column Better Auth only carries
|
|
7
|
+
// (additionalFields below), and the permission table in the plugin SDK (`can`). No admin plugin.
|
|
8
|
+
// - Archived accounts (src/server/users.ts) cannot sign in: the session hook below refuses them,
|
|
9
|
+
// on every way in (password, two-factor code), and getSessionUser ignores them.
|
|
10
|
+
// - Sessions last 2 hours. Sign-in is throttled in src/server/throttle.ts (per client, per email
|
|
11
|
+
// and client, and per email overall).
|
|
12
|
+
// - Two-factor sign-in (authenticator app plus backup codes) with Better Auth's twoFactor plugin,
|
|
13
|
+
// driven by the server actions in src/server/actions/two-factor.ts; its HTTP endpoints stay closed
|
|
14
|
+
// (see the route handler). Rules around it (who must use it, admin reset) are in two-factor.ts.
|
|
15
|
+
// - Sign-in providers (OAuth 2 / OIDC, src/server/auth-providers.ts) through the genericOAuth
|
|
16
|
+
// plugin, built from the enabled providers in the database and rebuilt when they change
|
|
17
|
+
// (getAuth). A provider only signs in an account that connected it first; it never creates or
|
|
18
|
+
// links one by email. Each session records how it signed in (`sign_in_method`).
|
|
19
|
+
// - Every role change goes through src/server/users.ts and its last-admin protection; the route
|
|
20
|
+
// handler opens only the endpoints this app uses.
|
|
21
|
+
import { betterAuth } from 'better-auth'
|
|
22
|
+
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
|
|
23
|
+
import { nextCookies } from 'better-auth/next-js'
|
|
24
|
+
import { APIError } from 'better-auth/api'
|
|
25
|
+
import { genericOAuth, twoFactor, type GenericOAuthConfig } from 'better-auth/plugins'
|
|
26
|
+
|
|
27
|
+
import { eq } from 'drizzle-orm'
|
|
28
|
+
|
|
29
|
+
import { getDatabase, type Database } from '@/db/client'
|
|
30
|
+
|
|
31
|
+
import { logError } from './result'
|
|
32
|
+
import { CLIENT_IP_HEADER } from './throttle'
|
|
33
|
+
import { generateBackupCodes } from './two-factor-codes'
|
|
34
|
+
|
|
35
|
+
const production = process.env.NODE_ENV === 'production'
|
|
36
|
+
// `next build` loads this too (often in CI with no secrets), so it is exempt from the checks.
|
|
37
|
+
const enforce = production && process.env.NEXT_PHASE !== 'phase-production-build'
|
|
38
|
+
|
|
39
|
+
// Only used when BETTER_AUTH_SECRET is empty during local development.
|
|
40
|
+
const DEV_SECRET = 'insecure-development-secret-do-not-deploy'
|
|
41
|
+
|
|
42
|
+
function resolveSecret(): string {
|
|
43
|
+
const secret = process.env.BETTER_AUTH_SECRET ?? ''
|
|
44
|
+
if (enforce && (secret.length < 32 || secret === 'change-me')) {
|
|
45
|
+
throw new Error('BETTER_AUTH_SECRET must be a random string of at least 32 characters. Generate one with: openssl rand -hex 32')
|
|
46
|
+
}
|
|
47
|
+
return secret || DEV_SECRET
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Throws, in production, when the signing secret is missing or weak. Called at server start
|
|
52
|
+
* (src/instrumentation.ts) so a bad deploy fails loudly there instead of answering every sign-in
|
|
53
|
+
* with an error. The site URL is checked when this module loads.
|
|
54
|
+
*/
|
|
55
|
+
export function assertAuthConfig() {
|
|
56
|
+
resolveSecret()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The signing secret (the development fallback when unset outside production). Server-only. */
|
|
60
|
+
export function authSecret(): string {
|
|
61
|
+
return resolveSecret()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Public URL of the site. Browsers may only send cookie-authenticated requests from here.
|
|
65
|
+
const siteURL = (process.env.NEXT_PUBLIC_SERVER_URL ?? '').trim().replace(/\/+$/, '')
|
|
66
|
+
if (enforce && !siteURL) {
|
|
67
|
+
throw new Error('NEXT_PUBLIC_SERVER_URL must be set in production, for example https://adopt.example.com')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** How long "Trust this device" skips the code step on that browser. */
|
|
71
|
+
export const TRUST_DEVICE_DAYS = 30
|
|
72
|
+
|
|
73
|
+
export const MIN_PASSWORD_LENGTH = production ? 12 : 8
|
|
74
|
+
|
|
75
|
+
/** The site's own address, for links that leave the site (reset emails). Never taken from a request. */
|
|
76
|
+
export const SITE_URL = siteURL || 'http://localhost:3000'
|
|
77
|
+
|
|
78
|
+
/** Better Auth's error for a sign-in to an archived account (actions/auth.ts shows it). */
|
|
79
|
+
export const ACCOUNT_ARCHIVED = 'ACCOUNT_ARCHIVED'
|
|
80
|
+
|
|
81
|
+
/** How often a server checks whether the sign-in providers changed (another server may have saved). */
|
|
82
|
+
const PROVIDER_RECHECK_MS = 30_000
|
|
83
|
+
|
|
84
|
+
/** The provider of a session made by a provider's callback (`/callback/<id>`), else null. */
|
|
85
|
+
function providerOf(ctx: { path?: string; params?: Record<string, unknown> } | null | undefined): string | null {
|
|
86
|
+
if (!ctx?.path?.startsWith('/callback/')) return null
|
|
87
|
+
const id = ctx.params?.id
|
|
88
|
+
return typeof id === 'string' ? id : null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function createAuth({ db, t, dialect }: Database, providers: GenericOAuthConfig[]) {
|
|
92
|
+
const baseURL = SITE_URL
|
|
93
|
+
return betterAuth({
|
|
94
|
+
appName: 'Pet Adopt',
|
|
95
|
+
baseURL,
|
|
96
|
+
secret: resolveSecret(),
|
|
97
|
+
trustedOrigins: production ? [baseURL] : [baseURL, 'http://localhost:3000', 'http://localhost:3001', 'http://127.0.0.1:3000'],
|
|
98
|
+
database: drizzleAdapter(db, { provider: dialect, schema: t, usePlural: true }),
|
|
99
|
+
emailAndPassword: {
|
|
100
|
+
enabled: true,
|
|
101
|
+
disableSignUp: true,
|
|
102
|
+
minPasswordLength: MIN_PASSWORD_LENGTH,
|
|
103
|
+
maxPasswordLength: 128,
|
|
104
|
+
},
|
|
105
|
+
session: {
|
|
106
|
+
expiresIn: 60 * 60 * 2,
|
|
107
|
+
updateAge: 60 * 10,
|
|
108
|
+
// 'password' or 'provider:<id>': a provider sign-in counts as two-factor (two-factor.ts).
|
|
109
|
+
additionalFields: { signInMethod: { type: 'string', required: false, input: false } },
|
|
110
|
+
},
|
|
111
|
+
account: {
|
|
112
|
+
// Provider tokens are not used by the site; stored encrypted all the same.
|
|
113
|
+
encryptOAuthTokens: true,
|
|
114
|
+
accountLinking: {
|
|
115
|
+
enabled: true,
|
|
116
|
+
// Linking happens only when a signed-in person connects a provider (Account page), never by
|
|
117
|
+
// a matching email at sign-in. Their provider email may differ from their email here.
|
|
118
|
+
disableImplicitLinking: true,
|
|
119
|
+
allowDifferentEmails: true,
|
|
120
|
+
// Explicit links need no email check from the provider: the person is signed in here.
|
|
121
|
+
trustedProviders: providers.map((provider) => provider.providerId),
|
|
122
|
+
updateUserInfoOnLink: false,
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
// Errors from a provider's callback land on the sign-in page (?error=<code>).
|
|
126
|
+
onAPIError: { errorURL: '/admin/login' },
|
|
127
|
+
// Our own columns on users, so Better Auth reads them into the session user. `input: false`: no
|
|
128
|
+
// Better Auth endpoint may set them; users.ts does.
|
|
129
|
+
user: {
|
|
130
|
+
additionalFields: {
|
|
131
|
+
role: { type: 'string', required: false, input: false },
|
|
132
|
+
archivedAt: { type: 'date', required: false, input: false },
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
databaseHooks: {
|
|
136
|
+
session: {
|
|
137
|
+
create: {
|
|
138
|
+
// Every new session, whatever the way in (password, two-factor code), checks the account
|
|
139
|
+
// is not archived. Runs after the password was checked, so it tells nothing to a guesser.
|
|
140
|
+
async before(session, ctx) {
|
|
141
|
+
const [user] = await db.select({ archivedAt: t.users.archivedAt }).from(t.users).where(eq(t.users.id, session.userId)).limit(1)
|
|
142
|
+
if (user?.archivedAt) throw new APIError('FORBIDDEN', { message: 'This account is archived.', code: ACCOUNT_ARCHIVED })
|
|
143
|
+
const provider = providerOf(ctx)
|
|
144
|
+
// A session that replaces another (password change, two-factor on or off) keeps how the
|
|
145
|
+
// person signed in: from the copied fields (two-factor) or the request's own session
|
|
146
|
+
// (a password change makes a fresh one).
|
|
147
|
+
const current = (ctx as { context?: { session?: { session?: { signInMethod?: unknown } } } } | null)?.context?.session?.session
|
|
148
|
+
const kept = (session as { signInMethod?: unknown }).signInMethod ?? current?.signInMethod
|
|
149
|
+
const signInMethod = provider ? `provider:${provider}` : typeof kept === 'string' && kept ? kept : 'password'
|
|
150
|
+
return { data: { ...session, signInMethod } }
|
|
151
|
+
},
|
|
152
|
+
// A provider sign-in happens in the callback route, not a server action: log it here.
|
|
153
|
+
async after(session, ctx) {
|
|
154
|
+
const provider = providerOf(ctx)
|
|
155
|
+
if (!provider) return
|
|
156
|
+
const { recordProviderActivity } = await import('./activity')
|
|
157
|
+
await recordProviderActivity(session.userId, 'auth.sign-in', provider, (name) => `Signed in with ${name}`)
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
account: {
|
|
162
|
+
create: {
|
|
163
|
+
// Connecting a provider (Account page) finishes in the callback route: log it here.
|
|
164
|
+
async after(account) {
|
|
165
|
+
if (account.providerId === 'credential') return
|
|
166
|
+
const { recordProviderActivity } = await import('./activity')
|
|
167
|
+
await recordProviderActivity(account.userId, 'account.provider-connect', account.providerId, (name) => `Connected ${name} for signing in`)
|
|
168
|
+
// No profile picture yet: use the provider's (from its ID token, verified by Better Auth).
|
|
169
|
+
const { adoptProviderPicture, pictureFromIdToken } = await import('./avatars')
|
|
170
|
+
await adoptProviderPicture(account.userId, pictureFromIdToken(account.idToken))
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
advanced: {
|
|
176
|
+
cookiePrefix: 'pet-adopt',
|
|
177
|
+
useSecureCookies: production,
|
|
178
|
+
// Better Auth's own address-based limiter must read the same header as our throttle.
|
|
179
|
+
ipAddress: { ipAddressHeaders: [CLIENT_IP_HEADER], ipv6Subnet: 64 },
|
|
180
|
+
},
|
|
181
|
+
rateLimit: {
|
|
182
|
+
enabled: true,
|
|
183
|
+
storage: 'database',
|
|
184
|
+
window: 60,
|
|
185
|
+
max: 100,
|
|
186
|
+
// Sign-in is limited by src/server/throttle.ts (per email and per client, atomic). Better Auth's
|
|
187
|
+
// own rule keys on one address and would share a single bucket across every owner whenever it
|
|
188
|
+
// cannot read the proxy header, locking everyone out after a few sign-ins.
|
|
189
|
+
// Likewise "change password", which Better Auth would otherwise cap at 3 per 10 seconds per
|
|
190
|
+
// address; it is limited per user by guardPasswordChange (route and action).
|
|
191
|
+
customRules: { '/sign-in/email': false, '/change-password': false },
|
|
192
|
+
},
|
|
193
|
+
plugins: [
|
|
194
|
+
// Sign-in providers; an empty list registers none (the plugin's endpoints then do nothing).
|
|
195
|
+
genericOAuth({ config: providers }),
|
|
196
|
+
twoFactor({
|
|
197
|
+
// Shown in authenticator apps; each setup passes the site's name instead (actions/two-factor.ts).
|
|
198
|
+
issuer: 'Pet Adopt',
|
|
199
|
+
// The code step after the password: 10 minutes to enter it, and "Trust this device" lasts 30 days.
|
|
200
|
+
twoFactorCookieMaxAge: 600,
|
|
201
|
+
trustDeviceMaxAge: TRUST_DEVICE_DAYS * 24 * 60 * 60,
|
|
202
|
+
// Ten one-time backup codes, stored encrypted (Better Auth's default, stated here on purpose).
|
|
203
|
+
// Ours are lower case without look-alikes (BACKUP_CODE_ALPHABET), so they survive paper.
|
|
204
|
+
backupCodeOptions: { storeBackupCodes: 'encrypted', customBackupCodesGenerate: () => generateBackupCodes() },
|
|
205
|
+
// 10 wrong codes in a row lock the code step for 15 minutes, across sign-in attempts.
|
|
206
|
+
accountLockout: { enabled: true, maxFailedAttempts: 10, durationSeconds: 15 * 60 },
|
|
207
|
+
}),
|
|
208
|
+
// Last: it copies the cookies the other plugins set into Next's response.
|
|
209
|
+
nextCookies(),
|
|
210
|
+
],
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export type Auth = ReturnType<typeof createAuth>
|
|
215
|
+
|
|
216
|
+
// checkedAt is performance.now(), not Date.now(): getAuth() runs inside page renders, where Next
|
|
217
|
+
// (Cache Components) treats a wall-clock read as a value that changes per request and reports it.
|
|
218
|
+
// A monotonic timer is fine there, and the recheck only needs elapsed time.
|
|
219
|
+
type Holder = { promise?: Promise<Auth>; version?: string; checkedAt?: number }
|
|
220
|
+
const holder = ((globalThis as { __petAdoptAuth?: Holder }).__petAdoptAuth ??= {})
|
|
221
|
+
|
|
222
|
+
async function build(): Promise<Auth> {
|
|
223
|
+
const database = await getDatabase()
|
|
224
|
+
// Imported here: auth-providers.ts reads SITE_URL from this file.
|
|
225
|
+
const { providerConfigs, providersVersion } = await import('./auth-providers')
|
|
226
|
+
const [configs, version] = await Promise.all([providerConfigs(), providersVersion()])
|
|
227
|
+
holder.version = version
|
|
228
|
+
holder.checkedAt = performance.now()
|
|
229
|
+
// Everything Better Auth does runs with its requests held to public addresses (provider-guard.ts):
|
|
230
|
+
// building it reads the providers' discovery documents, and its handler and API calls exchange
|
|
231
|
+
// codes and read user info and signing keys at addresses an admin typed in.
|
|
232
|
+
const { guarded, guardedFunctions } = await import('./provider-guard')
|
|
233
|
+
const auth = guarded(() => createAuth(database, configs as GenericOAuthConfig[]))
|
|
234
|
+
const handler = auth.handler
|
|
235
|
+
return Object.assign(auth, { handler: (request: Request) => guarded(() => handler(request)), api: guardedFunctions(auth.api) })
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Better Auth for this server. Rebuilt when the sign-in providers change: at once on the server
|
|
240
|
+
* that saved them (forgetAuth), within PROVIDER_RECHECK_MS on the others.
|
|
241
|
+
*/
|
|
242
|
+
export async function getAuth(): Promise<Auth> {
|
|
243
|
+
const now = performance.now()
|
|
244
|
+
// Negative only when checkedAt came from another clock (a dev reload of older code): check then too.
|
|
245
|
+
const sinceCheck = now - (holder.checkedAt ?? Number.NEGATIVE_INFINITY)
|
|
246
|
+
if (holder.promise && (sinceCheck > PROVIDER_RECHECK_MS || sinceCheck < 0)) {
|
|
247
|
+
holder.checkedAt = now
|
|
248
|
+
try {
|
|
249
|
+
const { providersVersion } = await import('./auth-providers')
|
|
250
|
+
if ((await providersVersion()) !== holder.version) holder.promise = undefined
|
|
251
|
+
} catch (error) {
|
|
252
|
+
// Keep the current instance; the next check tries again (checkedAt above limits the log too).
|
|
253
|
+
logError(error, 'could not check whether the sign-in providers changed')
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
holder.promise ??= build()
|
|
257
|
+
holder.promise.catch(() => {
|
|
258
|
+
holder.promise = undefined
|
|
259
|
+
})
|
|
260
|
+
return holder.promise
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Drops this server's Better Auth so the next getAuth() is built from the current providers. */
|
|
264
|
+
export function forgetAuth(): void {
|
|
265
|
+
holder.promise = undefined
|
|
266
|
+
}
|