diff --git a/apps/web/.env.example b/apps/web/.env.example index 54f0d4e..0e4d700 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -4,20 +4,25 @@ # Base URL of the site (used by auth + links) VITE_BASE_URL="http://localhost:3000" -# Postgres connection string -DATABASE_URL="postgres://user:password@localhost:5432/battlify" - -# Better Auth — generate with: pnpm auth:secret +# Better Auth — generate with: bun run auth:secret BETTER_AUTH_SECRET="replace-with-a-long-random-string" -# GitHub OAuth (https://github.com/settings/developers) -GITHUB_CLIENT_ID="" -GITHUB_CLIENT_SECRET="" +# Sign-in is Google and Apple only. +# Redirect URI: /api/auth/callback/ # Google OAuth (https://console.cloud.google.com/apis/credentials) GOOGLE_CLIENT_ID="" GOOGLE_CLIENT_SECRET="" +# Sign in with Apple (https://developer.apple.com/account/resources) +# Services ID, Team ID, and the Key ID + .p8 of a "Sign in with Apple" key. +# APPLE_PRIVATE_KEY: the .p8 contents on one line, newlines written as \n. +APPLE_CLIENT_ID="" +APPLE_TEAM_ID="" +APPLE_KEY_ID="" +APPLE_PRIVATE_KEY="" +APPLE_APP_BUNDLE_IDENTIFIER="" + # Dodo Payments (https://app.dodopayments.com) DODO_PAYMENTS_API_KEY="" DODO_PAYMENTS_WEBHOOK_SECRET="" diff --git a/apps/web/package.json b/apps/web/package.json index 78dec2f..e5b79ac 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -50,6 +50,7 @@ "cnfast": "0.0.8", "dodopayments": "^2.40.1", "drizzle-orm": "0.45.2", + "jose": "^6.1.3", "lucide-react": "1.22.0", "motion": "^12.42.2", "postgres": "3.4.9", diff --git a/apps/web/src/components/auth/sign-in-methods.tsx b/apps/web/src/components/auth/sign-in-methods.tsx index 1db882e..704ba77 100644 --- a/apps/web/src/components/auth/sign-in-methods.tsx +++ b/apps/web/src/components/auth/sign-in-methods.tsx @@ -1,6 +1,6 @@ -import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"; +import { SiApple, SiGoogle } from "@icons-pack/react-simple-icons"; import { useMutation, useQuery } from "@tanstack/react-query"; -import { CheckIcon, MailIcon } from "lucide-react"; +import { CheckIcon } from "lucide-react"; import { toast } from "sonner"; import { Button } from "#/components/ui/button"; @@ -8,13 +8,13 @@ import { authClient } from "#/lib/auth/auth-client"; import { $getSocialProviders } from "#/lib/auth/functions"; const PROVIDERS = [ - { id: "github", label: "GitHub", icon: SiGithub }, { id: "google", label: "Google", icon: SiGoogle }, + { id: "apple", label: "Apple", icon: SiApple }, ] as const; /** * Lists how this account can sign in and lets the user connect the other - * provider, so GitHub and Google both open the same account and license. + * provider, so Google and Apple both open the same account and license. */ export function SignInMethods() { const { data: accounts } = useQuery({ @@ -76,15 +76,6 @@ export function SignInMethods() { )} ))} -
  • - - - Email and password - - - {linked.has("credential") ? "Set" : "Not set"} - -
  • ); diff --git a/apps/web/src/components/sign-in-social-button.tsx b/apps/web/src/components/sign-in-social-button.tsx index 87f892a..ef0bbf4 100644 --- a/apps/web/src/components/sign-in-social-button.tsx +++ b/apps/web/src/components/sign-in-social-button.tsx @@ -12,10 +12,7 @@ interface SocialLoginButtonProps { } export function SignInSocialButton(props: SocialLoginButtonProps) { - const providerLabel = - props.provider === "github" - ? "GitHub" - : props.provider.charAt(0).toUpperCase() + props.provider.slice(1); + const providerLabel = props.provider.charAt(0).toUpperCase() + props.provider.slice(1); const mutation = useMutation({ mutationFn: async () => @@ -41,7 +38,7 @@ export function SignInSocialButton(props: SocialLoginButtonProps) { onClick={() => mutation.mutate()} > {props.icon} - {providerLabel} + Continue with {providerLabel} ); } diff --git a/apps/web/src/env/server.ts b/apps/web/src/env/server.ts index 6fd2b6e..3ba2175 100644 --- a/apps/web/src/env/server.ts +++ b/apps/web/src/env/server.ts @@ -6,11 +6,18 @@ export const env = createEnv({ VITE_BASE_URL: z.url().default("http://localhost:3000"), BETTER_AUTH_SECRET: z.string().min(1), - // OAuth2 providers, optional, update as needed - GITHUB_CLIENT_ID: z.string().optional(), - GITHUB_CLIENT_SECRET: z.string().optional(), + // Sign-in providers (the only ways in). Each is optional so the worker + // boots before it's set up; the login page hides providers that aren't. GOOGLE_CLIENT_ID: z.string().optional(), GOOGLE_CLIENT_SECRET: z.string().optional(), + // Sign in with Apple: the Services ID, your Team ID, and the Key ID + .p8 + // private key of a "Sign in with Apple" key. The client secret is a JWT + // the server signs from these (see lib/auth/apple.ts). + APPLE_CLIENT_ID: z.string().optional(), + APPLE_TEAM_ID: z.string().optional(), + APPLE_KEY_ID: z.string().optional(), + APPLE_PRIVATE_KEY: z.string().optional(), + APPLE_APP_BUNDLE_IDENTIFIER: z.string().optional(), // Dodo Payments — https://better-auth.com/docs/plugins/dodopayments // Optional so the app still boots before you paste real values in. diff --git a/apps/web/src/lib/auth/apple.ts b/apps/web/src/lib/auth/apple.ts new file mode 100644 index 0000000..e337cbc --- /dev/null +++ b/apps/web/src/lib/auth/apple.ts @@ -0,0 +1,28 @@ +import "@tanstack/react-start/server-only"; +import { importPKCS8, SignJWT } from "jose"; + +import { env } from "#/env/server"; + +export const appleConfigured = Boolean( + env.APPLE_CLIENT_ID && env.APPLE_TEAM_ID && env.APPLE_KEY_ID && env.APPLE_PRIVATE_KEY, +); + +/** + * Apple wants the OAuth client secret as an ES256 JWT signed with the .p8 key, + * valid for at most six months. https://better-auth.com/docs/authentication/apple + * + * The key may be stored with literal "\n"s (one-line secrets), so restore them. + */ +export async function appleClientSecret(): Promise { + const pem = env.APPLE_PRIVATE_KEY!.replace(/\\n/g, "\n").trim(); + const key = await importPKCS8(pem, "ES256"); + const now = Math.floor(Date.now() / 1000); + return new SignJWT({}) + .setProtectedHeader({ alg: "ES256", kid: env.APPLE_KEY_ID! }) + .setIssuer(env.APPLE_TEAM_ID!) + .setSubject(env.APPLE_CLIENT_ID!) + .setAudience("https://appleid.apple.com") + .setIssuedAt(now) + .setExpirationTime(now + 180 * 24 * 60 * 60) + .sign(key); +} diff --git a/apps/web/src/lib/auth/auth.ts b/apps/web/src/lib/auth/auth.ts index be4f30d..51ce0e0 100644 --- a/apps/web/src/lib/auth/auth.ts +++ b/apps/web/src/lib/auth/auth.ts @@ -6,6 +6,7 @@ import { tanstackStartCookies } from "better-auth/tanstack-start"; import { eq } from "drizzle-orm"; import { env } from "#/env/server"; +import { appleClientSecret, appleConfigured } from "#/lib/auth/apple"; import { db } from "#/lib/db"; import * as schema from "#/lib/db/schema"; import { issueLicenseForUser } from "#/lib/license/service"; @@ -22,18 +23,20 @@ export const auth = betterAuth({ baseURL: env.VITE_BASE_URL, // The old host stays attached for already-installed apps; accept auth // requests from it too so sign-in doesn't fail on origin checks there. - trustedOrigins: [env.VITE_BASE_URL, "https://battlify.discerns.app"], + // Apple posts the OAuth callback from appleid.apple.com (form_post). + trustedOrigins: [env.VITE_BASE_URL, "https://battlify.discerns.app", "https://appleid.apple.com"], // https://better-auth.com/docs/concepts/users-accounts#account-linking - // One person, one account: GitHub, Google and email sign-ins with the same - // address resolve to the same user (and the same license). Both providers - // verify the email they return, so they are trusted to link. + // One person, one account: Google and Apple sign-ins with the same address + // resolve to the same user (and the same license). Both verify the email they + // return, so they are trusted to link. Accounts made with the old email/password + // sign-in are reached the same way: sign in with Google or Apple on that address. account: { accountLinking: { enabled: true, - trustedProviders: ["google", "github"], - // Email/password sign-ups are never verified here (no verification - // mail is sent), so the default `true` makes every Google/GitHub - // sign-in for an existing account fail with "account_not_linked". + trustedProviders: ["google", "apple"], + // Old email/password accounts were never verified (no verification + // mail was sent), so the default `true` would make every Google/Apple + // sign-in for one of them fail with "account_not_linked". // Linking marks the email verified, since the provider vouched for it. requireLocalEmailVerified: false, }, @@ -121,17 +124,9 @@ export const auth = betterAuth({ }, // https://better-auth.com/docs/concepts/oauth - // Only register a provider when its credentials are actually configured, - // so the worker still boots when GitHub/Google aren't set up yet. + // Google and Apple are the only ways in. A provider is registered only when its + // credentials are configured, so the worker still boots without them. socialProviders: { - ...(env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET - ? { - github: { - clientId: env.GITHUB_CLIENT_ID, - clientSecret: env.GITHUB_CLIENT_SECRET, - }, - } - : {}), ...(env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET ? { google: { @@ -140,11 +135,16 @@ export const auth = betterAuth({ }, } : {}), - }, - - // https://better-auth.com/docs/authentication/email-password - emailAndPassword: { - enabled: true, + ...(appleConfigured + ? { + // Async so the client-secret JWT is signed when auth initialises. + apple: async () => ({ + clientId: env.APPLE_CLIENT_ID!, + clientSecret: await appleClientSecret(), + appBundleIdentifier: env.APPLE_APP_BUNDLE_IDENTIFIER, + }), + } + : {}), }, experimental: { diff --git a/apps/web/src/lib/auth/functions.ts b/apps/web/src/lib/auth/functions.ts index 1a1180a..f8f85ed 100644 --- a/apps/web/src/lib/auth/functions.ts +++ b/apps/web/src/lib/auth/functions.ts @@ -2,6 +2,7 @@ import { createServerFn, createServerOnlyFn } from "@tanstack/react-start"; import { getRequest, setResponseHeader } from "@tanstack/react-start/server"; import { env } from "#/env/server"; +import { appleConfigured } from "#/lib/auth/apple"; import { auth } from "#/lib/auth/auth"; /** @@ -22,8 +23,8 @@ export const $getUser = createServerFn({ method: "GET" }).handler(async () => { * instead of offering a button that fails with "Provider not found". */ export const $getSocialProviders = createServerFn({ method: "GET" }).handler(() => ({ - github: Boolean(env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET), google: Boolean(env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET), + apple: appleConfigured, })); interface GetUserServerQuery { diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 1019986..f7baf06 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -31,7 +31,6 @@ import { Route as LegalTermsRouteImport } from './routes/legal/terms' import { Route as LegalPrivacyRouteImport } from './routes/legal/privacy' import { Route as LegalLicenseRouteImport } from './routes/legal/license' import { Route as BlogSlugRouteImport } from './routes/blog/$slug' -import { Route as GuestSignupRouteImport } from './routes/_guest/signup' import { Route as GuestLoginRouteImport } from './routes/_guest/login' import { Route as AuthAppRouteRouteImport } from './routes/_auth/app/route' import { Route as AuthAppIndexRouteImport } from './routes/_auth/app/index' @@ -145,11 +144,6 @@ const BlogSlugRoute = BlogSlugRouteImport.update({ path: '/$slug', getParentRoute: () => BlogRouteRoute, } as any) -const GuestSignupRoute = GuestSignupRouteImport.update({ - id: '/signup', - path: '/signup', - getParentRoute: () => GuestRouteRoute, -} as any) const GuestLoginRoute = GuestLoginRouteImport.update({ id: '/login', path: '/login', @@ -189,7 +183,6 @@ export interface FileRoutesByFullPath { '/terms': typeof TermsRoute '/app': typeof AuthAppRouteRouteWithChildren '/login': typeof GuestLoginRoute - '/signup': typeof GuestSignupRoute '/blog/$slug': typeof BlogSlugRoute '/legal/license': typeof LegalLicenseRoute '/legal/privacy': typeof LegalPrivacyRoute @@ -214,7 +207,6 @@ export interface FileRoutesByTo { '/sitemap.xml': typeof SitemapDotxmlRoute '/terms': typeof TermsRoute '/login': typeof GuestLoginRoute - '/signup': typeof GuestSignupRoute '/blog/$slug': typeof BlogSlugRoute '/legal/license': typeof LegalLicenseRoute '/legal/privacy': typeof LegalPrivacyRoute @@ -244,7 +236,6 @@ export interface FileRoutesById { '/terms': typeof TermsRoute '/_auth/app': typeof AuthAppRouteRouteWithChildren '/_guest/login': typeof GuestLoginRoute - '/_guest/signup': typeof GuestSignupRoute '/blog/$slug': typeof BlogSlugRoute '/legal/license': typeof LegalLicenseRoute '/legal/privacy': typeof LegalPrivacyRoute @@ -273,7 +264,6 @@ export interface FileRouteTypes { | '/terms' | '/app' | '/login' - | '/signup' | '/blog/$slug' | '/legal/license' | '/legal/privacy' @@ -298,7 +288,6 @@ export interface FileRouteTypes { | '/sitemap.xml' | '/terms' | '/login' - | '/signup' | '/blog/$slug' | '/legal/license' | '/legal/privacy' @@ -327,7 +316,6 @@ export interface FileRouteTypes { | '/terms' | '/_auth/app' | '/_guest/login' - | '/_guest/signup' | '/blog/$slug' | '/legal/license' | '/legal/privacy' @@ -514,13 +502,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogRouteRoute } - '/_guest/signup': { - id: '/_guest/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof GuestSignupRouteImport - parentRoute: typeof GuestRouteRoute - } '/_guest/login': { id: '/_guest/login' path: '/login' @@ -578,12 +559,10 @@ const AuthRouteRouteWithChildren = AuthRouteRoute._addFileChildren( interface GuestRouteRouteChildren { GuestLoginRoute: typeof GuestLoginRoute - GuestSignupRoute: typeof GuestSignupRoute } const GuestRouteRouteChildren: GuestRouteRouteChildren = { GuestLoginRoute: GuestLoginRoute, - GuestSignupRoute: GuestSignupRoute, } const GuestRouteRouteWithChildren = GuestRouteRoute._addFileChildren( diff --git a/apps/web/src/routes/_guest/login.tsx b/apps/web/src/routes/_guest/login.tsx index 315d84a..465eb9e 100644 --- a/apps/web/src/routes/_guest/login.tsx +++ b/apps/web/src/routes/_guest/login.tsx @@ -1,20 +1,9 @@ -import { - GithubIcon, - GoogleIcon, - Loading03Icon, - LockPasswordIcon, - Mail02Icon, -} from "@hugeicons/core-free-icons"; -import { useMutation } from "@tanstack/react-query"; +import { AppleIcon, GoogleIcon } from "@hugeicons/core-free-icons"; import { createFileRoute, Link } from "@tanstack/react-router"; -import { toast } from "sonner"; -import { AuthField } from "#/components/auth/auth-field"; import { Icon } from "#/components/icon"; import { AppIcon } from "#/components/logo"; import { SignInSocialButton } from "#/components/sign-in-social-button"; -import { Button } from "#/components/ui/button"; -import { authClient } from "#/lib/auth/auth-client"; import { seo } from "#/lib/seo"; export const Route = createFileRoute("/_guest/login")({ @@ -25,107 +14,35 @@ export const Route = createFileRoute("/_guest/login")({ function LoginForm() { const { redirectUrl, providers } = Route.useRouteContext(); - const { mutate: emailLoginMutate, isPending } = useMutation({ - mutationFn: async (data: { email: string; password: string }) => - await authClient.signIn.email( - { - ...data, - callbackURL: redirectUrl, - }, - { - onError: ({ error }) => { - toast.error(error.message || "An error occurred while signing in."); - }, - }, - ), - }); - - const handleSubmit = (e: React.SubmitEvent) => { - e.preventDefault(); - if (isPending) return; - - const formData = new FormData(e.currentTarget); - const email = formData.get("email") as string; - const password = formData.get("password") as string; - - if (!email || !password) return; - - emailLoginMutate({ email, password }); - }; - return (
    -

    Sign in to your account

    -

    - No account?{" "} - - Create one - -

    +

    Sign in to eWiz

    +

    New here? Signing in creates your account.

    -
    - } - placeholder="Enter your email..." - readOnly={isPending} - required - /> - } - placeholder="Enter your password..." - readOnly={isPending} - required - rightSlot={ - - Forgot password? - - } - /> - - - - {providers.google || providers.github ? ( - <> -
    - Or continue with -
    - -
    - {providers.google ? ( - } - /> - ) : null} - {providers.github ? ( - } - /> - ) : null} -
    - - ) : null} +
    + {providers.apple ? ( + } + /> + ) : null} + {providers.google ? ( + } + /> + ) : null} + {!providers.apple && !providers.google ? ( +

    Sign-in isn't available right now.

    + ) : null} +
    ); } diff --git a/apps/web/src/routes/_guest/signup.tsx b/apps/web/src/routes/_guest/signup.tsx deleted file mode 100644 index 36bc0fa..0000000 --- a/apps/web/src/routes/_guest/signup.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { - GithubIcon, - GoogleIcon, - Loading03Icon, - LockPasswordIcon, - Mail02Icon, - UserIcon, -} from "@hugeicons/core-free-icons"; -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { createFileRoute, Link, useNavigate } from "@tanstack/react-router"; -import { toast } from "sonner"; - -import { AuthField } from "#/components/auth/auth-field"; -import { Icon } from "#/components/icon"; -import { AppIcon } from "#/components/logo"; -import { SignInSocialButton } from "#/components/sign-in-social-button"; -import { Button } from "#/components/ui/button"; -import { authClient } from "#/lib/auth/auth-client"; -import { authQueryOptions } from "#/lib/auth/queries"; -import { seo } from "#/lib/seo"; - -export const Route = createFileRoute("/_guest/signup")({ - head: () => ({ ...seo({ title: "Create your account", path: "/signup", noindex: true }) }), - component: SignupForm, -}); - -function SignupForm() { - const { redirectUrl, providers } = Route.useRouteContext(); - const queryClient = useQueryClient(); - const navigate = useNavigate(); - - const { mutate: signupMutate, isPending } = useMutation({ - mutationFn: async (data: { name: string; email: string; password: string }) => { - await authClient.signUp.email( - { - ...data, - callbackURL: redirectUrl, - }, - { - onError: ({ error }) => { - toast.error(error.message || "An error occurred while signing up."); - }, - onSuccess: () => { - queryClient.removeQueries({ queryKey: authQueryOptions().queryKey }); - navigate({ to: redirectUrl }); - }, - }, - ); - }, - }); - - const handleSubmit = (e: React.SubmitEvent) => { - e.preventDefault(); - if (isPending) return; - - const formData = new FormData(e.currentTarget); - const name = formData.get("name") as string; - const email = formData.get("email") as string; - const password = formData.get("password") as string; - const confirmPassword = formData.get("confirm_password") as string; - - if (!name || !email || !password || !confirmPassword) return; - - if (password !== confirmPassword) { - toast.error("Passwords do not match."); - return; - } - - signupMutate({ name, email, password }); - }; - - return ( -
    -
    - - - -

    Create your account

    -

    - Already have one?{" "} - - Sign in - -

    -
    - -
    - } - placeholder="Enter your name..." - readOnly={isPending} - required - /> - } - placeholder="Enter your email..." - readOnly={isPending} - required - /> - } - placeholder="Create a password..." - readOnly={isPending} - required - /> - } - placeholder="Re-enter your password..." - readOnly={isPending} - required - /> - - - - {providers.google || providers.github ? ( - <> -
    - Or continue with -
    - -
    - {providers.google ? ( - } - /> - ) : null} - {providers.github ? ( - } - /> - ) : null} -
    - - ) : null} -
    - ); -} diff --git a/apps/web/src/routes/robots[.]txt.ts b/apps/web/src/routes/robots[.]txt.ts index af52ab8..5b7115e 100644 --- a/apps/web/src/routes/robots[.]txt.ts +++ b/apps/web/src/routes/robots[.]txt.ts @@ -16,7 +16,6 @@ export const Route = createFileRoute("/robots.txt")({ "Allow: /", "Disallow: /app", "Disallow: /login", - "Disallow: /signup", "Disallow: /buy", "Disallow: /api/", "", diff --git a/apps/web/wrangler.toml b/apps/web/wrangler.toml index 19345d7..eace140 100644 --- a/apps/web/wrangler.toml +++ b/apps/web/wrangler.toml @@ -24,8 +24,9 @@ VITE_BASE_URL = "https://ewiz.app" DODO_PAYMENTS_ENVIRONMENT = "live_mode" # Secrets: set via `wrangler secret put ` # BETTER_AUTH_SECRET, DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_SECRET, -# DODO_BATTLIFY_PRODUCT_ID, LICENSE_SIGNING_PRIVATE_KEY, -# GITHUB_CLIENT_ID/SECRET, GOOGLE_CLIENT_ID/SECRET, GITHUB_RELEASES_TOKEN +# DODO_BATTLIFY_PRODUCT_ID, LICENSE_SIGNING_PRIVATE_KEY, GITHUB_RELEASES_TOKEN, +# GOOGLE_CLIENT_ID/SECRET, APPLE_CLIENT_ID, APPLE_TEAM_ID, APPLE_KEY_ID, +# APPLE_PRIVATE_KEY (APPLE_APP_BUNDLE_IDENTIFIER optional) [assets] directory = "./public" diff --git a/bun.lock b/bun.lock index 03ed926..4914b83 100644 --- a/bun.lock +++ b/bun.lock @@ -39,6 +39,7 @@ "cnfast": "0.0.8", "dodopayments": "^2.40.1", "drizzle-orm": "0.45.2", + "jose": "^6.1.3", "lucide-react": "1.22.0", "motion": "^12.42.2", "postgres": "3.4.9",