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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ jobs:
node-version-file: .nvmrc
- run: node .yarn/releases/yarn-4.18.0.cjs install --immutable
- run: node .yarn/releases/yarn-4.18.0.cjs typecheck
- run: node .yarn/releases/yarn-4.18.0.cjs typecheck:e2e
- run: node .yarn/releases/yarn-4.18.0.cjs lint
- run: node --test --test-concurrency=1 scripts/baseline-report.test.mjs scripts/e2e/coverage-validator.test.mjs scripts/e2e/coverage-cli.test.mjs
- run: node .yarn/releases/yarn-4.18.0.cjs test --maxWorkers=2
- name: Build public demo
env:
Expand Down
6 changes: 0 additions & 6 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,14 @@ RUN node .yarn/releases/yarn-4.18.0.cjs install --immutable
COPY . .
RUN node .yarn/releases/yarn-4.18.0.cjs build

# Bundle static assets with nginx
FROM nginx:1.30.0-alpine@sha256:0272e4604ed93c1792f03695a033a6e8546840f86e0de20a884bb17d2c924883 as production
ARG BUILD_VERSION
LABEL org.opencontainers.image.revision=$BUILD_VERSION
ENV NODE_ENV production
# Copy built assets from builder
COPY --from=builder /app/build /usr/share/nginx/html
RUN test -n "$BUILD_VERSION" && printf '%s\n' "$BUILD_VERSION" > /usr/share/nginx/html/frontend-version
# Add your nginx.conf
COPY nginx.conf /etc/nginx/conf.d/default.template
COPY entrypoint.sh entrypoint.sh
# Expose port
EXPOSE 80
# Require a real HTTP version response matching the immutable image file, at the configured prefix.
HEALTHCHECK --interval=10s --timeout=4s --start-period=20s --retries=6 CMD test "$(wget -q -T 3 -O - "http://127.0.0.1${RESOURCE_PATH_PREFIX%/}/frontend-version")" = "$(cat /usr/share/nginx/html/frontend-version)" || exit 1
# Start nginx
CMD ["/bin/sh", "/entrypoint.sh"]
10 changes: 1 addition & 9 deletions Dockerfile.verify-basename
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
# Throwaway image for scripts/verify-container-basename.mjs (real-browser check against a
# running epoca-frontend container -- see verify_docker_image in .gitlab-ci.yml).
#
# Built via `docker build`, not `docker run -v`: this CI job's docker:dind service has its own
# filesystem, separate from the job container's, so a `-v "$(pwd):/work"` bind mount silently
# mounts an empty directory there (a known docker-in-docker limitation) -- `docker build` instead
# streams the build context over the API, which works regardless. Installing just the one
# `playwright` package here (not a full `yarn install`) is also lighter than mounting the whole
# workspace only to reach one dependency.
# Build the verifier image: Docker-in-Docker cannot bind-mount the job container filesystem.
FROM mcr.microsoft.com/playwright:v1.49.1-noble
WORKDIR /verify
COPY scripts/verify-container-basename.mjs .
Expand Down
10 changes: 2 additions & 8 deletions entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,14 @@ echo "#" "Interpolating environment variables"
echo "#"
echo

# Strip any trailing slash the operator may have set (e.g. "/teams/epoca/"), so downstream
# substitution always collapses to exactly one slash. A trailing slash on RESOURCE_PATH_PREFIX
# produces a literal `//` in nginx.conf's `location` block; nginx's `merge_slashes on` default
# then collapses `//` in every incoming request before matching, so that block can never match
# any request -- total site outage (every request 404s).
# Strip trailing slashes: nginx normalizes request paths, so a double-slash location would never match.
PUBLIC_URL="${PUBLIC_URL%/}"
RESOURCE_PATH_PREFIX="${RESOURCE_PATH_PREFIX%/}"

envsubst < /usr/share/nginx/html/assets/env.template.js > /usr/share/nginx/html/assets/env.js
envsubst '${APP_VERSION} ${RESOURCE_PATH_PREFIX}' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf

# Vite's `--base=/__PUBLIC_URL__/` build flag bakes the literal `/__PUBLIC_URL__/` token into
# every built file referencing a path -- index.html, .css (url(...)), and .js (chunk loading,
# asset URLs, and `import.meta.env.BASE_URL`). Rewrite it across all of them here.
# Rewrite the Vite base token in HTML, CSS and JS, including lazy chunk URLs.
find /usr/share/nginx/html -type f \( -name '*.html' -o -name '*.css' -o -name '*.js' \) \
-exec sed -i "s;/__PUBLIC_URL__/;${PUBLIC_URL}/;g" {} +

