Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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: <VITE_BASE_URL>/api/auth/callback/<google|apple>

# 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=""
Expand Down
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
17 changes: 4 additions & 13 deletions apps/web/src/components/auth/sign-in-methods.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
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";
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({
Expand Down Expand Up @@ -76,15 +76,6 @@ export function SignInMethods() {
)}
</li>
))}
<li className="flex items-center justify-between py-2">
<span className="flex items-center gap-2.5 text-sm">
<MailIcon className="size-4" aria-hidden />
Email and password
</span>
<span className="text-xs text-muted-foreground">
{linked.has("credential") ? "Set" : "Not set"}
</span>
</li>
</ul>
</section>
);
Expand Down
7 changes: 2 additions & 5 deletions apps/web/src/components/sign-in-social-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 () =>
Expand All @@ -41,7 +38,7 @@ export function SignInSocialButton(props: SocialLoginButtonProps) {
onClick={() => mutation.mutate()}
>
{props.icon}
{providerLabel}
Continue with {providerLabel}
</Button>
);
}
13 changes: 10 additions & 3 deletions apps/web/src/env/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
28 changes: 28 additions & 0 deletions apps/web/src/lib/auth/apple.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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);
}
46 changes: 23 additions & 23 deletions apps/web/src/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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,
},
Expand Down Expand Up @@ -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: {
Expand All @@ -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: {
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/lib/auth/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand All @@ -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 {
Expand Down
21 changes: 0 additions & 21 deletions apps/web/src/routeTree.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -273,7 +264,6 @@ export interface FileRouteTypes {
| '/terms'
| '/app'
| '/login'
| '/signup'
| '/blog/$slug'
| '/legal/license'
| '/legal/privacy'
Expand All @@ -298,7 +288,6 @@ export interface FileRouteTypes {
| '/sitemap.xml'
| '/terms'
| '/login'
| '/signup'
| '/blog/$slug'
| '/legal/license'
| '/legal/privacy'
Expand Down Expand Up @@ -327,7 +316,6 @@ export interface FileRouteTypes {
| '/terms'
| '/_auth/app'
| '/_guest/login'
| '/_guest/signup'
| '/blog/$slug'
| '/legal/license'
| '/legal/privacy'
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading