Skip to content
Open
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
20 changes: 14 additions & 6 deletions .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,22 +38,30 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v7
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '22'
cache: 'npm'
- run: npm install --legacy-peer-deps
- run: npm audit --audit-level=high
continue-on-error: true
- name: Upload audit report
if: always()
run: npm audit --json > npm-audit-report.json || true
- name: Use the declared npm version
run: npm install --global npm@10.8.0
- name: Install the locked dependency graph
run: npm ci --ignore-scripts --no-audit --no-fund
- name: Audit locked npm dependencies
run: |
set +e
npm audit --audit-level=high --json > npm-audit-report.json
audit_exit=$?
set -e
cat npm-audit-report.json
exit "$audit_exit"
- uses: actions/upload-artifact@v7
if: always()
with:
name: npm-audit-report
path: npm-audit-report.json
if-no-files-found: error

python-safety:
runs-on: ubuntu-latest
Expand Down
14 changes: 10 additions & 4 deletions MERGE_POLICY.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,16 @@ an exact advisory/package/version/image scope, applicability evidence,
compensating controls, an accountable approver, linked issue, expiry, and an
enforced expiry check. A missing advisory or unproven exposure remains unresolved.

The other security jobs also remain completion gates: `npm-audit`, `python-safety`,
and `bandit` still tolerate findings. CodeQL check failure also depends on the
repository's code-scanning settings. Their green conclusions do not establish
absence of vulnerabilities.
`npm-audit` installs the committed dependency graph with the declared npm version
and `npm ci`, then fails on high/critical npm advisories or audit execution errors.
It retains the JSON report even when the audit fails. A passing result covers
that dependency graph and the advisory data available during that run; it is not
a claim that the application has no vulnerabilities.

The other security jobs remain completion gates: `python-safety` and `bandit`
still tolerate findings. CodeQL check failure also depends on the repository's
code-scanning settings. Their green conclusions do not establish absence of
vulnerabilities.

> **`trivy` is lowercase.** Two distinct check-runs exist on the same head —
> `trivy` reports `success`, `Trivy` reports `neutral`, confirmed on both heads
Expand Down
13 changes: 7 additions & 6 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"@ai-sdk/gateway": "^4.0.90",
"@ai-sdk/react": "4.0.117",
"@flags-sdk/vercel": "^1.4.9",
"@google/genai": "^2.24.0",
"@google/genai": "^2.30.0",
"@google/generative-ai": "^0.24.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/core": "2.11.0",
Expand Down Expand Up @@ -48,7 +48,7 @@
"flags": "^4.3.1",
"jpeg-js": "^0.4.4",
"lucide-react": "^1.47.0",
"next": "16.3.8",
"next": "16.4.3",
"next-auth": "^4.24.15",
"openai": "^7.23.0",
"react": "^19",
Expand All @@ -64,10 +64,11 @@
"v0": "3.0.7",
"workflow": "^4.8.9",
"yaml": "^2.9.1",
"zod": "^4.6.5",
"zod": "^4.6.6",
"zustand": "^5.0.15"
},
"devDependencies": {
"@modelcontextprotocol/sdk": "^1.32.0",
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@testing-library/dom": "^10.4.2",
Expand All @@ -78,14 +79,14 @@
"@types/react-dom": "^19",
"autoprefixer": "^10.6.1",
"eslint": "^9.39.5",
"eslint-config-next": "^16.3.6",
"eslint-config-next": "^16.4.3",
"jsdom": "^30.1.1",
"playwright": "^1.62.1",
"postcss": "^8.5.26",
"tailwindcss": "^4.3.3",
"typescript": "6.0.3",
"vite": "^8.3.0",
"vitest": "^5.0.0"
"vite": "^8.3.3",
"vitest": "^5.0.3"
},
"overrides": {
"@protobufjs/utf8": "^1.1.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { createServer, type Server } from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { z } from 'zod';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';

const webRequire = createRequire(import.meta.url);
const rootRequire = createRequire(fileURLToPath(new URL('../../../../../package.json', import.meta.url)));
const servers: Server[] = [];

afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve, reject) => {
server.closeAllConnections();
server.close((error) => error ? reject(error) : resolve());
})));
});

