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 .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@
the `Components` page (tokens frame, components, `component_unknown`, variants and states, motion per micro-interaction)) and stores the result in
`design_attestations`, one row per design frame at its `updatedAt`, append-only. The route
`/api/design-attestations/:id` reads a run with `current` (false once any frame changed).
`GET /api/service/design-attestations/:id` (G4, CHE-7080) serves the same JSON plus `pageIssueId` (the attested
page's current Multica issue, or null) to Multica: it sits before the `/api` session gate, wants
`Authorization: Bearer <DOOP_ATTESTATION_READ_TOKEN>` (compared as SHA-256 digests with `timingSafeEqual`; 401 if
missing or wrong, 503 while the variable is unset, at least 32 characters), is GET only, and 404s an unknown id.
`extraChecks` is the plug-in point for the requirement ledger. Tests: `designCompleteness.test.ts`,
`designAttestation.test.ts`.

Expand Down
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -416,3 +416,6 @@
#MULTICA_API_TOKEN=
#MULTICA_WORKSPACE_ID=
#MULTICA_WEB_URL=
# Bearer token for Multica's design-attestation reads (32+ characters).
# Unset = the service route returns 503.
#DOOP_ATTESTATION_READ_TOKEN=
10 changes: 10 additions & 0 deletions server/designAttestations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,13 @@ export async function readAttestation(
currentAttestation(canvas, head.pageId, rows, requirementsNow?.hash ?? null)?.runId === runId,
}
}

/** The view plus the issue the attested page is bound to now (null when unbound): the G4 service route's answer. */
export async function readServiceAttestation(
runId: string,
): Promise<(AttestationView & { pageIssueId: string | null }) | null> {
const view = await readAttestation(runId)
if (!view) return null
const page = store.getCanvas(view.canvasId)?.pages?.find((p) => p.id === view.pageId)
return { ...view, pageIssueId: page?.issueId ?? null }
}
9 changes: 9 additions & 0 deletions server/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ const origin = makeExactValidator<string>((input) => {
return input.replace(/\/+$/, '')
})

/** A secret of at least `minimum` characters: a short shared token is guessable. */
const secret = (minimum: number) =>
makeExactValidator<string>((input) => {
if (input.length < minimum) throw new TypeError(`Too short (expected >= ${minimum} characters)`)
return input
})

