⭐️⭐️⭐️ 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
Merge commit from fork
Pasqual Troncone79669a3690fb
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.mdindex a50378e5..234b1946 100644--- a/apps/api/AGENTS.md+++ b/apps/api/AGENTS.md@@ -504,6 +504,10 @@ directly). Helpers in `src/__tests__/helpers/`: `api` (anonymous client), `autheeither. The web app never imports these packages; it uses this API over HTTP.- CORS `origin` is the `trustedOrigins` list exported by `@repo/auth` — do not re-parse`APP_URL` here.+- A state-changing request that carries the session cookie must come from a trusted+ origin or the api's own; the `onRequest` guard in `app.ts` refuses the rest with 403+ `CSRF_ORIGIN_REJECTED`. `/api/auth/*` is left to better-auth's own check, and requests+ authenticated by api key or bearer token are not checked.- swagger `/docs` (planner) is separate from better-auth's `/api/auth/reference`; bothstay reachable without a session.- Dev: `bun run dev`. Prod: the Dockerfile migrates, then starts the server; the compose files and the Helm chart run the migrations as a separate step and start only the server.diff --git a/apps/api/src/__tests__/integration/csrf-origin.test.ts b/apps/api/src/__tests__/integration/csrf-origin.test.tsnew file mode 100644index 00000000..54653b8e--- /dev/null+++ b/apps/api/src/__tests__/integration/csrf-origin.test.ts@@ -0,0 +1,106 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { trustedOrigins } from '@repo/auth';+import { app, authedApi } from '../helpers/app';+import { signUpTestUser } from '../helpers/auth';+import { resetDb } from '../helpers/db';++// A page on a sibling subdomain is same-site to the api, so a lax session cookie+// reaches it. The api refuses such a state-changing request on every path but+// /api/auth/*, which better-auth guards itself.+const EVIL = 'https://evil.example.com';++// A team is created in a workspace; the user's own is the one sign-up gives them.+let workspaceId: number | null = null;++async function signUp() {+ const user = await signUpTestUser();+ workspaceId = user.workspaceId;+ return user;+}++function createTeam(headers: Record<string, string>, slug: string, path = '/teams') {+ return app.handle(+ new Request(`http://localhost${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...headers },+ body: JSON.stringify({ name: slug, slug, workspaceId }),+ }),+ );+}++async function code(res: Response): Promise<string | undefined> {+ const body = (await res.json().catch(() => ({}))) as { code?: string };+ return body.code;+}++async function teamSlugs(cookie: string): Promise<(string | null)[]> {+ const teams = await authedApi(cookie).teams.get();+ return teams.data!.map((team) => team.slug);+}++describe('cross-site request guard', () => {+ beforeEach(resetDb);++ it('refuses a cookie request from an untrusted origin and changes nothing', async () => {+ const { cookie } = await signUp();+ const res = await createTeam({ cookie, origin: EVIL }, 'from-evil');+ expect(res.status).toBe(403);+ expect(await code(res)).toBe('CSRF_ORIGIN_REJECTED');+ expect(await teamSlugs(cookie)).not.toContain('from-evil');+ });++ it('refuses a cookie request with no Origin whose Sec-Fetch-Site is same-site', async () => {+ const { cookie } = await signUp();+ const res = await createTeam({ cookie, 'sec-fetch-site': 'same-site' }, 'no-origin');+ expect(res.status).toBe(403);+ expect(await code(res)).toBe('CSRF_ORIGIN_REJECTED');+ });++ it('accepts a cookie request from the web origin', async () => {+ const { cookie } = await signUp();+ const res = await createTeam({ cookie, origin: trustedOrigins[0]! }, 'from-web');+ expect(res.status).toBe(201);+ expect(await teamSlugs(cookie)).toContain('from-web');+ });++ it("accepts a cookie request from the api's own origin (the /docs page)", async () => {+ const { cookie } = await signUp();+ const apiOrigin = new URL(process.env.API_URL!).origin;+ const res = await createTeam({ cookie, origin: apiOrigin }, 'from-docs');+ expect(res.status).toBe(201);+ });++ it('accepts a cookie request without Origin or Sec-Fetch-Site (server-side calls)', async () => {+ const { cookie } = await signUp();+ const res = await createTeam({ cookie }, 'from-server');+ expect(res.status).toBe(201);+ });++ it('leaves api-key, bearer and cookieless requests to the usual auth', async () => {+ const others: Record<string, string>[] = [+ { 'x-api-key': 'ipk_unknown' },+ { authorization: 'Bearer x' },+ {},+ ];+ for (const headers of others) {+ const res = await createTeam({ ...headers, origin: EVIL }, 'other-auth');+ expect(await code(res)).not.toBe('CSRF_ORIGIN_REJECTED');+ }+ });++ it('does not let a bogus api key carry a cookie request past the guard', async () => {+ const { cookie } = await signUp();+ const res = await createTeam(+ { cookie, 'x-api-key': 'ipk_unknown', origin: EVIL },+ 'key-and-cookie',+ );+ expect(res.status).toBe(401);+ expect(await teamSlugs(cookie)).not.toContain('key-and-cookie');+ });++ it('does not apply to /api/auth/*', async () => {+ const { cookie } = await signUp();+ const res = await createTeam({ cookie, origin: EVIL }, 'auth-path', '/api/auth/sign-out');+ expect(await code(res)).not.toBe('CSRF_ORIGIN_REJECTED');+ });+});diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 06c54119..09d44a80 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -52,6 +52,31 @@ For agent clients, use the MCP endpoint at [${apiUrl}/mcp](${apiUrl}/mcp). SCIM,const LEGACY_OIDC_CALLBACK = `/api/auth/oauth2/callback/${OIDC_PROVIDER_ID}`;const OIDC_CALLBACK = `/api/auth/callback/${OIDC_PROVIDER_ID}`;+// A browser attaches the session cookie to any request to this origin, including one+// a page on another origin (a sibling subdomain, say) makes on the visitor's behalf.+// better-auth guards its own /api/auth/* with an origin check; this extends the same+// guard to the rest of the api. It only applies to state-changing, cookie-driven+// requests: an api key or bearer token is not sent automatically by a browser, so it+// is not a CSRF vector (MCP and SCIM use bearer tokens, webhooks are signed), and the+// server-side calls the web makes carry neither Origin nor Sec-Fetch-Site.+const CSRF_SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);+// The api's own origin counts too: the /docs page sends its "Try it" requests from it.+const csrfTrustedOrigins = [...trustedOrigins, new URL(apiUrl).origin];++function isCrossSiteCookieRequest(request: Request): boolean {+ if (CSRF_SAFE_METHODS.has(request.method)) return false;+ if (new URL(request.url).pathname.startsWith('/api/auth/')) return false;+ const cookie = request.headers.get('cookie');+ if (!cookie || !cookie.includes('session_token')) return false;+ if (request.headers.get('authorization') || request.headers.get('x-api-key')) return false;+ const origin = request.headers.get('origin');+ if (origin !== null) return !csrfTrustedOrigins.includes(origin);+ // No Origin: trust Sec-Fetch-Site when the browser sent it, allow its absence+ // (non-browser clients that happen to carry a cookie are not page-driven).+ const site = request.headers.get('sec-fetch-site');+ return site !== null && site !== 'same-origin' && site !== 'none';+}+// 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.@@ -66,6 +91,12 @@ export const app = new Elysia())// Before the routes: a hook applies only to the routes registered after it..use(requestTracking)+ .onRequest(({ request, set }) => {+ if (isCrossSiteCookieRequest(request)) {+ set.status = 403;+ return { error: 'Cross-site request refused', code: 'CSRF_ORIGIN_REJECTED' };+ }+ }).onAfterHandle({ as: 'global' }, ({ request, response }) =>normalizeOpenApiResponse(request, response),)