async function localEndpoint() {
const server = createServer((request, response) => {
response.writeHead(200, { 'content-type': 'application/json' });
response.end(JSON.stringify({ method: request.method, path: request.url }));
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('Local fixture did not bind a TCP port');
return `http://127.0.0.1:${address.port}/receipt`;
}

describe('installed dependency consumer compatibility', () => {
it('round-trips MCP tools and enforces Zod input validation before executing a handler', async () => {
const server = new McpServer({ name: 'eventrelay-offline-regression', version: '1.0.0' });
const handler = vi.fn(async ({ message }: { message: string }) => ({
content: [{ type: 'text' as const, text: message.toUpperCase() }],
}));
server.registerTool('echo', {
description: 'Local transport fixture; no provider or external service.',
inputSchema: { message: z.string().min(1) },
}, handler);
const client = new Client({ name: 'eventrelay-offline-client', version: '1.0.0' });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const listing = await client.listTools();
expect(listing.tools[0].inputSchema).toMatchObject({
type: 'object', properties: { message: { type: 'string', minLength: 1 } }, required: ['message'],
});
expect(await client.callTool({ name: 'echo', arguments: { message: 'evidence' } }))
.toMatchObject({ content: [{ type: 'text', text: 'EVIDENCE' }] });
expect(await client.callTool({ name: 'echo', arguments: { message: 123 } }))
.toMatchObject({ isError: true });
expect(handler).toHaveBeenCalledTimes(1);
} finally {
await client.close();
await server.close();
}
});

it('loads Next native Sharp dependency and transforms real PNG bytes', async () => {
const nextRequire = createRequire(webRequire.resolve('next'));
const sharp = nextRequire('sharp') as typeof import('sharp').default;
const source = await sharp({
create: { width: 4, height: 4, channels: 4, background: { r: 20, g: 80, b: 160, alpha: 1 } },
}).png().toBuffer();
const resized = await sharp(source).resize(2, 2).png().toBuffer();
expect(source.subarray(1, 4).toString()).toBe('PNG');
expect(await sharp(resized).metadata()).toMatchObject({ format: 'png', width: 2, height: 2 });
});

it.each([
['root tools', () => rootRequire('undici')],
['web runtime', () => webRequire('undici')],
...['@ai-sdk/provider-utils', '@workflow/world-local', '@workflow/world-vercel', '@vercel/blob']
.map((name) => [name, () => createRequire(webRequire.resolve(name))('undici')] as const),
] as const)('%s uses its own Undici Agent with a real loopback response', async (_name, load) => {
// Resolve from the actual consumer so nested Undici 6/7 and root 8 all run.
// This catches Agent/fetch class mismatches across hoisted dependency copies.
const { Agent, fetch } = load() as typeof import('undici');
const dispatcher = new Agent();
try {
const response = await fetch(await localEndpoint(), { dispatcher });
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ method: 'GET', path: '/receipt' });
} finally {
await dispatcher.close();
}
});
});
191 changes: 191 additions & 0 deletions apps/web/src/lib/__tests__/gemini-sdk-continuation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GoogleGenAI, Type, type Fetch, type GenerateContentResponse } from '@google/genai';
import { geminiSampling } from '../gemini-parameters';

// Exercise the installed SDK's public API and HTTP serialization, not mocked
// models methods. All responses are synthetic transport fixtures; no provider
// credentials, billing, or claims about live model availability are involved.
type Payload = Record<string, unknown>;
const MODEL = 'gemini-3.8-flash';
const request = { model: MODEL, contents: 'Summarize the supplied evidence.' };

function response(text: string, finishReason = 'STOP', continuationToken?: string, groundingMetadata?: Payload): Payload {
return {
candidates: [{
index: 0,
content: { role: 'model', parts: [{ text }] },
finishReason,
...(continuationToken ? { continuationToken } : {}),
...(groundingMetadata ? { groundingMetadata } : {}),
}],
};
}