/** Comma-separated values, trimmed, empties dropped. */
const list = makeExactValidator<string[]>((input) =>
input
Expand Down Expand Up @@ -170,6 +177,8 @@ const schema = {
MULTICA_API_TOKEN: str({ default: undefined }),
MULTICA_WORKSPACE_ID: str({ default: undefined }),
MULTICA_WEB_URL: str({ default: undefined }),
/* G4: the bearer token Multica sends to GET /api/service/design-attestations/:id; unset = route answers 503 */
DOOP_ATTESTATION_READ_TOKEN: secret(32)({ default: undefined }),
LINEAR_API_URL: str({ default: 'https://api.linear.app/graphql' }),
LINEAR_TOKEN_URL: str({ default: 'https://api.linear.app/oauth/token' }),
SLACK_CLIENT_ID: str({ default: undefined }),
Expand Down
16 changes: 14 additions & 2 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { handleGeminiCloudMcp } from './geminiCloudMcp.ts'
import { serveClient } from './clientStatic.ts'
import { geminiCloudWorkerFor } from './geminiCloudRuns.ts'
import http from 'node:http'
import { createHash } from 'node:crypto'
import { createHash, timingSafeEqual } from 'node:crypto'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import express from 'express'
Expand Down Expand Up @@ -48,7 +48,7 @@ import * as demo from './demo.ts'
import { db, initDb } from './db/index.ts'
import * as authSchema from './db/auth-schema.ts'
import * as persist from './db/persist.ts'
import { readAttestation } from './designAttestations.ts'
import { readAttestation, readServiceAttestation } from './designAttestations.ts'
import { handleMcpRequest } from './mcp.ts'
import {
getAsset,
Expand Down Expand Up @@ -666,6 +666,18 @@ declare global {
the gate looks at that session (shared/desktopConnect.ts) */
app.get('/api/integrations/:provider/callback', relayDesktopCallback)
app.use('/api/live-activities', logLiveActivityRequests)
/* G4 (CHE-7080): Multica reads an attestation with one shared bearer token, not a session. Registered
before the /api session gate; GET only; SHA-256 digests are compared so the token's length leaks nothing. */
const sha256 = (value: string) => createHash('sha256').update(value).digest()
app.get('/api/service/design-attestations/:id', async (req, res) => {
const expected = env.DOOP_ATTESTATION_READ_TOKEN
if (!expected) return res.status(503).json({ error: 'attestation read token not configured' })
const presented = /^Bearer (.+)$/.exec(req.headers.authorization ?? '')?.[1] ?? ''
if (!timingSafeEqual(sha256(presented), sha256(expected))) return res.status(401).json({ error: 'unauthorized' })
const view = await readServiceAttestation(req.params.id)
if (!view) return res.status(404).json({ error: 'attestation not found' })
res.json(view)
})
app.use('/api', async (req, res, next) => {
try {
const session = await auth.api.getSession({ headers: fromNodeHeaders(req.headers) })
Expand Down
175 changes: 175 additions & 0 deletions tests/designAttestationService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { createServer, type Server as HttpServer } from 'node:http'
import { Client as McpClient } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import type { Canvas, Frame } from '../shared/types'
import { Client, freePort, startServer, type Server } from './harness.ts'
import { addMotionAndDocs, sloplintFor } from './motionFixtures.ts'

/* G4 service read route (CHE-7080, plan CHE-7064 r3 D1.7): Multica reads an
attestation with one shared bearer token instead of a user session. */

const TOKEN = 'attestation-read-token-0123456789abcdef-xyz'
const ISSUE = '01a1d642-a8dd-75cd-886c-97d80b9e0048'
const ROUTE = '/api/service/design-attestations'

/* a complete page, the same shape tests/designAttestation.test.ts builds: only a complete run can be current */
const RECON = JSON.stringify({
scanHash: 'scan-1',
candidates: [{ id: 'sort-oldest', file: 'display-parts.tsx', line: 29, decision: 'keep' }],
})
const MOTION = JSON.stringify({
trigger: 'hover',
property: 'opacity',
duration: '200ms',
easing: 'ease-out',
reducedMotion: 'none',
})
const HIFI = `<main>
<button data-recon-ref="sort-oldest">Oldest</button>
<p data-doop-state="loading"></p><p data-doop-state="empty"></p><p data-doop-state="error"></p>
<p data-doop-state-na="disconnected: read-only screen"></p>
<div data-doop-motion='${MOTION}'></div>
</main>`

describe('service read route, token unset', () => {
let bare: Server
beforeAll(async () => {
bare = await startServer()
}, 60_000)
afterAll(() => bare?.stop())

it('answers 503 to every request, with or without a token', async () => {
expect((await fetch(`${bare.base}${ROUTE}/anything`)).status).toBe(503)
const withToken = await fetch(`${bare.base}${ROUTE}/anything`, { headers: { Authorization: `Bearer ${TOKEN}` } })
expect(withToken.status).toBe(503)
})
})

/* G3 (g3-r7) only attests a page bound to an issue, with the requirement ledger read from Multica: a stub Multica answers it */
function stubMultica(): Promise<{ http: HttpServer; port: number }> {
const http = createServer((req, res) => {
res.setHeader('Content-Type', 'application/json')
if (req.url === `/api/issues/${ISSUE}`)
return void res.end(JSON.stringify({ id: ISSUE, identifier: 'CHE-77', description: null }))
if (req.url === `/api/issues/${ISSUE}/comments`) return void res.end('[]')
res.statusCode = 404
res.end('{}')
})
return freePort().then(
(port) => new Promise((resolve) => http.listen(port, '127.0.0.1', () => resolve({ http, port }))),
)
}

describe('service read route, token set', () => {
let multica: HttpServer
let server: Server
let owner: Client
let agent: McpClient
let canvas: Canvas
let pageId: string
let design: Frame
let attestationId: string

const read = (id: string, auth?: string) =>
fetch(`${server.base}${ROUTE}/${id}`, { headers: auth ? { Authorization: auth } : {} })
const bearer = `Bearer ${TOKEN}`
const setPageIssue = (issueId: string | null) =>
owner.req(`/api/canvases/${canvas.id}/pages/${pageId}/issue`, { method: 'PUT', body: JSON.stringify({ issueId }) })

beforeAll(async () => {
const stub = await stubMultica()
multica = stub.http
server = await startServer({
DOOP_ATTESTATION_READ_TOKEN: TOKEN,
MULTICA_API_URL: `http://127.0.0.1:${stub.port}`,
MULTICA_API_TOKEN: 'svc-token',
MULTICA_WORKSPACE_ID: 'ws-1',
})
owner = await new Client(server).signUp('svc-attest@test.dev', 'Svc Owner')
const { secret } = await (await owner.post('/api/agent-keys', { name: 'Reviewer' })).json()
agent = new McpClient({ name: 'svc-attestation-test', version: '1.0.0' })
await agent.connect(
new StreamableHTTPClientTransport(new URL('/mcp', server.base), {
requestInit: { headers: { Authorization: `Bearer ${secret}` } },
}),
)
canvas = await (await owner.post('/api/canvases', { name: 'Svc proposal' })).json()
pageId = canvas.pages?.[0]?.id ?? `${canvas.id}:page1`
expect((await setPageIssue(ISSUE)).status).toBe(200)
const addFrame = async (name: string, html: string): Promise<Frame> =>
(await owner.post(`/api/canvases/${canvas.id}/frames`, { name, html })).json()
await addFrame('Recon', `<script type="application/json" id="doop-recon">${RECON}</script>`)
const wire = await addFrame('Wire', '<div data-doop-stage="wireframe"></div>')
design = await addFrame('Hi-fi', HIFI)
await addMotionAndDocs(owner, canvas.id, 'CHE-77', ['Hi-fi'])
await owner.patch(`/api/frames/${wire.id}`, {
html: `<div data-doop-stage="wireframe"><a data-doop-on="click" data-doop-action="navigate:${design.id}">next</a></div>`,
})
await agent.callTool({
name: 'set_prototype_start',
arguments: { canvas_id: canvas.id, frame_id: wire.id, agent_name: 'Reviewer' },
})
const result = await agent.callTool({
name: 'check_design_completeness',
arguments: { canvas_id: canvas.id, sloplint: await sloplintFor(owner, canvas.id), agent_name: 'Reviewer' },
})
const text = (result.content as { type: string; text?: string }[]).find((c) => c.type === 'text')!.text!
attestationId = JSON.parse(text).attestation_id
}, 120_000)

afterAll(async () => {
await agent?.close()
server?.stop()
multica?.close()
})

it('refuses a missing token with 401', async () => {
expect((await read(attestationId)).status).toBe(401)
})

it('refuses a wrong token with 401', async () => {
expect((await read(attestationId, 'Bearer nope')).status).toBe(401)
expect((await read(attestationId, `Bearer ${TOKEN}x`)).status).toBe(401)
expect((await read(attestationId, TOKEN)).status).toBe(401)
})

it('answers 404 for an unknown id', async () => {
expect((await read('nope', bearer)).status).toBe(404)
})

it('serves GET only', async () => {
const res = await fetch(`${server.base}${ROUTE}/${attestationId}`, {
method: 'DELETE',
headers: { Authorization: bearer },
})
expect(res.status).toBeGreaterThanOrEqual(401)
expect(res.status).not.toBe(200)
})

it('returns the view with current true and the bound pageIssueId', async () => {
const res = await read(attestationId, bearer)
expect(res.status).toBe(200)
expect(await res.json()).toMatchObject({
id: attestationId,
canvasId: canvas.id,
pageId,
current: true,
pageIssueId: ISSUE,
})
})

it('reports current false after a frame edit', async () => {
await owner.patch(`/api/frames/${design.id}`, { html: HIFI + '<!-- edited -->' })
const res = await read(attestationId, bearer)
expect(res.status).toBe(200)
expect((await res.json()).current).toBe(false)
})

it('reports pageIssueId null once the page is unbound', async () => {
expect((await setPageIssue(null)).status).toBe(200)
const res = await read(attestationId, bearer)
expect(res.status).toBe(200)
expect((await res.json()).pageIssueId).toBeNull()
})
})
Loading