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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ PLATFORM_SITE_DOMAIN=localhost
# PLATFORM_SITE_DOMAIN apex as its custom domain (dogfooding).
PLATFORM_TEAM_ID=
ENABLE_TRUST_PROXY=false
# Optional: a hop count, `true`, `false`, or proxy addresses and subnets such
# as `loopback, 10.0.0.0/8`. When set, it takes precedence over
# ENABLE_TRUST_PROXY.
TRUST_PROXY=

# Optional published host ports.
API_PORT=4000
Expand Down
5 changes: 5 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ API_PUBLIC_URL=http://localhost:4000
# proxy hop (for example, a local Tailscale Funnel proxying to this process).
# This lets Express and express-rate-limit use X-Forwarded-For correctly.
ENABLE_TRUST_PROXY=false
# Optional: the proxies to trust for the client address (Express's
# `trust proxy`): a hop count, `true`, `false`, or addresses and subnets such
# as `loopback, 10.0.0.0/8`. When set, it takes precedence over
# ENABLE_TRUST_PROXY.
# TRUST_PROXY=

# Shared secret required on the X-Frontlit-Provisioning-Secret header for
# POST /provisioning/teams.
Expand Down
18 changes: 9 additions & 9 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@
"@ai-sdk/azure": "^3.0.99",
"@ai-sdk/openai": "^4.0.23",
"@aws-sdk/client-s3": "^3.1111.0",
"@better-auth/cimd": "1.7.7",
"@better-auth/oauth-provider": "1.7.7",
"@codelitdev/mcp-server-kit": "0.8.0",
"@codelitdev/oauth-server-kit": "0.8.0",
"@codelitdev/observability": "0.8.0",
"@codelitdev/platform": "0.8.0",
"@better-auth/cimd": "1.7.22",
"@better-auth/oauth-provider": "1.7.22",
"@codelitdev/mcp-server-kit": "0.15.0",
"@codelitdev/oauth-server-kit": "0.15.0",
"@codelitdev/observability": "0.15.0",
"@codelitdev/platform": "0.15.0",
"@frontlit/api-contract": "workspace:*",
"@frontlit/page-builder": "workspace:*",
"@frontlit/text-editor": "workspace:*",
Expand All @@ -55,7 +55,7 @@
"@ts-rest/open-api": "^3.52.1",
"ai": "^7.0.41",
"ai-sdk-provider-opencode-sdk": "^4.1.0",
"better-auth": "1.7.7",
"better-auth": "1.7.22",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"drizzle-orm": "^0.45.2",
Expand All @@ -74,8 +74,8 @@
"zod-to-json-schema": "^3.25.2"
},
"devDependencies": {
"@codelitdev/billing": "0.8.0",
"@codelitdev/platform-conformance": "0.8.0",
"@codelitdev/billing": "0.15.0",
"@codelitdev/platform-conformance": "0.15.0",
"@electric-sql/pglite": "^0.2.17",
"@modelcontextprotocol/client": "^2.2.0",
"@types/cors": "^2.8.12",
Expand Down
8 changes: 7 additions & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import swaggerUi from "swagger-ui-express";
import { toNodeHandler } from "better-auth/node";
import { logger, observability } from "./services/log";
import { auth } from "./auth/better-auth";
import { CLIENT_IP_HEADER } from "./auth/cookie-options";
import { trustProxySetting } from "./auth/trust-proxy";
import { createClientIpMiddleware } from "@codelitdev/oauth-server-kit/express";
import oauthPagesRoutes from "./auth/oauth-pages";
import sessionReverifyRoutes from "./auth/session-reverify";
import mcpRoutes from "./mcp/routes";
Expand Down Expand Up @@ -42,7 +45,10 @@ import { openApiDocument } from "./openapi";
export function createApp() {
const app = express();

app.set("trust proxy", process.env.ENABLE_TRUST_PROXY === "true" ? 1 : false);
app.set("trust proxy", trustProxySetting(process.env));
// Better Auth's rate limits and session IPs read the client address from
// this header only, never from X-Forwarded-For.
app.use(createClientIpMiddleware({ header: CLIENT_IP_HEADER }));

app.use((req, res, next) => {
const reqId = readOrCreateRequestId(
Expand Down
28 changes: 15 additions & 13 deletions apps/api/src/auth/better-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import { jwt } from "better-auth/plugins/jwt";
import { oauthProvider } from "@better-auth/oauth-provider";
import { oauthProviderResourceClient } from "@better-auth/oauth-provider/resource-client";
import { cimd } from "@better-auth/cimd";
import { createOAuthProviderOptions } from "@codelitdev/oauth-server-kit/better-auth";
import {
createOAuthProviderOptions,
secureEmailAndPasswordOptions,
secureSessionOptions,
} from "@codelitdev/oauth-server-kit/better-auth";
import type { HostedLoginMethod } from "@codelitdev/oauth-server-kit/express";
import { db } from "../db/client";
import * as schema from "../db/schema";
Expand All @@ -16,7 +20,7 @@ import { MailNotConfiguredError, sendMail } from "../utils/mail";
import { ensureFrontLitAccountForUser } from "../account/queries";
import { MCP_SCOPES_SUPPORTED } from "../mcp/policy";
import { fetchClientMetadataResource } from "./cimd-fetch";
import { AUTH_COOKIE_PREFIX } from "./cookie-prefix";
import { authCookieOptions } from "./cookie-options";
import {
CAPTCHA_PROTECTED_ENDPOINTS,
TURNSTILE_TESTING_SECRET,
Expand Down Expand Up @@ -149,21 +153,19 @@ export const auth = betterAuth({
);
},
},
advanced: {
cookiePrefix: AUTH_COOKIE_PREFIX,
...(authCookieDomain
? {
crossSubDomainCookies: {
enabled: true,
domain: authCookieDomain,
},
}
: {}),
},
// `__Secure-frontlit.session_token` when AUTH_COOKIE_DOMAIN shares it with
// the web app, `__Host-` on a single https host, plain over http. Client
// addresses come only from the header `createClientIpMiddleware` sets.
advanced: authCookieOptions({ baseURL: authBaseUrl, cookieDomain: authCookieDomain }),
// Password sign-in stays off: FrontLit signs people in with email codes,
// Google and OAuth.
emailAndPassword: secureEmailAndPasswordOptions(),
user: {
modelName: "authUser",
},
session: {
// No cookie cache: a revoked session stops working immediately.
...secureSessionOptions(),
modelName: "authSession",
expiresIn: 60 * 60 * 24 * 30,
updateAge: 60 * 60 * 24,
Expand Down
41 changes: 41 additions & 0 deletions apps/api/src/auth/cookie-options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { sessionCookieName } from "@codelitdev/oauth-server-kit/better-auth";
import { authCookieOptions } from "./cookie-options";

describe("authCookieOptions", () => {
it("names the session cookie for each deployment shape", () => {
expect(
sessionCookieName(
authCookieOptions({
baseURL: "https://api.frontlit.example",
cookieDomain: "frontlit.example",
}),
),
).toBe("__Secure-frontlit.session_token");
expect(
sessionCookieName(authCookieOptions({ baseURL: "https://api.frontlit.example" })),
).toBe("__Host-frontlit.session_token");
expect(
sessionCookieName(authCookieOptions({ baseURL: "http://localhost:4000" })),
).toBe("frontlit.session_token");
});

it("shares the cookie across subdomains only when a domain is set", () => {
expect(
authCookieOptions({
baseURL: "https://api.frontlit.example",
cookieDomain: "frontlit.example",
}).crossSubDomainCookies,
).toEqual({ enabled: true, domain: "frontlit.example" });
expect(
authCookieOptions({ baseURL: "https://api.frontlit.example" })
.crossSubDomainCookies,
).toBeUndefined();
});

it("reads the client address only from the internal header", () => {
expect(authCookieOptions({ baseURL: "http://localhost:4000" }).ipAddress).toEqual({
ipAddressHeaders: ["x-frontlit-client-ip"],
});
});
});
24 changes: 24 additions & 0 deletions apps/api/src/auth/cookie-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { secureCookieOptions } from "@codelitdev/oauth-server-kit/better-auth";
import { AUTH_COOKIE_PREFIX } from "./cookie-prefix";

/** Internal header that carries the client address to Better Auth. The
* client-IP middleware in `app.ts` overwrites whatever a client sends in it. */
export const CLIENT_IP_HEADER = "x-frontlit-client-ip";

/**
* Better Auth `advanced` options. The session cookie is
* `__Host-frontlit.session_token` on a single https host,
* `__Secure-frontlit.session_token` when `cookieDomain` shares it across
* subdomains (the web app and API in production), and plain
* `frontlit.session_token` over http.
*/
export function authCookieOptions(input: { baseURL: string; cookieDomain?: string }) {
return secureCookieOptions({
baseURL: input.baseURL,
cookiePrefix: AUTH_COOKIE_PREFIX,
...(input.cookieDomain
? { crossSubDomainCookies: { enabled: true, domain: input.cookieDomain } }
: {}),
clientIpHeader: CLIENT_IP_HEADER,
});
}
1 change: 1 addition & 0 deletions apps/api/src/auth/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ describe("FrontLit auth middleware projection", () => {
subject: "auth-user-1",
email: "owner@example.com",
scopes: [],
authenticatedAt: new Date(),
},
account,
accountId: account.id,
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/auth/resolve-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const sessionIdentity = {
email: "owner@example.com",
name: "Owner",
scopes: [] as [],
authenticatedAt: new Date("2026-01-01T00:00:00Z"),
};

function dependencies(overrides: Partial<AuthDependencies> = {}): AuthDependencies {
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/auth/session-freshness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ describe("session freshness", () => {
expect(
sessionTokenFromCookieHeader("__Secure-frontlit.session_token=tok.sig"),
).toBe("tok");
expect(sessionTokenFromCookieHeader("__Host-frontlit.session_token=host.sig")).toBe(
"host",
);
});
});

Expand Down Expand Up @@ -169,6 +172,7 @@ describe("resolveAuth sessionAuthenticatedAt on the production path", () => {
email: "live@example.com",
name: "Owner",
scopes: [],
authenticatedAt: new Date(),
},
}),
authenticateBearer: async () => null,
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/auth/session-freshness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function sessionTokenFromCookieHeader(
if (!cookie) return undefined;
const match = cookie.match(
new RegExp(
`(?:^|;\\s*)(?:__Secure-)?${AUTH_COOKIE_PREFIX}\\.session_token=([^;]+)`,
`(?:^|;\\s*)(?:__Secure-|__Host-)?${AUTH_COOKIE_PREFIX}\\.session_token=([^;]+)`,
),
);
if (!match?.[1]) return undefined;
Expand Down
20 changes: 20 additions & 0 deletions apps/api/src/auth/trust-proxy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { trustProxySetting } from "./trust-proxy";

describe("trustProxySetting", () => {
it("keeps the ENABLE_TRUST_PROXY behaviour when TRUST_PROXY is unset", () => {
expect(trustProxySetting({})).toBe(false);
expect(trustProxySetting({ ENABLE_TRUST_PROXY: "false" })).toBe(false);
expect(trustProxySetting({ ENABLE_TRUST_PROXY: "true" })).toBe(1);
expect(trustProxySetting({ ENABLE_TRUST_PROXY: "true", TRUST_PROXY: " " })).toBe(1);
});

it("lets TRUST_PROXY win and accepts hops, booleans and subnets", () => {
expect(trustProxySetting({ ENABLE_TRUST_PROXY: "true", TRUST_PROXY: "2" })).toBe(2);
expect(trustProxySetting({ TRUST_PROXY: "false" })).toBe(false);
expect(trustProxySetting({ TRUST_PROXY: "true" })).toBe(true);
expect(trustProxySetting({ TRUST_PROXY: "10.0.0.0/8, loopback" })).toBe(
"10.0.0.0/8, loopback",
);
});
});
14 changes: 14 additions & 0 deletions apps/api/src/auth/trust-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { parseTrustProxy } from "@codelitdev/oauth-server-kit/express";

/**
* Express's `trust proxy` setting. `TRUST_PROXY` takes a hop count, `true`,
* `false`, or addresses and subnets (see `parseTrustProxy`). Without it,
* `ENABLE_TRUST_PROXY=true` still trusts one hop, and nothing is trusted
* otherwise, as before `TRUST_PROXY` existed.
*/
export function trustProxySetting(
env: Record<string, string | undefined>,
): boolean | number | string {
if (env.TRUST_PROXY?.trim()) return parseTrustProxy(env.TRUST_PROXY);
return env.ENABLE_TRUST_PROXY === "true" ? 1 : false;
}
54 changes: 54 additions & 0 deletions apps/api/src/mcp/open-world.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { OPEN_WORLD_MCP_TOOLS } from "./policy";
import { registerAllTools } from "./server";
import { createMcpToolRegistrar } from "./tool-registry";

function advertisedAnnotations() {
const annotations = new Map<string, Record<string, unknown>>();
const server = {
registerTool: (name: string, config: any) => {
annotations.set(name, config.annotations);
},
};
registerAllTools(createMcpToolRegistrar(server as any));
return annotations;
}

describe("MCP openWorldHint", () => {
const annotations = advertisedAnnotations();

it("is true for tools that email people or call GitHub", () => {
for (const name of [
"send_broadcast",
"reply_to_ticket",
// Emails the requester a receipt as a side effect.
"create_ticket",
"test_esp_config",
"create_documentation_git_migration_pr",
]) {
expect(annotations.get(name)?.openWorldHint, name).toBe(true);
}
});

it("is false for tools that stay in the team's own workspace", () => {
for (const name of [
"create_broadcast",
"list_contacts",
"publish_product_update",
"update_ticket_status",
"add_contact_tag",
"get_documentation_github",
]) {
expect(annotations.get(name)?.openWorldHint, name).toBe(false);
}
});

it("is an explicit boolean on every tool, and the set names only real tools", () => {
for (const [name, value] of annotations) {
expect(typeof value?.openWorldHint, name).toBe("boolean");
}
for (const name of OPEN_WORLD_MCP_TOOLS) {
expect(annotations.has(name), name).toBe(true);
}
});
});
40 changes: 40 additions & 0 deletions apps/api/src/mcp/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,46 @@ export const HIGH_IMPACT_MCP_TOOLS = new Set<McpToolName>([
"remove_redirect_domain",
]);

/**
* Tools that reach outside the team's own FrontLit workspace: they email real
* people, directly or as a side effect, or call GitHub live. The registry
* advertises `openWorldHint: true` for these and `false` for every other tool.
*
* Contacts, segments, broadcast drafts and ESP settings live in the team's
* provisioned SendLit team, which is still the team's own data. FrontLit only
* creates broadcast sequences there, so adding a contact or tag cannot start
* an automation that emails anyone. If FrontLit ever exposes drip sequences
* or rules, `create_contact` and `add_contact_tag` belong in this set.
* Team invitations email people too, but are not exposed over MCP.
*/
export const OPEN_WORLD_MCP_TOOLS = new Set<McpToolName>([
// Email to real people.
"send_broadcast",
"test_esp_config",
// Emails the requester a fresh magic link.
"reply_to_ticket",
// Emails the requester a receipt, and may start an Inbox AI auto-reply.
"create_ticket",
// Live GitHub calls: reading repositories and access, opening PRs,
// syncing, and changing the GitHub App connection.
"start_documentation_github_setup",
"list_documentation_github_repositories",
"validate_documentation_github_source",
"connect_documentation_github",
"sync_documentation_github",
"pause_documentation_github",
"resume_documentation_github",
"disconnect_documentation_github",
"grant_documentation_github_capabilities",
"submit_documentation_github_proposal",
"plan_documentation_git_migration",
"create_documentation_git_migration_pr",
"get_documentation_git_migration",
"verify_documentation_git_migration",
"activate_documentation_git_migration",
"cancel_documentation_git_migration",
]);

export type McpHumanRequirement =
| { kind: "permission"; permission: TeamPermission }
| { kind: "owner" }
Expand Down
Loading
Loading