function json(payload: Payload, status = 200): Response {
return new Response(JSON.stringify(payload), { status, headers: { 'content-type': 'application/json' } });
}

function sse(...payloads: Payload[]): Response {
return new Response(payloads.map((payload) => `data: ${JSON.stringify(payload)}\n\n`).join(''), {
headers: { 'content-type': 'text/event-stream' },
});
}

function harness(...hops: Array<Response | Error>) {
const fetch = vi.fn<Fetch>(async () => {
const hop = hops.shift();
if (!hop) throw new Error('Unexpected SDK request: transport fixtures exhausted');
if (hop instanceof Error) throw hop;
return hop;
});
const client = new GoogleGenAI({
apiKey: 'offline-test-key',
vertexai: false,
httpOptions: { fetch, retryOptions: { attempts: 1 } },
});
return { client, fetch };
}

async function collect(client: GoogleGenAI): Promise<GenerateContentResponse[]> {
const chunks: GenerateContentResponse[] = [];
for await (const chunk of await client.models.generateContentStream(request)) chunks.push(chunk);
return chunks;
}

function grounding(label: string): Payload {
return {
groundingChunks: [{ web: { uri: `https://example.test/${label}`, title: label } }],
groundingSupports: [{
segment: { partIndex: 0, startIndex: 0, endIndex: label.length, text: label },
groundingChunkIndices: [0],
}],
webSearchQueries: [label],
};
}

beforeEach(() => {
// Fail closed if a future SDK version bypasses the explicitly supplied fetch.
vi.stubGlobal('fetch', vi.fn(() => { throw new Error('Live network is forbidden in this test'); }));
});
afterEach(() => vi.unstubAllGlobals());

