From 53450206f58a29a0f91f771ded1a8c2a42310c58 Mon Sep 17 00:00:00 2001 From: Konsti Wohlwend Date: Mon, 1 Jul 2024 22:42:08 -0700 Subject: [PATCH] Create users & auth endpoints in backend (#85) --- .gitignore | 2 + README.md | 5 +- apps/backend/next.config.mjs | 4 +- apps/backend/package.json | 25 +- .../migration.sql | 22 + apps/backend/prisma/schema.prisma | 28 + apps/backend/prisma/seed.ts | 1 + apps/backend/sentry.client.config.ts | 2 +- apps/backend/sentry.edge.config.ts | 2 +- apps/backend/sentry.server.config.ts | 2 +- .../oauth/access-token/[provider]/route.tsx | 3 + .../auth/oauth/authorize/[provider]/route.tsx | 3 + .../auth/oauth/callback/[provider]/route.tsx | 3 + .../src/app/api/v1/auth/oauth/token/route.tsx | 3 + .../v1/auth/otp/send-sign-in-code/route.tsx | 88 +++ .../src/app/api/v1/auth/otp/sign-in/route.tsx | 3 + .../otp/sign-in/verification-code-handler.tsx | 47 ++ .../app/api/v1/auth/password/reset/route.tsx | 3 + .../auth/password/send-reset-code/route.tsx | 3 + .../api/v1/auth/password/sign-in/route.tsx | 3 + .../api/v1/auth/password/sign-up/route.tsx | 3 + .../app/api/v1/auth/password/update/route.tsx | 3 + .../src/app/api/v1/auth/sign-out/route.tsx | 3 + apps/backend/src/app/api/v1/route.ts | 11 +- .../src/app/api/v1/users/[userId]/route.tsx | 5 + .../send-email-verification-code/route.tsx | 3 + .../v1/users/[userId]/verify-email/route.tsx | 3 + apps/backend/src/app/api/v1/users/crud.tsx | 119 ++++ .../backend/src/app/api/v1/users/me/route.tsx | 5 + apps/backend/src/app/api/v1/users/route.tsx | 4 + apps/backend/src/app/page.tsx | 4 + apps/backend/src/lib/email-templates.tsx | 140 ++++ apps/backend/src/lib/emails.tsx | 222 ++++++ apps/backend/src/lib/openapi.tsx | 39 +- apps/backend/src/lib/projects.tsx | 27 +- apps/backend/src/lib/redirect-urls.tsx | 7 +- apps/backend/src/lib/teams.tsx | 27 +- apps/backend/src/lib/users.tsx | 206 ------ apps/backend/src/middleware.tsx | 3 +- .../src/route-handlers/crud-handler.tsx | 178 +++-- .../src/route-handlers/prisma-handler.tsx | 94 ++- .../src/route-handlers/smart-request.tsx | 132 ++-- .../src/route-handlers/smart-response.tsx | 82 ++- .../route-handlers/smart-route-handler.tsx | 115 ++- .../verification-code-handler.tsx | 125 ++++ apps/dashboard/package.json | 22 +- apps/dashboard/prisma/schema.prisma | 28 + .../[projectId]/domains/page-client.tsx | 3 +- .../[projectId]/emails/page-client.tsx | 10 +- .../emails/templates/[type]/page-client.tsx | 16 +- .../projects/[projectId]/sidebar-layout.tsx | 2 +- .../api/v1/auth/email-verification/route.tsx | 6 +- .../app/api/v1/auth/forgot-password/route.tsx | 2 +- .../v1/auth/magic-link-verification/route.tsx | 6 +- .../app/api/v1/auth/password-reset/route.tsx | 6 +- .../app/api/v1/auth/send-magic-link/route.tsx | 2 +- .../v1/auth/send-verification-email/route.tsx | 2 +- .../src/app/api/v1/auth/signup/route.tsx | 2 +- .../src/app/api/v1/current-user/crud.tsx | 3 + .../api/v1/email-templates/[type]/route.tsx | 2 +- apps/dashboard/src/globals.d.ts | 5 - apps/dashboard/src/lib/email-templates.tsx | 4 +- .../src/{email/index.tsx => lib/emails.tsx} | 2 +- apps/dashboard/src/lib/openapi.tsx | 273 -------- .../src/route-handlers/crud-handler.tsx | 13 +- .../src/route-handlers/prisma-handler.tsx | 8 +- .../src/route-handlers/smart-request.tsx | 2 +- .../src/route-handlers/smart-response.tsx | 3 +- .../route-handlers/smart-route-handler.tsx | 9 +- apps/dashboard/src/stack.tsx | 2 +- apps/e2e/.env | 3 + apps/e2e/.env.development | 3 + apps/e2e/.eslintrc.cjs | 14 + apps/e2e/LICENSE | 662 +++++++++++++++++- apps/e2e/tests/backend/backend-helpers.ts | 180 ++++- .../api/v1/auth/otp/send-sign-in-code.test.ts | 45 ++ .../endpoints/api/v1/auth/otp/sign-in.test.ts | 41 ++ .../backend/endpoints/api/v1/index.test.ts | 133 +++- .../backend/endpoints/api/v1/users.test.ts | 411 +++++++++++ .../tests/dashboard/internal-project.test.ts | 4 +- apps/e2e/tests/global-setup.ts | 3 +- apps/e2e/tests/helpers.ts | 157 ++++- apps/e2e/tests/snapshot-serializer.ts | 78 ++- .../docs/pages/getting-started/overview.mdx | 2 +- .../fern/docs/pages/getting-started/setup.mdx | 2 +- .../fern/docs/pages/getting-started/users.mdx | 25 +- eslint-configs/defaults.js | 5 + examples/cjs-test/package.json | 4 +- package.json | 3 +- packages/init-stack/package-lock.json | 175 ----- packages/stack-emails/.eslintrc.cjs | 6 + .../stack-emails}/LICENSE | 0 packages/stack-emails/package.json | 96 +++ .../src/components/action-dialog.tsx | 122 ++++ .../src/components/browser-frame/LICENSE | 3 + .../src/components/browser-frame/index.tsx | 33 + .../src/components/copy-button.tsx | 38 + .../src/components/dev-error-notifier.tsx | 44 ++ .../stack-emails/src/components/env-keys.tsx | 90 +++ packages/stack-emails/src/components/link.tsx | 46 ++ .../stack-emails/src/components/router.tsx | 45 ++ .../stack-emails/src/components/settings.tsx | 186 +++++ .../src/components/simple-tooltip.tsx | 31 + .../src/components/smart-image.tsx | 32 + .../src/components/ui/accordion.tsx | 57 ++ .../src/components/ui/alert-dialog.tsx | 141 ++++ .../stack-emails/src/components/ui/alert.tsx | 59 ++ .../src/components/ui/aspect-ratio.tsx | 7 + .../stack-emails/src/components/ui/avatar.tsx | 50 ++ .../stack-emails/src/components/ui/badge.tsx | 37 + .../src/components/ui/breadcrumb.tsx | 115 +++ .../stack-emails/src/components/ui/button.tsx | 88 +++ .../stack-emails/src/components/ui/card.tsx | 91 +++ .../src/components/ui/checkbox.tsx | 30 + .../src/components/ui/collapsible.tsx | 11 + .../src/components/ui/context-menu.tsx | 204 ++++++ .../stack-emails/src/components/ui/dialog.tsx | 130 ++++ .../src/components/ui/dropdown-menu.tsx | 205 ++++++ .../stack-emails/src/components/ui/form.tsx | 174 +++++ .../src/components/ui/hover-card.tsx | 29 + .../src/components/ui/inline-code.tsx | 39 ++ .../stack-emails/src/components/ui/input.tsx | 51 ++ .../stack-emails/src/components/ui/label.tsx | 39 ++ .../src/components/ui/menubar.tsx | 240 +++++++ .../src/components/ui/navigation-menu.tsx | 128 ++++ .../src/components/ui/popover.tsx | 33 + .../src/components/ui/progress.tsx | 28 + .../src/components/ui/radio-group.tsx | 44 ++ .../src/components/ui/scroll-area.tsx | 48 ++ .../stack-emails/src/components/ui/select.tsx | 164 +++++ .../src/components/ui/separator.tsx | 31 + .../stack-emails/src/components/ui/sheet.tsx | 140 ++++ .../src/components/ui/skeleton.tsx | 15 + .../stack-emails/src/components/ui/slider.tsx | 28 + .../src/components/ui/spinner.tsx | 14 + .../stack-emails/src/components/ui/switch.tsx | 74 ++ .../stack-emails/src/components/ui/table.tsx | 121 ++++ .../stack-emails/src/components/ui/tabs.tsx | 55 ++ .../src/components/ui/textarea.tsx | 24 + .../stack-emails/src/components/ui/toast.tsx | 129 ++++ .../src/components/ui/toaster.tsx | 35 + .../src/components/ui/toggle-group.tsx | 61 ++ .../stack-emails/src/components/ui/toggle.tsx | 45 ++ .../src/components/ui/tooltip.tsx | 39 ++ .../src/components/ui/typography.tsx | 46 ++ .../src/components/ui/use-toast.ts | 195 ++++++ .../src/editor}/blocks/block-button.tsx | 0 .../blocks/block-columns-container.tsx | 0 .../src/editor}/blocks/block-container.tsx | 0 .../src/editor}/blocks/block-divider.tsx | 0 .../src/editor}/blocks/block-heading.tsx | 0 .../src/editor}/blocks/block-image.tsx | 0 .../src/editor}/blocks/block-spacer.tsx | 0 .../src/editor}/blocks/block-text.tsx | 0 .../builders/buildBlockComponent.tsx | 0 .../buildBlockConfigurationDictionary.ts | 0 .../builders/buildBlockConfigurationSchema.ts | 0 .../src/editor}/document-core/index.ts | 0 .../columns-container-editor.tsx | 0 .../columns-container-props-schema.ts | 0 .../blocks/container/container-editor.tsx | 0 .../container/container-props-schema.tsx | 0 .../email-layout/email-layout-editor.tsx | 0 .../email-layout-props-schema.tsx | 0 .../block-wrappers/editor-block-wrapper.tsx | 0 .../block-wrappers/reader-block-wrapper.tsx | 0 .../helpers/block-wrappers/tune-menu.tsx | 0 .../add-block-menu/block-button.tsx | 2 +- .../add-block-menu/blocks-menu.tsx | 2 +- .../add-block-menu/buttons.tsx | 0 .../add-block-menu/index.tsx | 0 .../helpers/editor-children-ids/index.tsx | 0 .../documents/blocks/helpers/font-family.ts | 0 .../documents/blocks/helpers/t-style.ts | 0 .../editor}/documents/blocks/helpers/zod.ts | 0 .../src/editor}/documents/editor/core.tsx | 1 - .../editor}/documents/editor/editor-block.tsx | 2 +- .../documents/editor/editor-context.tsx | 4 +- .../stack-emails/src/editor}/editor.tsx | 24 +- .../columns-container-props-schema.ts | 0 .../columns-container-reader.tsx | 2 +- .../container/container-props-schema.tsx | 0 .../blocks/container/container-reader.tsx | 2 +- .../email-layout-props-schema.tsx | 0 .../email-layout/email-layout-reader.tsx | 2 +- .../src/editor}/email-builder/index.ts | 0 .../src/editor}/email-builder/reader/core.tsx | 0 .../sidebar/configuration-panel/index.tsx | 2 +- .../input-panels/button-sidebar-panel.tsx | 0 .../columns-container-sidebar-panel.tsx | 0 .../input-panels/container-sidebar-panel.tsx | 0 .../input-panels/divider-sidebar-panel.tsx | 0 .../input-panels/heading-sidebar-panel.tsx | 0 .../helpers/base-sidebar-panel.tsx | 4 +- .../inputs/color-input/base-color-input.tsx | 2 +- .../helpers/inputs/color-input/index.tsx | 0 .../helpers/inputs/column-widths-input.tsx | 0 .../helpers/inputs/font-family.tsx | 4 +- .../helpers/inputs/font-size-input.tsx | 2 +- .../helpers/inputs/font-weight-input.tsx | 0 .../helpers/inputs/padding-input.tsx | 2 +- .../helpers/inputs/raw/raw-slider-input.tsx | 4 +- .../helpers/inputs/single-toggle-group.tsx | 6 +- .../helpers/inputs/slider-input.tsx | 2 +- .../helpers/inputs/text-align-input.tsx | 0 .../helpers/inputs/text-dimension-input.tsx | 2 +- .../helpers/inputs/text-input.tsx | 6 +- .../multi-style-property-panel.tsx | 0 .../single-style-property-panel.tsx | 0 .../input-panels/image-sidebar-panel.tsx | 0 .../input-panels/spacer-sidebar-panel.tsx | 0 .../input-panels/text-sidebar-panel.tsx | 0 .../src/editor}/sidebar/index.tsx | 6 +- .../src/editor}/sidebar/settings-panel.tsx | 2 +- .../sidebar/toggle-inspector-panel-button.tsx | 2 +- .../src/editor}/sidebar/variables-panel.tsx | 8 +- .../template-panel/download-json/index.tsx | 2 +- .../import-json/import-json-dialog.tsx | 8 +- .../template-panel/import-json/index.tsx | 2 +- .../import-json/validateJsonStringValue.ts | 0 .../src/editor}/template-panel/index.tsx | 4 +- packages/stack-emails/src/globals.d.ts | 4 + .../src}/templates/email-verification.tsx | 4 +- .../stack-emails/src}/templates/empty.tsx | 2 +- .../src}/templates/magic-link.tsx | 4 +- .../src}/templates/password-reset.tsx | 4 +- .../stack-emails/src}/utils.tsx | 17 +- packages/stack-emails/tsconfig.json | 17 + packages/stack-shared/src/crud.tsx | 75 +- .../src/interface/clientInterface.ts | 16 +- .../src/interface/crud/current-user.ts | 54 +- .../src/interface/crud/email-templates.ts | 2 +- .../stack-shared/src/interface/crud/fields.ts | 13 - .../stack-shared/src/interface/crud/oauth.ts | 4 +- .../stack-shared/src/interface/crud/users.ts | 81 ++- packages/stack-shared/src/known-errors.tsx | 328 +++++---- packages/stack-shared/src/schema-fields.ts | 70 ++ packages/stack-shared/src/utils/errors.tsx | 2 +- packages/stack-shared/src/utils/objects.tsx | 29 +- packages/stack-shared/src/utils/strings.tsx | 47 +- packages/stack/package.json | 2 +- .../components-page/email-verification.tsx | 6 +- .../components-page/magic-link-callback.tsx | 6 +- .../src/components-page/password-reset.tsx | 6 +- packages/stack/src/lib/stack-app.ts | 16 +- pnpm-lock.yaml | 235 ++++++- turbo.json | 7 - vitest.workspace.ts | 6 + 248 files changed, 8006 insertions(+), 1423 deletions(-) create mode 100644 apps/backend/prisma/migrations/20240702050143_verification_codes/migration.sql create mode 100644 apps/backend/src/app/api/v1/auth/oauth/access-token/[provider]/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/oauth/authorize/[provider]/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/oauth/callback/[provider]/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/oauth/token/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/otp/send-sign-in-code/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/otp/sign-in/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/otp/sign-in/verification-code-handler.tsx create mode 100644 apps/backend/src/app/api/v1/auth/password/reset/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/password/send-reset-code/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/password/sign-in/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/password/sign-up/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/password/update/route.tsx create mode 100644 apps/backend/src/app/api/v1/auth/sign-out/route.tsx create mode 100644 apps/backend/src/app/api/v1/users/[userId]/route.tsx create mode 100644 apps/backend/src/app/api/v1/users/[userId]/send-email-verification-code/route.tsx create mode 100644 apps/backend/src/app/api/v1/users/[userId]/verify-email/route.tsx create mode 100644 apps/backend/src/app/api/v1/users/crud.tsx create mode 100644 apps/backend/src/app/api/v1/users/me/route.tsx create mode 100644 apps/backend/src/app/api/v1/users/route.tsx create mode 100644 apps/backend/src/lib/email-templates.tsx create mode 100644 apps/backend/src/lib/emails.tsx delete mode 100644 apps/backend/src/lib/users.tsx create mode 100644 apps/backend/src/route-handlers/verification-code-handler.tsx rename apps/dashboard/src/{email/index.tsx => lib/emails.tsx} (98%) delete mode 100644 apps/dashboard/src/lib/openapi.tsx create mode 100644 apps/e2e/tests/backend/endpoints/api/v1/auth/otp/send-sign-in-code.test.ts create mode 100644 apps/e2e/tests/backend/endpoints/api/v1/auth/otp/sign-in.test.ts create mode 100644 apps/e2e/tests/backend/endpoints/api/v1/users.test.ts delete mode 100644 packages/init-stack/package-lock.json create mode 100644 packages/stack-emails/.eslintrc.cjs rename {apps/dashboard/src/components/email-editor => packages/stack-emails}/LICENSE (100%) create mode 100644 packages/stack-emails/package.json create mode 100644 packages/stack-emails/src/components/action-dialog.tsx create mode 100644 packages/stack-emails/src/components/browser-frame/LICENSE create mode 100644 packages/stack-emails/src/components/browser-frame/index.tsx create mode 100644 packages/stack-emails/src/components/copy-button.tsx create mode 100644 packages/stack-emails/src/components/dev-error-notifier.tsx create mode 100644 packages/stack-emails/src/components/env-keys.tsx create mode 100644 packages/stack-emails/src/components/link.tsx create mode 100644 packages/stack-emails/src/components/router.tsx create mode 100644 packages/stack-emails/src/components/settings.tsx create mode 100644 packages/stack-emails/src/components/simple-tooltip.tsx create mode 100644 packages/stack-emails/src/components/smart-image.tsx create mode 100644 packages/stack-emails/src/components/ui/accordion.tsx create mode 100644 packages/stack-emails/src/components/ui/alert-dialog.tsx create mode 100644 packages/stack-emails/src/components/ui/alert.tsx create mode 100644 packages/stack-emails/src/components/ui/aspect-ratio.tsx create mode 100644 packages/stack-emails/src/components/ui/avatar.tsx create mode 100644 packages/stack-emails/src/components/ui/badge.tsx create mode 100644 packages/stack-emails/src/components/ui/breadcrumb.tsx create mode 100644 packages/stack-emails/src/components/ui/button.tsx create mode 100644 packages/stack-emails/src/components/ui/card.tsx create mode 100644 packages/stack-emails/src/components/ui/checkbox.tsx create mode 100644 packages/stack-emails/src/components/ui/collapsible.tsx create mode 100644 packages/stack-emails/src/components/ui/context-menu.tsx create mode 100644 packages/stack-emails/src/components/ui/dialog.tsx create mode 100644 packages/stack-emails/src/components/ui/dropdown-menu.tsx create mode 100644 packages/stack-emails/src/components/ui/form.tsx create mode 100644 packages/stack-emails/src/components/ui/hover-card.tsx create mode 100644 packages/stack-emails/src/components/ui/inline-code.tsx create mode 100644 packages/stack-emails/src/components/ui/input.tsx create mode 100644 packages/stack-emails/src/components/ui/label.tsx create mode 100644 packages/stack-emails/src/components/ui/menubar.tsx create mode 100644 packages/stack-emails/src/components/ui/navigation-menu.tsx create mode 100644 packages/stack-emails/src/components/ui/popover.tsx create mode 100644 packages/stack-emails/src/components/ui/progress.tsx create mode 100644 packages/stack-emails/src/components/ui/radio-group.tsx create mode 100644 packages/stack-emails/src/components/ui/scroll-area.tsx create mode 100644 packages/stack-emails/src/components/ui/select.tsx create mode 100644 packages/stack-emails/src/components/ui/separator.tsx create mode 100644 packages/stack-emails/src/components/ui/sheet.tsx create mode 100644 packages/stack-emails/src/components/ui/skeleton.tsx create mode 100644 packages/stack-emails/src/components/ui/slider.tsx create mode 100644 packages/stack-emails/src/components/ui/spinner.tsx create mode 100644 packages/stack-emails/src/components/ui/switch.tsx create mode 100644 packages/stack-emails/src/components/ui/table.tsx create mode 100644 packages/stack-emails/src/components/ui/tabs.tsx create mode 100644 packages/stack-emails/src/components/ui/textarea.tsx create mode 100644 packages/stack-emails/src/components/ui/toast.tsx create mode 100644 packages/stack-emails/src/components/ui/toaster.tsx create mode 100644 packages/stack-emails/src/components/ui/toggle-group.tsx create mode 100644 packages/stack-emails/src/components/ui/toggle.tsx create mode 100644 packages/stack-emails/src/components/ui/tooltip.tsx create mode 100644 packages/stack-emails/src/components/ui/typography.tsx create mode 100644 packages/stack-emails/src/components/ui/use-toast.ts rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-button.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-columns-container.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-container.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-divider.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-heading.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-image.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-spacer.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/blocks/block-text.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/document-core/builders/buildBlockComponent.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/document-core/builders/buildBlockConfigurationDictionary.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/document-core/builders/buildBlockConfigurationSchema.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/document-core/index.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/columns-container/columns-container-editor.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/columns-container/columns-container-props-schema.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/container/container-editor.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/container/container-props-schema.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/email-layout/email-layout-editor.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/email-layout/email-layout-props-schema.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/block-wrappers/editor-block-wrapper.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/block-wrappers/reader-block-wrapper.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/block-wrappers/tune-menu.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/editor-children-ids/add-block-menu/block-button.tsx (88%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/editor-children-ids/add-block-menu/blocks-menu.tsx (88%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/editor-children-ids/add-block-menu/buttons.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/editor-children-ids/add-block-menu/index.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/editor-children-ids/index.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/font-family.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/t-style.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/blocks/helpers/zod.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/editor/core.tsx (98%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/editor/editor-block.tsx (92%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/documents/editor/editor-context.tsx (95%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/editor.tsx (73%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/blocks/columns-container/columns-container-props-schema.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/blocks/columns-container/columns-container-reader.tsx (87%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/blocks/container/container-props-schema.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/blocks/container/container-reader.tsx (85%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/blocks/email-layout/email-layout-props-schema.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/blocks/email-layout/email-layout-reader.tsx (96%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/index.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/email-builder/reader/core.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/index.tsx (97%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/button-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/columns-container-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/container-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/divider-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/heading-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/base-sidebar-panel.tsx (81%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/color-input/base-color-input.tsx (97%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/color-input/index.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/column-widths-input.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/font-family.tsx (91%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/font-size-input.tsx (92%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/font-weight-input.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/padding-input.tsx (96%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/raw/raw-slider-input.tsx (81%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/single-toggle-group.tsx (81%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/slider-input.tsx (91%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/text-align-input.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/text-dimension-input.tsx (94%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/inputs/text-input.tsx (85%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/style-inputs/multi-style-property-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/helpers/style-inputs/single-style-property-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/image-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/spacer-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/configuration-panel/input-panels/text-sidebar-panel.tsx (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/index.tsx (93%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/settings-panel.tsx (98%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/toggle-inspector-panel-button.tsx (92%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/sidebar/variables-panel.tsx (80%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/template-panel/download-json/index.tsx (93%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/template-panel/import-json/import-json-dialog.tsx (86%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/template-panel/import-json/index.tsx (90%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/template-panel/import-json/validateJsonStringValue.ts (100%) rename {apps/dashboard/src/components/email-editor => packages/stack-emails/src/editor}/template-panel/index.tsx (94%) create mode 100644 packages/stack-emails/src/globals.d.ts rename {apps/dashboard/src/email => packages/stack-emails/src}/templates/email-verification.tsx (96%) rename {apps/dashboard/src/email => packages/stack-emails/src}/templates/empty.tsx (72%) rename {apps/dashboard/src/email => packages/stack-emails/src}/templates/magic-link.tsx (96%) rename {apps/dashboard/src/email => packages/stack-emails/src}/templates/password-reset.tsx (96%) rename {apps/dashboard/src/email => packages/stack-emails/src}/utils.tsx (92%) create mode 100644 packages/stack-emails/tsconfig.json delete mode 100644 packages/stack-shared/src/interface/crud/fields.ts create mode 100644 packages/stack-shared/src/schema-fields.ts create mode 100644 vitest.workspace.ts diff --git a/.gitignore b/.gitignore index 2ed860ef6..e649ed1c6 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,8 @@ ui-debug.log .husky tmp +vitest.config.ts.timestamp-* + # Dependencies node_modules diff --git a/README.md b/README.md index 2871e1252..7e07f5a49 100644 --- a/README.md +++ b/README.md @@ -108,9 +108,12 @@ pnpm run codegen # Start the dev server pnpm run dev + +# In a different terminal, run tests in watch mode +pnpm run test ``` -You can now open the dashboard at [http://localhost:8101](http://localhost:8101), API on port 8102, demo on port 8103, and docs on port 8104. You can also run the tests with `pnpm run test:watch`. +You can now open the dashboard at [http://localhost:8101](http://localhost:8101), API on port 8102, demo on port 8103, docs on port 8104, Inbucket (e-mails) on port 8105, and Prisma Studio on port 8106. Your IDE may show an error on all `@stackframe/XYZ` imports. To fix this, simply restart the TypeScript language server; for example, in VSCode you can open the command palette (Ctrl+Shift+P) and run `Developer: Reload Window` or `TypeScript: Restart TS server`. diff --git a/apps/backend/next.config.mjs b/apps/backend/next.config.mjs index 633c3f23d..e18fe3773 100644 --- a/apps/backend/next.config.mjs +++ b/apps/backend/next.config.mjs @@ -14,8 +14,8 @@ const withConfiguredSentryConfig = (nextConfig) => // Suppresses source map uploading logs during build silent: true, - org: "stackframe-pw", - project: "stack-api", + org: process.env.SENTRY_ORG, + project: process.env.SENTRY_PROJECT, }, { // For all available options, see: diff --git a/apps/backend/package.json b/apps/backend/package.json index 64937cb6b..ffbcc0875 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -7,23 +7,23 @@ "typecheck": "tsc --noEmit", "with-env": "dotenv -c development --", "with-env:prod": "dotenv -c --", - "dev": "concurrently \"next dev --port 8102\" \"npm run watch-docs\"", - "build": "npm run codegen && next build", - "analyze-bundle": "ANALYZE_BUNDLE=1 npm run build", + "dev": "concurrently \"next dev --port 8102\" \"pnpm run watch-docs\" \"pnpm run prisma-studio\"", + "build": "pnpm run codegen && next build", + "analyze-bundle": "ANALYZE_BUNDLE=1 pnpm run build", "start": "next start --port 8102", - "codegen": "npm run prisma -- generate && npm run generate-docs", - "psql": "npm run with-env -- bash -c 'psql $STACK_DATABASE_CONNECTION_STRING'", - "prisma": "npm run with-env -- prisma", + "codegen": "pnpm run prisma generate && pnpm run generate-docs", + "psql": "pnpm run with-env bash -c 'psql $STACK_DATABASE_CONNECTION_STRING'", + "prisma": "pnpm run with-env prisma", + "prisma-studio": "pnpm run with-env prisma studio --port 8106 --browser none", "lint": "next lint", - "watch-docs": "npm run with-env -- chokidar --silent '../../**/*' -i '../../docs/**' -i '../../**/node_modules/**' -i '../../**/.next/**' -i '../../**/dist/**' -c 'tsx scripts/generate-docs.ts'", - "generate-docs": "npm run with-env -- tsx scripts/generate-docs.ts", - "generate-keys": "npm run with-env -- tsx scripts/generate-keys.ts" + "watch-docs": "pnpm run with-env chokidar --silent '../../**/*' -i '../../docs/**' -i '../../**/node_modules/**' -i '../../**/.next/**' -i '../../**/dist/**' -c 'tsx scripts/generate-docs.ts'", + "generate-docs": "pnpm run with-env tsx scripts/generate-docs.ts", + "generate-keys": "pnpm run with-env tsx scripts/generate-keys.ts" }, "prisma": { - "seed": "npm run with-env -- tsx prisma/seed.ts" + "seed": "pnpm run with-env tsx prisma/seed.ts" }, "dependencies": { - "@hookform/resolvers": "^3.3.4", "@next/bundle-analyzer": "^14.0.3", "@node-oauth/oauth2-server": "^5.1.0", "@prisma/client": "^5.9.1", @@ -32,13 +32,13 @@ "@react-email/tailwind": "^0.0.14", "@sentry/nextjs": "^7.105.0", "@stackframe/stack-shared": "workspace:*", + "@stackframe/stack-emails": "workspace:*", "@vercel/analytics": "^1.2.2", "bcrypt": "^5.1.1", "date-fns": "^3.6.0", "dotenv-cli": "^7.3.0", "handlebars": "^4.7.8", "jose": "^5.2.2", - "lodash": "^4.17.21", "next": "^14.1", "nodemailer": "^6.9.10", "openid-client": "^5.6.4", @@ -54,7 +54,6 @@ }, "devDependencies": { "@types/bcrypt": "^5.0.2", - "@types/lodash": "^4.17.4", "@types/node": "^20.8.10", "@types/nodemailer": "^6.4.14", "@types/react": "^18.2.66", diff --git a/apps/backend/prisma/migrations/20240702050143_verification_codes/migration.sql b/apps/backend/prisma/migrations/20240702050143_verification_codes/migration.sql new file mode 100644 index 000000000..3722fa947 --- /dev/null +++ b/apps/backend/prisma/migrations/20240702050143_verification_codes/migration.sql @@ -0,0 +1,22 @@ +-- CreateEnum +CREATE TYPE "VerificationCodeType" AS ENUM ('ONE_TIME_PASSWORD'); + +-- CreateTable +CREATE TABLE "VerificationCode" ( + "projectId" TEXT NOT NULL, + "id" UUID NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + "type" "VerificationCodeType" NOT NULL, + "code" TEXT NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "usedAt" TIMESTAMP(3), + "redirectUrl" TEXT, + "email" TEXT NOT NULL, + "data" JSONB NOT NULL, + + CONSTRAINT "VerificationCode_pkey" PRIMARY KEY ("projectId","id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "VerificationCode_projectId_code_key" ON "VerificationCode"("projectId", "code"); diff --git a/apps/backend/prisma/schema.prisma b/apps/backend/prisma/schema.prisma index ac9268466..b96a707a8 100644 --- a/apps/backend/prisma/schema.prisma +++ b/apps/backend/prisma/schema.prisma @@ -315,6 +315,32 @@ model ProjectUserAuthorizationCode { @@id([projectId, authorizationCode]) } +model VerificationCode { + projectId String + id String @default(uuid()) @db.Uuid + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + type VerificationCodeType + code String + expiresAt DateTime + usedAt DateTime? + redirectUrl String? + + email String + + data Json + + @@id([projectId, id]) + @@unique([projectId, code]) +} + +enum VerificationCodeType { + ONE_TIME_PASSWORD +} + +// @deprecated model ProjectUserEmailVerificationCode { projectId String projectUserId String @db.Uuid @@ -332,6 +358,7 @@ model ProjectUserEmailVerificationCode { @@id([projectId, code]) } +// @deprecated model ProjectUserPasswordResetCode { projectId String projectUserId String @db.Uuid @@ -349,6 +376,7 @@ model ProjectUserPasswordResetCode { @@id([projectId, code]) } +// @deprecated model ProjectUserMagicLinkCode { projectId String projectUserId String @db.Uuid diff --git a/apps/backend/prisma/seed.ts b/apps/backend/prisma/seed.ts index 97207193d..347bde4cf 100644 --- a/apps/backend/prisma/seed.ts +++ b/apps/backend/prisma/seed.ts @@ -31,6 +31,7 @@ async function seed() { description: "Internal API key set", publishableClientKey: "this-publishable-client-key-is-for-local-development-only", secretServerKey: "this-secret-server-key-is-for-local-development-only", + superSecretAdminKey: "this-super-secret-admin-key-is-for-local-development-only", expiresAt: new Date('2099-12-31T23:59:59Z'), }], }, diff --git a/apps/backend/sentry.client.config.ts b/apps/backend/sentry.client.config.ts index 5030d896d..938cb6cc7 100644 --- a/apps/backend/sentry.client.config.ts +++ b/apps/backend/sentry.client.config.ts @@ -5,7 +5,7 @@ import * as Sentry from "@sentry/nextjs"; Sentry.init({ - dsn: "https://0dc90570e0d280c1b4252ed61a328bfc@o4507084192022528.ingest.us.sentry.io/4507442898272256", + dsn: process.env.NEXT_PUBLIC_SENTRY_DSN, // Adjust this value in production, or use tracesSampler for greater control tracesSampleRate: 1, diff --git a/apps/backend/sentry.edge.config.ts b/apps/backend/sentry.edge.config.ts index 2d15b5a74..2f4d42adf 100644 --- a/apps/backend/sentry.edge.config.ts +++ b/apps/backend/sentry.edge.config.ts @@ -6,7 +6,7 @@ import * as Sentry from "@sentry/nextjs"; Sentry.init({ - dsn: "https://0dc90570e0d280c1b4252ed61a328bfc@o4507084192022528.ingest.us.sentry.io/4507442898272256", + dsn: process.env.NEXT_PUBLIC_SENTRY_DSN, // Adjust this value in production, or use tracesSampler for greater control tracesSampleRate: 1, diff --git a/apps/backend/sentry.server.config.ts b/apps/backend/sentry.server.config.ts index 68a3aef1f..34b24d01d 100644 --- a/apps/backend/sentry.server.config.ts +++ b/apps/backend/sentry.server.config.ts @@ -5,7 +5,7 @@ import * as Sentry from "@sentry/nextjs"; Sentry.init({ - dsn: "https://0dc90570e0d280c1b4252ed61a328bfc@o4507084192022528.ingest.us.sentry.io/4507442898272256", + dsn: process.env.NEXT_PUBLIC_SENTRY_DSN, // Adjust this value in production, or use tracesSampler for greater control tracesSampleRate: 1, diff --git a/apps/backend/src/app/api/v1/auth/oauth/access-token/[provider]/route.tsx b/apps/backend/src/app/api/v1/auth/oauth/access-token/[provider]/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/oauth/access-token/[provider]/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/oauth/authorize/[provider]/route.tsx b/apps/backend/src/app/api/v1/auth/oauth/authorize/[provider]/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/oauth/authorize/[provider]/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/oauth/callback/[provider]/route.tsx b/apps/backend/src/app/api/v1/auth/oauth/callback/[provider]/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/oauth/callback/[provider]/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/oauth/token/route.tsx b/apps/backend/src/app/api/v1/auth/oauth/token/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/oauth/token/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/otp/send-sign-in-code/route.tsx b/apps/backend/src/app/api/v1/auth/otp/send-sign-in-code/route.tsx new file mode 100644 index 000000000..d18dec2a8 --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/otp/send-sign-in-code/route.tsx @@ -0,0 +1,88 @@ +import * as yup from "yup"; +import { prismaClient } from "@/prisma-client"; +import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler"; +import { sendEmailFromTemplate } from "@/lib/emails"; +import { StackAssertionError, StatusError } from "@stackframe/stack-shared/dist/utils/errors"; +import { signInVerificationCodeHandler } from "../sign-in/verification-code-handler"; +import { adaptSchema, clientOrHigherAuthTypeSchema, signInEmailSchema, verificationLinkRedirectUrlSchema } from "@stackframe/stack-shared/dist/schema-fields"; +import { usersCrudHandlers } from "../../../users/crud"; + +export const POST = createSmartRouteHandler({ + request: yup.object({ + auth: yup.object({ + type: clientOrHigherAuthTypeSchema, + project: adaptSchema, + }).required(), + body: yup.object({ + email: signInEmailSchema.required(), + redirectUrl: verificationLinkRedirectUrlSchema, + }).required(), + }), + response: yup.object({ + statusCode: yup.number().oneOf([200]).required(), + bodyType: yup.string().oneOf(["success"]).required(), + }), + async handler({ auth: { project }, body: { email, redirectUrl } }, fullReq) { + if (!project.evaluatedConfig.magicLinkEnabled) { + throw new StatusError(StatusError.Forbidden, "Magic link is not enabled for this project"); + } + + const usersPrisma = await prismaClient.projectUser.findMany({ + where: { + projectId: project.id, + primaryEmail: email, + authWithEmail: true, + }, + }); + if (usersPrisma.length > 1) { + throw new StackAssertionError(`Multiple users found in the database with the same primary email ${email}, and all with e-mail sign-in allowed. This should never happen (only non-email/OAuth accounts are allowed to share the same primaryEmail).`); + } + + const userPrisma = usersPrisma.length > 0 ? usersPrisma[0] : null; + const isNewUser = !userPrisma; + let userObj: Pick, "projectUserId" | "displayName" | "primaryEmail"> | null = userPrisma; + if (!userObj) { + // TODO this should be in the same transaction as the read above + const createdUser = await usersCrudHandlers.adminCreate({ + project, + data: { + auth_with_email: true, + primary_email: email, + primary_email_verified: false, + }, + }); + userObj = { + projectUserId: createdUser.id, + displayName: createdUser.display_name, + primaryEmail: createdUser.primary_email, + }; + } + + const { link } = await signInVerificationCodeHandler.sendCode({ + project, + method: { email }, + data: { + user_id: userObj.projectUserId, + is_new_user: isNewUser, + }, + redirectUrl, + }); + + await sendEmailFromTemplate({ + project, + email, + templateId: "MAGIC_LINK", + variables: { + userDisplayName: userObj.displayName, + userPrimaryEmail: userObj.primaryEmail, + projectDisplayName: project.displayName, + magicLink: link.toString(), + }, + }); + + return { + statusCode: 200, + bodyType: "success", + }; + }, +}); diff --git a/apps/backend/src/app/api/v1/auth/otp/sign-in/route.tsx b/apps/backend/src/app/api/v1/auth/otp/sign-in/route.tsx new file mode 100644 index 000000000..bb9aa50c4 --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/otp/sign-in/route.tsx @@ -0,0 +1,3 @@ +import { signInVerificationCodeHandler } from "./verification-code-handler"; + +export const POST = signInVerificationCodeHandler.postHandler; diff --git a/apps/backend/src/app/api/v1/auth/otp/sign-in/verification-code-handler.tsx b/apps/backend/src/app/api/v1/auth/otp/sign-in/verification-code-handler.tsx new file mode 100644 index 000000000..5a04e0d01 --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/otp/sign-in/verification-code-handler.tsx @@ -0,0 +1,47 @@ +import * as yup from "yup"; +import { prismaClient } from "@/prisma-client"; +import { createAuthTokens } from "@/lib/tokens"; +import { createVerificationCodeHandler } from "@/route-handlers/verification-code-handler"; +import { signInResponseSchema } from "@stackframe/stack-shared/dist/schema-fields"; +import { VerificationCodeType } from "@prisma/client"; + +export const signInVerificationCodeHandler = createVerificationCodeHandler({ + type: VerificationCodeType.ONE_TIME_PASSWORD, + data: yup.object({ + user_id: yup.string().required(), + is_new_user: yup.boolean().required(), + }), + response: yup.object({ + statusCode: yup.number().oneOf([200]).required(), + body: signInResponseSchema.required(), + }), + async handler(project, { email }, data) { + const projectUser = await prismaClient.projectUser.update({ + where: { + projectId_projectUserId: { + projectId: project.id, + projectUserId: data.user_id, + }, + primaryEmail: email, + }, + data: { + primaryEmailVerified: true, + }, + }); + + const { refreshToken, accessToken } = await createAuthTokens({ + projectId: project.id, + projectUserId: projectUser.projectUserId, + }); + + return { + statusCode: 200, + body: { + refresh_token: refreshToken, + access_token: accessToken, + is_new_user: data.is_new_user, + user_id: data.user_id, + }, + }; + }, +}); diff --git a/apps/backend/src/app/api/v1/auth/password/reset/route.tsx b/apps/backend/src/app/api/v1/auth/password/reset/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/password/reset/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/password/send-reset-code/route.tsx b/apps/backend/src/app/api/v1/auth/password/send-reset-code/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/password/send-reset-code/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/password/sign-in/route.tsx b/apps/backend/src/app/api/v1/auth/password/sign-in/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/password/sign-in/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/password/sign-up/route.tsx b/apps/backend/src/app/api/v1/auth/password/sign-up/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/password/sign-up/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/password/update/route.tsx b/apps/backend/src/app/api/v1/auth/password/update/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/password/update/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/auth/sign-out/route.tsx b/apps/backend/src/app/api/v1/auth/sign-out/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/auth/sign-out/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/route.ts b/apps/backend/src/app/api/v1/route.ts index 5039b4f1a..8d9ec7b89 100644 --- a/apps/backend/src/app/api/v1/route.ts +++ b/apps/backend/src/app/api/v1/route.ts @@ -1,13 +1,14 @@ import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler"; import { deindent, typedCapitalize } from "@stackframe/stack-shared/dist/utils/strings"; import * as yup from "yup"; +import { adaptSchema } from "@stackframe/stack-shared/dist/schema-fields"; export const GET = createSmartRouteHandler({ request: yup.object({ auth: yup.object({ - type: yup.mixed(), - user: yup.mixed(), - project: yup.mixed(), + type: adaptSchema, + user: adaptSchema, + project: adaptSchema, }).nullable(), method: yup.string().oneOf(["GET"]).required(), }), @@ -24,8 +25,8 @@ export const GET = createSmartRouteHandler({ Welcome to the Stack API endpoint! Please refer to the documentation at https://docs.stack-auth.com. Authentication: ${!req.auth ? "None" : deindent` ${typedCapitalize(req.auth.type)} - Project: ${req.auth.project ? req.auth.project.id : "None"} - User: ${req.auth.user ? req.auth.user.primaryEmail ?? req.auth.user.id : "None"} + Project: ${req.auth.project.id} + User: ${req.auth.user ? req.auth.user.primary_email ?? req.auth.user.id : "None"} `} `, }; diff --git a/apps/backend/src/app/api/v1/users/[userId]/route.tsx b/apps/backend/src/app/api/v1/users/[userId]/route.tsx new file mode 100644 index 000000000..e358a810c --- /dev/null +++ b/apps/backend/src/app/api/v1/users/[userId]/route.tsx @@ -0,0 +1,5 @@ +import { usersCrudHandlers } from "../crud"; + +export const GET = usersCrudHandlers.readHandler; +export const PATCH = usersCrudHandlers.updateHandler; +export const DELETE = usersCrudHandlers.deleteHandler; diff --git a/apps/backend/src/app/api/v1/users/[userId]/send-email-verification-code/route.tsx b/apps/backend/src/app/api/v1/users/[userId]/send-email-verification-code/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/users/[userId]/send-email-verification-code/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/users/[userId]/verify-email/route.tsx b/apps/backend/src/app/api/v1/users/[userId]/verify-email/route.tsx new file mode 100644 index 000000000..b3d0b374a --- /dev/null +++ b/apps/backend/src/app/api/v1/users/[userId]/verify-email/route.tsx @@ -0,0 +1,3 @@ +import { NextResponse } from "next/server"; + +export const GET = () => NextResponse.json("TODO"); diff --git a/apps/backend/src/app/api/v1/users/crud.tsx b/apps/backend/src/app/api/v1/users/crud.tsx new file mode 100644 index 000000000..a007fe3ae --- /dev/null +++ b/apps/backend/src/app/api/v1/users/crud.tsx @@ -0,0 +1,119 @@ +import { addUserToTeam, createServerTeam, getServerTeamFromDbType } from "@/lib/teams"; +import { createCrudHandlers } from "@/route-handlers/crud-handler"; +import { createPrismaCrudHandlers } from "@/route-handlers/prisma-handler"; +import { BooleanTrue, Prisma } from "@prisma/client"; +import { KnownErrors } from "@stackframe/stack-shared"; +import { usersCrud } from "@stackframe/stack-shared/dist/interface/crud/users"; +import { currentUserCrud } from "@stackframe/stack-shared/dist/interface/crud/current-user"; +import { userIdOrMeRequestSchema } from "@stackframe/stack-shared/dist/schema-fields"; +import * as yup from "yup"; +import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; + +export const usersCrudHandlers = createPrismaCrudHandlers(usersCrud, "projectUser", { + paramsSchema: yup.object({ + userId: userIdOrMeRequestSchema.required(), + }), + baseFields: async ({ auth, params }) => { + const projectId = auth.project.id; + const userId = params.userId; + return { + projectId, + projectUserId: userId, + }; + }, + whereUnique: async ({ auth, params }) => { + const projectId = auth.project.id; + const userId = params.userId; + return { + projectId_projectUserId: { + projectId, + projectUserId: userId, + }, + }; + }, + include: async () => ({ + projectUserOAuthAccounts: true, + teamMembers: { + include: { + team: true, + }, + where: { + isSelected: BooleanTrue.TRUE, + }, + }, + }), + notFoundError: () => new KnownErrors.UserNotFound(), + crudToPrisma: async (crud, { auth }) => { + const projectId = auth.project.id; + return { + displayName: crud.display_name === undefined ? undefined : (crud.display_name || null), + clientMetadata: crud.client_metadata === null ? Prisma.JsonNull : crud.client_metadata, + serverMetadata: crud.server_metadata === null ? Prisma.JsonNull : crud.server_metadata, + projectId, + primaryEmail: crud.primary_email, + primaryEmailVerified: crud.primary_email_verified ?? (crud.primary_email !== undefined ? false : undefined), + authWithEmail: crud.auth_with_email, + }; + }, + prismaToCrud: async (prisma, { auth }) => { + const selectedTeamMembers = prisma.teamMembers; + if (selectedTeamMembers.length > 1) { + throw new StackAssertionError("User cannot have more than one selected team; this should never happen"); + } + return { + project_id: prisma.projectId, + id: prisma.projectUserId, + display_name: prisma.displayName || null, + primary_email: prisma.primaryEmail, + primary_email_verified: prisma.primaryEmailVerified, + profile_image_url: prisma.profileImageUrl, + signed_up_at_millis: prisma.createdAt.getTime(), + client_metadata: prisma.clientMetadata, + server_metadata: prisma.serverMetadata, + auth_method: prisma.passwordHash ? 'credential' as const : 'oauth' as const, // not used anymore, for backwards compatibility + has_password: !!prisma.passwordHash, + auth_with_email: prisma.authWithEmail, + oauth_providers: prisma.projectUserOAuthAccounts.map((a) => a.oauthProviderConfigId), + selected_team_id: selectedTeamMembers[0]?.teamId ?? null, + selected_team: selectedTeamMembers[0] ? getServerTeamFromDbType(selectedTeamMembers[0]?.team) : null, + }; + }, + onCreate: async (prisma, context) => { + // TODO use the same transaction as the one that creates the user row + + const project = context.auth.project; + if (project.evaluatedConfig.createTeamOnSignUp) { + const team = await createServerTeam( + project.id, + { + displayName: `${prisma.displayName ?? prisma.primaryEmail ?? "Unnamed user"}'s personal team`, + }, + ); + await addUserToTeam(project.id, team.id, prisma.projectUserId); + } + }, +}); + +export const currentUserCrudHandlers = createCrudHandlers(currentUserCrud, { + paramsSchema: yup.object({} as const), + async onRead({ auth }) { + return await usersCrudHandlers.adminRead({ + project: auth.project, + userId: auth.user?.id ?? throwErr(new KnownErrors.CannotGetOwnUserWithoutUser()), + }); + }, + async onUpdate({ auth, data }) { + return await usersCrudHandlers.adminUpdate({ + project: auth.project, + userId: auth.user?.id ?? throwErr(new KnownErrors.CannotGetOwnUserWithoutUser()), + data, + }); + }, + async onDelete({ auth, data }) { + return await usersCrudHandlers.adminDelete({ + project: auth.project, + userId: auth.user?.id ?? throwErr(new KnownErrors.CannotGetOwnUserWithoutUser()), + data, + }); + }, +}); diff --git a/apps/backend/src/app/api/v1/users/me/route.tsx b/apps/backend/src/app/api/v1/users/me/route.tsx new file mode 100644 index 000000000..93a32cd61 --- /dev/null +++ b/apps/backend/src/app/api/v1/users/me/route.tsx @@ -0,0 +1,5 @@ +import { currentUserCrudHandlers } from "../crud"; + +export const GET = currentUserCrudHandlers.readHandler; +export const PATCH = currentUserCrudHandlers.updateHandler; +export const DELETE = currentUserCrudHandlers.deleteHandler; diff --git a/apps/backend/src/app/api/v1/users/route.tsx b/apps/backend/src/app/api/v1/users/route.tsx new file mode 100644 index 000000000..dd9134461 --- /dev/null +++ b/apps/backend/src/app/api/v1/users/route.tsx @@ -0,0 +1,4 @@ +import { usersCrudHandlers } from "./crud"; + +export const GET = usersCrudHandlers.listHandler; +export const POST = usersCrudHandlers.createHandler; diff --git a/apps/backend/src/app/page.tsx b/apps/backend/src/app/page.tsx index a0b9bf1c6..7f37d18c9 100644 --- a/apps/backend/src/app/page.tsx +++ b/apps/backend/src/app/page.tsx @@ -4,6 +4,10 @@ export default function Home() { return <> Welcome to Stack's API endpoint.

+ Were you looking for Stack's dashboard instead?
+
+ You can also return to https://stack-auth.com.
+
API v1
; } diff --git a/apps/backend/src/lib/email-templates.tsx b/apps/backend/src/lib/email-templates.tsx new file mode 100644 index 000000000..38c652d25 --- /dev/null +++ b/apps/backend/src/lib/email-templates.tsx @@ -0,0 +1,140 @@ +// TODO remove and replace with CRUD handler + +import { prismaClient } from "@/prisma-client"; +import { EmailTemplateType } from "@prisma/client"; +import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects"; +import { getProject } from "./projects"; +import { EmailTemplateCrud, ListEmailTemplatesCrud } from "@stackframe/stack-shared/dist/interface/crud/email-templates"; +import { EMAIL_TEMPLATES_METADATA } from "@stackframe/stack-emails/dist/utils"; +import { TEditorConfiguration } from "@stackframe/stack-emails/dist/editor/documents/editor/core"; + +export async function listEmailTemplatesWithDefault(projectId: string) { + const project = await getProject(projectId); + if (!project) { + throw new Error("Project not found"); + } + + const templates = await prismaClient.emailTemplate.findMany({ + where: { + projectConfigId: project.evaluatedConfig.id, + }, + }); + const templateMap = new Map(); + for (const template of templates) { + templateMap.set(template.type, { content: template.content || {}, subject: template.subject }); + } + + const results: ListEmailTemplatesCrud['Server']['Read'] = []; + for (const type of Object.values(EmailTemplateType)) { + const template = templateMap.get(type) ?? { + content: EMAIL_TEMPLATES_METADATA[type].defaultContent, + subject: EMAIL_TEMPLATES_METADATA[type].defaultSubject + }; + results.push({ type, content: template.content, default: !templateMap.has(type), subject: template.subject }); + } + + return results; +} + +export async function getEmailTemplateWithDefault(projectId: string, type: EmailTemplateType) { + const template = await getEmailTemplate(projectId, type); + if (template) { + return template; + } + return { + type, + content: EMAIL_TEMPLATES_METADATA[type].defaultContent, + subject: EMAIL_TEMPLATES_METADATA[type].defaultSubject, + default: true, + }; +} + +export async function getEmailTemplate(projectId: string, type: EmailTemplateType) { + const project = await getProject(projectId); + if (!project) { + throw new Error("Project not found"); + } + + const template = await prismaClient.emailTemplate.findUnique({ + where: { + projectConfigId_type: { + projectConfigId: project.evaluatedConfig.id, + type, + }, + }, + }); + + return template ? { + ...template, + content: template.content as TEditorConfiguration, + } : null; +} + +export async function updateEmailTemplate( + projectId: string, + type: EmailTemplateType, + update: Partial +) { + const project = await getProject(projectId); + if (!project) { + throw new Error("Project not found"); + } + + const result = await prismaClient.emailTemplate.update({ + where: { + projectConfigId_type: { + projectConfigId: project.evaluatedConfig.id, + type, + }, + }, + data: filterUndefined({ + content: update.content, + }), + }); + + return { + ...result, + content: result.content as any, + }; +} + +export async function deleteEmailTemplate(projectId: string, type: EmailTemplateType) { + const project = await getProject(projectId); + if (!project) { + throw new Error("Project not found"); + } + + return await prismaClient.emailTemplate.delete({ + where: { + projectConfigId_type: { + projectConfigId: project.evaluatedConfig.id, + type: type, + }, + }, + }); +} + +export async function createEmailTemplate( + projectId: string, + type: EmailTemplateType, + data: EmailTemplateCrud['Server']['Update'] +) { + const project = await getProject(projectId); + if (!project) { + throw new Error("Project not found"); + } + + const result = await prismaClient.emailTemplate.create({ + data: { + projectConfigId: project.evaluatedConfig.id, + type, + content: data.content, + subject: data.subject, + }, + }); + + return { + ...result, + content: result.content as any, + }; +} diff --git a/apps/backend/src/lib/emails.tsx b/apps/backend/src/lib/emails.tsx new file mode 100644 index 000000000..ead94c430 --- /dev/null +++ b/apps/backend/src/lib/emails.tsx @@ -0,0 +1,222 @@ +import nodemailer from 'nodemailer'; +import { prismaClient } from '@/prisma-client'; +import { getEnvVariable } from '@stackframe/stack-shared/dist/utils/env'; +import { generateSecureRandomString } from '@stackframe/stack-shared/dist/utils/crypto'; +import { getProject } from '@/lib/projects'; +import { UserJson, ProjectJson } from '@stackframe/stack-shared'; +import { getEmailTemplateWithDefault } from '@/lib/email-templates'; +import { renderEmailTemplate } from '@stackframe/stack-emails/dist/utils'; +import { EmailTemplateType } from '@prisma/client'; +import { usersCrudHandlers } from '@/app/api/v1/users/crud'; +import { UsersCrud } from '@stackframe/stack-shared/dist/interface/crud/users'; + + +function getPortConfig(port: number | string) { + let parsedPort = parseInt(port.toString()); + const secure = parsedPort === 465; + return { secure }; +} + +export type EmailConfig = { + host: string, + port: number, + username: string, + password: string, + senderEmail: string, + senderName: string, + secure: boolean, + type: 'shared' | 'standard', +} + +export async function sendEmail({ + emailConfig, + to, + subject, + text, + html, +}: { + emailConfig: EmailConfig, + to: string | string[], + subject: string, + html: string, + text?: string, +}) { + const transporter = nodemailer.createTransport({ + host: emailConfig.host, + port: emailConfig.port, + secure: emailConfig.secure, + auth: { + user: emailConfig.username, + pass: emailConfig.password, + }, + }); + + return await transporter.sendMail({ + from: `"${emailConfig.senderName}" <${emailConfig.senderEmail}>`, + to, + subject, + text, + html + }); +} + +export async function sendEmailFromTemplate(options: { + project: ProjectJson, + email: string, + templateId: EmailTemplateType, + variables: Record, +}) { + const template = await getEmailTemplateWithDefault(options.project.id, options.templateId); + + const { subject, html, text } = renderEmailTemplate(template.subject, template.content, options.variables); + + await sendEmail({ + emailConfig: await getEmailConfig(options.project), + to: options.email, + subject, + html, + text, + }); +} + +async function getEmailConfig(project: ProjectJson): Promise { + const projectEmailConfig = project.evaluatedConfig.emailConfig; + if (!projectEmailConfig) { + throw new Error('Email service config not found. TODO: When can this even happen?'); + } + + if (projectEmailConfig.type === 'shared') { + return { + host: getEnvVariable('STACK_EMAIL_HOST'), + port: parseInt(getEnvVariable('STACK_EMAIL_PORT')), + username: getEnvVariable('STACK_EMAIL_USERNAME'), + password: getEnvVariable('STACK_EMAIL_PASSWORD'), + senderEmail: getEnvVariable('STACK_EMAIL_SENDER'), + senderName: project.displayName, + secure: getPortConfig(getEnvVariable('STACK_EMAIL_PORT')).secure, + type: 'shared', + }; + } else { + return { + host: projectEmailConfig.host, + port: projectEmailConfig.port, + username: projectEmailConfig.username, + password: projectEmailConfig.password, + senderEmail: projectEmailConfig.senderEmail, + senderName: projectEmailConfig.senderName, + secure: getPortConfig(projectEmailConfig.port).secure, + type: 'standard', + }; + } +} + +async function getDBInfo(projectId: string, projectUserId: string): Promise<{ + emailConfig: EmailConfig, + project: ProjectJson, + projectUser: UsersCrud["Admin"]["Read"], +}> { + const project = await getProject(projectId); + + if (!project) { + throw new Error('Project not found'); + } + + const user = await usersCrudHandlers.adminRead({ + project, + userId: projectUserId, + }); + + return { + emailConfig: await getEmailConfig(project), + project, + projectUser: user, + }; +} + +export async function sendVerificationEmail( + projectId: string, + projectUserId: string, + redirectUrl: string, +) { + const { project, emailConfig, projectUser } = await getDBInfo(projectId, projectUserId); + + if (!projectUser.primary_email) { + throw Error('The user does not have a primary email'); + } + + if (projectUser.primary_email_verified) { + throw Error('Email already verified'); + } + + const verificationCode = await prismaClient.projectUserEmailVerificationCode.create({ + data: { + projectId, + projectUserId, + code: generateSecureRandomString(), + redirectUrl, + expiresAt: new Date(Date.now() + 3 * 60 * 60 * 1000), // expires in 3 hours + } + }); + + const verificationUrl = new URL(redirectUrl); + verificationUrl.searchParams.append('code', verificationCode.code); + + const template = await getEmailTemplateWithDefault(projectId, 'EMAIL_VERIFICATION'); + const variables: Record = { + userDisplayName: projectUser.display_name, + userPrimaryEmail: projectUser.primary_email, + projectDisplayName: project.displayName, + emailVerificationLink: verificationUrl.toString(), + }; + const { subject, html, text } = renderEmailTemplate(template.subject, template.content, variables); + + await sendEmail({ + emailConfig, + to: projectUser.primary_email, + subject, + html, + text, + }); +} + +export async function sendPasswordResetEmail( + projectId: string, + projectUserId: string, + redirectUrl: string, +) { + const { project, emailConfig, projectUser } = await getDBInfo(projectId, projectUserId); + + if (!projectUser.primary_email) { + throw Error('The user does not have a primary email'); + } + + const resetCode = await prismaClient.projectUserPasswordResetCode.create({ + data: { + projectId, + projectUserId, + code: generateSecureRandomString(), + redirectUrl, + expiresAt: new Date(Date.now() + 3 * 60 * 60 * 1000), // expires in 3 hours + } + }); + + const passwordResetUrl = new URL(redirectUrl); + passwordResetUrl.searchParams.append('code', resetCode.code); + + const template = await getEmailTemplateWithDefault(projectId, 'PASSWORD_RESET'); + const variables: Record = { + userDisplayName: projectUser.display_name, + userPrimaryEmail: projectUser.primary_email, + projectDisplayName: project.displayName, + passwordResetLink: passwordResetUrl.toString(), + }; + const { subject, html, text } = renderEmailTemplate(template.subject, template.content, variables); + + await sendEmail({ + emailConfig, + to: projectUser.primary_email, + subject, + html, + text, + }); +} diff --git a/apps/backend/src/lib/openapi.tsx b/apps/backend/src/lib/openapi.tsx index 2fe91a1cc..6f2e708a2 100644 --- a/apps/backend/src/lib/openapi.tsx +++ b/apps/backend/src/lib/openapi.tsx @@ -1,4 +1,5 @@ import { SmartRouteHandler } from '@/route-handlers/smart-route-handler'; +import { EndpointDocumentation } from '@stackframe/stack-shared/dist/crud'; import { StackAssertionError } from '@stackframe/stack-shared/dist/utils/errors'; import { HttpMethod } from '@stackframe/stack-shared/dist/utils/http'; import { deindent } from '@stackframe/stack-shared/dist/utils/strings'; @@ -34,13 +35,6 @@ export function parseOpenAPI(options: { }; } -const endpointMetadataSchema = yup.object({ - summary: yup.string().required(), - description: yup.string().required(), - hide: yup.boolean().optional(), - tags: yup.array(yup.string()).required(), -}); - function undefinedIfMixed(value: yup.SchemaFieldDescription | undefined): yup.SchemaFieldDescription | undefined { if (!value) return undefined; return value.type === 'mixed' ? undefined : value; @@ -101,18 +95,15 @@ function parseRouteHandler(options: { throw new StackAssertionError(deindent` OpenAPI generator matched multiple overloads for audience ${options.audience} on endpoint ${options.method} ${options.path}. - This does not necessarily mean there is a bug; the OpenAPI generator uses a heuristic to pick the allowed overloads, and may pick too many. Currently, this heuristic checks whether the request.auth.type property in the schema is a yup.string.oneOf(...) and matches it to the expected audience of the schema. If there are multiple overloads matching a single audience, for example because none of the overloads specify request.auth.type, the OpenAPI generator will not know which overload to generate specs for, and hence fails. + This does not necessarily mean there is a bug in the endpoint; the OpenAPI generator uses a heuristic to pick the allowed overloads, and may pick too many. Currently, this heuristic checks whether the request.auth.type property in the schema is a yup.string.oneOf(...) and matches it to the expected audience of the schema. If there are multiple overloads matching a single audience, for example because none of the overloads specify request.auth.type, the OpenAPI generator will not know which overload to generate specs for, and hence fails. Either specify request.auth.type on the schema of the specified endpoint or update the OpenAPI generator to support your use case. `); } result = parseOverload({ - metadata: overload.metadata ?? { - summary: `${options.method} ${options.path}`, - description: `No documentation available for this endpoint.`, - tags: ["Uncategorized"], - }, + metadata: overload.metadata, + method: options.method, path: options.path, pathDesc: undefinedIfMixed(requestDescribe.fields.params), parameterDesc: undefinedIfMixed(requestDescribe.fields.query), @@ -126,13 +117,13 @@ function parseRouteHandler(options: { function getFieldSchema(field: yup.SchemaFieldDescription): { type: string, items?: any } | undefined { const meta = "meta" in field ? field.meta : {}; - if (meta?.openapi?.hide) { + if (meta?.openapiField?.hidden) { return undefined; } const openapiFieldExtra = { - example: meta?.openapi?.exampleValue, - description: meta?.openapi?.description, + example: meta?.openapiField?.exampleValue, + description: meta?.openapiField?.description, }; switch (field.type) { @@ -216,19 +207,25 @@ function toExamples(description: yup.SchemaFieldDescription) { return Object.entries(description.fields).reduce((acc, [key, field]) => { const schema = getFieldSchema(field); if (!schema) return acc; - const example = "meta" in field ? field.meta?.openapi?.exampleValue : undefined; + const example = "meta" in field ? field.meta?.openapiField?.exampleValue : undefined; return { ...acc, [key]: example }; }, {}); } export function parseOverload(options: { - metadata: yup.InferType, + metadata: EndpointDocumentation | undefined, + method: string, path: string, pathDesc?: yup.SchemaFieldDescription, parameterDesc?: yup.SchemaFieldDescription, requestBodyDesc?: yup.SchemaFieldDescription, responseDesc?: yup.SchemaFieldDescription, }) { + const endpointDocumentation = options.metadata ?? { + summary: `${options.method} ${options.path}`, + description: `No documentation available for this endpoint.`, + }; + const pathParameters = options.pathDesc ? toParameters(options.pathDesc, options.path) : []; const queryParameters = options.parameterDesc ? toParameters(options.parameterDesc) : []; const responseSchema = options.responseDesc ? toSchema(options.responseDesc) : {}; @@ -251,11 +248,11 @@ export function parseOverload(options: { } return { - summary: options.metadata.summary, - description: options.metadata.description, + summary: endpointDocumentation.summary, + description: endpointDocumentation.description, parameters: queryParameters.concat(pathParameters), requestBody, - tags: options.metadata.tags, + tags: endpointDocumentation.tags ?? ["Uncategorized"], responses: { 200: { description: 'Successful response', diff --git a/apps/backend/src/lib/projects.tsx b/apps/backend/src/lib/projects.tsx index 095e5c347..1f28877f5 100644 --- a/apps/backend/src/lib/projects.tsx +++ b/apps/backend/src/lib/projects.tsx @@ -3,12 +3,14 @@ import { KnownErrors, OAuthProviderConfigJson, ProjectJson, ServerUserJson } fro import { Prisma, ProxiedOAuthProviderType, StandardOAuthProviderType } from "@prisma/client"; import { prismaClient } from "@/prisma-client"; import { decodeAccessToken } from "./tokens"; -import { getServerUser } from "./users"; import { generateUuid } from "@stackframe/stack-shared/dist/utils/uuids"; import { EmailConfigJson, SharedProvider, StandardProvider, sharedProviders, standardProviders } from "@stackframe/stack-shared/dist/interface/clientInterface"; import { OAuthProviderUpdateOptions, ProjectUpdateOptions } from "@stackframe/stack-shared/dist/interface/adminInterface"; import { StackAssertionError, StatusError, captureError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; import { fullPermissionInclude, isTeamSystemPermission, listServerPermissionDefinitions, serverPermissionDefinitionJsonFromDbType, serverPermissionDefinitionJsonFromTeamSystemDbType, teamPermissionIdSchema, teamSystemPermissionStringToDBType } from "./permissions"; +import { usersCrudHandlers } from "@/app/api/v1/users/crud"; +import { CrudHandlerInvokationError } from "@/route-handlers/crud-handler"; +import { UsersCrud } from "@stackframe/stack-shared/dist/interface/crud/users"; function toDBSharedProvider(type: SharedProvider): ProxiedOAuthProviderType { @@ -118,12 +120,21 @@ export async function whyNotProjectAdmin(projectId: string, adminAccessToken: st return "wrong-project-id"; } - const projectUser = await getServerUser("internal", userId); - if (!projectUser) { - return "not-admin"; + let user; + try { + user = await usersCrudHandlers.adminRead({ + project: await getProject("internal") ?? throwErr("Can't find internal project??"), + userId, + }); + } catch (e) { + if (e instanceof CrudHandlerInvokationError && e.cause instanceof KnownErrors.UserNotFound) { + // this may happen eg. if the user has a valid access token but has since been deleted + return "not-admin"; + } + throw e; } - const allProjects = listProjectIds(projectUser); + const allProjects = listProjectIds(user); if (!allProjects.includes(projectId)) { return "not-admin"; } @@ -135,8 +146,8 @@ export async function isProjectAdmin(projectId: string, adminAccessToken: string return !await whyNotProjectAdmin(projectId, adminAccessToken); } -function listProjectIds(projectUser: ServerUserJson) { - const serverMetadata = projectUser.serverMetadata; +function listProjectIds(projectUser: UsersCrud["Admin"]["Read"]) { + const serverMetadata = projectUser.server_metadata; if (typeof serverMetadata !== "object" || !(!serverMetadata || "managedProjectIds" in serverMetadata)) { throw new StackAssertionError("Invalid server metadata, did something go wrong?", { serverMetadata }); } @@ -148,7 +159,7 @@ function listProjectIds(projectUser: ServerUserJson) { return managedProjectIds; } -export async function listProjects(projectUser: ServerUserJson): Promise { +export async function listProjects(projectUser: UsersCrud["Admin"]["Read"]): Promise { const managedProjectIds = listProjectIds(projectUser); const projects = await prismaClient.project.findMany({ diff --git a/apps/backend/src/lib/redirect-urls.tsx b/apps/backend/src/lib/redirect-urls.tsx index ae6c856ad..1c65ee80d 100644 --- a/apps/backend/src/lib/redirect-urls.tsx +++ b/apps/backend/src/lib/redirect-urls.tsx @@ -1,11 +1,12 @@ import { DomainConfigJson } from "@stackframe/stack-shared/dist/interface/clientInterface"; -export function validateRedirectUrl(url: string, domains: DomainConfigJson[], allowLocalhost: boolean): boolean { - if (allowLocalhost && (new URL(url).hostname === "localhost" || new URL(url).hostname.match(/^127\.\d+\.\d+\.\d+$/))) { +export function validateRedirectUrl(urlOrString: string | URL, domains: DomainConfigJson[], allowLocalhost: boolean): boolean { + const url = new URL(urlOrString); + if (allowLocalhost && (url.hostname === "localhost" || url.hostname.match(/^127\.\d+\.\d+\.\d+$/))) { return true; } return domains.some((domain) => { - const testUrl = new URL(url); + const testUrl = url; const baseUrl = new URL(domain.handlerPath, domain.domain); const sameOrigin = baseUrl.protocol === testUrl.protocol && baseUrl.hostname === testUrl.hostname; diff --git a/apps/backend/src/lib/teams.tsx b/apps/backend/src/lib/teams.tsx index 56ed2a354..382c8460c 100644 --- a/apps/backend/src/lib/teams.tsx +++ b/apps/backend/src/lib/teams.tsx @@ -5,16 +5,12 @@ import { TeamJson } from "@stackframe/stack-shared/dist/interface/clientInterfac import { ServerTeamCustomizableJson, ServerTeamJson, ServerTeamMemberJson } from "@stackframe/stack-shared/dist/interface/serverInterface"; import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects"; import { Prisma } from "@prisma/client"; -import { getServerUserFromDbType } from "./users"; -import { serverUserInclude } from "./users"; +import { usersCrudHandlers } from "@/app/api/v1/users/crud"; // TODO technically we can split this; listUserTeams only needs `team`, and listServerTeams only needs `projectUser`; listTeams needs neither // note: this is a function to prevent circular dependencies between the teams and users file export const createFullTeamMemberInclude = () => ({ team: true, - projectUser: { - include: serverUserInclude, - }, } as const satisfies Prisma.TeamMemberInclude); export type ServerTeamMemberDB = Prisma.TeamMemberGetPayload<{ include: ReturnType }>; @@ -57,18 +53,6 @@ export async function listServerTeams(projectId: string): Promise { - const members = await prismaClient.teamMember.findMany({ - where: { - projectId, - teamId, - }, - include: createFullTeamMemberInclude(), - }); - - return members.map((member) => getServerTeamMemberFromDbType(member)); -} - export async function getTeam(projectId: string, teamId: string): Promise { // TODO more efficient filtering const teams = await listTeams(projectId); @@ -153,12 +137,3 @@ export function getServerTeamFromDbType(team: Prisma.TeamGetPayload<{}>): Server createdAtMillis: team.createdAt.getTime(), }; } - -export function getServerTeamMemberFromDbType(member: ServerTeamMemberDB): ServerTeamMemberJson { - return { - userId: member.projectUserId, - user: getServerUserFromDbType(member.projectUser), - teamId: member.teamId, - displayName: member.projectUser.displayName, - }; -} diff --git a/apps/backend/src/lib/users.tsx b/apps/backend/src/lib/users.tsx deleted file mode 100644 index a775e3fd4..000000000 --- a/apps/backend/src/lib/users.tsx +++ /dev/null @@ -1,206 +0,0 @@ -// TODO remove and replace with CRUD handler - -import { UserJson, ServerUserJson, KnownErrors } from "@stackframe/stack-shared"; -import { Prisma } from "@prisma/client"; -import { prismaClient } from "@/prisma-client"; -import { getProject } from "@/lib/projects"; -import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects"; -import { UserUpdateJson } from "@stackframe/stack-shared/dist/interface/clientInterface"; -import { ServerUserUpdateJson } from "@stackframe/stack-shared/dist/interface/serverInterface"; -import { addUserToTeam, createServerTeam, getClientTeamFromServerTeam, getServerTeamFromDbType } from "./teams"; -import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors"; - -export const serverUserInclude = { - projectUserOAuthAccounts: true, - teamMembers: { - include: { - team: true, - }, - }, -} as const satisfies Prisma.ProjectUserInclude; - -export type ServerUserDB = Prisma.ProjectUserGetPayload<{ include: typeof serverUserInclude }>; - -export async function getClientUser(projectId: string, userId: string): Promise { - return await updateClientUser(projectId, userId, {}); -} - -export async function getServerUser(projectId: string, userId: string): Promise { - return await updateServerUser(projectId, userId, {}); -} - -export async function listServerUsers(projectId: string): Promise { - const users = await prismaClient.projectUser.findMany({ - where: { - projectId, - }, - include: serverUserInclude, - }); - - return users.map((u) => getServerUserFromDbType(u)); -} - -export async function updateClientUser( - projectId: string, - userId: string, - update: UserUpdateJson, -): Promise { - const user = await updateServerUser( - projectId, - userId, - { - displayName: update.displayName, - clientMetadata: update.clientMetadata, - selectedTeamId: update.selectedTeamId, - }, - ); - if (!user) { - return null; - } - - return getClientUserFromServerUser(user); -} - -export async function updateServerUser( - projectId: string, - userId: string, - update: ServerUserUpdateJson, -): Promise { - let user; - try { - if (update.selectedTeamId !== undefined) { - await prismaClient.teamMember.updateMany({ - where: { - projectId, - projectUserId: userId, - }, - data: { - isSelected: null, - }, - }); - - if (update.selectedTeamId !== null) { - await prismaClient.teamMember.update({ - where: { - projectId_projectUserId_teamId: { - projectId, - projectUserId: userId, - teamId: update.selectedTeamId, - }, - }, - data: { - isSelected: 'TRUE' - }, - }); - } - } - - user = await prismaClient.projectUser.update({ - where: { - projectId_projectUserId: { - projectId, - projectUserId: userId, - }, - }, - include: serverUserInclude, - data: filterUndefined({ - displayName: update.displayName, - primaryEmail: update.primaryEmail, - primaryEmailVerified: update.primaryEmailVerified, - clientMetadata: update.clientMetadata as any, - serverMetadata: update.serverMetadata as any, - }), - }); - } catch (e) { - // TODO this is kinda hacky, instead we should have the entire method throw an error instead of returning null and have a separate getServerUser function that may return null - if ((e as any)?.code === 'P2025') { - return null; - } - throw e; - } - - return getServerUserFromDbType(user); -} - -export async function deleteServerUser(projectId: string, userId: string): Promise { - try { - await prismaClient.projectUser.delete({ - where: { - projectId: projectId, - projectId_projectUserId: { - projectId, - projectUserId: userId, - }, - }, - }); - } catch (e) { - if ((e as any)?.code === 'P2025') { - throw new KnownErrors.UserNotFound(); - } - throw e; - } -} - -function getClientUserFromServerUser(serverUser: ServerUserJson): UserJson { - return { - projectId: serverUser.projectId, - id: serverUser.id, - displayName: serverUser.displayName, - primaryEmail: serverUser.primaryEmail, - primaryEmailVerified: serverUser.primaryEmailVerified, - profileImageUrl: serverUser.profileImageUrl, - signedUpAtMillis: serverUser.signedUpAtMillis, - clientMetadata: serverUser.clientMetadata, - authMethod: serverUser.authMethod, // not used anymore, for backwards compatibility - authWithEmail: serverUser.authWithEmail, - hasPassword: serverUser.hasPassword, - oauthProviders: serverUser.oauthProviders, - selectedTeamId: serverUser.selectedTeamId, - selectedTeam: serverUser.selectedTeam && getClientTeamFromServerTeam(serverUser.selectedTeam), - }; -} - -export function getServerUserFromDbType( - user: ServerUserDB, -): ServerUserJson { - const rawSelectedTeam = user.teamMembers.filter(m => m.isSelected)[0]?.team; - return { - projectId: user.projectId, - id: user.projectUserId, - displayName: user.displayName, - primaryEmail: user.primaryEmail, - primaryEmailVerified: user.primaryEmailVerified, - profileImageUrl: user.profileImageUrl, - signedUpAtMillis: user.createdAt.getTime(), - clientMetadata: user.clientMetadata as any, - serverMetadata: user.serverMetadata as any, - authMethod: user.passwordHash ? 'credential' : 'oauth', // not used anymore, for backwards compatibility - hasPassword: !!user.passwordHash, - authWithEmail: user.authWithEmail, - oauthProviders: user.projectUserOAuthAccounts.map((a) => a.oauthProviderConfigId), - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - selectedTeamId: rawSelectedTeam?.teamId ?? null, - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - selectedTeam: (rawSelectedTeam && getServerTeamFromDbType(rawSelectedTeam)) ?? null, - }; -} - -export async function createTeamOnSignUp(projectId: string, userId: string): Promise { - const project = await getProject(projectId); - if (!project) { - throw new Error('Project not found'); - } - if (!project.evaluatedConfig.createTeamOnSignUp) { - return; - } - const user = await getServerUser(projectId, userId); - if (!user) { - throw new Error('User not found'); - } - - const team = await createServerTeam( - projectId, - { displayName: user.displayName ? `${user.displayName}'s personal team` : 'Personal team' } - ); - await addUserToTeam(projectId, team.id, userId); -} diff --git a/apps/backend/src/middleware.tsx b/apps/backend/src/middleware.tsx index 35673a3ff..6ca3f8f26 100644 --- a/apps/backend/src/middleware.tsx +++ b/apps/backend/src/middleware.tsx @@ -5,7 +5,6 @@ import type { NextRequest } from 'next/server'; const corsAllowedRequestHeaders = [ // General - 'authorization', 'content-type', 'x-stack-project-id', 'x-stack-override-error-status', @@ -13,7 +12,7 @@ const corsAllowedRequestHeaders = [ 'x-stack-client-version', // Project auth - 'x-stack-request-type', + 'x-stack-access-type', 'x-stack-publishable-client-key', 'x-stack-secret-server-key', 'x-stack-super-secret-admin-key', diff --git a/apps/backend/src/route-handlers/crud-handler.tsx b/apps/backend/src/route-handlers/crud-handler.tsx index 8218c8dac..2ee627f3f 100644 --- a/apps/backend/src/route-handlers/crud-handler.tsx +++ b/apps/backend/src/route-handlers/crud-handler.tsx @@ -8,6 +8,8 @@ import { typedIncludes } from "@stackframe/stack-shared/dist/utils/arrays"; import { deindent, typedToLowercase } from "@stackframe/stack-shared/dist/utils/strings"; import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; import { SmartRequestAuth } from "./smart-request"; +import { ProjectJson } from "@stackframe/stack-shared"; +import { UsersCrud } from "@stackframe/stack-shared/dist/interface/crud/users"; type GetAdminKey, K extends Capitalize> = K extends keyof T["Admin"] ? T["Admin"][K] : void; @@ -22,71 +24,91 @@ type CrudSingleRouteHandler, K extends Capitalize[] + ? { + items: GetAdminKey[], + is_paginated: false, + } : GetAdminKey ) > : void; type CrudRouteHandlersUnfiltered, Params extends {}> = { - onCreate: CrudSingleRouteHandler, - onRead: CrudSingleRouteHandler, - onList: keyof Params extends never ? void : CrudSingleRouteHandler, true>, - onUpdate: CrudSingleRouteHandler, - onDelete: CrudSingleRouteHandler, + onCreate?: CrudSingleRouteHandler, + onRead?: CrudSingleRouteHandler, + onList?: keyof Params extends never ? void : CrudSingleRouteHandler, true>, + onUpdate?: CrudSingleRouteHandler, + onDelete?: CrudSingleRouteHandler, }; -export type RouteHandlerMetadataMap = { - create?: SmartRouteHandlerOverloadMetadata, - read?: SmartRouteHandlerOverloadMetadata, - list?: SmartRouteHandlerOverloadMetadata, - update?: SmartRouteHandlerOverloadMetadata, - delete?: SmartRouteHandlerOverloadMetadata, -}; +export type ParamsSchema = yup.ObjectSchema<{}>; -type CrudHandlerOptions, ParamNames extends string> = - & FilterUndefined>> +type CrudHandlerOptions, PS extends ParamsSchema> = + & FilterUndefined>> & { - paramNames: ParamNames[], - metadataMap?: RouteHandlerMetadataMap, + paramsSchema: PS, }; -type CrudHandlersFromOptions, any>> = CrudHandlers< - | ("onCreate" extends keyof O ? "Create" : never) +type CrudHandlersFromOptions, PS extends ParamsSchema, O extends CrudHandlerOptions, ParamsSchema>> = CrudHandlers< + T, + PS, + ("onCreate" extends keyof O ? "Create" : never) | ("onRead" extends keyof O ? "Read" : never) | ("onList" extends keyof O ? "List" : never) | ("onUpdate" extends keyof O ? "Update" : never) | ("onDelete" extends keyof O ? "Delete" : never) > -export type CrudHandlers< - T extends "Create" | "Read" | "List" | "Update" | "Delete", +type CrudHandlerDirectByAccess< + A extends "Client" | "Server" | "Admin", + T extends CrudTypeOf, + PS extends ParamsSchema, + L extends "Create" | "Read" | "List" | "Update" | "Delete" > = { - [K in `${Lowercase}Handler`]: SmartRouteHandler + [K in (keyof T[A]) & L as `${Uncapitalize}${K}`]: (options: + & { + project: ProjectJson, + user?: UsersCrud["Admin"]["Read"], + } + & (L extends "Create" | "List" ? Partial> : yup.InferType) + & (K extends "Read" ? {} : { + data: K extends "Read" ? void : T[A][K], + }) + ) => Promise<"Read" extends keyof T[A] ? (K extends "Delete" ? void : T[A]["Read"]) : void> }; -export function createCrudHandlers, any>>( +export type CrudHandlers< + T extends CrudTypeOf, + PS extends ParamsSchema, + L extends "Create" | "Read" | "List" | "Update" | "Delete", +> = +& { + [K in `${Uncapitalize}Handler`]: SmartRouteHandler +} +& CrudHandlerDirectByAccess<"Client", T, PS, L> +& CrudHandlerDirectByAccess<"Server", T, PS, L> +& CrudHandlerDirectByAccess<"Admin", T, PS, L>; + +export function createCrudHandlers, PS>>( crud: S, options: O, -): CrudHandlersFromOptions { +): CrudHandlersFromOptions, PS, O> { const optionsAsPartial = options as Partial, any>>; const operations = [ ["GET", "Read"], ["GET", "List"], ["POST", "Create"], - ["PUT", "Update"], + ["PATCH", "Update"], ["DELETE", "Delete"], ] as const; const accessTypes = ["client", "server", "admin"] as const; - const paramsSchema = yup.object(Object.fromEntries( - options.paramNames.map((paramName) => [paramName, yup.string().required()]) - )); + const paramsSchema = options.paramsSchema; return Object.fromEntries( operations.filter(([_, crudOperation]) => optionsAsPartial[`on${crudOperation}`] !== undefined) - .map(([httpMethod, crudOperation]) => { + .flatMap(([httpMethod, crudOperation]) => { const getSchemas = (accessType: "admin" | "server" | "client") => { const input = typedIncludes(["Read", "List"] as const, crudOperation) @@ -95,7 +117,10 @@ export function createCrudHandlers { - const adminSchemas = getSchemas("admin"); - const accessSchemas = getSchemas(accessType); + const aat = new Map(availableAccessTypes.map((accessType) => { + const adminSchemas = getSchemas("admin"); + const accessSchemas = getSchemas(accessType); + return [ + accessType, + { + accessSchemas, + adminSchemas, + invoke: async (options: { params: yup.InferType | Partial>, data: any, auth: SmartRequestAuth }) => { + const actualParamsSchema = typedIncludes(["List", "Create"], crudOperation) ? paramsSchema.partial() : paramsSchema; + const paramsValidated = await validate(options.params, actualParamsSchema, "Params validation"); + + const adminData = await validate(options.data, adminSchemas.input, "Input validation"); + + const result = await optionsAsPartial[`on${crudOperation}`]?.({ + params: paramsValidated, + data: adminData, + auth: options.auth, + }); + + const resultAdminValidated = await validate(result, adminSchemas.output, "Result admin validation"); + const resultAccessValidated = await validate(resultAdminValidated, accessSchemas.output, `Result ${accessType} validation`); + + return resultAccessValidated; + }, + }, + ]; + })); + const routeHandler = createSmartRouteHandler( + [...aat], + ([accessType, { invoke, accessSchemas, adminSchemas }]) => { const frw = routeHandlerTypeHelper({ request: yup.object({ auth: yup.object({ @@ -121,50 +172,79 @@ export function createCrudHandlers { const data = req.body; - const adminData = await validate(data, adminSchemas.input, "Input validation"); - - const result = await optionsAsPartial[`on${crudOperation}`]?.({ - params: req.params, - data: adminData, + + const result = await invoke({ + params: req.params as any, + data, auth: fullReq.auth ?? throwErr("Auth not found in CRUD handler; this should never happen! (all clients are at least client to access CRUD handler)"), }); - const resultAdminValidated = await validate(result, adminSchemas.output, "Result admin validation"); - const resultAccessValidated = await validate(resultAdminValidated, accessSchemas.output, `Result ${accessType} validation`); - return { statusCode: crudOperation === "Create" ? 201 : 200, headers: { location: crudOperation === "Create" ? [req.url] : undefined, }, - bodyType: "json", - body: resultAccessValidated, + bodyType: crudOperation === "Delete" ? "empty" : "json", + body: result, }; }, }); return { ...frw, - metadata: options.metadataMap?.[typedToLowercase(crudOperation)], + metadata: crud[accessType][`${typedToLowercase(crudOperation)}Docs`], }; } ); - return [`${typedToLowercase(crudOperation)}Handler`, routeHandler]; + return [ + [`${typedToLowercase(crudOperation)}Handler`, routeHandler], + ...[...aat].map(([accessType, { invoke }]) => ( + [ + `${accessType}${crudOperation}`, + async ({ user, project, data, ...params }: { + params: yup.InferType, + project: ProjectJson, + user?: UsersCrud["Admin"]["Read"], + data: any, + }) => { + try { + return await invoke({ + params, + data, + auth: { + user, + project, + type: accessType, + }, + }); + } catch (error) { + throw new CrudHandlerInvokationError(error); + } + }, + ] + )), + ]; }) ) as any; } +export class CrudHandlerInvokationError extends Error { + constructor(public readonly cause: unknown) { + super("Error while invoking CRUD handler programmatically. This is a wrapper error to prevent caught errors (eg. StatusError) from being caught by outer catch blocks. Check the `cause` property.\n\nOriginal error: " + cause, { cause }); + } +} + async function validate(obj: unknown, schema: yup.ISchema, name: string): Promise { try { return await schema.validate(obj, { diff --git a/apps/backend/src/route-handlers/prisma-handler.tsx b/apps/backend/src/route-handlers/prisma-handler.tsx index 66b9c6ae2..b5a761b7d 100644 --- a/apps/backend/src/route-handlers/prisma-handler.tsx +++ b/apps/backend/src/route-handlers/prisma-handler.tsx @@ -1,10 +1,12 @@ import { CrudSchema, CrudTypeOf } from "@stackframe/stack-shared/dist/crud"; -import { CrudHandlers, RouteHandlerMetadataMap, createCrudHandlers } from "./crud-handler"; +import { CrudHandlers, ParamsSchema, createCrudHandlers } from "./crud-handler"; import { SmartRequestAuth } from "./smart-request"; import { Prisma } from "@prisma/client"; import { GetResult } from "@prisma/client/runtime/library"; import { StatusError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; import { prismaClient } from "@/prisma-client"; +import * as yup from "yup"; +import { typedAssign } from "@stackframe/stack-shared/dist/utils/objects"; type AllPrismaModelNames = Prisma.TypeMap["meta"]["modelProps"]; type WhereUnique = Prisma.TypeMap["model"][Capitalize]["operations"]["findUniqueOrThrow"]["args"]["where"]; @@ -15,18 +17,21 @@ type BaseFields = Where & Partial>; type PRead, I extends Include> = GetResult]["payload"], { where: W, include: I }, "findUniqueOrThrow">; type PUpdate = Prisma.TypeMap["model"][Capitalize]["operations"]["update"]["args"]["data"]; type PCreate = Prisma.TypeMap["model"][Capitalize]["operations"]["create"]["args"]["data"]; +type PEitherWrite = (PCreate | PUpdate) & Partial & PUpdate>; -type Context = { - params: Record, +type Context = { + params: [AllParams] extends [true] ? yup.InferType : Partial>, auth: SmartRequestAuth, }; type CRead> = T extends { Admin: { Read: infer R } } ? R : never; type CCreate> = T extends { Admin: { Create: infer R } } ? R : never; type CUpdate> = T extends { Admin: { Update: infer R } } ? R : never; -type CEitherWrite> = CCreate | CUpdate; +type CEitherWrite> = (CCreate | CUpdate) & Partial & CUpdate>; -export type CrudHandlersFromCrudType> = CrudHandlers< +type CrudHandlersFromCrudType, PS extends ParamsSchema> = CrudHandlers< + T, + PS, | ("Create" extends keyof T["Admin"] ? "Create" : never) | ("Read" extends keyof T["Admin"] ? "Read" : never) | ("Read" extends keyof T["Admin"] ? "List" : never) @@ -34,10 +39,22 @@ export type CrudHandlersFromCrudType> = CrudHan | ("Delete" extends keyof T["Admin"] ? "Delete" : never) >; +type ExtraDataFromCrudType< + S extends CrudSchema, + PrismaModelName extends AllPrismaModelNames, + PS extends ParamsSchema, + W extends Where, + I extends Include, + B extends BaseFields, +> = { + getInclude(params: yup.InferType, context: Pick, "auth">): Promise, + transformPrismaToCrudObject(prisma: PRead, params: yup.InferType, context: Pick, "auth">): Promise>>, +}; + export function createPrismaCrudHandlers< S extends CrudSchema, PrismaModelName extends AllPrismaModelNames, - ParamName extends string, + PS extends ParamsSchema, W extends Where, I extends Include, B extends BaseFields, @@ -45,16 +62,17 @@ export function createPrismaCrudHandlers< crudSchema: S, prismaModelName: PrismaModelName, options: & { - paramNames: ParamName[], - baseFields: (context: Context) => Promise, - where?: (context: Context) => Promise, - whereUnique?: (context: Context) => Promise>, - include: (context: Context) => Promise, - crudToPrisma?: ((crud: CEitherWrite>, context: Context) => Promise | Omit, keyof B>>), - prismaToCrud?: (prisma: PRead, context: Context) => Promise>>, + paramsSchema: PS, + baseFields: (context: Context) => Promise, + where?: (context: Context) => Promise, + whereUnique?: (context: Context) => Promise>, + include: (context: Context) => Promise, + crudToPrisma?: + & ((crud: CEitherWrite>, context: Context) => Promise>), + prismaToCrud?: (prisma: PRead, context: Context) => Promise>>, + onCreate?: (prisma: PRead, context: Context) => Promise, fieldMapping?: any, - createNotFoundError?: (context: Context) => Error, - metadataMap?: RouteHandlerMetadataMap, + notFoundError?: (context: Context) => Error, } & ( | { @@ -68,10 +86,10 @@ export function createPrismaCrudHandlers< fieldMapping: {}, } ), -): CrudHandlersFromCrudType> { - const wrapper = (func: (data: any, context: Context, queryBase: any) => Promise): (opts: { params: Record, data?: unknown, auth: SmartRequestAuth }) => Promise => { +): CrudHandlersFromCrudType, PS> & ExtraDataFromCrudType { + const wrapper = (allParams: AllParams, func: (data: any, context: Context, queryBase: any) => Promise): (opts: Context & { data?: unknown }) => Promise => { return async (req) => { - const context: Context = { + const context: Context = { params: req.params, auth: req.auth, }; @@ -81,7 +99,7 @@ export function createPrismaCrudHandlers< return await func(req.data, context, { where: whereBase, include: includeBase }); } catch (e) { if ((e as any)?.code === 'P2025') { - throw (options.createNotFoundError ?? (() => new StatusError(StatusError.NotFound)))(context); + throw (options.notFoundError ?? (() => new StatusError(StatusError.NotFound)))(context); } throw e; } @@ -91,9 +109,9 @@ export function createPrismaCrudHandlers< const prismaToCrud = options.prismaToCrud ?? throwErr("missing prismaToCrud is not yet implemented"); const crudToPrisma = options.crudToPrisma ?? throwErr("missing crudToPrisma is not yet implemented"); - return createCrudHandlers(crudSchema, { - paramNames: options.paramNames, - onRead: wrapper(async (data, context) => { + return typedAssign(createCrudHandlers(crudSchema, { + paramsSchema: options.paramsSchema, + onRead: wrapper(true, async (data, context) => { const prisma = await (prismaClient[prismaModelName].findUniqueOrThrow as any)({ include: await options.include(context), where: { @@ -104,7 +122,7 @@ export function createPrismaCrudHandlers< }); return await prismaToCrud(prisma, context); }), - onList: wrapper(async (data, context) => { + onList: wrapper(false, async (data, context) => { const prisma: any[] = await (prismaClient[prismaModelName].findMany as any)({ include: await options.include(context), where: { @@ -112,9 +130,12 @@ export function createPrismaCrudHandlers< ...await options.where?.(context), }, }); - return await Promise.all(prisma.map((p) => prismaToCrud(p, context))); + const items = await Promise.all(prisma.map((p) => prismaToCrud(p, context))); + return { + items, + }; }), - onCreate: wrapper(async (data, context) => { + onCreate: wrapper(false, async (data, context) => { const prisma = await (prismaClient[prismaModelName].create as any)({ include: await options.include(context), data: { @@ -122,9 +143,12 @@ export function createPrismaCrudHandlers< ...await crudToPrisma(data, context), }, }); + // TODO pass the same transaction to onCreate as the one that creates the user row + // we should probably do this with all functions and pass a transaction around in the context + await options.onCreate?.(prisma, context); return await prismaToCrud(prisma, context); }), - onUpdate: wrapper(async (data, context) => { + onUpdate: wrapper(true, async (data, context) => { const prisma = await (prismaClient[prismaModelName].update as any)({ include: await options.include(context), where: { @@ -136,7 +160,7 @@ export function createPrismaCrudHandlers< }); return await prismaToCrud(prisma, context); }), - onDelete: wrapper(async (data, context) => { + onDelete: wrapper(true, async (data, context) => { await (prismaClient[prismaModelName].delete as any)({ include: await options.include(context), where: { @@ -146,6 +170,18 @@ export function createPrismaCrudHandlers< }, }); }), - metadataMap: options.metadataMap, - }); + }), { + getInclude(params, context) { + return options.include({ + ...context, + params, + }); + }, + transformPrismaToCrudObject(prisma, params, context) { + return prismaToCrud(prisma, { + ...context, + params, + }); + }, + } satisfies ExtraDataFromCrudType); } diff --git a/apps/backend/src/route-handlers/smart-request.tsx b/apps/backend/src/route-handlers/smart-request.tsx index 6e017dd6e..913e0017f 100644 --- a/apps/backend/src/route-handlers/smart-request.tsx +++ b/apps/backend/src/route-handlers/smart-request.tsx @@ -3,25 +3,29 @@ import "../polyfills"; import { NextRequest } from "next/server"; import { StackAssertionError, StatusError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; import * as yup from "yup"; -import { DeepPartial } from "@stackframe/stack-shared/dist/utils/objects"; +import { deepPlainClone } from "@stackframe/stack-shared/dist/utils/objects"; import { groupBy, typedIncludes } from "@stackframe/stack-shared/dist/utils/arrays"; -import { KnownErrors, ProjectJson, ServerUserJson } from "@stackframe/stack-shared"; -import { IsAny } from "@stackframe/stack-shared/dist/utils/types"; +import { KnownErrors, ProjectJson } from "@stackframe/stack-shared"; import { checkApiKeySet } from "@/lib/api-keys"; import { updateProject, whyNotProjectAdmin } from "@/lib/projects"; -import { updateServerUser } from "@/lib/users"; import { decodeAccessToken } from "@/lib/tokens"; import { deindent } from "@stackframe/stack-shared/dist/utils/strings"; +import { ReplaceFieldWithOwnUserId, StackAdaptSentinel } from "@stackframe/stack-shared/dist/schema-fields"; +import { UsersCrud } from "@stackframe/stack-shared/dist/interface/crud/users"; +import { usersCrudHandlers } from "@/app/api/v1/users/crud"; const allowedMethods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] as const; export type SmartRequestAuth = { project: ProjectJson, - user: ServerUserJson | null, - projectAccessType: "key" | "internal-user-token", + user?: UsersCrud["Admin"]["Read"] | undefined, type: "client" | "server" | "admin", }; +export type DeepPartialSmartRequestWithSentinel = (T extends object ? { + [P in keyof T]?: DeepPartialSmartRequestWithSentinel +} : T) | StackAdaptSentinel; + export type SmartRequest = { auth: SmartRequestAuth | null, url: string, @@ -33,27 +37,75 @@ export type SmartRequest = { }; export type MergeSmartRequest = - IsAny extends true ? MSQ : ( - T extends object ? (MSQ extends object ? { [K in keyof T]: K extends keyof MSQ ? MergeSmartRequest : undefined } : MSQ) - : T + StackAdaptSentinel extends T ? NonNullable | (MSQ & Exclude) : ( + T extends object ? (MSQ extends object ? { [K in keyof T & keyof MSQ]: MergeSmartRequest } : (T & MSQ)) + : (T & MSQ) ); -async function validate(obj: unknown, schema: yup.Schema, req: NextRequest): Promise { +async function validate(obj: SmartRequest, schema: yup.Schema, req: NextRequest | null): Promise { try { return await schema.validate(obj, { abortEarly: false, stripUnknown: true, }); } catch (error) { - if (error instanceof yup.ValidationError) { - throw new KnownErrors.SchemaError( - deindent` - Request validation failed on ${req.method} ${req.nextUrl.pathname}: - ${(error.inner.length ? error.inner : [error]).map(e => deindent` - - ${e.message} - `).join("\n")} - `, - ); + if (error instanceof ReplaceFieldWithOwnUserId) { + // parse yup path + let pathRemaining = error.path; + const fieldPath = []; + while (pathRemaining.length > 0) { + if (pathRemaining.startsWith("[")) { + const index = pathRemaining.indexOf("]"); + if (index < 0) throw new StackAssertionError("Invalid path"); + fieldPath.push(JSON.parse(pathRemaining.slice(1, index))); + pathRemaining = pathRemaining.slice(index + 1); + } else { + let dotIndex = pathRemaining.indexOf("."); + if (dotIndex === -1) dotIndex = pathRemaining.length; + fieldPath.push(pathRemaining.slice(0, dotIndex)); + pathRemaining = pathRemaining.slice(dotIndex + 1); + } + } + + const newObj = deepPlainClone(obj); + let it = newObj; + for (const field of fieldPath.slice(0, -1)) { + if (!Object.prototype.hasOwnProperty.call(it, field)) { + throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`); + } + it = (it as any)[field]; + } + (it as any)[fieldPath[fieldPath.length - 1]] = obj.auth?.user?.id ?? throwErr(new KnownErrors.CannotGetOwnUserWithoutUser()); + + return await validate(newObj, schema, req); + } else if (error instanceof yup.ValidationError) { + if (req === null) { + // we weren't called by a HTTP request, so it must be a logical error in a manual invokation + throw new StackAssertionError("Request validation failed", {}, { cause: error }); + } else { + const inners = error.inner.length ? error.inner : [error]; + const description = schema.describe(); + + for (const inner of inners) { + if (inner.path === "auth" && inner.type === "nullable" && inner.value === null) { + throw new KnownErrors.AccessTypeRequired(); + } + if (inner.path === "auth.type" && inner.type === "oneOf") { + // Project access type not sufficient + const authTypeField = ((description as yup.SchemaObjectDescription).fields["auth"] as yup.SchemaObjectDescription).fields["type"] as yup.SchemaDescription; + throw new KnownErrors.InsufficientAccessType(inner.value, authTypeField.oneOf as any[]); + } + } + + throw new KnownErrors.SchemaError( + deindent` + Request validation failed on ${req.method} ${req.nextUrl.pathname}: + ${inners.map(e => deindent` + - ${e.message} + `).join("\n")} + `, + ); + } } throw error; } @@ -106,12 +158,13 @@ async function parseBody(req: NextRequest, bodyBuffer: ArrayBuffer): Promise { const projectId = req.headers.get("x-stack-project-id"); - let requestType = req.headers.get("x-stack-request-type"); + let requestType = req.headers.get("x-stack-access-type"); const publishableClientKey = req.headers.get("x-stack-publishable-client-key"); const secretServerKey = req.headers.get("x-stack-secret-server-key"); const superSecretAdminKey = req.headers.get("x-stack-super-secret-admin"); const adminAccessToken = req.headers.get("x-stack-admin-access-token"); - const authorization = req.headers.get("authorization"); + const accessToken = req.headers.get("x-stack-access-token"); + const refreshToken = req.headers.get("x-stack-refresh-token"); const eitherKeyOrToken = !!(publishableClientKey || secretServerKey || superSecretAdminKey || adminAccessToken); @@ -188,32 +241,30 @@ async function parseAuth(req: NextRequest): Promise { } let user = null; - if (authorization) { - const decodedAccessToken = await decodeAccessToken(authorization.split(" ")[1]); + if (accessToken) { + const decodedAccessToken = await decodeAccessToken(accessToken); const { userId, projectId: accessTokenProjectId } = decodedAccessToken; if (accessTokenProjectId !== projectId) { throw new KnownErrors.InvalidProjectForAccessToken(); } - user = await updateServerUser( - projectId, + user = await usersCrudHandlers.adminRead({ + project, userId, - {}, - ); + }); } return { project, - user, - projectAccessType, + user: user ?? undefined, type: requestType, }; } -export async function createLazyRequestParser>(req: NextRequest, bodyBuffer: ArrayBuffer, schema: yup.Schema, options?: { params: Record }): Promise<() => Promise<[T, SmartRequest]>> { +export async function createSmartRequest(req: NextRequest, bodyBuffer: ArrayBuffer, options?: { params: Record }): Promise { const urlObject = new URL(req.url); - const toValidate: SmartRequest = { + return { url: req.url, method: typedIncludes(allowedMethods, req.method) ? req.method : throwErr(new StatusError(405, "Method not allowed")), body: await parseBody(req, bodyBuffer), @@ -224,22 +275,9 @@ export async function createLazyRequestParser [await validate(toValidate, schema, req), toValidate]; + } satisfies SmartRequest; } -export async function deprecatedParseRequest & { headers: Record }>>(req: NextRequest, schema: yup.Schema, options?: { params: Record }): Promise { - const urlObject = new URL(req.url); - const toValidate: Omit & { headers: Record } = { - url: req.url, - method: typedIncludes(allowedMethods, req.method) ? req.method : throwErr(new StatusError(405, "Method not allowed")), - body: await parseBody(req, await req.arrayBuffer()), - headers: Object.fromEntries([...req.headers.entries()].map(([k, v]) => [k.toLowerCase(), v])), - query: Object.fromEntries(urlObject.searchParams.entries()), - params: options?.params ?? {}, - auth: null, - }; - - return await validate(toValidate, schema, req); +export async function validateSmartRequest(nextReq: NextRequest | null, smartReq: SmartRequest, schema: yup.Schema): Promise { + return await validate(smartReq, schema, nextReq); } diff --git a/apps/backend/src/route-handlers/smart-response.tsx b/apps/backend/src/route-handlers/smart-response.tsx index 0e14bcac1..53282c9e1 100644 --- a/apps/backend/src/route-handlers/smart-response.tsx +++ b/apps/backend/src/route-handlers/smart-response.tsx @@ -4,6 +4,7 @@ import { NextRequest } from "next/server"; import * as yup from "yup"; import { Json } from "@stackframe/stack-shared/dist/utils/json"; import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors"; +import { deepPlainEquals } from "@stackframe/stack-shared/dist/utils/objects"; export type SmartResponse = { statusCode: number, @@ -11,30 +12,38 @@ export type SmartResponse = { } & ( | { bodyType?: undefined, - body?: ArrayBuffer | Json, + body?: ArrayBuffer | Json | undefined, + } + | { + bodyType: "empty", + body: undefined, } | { bodyType: "text", - body?: string, + body: string, } | { bodyType: "json", - body?: Json, + body: Json, } | { bodyType: "binary", - body?: ArrayBuffer, + body: ArrayBuffer, + } + | { + bodyType: "success", + body?: undefined, } ); -async function validate(req: NextRequest, obj: unknown, schema: yup.Schema): Promise { +async function validate(req: NextRequest | null, obj: unknown, schema: yup.Schema): Promise { try { return await schema.validate(obj, { abortEarly: false, stripUnknown: true, }); } catch (error) { - throw new StackAssertionError(`Error occured during ${req.url} response validation: ${error}`, { obj, schema, error }, { cause: error }); + throw new StackAssertionError(`Error occured during ${req ? `${req.method} ${req.url}` : "a custom endpoint invokation's"} response validation: ${error}`, { obj, schema, error }, { cause: error }); } } @@ -46,37 +55,48 @@ function isBinaryBody(body: unknown): body is BodyInit { || ArrayBuffer.isView(body); } -export async function createResponse(req: NextRequest, requestId: string, obj: T, schema: yup.Schema): Promise { +export async function createResponse(req: NextRequest | null, requestId: string, obj: T, schema: yup.Schema): Promise { const validated = await validate(req, obj, schema); let status = validated.statusCode; const headers = new Map; let arrayBufferBody; - if (obj.body === undefined) { - arrayBufferBody = new ArrayBuffer(0); - } else { - const bodyType = validated.bodyType ?? (isBinaryBody(validated.body) ? "binary" : "json"); - switch (bodyType) { - case "json": { - headers.set("content-type", ["application/json; charset=utf-8"]); - arrayBufferBody = new TextEncoder().encode(JSON.stringify(validated.body)); - break; - } - case "text": { - headers.set("content-type", ["text/plain; charset=utf-8"]); - if (typeof validated.body !== "string") throw new Error(`Invalid body, expected string, got ${validated.body}`); - arrayBufferBody = new TextEncoder().encode(validated.body); - break; - } - case "binary": { - if (!isBinaryBody(validated.body)) throw new Error(`Invalid body, expected ArrayBuffer, got ${validated.body}`); - arrayBufferBody = validated.body; - break; - } - default: { - throw new Error(`Invalid body type: ${bodyType}`); + + const bodyType = validated.bodyType ?? (validated.body === undefined ? "empty" : isBinaryBody(validated.body) ? "binary" : "json"); + switch (bodyType) { + case "empty": { + arrayBufferBody = new ArrayBuffer(0); + break; + } + case "json": { + if (validated.body === undefined || !deepPlainEquals(validated.body, JSON.parse(JSON.stringify(validated.body)))) { + throw new StackAssertionError("Invalid JSON body is not JSON", { body: validated.body }); } + headers.set("content-type", ["application/json; charset=utf-8"]); + arrayBufferBody = new TextEncoder().encode(JSON.stringify(validated.body)); + break; + } + case "text": { + headers.set("content-type", ["text/plain; charset=utf-8"]); + if (typeof validated.body !== "string") throw new Error(`Invalid body, expected string, got ${validated.body}`); + arrayBufferBody = new TextEncoder().encode(validated.body); + break; + } + case "binary": { + if (!isBinaryBody(validated.body)) throw new Error(`Invalid body, expected ArrayBuffer, got ${validated.body}`); + arrayBufferBody = validated.body; + break; + } + case "success": { + headers.set("content-type", ["application/json; charset=utf-8"]); + arrayBufferBody = new TextEncoder().encode(JSON.stringify({ + success: true, + })); + break; + } + default: { + throw new Error(`Invalid body type: ${bodyType}`); } } @@ -90,7 +110,7 @@ export async function createResponse(req: NextRequest, // If the x-stack-override-error-status header is given, override error statuses to 200 - if (req.headers.has("x-stack-override-error-status") && status >= 400 && status < 600) { + if (req?.headers.has("x-stack-override-error-status") && status >= 400 && status < 600) { status = 200; headers.set("x-stack-actual-status", [validated.statusCode.toString()]); } diff --git a/apps/backend/src/route-handlers/smart-route-handler.tsx b/apps/backend/src/route-handlers/smart-route-handler.tsx index 8022e48ed..4454cfe60 100644 --- a/apps/backend/src/route-handlers/smart-route-handler.tsx +++ b/apps/backend/src/route-handlers/smart-route-handler.tsx @@ -3,16 +3,20 @@ import "../polyfills"; import { NextRequest } from "next/server"; import { StackAssertionError, StatusError, captureError } from "@stackframe/stack-shared/dist/utils/errors"; import * as yup from "yup"; -import { DeepPartial } from "@stackframe/stack-shared/dist/utils/objects"; import { generateSecureRandomString } from "@stackframe/stack-shared/dist/utils/crypto"; import { KnownErrors } from "@stackframe/stack-shared/dist/known-errors"; import { runAsynchronously, wait } from "@stackframe/stack-shared/dist/utils/promises"; -import { MergeSmartRequest, SmartRequest, createLazyRequestParser } from "./smart-request"; +import { MergeSmartRequest, SmartRequest, DeepPartialSmartRequestWithSentinel, createSmartRequest, validateSmartRequest } from "./smart-request"; import { SmartResponse, createResponse } from "./smart-response"; +import { EndpointDocumentation } from "@stackframe/stack-shared/dist/crud"; +import { getNodeEnvironment } from "@stackframe/stack-shared/dist/utils/env"; class InternalServerError extends StatusError { - constructor() { - super(StatusError.InternalServerError); + constructor(error: unknown) { + super( + StatusError.InternalServerError, + ...getNodeEnvironment() === "development" ? [`Internal Server Error. The error message follows, but will be stripped in production. ${error}`] : [], + ); } } @@ -41,14 +45,14 @@ function catchError(error: unknown): StatusError { if (error instanceof StatusError) return error; captureError(`route-handler`, error); - return new InternalServerError(); + return new InternalServerError(error); } /** * Catches any errors thrown in the handler and returns a 500 response with the thrown error message. Also logs the * request details. */ -export function deprecatedSmartRouteHandler(handler: (req: NextRequest, options: any, requestId: string) => Promise): (req: NextRequest, options: any) => Promise { +function handleApiRequest(handler: (req: NextRequest, options: any, requestId: string) => Promise): (req: NextRequest, options: any) => Promise { return async (req: NextRequest, options: any) => { const requestId = generateSecureRandomString(80); let hasRequestFinished = false; @@ -106,58 +110,57 @@ export function deprecatedSmartRouteHandler(handler: (req: NextRequest, options: }; }; -export type SmartRouteHandlerOverloadMetadata = { - summary: string, - description: string, - tags: string[], -}; +export type SmartRouteHandlerOverloadMetadata = EndpointDocumentation; export type SmartRouteHandlerOverload< - Req extends DeepPartial, + Req extends DeepPartialSmartRequestWithSentinel, Res extends SmartResponse, > = { metadata?: SmartRouteHandlerOverloadMetadata, request: yup.Schema, response: yup.Schema, - handler: (req: Req & MergeSmartRequest, fullReq: SmartRequest) => Promise, + handler: (req: MergeSmartRequest, fullReq: SmartRequest) => Promise, }; export type SmartRouteHandlerOverloadGenerator< OverloadParam, - Req extends DeepPartial, + Req extends DeepPartialSmartRequestWithSentinel, Res extends SmartResponse, > = (param: OverloadParam) => SmartRouteHandlerOverload; export type SmartRouteHandler< OverloadParam = unknown, - Req extends DeepPartial = DeepPartial, + Req extends DeepPartialSmartRequestWithSentinel = DeepPartialSmartRequestWithSentinel, Res extends SmartResponse = SmartResponse, > = ((req: NextRequest, options: any) => Promise) & { overloads: Map>, + invoke: (smartRequest: SmartRequest) => Promise, } -const smartRouteHandlerSymbol = Symbol("smartRouteHandler"); +function getSmartRouteHandlerSymbol() { + return Symbol.for("stack-smartRouteHandler"); +} export function isSmartRouteHandler(handler: any): handler is SmartRouteHandler { - return handler?.[smartRouteHandlerSymbol] === true; + return handler?.[getSmartRouteHandlerSymbol()] === true; } export function createSmartRouteHandler< - Req extends DeepPartial, + Req extends DeepPartialSmartRequestWithSentinel, Res extends SmartResponse, >( handler: SmartRouteHandlerOverload, ): SmartRouteHandler export function createSmartRouteHandler< OverloadParam, - Req extends DeepPartial, + Req extends DeepPartialSmartRequestWithSentinel, Res extends SmartResponse, >( overloadParams: readonly OverloadParam[], overloadGenerator: SmartRouteHandlerOverloadGenerator ): SmartRouteHandler export function createSmartRouteHandler< - Req extends DeepPartial, + Req extends DeepPartialSmartRequestWithSentinel, Res extends SmartResponse, >( ...args: [readonly unknown[], SmartRouteHandlerOverloadGenerator] | [SmartRouteHandlerOverload] @@ -173,15 +176,13 @@ export function createSmartRouteHandler< throw new StackAssertionError("Duplicate overload parameters"); } - return Object.assign(deprecatedSmartRouteHandler(async (req, options, requestId) => { + const invoke = async (nextRequest: NextRequest | null, requestId: string, smartRequest: SmartRequest) => { const reqsParsed: [[Req, SmartRequest], SmartRouteHandlerOverload][] = []; const reqsErrors: unknown[] = []; - const bodyBuffer = await req.arrayBuffer(); - for (const [overloadParam, handler] of overloads.entries()) { - const requestParser = await createLazyRequestParser(req, bodyBuffer, handler.request, options); + for (const [overloadParam, overload] of overloads.entries()) { try { - const parserRes = await requestParser(); - reqsParsed.push([parserRes, handler]); + const parsedReq = await validateSmartRequest(nextRequest, smartRequest, overload.request); + reqsParsed.push([[parsedReq, smartRequest], overload]); } catch (e) { reqsErrors.push(e); } @@ -191,7 +192,7 @@ export function createSmartRouteHandler< throw reqsErrors[0]; } else { const caughtErrors = reqsErrors.map(e => catchError(e)); - throw new KnownErrors.AllOverloadsFailed(caughtErrors.map(e => e.toHttpJson())); + throw createOverloadsError(caughtErrors); } } @@ -201,19 +202,73 @@ export function createSmartRouteHandler< let smartRes = await handler.handler(smartReq as any, fullReq); - return await createResponse(req, requestId, smartRes, handler.response); + return await createResponse(nextRequest, requestId, smartRes, handler.response); + }; + + return Object.assign(handleApiRequest(async (req, options, requestId) => { + const bodyBuffer = await req.arrayBuffer(); + const smartRequest = await createSmartRequest(req, bodyBuffer, options); + return await invoke(req, requestId, smartRequest); }), { - [smartRouteHandlerSymbol]: true, + [getSmartRouteHandlerSymbol()]: true, + invoke: (smartRequest: SmartRequest) => invoke(null, "custom-endpoint-invokation", smartRequest), overloads, }); } +function createOverloadsError(errors: StatusError[]) { + return tryMergingOverloadErrors(errors) ?? new KnownErrors.AllOverloadsFailed(errors.map(e => e.toHttpJson())); +} + +function tryMergingOverloadErrors(errors: StatusError[]): StatusError | null { + if (errors.length > 6) { + // TODO fix this + throw new StackAssertionError("Too many overloads failed, refusing to trying to merge them as it would be computationally expensive and could be used for a DoS attack. Fix this if we ever have an endpoint with > 8 overloads"); + } else if (errors.length === 0) { + throw new StackAssertionError("No errors to merge"); + } else if (errors.length === 1) { + return errors[0]; + } else if (errors.length === 2) { + const [a, b] = errors; + + // Merge errors with the same JSON + if (JSON.stringify(a.toHttpJson()) === JSON.stringify(b.toHttpJson())) { + return a; + } + + // Merge "InsufficientAccessType" errors + if ( + a instanceof KnownErrors.InsufficientAccessType + && b instanceof KnownErrors.InsufficientAccessType + && a.constructorArgs[0] === b.constructorArgs[0] + ) { + return new KnownErrors.InsufficientAccessType(a.constructorArgs[0], [...new Set([...a.constructorArgs[1], ...b.constructorArgs[1]])]); + } + + return null; + } else { + // brute-force all combinations recursively + for (let i = 0; i < errors.length; i++) { + const errorsWithoutCurrent = [...errors]; + errorsWithoutCurrent.splice(i, 1); + const mergedWithoutCurrent = tryMergingOverloadErrors(errorsWithoutCurrent); + if (mergedWithoutCurrent !== null) { + const merged = tryMergingOverloadErrors([errors[i], mergedWithoutCurrent]); + if (merged !== null) { + return merged; + } + } + } + return null; + } +} + /** * needed in the multi-overload smartRouteHandler for weird TypeScript reasons that I don't understand * * if you can remove this wherever it's used without causing type errors, it's safe to remove */ -export function routeHandlerTypeHelper, Res extends SmartResponse>(handler: { +export function routeHandlerTypeHelper(handler: { request: yup.Schema, response: yup.Schema, handler: (req: Req & MergeSmartRequest, fullReq: SmartRequest) => Promise, diff --git a/apps/backend/src/route-handlers/verification-code-handler.tsx b/apps/backend/src/route-handlers/verification-code-handler.tsx new file mode 100644 index 000000000..b6398e238 --- /dev/null +++ b/apps/backend/src/route-handlers/verification-code-handler.tsx @@ -0,0 +1,125 @@ +import * as yup from "yup"; +import { SmartRouteHandler, createSmartRouteHandler } from "./smart-route-handler"; +import { SmartResponse } from "./smart-response"; +import { KnownErrors, ProjectJson } from "@stackframe/stack-shared"; +import { prismaClient } from "@/prisma-client"; +import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors"; +import { validateRedirectUrl } from "@/lib/redirect-urls"; +import { generateSecureRandomString } from "@stackframe/stack-shared/dist/utils/crypto"; +import { adaptSchema } from "@stackframe/stack-shared/dist/schema-fields"; +import { VerificationCodeType } from "@prisma/client"; + +type Method = { + email?: string, +}; + +type VerificationCodeHandler = { + sendCode(options: { + project: ProjectJson, + method: Method, + data: Data, + redirectUrl?: RedirectUrl, + expiresInMs?: number, + }): Promise<{ code: string } & ( + RedirectUrl extends undefined ? {} + : RedirectUrl extends string | URL ? { link: URL } + : { link?: URL } + )>, + postHandler: SmartRouteHandler, +}; + +/** + * Make sure to always check that the method is the same as the one in the data. + */ +export function createVerificationCodeHandler(options: { + type: VerificationCodeType, + data: yup.Schema, + response: yup.Schema, + handler(project: ProjectJson, method: Method, data: Data): Promise, +}): VerificationCodeHandler { + return { + async sendCode({ project, method, data, redirectUrl, expiresInMs }) { + if (!method.email) { + throw new StackAssertionError("No method specified"); + } + + const validatedData = await options.data.validate(data, { + strict: true, + }); + + if (redirectUrl !== undefined && !validateRedirectUrl( + redirectUrl, + project.evaluatedConfig.domains, + project.evaluatedConfig.allowLocalhost + )) { + throw new KnownErrors.RedirectUrlNotWhitelisted(); + } + + const verificationCode = await prismaClient.verificationCode.create({ + data: { + projectId: project.id, + type: options.type, + code: generateSecureRandomString(), + redirectUrl: redirectUrl?.toString() ?? undefined, + expiresAt: new Date(Date.now() + (expiresInMs ?? 1000 * 60 * 60 * 24 * 7)), // default: expire after 7 days + data: validatedData as any, + email: method.email, + } + }); + + let link; + if (redirectUrl !== undefined) { + link = new URL(redirectUrl); + link.searchParams.set('code', verificationCode.code); + } + + return { + code: verificationCode.code, + ...(link ? { link: link } : {}), + } as any; + }, + postHandler: createSmartRouteHandler({ + request: yup.object({ + auth: yup.object({ + project: adaptSchema.required(), + }).required(), + body: yup.object({ + code: yup.string().required(), + }).required(), + }), + response: options.response, + async handler({ body: { code }, auth }) { + const verificationCode = await prismaClient.verificationCode.findUnique({ + where: { + projectId_code: { + projectId: auth.project.id, + code, + }, + }, + }); + + if (!verificationCode) throw new KnownErrors.VerificationCodeNotFound(); + if (verificationCode.expiresAt < new Date()) throw new KnownErrors.VerificationCodeExpired(); + if (verificationCode.usedAt) throw new KnownErrors.VerificationCodeAlreadyUsed(); + + const validatedData = await options.data.validate(verificationCode.data, { + strict: true, + }); + + await prismaClient.verificationCode.update({ + where: { + projectId_code: { + projectId: auth.project.id, + code, + }, + }, + data: { + usedAt: new Date(), + }, + }); + + return await options.handler(auth.project, { email: verificationCode.email }, validatedData as any); + }, + }), + }; +} diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json index af3b577e0..716128b42 100644 --- a/apps/dashboard/package.json +++ b/apps/dashboard/package.json @@ -8,17 +8,17 @@ "with-env": "dotenv -c development --", "with-env:prod": "dotenv -c --", "dev": "next dev --port 8101", - "build": "npm run codegen && next build", - "analyze-bundle": "ANALYZE_BUNDLE=1 npm run build", + "build": "pnpm run codegen && next build", + "analyze-bundle": "ANALYZE_BUNDLE=1 pnpm run build", "start": "next start --port 8101", - "codegen": "npm run prisma -- generate", - "psql": "npm run with-env -- bash -c 'psql $STACK_DATABASE_CONNECTION_STRING'", - "prisma": "npm run with-env -- prisma", + "codegen": "pnpm run prisma generate", + "psql": "pnpm run with-env bash -c 'psql $STACK_DATABASE_CONNECTION_STRING'", + "prisma": "pnpm run with-env prisma", "lint": "next lint", - "generate-keys": "npm run with-env -- tsx scripts/generate-keys.ts" + "generate-keys": "pnpm run with-env tsx scripts/generate-keys.ts" }, "prisma": { - "seed": "npm run with-env -- tsx prisma/seed.ts" + "seed": "pnpm run with-env tsx prisma/seed.ts" }, "dependencies": { "@hookform/resolvers": "^3.3.4", @@ -56,12 +56,10 @@ "@radix-ui/react-toggle": "^1.0.3", "@radix-ui/react-toggle-group": "^1.0.4", "@radix-ui/react-tooltip": "^1.0.7", - "@react-email/components": "^0.0.14", - "@react-email/render": "^0.0.12", - "@react-email/tailwind": "^0.0.14", "@sentry/nextjs": "^7.105.0", "@stackframe/stack": "workspace:*", "@stackframe/stack-shared": "workspace:*", + "@stackframe/stack-emails": "workspace:*", "@tanstack/react-table": "^8.17.0", "@types/mdx": "^2", "@vercel/analytics": "^1.2.2", @@ -74,11 +72,9 @@ "date-fns": "^3.6.0", "dotenv-cli": "^7.3.0", "geist": "^1", - "handlebars": "^4.7.8", "highlight.js": "^11.9.0", "input-otp": "^1.2.4", "jose": "^5.2.2", - "lodash": "^4.17.21", "lucide-react": "^0.378.0", "next": "^14.1", "next-themes": "^0.2.1", @@ -91,7 +87,6 @@ "react-colorful": "^5.6.1", "react-day-picker": "^8.10.1", "react-dom": "^18", - "react-email": "2.1.0", "react-hook-form": "^7.51.4", "react-icons": "^5.0.1", "react-resizable-panels": "^2.0.19", @@ -111,7 +106,6 @@ "devDependencies": { "@types/bcrypt": "^5.0.2", "@types/canvas-confetti": "^1.6.4", - "@types/lodash": "^4.17.4", "@types/node": "^20.8.10", "@types/nodemailer": "^6.4.14", "@types/react": "^18.2.66", diff --git a/apps/dashboard/prisma/schema.prisma b/apps/dashboard/prisma/schema.prisma index ac9268466..b96a707a8 100644 --- a/apps/dashboard/prisma/schema.prisma +++ b/apps/dashboard/prisma/schema.prisma @@ -315,6 +315,32 @@ model ProjectUserAuthorizationCode { @@id([projectId, authorizationCode]) } +model VerificationCode { + projectId String + id String @default(uuid()) @db.Uuid + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + type VerificationCodeType + code String + expiresAt DateTime + usedAt DateTime? + redirectUrl String? + + email String + + data Json + + @@id([projectId, id]) + @@unique([projectId, code]) +} + +enum VerificationCodeType { + ONE_TIME_PASSWORD +} + +// @deprecated model ProjectUserEmailVerificationCode { projectId String projectUserId String @db.Uuid @@ -332,6 +358,7 @@ model ProjectUserEmailVerificationCode { @@id([projectId, code]) } +// @deprecated model ProjectUserPasswordResetCode { projectId String projectUserId String @db.Uuid @@ -349,6 +376,7 @@ model ProjectUserPasswordResetCode { @@id([projectId, code]) } +// @deprecated model ProjectUserMagicLinkCode { projectId String projectUserId String @db.Uuid diff --git a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/domains/page-client.tsx b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/domains/page-client.tsx index 59eb3b87c..b0bbbe91c 100644 --- a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/domains/page-client.tsx +++ b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/domains/page-client.tsx @@ -13,6 +13,7 @@ import { SmartFormDialog } from "@/components/form-dialog"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { ActionCell } from "@/components/data-table/elements/cells"; import Typography from "@/components/ui/typography"; +import { urlSchema } from "@stackframe/stack-shared/dist/schema-fields"; function EditDialog(props: { open?: boolean, @@ -40,7 +41,7 @@ function EditDialog(props: { ), }), - domain: yup.string() + domain: urlSchema .matches(/^https?:\/\//, "Origin must start with http:// or https://") .url("Domain must be a valid URL") .notOneOf(props.domains diff --git a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/page-client.tsx b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/page-client.tsx index 5a50e9f78..82ea89f25 100644 --- a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/page-client.tsx +++ b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/page-client.tsx @@ -10,14 +10,14 @@ import { Button } from "@/components/ui/button"; import { FormDialog } from "@/components/form-dialog"; import { EmailConfigJson } from "@stackframe/stack-shared/dist/interface/clientInterface"; import { Project } from "@stackframe/stack"; -import { Reader } from "@/components/email-editor/email-builder"; +import { Reader } from "@stackframe/stack-emails/dist/editor/email-builder/index"; import { Card } from "@/components/ui/card"; import Typography from "@/components/ui/typography"; import { ActionCell } from "@/components/data-table/elements/cells"; import { useRouter } from "@/components/router"; -import { EMAIL_TEMPLATES_METADATA, convertEmailSubjectVariables, convertEmailTemplateMetadataExampleValues, convertEmailTemplateVariables } from "@/email/utils"; +import { EMAIL_TEMPLATES_METADATA, convertEmailSubjectVariables, convertEmailTemplateMetadataExampleValues, convertEmailTemplateVariables } from "@stackframe/stack-emails/dist/utils"; import { useMemo, useState } from "react"; -import { validateEmailTemplateContent } from "@/email/utils"; +import { validateEmailTemplateContent } from "@stackframe/stack-emails/dist/utils"; import { EmailTemplateType } from "@stackframe/stack-shared/dist/interface/serverInterface"; import { ActionDialog } from "@/components/action-dialog"; @@ -95,7 +95,7 @@ function EmailPreview(props: { content: any, type: EmailTemplateType }) { const valid = validateEmailTemplateContent(props.content); if (!valid) return [false, null]; - const metadata = convertEmailTemplateMetadataExampleValues(EMAIL_TEMPLATES_METADATA[props.type], project); + const metadata = convertEmailTemplateMetadataExampleValues(EMAIL_TEMPLATES_METADATA[props.type], project.displayName); const document = convertEmailTemplateVariables(props.content, metadata.variables); return [true, document]; }, [props.content, props.type, project]); @@ -122,7 +122,7 @@ function EmailPreview(props: { content: any, type: EmailTemplateType }) { function SubjectPreview(props: { subject: string, type: EmailTemplateType }) { const project = useAdminApp().useProjectAdmin(); const subject = useMemo(() => { - const metadata = convertEmailTemplateMetadataExampleValues(EMAIL_TEMPLATES_METADATA[props.type], project); + const metadata = convertEmailTemplateMetadataExampleValues(EMAIL_TEMPLATES_METADATA[props.type], project.displayName); return convertEmailSubjectVariables(props.subject, metadata.variables); }, [props.subject, props.type, project]); return subject; diff --git a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/templates/[type]/page-client.tsx b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/templates/[type]/page-client.tsx index e0b3f116c..524b83722 100644 --- a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/templates/[type]/page-client.tsx +++ b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/emails/templates/[type]/page-client.tsx @@ -1,12 +1,11 @@ 'use client'; - -import EmailEditor from "@/components/email-editor/editor"; +import EmailEditor from "@stackframe/stack-emails/dist/editor/editor"; import { EmailTemplateType } from "@stackframe/stack-shared/dist/interface/serverInterface"; import { useAdminApp } from "../../../use-admin-app"; -import { useRouter } from "@/components/router"; -import { EMAIL_TEMPLATES_METADATA, validateEmailTemplateContent } from "@/email/utils"; +import { confirmAlertMessage, useRouter, useRouterConfirm } from "@/components/router"; +import { EMAIL_TEMPLATES_METADATA, validateEmailTemplateContent } from "@stackframe/stack-emails/dist/utils"; import ErrorPage from "@/components/ui/error-page"; -import { TEditorConfiguration } from "@/components/email-editor/documents/editor/core"; +import { TEditorConfiguration } from "@stackframe/stack-emails/dist/editor/documents/editor/core"; import { useToast } from "@/components/ui/use-toast"; import { usePathname } from "next/navigation"; @@ -16,7 +15,9 @@ export default function PageClient(props: { templateType: EmailTemplateType }) { const template = emailTemplates.find((template) => template.type === props.templateType); const router = useRouter(); const pathname = usePathname(); + const { setNeedConfirm } = useRouterConfirm(); const { toast } = useToast(); + const project = app.useProjectAdmin(); if (!template) { // this should not happen, the outer server component should handle this @@ -51,7 +52,10 @@ export default function PageClient(props: { templateType: EmailTemplateType }) { metadata={EMAIL_TEMPLATES_METADATA[props.templateType]} onSave={onSave} onCancel={onCancel} + confirmAlertMessage={confirmAlertMessage} + setNeedConfirm={setNeedConfirm} + projectDisplayName={project.displayName} /> ); -} \ No newline at end of file +} diff --git a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/sidebar-layout.tsx b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/sidebar-layout.tsx index f957fcfe6..18d187d2f 100644 --- a/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/sidebar-layout.tsx +++ b/apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/sidebar-layout.tsx @@ -32,7 +32,7 @@ import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"; import Typography from "@/components/ui/typography"; import { useTheme } from "next-themes"; import { useAdminApp } from "./use-admin-app"; -import { EMAIL_TEMPLATES_METADATA } from "@/email/utils"; +import { EMAIL_TEMPLATES_METADATA } from "@stackframe/stack-emails/dist/utils"; import { Link } from "@/components/link"; type BreadcrumbItem = { item: React.ReactNode, href: string } diff --git a/apps/dashboard/src/app/api/v1/auth/email-verification/route.tsx b/apps/dashboard/src/app/api/v1/auth/email-verification/route.tsx index f9f26acd6..32f4d5036 100644 --- a/apps/dashboard/src/app/api/v1/auth/email-verification/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/email-verification/route.tsx @@ -21,15 +21,15 @@ export const POST = deprecatedSmartRouteHandler(async (req: NextRequest) => { }); if (!codeRecord) { - throw new KnownErrors.EmailVerificationCodeNotFound(); + throw new KnownErrors.VerificationCodeNotFound(); } if (codeRecord.expiresAt < new Date()) { - throw new KnownErrors.EmailVerificationCodeExpired(); + throw new KnownErrors.VerificationCodeExpired(); } if (codeRecord.usedAt) { - throw new KnownErrors.EmailVerificationCodeAlreadyUsed(); + throw new KnownErrors.VerificationCodeAlreadyUsed(); } await prismaClient.projectUser.update({ diff --git a/apps/dashboard/src/app/api/v1/auth/forgot-password/route.tsx b/apps/dashboard/src/app/api/v1/auth/forgot-password/route.tsx index 81fe8d430..03d5ec11b 100644 --- a/apps/dashboard/src/app/api/v1/auth/forgot-password/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/forgot-password/route.tsx @@ -3,7 +3,7 @@ import * as yup from "yup"; import { prismaClient } from "@/prisma-client"; import { deprecatedSmartRouteHandler } from "@/route-handlers/smart-route-handler"; import { deprecatedParseRequest } from "@/route-handlers/smart-request"; -import { sendPasswordResetEmail } from "@/email"; +import { sendPasswordResetEmail } from "@/lib/emails"; import { getApiKeySet, publishableClientKeyHeaderSchema } from "@/lib/api-keys"; import { getProject } from "@/lib/projects"; import { validateUrl } from "@/lib/utils"; diff --git a/apps/dashboard/src/app/api/v1/auth/magic-link-verification/route.tsx b/apps/dashboard/src/app/api/v1/auth/magic-link-verification/route.tsx index 0150f6ac7..3f8821a20 100644 --- a/apps/dashboard/src/app/api/v1/auth/magic-link-verification/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/magic-link-verification/route.tsx @@ -25,15 +25,15 @@ export const POST = deprecatedSmartRouteHandler(async (req: NextRequest) => { }); if (!codeRecord) { - throw new KnownErrors.MagicLinkCodeNotFound(); + throw new KnownErrors.VerificationCodeNotFound(); } if (codeRecord.expiresAt < new Date()) { - throw new KnownErrors.MagicLinkCodeExpired(); + throw new KnownErrors.VerificationCodeExpired(); } if (codeRecord.usedAt) { - throw new KnownErrors.MagicLinkCodeAlreadyUsed(); + throw new KnownErrors.VerificationCodeAlreadyUsed(); } await prismaClient.projectUser.update({ diff --git a/apps/dashboard/src/app/api/v1/auth/password-reset/route.tsx b/apps/dashboard/src/app/api/v1/auth/password-reset/route.tsx index 649f8452a..386828b8d 100644 --- a/apps/dashboard/src/app/api/v1/auth/password-reset/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/password-reset/route.tsx @@ -25,15 +25,15 @@ export const POST = deprecatedSmartRouteHandler(async (req: NextRequest) => { }); if (!codeRecord) { - throw new KnownErrors.PasswordResetCodeNotFound(); + throw new KnownErrors.VerificationCodeNotFound(); } if (codeRecord.expiresAt < new Date()) { - throw new KnownErrors.PasswordResetCodeExpired(); + throw new KnownErrors.VerificationCodeExpired(); } if (codeRecord.usedAt) { - throw new KnownErrors.PasswordResetCodeAlreadyUsed(); + throw new KnownErrors.VerificationCodeAlreadyUsed(); } if (onlyVerifyCode) { diff --git a/apps/dashboard/src/app/api/v1/auth/send-magic-link/route.tsx b/apps/dashboard/src/app/api/v1/auth/send-magic-link/route.tsx index ae5f6b8bb..7a5589e8f 100644 --- a/apps/dashboard/src/app/api/v1/auth/send-magic-link/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/send-magic-link/route.tsx @@ -3,7 +3,7 @@ import * as yup from "yup"; import { prismaClient } from "@/prisma-client"; import { deprecatedSmartRouteHandler } from "@/route-handlers/smart-route-handler"; import { deprecatedParseRequest } from "@/route-handlers/smart-request"; -import { sendMagicLink } from "@/email"; +import { sendMagicLink } from "@/lib/emails"; import { getApiKeySet, publishableClientKeyHeaderSchema } from "@/lib/api-keys"; import { getProject } from "@/lib/projects"; import { validateUrl } from "@/lib/utils"; diff --git a/apps/dashboard/src/app/api/v1/auth/send-verification-email/route.tsx b/apps/dashboard/src/app/api/v1/auth/send-verification-email/route.tsx index 5c6641e33..89719a0a0 100644 --- a/apps/dashboard/src/app/api/v1/auth/send-verification-email/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/send-verification-email/route.tsx @@ -5,7 +5,7 @@ import { deprecatedSmartRouteHandler } from "@/route-handlers/smart-route-handle import { deprecatedParseRequest } from "@/route-handlers/smart-request"; import { checkApiKeySet, publishableClientKeyHeaderSchema } from "@/lib/api-keys"; import { decodeAccessToken, authorizationHeaderSchema } from "@/lib/tokens"; -import { sendVerificationEmail } from "@/email"; +import { sendVerificationEmail } from "@/lib/emails"; import { KnownErrors } from "@stackframe/stack-shared"; import { prismaClient } from "@/prisma-client"; diff --git a/apps/dashboard/src/app/api/v1/auth/signup/route.tsx b/apps/dashboard/src/app/api/v1/auth/signup/route.tsx index b06087772..3b4c0294d 100644 --- a/apps/dashboard/src/app/api/v1/auth/signup/route.tsx +++ b/apps/dashboard/src/app/api/v1/auth/signup/route.tsx @@ -6,7 +6,7 @@ import { prismaClient } from "@/prisma-client"; import { deprecatedSmartRouteHandler } from "@/route-handlers/smart-route-handler"; import { deprecatedParseRequest } from "@/route-handlers/smart-request"; import { createAuthTokens } from "@/lib/tokens"; -import { sendVerificationEmail } from "@/email"; +import { sendVerificationEmail } from "@/lib/emails"; import { getProject } from "@/lib/projects"; import { validateUrl } from "@/lib/utils"; import { getPasswordError } from "@stackframe/stack-shared/dist/helpers/password"; diff --git a/apps/dashboard/src/app/api/v1/current-user/crud.tsx b/apps/dashboard/src/app/api/v1/current-user/crud.tsx index a82f8456a..683fc2ce2 100644 --- a/apps/dashboard/src/app/api/v1/current-user/crud.tsx +++ b/apps/dashboard/src/app/api/v1/current-user/crud.tsx @@ -21,6 +21,9 @@ export const currentUserCrudHandlers = createCrudHandlers(currentUserCrud, { if (!user) throw new KnownErrors.UserNotFound(); return user; }, + async onDelete({ auth }) { + throw new Error("not supported"); + }, metadataMap: { read: { summary: 'Get the current user', diff --git a/apps/dashboard/src/app/api/v1/email-templates/[type]/route.tsx b/apps/dashboard/src/app/api/v1/email-templates/[type]/route.tsx index a3a1a80c2..db7d16757 100644 --- a/apps/dashboard/src/app/api/v1/email-templates/[type]/route.tsx +++ b/apps/dashboard/src/app/api/v1/email-templates/[type]/route.tsx @@ -1,5 +1,5 @@ import { createEmailTemplate, deleteEmailTemplate, getEmailTemplate, updateEmailTemplate } from "@/lib/email-templates"; -import { validateEmailTemplateContent } from "@/email/utils"; +import { validateEmailTemplateContent } from "@stackframe/stack-emails/dist/utils"; import { createCrudHandlers } from "@/route-handlers/crud-handler"; import { emailTemplateCrud } from "@stackframe/stack-shared/dist/interface/crud/email-templates"; import { emailTemplateTypes } from "@stackframe/stack-shared/dist/interface/serverInterface"; diff --git a/apps/dashboard/src/globals.d.ts b/apps/dashboard/src/globals.d.ts index 98d1e80dc..7c69dbb07 100644 --- a/apps/dashboard/src/globals.d.ts +++ b/apps/dashboard/src/globals.d.ts @@ -6,8 +6,3 @@ declare namespace React { inert?: '', } } - -declare module "handlebars/dist/handlebars.js" { - import * as Handlebars from 'handlebars'; - export = Handlebars; -} diff --git a/apps/dashboard/src/lib/email-templates.tsx b/apps/dashboard/src/lib/email-templates.tsx index 1642cd8f4..d2349fc95 100644 --- a/apps/dashboard/src/lib/email-templates.tsx +++ b/apps/dashboard/src/lib/email-templates.tsx @@ -3,8 +3,8 @@ import { EmailTemplateType } from "@prisma/client"; import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects"; import { getProject } from "./projects"; import { EmailTemplateCrud, ListEmailTemplatesCrud } from "@stackframe/stack-shared/dist/interface/crud/email-templates"; -import { EMAIL_TEMPLATES_METADATA } from "@/email/utils"; -import { TEditorConfiguration } from "@/components/email-editor/documents/editor/core"; +import { EMAIL_TEMPLATES_METADATA } from "@stackframe/stack-emails/dist/utils"; +import { TEditorConfiguration } from "@stackframe/stack-emails/dist/editor/documents/editor/core"; export async function listEmailTemplatesWithDefault(projectId: string) { const project = await getProject(projectId); diff --git a/apps/dashboard/src/email/index.tsx b/apps/dashboard/src/lib/emails.tsx similarity index 98% rename from apps/dashboard/src/email/index.tsx rename to apps/dashboard/src/lib/emails.tsx index 9b550a871..4f73f0cab 100644 --- a/apps/dashboard/src/email/index.tsx +++ b/apps/dashboard/src/lib/emails.tsx @@ -5,8 +5,8 @@ import { generateSecureRandomString } from '@stackframe/stack-shared/dist/utils/ import { getProject } from '@/lib/projects'; import { UserJson, ProjectJson } from '@stackframe/stack-shared'; import { getClientUser } from '@/lib/users'; -import { renderEmailTemplate } from './utils'; import { getEmailTemplateWithDefault } from '@/lib/email-templates'; +import { renderEmailTemplate } from '@stackframe/stack-emails/dist/utils'; function getPortConfig(port: number | string) { diff --git a/apps/dashboard/src/lib/openapi.tsx b/apps/dashboard/src/lib/openapi.tsx deleted file mode 100644 index 2fe91a1cc..000000000 --- a/apps/dashboard/src/lib/openapi.tsx +++ /dev/null @@ -1,273 +0,0 @@ -import { SmartRouteHandler } from '@/route-handlers/smart-route-handler'; -import { StackAssertionError } from '@stackframe/stack-shared/dist/utils/errors'; -import { HttpMethod } from '@stackframe/stack-shared/dist/utils/http'; -import { deindent } from '@stackframe/stack-shared/dist/utils/strings'; -import * as yup from 'yup'; - -export function parseOpenAPI(options: { - endpoints: Map>, - audience: 'client' | 'server' | 'admin', -}) { - return { - openapi: '3.1.0', - info: { - title: 'Stack REST API', - version: '1.0.0', - }, - servers: [{ - url: 'https://app.stack-auth.com/api/v1', - description: 'Stack REST API', - }], - paths: Object.fromEntries( - [...options.endpoints] - .map(([path, handlersByMethod]) => ( - [path, Object.fromEntries( - [...handlersByMethod] - .map(([method, handler]) => ( - [method.toLowerCase(), parseRouteHandler({ handler, method, path, audience: options.audience })] - )) - .filter(([_, handler]) => handler !== undefined) - )] - )) - .filter(([_, handlersByMethod]) => Object.keys(handlersByMethod).length > 0), - ), - }; -} - -const endpointMetadataSchema = yup.object({ - summary: yup.string().required(), - description: yup.string().required(), - hide: yup.boolean().optional(), - tags: yup.array(yup.string()).required(), -}); - -function undefinedIfMixed(value: yup.SchemaFieldDescription | undefined): yup.SchemaFieldDescription | undefined { - if (!value) return undefined; - return value.type === 'mixed' ? undefined : value; -} - -function isSchemaObjectDescription(value: yup.SchemaFieldDescription): value is yup.SchemaObjectDescription & { type: 'object' } { - return value.type === 'object'; -} - -function isSchemaMixedDescription(value: yup.SchemaFieldDescription): value is yup.SchemaDescription & { type: 'mixed' } { - return value.type === 'mixed'; -} - -function isSchemaArrayDescription(value: yup.SchemaFieldDescription): value is yup.SchemaInnerTypeDescription & { type: 'array', innerType: yup.SchemaInnerTypeDescription } { - return value.type === 'array'; -} - -function isSchemaTupleDescription(value: yup.SchemaFieldDescription): value is yup.SchemaInnerTypeDescription & { type: 'tuple', innerType: yup.SchemaInnerTypeDescription[] } { - return value.type === 'tuple'; -} - -function isMaybeRequestSchemaForAudience(requestDescribe: yup.SchemaObjectDescription, audience: 'client' | 'server' | 'admin') { - const schemaAuth = requestDescribe.fields.auth; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- yup types are wrong and claim that fields always exist - if (!schemaAuth) return true; - if (isSchemaMixedDescription(schemaAuth)) return true; - if (!isSchemaObjectDescription(schemaAuth)) return true; - const schemaAudience = schemaAuth.fields.type; - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- same as above - if (!schemaAudience) return true; - if ("oneOf" in schemaAudience) { - return schemaAudience.oneOf.includes(audience); - } -} - - -function parseRouteHandler(options: { - handler: SmartRouteHandler, - path: string, - method: HttpMethod, - audience: 'client' | 'server' | 'admin', -}) { - let result: any = undefined; - - for (const overload of options.handler.overloads.values()) { - const requestDescribe = overload.request.describe(); - const responseDescribe = overload.response.describe(); - if (!isSchemaObjectDescription(requestDescribe)) throw new Error('Request schema must be a yup.ObjectSchema'); - if (!isSchemaObjectDescription(responseDescribe)) throw new Error('Response schema must be a yup.ObjectSchema'); - - // estimate whether this overload is the right one based on a heuristic - if (!isMaybeRequestSchemaForAudience(requestDescribe, options.audience)) { - // This overload is definitely not for the audience - continue; - } - - if (result) { - throw new StackAssertionError(deindent` - OpenAPI generator matched multiple overloads for audience ${options.audience} on endpoint ${options.method} ${options.path}. - - This does not necessarily mean there is a bug; the OpenAPI generator uses a heuristic to pick the allowed overloads, and may pick too many. Currently, this heuristic checks whether the request.auth.type property in the schema is a yup.string.oneOf(...) and matches it to the expected audience of the schema. If there are multiple overloads matching a single audience, for example because none of the overloads specify request.auth.type, the OpenAPI generator will not know which overload to generate specs for, and hence fails. - - Either specify request.auth.type on the schema of the specified endpoint or update the OpenAPI generator to support your use case. - `); - } - - result = parseOverload({ - metadata: overload.metadata ?? { - summary: `${options.method} ${options.path}`, - description: `No documentation available for this endpoint.`, - tags: ["Uncategorized"], - }, - path: options.path, - pathDesc: undefinedIfMixed(requestDescribe.fields.params), - parameterDesc: undefinedIfMixed(requestDescribe.fields.query), - requestBodyDesc: undefinedIfMixed(requestDescribe.fields.body), - responseDesc: undefinedIfMixed(responseDescribe.fields.body), - }); - } - - return result; -} - -function getFieldSchema(field: yup.SchemaFieldDescription): { type: string, items?: any } | undefined { - const meta = "meta" in field ? field.meta : {}; - if (meta?.openapi?.hide) { - return undefined; - } - - const openapiFieldExtra = { - example: meta?.openapi?.exampleValue, - description: meta?.openapi?.description, - }; - - switch (field.type) { - case 'string': - case 'number': - case 'boolean': { - return { type: field.type, ...openapiFieldExtra }; - } - case 'mixed': { - return { type: 'object', ...openapiFieldExtra }; - } - case 'object': { - return { type: 'object', ...openapiFieldExtra }; - } - case 'array': { - return { type: 'array', items: getFieldSchema((field as any).innerType), ...openapiFieldExtra }; - } - default: { - throw new Error(`Unsupported field type: ${field.type}`); - } - } -} - -function toParameters(description: yup.SchemaFieldDescription, path?: string) { - const pathParams: string[] = path ? path.match(/{[^}]+}/g) || [] : []; - if (!isSchemaObjectDescription(description)) { - throw new StackAssertionError('Parameters field must be an object schema', { actual: description }); - } - - return Object.entries(description.fields).map(([key, field]) => { - if (path && !pathParams.includes(`{${key}}`)) { - return { schema: null }; - } - return { - name: key, - in: path ? 'path' : 'query', - schema: getFieldSchema(field as any), - required: !(field as any).optional && !(field as any).nullable, - }; - }).filter((x) => x.schema !== null); -} - -function toSchema(description: yup.SchemaFieldDescription): any { - if (isSchemaObjectDescription(description)) { - return { - type: 'object', - properties: Object.fromEntries(Object.entries(description.fields).map(([key, field]) => { - return [key, getFieldSchema(field)]; - }, {})) - }; - } else if (isSchemaArrayDescription(description)) { - return { - type: 'array', - items: toSchema(description.innerType), - }; - } else { - throw new StackAssertionError(`Unsupported schema type: ${description.type}`, { actual: description }); - } -} - -function toRequired(description: yup.SchemaFieldDescription) { - let res: string[] = []; - if (isSchemaObjectDescription(description)) { - res = Object.entries(description.fields) - .filter(([_, field]) => !(field as any).optional && !(field as any).nullable) - .map(([key]) => key); - } else if (isSchemaArrayDescription(description)) { - res = []; - } else { - throw new StackAssertionError(`Unsupported schema type: ${description.type}`, { actual: description }); - } - if (res.length === 0) return undefined; - return res; -} - -function toExamples(description: yup.SchemaFieldDescription) { - if (!isSchemaObjectDescription(description)) { - throw new StackAssertionError('Examples field must be an object schema', { actual: description }); - } - - return Object.entries(description.fields).reduce((acc, [key, field]) => { - const schema = getFieldSchema(field); - if (!schema) return acc; - const example = "meta" in field ? field.meta?.openapi?.exampleValue : undefined; - return { ...acc, [key]: example }; - }, {}); -} - -export function parseOverload(options: { - metadata: yup.InferType, - path: string, - pathDesc?: yup.SchemaFieldDescription, - parameterDesc?: yup.SchemaFieldDescription, - requestBodyDesc?: yup.SchemaFieldDescription, - responseDesc?: yup.SchemaFieldDescription, -}) { - const pathParameters = options.pathDesc ? toParameters(options.pathDesc, options.path) : []; - const queryParameters = options.parameterDesc ? toParameters(options.parameterDesc) : []; - const responseSchema = options.responseDesc ? toSchema(options.responseDesc) : {}; - const responseRequired = options.responseDesc ? toRequired(options.responseDesc) : undefined; - - let requestBody; - if (options.requestBodyDesc) { - requestBody = { - required: true, - content: { - 'application/json': { - schema: { - ...toSchema(options.requestBodyDesc), - required: toRequired(options.requestBodyDesc), - example: toExamples(options.requestBodyDesc), - }, - }, - }, - }; - } - - return { - summary: options.metadata.summary, - description: options.metadata.description, - parameters: queryParameters.concat(pathParameters), - requestBody, - tags: options.metadata.tags, - responses: { - 200: { - description: 'Successful response', - content: { - 'application/json': { - schema: { - ...responseSchema, - required: responseRequired, - }, - }, - }, - }, - }, - }; -} diff --git a/apps/dashboard/src/route-handlers/crud-handler.tsx b/apps/dashboard/src/route-handlers/crud-handler.tsx index ba5ef4b31..a1f9ad9c6 100644 --- a/apps/dashboard/src/route-handlers/crud-handler.tsx +++ b/apps/dashboard/src/route-handlers/crud-handler.tsx @@ -1,16 +1,15 @@ import "../polyfills"; -import { NextRequest } from "next/server"; import * as yup from "yup"; import { SmartRouteHandler, SmartRouteHandlerOverloadMetadata, routeHandlerTypeHelper, createSmartRouteHandler } from "./smart-route-handler"; import { CrudOperation, CrudSchema, CrudTypeOf } from "@stackframe/stack-shared/dist/crud"; -import { FilterUndefined } from "@stackframe/stack-shared/dist/utils/objects"; +import { FilterUndefined, deepPlainCamelCaseToSnakeCase, deepPlainSnakeCaseToCamelCase } from "@stackframe/stack-shared/dist/utils/objects"; import { typedIncludes } from "@stackframe/stack-shared/dist/utils/arrays"; import { deindent, typedToLowercase } from "@stackframe/stack-shared/dist/utils/strings"; import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; import { SmartRequestAuth } from "./smart-request"; -type GetAdminKey, K extends Capitalize> = K extends keyof T["Admin"] ? T["Admin"][K] : void; +type GetAdminKey, K extends Capitalize> = any; type CrudSingleRouteHandler, K extends Capitalize, Params extends {}, Multi extends boolean = false> = K extends keyof T["Admin"] @@ -121,7 +120,7 @@ export function createCrudHandlers deepPlainCamelCaseToSnakeCase(value)), params: crudOperation === "List" ? paramsSchema.partial() : paramsSchema, }), response: yup.object({ @@ -136,11 +135,13 @@ export function createCrudHandlers = { auth: SmartRequestAuth, }; -type CRead> = T extends { Admin: { Read: infer R } } ? R : never; -type CCreate> = T extends { Admin: { Create: infer R } } ? R : never; -type CUpdate> = T extends { Admin: { Update: infer R } } ? R : never; -type CEitherWrite> = CCreate | CUpdate; +type CRead> = any; +type CCreate> = any; +type CUpdate> = any; +type CEitherWrite> = any; export type CrudHandlersFromCrudType> = CrudHandlers< | ("Create" extends keyof T["Admin"] ? "Create" : never) diff --git a/apps/dashboard/src/route-handlers/smart-request.tsx b/apps/dashboard/src/route-handlers/smart-request.tsx index 1f9c6bcd4..0f511530e 100644 --- a/apps/dashboard/src/route-handlers/smart-request.tsx +++ b/apps/dashboard/src/route-handlers/smart-request.tsx @@ -3,7 +3,7 @@ import "../polyfills"; import { NextRequest } from "next/server"; import { StackAssertionError, StatusError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; import * as yup from "yup"; -import { DeepPartial } from "@stackframe/stack-shared/dist/utils/objects"; +import { DeepPartial, deepPlainCamelCaseToSnakeCase } from "@stackframe/stack-shared/dist/utils/objects"; import { groupBy, typedIncludes } from "@stackframe/stack-shared/dist/utils/arrays"; import { KnownError, KnownErrors, ProjectJson, ServerUserJson, UserJson } from "@stackframe/stack-shared"; import { IsAny } from "@stackframe/stack-shared/dist/utils/types"; diff --git a/apps/dashboard/src/route-handlers/smart-response.tsx b/apps/dashboard/src/route-handlers/smart-response.tsx index 0e14bcac1..785761fa1 100644 --- a/apps/dashboard/src/route-handlers/smart-response.tsx +++ b/apps/dashboard/src/route-handlers/smart-response.tsx @@ -4,6 +4,7 @@ import { NextRequest } from "next/server"; import * as yup from "yup"; import { Json } from "@stackframe/stack-shared/dist/utils/json"; import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors"; +import { deepPlainSnakeCaseToCamelCase } from "@stackframe/stack-shared/dist/utils/objects"; export type SmartResponse = { statusCode: number, @@ -60,7 +61,7 @@ export async function createResponse(req: NextRequest, switch (bodyType) { case "json": { headers.set("content-type", ["application/json; charset=utf-8"]); - arrayBufferBody = new TextEncoder().encode(JSON.stringify(validated.body)); + arrayBufferBody = new TextEncoder().encode(JSON.stringify(deepPlainSnakeCaseToCamelCase(validated.body))); break; } case "text": { diff --git a/apps/dashboard/src/route-handlers/smart-route-handler.tsx b/apps/dashboard/src/route-handlers/smart-route-handler.tsx index 8022e48ed..5cc4261b5 100644 --- a/apps/dashboard/src/route-handlers/smart-route-handler.tsx +++ b/apps/dashboard/src/route-handlers/smart-route-handler.tsx @@ -11,8 +11,11 @@ import { MergeSmartRequest, SmartRequest, createLazyRequestParser } from "./smar import { SmartResponse, createResponse } from "./smart-response"; class InternalServerError extends StatusError { - constructor() { - super(StatusError.InternalServerError); + constructor(error: unknown) { + super( + StatusError.InternalServerError, + ...process.env.NODE_ENV === "development" ? [`Internal Server Error. The error message follows, but will be stripped in production. ${error}`] : [], + ); } } @@ -41,7 +44,7 @@ function catchError(error: unknown): StatusError { if (error instanceof StatusError) return error; captureError(`route-handler`, error); - return new InternalServerError(); + return new InternalServerError(error); } /** diff --git a/apps/dashboard/src/stack.tsx b/apps/dashboard/src/stack.tsx index 6b2008a23..130b39036 100644 --- a/apps/dashboard/src/stack.tsx +++ b/apps/dashboard/src/stack.tsx @@ -10,7 +10,7 @@ export const stackServerApp = new StackServerApp<"nextjs-cookie", true, 'interna tokenStore: "nextjs-cookie", urls: { afterSignIn: "/projects", - afterSignUp: "/projects", + afterSignUp: "/new-project", afterSignOut: "/", } }); diff --git a/apps/e2e/.env b/apps/e2e/.env index 7c8d78a7e..81dfb9b69 100644 --- a/apps/e2e/.env +++ b/apps/e2e/.env @@ -3,3 +3,6 @@ STACK_BACKEND_BASE_URL= STACK_INTERNAL_PROJECT_ID= STACK_INTERNAL_PROJECT_CLIENT_KEY= STACK_INTERNAL_PROJECT_SERVER_KEY= +STACK_INTERNAL_PROJECT_ADMIN_KEY= + +INBUCKET_API_URL= diff --git a/apps/e2e/.env.development b/apps/e2e/.env.development index 1642a92c8..25710918c 100644 --- a/apps/e2e/.env.development +++ b/apps/e2e/.env.development @@ -3,3 +3,6 @@ STACK_BACKEND_BASE_URL=http://localhost:8102 STACK_INTERNAL_PROJECT_ID=internal STACK_INTERNAL_PROJECT_CLIENT_KEY=this-publishable-client-key-is-for-local-development-only STACK_INTERNAL_PROJECT_SERVER_KEY=this-secret-server-key-is-for-local-development-only +STACK_INTERNAL_PROJECT_ADMIN_KEY=this-super-secret-admin-key-is-for-local-development-only + +INBUCKET_API_URL=http://localhost:8105 diff --git a/apps/e2e/.eslintrc.cjs b/apps/e2e/.eslintrc.cjs index 31b2edd96..f03fc7332 100644 --- a/apps/e2e/.eslintrc.cjs +++ b/apps/e2e/.eslintrc.cjs @@ -3,4 +3,18 @@ module.exports = { "../../eslint-configs/defaults.js", ], "ignorePatterns": ['/*', '!/tests'], + "rules": { + "no-restricted-imports": [ + "error", + { + patterns: [ + { + group: ["vitest"], + importNames: ["test", "it"], + message: "Use test or it from helpers instead.", + }, + ], + }, + ], + } }; diff --git a/apps/e2e/LICENSE b/apps/e2e/LICENSE index 0ec883d12..be3f7b28e 100644 --- a/apps/e2e/LICENSE +++ b/apps/e2e/LICENSE @@ -1,7 +1,661 @@ -Copyright 2024 Stackframe + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + Preamble -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/apps/e2e/tests/backend/backend-helpers.ts b/apps/e2e/tests/backend/backend-helpers.ts index ce1a4d7e2..7fb00813e 100644 --- a/apps/e2e/tests/backend/backend-helpers.ts +++ b/apps/e2e/tests/backend/backend-helpers.ts @@ -1,6 +1,180 @@ -import { STACK_BACKEND_BASE_URL, NiceResponse, niceFetch } from "../helpers"; +import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects"; +import { STACK_BACKEND_BASE_URL, Context, STACK_INTERNAL_PROJECT_ADMIN_KEY, STACK_INTERNAL_PROJECT_CLIENT_KEY, STACK_INTERNAL_PROJECT_ID, STACK_INTERNAL_PROJECT_SERVER_KEY, Mailbox, NiceResponse, createMailbox, niceFetch } from "../helpers"; +import { expect } from "vitest"; +import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors"; -export function niceBackendFetch(url: string, options?: RequestInit): Promise { - const res = niceFetch(new URL(url, STACK_BACKEND_BASE_URL), options); +type BackendContext = { + projectKeys: ProjectKeys, + mailbox: Mailbox, + userAuth: { + refreshToken: string, + accessToken?: string, + } | null, +}; + +export const backendContext = new Context>( + () => ({ + projectKeys: InternalProjectKeys, + mailbox: createMailbox(), + userAuth: null, + }), + (acc, update) => ({ + ...acc, + ...filterUndefined(update), + }), +); + +export type ProjectKeys = "no-project" | { + projectId: string, + publishableClientKey: string, + secretServerKey: string, + superSecretAdminKey: string, +}; + +export const InternalProjectKeys = { + projectId: STACK_INTERNAL_PROJECT_ID, + publishableClientKey: STACK_INTERNAL_PROJECT_CLIENT_KEY, + secretServerKey: STACK_INTERNAL_PROJECT_SERVER_KEY, + superSecretAdminKey: STACK_INTERNAL_PROJECT_ADMIN_KEY, +}; + +function expectSnakeCase(obj: unknown, path: string): void { + if (typeof obj !== "object" || obj === null) return; + if (Array.isArray(obj)) { + for (let i = 0; i < obj.length; i++) { + expectSnakeCase(obj[i], `${path}[${i}]`); + } + } else { + for (const [key, value] of Object.entries(obj)) { + if (key.match(/[a-z0-9][A-Z][a-z0-9]+/) && !key.includes("_")) { + throw new StackAssertionError(`Object has camelCase key (expected snake case): ${path}.${key}`); + } + expectSnakeCase(value, `${path}.${key}`); + } + } +} + +export async function niceBackendFetch(url: string, options?: Omit & { + accessType?: null | "client" | "server" | "admin", + body?: unknown, + headers?: Record, +}): Promise { + const { body, headers, accessType, ...otherOptions } = options ?? {}; + const { projectKeys, userAuth } = backendContext.value; + const res = await niceFetch(new URL(url, STACK_BACKEND_BASE_URL), { + ...otherOptions, + ...body !== undefined ? { body: JSON.stringify(body) } : {}, + headers: filterUndefined({ + "content-type": body !== undefined ? "application/json" : undefined, + "x-stack-access-type": accessType ?? undefined, + ...projectKeys !== "no-project" ? { + "x-stack-project-id": projectKeys.projectId, + "x-stack-publishable-client-key": projectKeys.publishableClientKey, + "x-stack-secret-server-key": projectKeys.secretServerKey, + "x-stack-super-secret-admin-key": projectKeys.superSecretAdminKey, + } : {}, + ...!userAuth ? {} : { + "x-stack-access-token": userAuth.accessToken, + "x-stack-refresh-token": userAuth.refreshToken, + }, + ...Object.fromEntries(new Headers(headers).entries()), + }), + }); + if (res.status >= 500 && res.status < 600) { + throw new StackAssertionError(`Unexpected internal server error: ${res.status} ${res.body}`); + } + if (res.headers.has("x-stack-known-error")) { + expect(res.status).toBeGreaterThanOrEqual(400); + expect(res.status).toBeLessThan(500); + expect(res.body).toMatchObject({ + code: res.headers.get("x-stack-known-error"), + }); + } + if (typeof res.body === "object" && res.body) { + expectSnakeCase(res.body, "body"); + } return res; } + + +export namespace Auth { + export namespace Otp { + type SendSignInCodeResult = { + sendSignInCodeResponse: NiceResponse, + }; + export async function sendSignInCode(): Promise { + const mailbox = backendContext.value.mailbox; + const response = await niceBackendFetch("/api/v1/auth/otp/send-sign-in-code", { + method: "POST", + accessType: "client", + body: { + email: mailbox.emailAddress, + redirectUrl: "http://localhost:12345", + }, + }); + expect(response).toMatchInlineSnapshot(` + NiceResponse { + "status": 200, + "body": { "success": true }, + "headers": Headers { + "x-stack-request-id": , +