From 08485b5149071c61c26eccd6bb5e79c1b6043ca0 Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 20:41:29 +0000 Subject: [PATCH] GEN-2012 add settings integrations dashboard --- packages/app/src/index.ts | 2 +- packages/app/src/tenant.ts | 6 +++--- packages/app/src/ui.ts | 14 ++++++++++++-- packages/app/test/ui.test.ts | 10 +++++++++- packages/app/test/worker.test.ts | 17 +++++++++++++++++ 5 files changed, 42 insertions(+), 7 deletions(-) diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index cc699e0a..24741faa 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -91,7 +91,7 @@ app.get("/auth/linear/callback", async (c) => { const memberResponse = await stub.fetch("https://tenant/members", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: viewer.id, email: viewer.email }) }); const member = await memberResponse.json() as { role: string; session_version: number }; if (member.role !== "owner") return c.text("This Factorize tenant requires an owner invitation.", 403); - await stub.fetch("https://tenant/connections/linear", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name }) }); + await stub.fetch("https://tenant/connections/linear", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name, viewerId: viewer.id, viewerEmail: viewer.email }) }); const lifetime = 60 * 60 * 24 * 7; setCookie(c, "factorize_session", await signSession({ tenantId: organization.id, userId: viewer.id, email: viewer.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: member.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); const oauthReturn = getCookie(c, "factorize_oauth_return"); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 708d5292..1ceb3f36 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -260,7 +260,7 @@ export class Tenant extends DurableObject { } private async saveLinear(input: unknown): Promise { - const value = input as { accessToken?: string; refreshToken?: string; organizationId?: string; organizationName?: string }; + const value = input as { accessToken?: string; refreshToken?: string; organizationId?: string; organizationName?: string; viewerId?: string; viewerEmail?: string }; if (!value.accessToken || !value.refreshToken || !value.organizationId) throw new Error("Linear tokens and organization are required"); await this.putConnection("linear", value); return json({ ok: true }); @@ -352,12 +352,12 @@ export class Tenant extends DurableObject { } private async connectionStatus(): Promise { - const linear = await this.connection<{ organizationName?: string }>("linear"); + const linear = await this.connection<{ organizationName?: string; viewerEmail?: string }>("linear"); const connections = await this.exeConnections(); const exe = await this.connection("exe"); const ampConnections = await this.ampConnections(); return json({ - linear: linear ? { organizationName: linear.organizationName ?? null } : null, + linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, exe: exe ? { vmName: exe.vmName, agentKind: exe.agentKind, cwd: exe.cwd, herdrCommand: exe.herdrCommand ?? "herdr", agentCommand: exe.agentCommand ?? defaultAgentCommand(exe.agentKind) } : null, exeConnections: connections.map(({ apiToken, ...connection }) => connection), ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection), diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index c1792ebd..9857cf64 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -260,5 +260,15 @@ async function load(){const [j,runs]=await Promise.all([request('/api/jobs/'+enc export const jobRunPage = (viewer: { email: string }, runId: string) => shell("Run — Factorize", viewer, `

Loading run…

`, `${uiHelpers} const root=$('#run-detail'),id=root.dataset.id;request('/api/job-runs/'+encodeURIComponent(id)).then(r=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),trusted=typeof r.destination_url==='string'&&r.destination_url.startsWith('https://');root.innerHTML='← Job

Run '+esc(r.id.slice(0,8))+'

'+esc(r.backend_kind)+' · '+new Date(r.created_at).toLocaleString()+'

'+stateBadge(r.state)+(canStop?'':'')+'

Observation

'+(trusted?'Open '+esc(r.backend_kind)+' destination ↗':'

This backend has no external observation link.

')+'
'+(canOutput?'

Output

'+esc(r.result||'Output is not available yet.')+'
':'
Output is available only in the backend observation experience.
');if(canStop)$('#stop-run').onclick=async()=>{await request('/api/job-runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()}}).catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); -export const settingsPage = (viewer: { email: string }) => shell("Settings — Factorize", viewer, `
${dashboardHead("Settings", "Create and rotate provider connections here. Credential values never appear in Jobs or MCP.")}

Exe.dev execution connections

Loading…

Amp cloud execution

Loading…

`, `${uiHelpers} -async function load(){const s=await request('/api/connections/status');$('#connections').innerHTML=s.exeConnections?.length?'
    '+s.exeConnections.map(c=>'
  • '+esc(c.vmName)+' · '+esc(c.agentKind)+' · '+esc(c.cwd)+'
  • ').join('')+'
':'No execution connections yet.';$('#amp-connections').innerHTML=s.ampConnections?.length?s.ampConnections.map(c=>'
'+esc(c.project)+' · Amp cloud
').join(''):'No Amp connections yet.'}$('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The credential is stored securely and will not be displayed.';load()}catch(x){m.textContent=x.message}};const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection failed.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token will not be displayed.';load()}catch(x){m.textContent=x.message}};load();`); +export const settingsPage = (viewer: { email: string }) => shell("Integrations — Factorize", viewer, `
${dashboardHead("Integrations", "Connect every provider used by your Jobs. Stored credentials are write-only and are never displayed.")} + +

Linear

Issues, projects, and trigger resources.

Loading…
Checking your workspace…
Reconnect Linear
+

GitHub App

Repositories and supported GitHub triggers.

Loading…
Loading installations…
+

Exe.dev execution

VM destinations and working directories.

Loading…
Loading connections…

+

Amp cloud execution

Cloud projects used as execution targets.

Loading…
Loading connections…

`, `${uiHelpers} +const badge=(id,label,tone)=>{const el=$(id);el.textContent=label;el.className='rounded-full px-3 py-1 text-xs font-semibold '+(tone==='ok'?'bg-green-100 text-green-800 dark:bg-green-950 dark:text-green-200':tone==='warn'?'bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200':'bg-stone-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300')}; +const testButton=(kind,id)=>''; +async function load(){try{const [s,gh]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations')]);if(s.linear){badge('#linear-status','Connected','ok');$('#linear-details').innerHTML=''+esc(s.linear.organizationName||'Linear workspace')+''+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):'');$('#linear-action').textContent='Reconnect Linear'}else{badge('#linear-status','Not connected','warn');$('#linear-details').textContent='Connect a Linear workspace to load issue and project resources.';$('#linear-action').textContent='Connect Linear'}const exe=s.exeConnections||[];badge('#exe-status',exe.length?'Connected':'Not connected',exe.length?'ok':'warn');$('#connections').innerHTML=exe.length?'
    '+exe.map(c=>'
  • '+esc(c.vmName)+''+esc(c.cwd)+' · '+esc(c.agentKind)+''+testButton('exe',c.connectionId)+'
  • ').join('')+'
':'No exe.dev connections yet.';const amps=s.ampConnections||[];badge('#amp-status',amps.length?'Connected':'Not connected',amps.length?'ok':'warn');$('#amp-connections').innerHTML=amps.length?'
    '+amps.map(c=>'
  • '+esc(c.project)+''+testButton('amp',c.connectionId)+'
  • ').join('')+'
':'No Amp connections yet.';if(gh.status===404){badge('#github-status','Unavailable','neutral');$('#github-installations').textContent='GitHub integration is not enabled for this Factorize deployment.';$('#github-install').classList.add('hidden');$('#github-manage').classList.add('hidden')}else if(!gh.ok){badge('#github-status','Action required','warn');$('#github-installations').textContent='GitHub installation status could not be loaded.'}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-status',active.length?'Connected':installs.length?'Action required':'Not connected',active.length?'ok':'warn');$('#github-installations').innerHTML=installs.length?'
    '+installs.map(x=>'
  • '+esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub')+' · '+esc(x.state)+'
  • ').join('')+'
':'No GitHub App installations yet.'}bindTests()}catch(e){const error=$('#integration-error');error.textContent=e.message||'Could not load integration status.';error.classList.remove('hidden');['#linear-status','#github-status','#exe-status','#amp-status'].forEach(id=>badge(id,'Unavailable','neutral'))}} +function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} +$('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; +const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}};load();`); diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index 25bcb8ab..271761fb 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -138,7 +138,15 @@ describe("pages", () => { expect(detail).toContain("Run now"); expect(run).toContain("destination_url"); expect(run).toContain("caps.includes('output')"); - expect(settings).toContain("Save / rotate connection"); + expect(settings).toContain("Connect every provider used by your Jobs"); + expect(settings).toContain("Linear"); + expect(settings).toContain("GitHub App"); + expect(settings).toContain("Exe.dev execution"); + expect(settings).toContain("Amp cloud execution"); + expect(settings).toContain("Not connected"); + expect(settings).toContain("Action required"); + expect(settings).toContain("Unavailable"); + expect(settings).toContain("write-only"); for (const [name, html] of Object.entries({ list, editor, detail, run, settings })) { try { expectInlineScriptsToParse(html); } catch (error) { throw new Error(`${name}: ${error}`); } } diff --git a/packages/app/test/worker.test.ts b/packages/app/test/worker.test.ts index c65d56cc..c79c3774 100644 --- a/packages/app/test/worker.test.ts +++ b/packages/app/test/worker.test.ts @@ -85,6 +85,23 @@ describe("Worker routes", () => { await expect(response.json()).resolves.toEqual(projects); }); + it("returns secret-free integration status through the owner boundary", async () => { + const status = { + linear: { organizationName: "Generation", viewerEmail: "owner@example.com" }, + exeConnections: [{ connectionId: "exe-1", vmName: "exedev@workbox", cwd: "/repo", agentKind: "codex" }], + ampConnections: [{ connectionId: "amp-1", project: "generation/factorize", apiBaseUrl: "https://ampcode.com/api/cloud/v1" }], + }; + const response = await app.request("https://factorize.test/api/connections/status", { + headers: { cookie: await sessionCookie() }, + }, testEnv(ownerHandler({ "/connections/status": Response.json(status) }))); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body).toEqual(status); + expect(JSON.stringify(body)).not.toContain("apiToken"); + expect(JSON.stringify(body)).not.toContain("accessToken"); + expect(JSON.stringify(body)).not.toContain("refreshToken"); + }); + it("returns flow activity through the authenticated Durable Object boundary", async () => { const activity = { flow: { id: "flow-1", name: "Bugs" }, events: [], runs: [] }; const response = await app.request("https://factorize.test/api/pipes/flow-1", {