paperclip/server/src/auth/better-auth.ts
Devin Foley b2496c8067
fix(auth): trust allowed hostname port variants on detected listen port (#4554)
## Thinking Path

> - Paperclip is the control plane for autonomous AI companies, so
authenticated board access has to be predictable across local and
worktree deployments.
> - This change sits in the authenticated-mode server startup and Better
Auth origin-trust wiring.
> - The original auth branch fixed one real gap by adding port-qualified
trusted origins for allowed hostnames on non-default ports.
> - Review of that branch found a second-order bug: trusted origins were
still derived from the configured port before startup detected the
actual listen port.
> - In isolated worktrees, that meant a common `3100 -> 3101` port shift
could still leave Better Auth trusting the stale origin.
> - This pull request keeps the original allowed-hostname port-variant
fix, then moves trust derivation onto the resolved listen port and adds
regression coverage around startup wiring.
> - The benefit is that authenticated sessions keep working on allowed
private hostnames even when Paperclip has to auto-shift to a different
local port.

## What Changed

- Added `:port` trusted-origin variants for authenticated-mode
`allowedHostnames` when Paperclip runs on non-default ports.
- Changed authenticated startup so `listenPort` is detected before
Better Auth initialization, and explicit auth base URLs are rewritten
before auth startup.
- Updated `deriveAuthTrustedOrigins()` to accept the resolved listen
port so Better Auth trusts the actual browser origin instead of the
stale configured port.
- Added focused regression coverage in
`server/src/__tests__/better-auth.test.ts` and
`server/src/__tests__/server-startup-feedback-export.test.ts`.

## Verification

- `pnpm exec vitest run server/src/__tests__/better-auth.test.ts
server/src/__tests__/server-startup-feedback-export.test.ts`
- Reviewer re-check: reviewed commits `380f5b9f` and `092bb34c` after
the follow-up fix landed and found no remaining issues.

## Risks

- Low risk: this only affects authenticated-mode origin derivation and
startup ordering around detected listen ports.
- Main behavioral shift: startup no longer mutates `config.port` to the
selected port; it now carries `requestedListenPort` separately and uses
`listenPort` where runtime behavior needs the resolved value.
- If another path was implicitly relying on `config.port` being
overwritten during startup, that path would need follow-up, though the
current startup/test coverage did not reveal one.

> I checked `ROADMAP.md` and did not find an overlapping planned core
work item for this auth trusted-origin port handling fix.

## Model Used

- OpenAI Codex via Paperclip `codex_local` agents for implementation and
review. Exact backend model ID/context window were not surfaced in this
run context; work was performed through the Codex local adapter with
tool use, code execution, and review passes.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-04-26 15:40:39 -07:00

176 lines
5.5 KiB
TypeScript

import type { Request, RequestHandler } from "express";
import type { IncomingHttpHeaders } from "node:http";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { toNodeHandler } from "better-auth/node";
import type { Db } from "@paperclipai/db";
import {
authAccounts,
authSessions,
authUsers,
authVerifications,
} from "@paperclipai/db";
import type { Config } from "../config.js";
import { resolvePaperclipInstanceId } from "../home-paths.js";
export type BetterAuthSessionUser = {
id: string;
email?: string | null;
name?: string | null;
};
export type BetterAuthSessionResult = {
session: { id: string; userId: string } | null;
user: BetterAuthSessionUser | null;
};
type BetterAuthInstance = ReturnType<typeof betterAuth>;
const AUTH_COOKIE_PREFIX_FALLBACK = "default";
const AUTH_COOKIE_PREFIX_INVALID_SEGMENTS_RE = /[^a-zA-Z0-9_-]+/g;
export function deriveAuthCookiePrefix(instanceId = resolvePaperclipInstanceId()): string {
const scopedInstanceId = instanceId
.trim()
.replace(AUTH_COOKIE_PREFIX_INVALID_SEGMENTS_RE, "-")
.replace(/^-+|-+$/g, "") || AUTH_COOKIE_PREFIX_FALLBACK;
return `paperclip-${scopedInstanceId}`;
}
export function buildBetterAuthAdvancedOptions(input: { disableSecureCookies: boolean }) {
return {
cookiePrefix: deriveAuthCookiePrefix(),
...(input.disableSecureCookies ? { useSecureCookies: false } : {}),
};
}
function headersFromNodeHeaders(rawHeaders: IncomingHttpHeaders): Headers {
const headers = new Headers();
for (const [key, raw] of Object.entries(rawHeaders)) {
if (!raw) continue;
if (Array.isArray(raw)) {
for (const value of raw) headers.append(key, value);
continue;
}
headers.set(key, raw);
}
return headers;
}
function headersFromExpressRequest(req: Request): Headers {
return headersFromNodeHeaders(req.headers);
}
export function deriveAuthTrustedOrigins(config: Config, opts?: { listenPort?: number }): string[] {
const baseUrl = config.authBaseUrlMode === "explicit" ? config.authPublicBaseUrl : undefined;
const trustedOrigins = new Set<string>();
if (baseUrl) {
try {
trustedOrigins.add(new URL(baseUrl).origin);
} catch {
// Better Auth will surface invalid base URL separately.
}
}
if (config.deploymentMode === "authenticated") {
const port = opts?.listenPort ?? config.port;
const needsPortVariants = port !== 80 && port !== 443;
for (const hostname of config.allowedHostnames) {
const trimmed = hostname.trim().toLowerCase();
if (!trimmed) continue;
trustedOrigins.add(`https://${trimmed}`);
trustedOrigins.add(`http://${trimmed}`);
if (needsPortVariants) {
trustedOrigins.add(`https://${trimmed}:${port}`);
trustedOrigins.add(`http://${trimmed}:${port}`);
}
}
}
return Array.from(trustedOrigins);
}
export function createBetterAuthInstance(db: Db, config: Config, trustedOrigins: string[]): BetterAuthInstance {
const baseUrl = config.authBaseUrlMode === "explicit" ? config.authPublicBaseUrl : undefined;
const secret = process.env.BETTER_AUTH_SECRET ?? process.env.PAPERCLIP_AGENT_JWT_SECRET;
if (!secret) {
throw new Error(
"BETTER_AUTH_SECRET (or PAPERCLIP_AGENT_JWT_SECRET) must be set. " +
"For local development, set BETTER_AUTH_SECRET=paperclip-dev-secret in your .env file.",
);
}
const publicUrl = process.env.PAPERCLIP_PUBLIC_URL ?? baseUrl;
const isHttpOnly = publicUrl ? publicUrl.startsWith("http://") : false;
const authConfig = {
baseURL: baseUrl,
secret,
trustedOrigins,
database: drizzleAdapter(db, {
provider: "pg",
schema: {
user: authUsers,
session: authSessions,
account: authAccounts,
verification: authVerifications,
},
}),
emailAndPassword: {
enabled: true,
requireEmailVerification: false,
disableSignUp: config.authDisableSignUp,
},
advanced: buildBetterAuthAdvancedOptions({ disableSecureCookies: isHttpOnly }),
};
if (!baseUrl) {
delete (authConfig as { baseURL?: string }).baseURL;
}
return betterAuth(authConfig);
}
export function createBetterAuthHandler(auth: BetterAuthInstance): RequestHandler {
const handler = toNodeHandler(auth);
return (req, res, next) => {
void Promise.resolve(handler(req, res)).catch(next);
};
}
export async function resolveBetterAuthSessionFromHeaders(
auth: BetterAuthInstance,
headers: Headers,
): Promise<BetterAuthSessionResult | null> {
const api = (auth as unknown as { api?: { getSession?: (input: unknown) => Promise<unknown> } }).api;
if (!api?.getSession) return null;
const sessionValue = await api.getSession({
headers,
});
if (!sessionValue || typeof sessionValue !== "object") return null;
const value = sessionValue as {
session?: { id?: string; userId?: string } | null;
user?: { id?: string; email?: string | null; name?: string | null } | null;
};
const session = value.session?.id && value.session.userId
? { id: value.session.id, userId: value.session.userId }
: null;
const user = value.user?.id
? {
id: value.user.id,
email: value.user.email ?? null,
name: value.user.name ?? null,
}
: null;
if (!session || !user) return null;
return { session, user };
}
export async function resolveBetterAuthSession(
auth: BetterAuthInstance,
req: Request,
): Promise<BetterAuthSessionResult | null> {
return resolveBetterAuthSessionFromHeaders(auth, headersFromExpressRequest(req));
}