⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: let API_URL be a subdomain or a path on the web's host (#519)
Pasqual Troncone1ca1b0ccdc0b
diff --git a/.env.example b/.env.exampleindex 5f60623a..79351fa3 100644--- a/.env.example+++ b/.env.example@@ -15,7 +15,8 @@ POSTGRES_PORT=5432DATABASE_URL=postgres://itsaplan:itsaplan@localhost:5432/itsaplan# ── Public origins (each set once; every service derives from these) ──-# API_URL — api origin: auth handler, email links, and the origin the browser calls.+# API_URL — api URL: auth handler, email links, and what the browser calls. An origin+# (its own subdomain), or a path on the web's host (https://app.example.com/api).# APP_URL — web origin: CORS/auth trusted origins, passkey, email links.API_URL=http://localhost:3000APP_URL=http://localhost:3001@@ -33,8 +34,9 @@ BETTER_AUTH_SECRET=change-me-please-generate-a-real-secret # openssl rand -base# In prod set to the public frontend hostname (no scheme, no port).# PASSKEY_RP_ID=app.example.com# PASSKEY_RP_NAME=Its a Plan-# Cookie domain override. Defaults to the parent domain of APP_URL;-# set only for multi-label TLDs or deep subdomains.+# Cookie domain override. Defaults to the parent domain of APP_URL, or to no domain+# (a host-only cookie) when API_URL is on the web's host; set only for multi-label+# TLDs or deep subdomains.# COOKIE_DOMAIN=.example.com# ── API (Elysia) ──diff --git a/apps/api/src/__tests__/integration/auth-urls.test.ts b/apps/api/src/__tests__/integration/auth-urls.test.tsnew file mode 100644index 00000000..4ac8ffa4--- /dev/null+++ b/apps/api/src/__tests__/integration/auth-urls.test.ts@@ -0,0 +1,146 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { resetDb } from '#tests/helpers/db';++// The URLs are read from the environment when @repo/auth loads, so each case runs its+// script in a process of its own. The script prints one JSON line.+async function runAuth(env: Record<string, string>, script: string) {+ const proc = Bun.spawn([process.execPath, '-e', `${script}\nprocess.exit(0);`], {+ env: { ...process.env, ...env },+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out, err] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ if ((await proc.exited) !== 0) throw new Error(err);+ return JSON.parse(out.trim().split('\n').pop()!);+}++const ERROR_URL = `+ const { auth } = await import('@repo/auth');+ console.log(JSON.stringify({ errorURL: auth.options.onAPIError?.errorURL ?? null }));+`;++// Starts the Google and the OIDC sign-in, and reads the redirect URI each authorization+// URL carries. The OIDC provider only has to answer its discovery document.+const REDIRECT_URIS = `+ const { auth, setGoogleSettings, setOidcSettings } = await import('@repo/auth');+ const idp = Bun.serve({+ port: 0,+ fetch: (req) => {+ const { origin } = new URL(req.url);+ return Response.json({+ issuer: origin,+ authorization_endpoint: origin + '/authorize',+ token_endpoint: origin + '/token',+ });+ },+ });+ await setGoogleSettings({ enabled: true, clientId: 'google-client', clientSecret: 'secret' });+ await setOidcSettings({+ enabled: true,+ discoveryUrl: 'http://localhost:' + idp.port + '/.well-known/openid-configuration',+ clientId: 'oidc-client',+ clientSecret: 'secret',+ });+ const start = async (path, body) => {+ const res = await auth.handler(+ new Request(new URL(process.env.API_URL).origin + '/api/auth' + path, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ }),+ );+ return new URL((await res.json()).url).searchParams.get('redirect_uri');+ };+ console.log(JSON.stringify({+ google: await start('/sign-in/social', { provider: 'google' }),+ oidc: await start('/sign-in/oauth2', { providerId: 'oidc' }),+ }));+`;++// Sends the three authentication emails and reads the link each one carries. The mail+// provider is Resend, whose API call is caught here instead of reaching the network.+const EMAIL_LINKS = `+ const { auth, setEmailSettings, setAuthSettings } = await import('@repo/auth');+ await setEmailSettings({ resend: { enabled: true, apiKey: 're_test' }, from: '[email protected]' });+ await setAuthSettings({ magicLink: true, requireEmailVerification: true });+ const links = {};+ const realFetch = globalThis.fetch;+ globalThis.fetch = async (url, init) => {+ if (!String(url).startsWith('https://api.resend.com/')) return realFetch(url, init);+ const mail = JSON.parse(init.body);+ links[mail.subject] = mail.text.match(/https?:\\/\\/\\S+/)[0];+ return Response.json({ id: 'sent' });+ };+ const post = (path, body) =>+ auth.handler(+ new Request(new URL(process.env.API_URL).origin + '/api/auth' + path, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ }),+ );+ await post('/sign-up/email', { email: '[email protected]', password: 'test-password-123', name: 'User' });+ await post('/sign-in/magic-link', { email: '[email protected]' });+ await post('/request-password-reset', { email: '[email protected]', redirectTo: '/reset-password' });+ for (let i = 0; i < 50 && Object.keys(links).length < 3; i++) await Bun.sleep(100);+ console.log(JSON.stringify(links));+`;++describe('auth URLs from the environment', () => {+ beforeEach(resetDb);++ it('leaves better-auth its own error page when API_URL has no path', async () => {+ const loaded = await runAuth(+ { API_URL: 'http://localhost:3000/', APP_URL: 'http://app.test' },+ ERROR_URL,+ );++ expect(loaded.errorURL).toBeNull();+ });++ it('sends early OAuth failures to the sign-in page when API_URL has a path', async () => {+ const loaded = await runAuth(+ { API_URL: 'https://example.test/api', APP_URL: 'https://example.test/' },+ ERROR_URL,+ );++ expect(loaded.errorURL).toBe('https://example.test/login');+ });++ it('puts the path of API_URL in the redirect URIs sent to Google and the OIDC provider', async () => {+ const uris = await runAuth(+ { API_URL: 'https://example.test/api', APP_URL: 'https://example.test' },+ REDIRECT_URIS,+ );++ expect(uris).toEqual({+ google: 'https://example.test/api/api/auth/callback/google',+ oidc: 'https://example.test/api/api/auth/oauth2/callback/oidc',+ });+ });++ it('puts the path of API_URL in the links of the authentication emails', async () => {+ const links = await runAuth(+ { API_URL: 'https://example.test/api', APP_URL: 'https://example.test' },+ EMAIL_LINKS,+ );++ expect(Object.keys(links).sort()).toEqual([+ 'Confirm your email address',+ 'Reset your password',+ 'Your sign-in link',+ ]);+ for (const link of Object.values(links)) {+ expect(link).toStartWith('https://example.test/api/api/auth/');+ }+ });++ it('refuses to start with an API_URL that is not a URL', async () => {+ await expect(+ runAuth({ API_URL: 'not a url', APP_URL: 'http://app.test' }, ERROR_URL),+ ).rejects.toThrow('API_URL is not a valid URL: not a url');+ });+});diff --git a/apps/api/src/__tests__/integration/host-cookie.test.ts b/apps/api/src/__tests__/integration/host-cookie.test.tsnew file mode 100644index 00000000..40aec850--- /dev/null+++ b/apps/api/src/__tests__/integration/host-cookie.test.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { resetDb } from '#tests/helpers/db';++// The cookie names are fixed from the environment when @repo/auth loads, so each case+// loads it in a process of its own.+async function inspect(env: Record<string, string>) {+ const script = `+ const { auth } = await import('@repo/auth');+ const { authCookies } = await auth.$context;+ const res = await auth.handler(+ new Request(new URL(process.env.API_URL).origin + '/api/auth/sign-out', {+ method: 'POST',+ headers: { origin: new URL(process.env.APP_URL).origin },+ }),+ );+ console.log(JSON.stringify({ authCookies, signOut: res.headers.getSetCookie() }));+ process.exit(0);+ `;+ const proc = Bun.spawn([process.execPath, '-e', script], {+ env: { ...process.env, ...env },+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out, err] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ if ((await proc.exited) !== 0) throw new Error(err);+ return JSON.parse(out.trim().split('\n').pop()!) as {+ authCookies: Record<string, { name: string; attributes: Record<string, unknown> }>;+ signOut: string[];+ };+}++// Web at the root of its host and the api under /api, as deployed.+const HTTPS = { API_URL: 'https://app.example.test/api', APP_URL: 'https://app.example.test' };++// A sibling subdomain can plant a __Secure- cookie (with a Domain, or a narrower Path)+// that shadows the real one; a __Host- name is only accepted host-only at Path=/.+describe('session cookies use the __Host- prefix over HTTPS', () => {+ beforeEach(resetDb);++ it('names the session cookies __Host- with Path=/, Secure and no Domain', async () => {+ const { authCookies } = await inspect(HTTPS);++ for (const cookie of [+ authCookies.sessionToken!,+ authCookies.sessionData!,+ authCookies.dontRememberToken!,+ ]) {+ expect(cookie.name.startsWith('__Host-better-auth.')).toBe(true);+ expect(cookie.attributes.path).toBe('/');+ expect(cookie.attributes.secure).toBe(true);+ expect(cookie.attributes.domain).toBeUndefined();+ }+ });++ it('expires the __Host- cookie on sign-out in its one valid scope', async () => {+ const { signOut } = await inspect(HTTPS);++ const host = signOut.filter((c) => c.startsWith('__Host-better-auth.session_token=;'));+ expect(host.length).toBeGreaterThan(0);+ for (const cookie of host) {+ expect(cookie).toContain('Path=/');+ expect(cookie).not.toContain('Domain=');+ }+ });++ it('signs in and reads the session back through the __Host- cookie', async () => {+ const script = `+ const { auth } = await import('@repo/auth');+ const email = 'host-cookie-' + Date.now() + '@example.com';+ const res = await auth.api.signUpEmail({+ body: { email, password: 'test-password-123', name: 'Host Cookie' },+ asResponse: true,+ });+ const set = res.headers.getSetCookie();+ const cookie = set.map((c) => c.split(';')[0]).join('; ');+ const session = await auth.api.getSession({ headers: new Headers({ cookie }) });+ console.log(JSON.stringify({ set, email: session?.user.email, expected: email }));+ process.exit(0);+ `;+ const proc = Bun.spawn([process.execPath, '-e', script], {+ env: { ...process.env, ...HTTPS },+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out, err] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ if ((await proc.exited) !== 0) throw new Error(err);+ const { set, email, expected } = JSON.parse(out.trim().split('\n').pop()!);++ expect(set.some((c: string) => c.startsWith('__Host-better-auth.session_token='))).toBe(true);+ expect(email).toBe(expected);+ });++ it('keeps the plain names over HTTP (local development)', async () => {+ const { authCookies } = await inspect({+ API_URL: 'http://localhost:3000',+ APP_URL: 'http://localhost:3001',+ });++ expect(authCookies.sessionToken!.name).toBe('better-auth.session_token');+ });++ it('keeps the __Secure- names on the parent domain when the api has its own subdomain', async () => {+ const { authCookies } = await inspect({+ API_URL: 'https://api.example.test',+ APP_URL: 'https://app.example.test',+ });++ const cookie = authCookies.sessionToken!;+ expect(cookie.name).toBe('__Secure-better-auth.session_token');+ expect(String(cookie.attributes.domain)).toContain('example.test');+ expect(cookie.attributes.path).toBe('/');+ });+});diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 3b8cddaf..ac7d38ba 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -3,6 +3,7 @@ import {getSessionFromHeaders,oAuthDiscoveryMetadata,oAuthProtectedResourceMetadata,+ withPublicDiscoveryUrls,trustedOrigins,getAuthSettings,hasConfiguredGoogle,@@ -45,6 +46,11 @@ JSON errors use \`{ "error": "message" }\` and may also include a stable \`code\For agent clients, use the MCP endpoint at [${apiUrl}/mcp](${apiUrl}/mcp). SCIM, worker-internal routes, and repository webhooks use the separate credentials shown on their operations.`;+const authorizationServer = async (request: Request) =>+ withPublicDiscoveryUrls(await oAuthDiscoveryMetadata(auth)(request));+const protectedResource = async (request: Request) =>+ withPublicDiscoveryUrls(await oAuthProtectedResourceMetadata(auth)(request));+// The assembled Elysia app, without `.listen()`. `index.ts` imports this and// binds the port; tests import it and pass it to Eden Treaty to drive routes in// memory (no network). Keep the chain unbroken so `type App` stays accurate.@@ -227,12 +233,16 @@ export const app = new Elysia()// OAuth discovery lives at the API origin because MCP clients resolve the// authorization server from protected-resource metadata before entering the// Better Auth base path.- .get('/.well-known/oauth-authorization-server', ({ request }) =>- oAuthDiscoveryMetadata(auth)(request),- )- .get('/.well-known/oauth-protected-resource/mcp', ({ request }) =>- oAuthProtectedResourceMetadata(auth)(request),- )+ //+ // An issuer with a path is looked up with the path after the well-known segment+ // (RFC 8414 §3), and some clients fall back to OpenID discovery, so each document+ // answers under any suffix; the proxy decides which of these paths reach the api.+ .get('/.well-known/oauth-authorization-server', ({ request }) => authorizationServer(request))+ .get('/.well-known/oauth-authorization-server/*', ({ request }) => authorizationServer(request))+ .get('/.well-known/openid-configuration', ({ request }) => authorizationServer(request))+ .get('/.well-known/openid-configuration/*', ({ request }) => authorizationServer(request))+ .get('/.well-known/oauth-protected-resource', ({ request }) => protectedResource(request))+ .get('/.well-known/oauth-protected-resource/*', ({ request }) => protectedResource(request))// better-auth: forward every /api/auth/* request to its handler. The OIDC// callback gets one extra step afterwards: folding the provider's `groups` claim// into the SCIM group tables, so a group mapped to a project in god mode grantsdiff --git a/apps/api/src/mcp/__tests__/integration/discovery-public-url.test.ts b/apps/api/src/mcp/__tests__/integration/discovery-public-url.test.tsnew file mode 100644index 00000000..784dd918--- /dev/null+++ b/apps/api/src/mcp/__tests__/integration/discovery-public-url.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from 'bun:test';++// @repo/auth reads API_URL when it loads, so the app with a public path prefix is+// loaded in a process of its own, once for every request below.+const REQUESTS = [+ { method: 'GET', path: '/.well-known/oauth-authorization-server' },+ { method: 'GET', path: '/.well-known/oauth-protected-resource/mcp' },+ { method: 'GET', path: '/.well-known/oauth-authorization-server/api' },+ { method: 'GET', path: '/.well-known/openid-configuration' },+ { method: 'GET', path: '/.well-known/openid-configuration/api' },+ { method: 'GET', path: '/.well-known/oauth-protected-resource/api/mcp' },+ { method: 'POST', path: '/mcp' },+];++interface Answer {+ status: number;+ challenge: string | null;+ body: Record<string, unknown>;+}++async function discover(): Promise<Map<string, Answer>> {+ const script = `+ const { app } = await import('${new URL('../../../app.ts', import.meta.url).pathname}');+ const out = {};+ for (const { method, path } of ${JSON.stringify(REQUESTS)}) {+ const res = await app.handle(new Request('http://localhost' + path, {+ method,+ headers: { 'content-type': 'application/json' },+ body: method === 'POST' ? JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) : undefined,+ }));+ out[method + ' ' + path] = {+ status: res.status,+ challenge: res.headers.get('www-authenticate'),+ body: await res.json(),+ };+ }+ console.log(JSON.stringify(out));+ process.exit(0);+ `;+ const proc = Bun.spawn([process.execPath, '-e', script], {+ env: { ...process.env, API_URL: 'https://example.test/api', APP_URL: 'https://example.test' },+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const [out, err] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ if ((await proc.exited) !== 0) throw new Error(err);+ return new Map(+ Object.entries(JSON.parse(out.trim().split('\n').pop()!) as Record<string, Answer>),+ );+}++let answers: Promise<Map<string, Answer>> | undefined;++// Loading the app takes a few seconds, so the first case to ask carries the load and+// gets the time for it.+async function answer(path: string, method = 'GET'): Promise<Answer> {+ return (await (answers ??= discover())).get(`${method} ${path}`)!;+}++const LOAD_TIMEOUT = 20_000;++describe('MCP discovery behind a public path prefix', () => {+ it(+ 'points the authorization-server metadata at the public prefix',+ async () => {+ const res = await answer('/.well-known/oauth-authorization-server');++ expect(res!.status).toBe(200);+ expect(res!.body).toMatchObject({+ issuer: 'https://example.test/api',+ authorization_endpoint: 'https://example.test/api/api/auth/mcp/authorize',+ token_endpoint: 'https://example.test/api/api/auth/mcp/token',+ registration_endpoint: 'https://example.test/api/api/auth/mcp/register',+ jwks_uri: 'https://example.test/api/api/auth/mcp/jwks',+ });+ },+ LOAD_TIMEOUT,+ );++ it(+ 'names the prefixed issuer as authorization server of the resource',+ async () => {+ const res = await answer('/.well-known/oauth-protected-resource/mcp');++ expect(res!.body).toMatchObject({+ resource: 'https://example.test/api/mcp',+ authorization_servers: ['https://example.test/api'],+ });+ },+ LOAD_TIMEOUT,+ );++ it(+ 'answers the RFC 8414 and OpenID lookups of a prefixed issuer',+ async () => {+ const results = await Promise.all([+ answer('/.well-known/oauth-authorization-server/api'),+ answer('/.well-known/openid-configuration'),+ answer('/.well-known/openid-configuration/api'),+ answer('/.well-known/oauth-protected-resource/api/mcp'),+ ]);++ for (const res of results) expect(res.status).toBe(200);+ expect(results[0]!.body.issuer).toBe('https://example.test/api');+ expect(results[3]!.body.resource).toBe('https://example.test/api/mcp');+ },+ LOAD_TIMEOUT,+ );++ it(+ 'challenges MCP clients with metadata reachable under the prefix',+ async () => {+ const res = await answer('/mcp', 'POST');++ const expected =+ 'Bearer resource_metadata="https://example.test/api/.well-known/oauth-protected-resource/mcp"';+ expect(res!.status).toBe(401);+ expect(res!.challenge).toBe(expected);+ expect((res!.body.error as Record<string, unknown>)['www-authenticate']).toBe(expected);+ },+ LOAD_TIMEOUT,+ );++ it('passes through the null better-auth answers when it cannot build a document', async () => {+ const { withPublicDiscoveryUrls } = await import('@repo/auth');++ const res = await withPublicDiscoveryUrls(Response.json(null));++ expect(res.status).toBe(200);+ expect(await res.json()).toBeNull();+ });+});diff --git a/apps/api/src/mcp/mount.ts b/apps/api/src/mcp/mount.tsindex 88f005de..776e62b4 100644--- a/apps/api/src/mcp/mount.ts+++ b/apps/api/src/mcp/mount.ts@@ -1,6 +1,6 @@import { t } from 'elysia';import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';-import { auth, isAccountDeactivated, withMcpAuth } from '@repo/auth';+import { auth, isAccountDeactivated, withMcpAuth, withPublicMcpChallenge } from '@repo/auth';import { buildMcpServer } from './server';import type { McpApp } from './types';import type { McpCredential } from './credential';@@ -57,9 +57,11 @@ export function mountMcp(app: any): void {}// withMcpAuth verifies the native OAuth token and returns the standard MCP// WWW-Authenticate challenge that clients use for OAuth discovery.- return withMcpAuth(auth, (_request, oauthSession) =>- serve({ kind: 'oauth', accessToken: oauthSession.accessToken }, oauthSession.userId),- )(request);+ return withPublicMcpChallenge(+ await withMcpAuth(auth, (_request, oauthSession) =>+ serve({ kind: 'oauth', accessToken: oauthSession.accessToken }, oauthSession.userId),+ )(request),+ );},{body: t.Any(),diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex d5fd73bd..eb1afa20 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -2,7 +2,7 @@# These are read by the server at startup and handed to the browser on every render,# so a deployment sets them on the container instead (see the root .env.example).-# Public API origin the browser reaches (same value as API_URL in the root .env):+# Public URL of the api the browser reaches (same value as API_URL in the root .env):API_URL=http://localhost:3000# Legal document URLs shown on the logged-out screens. Point them at this instance'sdiff --git a/apps/web/src/lib/auth-client.test.ts b/apps/web/src/lib/auth-client.test.tsnew file mode 100644index 00000000..1437a7d2--- /dev/null+++ b/apps/web/src/lib/auth-client.test.ts@@ -0,0 +1,20 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import { authBaseURL } from './auth-client';++describe('authBaseURL', () => {+ it('adds the better-auth mount to an API_URL that is an origin', () => {+ assert.equal(authBaseURL('https://api.example.com'), 'https://api.example.com/api/auth');+ });++ it('keeps the path of an API_URL served under a prefix', () => {+ assert.equal(+ authBaseURL('https://app.example.com/api'),+ 'https://app.example.com/api/api/auth',+ );+ assert.equal(+ authBaseURL('https://app.example.com/api/'),+ 'https://app.example.com/api/api/auth',+ );+ });+});diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.tsindex 5d92d229..07cb303e 100644--- a/apps/web/src/lib/auth-client.ts+++ b/apps/web/src/lib/auth-client.ts@@ -5,11 +5,17 @@ import { passkeyClient } from '@better-auth/passkey/client';import { apiKeyClient } from '@better-auth/api-key/client';import { API_URL, markSigningOut } from '@/lib/api/core/client';+// better-auth appends its default /api/auth only to a bare origin; an API_URL with a+// path would be used as-is, so the mount is spelled out.+export function authBaseURL(apiUrl: string): string {+ return `${apiUrl.replace(/\/+$/, '')}/api/auth`;+}+// The better-auth handler lives on the backend (Elysia), so baseURL is the API origin.// inferAdditionalFields declares the custom `role` column added in @repo/auth so the// session user is typed with it (the web app never imports server packages).export const authClient = createAuthClient({- baseURL: API_URL,+ baseURL: authBaseURL(API_URL),plugins: [inferAdditionalFields({user: {diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.tsindex 58cb16bf..c6b8c992 100644--- a/apps/web/src/proxy.test.ts+++ b/apps/web/src/proxy.test.ts@@ -46,6 +46,21 @@ describe('proxy', () => {assert.equal(res.headers.get('location'), 'http://localhost/');});+ // Over HTTPS the api names the session cookie with the __Host- prefix.+ it('treats a __Host- session cookie as a session', () => {+ const res = run('/login', '__Host-better-auth.session_token=value');+ assert.equal(res.headers.get('location'), 'http://localhost/');+ });++ it('expires a __Host- cookie only at Path=/, with Secure and no Domain', () => {+ const res = run('/login?expired=1', '__Host-better-auth.session_token=stale');+ const cleared = res.headers.getSetCookie();+ assert.equal(cleared.length, 1);+ assert.match(cleared[0]!, /^__Host-better-auth\.session_token=; Path=\/; Expires/);+ assert.match(cleared[0]!, /Secure/);+ assert.ok(!cleared[0]!.includes('Domain='));+ });+it('sends a visitor without a session to the login page', () => {const res = run('/', undefined);assert.equal(res.headers.get('location'), 'http://localhost/login');diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.tsindex 834f5005..72d7fa19 100644--- a/apps/web/src/proxy.ts+++ b/apps/web/src/proxy.ts@@ -33,7 +33,9 @@ function clearSession(request: NextRequest): NextResponse {const response = NextResponse.next();for (const { name } of request.cookies.getAll()) {if (!name.includes('better-auth.')) continue;- response.cookies.delete({ name, path: '/', secure: name.startsWith('__Secure-') });+ // A __Secure- or __Host- name is only accepted back with `secure`.+ const secure = name.startsWith('__Secure-') || name.startsWith('__Host-');+ response.cookies.delete({ name, path: '/', secure });}return response;}@@ -55,7 +57,11 @@ export function proxy(request: NextRequest) {// `/login?expired=1`, where the cookie is cleared for good.function gate(request: NextRequest): NextResponse {const { pathname } = request.nextUrl;- const hasSession = getSessionCookie(request) != null;+ // Over HTTPS the api names the session cookie with the __Host- prefix, which+ // getSessionCookie only finds when told the prefix.+ const hasSession =+ (getSessionCookie(request) ??+ getSessionCookie(request, { cookiePrefix: '__Host-better-auth' })) != null;const matches = matcher(pathname);if (OPEN_PATHS.some(matches)) return NextResponse.next();diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 09c24196..af60e893 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -14,7 +14,7 @@ The stack refuses to start while one of these is missing:| Variable | Value || ----------------------- | ------------------------------------------ |-| `API_URL` | public origin of the api |+| `API_URL` | public URL of the api || `APP_URL` | public origin of the web app || `POSTGRES_PASSWORD` | `openssl rand -base64 32` || `BETTER_AUTH_SECRET` | `openssl rand -base64 32` |@@ -34,6 +34,36 @@ becomes the instance admin.`.env.example` documents every variable, including the optional ones: legal document URLs,passkey and cookie settings, telemetry opt-out, and worker tuning.+## Where the api lives++`API_URL` takes one of two forms:++- **Its own subdomain**, such as `https://api.example.com` beside `APP_URL=https://app.example.com`.+ The session cookie is set on the parent domain (`.example.com`), so every subdomain of it+ receives the cookie. `COOKIE_DOMAIN` narrows it when the two share a deeper parent. An+ `APP_URL` on the apex domain (`https://example.com`) has no parent to take, so this form+ needs `COOKIE_DOMAIN=.example.com`.+- **A path on the web's host**, such as `https://app.example.com/api` beside+ `APP_URL=https://app.example.com`. No second hostname or certificate is needed, and the+ session cookie stays on that one host: it has no `Domain`, and over HTTPS its name carries+ the `__Host-` prefix, which keeps another subdomain from setting one in its place.++With a path, the reverse proxy sends that path to the api and removes it on the way, so the+api receives `/projects`, `/api/auth/...` and `/mcp` as it does on its own subdomain:++```+https://app.example.com/api/* -> api:3000/* (prefix removed)+https://app.example.com/* -> web:3001/*+```++For MCP clients that sign in with OAuth, the proxy also sends the discovery documents of the+host to the api: `/.well-known/oauth-authorization-server*`,+`/.well-known/oauth-protected-resource*` and `/.well-known/openid-configuration*`.++The OAuth redirect URIs that god mode shows include the path. An api on a different+registrable domain than the web app (`api.other.com`) does not work: the session cookie+cannot be shared across sites.+## Single sign-onAny provider with an OpenID Connect discovery document works: Keycloak, Authentik, KanIDM,diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex eb865ec5..d56bdff7 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -245,14 +245,20 @@ not required for it.the web app owns its own `auth-client.ts`.- Changing the config (plugins, fields) can change the DB tables → run `bun run auth:generate`(writes `packages/db/src/schema/auth.ts`), then `db:generate` + `db:migrate`.-- Config is env-driven: `API_URL` (backend origin, used as better-auth `baseURL`),- `BETTER_AUTH_SECRET`, `APP_URL` (frontend origin(s), comma-separated). `API_URL` and- `APP_URL` are mandatory and have no default — importing this module throws- when either is missing. Do not add a localhost fallback: cookies, the passkey- relying party, the cookie domain and every link in an authentication email are- derived from them, so a wrong value fails silently at runtime instead of at startup.- The parsed `trustedOrigins` list (from `APP_URL`) is exported so the api's CORS uses- the same value.-- **Cross-domain prod:** default cookies are `sameSite: "lax"`. If frontend/backend run on- different domains, switch to `sameSite: "none"` + `secure: true`; for subdomains use- `advanced.crossSubDomainCookies`.+- Config is env-driven: `API_URL` (public URL of the backend), `BETTER_AUTH_SECRET`,+ `APP_URL` (frontend origin(s), comma-separated). `API_URL` and `APP_URL` are mandatory+ and have no default — importing this module throws when either is missing. Do not add+ a localhost fallback: cookies, the passkey relying party, the cookie domain and every+ link in an authentication email are derived from them, so a wrong value fails silently+ at runtime instead of at startup. The parsed `trustedOrigins` list (from `APP_URL`) is+ exported so the api's CORS uses the same value.+- **`API_URL` with a path** (the api under a path of the web's host): better-auth's+ `baseURL` gets only the origin, because a path there replaces its `/api/auth` base path+ and the api's fixed mount stops matching. Every public URL built from it — the OAuth+ redirect URIs, the links in auth emails, the MCP resource and discovery documents — gets+ the path back through `apiPublicUrl` / `withPublicOrigin`.+- **Cookies:** `sameSite: "lax"`. Web and api on sibling subdomains share the cookie through+ `advanced.crossSubDomainCookies` on the parent domain of `APP_URL` (`COOKIE_DOMAIN`+ overrides it). On one host the cookie has no domain, and over HTTPS the session cookies+ are named `__Host-better-auth.*`. If frontend/backend run on different domains, switch+ to `sameSite: "none"` + `secure: true`.diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex 536f0f21..c609a342 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -25,7 +25,7 @@ import { sendAuthEmail } from './mail';// that misses it has to fail at startup instead of running on a localhost default.export const trustedOrigins = (process.env.APP_URL ?? '').split(',')- .map((origin) => origin.trim())+ .map((origin) => origin.trim().replace(/\/+$/, '')).filter(Boolean);if (trustedOrigins.length === 0) {throw new Error('APP_URL is not set: public origin(s) of the web app.');@@ -49,9 +49,23 @@ function parentDomain(origin: string | undefined): string | undefined {return '.' + labels.slice(1).join('.');}-// Explicit COOKIE_DOMAIN wins (needed for multi-label TLDs or deep subdomains);-// otherwise derive it from the frontend origin.-const cookieDomain = process.env.COOKIE_DOMAIN || parentDomain(trustedOrigins[0]);+function safeUrl(value: string | undefined): URL | undefined {+ if (!value) return undefined;+ try {+ return new URL(value);+ } catch {+ return undefined;+ }+}++// parentDomain() would widen the cookie to sibling subdomains even when web and api+// share a host, where a host-only cookie is enough.+const sameHost = safeUrl(trustedOrigins[0])?.hostname === safeUrl(process.env.API_URL)?.hostname;++// COOKIE_DOMAIN wins (multi-label TLDs, deep subdomains); otherwise host-only when web+// and api share a host, else the parent domain of the frontend.+const cookieDomain =+ process.env.COOKIE_DOMAIN || (sameHost ? undefined : parentDomain(trustedOrigins[0]));// WebAuthn relying-party id: the frontend domain the passkey is bound to (no port,// no scheme). The WebAuthn ceremony runs in the frontend JS, so the expected origin@@ -60,29 +74,103 @@ const cookieDomain = process.env.COOKIE_DOMAIN || parentDomain(trustedOrigins[0]// public frontend hostname.const passkeyRpID = process.env.PASSKEY_RP_ID ?? new URL(trustedOrigins[0]).hostname;-// Backend origin where the better-auth handler is mounted (/api/auth/*). Mandatory:-// every link in an authentication email and the Google redirect URI are built from it.-const baseURL = process.env.API_URL;-if (!baseURL) {- throw new Error('API_URL is not set: public origin of the backend.');+// Public URL of the backend, with the path a subpath proxy adds; the links in auth+// emails and the OAuth redirect URIs are built from it.+const apiPublicUrl = (process.env.API_URL ?? '').replace(/\/+$/, '');+if (!apiPublicUrl) {+ throw new Error('API_URL is not set: public URL of the backend.');+}+const apiUrl = safeUrl(apiPublicUrl);+if (!apiUrl) {+ throw new Error(`API_URL is not a valid URL: ${apiPublicUrl}`);+}++// A baseURL with a path replaces better-auth's /api/auth basePath and the api's fixed+// mount stops matching, so it only gets the origin.+const baseURL = apiUrl.origin;+const apiHasPath = apiUrl.pathname !== '/';++// Over HTTPS with a host-only cookie the session cookies carry the __Host- prefix:+// the browser then refuses a cookie of that name planted by a sibling subdomain (with+// a Domain, or a narrower Path), which __Secure- does not prevent. better-auth only+// writes __Secure-, so its automatic prefix is turned off and both prefixes are written+// into the names here.+const hostPrefixedCookies = baseURL.startsWith('https://') && !cookieDomain;+const SESSION_COOKIES = ['session_token', 'session_data', 'account_data', 'dont_remember'];++// better-auth builds the links it hands to the mailers from the origin-only baseURL;+// this puts the path back.+function withPublicOrigin(url: string): string {+ return url.startsWith(baseURL) ? apiPublicUrl + url.slice(baseURL.length) : url;+}++// MCP clients follow the discovery documents verbatim, and better-auth builds their+// URLs from the same origin-only baseURL: behind a path prefix they would land on+// whatever serves the root of the host. `resource` comes from apiPublicUrl already.+const DISCOVERY_URL_KEYS = new Set([+ 'issuer',+ 'authorization_servers',+ 'authorization_endpoint',+ 'token_endpoint',+ 'userinfo_endpoint',+ 'jwks_uri',+ 'registration_endpoint',+]);++export async function withPublicDiscoveryUrls(response: Response): Promise<Response> {+ const metadata = (await response.json()) as Record<string, unknown> | null;+ // better-auth answers null when it cannot build the document (no issuer).+ if (metadata === null || typeof metadata !== 'object') {+ return new Response(JSON.stringify(metadata), {+ status: response.status,+ headers: response.headers,+ });+ }+ for (const [key, value] of Object.entries(metadata)) {+ if (!DISCOVERY_URL_KEYS.has(key)) continue;+ if (typeof value === 'string') metadata[key] = withPublicOrigin(value);+ else if (Array.isArray(value)) metadata[key] = value.map((v) => withPublicOrigin(String(v)));+ }+ return new Response(JSON.stringify(metadata), {+ status: response.status,+ headers: response.headers,+ });}+// withMcpAuth points the 401 challenge at better-auth's own copy of the metadata,+// built from the origin-only baseURL; behind a path prefix it is replaced by the copy+// served under the prefix. Without one, better-auth's challenge reaches the api as is.+const MCP_CHALLENGE = `Bearer resource_metadata="${apiPublicUrl}/.well-known/oauth-protected-resource/mcp"`;++export async function withPublicMcpChallenge(response: Response): Promise<Response> {+ if (!apiHasPath || !response.headers.has('WWW-Authenticate')) return response;+ const headers = new Headers(response.headers);+ headers.set('WWW-Authenticate', MCP_CHALLENGE);+ const body = (await response.json()) as { error?: Record<string, unknown> };+ if (body.error) body.error['www-authenticate'] = MCP_CHALLENGE;+ return new Response(JSON.stringify(body), { status: response.status, headers });+}++// The fallback for a callback that fails early is better-auth's own /api/auth/error;+// under a path prefix that route is outside it, and /login turns ?error= into a message.+const oauthErrorURL = apiHasPath ? `${trustedOrigins[0]}/login` : undefined;+// User roles. "god" is the owner of the instance: the very first registered user// gets it automatically; everyone after is a plain "user". The role is assigned// server-side (input: false) so a client cannot request it at sign-up.export const USER_ROLES = ['god', 'user'] as const;export type UserRole = (typeof USER_ROLES)[number];+// The exact authorized redirect URI to register in the Google Cloud console;+// god mode shows it for copying.+export const GOOGLE_REDIRECT_URI = `${apiPublicUrl}/api/auth/callback/google`;+// Google OAuth credentials live in the database (god mode), not in env. The provider// is built once at startup, but it keeps this options object by reference and reads// clientId / clientSecret off it on every call, so refreshing the object per request// is what lets the owner change or revoke the credentials without a restart.-const googleOptions = { clientId: '', clientSecret: '' };--// The exact value that has to be registered as an authorized redirect URI in the-// Google Cloud console. better-auth derives it from baseURL; god mode shows it so the-// owner can copy it instead of assembling it by hand.-export const GOOGLE_REDIRECT_URI = `${baseURL}/api/auth/callback/google`;+// redirectURI is explicit: the one inferred from the origin-only baseURL lacks the path.+const googleOptions = { clientId: '', clientSecret: '', redirectURI: GOOGLE_REDIRECT_URI };// Loads the stored credentials into that object and reports whether Google sign-in// can run. A read failure disables the provider rather than failing the request with@@ -107,6 +195,11 @@ async function refreshGoogleOptions(): Promise<boolean> {// without a restart. Assign the fields, never replace the object.export const OIDC_PROVIDER_ID = 'oidc';+// The exact redirect URI to register with the identity provider; god mode shows it+// for copying.+export const OIDC_REDIRECT_URI = `${apiPublicUrl}/api/auth/oauth2/callback/${OIDC_PROVIDER_ID}`;++// redirectURI is explicit for the same reason as in googleOptions.const oidcOptions: GenericOAuthConfig = {providerId: OIDC_PROVIDER_ID,clientId: '',@@ -114,12 +207,9 @@ const oidcOptions: GenericOAuthConfig = {discoveryUrl: '',scopes: [],pkce: true,+ redirectURI: OIDC_REDIRECT_URI,};-// The exact value that has to be registered as a redirect URI with the identity-// provider. god mode shows it so the owner can copy it instead of assembling it.-export const OIDC_REDIRECT_URI = `${baseURL}/api/auth/oauth2/callback/${OIDC_PROVIDER_ID}`;-// Loads the stored credentials into that object and reports whether OIDC sign-in can// run. A read failure disables the provider rather than failing the request with a// stale secret.@@ -318,6 +408,7 @@ export const API_KEY_MAX_EXPIRES_IN_DAYS = 365;export const auth = betterAuth({baseURL,secret: process.env.BETTER_AUTH_SECRET,+ onAPIError: oauthErrorURL ? { errorURL: oauthErrorURL } : undefined,database: drizzleAdapter(db, {provider: 'pg',@@ -352,7 +443,7 @@ export const auth = betterAuth({to: user.email,subject: 'Reset your password',text: 'Use the link below to set a new password. Ignore this email if you did not ask for it.',- url,+ url: withPublicOrigin(url),});},},@@ -369,7 +460,7 @@ export const auth = betterAuth({to: user.email,subject: 'Confirm your email address',text: 'Use the link below to confirm this address and finish signing up.',- url,+ url: withPublicOrigin(url),});},},@@ -662,7 +753,7 @@ export const auth = betterAuth({to: email,subject: 'Your sign-in link',text: 'Use the link below to sign in. It works once and expires shortly.',- url,+ url: withPublicOrigin(url),});},}),@@ -686,7 +777,7 @@ export const auth = betterAuth({// clients such as ChatGPT without exposing a personal API key.mcp({loginPage: `${trustedOrigins[0]}/login`,- resource: `${baseURL}/mcp`,+ resource: `${apiPublicUrl}/mcp`,oidcConfig: {loginPage: `${trustedOrigins[0]}/login`,requirePKCE: true,@@ -728,9 +819,21 @@ export const auth = betterAuth({: {}),// For a single site (localhost / one domain) "lax" is enough. Subdomains of one// registrable domain are same-site, so "lax" cookies are still sent between them.+ ...(hostPrefixedCookies+ ? {+ useSecureCookies: false,+ cookiePrefix: '__Secure-better-auth',+ cookies: Object.fromEntries(+ SESSION_COOKIES.map((name) => [+ name,+ { name: `__Host-better-auth.${name}`, attributes: { path: '/', secure: true } },+ ]),+ ),+ }+ : {}),defaultCookieAttributes: {sameSite: 'lax',- secure: process.env.NODE_ENV === 'production',+ secure: hostPrefixedCookies || process.env.NODE_ENV === 'production',},},});