Skip to content

⭐️⭐️⭐️ 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.

feat: let the instance owner trust sites to frame public pages, and add seams for public pages and project settings sections (#715)

Croffb67e97585ae6
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index 24d28784..b2ec6bc9 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -338,6 +338,10 @@ Functions with no setter, for the routes such a build adds:
model calls cost, with `own` from `ownPrices(scope)` (`analytics.ts`) so a workspace's
prices count.
- `projectsWithPermission` (`shared/access.ts`): the projects a member may read.
+- `createIssue(project, input, null)` (`modules/issues/service.ts`): an issue no account
+ created, such as one a person files through a page the build serves to anyone.
+- `createComment({ issueId, body, authorName })` (`modules/issues/activity.ts`): a comment
+ from someone without an account, named `authorName`. Its mentions reach nobody.
## SCIM
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 8b174a19..791fe113 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -20,6 +20,8 @@ import { setMcpApp } from './mcp/app-ref';
import { gitWebhookRoutes } from './modules/git/webhook';
import { scimRoutes } from './modules/scim';
import { currentUserRoutes } from './modules/current-user';
+import { EmbedSitesSchema } from './modules/settings/model';
+import { getEmbedSites } from './modules/settings/service';
import { syncOidcGroupsAfterCallback } from './modules/scim/oidc-sync';
import { normalizeOpenApiResponse } from './openapi';
import { requestTracking } from './shared/request-tracker';
@@ -336,6 +338,19 @@ export const app = new Elysia()
},
},
)
+ // The sites the instance owner lets show the public pages in a frame, which the web app
+ // writes into frame-ancestors on those pages. Public on purpose: the web app's proxy
+ // reads it with no session, and every public page names the same sites in its header.
+ .get('/embed-sites', () => getEmbedSites(), {
+ response: { 200: EmbedSitesSchema },
+ detail: {
+ tags: ['System'],
+ summary: 'Get the sites that may embed public pages',
+ description:
+ 'Report the sites that may show the shared work items and views, and the public ' +
+ 'pages, in a frame. Public.',
+ },
+ })
// Root doubles as the liveness/health endpoint.
.get('/', () => ({ name: "It's a Plan api", status: 'ok' }), {
detail: {
diff --git a/apps/api/src/modules/god/__tests__/integration/god-embed-sites.test.ts b/apps/api/src/modules/god/__tests__/integration/god-embed-sites.test.ts
new file mode 100644
index 00000000..0213b957
--- /dev/null
+++ b/apps/api/src/modules/god/__tests__/integration/god-embed-sites.test.ts
@@ -0,0 +1,56 @@
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { app } from '../../../../app';
+import { resetDb } from '#tests/helpers/db';
+import { addUser, setup } from '../helpers';
+
+// The sites the instance owner lets show the public pages in a frame. Only the owner
+// changes them; anyone reads them, since the web app's proxy does so with no session.
+
+const publicRead = async () =>
+ (await app.handle(new Request('http://localhost/embed-sites'))).json() as Promise<{
+ origins: string[];
+ }>;
+
+describe('god embed sites', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ it('refuses both routes for a user who is not the instance owner', async () => {
+ await setup();
+ const outsider = await addUser();
+
+ expect((await outsider.api.god['embed-sites'].get()).status).toBe(403);
+ expect((await outsider.api.god['embed-sites'].put({ origins: [] })).status).toBe(403);
+ });
+
+ it('starts with no site, and reads the list without a session', async () => {
+ const { god } = await setup();
+
+ expect((await god.api.god['embed-sites'].get()).data).toEqual({ origins: [] });
+ expect(await publicRead()).toEqual({ origins: [] });
+ });
+
+ it('stores each site as its origin, once', async () => {
+ const { god } = await setup();
+
+ const put = await god.api.god['embed-sites'].put({
+ origins: ['https://Example.com/', ' https://example.com', 'http://localhost:5055'],
+ });
+
+ expect(put.data).toEqual({ origins: ['https://example.com', 'http://localhost:5055'] });
+ expect(await publicRead()).toEqual(put.data!);
+ });
+
+ it('refuses an address with a path, another scheme, or no host', async () => {
+ const { god } = await setup();
+ const put = (origin: string) => god.api.god['embed-sites'].put({ origins: [origin] });
+
+ expect((await put('https://example.com/forms')).status).toBe(400);
+ expect((await put('javascript:alert(1)')).status).toBe(400);
+ expect((await put("https://a.com; script-src 'unsafe-eval'")).status).toBe(400);
+ expect((await put('https://a.com;sandbox')).status).toBe(400);
+ expect((await put('example.com')).status).toBe(400);
+ expect(await publicRead()).toEqual({ origins: [] });
+ });
+});
diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.ts
index 00336285..6de796ff 100644
--- a/apps/api/src/modules/god/index.ts
+++ b/apps/api/src/modules/god/index.ts
@@ -89,6 +89,8 @@ import {
setStorageSettings,
getHotkeySettings,
setHotkeySettings,
+ getEmbedSites,
+ setEmbedSites,
getProjectDefaults,
setProjectDefaults,
getAgentSettings,
@@ -97,6 +99,7 @@ import {
import { getUpdateStatus } from '#modules/settings/updates';
import {
AgentSettingsSchema,
+ EmbedSitesSchema,
HotkeyCombosSchema,
ProjectDefaultsSchema,
StorageSettingsSchema,
@@ -480,6 +483,26 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
})
+ .get('/god/embed-sites', () => getEmbedSites(), {
+ response: { 200: EmbedSitesSchema, ...errors(401, 403) },
+ detail: {
+ summary: 'Get the sites that may embed public pages',
+ description:
+ 'Get the sites that may show the shared work items and views, and the public pages, in a frame.',
+ },
+ })
+
+ .put('/god/embed-sites', ({ body }) => setEmbedSites(body.origins), {
+ body: EmbedSitesSchema,
+ response: { 200: EmbedSitesSchema, ...errors(400, 401, 403) },
+ detail: {
+ summary: 'Set the sites that may embed public pages',
+ description:
+ 'Replace the list. Each entry is a site address with no path; it is stored as its ' +
+ 'origin. Every other site, and every other page, is refused a frame.',
+ },
+ })
+
// Whether a newer release is published, and the notes of the releases around the
// running one. Owner-only: they are the one who upgrades the instance, and the
// sidebar hides the indicator from everyone else. The version alone is readable by
diff --git a/apps/api/src/modules/issues/activity.ts b/apps/api/src/modules/issues/activity.ts
index 6afef5cc..153dad2d 100644
--- a/apps/api/src/modules/issues/activity.ts
+++ b/apps/api/src/modules/issues/activity.ts
@@ -326,9 +326,12 @@ export async function createComment(input: {
body: string;
// The comment being replied to. It has to be a comment on the same issue.
replyToId?: number | null;
+ // The name of an author without an account, such as someone writing in through a
+ // build's public page. Their mentions reach nobody: they are not in the team.
+ authorName?: string;
}): Promise<FeedItemRow> {
const actorUserId = input.actorUserId ?? null;
- const actorName = await userName(actorUserId);
+ const actorName = input.authorName ?? (await userName(actorUserId));
const replyToId = input.replyToId ?? null;
if (replyToId != null) {
const [parent] = await db
@@ -361,7 +364,7 @@ export async function createComment(input: {
// Resolved once: the agent halves start runs, the member half is notified.
const mentioned = await resolveMentionHandles(
projectId,
- parseMentionHandles(comment.body ?? ''),
+ input.authorName === undefined ? parseMentionHandles(comment.body ?? '') : [],
);
await enqueueMentionRuns(projectId, comment, mentioned.agentUserIds);
await notifyComment(projectId, comment, mentioned);
diff --git a/apps/api/src/modules/settings/model.ts b/apps/api/src/modules/settings/model.ts
index 06193442..96ed69bb 100644
--- a/apps/api/src/modules/settings/model.ts
+++ b/apps/api/src/modules/settings/model.ts
@@ -35,6 +35,14 @@ export const HotkeyCombosSchema = t.Record(
t.String({ pattern: '^(mod\\+|shift\\+|alt\\+)*[a-z0-9]{1,10}$' }),
);
+export const EmbedSitesSchema = t.Object({
+ origins: t.Array(t.String({ maxLength: 300 }), {
+ maxItems: 50,
+ description:
+ 'Sites that may show the public pages in a frame, as origins such as https://example.com.',
+ }),
+});
+
const ReleaseSchema = t.Object({
tag: t.String(),
version: t.String(),
diff --git a/apps/api/src/modules/settings/service.ts b/apps/api/src/modules/settings/service.ts
index fa70853d..8d91eaa1 100644
--- a/apps/api/src/modules/settings/service.ts
+++ b/apps/api/src/modules/settings/service.ts
@@ -5,10 +5,10 @@ import {
getStorageSettings,
type StorageSettings,
} from '@repo/db';
-import { intEnv } from '#shared/lib';
+import { HttpError, intEnv } from '#shared/lib';
-// The instance settings kept in app_setting: the upload limits and the keyboard
-// shortcuts.
+// The instance settings kept in app_setting: the upload limits, the keyboard
+// shortcuts and the sites that may frame the public pages.
// Instance-wide upload limits (app_setting key 'storage'). getStorageSettings/
// mimeAllowed/MB/StorageSettings live in @repo/db (packages/db/src/domains/storage.ts) —
@@ -117,3 +117,38 @@ export async function setHotkeySettings(combos: HotkeyCombos): Promise<HotkeyCom
await setSetting(HOTKEYS_SETTING_KEY, combos);
return combos;
}
+
+// The sites that may show the public pages in a frame (app_setting key 'embedSites'): the
+// shared work items and views, and what a build serves under /p. Kept as origins, the way the
+// web app writes them into frame-ancestors. Empty, no site may.
+const EMBED_SITES_KEY = 'embedSites';
+
+export async function getEmbedSites(): Promise<{ origins: string[] }> {
+ return { origins: (await getSetting<string[]>(EMBED_SITES_KEY)) ?? [] };
+}
+
+export async function setEmbedSites(origins: string[]): Promise<{ origins: string[] }> {
+ const sites = [...new Set(origins.map(siteOrigin))];
+ await setSetting(EMBED_SITES_KEY, sites);
+ return { origins: sites };
+}
+
+// The origins a site may be: a scheme, a host of letters, digits, dots and hyphens (an
+// international name is in its ASCII form by then), and a port. Nothing else reaches the
+// header, where a `;` or a space would start another directive.
+const SITE_ORIGIN = /^https?:\/\/[a-z0-9.-]+(:\d+)?$/;
+
+// A site as the browser names it in a frame check, from what the owner typed.
+function siteOrigin(text: string): string {
+ const invalid = () =>
+ new HttpError(400, `${text} is not a site address, such as https://example.com`);
+ let url: URL;
+ try {
+ url = new URL(text.trim());
+ } catch {
+ throw invalid();
+ }
+ const bare = url.pathname === '/' && !url.search && !url.hash && !url.username && !url.password;
+ if (!bare || !SITE_ORIGIN.test(url.origin)) throw invalid();
+ return url.origin;
+}
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index d1b06962..5dde94e4 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -27,6 +27,12 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`
group, each in the order given.
`/workspaces/:id` names no section and opens the first entry of the menu, so the order
also decides the page a workspace opens on.
+ `useProjectSettingsSections(project, core)` returns the project settings sidebar: here the
+ core's sections, while the hosted build adds its own at any position or drops some. The
+ sidebar lists the groups in the order their first section comes, each named in
+ `nav.groups.<group>`, so a section can open a group of its own. One the build adds
+ carries in `Component` the page `/:team/:projectKey/settings/<slug>` opens, which answers
+ 404 only once the project and every query in flight have loaded.
`NoTeamStart` is the start page of an account with no team and no workspace it owns,
which happens while personal workspaces are off; here it says who adds them.
`WorkspaceRailActions` sits below the workspace tiles of a rail; here it says where more
@@ -49,7 +55,12 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`
invited address as `email`; here it adds nothing, while the hosted build offers a sign-in
through providers of its own. `SignInPage` is what `/login/<name>` shows, a sign-in page under a
name of its own; here every name answers 404, while the hosted build can show the sign-in
- form there under a title of its own (`AuthLoginForm`'s `title`). A sign-in that comes back, or an auth form the server refuses, with
+ form there under a title of its own (`AuthLoginForm`'s `title`). `PublicPage({ path })` is what `/p/<path>` shows to
+ anyone, signed in or not, never indexed; here every path answers 404, while the hosted build
+ serves pages of its own there. Those pages and the share pages may be shown in a frame on
+ the sites the instance owner trusts (god mode, General; `GET /embed-sites`), which
+ `src/proxy.ts` writes into `frame-ancestors` beside the app itself; `next.config.ts` refuses a
+ frame to every other page. A sign-in that comes back, or an auth form the server refuses, with
a code the core does not know shows the text the build's messages give it under
`auth.errors.codes.<code>`.
`GodSectionExtras` renders at the end of every god section page, by its slug, for settings the hosted build adds to an existing section; `WorkspaceSectionExtras`
diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.json
index 762df745..c3131279 100644
--- a/apps/web/messages/ar/god.json
+++ b/apps/web/messages/ar/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "كل حساب بياخد مساحة عمل خاصة بيه باسم صاحبه. لو اتقفل، الناس بيشتغلوا بس في مساحات العمل اللي اتضافوا ليها.",
"agents": "الوكلاء",
"agentsSaved": "تم حفظ إعدادات الوكلاء",
+ "embedding": "التضمين",
+ "embedSites": "المواقع الموثوقة",
+ "embedSitesHint": "تُفتح المهام واللوحات المُشارَكة علنًا داخل إطار على هذه المواقع فقط. افصل بين المواقع بفواصل.",
+ "embedSitesInvalid": "اكتب كل موقع بالشكل https://example.com، دون مسار.",
+ "embedSaved": "تم حفظ المواقع الموثوقة",
"traceRetention": "مدة حفظ تتبّعات التشغيل",
"traceRetentionHint": "كل تشغيل لوكيل يسجّل استدعاءات النموذج والأدوات. لوحات الاستهلاك تحتسب العمليات المحفوظة فقط.",
"traceDays": "{days, plural, one {يوم واحد} two {يومان} few {# أيام} many {# يوماً} other {# يوم}}",
diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.json
index e61e4911..27d5ceb1 100644
--- a/apps/web/messages/en/god.json
+++ b/apps/web/messages/en/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Every account gets a workspace of its own, named after the person. Off, people work only in the workspaces they are added to.",
"agents": "Agents",
"agentsSaved": "Agent settings saved",
+ "embedding": "Embedding",
+ "embedSites": "Trusted sites",
+ "embedSitesHint": "Issues and boards shared publicly open in a frame on these sites only. Separate sites with commas.",
+ "embedSitesInvalid": "Enter each site as https://example.com, without a path.",
+ "embedSaved": "Trusted sites saved",
"traceRetention": "Keep run traces",
"traceRetentionHint": "Each agent run records its model and tool calls. Usage dashboards count only the runs still kept.",
"traceDays": "{days, plural, one {# day} other {# days}}",
diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.json
index 7317c594..cd40cc45 100644
--- a/apps/web/messages/es-ES/god.json
+++ b/apps/web/messages/es-ES/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Cada cuenta recibe un espacio de trabajo propio con el nombre de la persona. Desactivado, cada persona trabaja solo en los espacios de trabajo a los que se le ha añadido.",
"agents": "Agentes",
"agentsSaved": "Ajustes de agentes guardados",
+ "embedding": "Inserción",
+ "embedSites": "Sitios de confianza",
+ "embedSitesHint": "Los tickets y tableros compartidos públicamente se abren en un marco solo en estos sitios. Separa los sitios con comas.",
+ "embedSitesInvalid": "Escribe cada sitio como https://example.com, sin ruta.",
+ "embedSaved": "Sitios de confianza guardados",
"traceRetention": "Conservar trazas de ejecución",
"traceRetentionHint": "Cada ejecución de un agente registra sus llamadas al modelo y a las herramientas. Los paneles de consumo solo cuentan las ejecuciones conservadas.",
"traceDays": "{days, plural, one {# día} other {# días}}",
diff --git a/apps/web/messages/fa/god.json b/apps/web/messages/fa/god.json
index 38e5289c..b2f88f2e 100644
--- a/apps/web/messages/fa/god.json
+++ b/apps/web/messages/fa/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "هر حساب یک فضای کار اختصاصی به نام خود فرد می‌گیرد. در حالت خاموش، افراد فقط در فضاهای کاری که به آن‌ها اضافه شده‌اند کار می‌کنند.",
"agents": "ایجنت‌ها",
"agentsSaved": "تنظیمات ایجنت ذخیره شد",
+ "embedding": "جاسازی",
+ "embedSites": "سایت‌های مورد اعتماد",
+ "embedSitesHint": "تسک‌ها و بردهایی که به‌صورت عمومی به اشتراک گذاشته شده‌اند فقط در این سایت‌ها داخل فریم باز می‌شوند. سایت‌ها را با کاما جدا کنید.",
+ "embedSitesInvalid": "هر سایت را به شکل https://example.com و بدون مسیر وارد کنید.",
+ "embedSaved": "سایت‌های مورد اعتماد ذخیره شد",
"traceRetention": "نگهداری ردهای اجرا",
"traceRetentionHint": "هر اجرای ایجنت، فراخوانی‌های مدل و ابزار خود را ثبت می‌کند. داشبوردهای مصرف فقط اجراهایی را می‌شمارند که هنوز نگهداری می‌شوند.",
"traceDays": "{days, plural, one {# روز} other {# روز}}",
diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.json
index 5612bd91..f1a68306 100644
--- a/apps/web/messages/fr/god.json
+++ b/apps/web/messages/fr/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Chaque compte reçoit son propre espace de travail, à son nom. Désactivé, chacun travaille seulement dans les espaces de travail où il a été ajouté.",
"agents": "Agents",
"agentsSaved": "Paramètres des agents enregistrés",
+ "embedding": "Intégration",
+ "embedSites": "Sites de confiance",
+ "embedSitesHint": "Les tickets et tableaux partagés publiquement ne s’ouvrent dans un cadre que sur ces sites. Séparez les sites par des virgules.",
+ "embedSitesInvalid": "Saisissez chaque site sous la forme https://example.com, sans chemin.",
+ "embedSaved": "Sites de confiance enregistrés",
"traceRetention": "Conserver les traces d'exécution",
"traceRetentionHint": "Chaque exécution d'agent enregistre ses appels au modèle et aux outils. Les tableaux de consommation ne comptent que les exécutions conservées.",
"traceDays": "{days, plural, one {# jour} other {# jours}}",
diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.json
index b8f3f0bf..121a392c 100644
--- a/apps/web/messages/id/god.json
+++ b/apps/web/messages/id/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Setiap akun mendapat workspace sendiri dengan nama pemiliknya. Jika nonaktif, orang hanya bekerja di workspace tempat mereka ditambahkan.",
"agents": "Agen",
"agentsSaved": "Pengaturan agen disimpan",
+ "embedding": "Penyematan",
+ "embedSites": "Situs tepercaya",
+ "embedSitesHint": "Issue dan papan yang dibagikan secara publik hanya terbuka dalam frame di situs ini. Pisahkan situs dengan koma.",
+ "embedSitesInvalid": "Tulis setiap situs seperti https://example.com, tanpa path.",
+ "embedSaved": "Situs tepercaya disimpan",
"traceRetention": "Simpan trace eksekusi",
"traceRetentionHint": "Setiap eksekusi agen mencatat panggilan ke model dan alat. Dasbor penggunaan hanya menghitung eksekusi yang masih disimpan.",
"traceDays": "{days} hari",
diff --git a/apps/web/messages/ko/god.json b/apps/web/messages/ko/god.json
index 7d85b090..f1ab6106 100644
--- a/apps/web/messages/ko/god.json
+++ b/apps/web/messages/ko/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "각 계정에 사용자 이름을 딴 개인 워크스페이스가 하나씩 생성됩니다. 끄면 사용자는 자신이 추가된 워크스페이스에서만 작업할 수 있습니다.",
"agents": "AI 에이전트",
"agentsSaved": "AI 에이전트 설정이 저장되었습니다",
+ "embedding": "임베드",
+ "embedSites": "신뢰하는 사이트",
+ "embedSitesHint": "공개 공유된 이슈와 보드는 이 사이트에서만 프레임으로 열립니다. 사이트는 쉼표로 구분하세요.",
+ "embedSitesInvalid": "각 사이트를 경로 없이 https://example.com 형식으로 입력하세요.",
+ "embedSaved": "신뢰하는 사이트가 저장되었습니다",
"traceRetention": "실행 추적 기록 보관",
"traceRetentionHint": "각 AI 에이전트 실행에는 모델 및 도구 호출 기록이 저장됩니다. 사용량 대시보드에는 현재 보관 중인 실행 기록만 집계됩니다.",
"traceDays": "{days, plural, one {#일} other {#일}}",
diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.json
index 289362cf..c5b2ecee 100644
--- a/apps/web/messages/pt-BR/god.json
+++ b/apps/web/messages/pt-BR/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Cada conta recebe um workspace próprio com o nome da pessoa. Desativado, as pessoas trabalham apenas nos workspaces aos quais foram adicionadas.",
"agents": "Agentes",
"agentsSaved": "Configurações de agentes salvas",
+ "embedding": "Incorporação",
+ "embedSites": "Sites confiáveis",
+ "embedSitesHint": "Issues e quadros compartilhados publicamente abrem em um frame só nesses sites. Separe os sites com vírgulas.",
+ "embedSitesInvalid": "Digite cada site como https://example.com, sem caminho.",
+ "embedSaved": "Sites confiáveis salvos",
"traceRetention": "Manter rastros de execução",
"traceRetentionHint": "Cada execução de agente registra as chamadas ao modelo e às ferramentas. Os painéis de consumo contam só as execuções mantidas.",
"traceDays": "{days, plural, one {# dia} other {# dias}}",
diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.json
index 569c8339..b835c9e6 100644
--- a/apps/web/messages/ru/god.json
+++ b/apps/web/messages/ru/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Каждый аккаунт получает свой воркспейс с именем человека. Если выключено, люди работают только в воркспейсах, куда их добавили.",
"agents": "Агенты",
"agentsSaved": "Настройки агентов сохранены",
+ "embedding": "Встраивание",
+ "embedSites": "Доверенные сайты",
+ "embedSitesHint": "Задачи и доски в общем доступе открываются во фрейме только на этих сайтах. Разделяйте сайты запятыми.",
+ "embedSitesInvalid": "Укажите каждый сайт как https://example.com, без пути.",
+ "embedSaved": "Доверенные сайты сохранены",
"traceRetention": "Хранить трассировки запусков",
"traceRetentionHint": "Каждый запуск агента записывает вызовы модели и инструментов. Дашборды расходов учитывают только сохранённые запуски.",
"traceDays": "{days, plural, one {# день} few {# дня} other {# дней}}",
diff --git a/apps/web/messages/tr/god.json b/apps/web/messages/tr/god.json
index 99480154..8d86b437 100644
--- a/apps/web/messages/tr/god.json
+++ b/apps/web/messages/tr/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Her hesaba kullanıcının adını taşıyan kendine ait bir çalışma alanı verilir. Kapalıyken kişiler yalnızca eklendikleri çalışma alanlarında çalışabilir.",
"agents": "Ajanlar",
"agentsSaved": "Ajan ayarları kaydedildi",
+ "embedding": "Yerleştirme",
+ "embedSites": "Güvenilir siteler",
+ "embedSitesHint": "Herkese açık paylaşılan işler ve panolar yalnızca bu sitelerde bir çerçevede açılır. Siteleri virgülle ayırın.",
+ "embedSitesInvalid": "Her siteyi yol olmadan https://example.com biçiminde girin.",
+ "embedSaved": "Güvenilir siteler kaydedildi",
"traceRetention": "Çalıştırma izlerini saklama süresi",
"traceRetentionHint": "Her ajan çalıştırması model ve araç çağrılarını kaydeder. Kullanım panoları yalnızca saklanan çalıştırmaları sayar.",
"traceDays": "{days, plural, one {# gün} other {# gün}}",
diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.json
index 839a7d9c..79c668c0 100644
--- a/apps/web/messages/uk/god.json
+++ b/apps/web/messages/uk/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "Кожен акаунт отримує свій воркспейс з ім'ям людини. Якщо вимкнено, люди працюють лише у воркспейсах, до яких їх додали.",
"agents": "Агенти",
"agentsSaved": "Налаштування агентів збережено",
+ "embedding": "Вбудовування",
+ "embedSites": "Довірені сайти",
+ "embedSitesHint": "Задачі й дошки у спільному доступі відкриваються у фреймі лише на цих сайтах. Розділяйте сайти комами.",
+ "embedSitesInvalid": "Вкажіть кожен сайт як https://example.com, без шляху.",
+ "embedSaved": "Довірені сайти збережено",
"traceRetention": "Зберігати трасування запусків",
"traceRetentionHint": "Кожен запуск агента записує виклики моделі та інструментів. Дашборди витрат враховують лише збережені запуски.",
"traceDays": "{days, plural, one {# день} few {# дні} other {# днів}}",
diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.json
index 0ec5396a..642af0b8 100644
--- a/apps/web/messages/zh-CN/god.json
+++ b/apps/web/messages/zh-CN/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "每个账户都会获得一个以其姓名命名的专属工作区。关闭后,成员只能在被添加到的工作区中工作。",
"agents": "代理",
"agentsSaved": "代理设置已保存",
+ "embedding": "嵌入",
+ "embedSites": "受信任的网站",
+ "embedSitesHint": "公开共享的工作项和看板只能在这些网站的框架中打开。用逗号分隔网站。",
+ "embedSitesInvalid": "按 https://example.com 的格式输入每个网站,不带路径。",
+ "embedSaved": "受信任的网站已保存",
"traceRetention": "保留运行追踪",
"traceRetentionHint": "代理的每次运行都会记录模型和工具调用。用量面板只统计仍保留的运行。",
"traceDays": "{days} 天",
diff --git a/apps/web/messages/zh-TW/god.json b/apps/web/messages/zh-TW/god.json
index 4ce4fe05..ec343adc 100644
--- a/apps/web/messages/zh-TW/god.json
+++ b/apps/web/messages/zh-TW/god.json
@@ -181,6 +181,11 @@
"personalWorkspacesHint": "每個帳號都會獲得一個以其姓名命名的專屬工作區。關閉後,成員只能在被新增到的工作區中工作。",
"agents": "代理",
"agentsSaved": "代理設定已儲存",
+ "embedding": "嵌入",
+ "embedSites": "受信任的網站",
+ "embedSitesHint": "公開共享的工作項目和看板只能在這些網站的框架中開啟。以逗號分隔網站。",
+ "embedSitesInvalid": "依 https://example.com 的格式輸入每個網站,不含路徑。",
+ "embedSaved": "受信任的網站已儲存",
"traceRetention": "保留執行追蹤",
"traceRetentionHint": "代理的每次執行都會記錄模型和工具呼叫。用量面板只統計仍保留的執行。",
"traceDays": "{days} 天",
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index cc696433..c3bfe3b0 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -16,7 +16,6 @@ const cloudUiEntry = process.env.CLOUD_UI_ENTRY;
// unaffected and one behind TLS gets it without a second setting.
const SECURITY_HEADERS = [
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains' },
- { key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
// Passkeys are the one powerful feature the app uses; the rest is switched off for
@@ -33,7 +32,15 @@ const nextConfig: NextConfig = {
// standalone build for a lean docker image.
output: 'standalone',
poweredByHeader: false,
- headers: async () => [{ source: '/(.*)', headers: SECURITY_HEADERS }],
+ // No page may be framed, except the public ones (/share, /p) on the sites the instance
+ // owner trusts: src/proxy.ts decides those per request.
+ headers: async () => [
+ { source: '/(.*)', headers: SECURITY_HEADERS },
+ {
+ source: '/:path((?!(?:share|p)(?:/|$)).*)',
+ headers: [{ key: 'X-Frame-Options', value: 'DENY' }],
+ },
+ ],
// Monorepo: include the repo root in file tracing for standalone.
outputFileTracingRoot: tracingRoot,
// isomorphic-dompurify loads jsdom on the server, and jsdom reads its own data
diff --git a/apps/web/src/app/[teamRef]/(shell)/[projectKey]/settings/[section]/page.tsx b/apps/web/src/app/[teamRef]/(shell)/[projectKey]/settings/[section]/page.tsx
new file mode 100644
index 00000000..34713e46
--- /dev/null
+++ b/apps/web/src/app/[teamRef]/(shell)/[projectKey]/settings/[section]/page.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import { useParams } from 'next/navigation';
+import SettingsExtraSectionPage from '@/features/settings/SettingsExtraSectionPage';
+
+export default function Page() {
+ const { section } = useParams<{ section: string }>();
+ return <SettingsExtraSectionPage slug={section} />;
+}
diff --git a/apps/web/src/app/p/[...path]/page.tsx b/apps/web/src/app/p/[...path]/page.tsx
new file mode 100644
index 00000000..d1f13a28
--- /dev/null
+++ b/apps/web/src/app/p/[...path]/page.tsx
@@ -0,0 +1,10 @@
+'use client';
+
+import { useParams } from 'next/navigation';
+import { PublicPage } from '@/cloud';
+
+// A page a build serves to anyone, signed in or not; this one serves none.
+export default function Page() {
+ const { path } = useParams<{ path: string[] }>();
+ return <PublicPage path={path} />;
+}
diff --git a/apps/web/src/app/p/layout.tsx b/apps/web/src/app/p/layout.tsx
new file mode 100644
index 00000000..7bf28548
--- /dev/null
+++ b/apps/web/src/app/p/layout.tsx
@@ -0,0 +1,10 @@
+import type { Metadata } from 'next';
+
+// Pages a build serves to anyone with the link. Never indexed, as the share pages.
+export const metadata: Metadata = {
+ robots: { index: false, follow: false, nocache: true },
+};
+
+export default function PublicLayout({ children }: { children: React.ReactNode }) {
+ return children;
+}
diff --git a/apps/web/src/ce/PublicPage.tsx b/apps/web/src/ce/PublicPage.tsx
new file mode 100644
index 00000000..b0a97324
--- /dev/null
+++ b/apps/web/src/ce/PublicPage.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import { notFound } from 'next/navigation';
+
+// A page at /p/<path> that anyone opens, signed in or not. A self-hosted instance has
+// none; the hosted build serves pages of its own there, such as a public form.
+export default function PublicPage(_props: { path: string[] }) {
+ return notFound();
+}
diff --git a/apps/web/src/ce/index.ts b/apps/web/src/ce/index.ts
index 131768d5..1e926a71 100644
--- a/apps/web/src/ce/index.ts
+++ b/apps/web/src/ce/index.ts
@@ -9,10 +9,12 @@ export { default as GodSectionExtras } from './GodSectionExtras';
export { default as godSections } from './godSections';
export { cloudMessages, loadCloudMessages } from './messages';
export { default as NoTeamStart } from './NoTeamStart';
+export { default as PublicPage } from './PublicPage';
export { default as ScheduleDialog } from './ScheduleDialog';
export { default as ShellNotice } from './ShellNotice';
export { default as SignInExtras } from './SignInExtras';
export { default as SignInPage } from './SignInPage';
+export { default as useProjectSettingsSections } from './useProjectSettingsSections';
export { default as useWorkspaceSections } from './useWorkspaceSections';
export { default as WorkspaceRailActions } from './WorkspaceRailActions';
export { default as WorkspaceSectionExtras } from './WorkspaceSectionExtras';
diff --git a/apps/web/src/ce/useProjectSettingsSections.ts b/apps/web/src/ce/useProjectSettingsSections.ts
new file mode 100644
index 00000000..97936491
--- /dev/null
+++ b/apps/web/src/ce/useProjectSettingsSections.ts
@@ -0,0 +1,14 @@
+'use client';
+
+import type { ProjectDetail } from '@/lib/api/endpoints/projects';
+import type { SettingsSection } from '@/utils/settingsSections';
+
+// A self-hosted instance lists the core's project settings sections. The hosted build
+// returns them with its own added at any position, in a group of the core's or one of
+// its own, or with one left out. `project` is null until the Shell has loaded it.
+export default function useProjectSettingsSections(
+ _project: ProjectDetail | null,
+ core: SettingsSection[],
+): SettingsSection[] {
+ return core;
+}
diff --git a/apps/web/src/components/layout/Shell.tsx b/apps/web/src/components/layout/Shell.tsx
index 9a6c9613..d903b3d3 100644
--- a/apps/web/src/components/layout/Shell.tsx
+++ b/apps/web/src/components/layout/Shell.tsx
@@ -70,6 +70,7 @@ export default function Shell({
route,
unreadable ? t('project') : projectName,
unreadable || viewsFailed ? [] : views,
+ project,
);
const teamId = project?.project.teamId;
const issueRefs = useMemo(
diff --git a/apps/web/src/components/layout/ShellHeaderTitle.tsx b/apps/web/src/components/layout/ShellHeaderTitle.tsx
index 0f4d04dd..e24ae708 100644
--- a/apps/web/src/components/layout/ShellHeaderTitle.tsx
+++ b/apps/web/src/components/layout/ShellHeaderTitle.tsx
@@ -1,8 +1,9 @@
import { useTranslations } from 'next-intl';
-import { SETTINGS_SECTIONS } from '@/utils/settingsSections';
+import { AI_TEAM_SECTIONS } from '@/utils/settingsSections';
import type { IssueRef } from '@/lib/api/endpoints/issues';
import type { ShellRoute } from '@/hooks/useShellRoute';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
+import { useSettingsSections } from '@/hooks/useSettingsNavGroups';
import CycleBreadcrumb from '@/components/layout/CycleBreadcrumb';
import InitiativeBreadcrumb from '@/components/layout/InitiativeBreadcrumb';
import IssueBreadcrumb from '@/components/layout/IssueBreadcrumb';
@@ -22,12 +23,13 @@ export default function ShellHeaderTitle({
}) {
const t = useTranslations('nav');
const sectionText = useSettingsSectionText();
+ const sections = [...useSettingsSections(), ...AI_TEAM_SECTIONS];
// The label on the pages that are not an issue, initiative or cycle detail. An
// /agents/:section route names its section.
function pageLabel(): string {
const { sub, section, aiTeamSection } = route;
- const known = (slug: string) => SETTINGS_SECTIONS.some((s) => s.slug === slug);
+ const known = (slug: string) => sections.some((s) => s.slug === slug);
if (section) return known(section) ? sectionText(section).label : t('projectSettings');
if (sub === 'members') return t('members');
if (sub === 'dashboards') return t('dashboards');
diff --git a/apps/web/src/features/god/GodGeneralPage.tsx b/apps/web/src/features/god/GodGeneralPage.tsx
index e6a1e9c5..a6c04959 100644
--- a/apps/web/src/features/god/GodGeneralPage.tsx
+++ b/apps/web/src/features/god/GodGeneralPage.tsx
@@ -15,15 +15,17 @@ import {
import { Switch } from '@/components/ui/switch';
import GodSectionPage from './components/GodSectionPage';
import GodSettingsGate from './components/GodSettingsGate';
+import GodEmbedSitesSection from './components/general/GodEmbedSitesSection';
import {
useInstanceAgentSettingsQuery,
useInstanceAuthSettingsQuery,
+ useInstanceEmbedSitesQuery,
useInstanceProjectDefaultsQuery,
useUpdateInstanceAgentSettings,
useUpdateInstanceAuthSettings,
useUpdateInstanceProjectDefaults,
} from './services/god.service';
-import type { AgentSettings, InstanceAuthSettings } from '@/lib/api/endpoints/god';
+import type { AgentSettings, EmbedSites, InstanceAuthSettings } from '@/lib/api/endpoints/god';
import type { ProjectDefaults } from '@/lib/api/endpoints/projects';
// The trace windows offered; a window stored through the API outside them is offered too.
@@ -35,11 +37,12 @@ export default function GodGeneralPage() {
const defaults = useInstanceProjectDefaultsQuery().data;
const auth = useInstanceAuthSettingsQuery().data;
const agents = useInstanceAgentSettingsQuery().data;
+ const embed = useInstanceEmbedSitesQuery().data;
return (
<GodSettingsGate
slug="general"
- data={defaults && auth && agents ? { defaults, auth, agents } : undefined}
+ data={defaults && auth && agents && embed ? { defaults, auth, agents, embed } : undefined}
>
{(data) => <GeneralForm {...data} />}
</GodSettingsGate>
@@ -52,10 +55,12 @@ function GeneralForm({
defaults,
auth,
agents,
+ embed,
}: {
defaults: ProjectDefaults;
auth: InstanceAuthSettings;
agents: AgentSettings;
+ embed: EmbedSites;
}) {
const t = useTranslations('god.general');
const update = useUpdateInstanceProjectDefaults();
@@ -182,6 +187,8 @@ function GeneralForm({
/>
</SettingsCard>
</SettingsSection>
+
+ <GodEmbedSitesSection sites={embed} />
</div>
</GodSectionPage>
);
diff --git a/apps/web/src/features/god/components/general/GodEmbedSitesSection.tsx b/apps/web/src/features/god/components/general/GodEmbedSitesSection.tsx
new file mode 100644
index 00000000..2faca577
--- /dev/null
+++ b/apps/web/src/features/god/components/general/GodEmbedSitesSection.tsx
@@ -0,0 +1,68 @@
+'use client';
+
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { useTranslations } from 'next-intl';
+import type { EmbedSites } from '@/lib/api/endpoints/god';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import SettingsRow from '@/components/common/page/SettingsRow';
+import SettingsSection from '@/components/common/page/SettingsSection';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { useUpdateInstanceEmbedSites } from '../../services/god.service';
+import { isSiteAddress, parseSiteAddresses } from '../../utils/siteAddresses';
+
+// The sites that may show the shared work items and views, and the public pages, in a
+// frame. Every other site, and every other page, is refused one.
+export default function GodEmbedSitesSection({ sites }: { sites: EmbedSites }) {
+ const t = useTranslations('god.general');
+ const tCommon = useTranslations('common');
+ const update = useUpdateInstanceEmbedSites();
+ const [text, setText] = useState<string | null>(null);
+ const shown = text ?? sites.origins.join(', ');
+ const typed = parseSiteAddresses(shown);
+ const valid = typed.every(isSiteAddress);
+ const dirty = text !== null && typed.join() !== sites.origins.join();
+
+ async function save() {
+ try {
+ await update.mutateAsync(typed);
+ setText(null);
+ toast.success(t('embedSaved'));
+ } catch {
+ // The failure already surfaced through the global mutation error toast.
+ }
+ }
+
+ return (
+ <SettingsSection title={t('embedding')}>
+ <SettingsCard>
+ <SettingsRow
+ title={t('embedSites')}
+ description={t('embedSitesHint')}
+ note={valid ? undefined : t('embedSitesInvalid')}
+ control={
+ <div className="flex shrink-0 items-center gap-2">
+ <Input
+ className="w-40 sm:w-72"
+ placeholder="https://example.com"
+ aria-label={t('embedSites')}
+ aria-invalid={!valid}
+ value={shown}
+ disabled={update.isPending}
+ onChange={(e) => setText(e.target.value)}
+ />
+ <Button
+ size="sm"
+ disabled={!dirty || !valid || update.isPending}
+ onClick={() => void save()}
+ >
+ {tCommon('save')}
+ </Button>
+ </div>
+ }
+ />
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.ts
index 604a7140..abd225f2 100644
--- a/apps/web/src/features/god/services/god.service.ts
+++ b/apps/web/src/features/god/services/god.service.ts
@@ -34,6 +34,8 @@ import {
updateInstanceProjectDefaults,
getInstanceAgentSettings,
updateInstanceAgentSettings,
+ getInstanceEmbedSites,
+ updateInstanceEmbedSites,
getInstanceStorageSettings,
updateInstanceStorageSettings,
listInstanceUsers,
@@ -189,6 +191,22 @@ export function useUpdateInstanceAgentSettings() {
});
}
+// The sites that may frame the public pages.
+export function useInstanceEmbedSitesQuery() {
+ return useQuery({
+ queryKey: qk.instanceEmbedSites,
+ queryFn: () => getInstanceEmbedSites(),
+ });
+}
+
+export function useUpdateInstanceEmbedSites() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (origins: string[]) => updateInstanceEmbedSites(origins),
+ onSuccess: (data) => qc.setQueryData(qk.instanceEmbedSites, data),
+ });
+}
+
// The upload limits: file sizes, accepted attachment types, and the per-project
// storage quota.
export function useInstanceStorageSettingsQuery() {
diff --git a/apps/web/src/features/god/utils/siteAddresses.ts b/apps/web/src/features/god/utils/siteAddresses.ts
new file mode 100644
index 00000000..64f84fe0
--- /dev/null
+++ b/apps/web/src/features/god/utils/siteAddresses.ts
@@ -0,0 +1,22 @@
+// The sites typed into the embed list, split on commas, semicolons and spaces, once each.
+export function parseSiteAddresses(text: string): string[] {
+ return [...new Set(text.split(/[\s,;]+/).filter(Boolean))];
+}
+
+// A site address the api takes: http or https, a host, a port at most, nothing after.
+export function isSiteAddress(text: string): boolean {
+ try {
+ const url = new URL(text);
+ return (
+ (url.protocol === 'https:' || url.protocol === 'http:') &&
+ /^[a-z0-9.-]+$/.test(url.hostname) &&
+ url.pathname === '/' &&
+ !url.search &&
+ !url.hash &&
+ !url.username &&
+ !url.password
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/web/src/features/settings/SettingsExtraSectionPage.tsx b/apps/web/src/features/settings/SettingsExtraSectionPage.tsx
new file mode 100644
index 00000000..a049ec0f
--- /dev/null
+++ b/apps/web/src/features/settings/SettingsExtraSectionPage.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { useIsFetching } from '@tanstack/react-query';
+import { notFound } from 'next/navigation';
+import { useShell } from '@/context/shellContext';
+import { useSettingsSections } from '@/hooks/useSettingsNavGroups';
+
+// A project settings section without a route of its own: one the hosted build adds. Its
+// sections can depend on queries of their own, so a link straight to one waits for those
+// to load before it calls the section unknown.
+export default function SettingsExtraSectionPage({ slug }: { slug: string }) {
+ const { project } = useShell();
+ const Component = useSettingsSections().find((entry) => entry.slug === slug)?.Component;
+ const loading = useIsFetching() > 0;
+ if (!Component) {
+ if (!project || loading) return null;
+ notFound();
+ }
+ return <Component />;
+}
diff --git a/apps/web/src/hooks/useSettingsNavGroups.ts b/apps/web/src/hooks/useSettingsNavGroups.ts
index 182e436d..6c766f3b 100644
--- a/apps/web/src/hooks/useSettingsNavGroups.ts
+++ b/apps/web/src/hooks/useSettingsNavGroups.ts
@@ -1,22 +1,21 @@
+import { useContext } from 'react';
import { usePathname } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { type LucideIcon } from 'lucide-react';
+import { useProjectSettingsSections } from '@/cloud';
+import { ShellCtx } from '@/context/shellContext';
import { settingsPath } from '@/utils/paths';
-import {
- AUTOMATION_SECTIONS,
- CONFIGURATION_SECTIONS,
- GENERAL_SECTIONS,
- type SettingsSection,
-} from '@/utils/settingsSections';
+import { byKey } from '@/utils/messageKey';
+import { SETTINGS_MENU_SECTIONS, type SettingsSection } from '@/utils/settingsSections';
import { usePermissions } from '@/hooks/usePermissions';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
-// The project settings sidebar (the "Project settings" mode) lists the
-// Configuration sections flat under group labels. This hook builds those groups
-// from the section config and the viewer's permissions, and reports the first
-// reachable destination so the main sidebar's "Project settings" entry knows
-// where to point.
+// The project settings sidebar (the "Project settings" mode) lists the sections
+// flat under group labels, the groups in the order their first section comes. This
+// hook builds those groups from the sections and the viewer's permissions, and
+// reports the first reachable destination so the main sidebar's "Project settings"
+// entry knows where to point.
export type SettingsNavItem = {
key: string;
@@ -32,8 +31,14 @@ export type SettingsNavGroup = {
items: SettingsNavItem[];
};
-// `project` is only passed by the Shell, which calls this above its own context
-// provider; everything else reads the project from the context.
+// The sections of the settings sidebar, the hosted build's included. `project` is
+// only passed by the Shell, which calls this above its own context provider;
+// everything else reads the project from the context.
+export function useSettingsSections(project?: ProjectDetail | null): SettingsSection[] {
+ const ctx = useContext(ShellCtx);
+ return useProjectSettingsSections(project ?? ctx?.project ?? null, SETTINGS_MENU_SECTIONS);
+}
+
export function useSettingsNavGroups(
projectKey: string | null,
project?: ProjectDetail | null,
@@ -41,32 +46,27 @@ export function useSettingsNavGroups(
groups: SettingsNavGroup[];
firstHref: string | null;
} {
- const t = useTranslations('nav');
+ const groupLabel = byKey(useTranslations('nav.groups'));
const sectionText = useSettingsSectionText();
const pathname = usePathname();
const { can } = usePermissions(project);
+ const sections = useSettingsSections(project).filter((s) =>
+ can(s.resource, s.viewAction ?? 'read'),
+ );
- // The readable sections of one group as nav items.
- const toItems = (sections: SettingsSection[]): SettingsNavItem[] =>
- sections
- .filter((s) => can(s.resource, s.viewAction ?? 'read'))
+ const groups: SettingsNavGroup[] = [...new Set(sections.map((s) => s.group))].map((group) => ({
+ key: group,
+ label: groupLabel(group),
+ items: sections
+ .filter((s) => s.group === group)
.map((s) => ({
key: s.slug,
href: projectKey ? settingsPath(projectKey, s.slug) : '#',
icon: s.icon,
label: sectionText(s.slug).label,
active: pathname.endsWith(`/settings/${s.slug}`),
- }));
-
- const generalItems = toItems(GENERAL_SECTIONS);
- const workflowItems = toItems(CONFIGURATION_SECTIONS);
- const automationItems = toItems(AUTOMATION_SECTIONS);
-
- const groups: SettingsNavGroup[] = [
- { key: 'general', label: t('groups.project'), items: generalItems },
- { key: 'workflow', label: t('groups.workflow'), items: workflowItems },
- { key: 'automation', label: t('groups.automation'), items: automationItems },
- ].filter((g) => g.items.length > 0);
+ })),
+ }));
const firstHref = groups[0]?.items[0]?.href ?? null;
diff --git a/apps/web/src/hooks/useShellTitle.ts b/apps/web/src/hooks/useShellTitle.ts
index 17f68a57..126072ab 100644
--- a/apps/web/src/hooks/useShellTitle.ts
+++ b/apps/web/src/hooks/useShellTitle.ts
@@ -1,8 +1,10 @@
import { useTranslations } from 'next-intl';
+import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { View } from '@/lib/api/endpoints/views';
-import { AI_AGENTS_SECTION, SETTINGS_SECTIONS } from '@/utils/settingsSections';
+import { AI_AGENTS_SECTION, AI_TEAM_SECTIONS } from '@/utils/settingsSections';
import type { ShellRoute } from '@/hooks/useShellRoute';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
+import { useSettingsSections } from '@/hooks/useSettingsNavGroups';
import { titlePath, useDocumentTitle } from '@/hooks/useDocumentTitle';
const SECTION_LABELS = {
@@ -21,12 +23,17 @@ const SECTION_LABELS = {
// The tab title of a project route: the project and the section the route opens. A
// detail page names its entity over it, so this is also what the tab shows while that
// entity loads or when it cannot be read.
-export function useShellTitle(route: ShellRoute, projectName: string, views: View[]) {
+export function useShellTitle(
+ route: ShellRoute,
+ projectName: string,
+ views: View[],
+ project: ProjectDetail | null,
+) {
const t = useTranslations('nav');
const tScreens = useTranslations('meta.screens');
const sectionText = useSettingsSectionText();
- const known = (slug: string | null): slug is string =>
- SETTINGS_SECTIONS.some((s) => s.slug === slug);
+ const sections = [...useSettingsSections(project), ...AI_TEAM_SECTIONS];
+ const known = (slug: string | null): slug is string => sections.some((s) => s.slug === slug);
function sectionParts(): string[] {
const { sub, section, aiTeamSection } = route;
diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.ts
index 5fa11a3d..84065294 100644
--- a/apps/web/src/lib/api/endpoints/god.ts
+++ b/apps/web/src/lib/api/endpoints/god.ts
@@ -298,6 +298,19 @@ export const updateInstanceAgentSettings = (body: Partial<AgentSettings>) =>
body: JSON.stringify(body),
});
+// The sites that may show the shared work items and views, and the public pages, in a frame.
+export interface EmbedSites {
+ origins: string[];
+}
+
+export const getInstanceEmbedSites = () => request<EmbedSites>('/god/embed-sites');
+
+export const updateInstanceEmbedSites = (origins: string[]) =>
+ request<EmbedSites>('/god/embed-sites', {
+ method: 'PUT',
+ body: JSON.stringify({ origins }),
+ });
+
export const getInstanceStorageSettings = () => request<StorageSettings>('/god/storage-settings');
export const updateInstanceStorageSettings = (patch: StorageSettingsPatch) =>
diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts
index 3a3902b0..b2a26f9b 100644
--- a/apps/web/src/proxy.test.ts
+++ b/apps/web/src/proxy.test.ts
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import { afterEach, beforeEach, describe, it } from 'node:test';
import { NextRequest } from 'next/server';
import { proxy } from './proxy';
+import { forgetEmbedSites } from './utils/embedSites';
const COOKIE = 'better-auth.session_token=stale.signature';
@@ -25,13 +26,16 @@ function run(path: string, cookie?: string) {
}
describe('proxy', () => {
- it('keeps a stale session on the expired screen instead of bouncing it back', () => {
- const res = run('/login?expired=1', COOKIE);
+ it('keeps a stale session on the expired screen instead of bouncing it back', async () => {
+ const res = await run('/login?expired=1', COOKIE);
assert.equal(res.headers.get('location'), null);
});
- it('expires the stale cookies the api could not clear', () => {
- const res = run('/login?expired=1', `${COOKIE}; __Secure-better-auth.session_data=cached`);
+ it('expires the stale cookies the api could not clear', async () => {
+ const res = await run(
+ '/login?expired=1',
+ `${COOKIE}; __Secure-better-auth.session_data=cached`,
+ );
const cleared = res.headers.getSetCookie();
assert.equal(cleared.length, 2);
assert.match(cleared[0]!, /^better-auth\.session_token=;/);
@@ -41,24 +45,24 @@ describe('proxy', () => {
assert.match(cleared[1]!, /Secure/);
});
- it('sends a signed-in user away from the login page', () => {
- const res = run('/login', COOKIE);
+ it('sends a signed-in user away from the login page', async () => {
+ const res = await run('/login', COOKIE);
assert.equal(res.headers.get('location'), 'http://localhost/');
});
- it('leaves a signed-in user on the login page when it carries an error', () => {
- const res = run('/login?error=invalid_client', COOKIE);
+ it('leaves a signed-in user on the login page when it carries an error', async () => {
+ const res = await run('/login?error=invalid_client', COOKIE);
assert.equal(res.headers.get('location'), null);
});
// 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');
+ it('treats a __Host- session cookie as a session', async () => {
+ const res = await 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');
+ it('expires a __Host- cookie only at Path=/, with Secure and no Domain', async () => {
+ const res = await 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/);
@@ -66,29 +70,95 @@ describe('proxy', () => {
assert.ok(!cleared[0]!.includes('Domain='));
});
- it('sends a visitor without a session to the login page', () => {
- const res = run('/', undefined);
+ it('sends a visitor without a session to the login page', async () => {
+ const res = await run('/', undefined);
assert.equal(res.headers.get('location'), 'http://localhost/login');
});
});
describe('proxy security headers', () => {
- it('serves every page with a content security policy naming the api origin', () => {
+ it('serves every page with a content security policy naming the api origin', async () => {
process.env.API_URL = 'http://api.test:3000/';
- const csp = run('/login').headers.get('content-security-policy');
+ const csp = (await run('/login')).headers.get('content-security-policy');
assert.match(csp!, /(^|; )connect-src 'self' blob: http:\/\/api\.test:3000(;|$)/);
assert.match(csp!, /(^|; )frame-ancestors 'none'(;|$)/);
assert.match(csp!, /(^|; )object-src 'none'(;|$)/);
});
- it('keeps the policy on a redirect and on the expired screen', () => {
- assert.ok(run('/', undefined).headers.get('content-security-policy'));
- assert.ok(run('/login?expired=1', COOKIE).headers.get('content-security-policy'));
+ it('keeps the policy on a redirect and on the expired screen', async () => {
+ assert.ok((await run('/', undefined)).headers.get('content-security-policy'));
+ assert.ok((await run('/login?expired=1', COOKIE)).headers.get('content-security-policy'));
});
- it('leaves the media routes to the headers the api sends', () => {
- assert.equal(run('/media/avatars/u1', COOKIE).headers.get('content-security-policy'), null);
+ it('leaves the media routes to the headers the api sends', async () => {
+ assert.equal(
+ (await run('/media/avatars/u1', COOKIE)).headers.get('content-security-policy'),
+ null,
+ );
const document = '/protected-media/projects/KEY/documents/1/assets/x/raw';
- assert.equal(run(document, COOKIE).headers.get('content-security-policy'), null);
+ assert.equal((await run(document, COOKIE)).headers.get('content-security-policy'), null);
+ });
+});
+
+describe('proxy frames', () => {
+ const realFetch = globalThis.fetch;
+ let asked: string[] = [];
+
+ // The api answers `GET /embed-sites` with these sites, or not at all.
+ function api(origins: string[] | null) {
+ globalThis.fetch = (async (url: string) => {
+ asked.push(String(url));
+ if (!origins) throw new Error('unreachable');
+ return Response.json({ origins });
+ }) as typeof fetch;
+ }
+
+ const ancestors = (res: Response) =>
+ /frame-ancestors ([^;]+)/.exec(res.headers.get('content-security-policy')!)![1];
+
+ beforeEach(() => {
+ process.env.API_URL = 'http://api.test:3000';
+ asked = [];
+ forgetEmbedSites();
+ });
+
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ delete process.env.SERVICE_URL_API;
+ });
+
+ it('lets the trusted sites frame a share page and a public page', async () => {
+ api(['https://acme.com', 'http://localhost:5055']);
+ for (const path of ['/share/abc', '/p/forms/support']) {
+ const res = await run(path);
+ assert.equal(ancestors(res), "'self' https://acme.com http://localhost:5055");
+ assert.equal(res.headers.get('x-frame-options'), null);
+ }
+ assert.deepEqual(asked, ['http://api.test:3000/embed-sites']);
+ });
+
+ it("reads the sites at the api's address inside the deployment when it has one", async () => {
+ process.env.SERVICE_URL_API = 'http://api:3000';
+ api(['https://acme.com']);
+ await run('/share/abc');
+ assert.deepEqual(asked, ['http://api:3000/embed-sites']);
+ });
+
+ it('lets only the app frame a public page while no site is trusted or the api does not answer', async () => {
+ api([]);
+ const res = await run('/share/abc');
+ assert.equal(ancestors(res), "'self'");
+ assert.equal(res.headers.get('x-frame-options'), 'SAMEORIGIN');
+
+ forgetEmbedSites();
+ api(null);
+ assert.equal(ancestors(await run('/p/forms/support')), "'self'");
+ });
+
+ it('never frames another page, nor asks the api for one', async () => {
+ api(['https://acme.com']);
+ assert.equal(ancestors(await run('/login')), "'none'");
+ assert.equal(ancestors(await run('/projects', COOKIE)), "'none'");
+ assert.deepEqual(asked, []);
});
});
diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts
index c435cbf2..cb5af8fd 100644
--- a/apps/web/src/proxy.ts
+++ b/apps/web/src/proxy.ts
@@ -1,6 +1,7 @@
import { NextResponse, type NextRequest } from 'next/server';
import { getSessionCookie } from 'better-auth/cookies';
import { contentSecurityPolicy } from '@/utils/contentSecurityPolicy';
+import { readEmbedSites } from '@/utils/embedSites';
// Routes reachable without a session, and that bounce a signed-in user back to
// the app. Everything else requires one.
@@ -14,15 +15,20 @@ const PUBLIC_PATHS = ['/login', '/register'];
// anyone with the link, signed in or not.
// `/media` streams avatars and attachments from the api, which serves them without
// a session — a share page opened by a logged-out visitor shows them too.
+// `/p` holds the pages a build serves to anyone (`PublicPage` in `@/cloud`).
// `/protected-media` is intentionally absent: document assets carry private project
// content and must pass this session gate before their route forwards the cookie.
-const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share', '/media'];
+const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share', '/media', '/p'];
// Routes that stream bytes from the api and pass its headers through, including the
// sandbox policy it puts on a download. The document policy is for html only, and set
// here it would replace the api's.
const MEDIA_PATHS = ['/media', '/protected-media'];
+// The public pages a site the instance owner trusts may show in a frame, and the app itself,
+// which previews them that way. next.config.ts refuses a frame to every other page.
+const EMBEDDABLE_PATHS = ['/share', '/p'];
+
function matcher(pathname: string) {
return (path: string) => pathname === path || pathname.startsWith(`${path}/`);
}
@@ -40,11 +46,18 @@ function clearSession(request: NextRequest): NextResponse {
return response;
}
-export function proxy(request: NextRequest) {
+export async function proxy(request: NextRequest) {
const response = gate(request);
- if (!MEDIA_PATHS.some(matcher(request.nextUrl.pathname))) {
+ const matches = matcher(request.nextUrl.pathname);
+ if (MEDIA_PATHS.some(matches)) return response;
+ if (!EMBEDDABLE_PATHS.some(matches)) {
response.headers.set('Content-Security-Policy', contentSecurityPolicy());
+ return response;
}
+ const sites = await readEmbedSites();
+ response.headers.set('Content-Security-Policy', contentSecurityPolicy(["'self'", ...sites]));
+ // X-Frame-Options names one origin at most; with other sites the policy above decides.
+ if (sites.length === 0) response.headers.set('X-Frame-Options', 'SAMEORIGIN');
return response;
}
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index e03393df..a422c17e 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -330,6 +330,7 @@ export const qk = {
instanceTelegramSettings: ['instanceTelegramSettings'] as const,
instanceProjectDefaults: ['instanceProjectDefaults'] as const,
instanceAgentSettings: ['instanceAgentSettings'] as const,
+ instanceEmbedSites: ['instanceEmbedSites'] as const,
instanceStorageSettings: ['instanceStorageSettings'] as const,
// The upload limits as read by the upload UI (open to any signed-in user).
storageSettings: ['storageSettings'] as const,
diff --git a/apps/web/src/utils/contentSecurityPolicy.ts b/apps/web/src/utils/contentSecurityPolicy.ts
index c4082a41..1457966c 100644
--- a/apps/web/src/utils/contentSecurityPolicy.ts
+++ b/apps/web/src/utils/contentSecurityPolicy.ts
@@ -19,7 +19,8 @@ function apiOrigin(): string {
// pictures, and the /media proxy on this origin. blob: is fetched too: the image
// annotator reads a file picked in the new issue modal through its blob: URL. React
// evals in development only, to rebuild server error stacks in the browser.
-export function contentSecurityPolicy(): string {
+// `frameAncestors` are the sites that may show the page in a frame; none by default.
+export function contentSecurityPolicy(frameAncestors: string[] = []): string {
const scriptSources =
process.env.NODE_ENV === 'development'
? "'self' 'unsafe-inline' 'unsafe-eval'"
@@ -35,6 +36,6 @@ export function contentSecurityPolicy(): string {
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
- "frame-ancestors 'none'",
+ `frame-ancestors ${frameAncestors.length > 0 ? frameAncestors.join(' ') : "'none'"}`,
].join('; ');
}
diff --git a/apps/web/src/utils/embedSites.ts b/apps/web/src/utils/embedSites.ts
new file mode 100644
index 00000000..178b18a3
--- /dev/null
+++ b/apps/web/src/utils/embedSites.ts
@@ -0,0 +1,34 @@
+import { serverRuntimeEnv } from '@/utils/runtimeEnv';
+
+// The sites the instance owner lets show the public pages in a frame (`GET /embed-sites`),
+// read by the proxy at most once a minute. While the api does not answer, the last list
+// stands; before the first answer it is empty, so no site frames anything.
+const TTL_MS = 60_000;
+const TIMEOUT_MS = 2_000;
+
+let read: { at: number; origins: Promise<string[]> } = { at: 0, origins: Promise.resolve([]) };
+
+// Reached as the /media routes reach the api: by its address inside the deployment's network
+// when SERVICE_URL_API names one.
+async function fetchEmbedSites(): Promise<string[]> {
+ const origin = process.env.SERVICE_URL_API || serverRuntimeEnv().apiUrl;
+ const res = await fetch(`${origin}/embed-sites`, {
+ cache: 'no-store',
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`embed sites: ${res.status}`);
+ return ((await res.json()) as { origins: string[] }).origins;
+}
+
+export function readEmbedSites(): Promise<string[]> {
+ if (Date.now() - read.at >= TTL_MS) {
+ const last = read.origins;
+ read = { at: Date.now(), origins: fetchEmbedSites().catch(() => last) };
+ }
+ return read.origins;
+}
+
+// Drops what was read, so the next page reads the list again.
+export function forgetEmbedSites(): void {
+ read = { at: 0, origins: Promise.resolve([]) };
+}
diff --git a/apps/web/src/utils/settingsSections.ts b/apps/web/src/utils/settingsSections.ts
index 5d821b27..08d7ee0a 100644
--- a/apps/web/src/utils/settingsSections.ts
+++ b/apps/web/src/utils/settingsSections.ts
@@ -1,3 +1,4 @@
+import type { ComponentType } from 'react';
import {
Bot,
Clock3,
@@ -16,26 +17,23 @@ import {
} from 'lucide-react';
import type { PermissionAction, PermissionResource } from '@/lib/api/endpoints/roles';
-// The sidebar group a section is listed under: the project-level general settings,
-// workflow configuration, automation/integrations, or the AI section. 'ai-team' and
-// 'ai' sections are listed in the main sidebar's AI Team group, not in the project
-// settings sidebar.
-export type SettingsGroup = 'general' | 'configuration' | 'automation' | 'ai' | 'ai-team';
-
// The project settings sections, each mounted as its own page at
// /:team/:projectKey/settings/:section, except the 'ai-team' group, which is
// mounted at /:team/:projectKey/agents/:section. The slug is the route param; the tab
// components live in features/settings/components and take { project }. `resource`
// is the permission resource that gates the section: `viewAction` (read unless set)
-// to view it, and the create/edit/delete actions gate the controls inside. `group` places it in the
-// sidebar (see CONFIGURATION_SECTIONS / AUTOMATION_SECTIONS). The name and the
-// blurb of a section are messages under `sections.settings`.
+// to view it, and the create/edit/delete actions gate the controls inside. `group` is
+// the heading the settings sidebar lists it under, named in `nav.groups`; the 'ai-team'
+// and 'ai' sections are listed in the main sidebar's AI Team group instead. The name and
+// the blurb of a section are messages under `sections.settings`. A section the hosted
+// build adds (`useProjectSettingsSections` in `@/cloud`) carries its page in `Component`.
export type SettingsSection = {
slug: string;
icon: LucideIcon;
resource: PermissionResource;
viewAction?: PermissionAction;
- group: SettingsGroup;
+ group: string;
+ Component?: ComponentType;
};
export const SETTINGS_SECTIONS: SettingsSection[] = [
@@ -43,43 +41,43 @@ export const SETTINGS_SECTIONS: SettingsSection[] = [
slug: 'general',
icon: Info,
resource: 'danger_zone',
- group: 'general',
+ group: 'project',
},
{
slug: 'states',
icon: Columns3,
resource: 'states',
- group: 'configuration',
+ group: 'workflow',
},
{
slug: 'issue-types',
icon: Shapes,
resource: 'issue_types',
- group: 'configuration',
+ group: 'workflow',
},
{
slug: 'labels',
icon: Tags,
resource: 'labels',
- group: 'configuration',
+ group: 'workflow',
},
{
slug: 'custom-fields',
icon: ListPlus,
resource: 'custom_fields',
- group: 'configuration',
+ group: 'workflow',
},
{
slug: 'issue-templates',
icon: FileText,
resource: 'issue_templates',
- group: 'configuration',
+ group: 'workflow',
},
{
slug: 'configuration',
icon: SlidersHorizontal,
resource: 'workflow_config',
- group: 'configuration',
+ group: 'workflow',
},
{
slug: 'actions',
@@ -130,10 +128,8 @@ export const AI_AGENTS_SECTION: SettingsSection = {
group: 'ai',
};
-// The settings sections split by sidebar group.
-export const GENERAL_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group === 'general');
-export const CONFIGURATION_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group === 'configuration');
-export const AUTOMATION_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group === 'automation');
+// The sections the project settings sidebar lists.
+export const SETTINGS_MENU_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group !== 'ai-team');
export const AI_TEAM_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group === 'ai-team');
const BY_SLUG = new Map(SETTINGS_SECTIONS.map((s) => [s.slug, s]));