Expand Down
122 changes: 7 additions & 115 deletions eslint.config.js

Large diffs are not rendered by default.

4 changes: 1 addition & 3 deletions nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ server {
try_files $uri $uri/ ${RESOURCE_PATH_PREFIX}/index.html;
}

# index.html (also reached through the SPA fallback and the directory index) and the runtime
# env.js keep stable URLs across deployments, so browsers must revalidate them on every load.
# Content-hashed bundles under static/ stay cacheable.
# Revalidate stable HTML/env URLs on every load; hashed bundles remain cacheable.
location = ${RESOURCE_PATH_PREFIX}/index.html {
alias /usr/share/nginx/html/index.html;
include /etc/nginx/mime.types;
Expand Down
1 change: 0 additions & 1 deletion playwright.local-proxy.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const localBaseURL = 'http://127.0.0.1:5173';
const inertBaseURL = 'https://e2e.invalid';

const configureProxyTarget = (): void => {
// Also backs vite.config.ts's dev-server proxy target, so both stay in sync from one place.
const proxyTarget = process.env.EPOCA_LOCAL_PROXY_TARGET;
if (!proxyTarget?.trim()) {
throw new Error('EPOCA_LOCAL_PROXY_TARGET is required');
Expand Down
10 changes: 10 additions & 0 deletions scripts/baseline-report.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { z } from 'zod';

const baselineReportSchema = z.object({
numTotalTestSuites: z.number().int().positive(),
numTotalTests: z.number().int().positive(),
snapshot: z.object({ total: z.number().int().nonnegative() }),
});

/** @param {string} json */
export const parseBaselineReport = (json) => baselineReportSchema.parse(JSON.parse(json));
25 changes: 25 additions & 0 deletions scripts/baseline-report.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseBaselineReport } from './baseline-report.mjs';

const validReport = { numTotalTestSuites: 2, numTotalTests: 8, snapshot: { total: 0 } };

void test('accepts a real report with zero snapshots and ignores unrelated reporter fields', () => {
assert.deepEqual(parseBaselineReport(JSON.stringify({ ...validReport, success: true })), validReport);
});

void test('rejects malformed JSON and report fields before they reach baseline output', () => {
for (const value of [
null,
[],
{},
{ ...validReport, numTotalTests: '8' },
{ ...validReport, numTotalTestSuites: 0 },
{ ...validReport, numTotalTests: -1 },
{ ...validReport, numTotalTests: 1.5 },
{ ...validReport, snapshot: { total: -1 } },
]) {
assert.throws(() => parseBaselineReport(JSON.stringify(value)));
}
assert.throws(() => parseBaselineReport('{broken'));
});
35 changes: 8 additions & 27 deletions scripts/capture-baseline.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
// scripts/capture-baseline.mjs
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync, statSync, writeFileSync, mkdirSync } from 'node:fs';
import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { parseBaselineReport } from './baseline-report.mjs';

/** @param {string} command @param {string[]} args */
const run = (command, args) => execFileSync(command, args, { encoding: 'utf8' }).trim();

// Rethrows failures prefixed with the step name so the log makes clear which step broke.
/** @param {string} label @param {string} command @param {string[]} args */
const runStep = (label, command, args) => {
console.log(`Running ${label}...`);
try {
Expand All @@ -16,8 +17,10 @@ const runStep = (label, command, args) => {
}
};

/** @param {string} path */
const sha256File = (path) => createHash('sha256').update(readFileSync(path)).digest('hex');

/** @param {string} dir @returns {string[]} */
const walk = (dir) => {
const out = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
Expand All @@ -44,8 +47,6 @@ const lockfileSha = sha256File('yarn.lock');
const nodeVersion = process.version;
const yarnVersion = run('node', ['.yarn/releases/yarn-4.18.0.cjs', '--version']);

// Vitest's `json` reporter deliberately mirrors Jest's --json report shape, so this parses the
// same fields as before.
runStep('test suite', 'node', [
'.yarn/releases/yarn-4.18.0.cjs',
'vitest',
Expand All @@ -55,30 +56,14 @@ runStep('test suite', 'node', [
]);
let jestReport;
try {
jestReport = JSON.parse(readFileSync('target/baseline-jest-report.json', 'utf8'));
jestReport = parseBaselineReport(readFileSync('target/baseline-jest-report.json', 'utf8'));
} catch (error) {
throw new Error(`reading/parsing test report failed: ${error.message}`, { cause: error });
}
const jestSuiteCount = jestReport.numTotalTestSuites;
const jestTestCount = jestReport.numTotalTests;
const jestSnapshotCount = jestReport.snapshot?.total;

// A test run that collected nothing is exactly as wrong as one whose report is malformed, so
// fail loudly on a missing/non-integer field rather than writing `undefined` or a misleading 0
// into the accepted baseline.
for (const [fieldName, value] of [
['numTotalTestSuites', jestSuiteCount],
['numTotalTests', jestTestCount],
['snapshot.total', jestSnapshotCount],
]) {
if (!Number.isInteger(value) || (value === 0 && fieldName !== 'snapshot.total')) {
throw new Error(
`test report field "${fieldName}" is missing, not an integer, or zero (got ${JSON.stringify(value)}) — ` +
'the --json report shape may have changed or the test run produced no results.',
);
}
}

runStep('lint', 'node', ['.yarn/releases/yarn-4.18.0.cjs', 'lint', '-f', 'json', '-o', 'target/baseline-lint.json']);
const lintFindingsSha = sha256File('target/baseline-lint.json');

Expand All @@ -91,14 +76,10 @@ let buildFiles, bundleBytes, jsChunks, chunkManifestSha;
try {
buildFiles = walk('build');
bundleBytes = buildFiles.reduce((total, path) => total + statSync(path).size, 0);
// build/assets/env.template.js and other passthrough static files also end in .js but
// aren't real JS bundle chunks, so scope to the actual code-split output directory.
jsChunks = walk(join('build', 'static', 'js')).filter((path) => path.endsWith('.js'));

if (jsChunks.length === 0) {
throw new Error(
'No JS chunks found under build/static/js — build output looks incomplete or misconfigured',
);
throw new Error('No JS chunks found under build/static/js — build output looks incomplete or misconfigured');
}

const chunkManifest = jsChunks
Expand Down
28 changes: 23 additions & 5 deletions scripts/e2e/aggregate-list.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@ import { runAggregateE2E } from '../run-e2e-aggregate.mjs';

for (const tier of ['ci', 'all']) {
void test(`${tier} listing forwards --list to every child and marks discovery only`, () => {
/** @type {[string, string[], import("node:child_process").SpawnSyncOptions][]} */
const calls = [];
assert.equal(runAggregateE2E({ tier, listOnly: true, environment: {}, spawnImpl: (...args) => {
calls.push(args);
return { status: 0 };
} }), 0);
assert.equal(
runAggregateE2E({
tier,
listOnly: true,
environment: {},
spawnImpl: (executable, args, options) => {
calls.push([executable, args, options]);
return { status: 0 };
},
}),
0,
);
assert.equal(calls.length, 4);
for (const [, argv, options] of calls) {
assert.equal(argv.at(-1), '--list');
Expand All @@ -19,7 +28,16 @@ for (const tier of ['ci', 'all']) {

void test('aggregate stops on failure and preserves termination errors', () => {
let calls = 0;
assert.equal(runAggregateE2E({ tier: 'ci', spawnImpl: () => { calls += 1; return { status: 7 }; } }), 7);
assert.equal(
runAggregateE2E({
tier: 'ci',
spawnImpl: () => {
calls += 1;
return { status: 7 };
},
}),
7,
);
assert.equal(calls, 1);
assert.throws(() => runAggregateE2E({ tier: 'ci', spawnImpl: () => ({ signal: 'SIGTERM' }) }), /SIGTERM/);
assert.throws(() => runAggregateE2E({ tier: 'unknown', spawnImpl: () => assert.fail('must not spawn') }), /Unknown/);
Expand Down
42 changes: 17 additions & 25 deletions scripts/e2e/artifact-scanner-core.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createHash } from 'node:crypto';
import { constants } from 'node:fs';
import { access, cp, mkdir, mkdtemp, realpath, rename, rm, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import path from 'node:path';

/**
Expand Down Expand Up @@ -38,7 +38,6 @@ const knownPatterns = Object.freeze([
/(?:^|[^A-Za-z0-9])["']?(?:client[ _-]?secret|access[ _-]?token|refresh[ _-]?token|password|authorization)["']?\s*[:=]/im,
},
{ category: 'credential-prefix', pattern: /OAUTH_CLIENT[-_](?:SECRET|CREDENTIAL)[-_]SENTINEL/i },
// Retain the legacy signature to quarantine artifacts produced before the naming migration.
{ category: 'credential-prefix', pattern: /CT[-_]?521[-_](?:SECRET|CREDENTIAL)[-_]SENTINEL/i },
]);

Expand Down Expand Up @@ -67,10 +66,7 @@ const inspectBase64KnownCredential = (text) => {
const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), '=');
const padding = padded.endsWith('==') ? 2 : padded.endsWith('=') ? 1 : 0;
const decodedLength = Math.floor((padded.length * 3) / 4) - padding;
if (
decodedLength > MAX_DECODED_CANDIDATE_BYTES ||
decodedLength > MAX_TOTAL_DECODED_BYTES - decodedBytes
) {
if (decodedLength > MAX_DECODED_CANDIDATE_BYTES || decodedLength > MAX_TOTAL_DECODED_BYTES - decodedBytes) {
return 'scan-bound';
}
decodedBytes += decodedLength;
Expand Down Expand Up @@ -293,13 +289,20 @@ const adapterCategory = (error, fallback = 'snapshot-failure') =>
* @property {(info: TraversalHookInfo) => Promise<void> | void} [onBeforeDirectoryRead]
* @property {(info: TraversalHookInfo) => Promise<void> | void} [onFileOpened]
*
*/

/**
* @template {TraversalNode} [Node=TraversalNode]
* @typedef {object} TraversalAdapter
* @property {(source: string) => Promise<TraversalNode>} openRoot
* @property {(parent: TraversalNode, name: string) => Promise<TraversalNode> | TraversalNode} openChild
* @property {(node: TraversalNode) => AsyncIterable<string>} entries
* @property {(node: TraversalNode, expected: import('node:fs').Stats) => Promise<import('node:fs').Stats>} assertBound
* @property {(node: TraversalNode) => Promise<void>} close
* @property {(source: string) => Promise<Node>} openRoot
* @property {(parent: Node, name: string) => Promise<Node> | Node} openChild
* @property {(node: Node) => AsyncIterable<string>} entries
* @property {(node: Node, expected: import('node:fs').Stats) => Promise<import('node:fs').Stats>} assertBound
* @property {(node: Node) => Promise<void>} close
*
*/

/**
* @typedef {object} SnapshotEntry
* @property {string} sourceBasename
* @property {string} snapshotDirectory
Expand All @@ -322,15 +325,7 @@ const adapterCategory = (error, fallback = 'snapshot-failure') =>
* }} options
* @returns {Promise<SnapshotResult>}
*/
const snapshotSources = async ({
sources,
snapshotRoot,
limits,
needles,
findings,
traversalHooks,
adapter,
}) => {
const snapshotSources = async ({ sources, snapshotRoot, limits, needles, findings, traversalHooks, adapter }) => {
/** @type {SnapshotEntry[]} */
const snapshots = [];
/** @type {Map<string, string>} */
Expand Down Expand Up @@ -443,10 +438,7 @@ const snapshotSources = async ({
}
await traversalHooks?.onFileOpened?.({ sourceIndex, relativePath: relative });
const preReadStatus = await node.handle.stat();
if (
preReadStatus.size > limits.maxFileBytes ||
preReadStatus.size > limits.maxTotalBytes - counters.bytes
) {
if (preReadStatus.size > limits.maxFileBytes || preReadStatus.size > limits.maxTotalBytes - counters.bytes) {
findings.push({ category: 'scan-bound', location });
return;
}
Expand Down Expand Up @@ -517,7 +509,7 @@ export const runArtifactScan = async (
onSnapshotReady,
traversalHooks,
},
createAdapter
createAdapter,
) => {
if (!Array.isArray(sources) || sources.length === 0) throw new Error('At least one artifact source is required');
if (!safeDirectory || !quarantineDirectory) throw new Error('Safe and quarantine directories are required');
Expand Down
Loading
Loading