describe('installed Gemini SDK continuation contract', () => {
it('joins unary hops and preserves grounding references to the correct parts and sources', async () => {
const { client, fetch } = harness(
json(response('first', 'CONTINUATION', 'checkpoint-1', grounding('first'))),
json(response('second', 'STOP', undefined, grounding('second'))),
);
const result = await client.models.generateContent(request);
expect(result.text).toBe('firstsecond');
expect(fetch).toHaveBeenCalledTimes(2);
const candidate = result.candidates?.[0];
expect(candidate?.finishReason).toBe('STOP');
expect(candidate?.continuationToken).toBeUndefined();
expect(candidate?.groundingMetadata?.groundingChunks?.map((chunk) => chunk.web?.uri))
.toEqual(['https://example.test/first', 'https://example.test/second']);
expect(candidate?.groundingMetadata?.groundingSupports?.map((support) => ({
part: support.segment?.partIndex, chunks: support.groundingChunkIndices,
}))).toEqual([{ part: 0, chunks: [0] }, { part: 1, chunks: [1] }]);
expect(candidate?.groundingMetadata?.webSearchQueries).toEqual(['first', 'second']);
});

it('recovers a dropped resumed request and an empty resumed stream without duplicating text', async () => {
const { client, fetch } = harness(
sse(response('first', 'CONTINUATION', 'checkpoint-1')),
new TypeError('fetch failed'),
sse(),
sse(response('second')),
);
const chunks = await collect(client);
expect(chunks.map((chunk) => chunk.text)).toEqual(['first', 'second']);
expect(chunks[0].candidates?.[0]?.finishReason).toBeUndefined();
expect(chunks[1].candidates?.[0]?.finishReason).toBe('STOP');
expect(fetch).toHaveBeenCalledTimes(4);
// Inspect actual serialized continuation requests below, without depending
// on private SDK methods or state.
for (const [, init] of fetch.mock.calls.slice(1)) {
expect(JSON.parse(init?.body as string))
.toHaveProperty('continuationToken', 'checkpoint-1');
}
});

it.each(['unary', 'stream'] as const)('stops %s continuation on promptFeedback without candidates', async (mode) => {
const blocked = { promptFeedback: { blockReason: 'SAFETY', blockReasonMessage: 'Blocked fixture' } };
const { client, fetch } = harness(...(mode === 'unary'
? [json(response('partial', 'CONTINUATION', 'checkpoint-1')), json(blocked)]
: [sse(response('partial', 'CONTINUATION', 'checkpoint-1')), sse(blocked)]));
const result = mode === 'unary'
? await client.models.generateContent(request)
: (await collect(client)).at(-1);
expect(result?.promptFeedback?.blockReason).toBe('SAFETY');
expect(result?.candidates?.[0]?.continuationToken).toBeUndefined();
expect(fetch).toHaveBeenCalledTimes(2);
});

it('retains grounding metadata on streamed continuation chunks', async () => {
const { client, fetch } = harness(
sse(response('first', 'CONTINUATION', 'checkpoint-1', grounding('first'))),
sse(response('second', 'STOP', undefined, grounding('second'))),
);
const chunks = await collect(client);
expect(chunks.map((chunk) => chunk.candidates?.[0]?.groundingMetadata))
.toEqual([grounding('first'), grounding('second')]);
expect(fetch).toHaveBeenCalledTimes(2);
});

it('does not resume an earlier checkpoint after a safety-blocked streaming chunk', async () => {
const { client, fetch } = harness(sse(
{ candidates: [{ content: { role: 'model', parts: [{ text: 'partial' }] }, continuationToken: 'checkpoint-1' }] },
{ promptFeedback: { blockReason: 'SAFETY' } },
));
const chunks = await collect(client);
expect(chunks.at(-1)?.promptFeedback?.blockReason).toBe('SAFETY');
expect(fetch).toHaveBeenCalledTimes(1);
});

it.each(['unary', 'stream'] as const)('surfaces a rejected %s continuation request without retrying it', async (mode) => {
const { client, fetch } = harness(
mode === 'unary' ? json(response('partial', 'CONTINUATION', 'checkpoint-1'))
: sse(response('partial', 'CONTINUATION', 'checkpoint-1')),
json({ error: { code: 403, message: 'PERMISSION_DENIED', status: 'PERMISSION_DENIED' } }, 403),
);
const result = mode === 'unary' ? client.models.generateContent(request) : collect(client);
await expect(result).rejects.toMatchObject({ name: 'ApiError', status: 403 });
expect(fetch).toHaveBeenCalledTimes(2);
});

it('preserves the transport error after bounded empty-hop retries', async () => {
const { client, fetch } = harness(
sse(response('partial', 'CONTINUATION', 'checkpoint-1')),
new TypeError('connection reset'), sse(), sse(), sse(),
);
await expect(collect(client)).rejects.toThrow('connection reset');
expect(fetch).toHaveBeenCalledTimes(5);
});

it('does not retry a caller abort', async () => {
const abort = new Error('caller canceled');
abort.name = 'AbortError';
const { client, fetch } = harness(sse(response('partial', 'CONTINUATION', 'checkpoint-1')), abort);
await expect(collect(client)).rejects.toThrow('caller canceled');
expect(fetch).toHaveBeenCalledTimes(2);
});

it.each(['gemini-3.8-flash', 'gemini-2.5-flash'])('serializes structured extraction parameters for %s', async (model) => {
const { client, fetch } = harness(json(response('{"summary":"evidence"}')));
await client.models.generateContent({
...request, model,
config: {
...geminiSampling(model, 0.3),
responseMimeType: 'application/json',
responseSchema: { type: Type.OBJECT, properties: { summary: { type: Type.STRING } }, required: ['summary'] },
},
});
const [url, init] = fetch.mock.calls[0];
const body = JSON.parse(init?.body as string);
expect(String(url)).toContain(`${model}:generateContent`);
expect(body.generationConfig.responseMimeType).toBe('application/json');
expect(body.generationConfig.responseSchema.required).toEqual(['summary']);
expect(body.generationConfig.temperature).toBe(model === 'gemini-2.5-flash' ? 0.3 : undefined);
});
});
Loading
Loading