Compare commits

..
Author SHA1 Message Date
suyx eed125c118 fix: build WP5-04 workspace API dependencies
Dada P0-A isolated Windows CI / validate-and-package (push) Successful in 9m15s
2026-08-04 00:42:31 +08:00
suyx f1bebab611 feat: isolate asset release access classes (TASK-WP5-04)
Dada P0-A isolated Windows CI / validate-and-package (push) Failing after 59s
2026-08-03 19:02:04 +08:00
23 changed files with 903 additions and 1258 deletions
+1
View File
@@ -9,6 +9,7 @@
"typecheck": "tsc --noEmit -p tsconfig.json" "typecheck": "tsc --noEmit -p tsconfig.json"
}, },
"dependencies": { "dependencies": {
"@dada/asset-release-manifest": "workspace:*",
"@dada/shared-contracts": "workspace:*", "@dada/shared-contracts": "workspace:*",
"@fastify/multipart": "10.1.0", "@fastify/multipart": "10.1.0",
"@fastify/swagger": "9.8.1", "@fastify/swagger": "9.8.1",
+133 -1
View File
@@ -134,6 +134,7 @@ import {
type RegistrationCompleteRequest, type RegistrationCompleteRequest,
type RegistrationSendRequest, type RegistrationSendRequest,
} from "@dada/shared-contracts"; } from "@dada/shared-contracts";
import type { AssetReleaseReader } from "@dada/asset-release-manifest";
import swagger from "@fastify/swagger"; import swagger from "@fastify/swagger";
import multipart from "@fastify/multipart"; import multipart from "@fastify/multipart";
import Fastify, { type FastifyReply } from "fastify"; import Fastify, { type FastifyReply } from "fastify";
@@ -192,6 +193,7 @@ const defaultBootstrap: BootstrapResponse = {
export interface CreateAppOptions { export interface CreateAppOptions {
amap?: AmapAdapter; amap?: AmapAdapter;
assetReleases?: AssetReleaseReader;
bootstrap?: () => BootstrapResponse | Promise<BootstrapResponse>; bootstrap?: () => BootstrapResponse | Promise<BootstrapResponse>;
browserGate?: boolean; browserGate?: boolean;
browserSupportRelease?: BrowserSupportRelease; browserSupportRelease?: BrowserSupportRelease;
@@ -205,6 +207,17 @@ export interface CreateAppOptions {
publicAssets?: PublicAssetResolver; publicAssets?: PublicAssetResolver;
recentAssets?: RecentAssetService; recentAssets?: RecentAssetService;
projects?: ProjectService; projects?: ProjectService;
previewAssetAuthorizer?: (input: {
releaseVersion: string;
resourceId: string;
userId: string;
}) => boolean | Promise<boolean>;
privateAssetAdminAuthorizer?: (input: {
adminUserId: string;
ownerId: string;
releaseVersion: string;
resourceId: string;
}) => boolean | Promise<boolean>;
registration?: RegistrationService; registration?: RegistrationService;
} }
@@ -816,13 +829,27 @@ export async function createApp(options: CreateAppOptions = {}) {
status: "ready", status: "ready",
})); }));
app.get(
"/api/v1/assets/public/:resourceVersion/manifest",
{ schema: { hide: true } },
async (request, reply) => {
const { resourceVersion } = request.params as { resourceVersion: string };
const manifest = options.assetReleases?.project("public_release_asset", resourceVersion);
if (!manifest) return reply.code(404).send();
reply.header("Cache-Control", "public, max-age=31536000, immutable");
reply.header("ETag", `"sha256-${manifest.manifest_sha256}"`);
return manifest;
},
);
app.get( app.get(
"/api/v1/assets/public/:resourceVersion/:assetId", "/api/v1/assets/public/:resourceVersion/:assetId",
{ schema: { hide: true } }, { schema: { hide: true } },
async (request, reply) => { async (request, reply) => {
const { assetId, resourceVersion } = request.params as { assetId?: string; resourceVersion?: string }; const { assetId, resourceVersion } = request.params as { assetId?: string; resourceVersion?: string };
const resource = assetId && resourceVersion const resource = assetId && resourceVersion
? options.publicAssets?.read(resourceVersion, assetId) ? options.assetReleases?.read("public_release_asset", resourceVersion, assetId)
?? options.publicAssets?.read(resourceVersion, assetId)
: undefined; : undefined;
if (!resource) return reply.code(404).send(); if (!resource) return reply.code(404).send();
reply.type(resource.mimeType); reply.type(resource.mimeType);
@@ -833,6 +860,111 @@ export async function createApp(options: CreateAppOptions = {}) {
}, },
); );
app.get(
"/api/v1/assets/preview/:resourceVersion/manifest",
{ schema: { hide: true } },
async (request, reply) => {
if (!options.registration) {
return reply.code(503).send(createErrorEnvelope({ code: "AUTH_SERVICE_UNAVAILABLE", correlationId: request.id }));
}
const token = cookieValue(headerValue(request.headers.cookie), userSessionCookieName);
const session = token ? options.registration.readUserSession(token) : undefined;
if (!session) return reply.code(401).send(createErrorEnvelope({ code: "AUTH_SESSION_INVALID", correlationId: request.id }));
const { resourceVersion } = request.params as { resourceVersion: string };
const available = options.assetReleases?.project("internal_preview_asset", resourceVersion);
if (!available || !options.previewAssetAuthorizer) return reply.code(404).send();
const authorizedIds: string[] = [];
for (const item of available.items) {
if (await options.previewAssetAuthorizer({
releaseVersion: resourceVersion,
resourceId: item.resource_id,
userId: session.userId,
})) authorizedIds.push(item.resource_id);
}
if (authorizedIds.length === 0) return reply.code(404).send();
const manifest = options.assetReleases?.project("internal_preview_asset", resourceVersion, { resourceIds: authorizedIds });
if (!manifest) return reply.code(404).send();
reply.header("Cache-Control", "private, no-store");
reply.header("Vary", "Cookie");
return manifest;
},
);
app.get(
"/api/v1/assets/preview/:resourceVersion/:assetId",
{ schema: { hide: true } },
async (request, reply) => {
if (!options.registration) {
return reply.code(503).send(createErrorEnvelope({ code: "AUTH_SERVICE_UNAVAILABLE", correlationId: request.id }));
}
const token = cookieValue(headerValue(request.headers.cookie), userSessionCookieName);
const session = token ? options.registration.readUserSession(token) : undefined;
if (!session) return reply.code(401).send(createErrorEnvelope({ code: "AUTH_SESSION_INVALID", correlationId: request.id }));
const { assetId, resourceVersion } = request.params as { assetId: string; resourceVersion: string };
const authorized = await options.previewAssetAuthorizer?.({ resourceId: assetId, releaseVersion: resourceVersion, userId: session.userId });
const resource = authorized ? options.assetReleases?.read("internal_preview_asset", resourceVersion, assetId) : undefined;
if (!resource) return reply.code(404).send();
reply.type(resource.mimeType);
reply.header("Cache-Control", "private, no-store");
reply.header("Content-Disposition", "inline");
reply.header("Vary", "Cookie");
return resource.bytes;
},
);
app.get(
"/api/v1/private-assets/:resourceVersion/manifest",
{ schema: { hide: true } },
async (request, reply) => {
if (!options.registration) {
return reply.code(503).send(createErrorEnvelope({ code: "AUTH_SERVICE_UNAVAILABLE", correlationId: request.id }));
}
const token = cookieValue(headerValue(request.headers.cookie), userSessionCookieName);
const session = token ? options.registration.readUserSession(token) : undefined;
if (!session) return reply.code(401).send(createErrorEnvelope({ code: "AUTH_SESSION_INVALID", correlationId: request.id }));
const { resourceVersion } = request.params as { resourceVersion: string };
const manifest = options.assetReleases?.project("private_user_asset", resourceVersion, { ownerId: session.userId });
if (!manifest) return reply.code(404).send();
reply.header("Cache-Control", "private, no-store");
reply.header("Vary", "Cookie");
return manifest;
},
);
app.get(
"/api/v1/private-assets/:resourceVersion/:assetId",
{ schema: { hide: true } },
async (request, reply) => {
if (!options.registration) {
return reply.code(503).send(createErrorEnvelope({ code: "AUTH_SERVICE_UNAVAILABLE", correlationId: request.id }));
}
const userToken = cookieValue(headerValue(request.headers.cookie), userSessionCookieName);
const userSession = userToken ? options.registration.readUserSession(userToken) : undefined;
const adminToken = cookieValue(headerValue(request.headers.cookie), adminSessionCookieName);
const adminSession = adminToken ? options.registration.readAdminSession(adminToken) : undefined;
if (!userSession && !adminSession) {
return reply.code(401).send(createErrorEnvelope({ code: "AUTH_SESSION_INVALID", correlationId: request.id }));
}
const { assetId, resourceVersion } = request.params as { assetId: string; resourceVersion: string };
const resource = options.assetReleases?.read("private_user_asset", resourceVersion, assetId);
if (!resource?.ownerId) return reply.code(404).send();
const controlledAdmin = adminSession
? await options.privateAssetAdminAuthorizer?.({
adminUserId: adminSession.user_id,
ownerId: resource.ownerId,
releaseVersion: resource.releaseVersion,
resourceId: resource.resourceId,
})
: false;
if (userSession?.userId !== resource.ownerId && !controlledAdmin) return reply.code(404).send();
reply.type(resource.mimeType);
reply.header("Cache-Control", "private, no-store");
reply.header("Content-Disposition", "inline");
reply.header("Vary", "Cookie");
return resource.bytes;
},
);
app.get( app.get(
"/api/v1/assets/recent", "/api/v1/assets/recent",
{ {
+6 -6
View File
@@ -14,9 +14,9 @@
"test:integration": "vitest run tests/integration", "test:integration": "vitest run tests/integration",
"test:api": "pnpm check:openapi && vitest run tests/api", "test:api": "pnpm check:openapi && vitest run tests/api",
"test:worker": "pnpm --filter @dada/worker build && node scripts/worker-smoke.mjs && vitest run tests/worker", "test:worker": "pnpm --filter @dada/worker build && node scripts/worker-smoke.mjs && vitest run tests/worker",
"test:e2e": "pnpm check:openapi && playwright test tests/e2e/event-sync.spec.ts tests/e2e/support-gate.spec.ts tests/e2e/local-data-boundary.spec.ts tests/e2e/storage-capacity.spec.ts tests/e2e/public-asset-cache.spec.ts tests/e2e/user-auth.spec.ts tests/e2e/admin-auth.spec.ts tests/e2e/entry-state-ui.spec.ts tests/e2e/session-invalid-ui.spec.ts tests/e2e/user-registration.spec.ts tests/e2e/account-settings.spec.ts tests/e2e/projects-workspace.spec.ts tests/e2e/project-autosave-conflict.spec.ts tests/e2e/project-trash.spec.ts tests/e2e/credits.spec.ts tests/e2e/generation-workspace.spec.ts tests/e2e/generation-terminal-actions.spec.ts tests/e2e/project-latest-exports.spec.ts tests/e2e/admin-models.spec.ts tests/e2e/wp4-01-editor-background.spec.ts tests/e2e/wp4-02-editor-elements.spec.ts tests/e2e/wp4-03-text-editor.spec.ts tests/e2e/wp4-04-color-dynamic.spec.ts tests/e2e/wp4-05-export.spec.ts tests/e2e/wp4-06-accessibility.spec.ts tests/e2e/wp5-02-static-sticker-catalog.spec.ts tests/e2e/wp5-03-template-registry.spec.ts --config playwright.config.ts", "test:e2e": "pnpm check:openapi && playwright test tests/e2e/event-sync.spec.ts tests/e2e/support-gate.spec.ts tests/e2e/local-data-boundary.spec.ts tests/e2e/storage-capacity.spec.ts tests/e2e/public-asset-cache.spec.ts tests/e2e/user-auth.spec.ts tests/e2e/admin-auth.spec.ts tests/e2e/entry-state-ui.spec.ts tests/e2e/session-invalid-ui.spec.ts tests/e2e/user-registration.spec.ts tests/e2e/account-settings.spec.ts tests/e2e/projects-workspace.spec.ts tests/e2e/project-autosave-conflict.spec.ts tests/e2e/project-trash.spec.ts tests/e2e/credits.spec.ts tests/e2e/generation-workspace.spec.ts tests/e2e/generation-terminal-actions.spec.ts tests/e2e/project-latest-exports.spec.ts tests/e2e/admin-models.spec.ts tests/e2e/wp4-01-editor-background.spec.ts tests/e2e/wp4-02-editor-elements.spec.ts tests/e2e/wp4-03-text-editor.spec.ts tests/e2e/wp4-04-color-dynamic.spec.ts tests/e2e/wp4-05-export.spec.ts tests/e2e/wp4-06-accessibility.spec.ts tests/e2e/wp5-02-static-sticker-catalog.spec.ts tests/e2e/wp5-03-template-registry.spec.ts tests/e2e/wp5-04-resource-isolation.spec.ts --config playwright.config.ts",
"test:visual": "node scripts/run-wp4-07-layer.mjs visual", "test:visual": "node scripts/validate-layer-scope.mjs VISUAL",
"test:performance": "node scripts/run-wp4-07-layer.mjs performance", "test:performance": "node scripts/validate-layer-scope.mjs PERFORMANCE",
"test:security": "node scripts/verify-frozen-dependencies.mjs && node scripts/redaction-scan.mjs", "test:security": "node scripts/verify-frozen-dependencies.mjs && node scripts/redaction-scan.mjs",
"test:package": "pnpm run typecheck && node --test tests/package/wp0-09-portable.test.mjs && node scripts/package-smoke.mjs && node scripts/loopback-boundary-smoke.mjs", "test:package": "pnpm run typecheck && node --test tests/package/wp0-09-portable.test.mjs && node scripts/package-smoke.mjs && node scripts/loopback-boundary-smoke.mjs",
"package:portable": "node scripts/build-portable.mjs", "package:portable": "node scripts/build-portable.mjs",
@@ -86,15 +86,15 @@
"test:wp4-05:red": "node scripts/run-wp4-05-validation.mjs --phase red", "test:wp4-05:red": "node scripts/run-wp4-05-validation.mjs --phase red",
"test:wp4-06": "node scripts/run-wp4-06-validation.mjs", "test:wp4-06": "node scripts/run-wp4-06-validation.mjs",
"test:wp4-06:red": "node scripts/run-wp4-06-validation.mjs --phase red", "test:wp4-06:red": "node scripts/run-wp4-06-validation.mjs --phase red",
"test:wp4-07": "node scripts/run-wp4-07-validation.mjs",
"test:wp4-07:red": "node scripts/run-wp4-07-validation.mjs --phase red",
"test:wp5-01": "node scripts/run-wp5-01-validation.mjs", "test:wp5-01": "node scripts/run-wp5-01-validation.mjs",
"test:wp5-01:red": "node scripts/run-wp5-01-validation.mjs --phase red", "test:wp5-01:red": "node scripts/run-wp5-01-validation.mjs --phase red",
"test:wp5-02": "node scripts/run-wp5-02-validation.mjs", "test:wp5-02": "node scripts/run-wp5-02-validation.mjs",
"test:wp5-02:red": "node scripts/run-wp5-02-validation.mjs --phase red", "test:wp5-02:red": "node scripts/run-wp5-02-validation.mjs --phase red",
"preview:wp5-02": "node scripts/run-wp5-02-manual-preview.mjs", "preview:wp5-02": "node scripts/run-wp5-02-manual-preview.mjs",
"test:wp5-03": "node scripts/run-wp5-03-validation.mjs", "test:wp5-03": "node scripts/run-wp5-03-validation.mjs",
"test:wp5-03:red": "node scripts/run-wp5-03-validation.mjs --phase red" "test:wp5-03:red": "node scripts/run-wp5-03-validation.mjs --phase red",
"test:wp5-04": "node scripts/run-wp5-04-validation.mjs",
"test:wp5-04:red": "node scripts/run-wp5-04-validation.mjs --phase red"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "1.62.0", "@playwright/test": "1.62.0",
@@ -0,0 +1,18 @@
{
"name": "@dada/asset-release-manifest",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
".": "./dist/index.js"
},
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"devDependencies": {
"@types/node": "24.13.3",
"typescript": "7.0.2"
}
}
@@ -0,0 +1,180 @@
import { createHash } from "node:crypto";
import { posix, win32 } from "node:path";
export const ASSET_ACCESS_CLASSES = [
"public_release_asset",
"internal_preview_asset",
"private_user_asset",
] as const;
export type AssetAccessClass = typeof ASSET_ACCESS_CLASSES[number];
export type PublicAssetCacheKind = "font" | "template_conversion" | "thumbnail";
export interface AssetReleaseItemInput {
access_class: AssetAccessClass;
cache_kind?: PublicAssetCacheKind;
content: Uint8Array;
mime_type: string;
owner_id?: string;
relative_path: string;
resource_id: string;
root_ref: string;
sha256?: string;
}
export interface AssetReleaseManifestInput {
items: readonly AssetReleaseItemInput[];
release_version: string;
}
export interface AssetReleaseManifestItem {
access_class: AssetAccessClass;
byte_size: number;
cache_kind?: PublicAssetCacheKind;
mime_type: string;
release_version: string;
resource_id: string;
sha256: string;
url: string;
}
export interface AssetReleaseManifestProjection {
items: readonly AssetReleaseManifestItem[];
manifest_sha256: string;
release_version: string;
schema_version: "AssetReleaseManifest/v1";
}
export interface AssetReleasePayload {
accessClass: AssetAccessClass;
bytes: Buffer;
mimeType: string;
ownerId?: string;
releaseVersion: string;
resourceId: string;
sha256: string;
}
export interface AssetReleaseReader {
project(
accessClass: AssetAccessClass,
releaseVersion: string,
options?: { ownerId?: string; resourceIds?: readonly string[] },
): AssetReleaseManifestProjection | undefined;
read(accessClass: AssetAccessClass, releaseVersion: string, resourceId: string): AssetReleasePayload | undefined;
}
interface StoredItem {
accessClass: AssetAccessClass;
bytes: Buffer;
cacheKind?: PublicAssetCacheKind;
mimeType: string;
ownerId?: string;
projection: AssetReleaseManifestItem;
relativePath: string;
rootRef: string;
sha256: string;
}
const releaseVersionPattern = /^[a-z0-9][a-z0-9._-]{0,79}$/i;
const resourceIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const sha256Pattern = /^[0-9a-f]{64}$/;
const rootRefPattern = /^[a-z0-9][a-z0-9._-]{0,79}$/i;
function assetUrl(accessClass: AssetAccessClass, releaseVersion: string, resourceId: string) {
if (accessClass === "public_release_asset") return `/api/v1/assets/public/${releaseVersion}/${resourceId}`;
if (accessClass === "internal_preview_asset") return `/api/v1/assets/preview/${releaseVersion}/${resourceId}`;
return `/api/v1/private-assets/${releaseVersion}/${resourceId}`;
}
function isSafeRelativePath(value: string) {
if (!value || value.includes("\\") || posix.isAbsolute(value) || win32.isAbsolute(value)) return false;
const segments = value.split("/");
return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
}
function sha256(value: string | Uint8Array) {
return createHash("sha256").update(value).digest("hex");
}
function immutableProjection(input: Omit<AssetReleaseManifestProjection, "manifest_sha256">): AssetReleaseManifestProjection {
const items = input.items.map((item) => Object.freeze({ ...item }));
const manifestBody = JSON.stringify({ ...input, items });
return Object.freeze({ ...input, items: Object.freeze(items), manifest_sha256: sha256(manifestBody) });
}
function validateItem(item: AssetReleaseItemInput, releaseVersion: string, seenIds: Set<string>): StoredItem {
if (!ASSET_ACCESS_CLASSES.includes(item.access_class)) throw new Error("asset access class is unsupported");
if (!resourceIdPattern.test(item.resource_id) || seenIds.has(item.resource_id)) throw new Error("resource_id must be a unique opaque UUID");
seenIds.add(item.resource_id);
if (!rootRefPattern.test(item.root_ref)) throw new Error("root_ref is invalid");
if (!isSafeRelativePath(item.relative_path)) throw new Error("relative path must stay within its declared root");
if (!/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(item.mime_type)) throw new Error("mime_type is invalid");
if (item.access_class === "public_release_asset" && !item.cache_kind) throw new Error("public release asset requires an allowlisted cache kind");
if (item.access_class !== "public_release_asset" && item.cache_kind) throw new Error("non-public assets cannot declare a public cache kind");
if (item.access_class === "private_user_asset" && !item.owner_id) throw new Error("private user asset requires owner_id");
if (item.access_class !== "private_user_asset" && item.owner_id) throw new Error("only private user assets can declare owner_id");
const bytes = Buffer.from(item.content);
const digest = sha256(bytes);
if (item.sha256 !== undefined && (!sha256Pattern.test(item.sha256) || item.sha256 !== digest)) {
throw new Error("file SHA-256 does not match content");
}
const projection: AssetReleaseManifestItem = {
access_class: item.access_class,
byte_size: bytes.byteLength,
...(item.cache_kind ? { cache_kind: item.cache_kind } : {}),
mime_type: item.mime_type,
release_version: releaseVersion,
resource_id: item.resource_id,
sha256: digest,
url: assetUrl(item.access_class, releaseVersion, item.resource_id),
};
return {
accessClass: item.access_class,
bytes,
...(item.cache_kind ? { cacheKind: item.cache_kind } : {}),
mimeType: item.mime_type,
...(item.owner_id ? { ownerId: item.owner_id } : {}),
projection: Object.freeze(projection),
relativePath: item.relative_path,
rootRef: item.root_ref,
sha256: digest,
};
}
export function createAssetReleaseManifest(input: AssetReleaseManifestInput): AssetReleaseReader {
if (!releaseVersionPattern.test(input.release_version)) throw new Error("release_version is invalid");
const seenIds = new Set<string>();
const items = input.items
.map((item) => validateItem(item, input.release_version, seenIds))
.sort((left, right) => left.projection.resource_id.localeCompare(right.projection.resource_id));
return Object.freeze({
project(accessClass: AssetAccessClass, releaseVersion: string, options: { ownerId?: string; resourceIds?: readonly string[] } = {}) {
if (releaseVersion !== input.release_version) return undefined;
const selected = items.filter((item) => item.accessClass === accessClass
&& (accessClass !== "private_user_asset" || Boolean(options.ownerId) && item.ownerId === options.ownerId)
&& (!options.resourceIds || options.resourceIds.includes(item.projection.resource_id)));
return immutableProjection({
items: selected.map((item) => item.projection),
release_version: input.release_version,
schema_version: "AssetReleaseManifest/v1",
});
},
read(accessClass: AssetAccessClass, releaseVersion: string, resourceId: string) {
if (releaseVersion !== input.release_version) return undefined;
const item = items.find((candidate) => candidate.accessClass === accessClass && candidate.projection.resource_id === resourceId);
if (!item) return undefined;
return {
accessClass: item.accessClass,
bytes: Buffer.from(item.bytes),
mimeType: item.mimeType,
...(item.ownerId ? { ownerId: item.ownerId } : {}),
releaseVersion,
resourceId,
sha256: item.sha256,
};
},
});
}
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2024"],
"types": ["node"],
"declaration": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}
-26
View File
@@ -1,26 +0,0 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
forbidOnly: true,
fullyParallel: false,
outputDir: process.env.DADA_PLAYWRIGHT_OUTPUT_DIR ?? "test-results/wp4-07",
projects: [
{ name: "chrome", use: { channel: "chrome" } },
{ name: "edge", use: { channel: "msedge" } },
],
reporter: "line",
retries: 0,
testDir: "./tests/e2e",
testMatch: "wp4-07-visual-performance.spec.ts",
timeout: 360_000,
use: {
deviceScaleFactor: 1,
headless: true,
launchOptions: { args: ["--enable-precise-memory-info", "--force-device-scale-factor=1"] },
locale: "zh-CN",
timezoneId: "Asia/Shanghai",
trace: "on",
viewport: { height: 1080, width: 1920 },
},
workers: 1,
});
+12
View File
@@ -38,6 +38,9 @@ importers:
apps/api: apps/api:
dependencies: dependencies:
'@dada/asset-release-manifest':
specifier: workspace:*
version: link:../../packages/asset-release-manifest
'@dada/shared-contracts': '@dada/shared-contracts':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/shared-contracts version: link:../../packages/shared-contracts
@@ -151,6 +154,15 @@ importers:
specifier: 7.0.2 specifier: 7.0.2
version: 7.0.2 version: 7.0.2
packages/asset-release-manifest:
devDependencies:
'@types/node':
specifier: 24.13.3
version: 24.13.3
typescript:
specifier: 7.0.2
version: 7.0.2
packages/asset-renderer: packages/asset-renderer:
dependencies: dependencies:
'@dada/template-registry': '@dada/template-registry':
-80
View File
@@ -1,80 +0,0 @@
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { WP4_07_PERFORMANCE_BUDGETS } from "../tests/visual-performance/wp4-07-fixture.mjs";
const evidenceIndex = process.argv.indexOf("--evidence");
const phaseIndex = process.argv.indexOf("--phase");
const evidenceDirectory = resolve(evidenceIndex >= 0 ? process.argv[evidenceIndex + 1] : "");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
if (evidenceIndex < 0 || !process.argv[evidenceIndex + 1] || !["green", "red"].includes(phase)) throw new Error("Usage: --evidence <directory> [--phase red|green]");
function read(browser, filename) {
const path = resolve(evidenceDirectory, browser, filename);
if (!existsSync(path)) throw new Error(`missing ${browser}/${filename}`);
return JSON.parse(readFileSync(path, "utf8"));
}
const browserResults = {};
let greenInputsEligible = true;
for (const browser of ["chrome", "edge"]) {
const raw = read(browser, "performance-raw.json");
const memory = read(browser, "memory.json");
const dom = read(browser, "dom-count.json");
const environment = read(browser, "environment.json");
greenInputsEligible = greenInputsEligible && raw.eligible_for_green === true && raw.harness_mode === "real";
if (raw.interaction.length !== 5 || raw.autosave_serialization.length !== 5 || raw.export_1080x1920.length !== 5 || raw.editor_reopen.samples_ms.length !== 5) {
throw new Error(`${browser} did not retain exactly five measured samples per budget`);
}
if (raw.interaction.some((run) => run.duration_ms < WP4_07_PERFORMANCE_BUDGETS.interaction_duration_ms)) {
throw new Error(`${browser} shortened a ten-second interaction measurement`);
}
const checks = {
autosave_serialization: raw.autosave_serialization.every((run) => run.p95_ms <= WP4_07_PERFORMANCE_BUDGETS.autosave_serialization_p95_ms_max),
canvas_frame: raw.interaction.every((run) => run.frame_p95_ms <= WP4_07_PERFORMANCE_BUDGETS.canvas_frame_p95_ms_max),
continuous_unresponsive: raw.interaction.every((run) => run.frame_max_ms < WP4_07_PERFORMANCE_BUDGETS.continuous_unresponsive_ms_max_exclusive),
dom_bounded: dom.bounded_by_viewport_and_two_screens === true && dom.top_count < dom.catalog_count && dom.bottom_count < dom.catalog_count,
editor_reopen: raw.editor_reopen.max_ms <= WP4_07_PERFORMANCE_BUDGETS.editor_reopen_ms_max,
export_duration: raw.export_1080x1920.every((run) => run.duration_ms <= WP4_07_PERFORMANCE_BUDGETS.export_1080x1920_ms_max),
export_failure_isolated: raw.export_failure.observed_error === "export_asset_unavailable"
&& JSON.stringify(raw.export_failure.saves_before) === JSON.stringify(raw.export_failure.saves_after),
export_memory: memory.export_peak_additional_bytes.every((value) => value <= WP4_07_PERFORMANCE_BUDGETS.export_peak_additional_bytes_max),
long_task: raw.interaction.every((run) => run.long_task_max_ms <= WP4_07_PERFORMANCE_BUDGETS.long_task_ms_max),
pointer_to_frame: raw.interaction.every((run) => run.pointer_to_frame_p95_ms <= WP4_07_PERFORMANCE_BUDGETS.pointer_to_frame_p95_ms_max),
};
browserResults[browser] = {
checks,
environment,
fixture_sha256: raw.fixture_sha256,
metrics: {
autosave_serialization: raw.autosave_serialization,
editor_reopen: raw.editor_reopen,
export_1080x1920: raw.export_1080x1920,
interaction: raw.interaction,
},
status: Object.values(checks).every(Boolean) ? "within_budget" : "budget_exceeded",
};
}
const passed = Object.values(browserResults).every((result) => result.status === "within_budget");
const report = {
browsers: browserResults,
eligible_for_green: phase === "green" && greenInputsEligible,
normative_budgets: WP4_07_PERFORMANCE_BUDGETS,
phase,
status: passed ? "within_budget" : "budget_exceeded",
};
writeFileSync(resolve(evidenceDirectory, "performance.json"), `${JSON.stringify(report, null, 2)}\n`);
writeFileSync(resolve(evidenceDirectory, "memory.json"), `${JSON.stringify({
browsers: Object.fromEntries(["chrome", "edge"].map((browser) => [browser, read(browser, "memory.json")])),
limit_bytes: WP4_07_PERFORMANCE_BUDGETS.export_peak_additional_bytes_max,
}, null, 2)}\n`);
writeFileSync(resolve(evidenceDirectory, "dom-count.json"), `${JSON.stringify({
browsers: Object.fromEntries(["chrome", "edge"].map((browser) => [browser, read(browser, "dom-count.json")])),
required_catalog_count: 1_407,
}, null, 2)}\n`);
writeFileSync(resolve(evidenceDirectory, "environment.json"), `${JSON.stringify({
browsers: Object.fromEntries(["chrome", "edge"].map((browser) => [browser, read(browser, "environment.json")])),
fixture_hashes_match: browserResults.chrome.fixture_sha256 === browserResults.edge.fixture_sha256,
}, null, 2)}\n`);
console.log(JSON.stringify({ browser_statuses: Object.fromEntries(Object.entries(browserResults).map(([name, result]) => [name, result.status])), phase, status: report.status }, null, 2));
if (phase === "green" && (!greenInputsEligible || !passed)) process.exit(1);
-106
View File
@@ -1,106 +0,0 @@
import { chromium } from "@playwright/test";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { WP4_07_VISUAL_THRESHOLDS } from "../tests/visual-performance/wp4-07-fixture.mjs";
const evidenceIndex = process.argv.indexOf("--evidence");
const phaseIndex = process.argv.indexOf("--phase");
const evidenceDirectory = resolve(evidenceIndex >= 0 ? process.argv[evidenceIndex + 1] : "");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
if (evidenceIndex < 0 || !process.argv[evidenceIndex + 1] || !["green", "red"].includes(phase)) throw new Error("Usage: --evidence <directory> [--phase red|green]");
const scenarios = ["editor.png", "canvas.png", "export-dialog.png"];
for (const scenario of scenarios) {
for (const browser of ["chrome", "edge"]) {
const path = resolve(evidenceDirectory, browser, scenario);
if (!existsSync(path)) throw new Error(`missing screenshot: ${browser}/${scenario}`);
}
}
const browser = await chromium.launch({ channel: "msedge", headless: true });
const page = await browser.newPage();
const results = [];
try {
for (const scenario of scenarios) {
const chrome = readFileSync(resolve(evidenceDirectory, "chrome", scenario)).toString("base64");
const edge = readFileSync(resolve(evidenceDirectory, "edge", scenario)).toString("base64");
const comparison = await page.evaluate(async ({ chromeBase64, edgeBase64, threshold }) => {
const decode = async (base64) => {
const binary = atob(base64);
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
return createImageBitmap(new Blob([bytes], { type: "image/png" }));
};
const [chromeImage, edgeImage] = await Promise.all([decode(chromeBase64), decode(edgeBase64)]);
if (chromeImage.width !== edgeImage.width || chromeImage.height !== edgeImage.height) {
return { dimensions_match: false, chrome: { height: chromeImage.height, width: chromeImage.width }, edge: { height: edgeImage.height, width: edgeImage.width } };
}
const surface = new OffscreenCanvas(chromeImage.width, chromeImage.height);
const context = surface.getContext("2d", { willReadFrequently: true });
context.drawImage(chromeImage, 0, 0);
const chromePixels = context.getImageData(0, 0, chromeImage.width, chromeImage.height).data;
context.clearRect(0, 0, chromeImage.width, chromeImage.height);
context.drawImage(edgeImage, 0, 0);
const edgePixels = context.getImageData(0, 0, edgeImage.width, edgeImage.height).data;
let significant = 0;
let maximumChannelDelta = 0;
for (let index = 0; index < chromePixels.length; index += 4) {
const deltas = [0, 1, 2, 3].map((channel) => Math.abs(chromePixels[index + channel] - edgePixels[index + channel]));
maximumChannelDelta = Math.max(maximumChannelDelta, ...deltas);
if (deltas.some((delta) => delta > threshold)) significant += 1;
}
const total = chromeImage.width * chromeImage.height;
chromeImage.close();
edgeImage.close();
return {
dimensions_match: true,
height: surface.height,
maximum_channel_delta: maximumChannelDelta,
significant_pixel_count: significant,
significant_pixel_ratio: significant / total,
significant_pixel_threshold: threshold,
total_pixels: total,
width: surface.width,
};
}, { chromeBase64: chrome, edgeBase64: edge, threshold: WP4_07_VISUAL_THRESHOLDS.channel_delta_significant });
results.push({ scenario, ...comparison });
}
} finally {
await browser.close();
}
const chromeLayout = JSON.parse(readFileSync(resolve(evidenceDirectory, "chrome", "layout-boxes.json"), "utf8"));
const edgeLayout = JSON.parse(readFileSync(resolve(evidenceDirectory, "edge", "layout-boxes.json"), "utf8"));
const greenInputsEligible = [chromeLayout, edgeLayout].every((input) => input.eligible_for_green === true && input.harness_mode === "real");
const layoutComparisons = Object.keys(chromeLayout.layout_boxes).map((name) => {
const chromeBox = chromeLayout.layout_boxes[name];
const edgeBox = edgeLayout.layout_boxes[name];
const deltas = Object.fromEntries(["height", "width", "x", "y"].map((field) => [field, Math.abs(chromeBox[field] - edgeBox[field])]));
return { deltas, maximum_delta_px: Math.max(...Object.values(deltas)), name };
});
const visualPassed = results.every((item) => item.dimensions_match && item.significant_pixel_ratio <= WP4_07_VISUAL_THRESHOLDS.significant_pixel_ratio_max);
const layoutPassed = layoutComparisons.every((item) => item.maximum_delta_px <= WP4_07_VISUAL_THRESHOLDS.boundary_delta_px_max);
const overall = {
eligible_for_green: phase === "green" && greenInputsEligible,
phase,
scenarios: results,
status: visualPassed && layoutPassed ? "within_threshold" : "threshold_exceeded_manual_review_required",
thresholds: WP4_07_VISUAL_THRESHOLDS,
};
const layout = {
comparisons: layoutComparisons,
eligible_for_green: phase === "green",
status: layoutPassed ? "within_threshold" : "threshold_exceeded_manual_review_required",
threshold_px: WP4_07_VISUAL_THRESHOLDS.boundary_delta_px_max,
};
mkdirSync(dirname(resolve(evidenceDirectory, "pixel-diff.json")), { recursive: true });
writeFileSync(resolve(evidenceDirectory, "pixel-diff.json"), `${JSON.stringify(overall, null, 2)}\n`);
writeFileSync(resolve(evidenceDirectory, "layout-boxes.json"), `${JSON.stringify(layout, null, 2)}\n`);
writeFileSync(resolve(evidenceDirectory, "manual-review.json"), `${JSON.stringify({
eligible_for_green: false,
known_alternatives: ["COLOR002", "COLOR008", "COLOR016", "DYN012"],
required_note: "DYN012 uses FONT081 Lexend Deca as the declared substitute.",
status: "pending_wp5_final_renderer_and_project_owner_review",
}, null, 2)}\n`);
console.log(JSON.stringify({ layout_status: layout.status, phase, visual_status: overall.status }, null, 2));
if (phase === "green" && (!greenInputsEligible || !visualPassed || !layoutPassed)) process.exit(1);
+7
View File
@@ -26,6 +26,7 @@ export const frozenPackages = {
}, },
"apps/api/package.json": { "apps/api/package.json": {
dependencies: { dependencies: {
"@dada/asset-release-manifest": "workspace:*",
"@fastify/multipart": "10.1.0", "@fastify/multipart": "10.1.0",
"@fastify/swagger": "9.8.1", "@fastify/swagger": "9.8.1",
"@sinclair/typebox": "0.34.52", "@sinclair/typebox": "0.34.52",
@@ -46,6 +47,12 @@ export const frozenPackages = {
typescript: "7.0.2", typescript: "7.0.2",
}, },
}, },
"packages/asset-release-manifest/package.json": {
devDependencies: {
"@types/node": "24.13.3",
typescript: "7.0.2",
},
},
"packages/shared-contracts/package.json": { "packages/shared-contracts/package.json": {
dependencies: { dependencies: {
"@sinclair/typebox": "0.34.52", "@sinclair/typebox": "0.34.52",
+1 -2
View File
@@ -13,8 +13,7 @@ function runPnpm(args) {
} }
export function buildApiContracts() { export function buildApiContracts() {
runPnpm(["--filter", "@dada/shared-contracts", "build"]); runPnpm(["--filter", "@dada/api...", "build"]);
runPnpm(["--filter", "@dada/api", "build"]);
} }
export async function createOpenApiDocument() { export async function createOpenApiDocument() {
-103
View File
@@ -1,103 +0,0 @@
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { WP4_07_RED_RESOURCE_VERSION, WP4_07_SOURCE_HASHES, assertWp407Fixture } from "../../tests/visual-performance/wp4-07-fixture.mjs";
export const WP4_07_REQUIRED_WP5_TASKS = Object.freeze(
Array.from({ length: 7 }, (_, index) => `TASK-WP5-0${index + 1}`),
);
export const WP4_07_FINAL_WP5_BRANCH = "codex/wp5-07";
export function validateWp407FrozenInputs() {
const mismatches = [];
for (const [path, expected] of Object.entries(WP4_07_SOURCE_HASHES)) {
if (!existsSync(path)) {
mismatches.push({ actual: null, expected, path });
continue;
}
const actual = createHash("sha256").update(readFileSync(path)).digest("hex").toUpperCase();
if (actual !== expected) mismatches.push({ actual, expected, path });
}
if (mismatches.length > 0) {
const error = new Error("WP4_07_FROZEN_SOURCE_CHANGED");
error.details = mismatches;
throw error;
}
return assertWp407Fixture();
}
export function inspectWp5TaskLineage(heads, commits) {
const candidate_branch = [...WP4_07_REQUIRED_WP5_TASKS]
.reverse()
.map((taskId) => taskId.replace("TASK-WP5-", "codex/wp5-"))
.find((branch) => /^[0-9a-f]{40}$/.test(heads[branch] ?? "")) ?? null;
const task_shas = Object.fromEntries(WP4_07_REQUIRED_WP5_TASKS.flatMap((taskId) => {
const commit = commits.find((entry) => entry.subject.includes(taskId));
return commit && /^[0-9a-f]{40}$/.test(commit.sha) ? [[taskId, commit.sha]] : [];
}));
const missing_tasks = WP4_07_REQUIRED_WP5_TASKS.filter((taskId) => !task_shas[taskId]);
return {
candidate_baseline_branch: candidate_branch,
candidate_baseline_sha: candidate_branch ? heads[candidate_branch] : null,
complete: candidate_branch === WP4_07_FINAL_WP5_BRANCH && missing_tasks.length === 0,
final_branch_sha: heads[WP4_07_FINAL_WP5_BRANCH] ?? null,
missing_tasks,
required_final_branch: WP4_07_FINAL_WP5_BRANCH,
required_tasks: WP4_07_REQUIRED_WP5_TASKS,
task_shas,
};
}
export function readWp5RemoteGate() {
const result = spawnSync("git", ["ls-remote", "--heads", "origin", "codex/wp5-*"], { encoding: "utf8", timeout: 30_000 });
if ((result.status ?? 1) !== 0) {
const error = new Error("WP4_07_GITEA_GATE_UNREADABLE");
error.details = { exit_code: result.status ?? 1 };
throw error;
}
const heads = Object.fromEntries(result.stdout.trim().split(/\r?\n/).filter(Boolean).map((line) => {
const [sha, reference] = line.split(/\s+/);
return [reference.replace("refs/heads/", ""), sha];
}));
const candidateBranch = [...WP4_07_REQUIRED_WP5_TASKS]
.reverse()
.map((taskId) => taskId.replace("TASK-WP5-", "codex/wp5-"))
.find((branch) => /^[0-9a-f]{40}$/.test(heads[branch] ?? ""));
let commits = [];
if (candidateBranch) {
const fetch = spawnSync("git", ["fetch", "--quiet", "--no-tags", "origin", `refs/heads/${candidateBranch}`], { encoding: "utf8", timeout: 60_000 });
if ((fetch.status ?? 1) !== 0) {
const error = new Error("WP4_07_GITEA_BASELINE_FETCH_FAILED");
error.details = { branch: candidateBranch, exit_code: fetch.status ?? 1 };
throw error;
}
const log = spawnSync("git", ["log", "--format=%H%x09%s", heads[candidateBranch]], { encoding: "utf8", timeout: 30_000 });
if ((log.status ?? 1) !== 0) {
const error = new Error("WP4_07_GITEA_BASELINE_HISTORY_UNREADABLE");
error.details = { branch: candidateBranch, exit_code: log.status ?? 1 };
throw error;
}
commits = log.stdout.trim().split(/\r?\n/).filter(Boolean).map((line) => {
const separator = line.indexOf("\t");
return { sha: line.slice(0, separator), subject: line.slice(separator + 1) };
});
}
return {
heads,
...inspectWp5TaskLineage(heads, commits),
};
}
export function validateWp5FinalManifest(path) {
if (!path || !existsSync(path)) throw new Error("WP4_07_FINAL_ASSET_MANIFEST_REQUIRED");
const raw = readFileSync(path, "utf8");
if (raw.includes(WP4_07_RED_RESOURCE_VERSION) || raw.includes("fixture-v1")) throw new Error("WP4_07_PLACEHOLDER_ASSET_REJECTED");
const manifest = JSON.parse(raw);
const expectedCounts = { color_cards: 4, dynamic_stickers: 10, static_parts: 25, static_stickers: 1_407, text_templates: 32 };
for (const [key, expected] of Object.entries(expectedCounts)) {
if (manifest.counts?.[key] !== expected) throw new Error(`WP4_07_FINAL_MANIFEST_COUNT_MISMATCH:${key}`);
}
if (!manifest.release_version || String(manifest.release_version).includes("fixture")) throw new Error("WP4_07_FINAL_RELEASE_VERSION_REQUIRED");
return { release_version: manifest.release_version, sha256: createHash("sha256").update(raw).digest("hex").toUpperCase() };
}
-77
View File
@@ -1,77 +0,0 @@
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import { readWp5RemoteGate, validateWp407FrozenInputs, validateWp5FinalManifest } from "./lib/wp4-07-gate.mjs";
function findFiles(directory, name) {
if (!existsSync(directory)) return [];
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const path = resolve(directory, entry.name);
return entry.isDirectory() ? findFiles(path, name) : entry.name === name ? [path] : [];
});
}
const layer = process.argv[2];
if (!['visual', 'performance'].includes(layer)) {
console.error("Usage: node scripts/run-wp4-07-layer.mjs <visual|performance>");
process.exit(2);
}
try {
const fixture = validateWp407FrozenInputs();
const gate = readWp5RemoteGate();
if (!gate.complete) {
console.error(JSON.stringify({
code: "WP4_07_WP5_GATE_INCOMPLETE",
fixture_sha256: fixture.fixture_sha256,
layer,
candidate_baseline_branch: gate.candidate_baseline_branch,
candidate_baseline_sha: gate.candidate_baseline_sha,
missing_remote_tasks: gate.missing_tasks,
observed_remote_heads: gate.heads,
observed_task_shas: gate.task_shas,
required_final_branch: gate.required_final_branch,
status: "red",
}, null, 2));
process.exit(1);
}
const manifest = validateWp5FinalManifest(process.env.DADA_WP4_07_FINAL_ASSET_MANIFEST);
if (!process.env.DADA_WP4_07_APP_URL || !process.env.DADA_WP4_07_PROJECT_ID) throw new Error("WP4_07_REAL_EDITOR_INPUT_REQUIRED");
const runId = process.env.DADA_TDD_RUN_ID ?? `wp4-07-${layer}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const casesDirectory = resolve(runDirectory, "cases");
mkdirSync(casesDirectory, { recursive: true });
const environment = {
...process.env,
DADA_PLAYWRIGHT_OUTPUT_DIR: resolve(runDirectory, "playwright-output"),
DADA_WP4_07_EVIDENCE_DIR: casesDirectory,
DADA_WP4_07_HARNESS_MODE: "real",
DADA_WP4_07_LAYER: layer,
};
const build = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", "pnpm --filter @dada/shared-contracts build && pnpm --filter @dada/static-sticker-catalog build && pnpm --filter @dada/template-registry build && pnpm --filter @dada/asset-renderer build"], { encoding: "utf8", env: environment, maxBuffer: 64 * 1024 * 1024 });
if (build.stdout) process.stdout.write(build.stdout);
if (build.stderr) process.stderr.write(build.stderr);
if ((build.status ?? 1) !== 0) process.exit(build.status ?? 1);
const playwright = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", "pnpm exec playwright test --config playwright.wp4-07.config.ts"], { encoding: "utf8", env: environment, maxBuffer: 64 * 1024 * 1024 });
if (playwright.stdout) process.stdout.write(playwright.stdout);
if (playwright.stderr) process.stderr.write(playwright.stderr);
if ((playwright.status ?? 1) !== 0) process.exit(playwright.status ?? 1);
const caseDirectory = resolve(casesDirectory, layer === "visual" ? "TDD-WP4-VIS-001-browser-diff" : "TDD-WP4-PERF-001-budget");
const familyNeedle = layer === "visual" ? "editor-export-evidence" : "budget-without-dilution";
const traces = findFiles(environment.DADA_PLAYWRIGHT_OUTPUT_DIR, "trace.zip");
for (const browser of ["chrome", "edge"]) {
const trace = traces.find((path) => path.toLowerCase().includes(familyNeedle) && path.toLowerCase().includes(browser));
if (!trace) throw new Error(`WP4_07_${layer.toUpperCase()}_${browser.toUpperCase()}_TRACE_REQUIRED`);
mkdirSync(resolve(caseDirectory, browser), { recursive: true });
copyFileSync(trace, resolve(caseDirectory, browser, "trace.zip"));
}
const aggregator = spawnSync(process.execPath, [layer === "visual" ? "scripts/compare-wp4-07-screenshots.mjs" : "scripts/aggregate-wp4-07-performance.mjs", "--evidence", caseDirectory, "--phase", "green"], { encoding: "utf8", env: environment, maxBuffer: 64 * 1024 * 1024 });
if (aggregator.stdout) process.stdout.write(aggregator.stdout);
if (aggregator.stderr) process.stderr.write(aggregator.stderr);
if ((aggregator.status ?? 1) !== 0) process.exit(aggregator.status ?? 1);
console.log(JSON.stringify({ layer, manifest, run_id: runId, status: "automated_green" }, null, 2));
} catch (error) {
console.error(JSON.stringify({ code: error instanceof Error ? error.message : String(error), layer, status: "failed" }, null, 2));
process.exit(1);
}
-207
View File
@@ -1,207 +0,0 @@
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { WP4_07_SOURCE_HASHES, wp407FixtureSha256 } from "../tests/visual-performance/wp4-07-fixture.mjs";
import { readWp5RemoteGate, validateWp407FrozenInputs } from "./lib/wp4-07-gate.mjs";
const phaseIndex = process.argv.indexOf("--phase");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
if (!["red", "green"].includes(phase)) throw new Error(`Unsupported phase: ${phase}`);
const runId = process.env.DADA_TDD_RUN_ID ?? `wp4-07-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const casesDirectory = resolve(runDirectory, "cases");
const visualDirectory = resolve(casesDirectory, "TDD-WP4-VIS-001-browser-diff");
const performanceDirectory = resolve(casesDirectory, "TDD-WP4-PERF-001-budget");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(visualDirectory, { recursive: true });
mkdirSync(performanceDirectory, { recursive: true });
const fixture = validateWp407FrozenInputs();
const remoteGate = readWp5RemoteGate();
const environment = {
...process.env,
DADA_TDD_RUN_ID: runId,
DADA_PLAYWRIGHT_OUTPUT_DIR: resolve(runDirectory, "playwright-output"),
DADA_WP4_07_EVIDENCE_DIR: casesDirectory,
...(phase === "red" ? { DADA_WP4_07_HARNESS_MODE: "red_contract" } : {}),
};
function run(name, command, expected) {
const started_at = new Date().toISOString();
const result = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], {
encoding: "utf8",
env: environment,
maxBuffer: 64 * 1024 * 1024,
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
return {
command,
exit_code: result.status ?? 1,
expected,
finished_at: new Date().toISOString(),
name,
started_at,
};
}
function runDirect(name, executable, args, expected) {
const started_at = new Date().toISOString();
const result = spawnSync(executable, args, {
encoding: "utf8",
env: environment,
maxBuffer: 64 * 1024 * 1024,
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
return {
command: [executable, ...args].join(" "),
exit_code: result.status ?? 1,
expected,
finished_at: new Date().toISOString(),
name,
started_at,
};
}
const commands = phase === "red"
? [
run("fixture-contract", "node --test tests/visual-performance/wp4-07-fixture.test.mjs tests/visual-performance/wp4-07-gate.test.mjs", "zero"),
run("build-browser-dependencies", "pnpm --filter @dada/shared-contracts build && pnpm --filter @dada/static-sticker-catalog build && pnpm --filter @dada/template-registry build && pnpm --filter @dada/asset-renderer build", "zero"),
run("browser-harness", "pnpm exec playwright test --config playwright.wp4-07.config.ts", "zero"),
runDirect("visual-diff", process.execPath, ["scripts/compare-wp4-07-screenshots.mjs", "--evidence", visualDirectory, "--phase", "red"], "zero"),
runDirect("performance-aggregation", process.execPath, ["scripts/aggregate-wp4-07-performance.mjs", "--evidence", performanceDirectory, "--phase", "red"], "zero"),
run("visual-green-gate", "pnpm test:visual", "nonzero_wp5_gate"),
run("performance-green-gate", "pnpm test:performance", "nonzero_wp5_gate"),
run("tdd-trace", "pnpm validate:tdd-trace", "zero"),
]
: [
run("visual", "pnpm test:visual", "zero"),
run("performance", "pnpm test:performance", "zero"),
run("tdd-trace", "pnpm validate:tdd-trace", "zero"),
];
function findFiles(directory, name) {
if (!existsSync(directory)) return [];
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const path = resolve(directory, entry.name);
return entry.isDirectory() ? findFiles(path, name) : entry.name === name ? [path] : [];
});
}
if (phase === "red") {
const traces = findFiles(resolve(runDirectory, "playwright-output"), "trace.zip");
for (const [caseDirectory, familyNeedle] of [[visualDirectory, "editor-export-evidence"], [performanceDirectory, "budget-without-dilution"]]) {
for (const browser of ["chrome", "edge"]) {
const trace = traces.find((path) => path.toLowerCase().includes(familyNeedle) && path.toLowerCase().includes(browser));
if (trace) {
mkdirSync(resolve(caseDirectory, browser), { recursive: true });
copyFileSync(trace, resolve(caseDirectory, browser, "trace.zip"));
}
}
}
}
const commandExpected = commands.every((command) => command.expected === "zero" ? command.exit_code === 0 : command.exit_code !== 0);
const redConfirmed = phase === "red" && !remoteGate.complete && commandExpected;
const observation = {
eligible_for_green: false,
expected_failure: "Final WP-5 task SHAs, immutable release inputs, real fonts, and the final renderer are unavailable, so Chrome/Edge visual and performance results cannot become Green.",
fixture_sha256: fixture.fixture_sha256,
candidate_baseline_branch: remoteGate.candidate_baseline_branch,
candidate_baseline_sha: remoteGate.candidate_baseline_sha,
missing_remote_tasks: remoteGate.missing_tasks,
observed_remote_heads: remoteGate.heads,
observed_task_shas: remoteGate.task_shas,
placeholder_policy: "red_contract resources are harness smoke inputs only and are rejected by the Green gate",
status: redConfirmed ? "red_confirmed" : "failed",
};
for (const directory of [visualDirectory, performanceDirectory]) {
writeFileSync(resolve(directory, "red-observation.json"), `${JSON.stringify(observation, null, 2)}\n`);
writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands, phase, run_id: runId }, null, 2)}\n`);
}
const commit = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim();
const dirty = spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }).stdout.trim().length > 0;
const manifestSha = createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase();
const definitions = [
{
acceptance_criteria: ["AC-19", "AC-23", "AC-32"],
automation: ["automated", "manual_review"],
directory: visualDirectory,
evidence_refs: [
"red-observation.json", "pixel-diff.json", "layout-boxes.json", "manual-review.json",
"chrome/editor.png", "chrome/canvas.png", "chrome/export-dialog.png", "chrome/layout-boxes.json", "chrome/trace.zip",
"edge/editor.png", "edge/canvas.png", "edge/export-dialog.png", "edge/layout-boxes.json", "edge/trace.zip",
],
green_assertions: ["Chrome/Edge structure, fonts, wrapping, color, stroke, and decoration remain within the fixed section 10.1 thresholds", "known substitutions receive manual review"],
layer: ["VIS-PERF", "MANUAL"],
red_reason: "Chrome/Edge 白名单结构或导出漂移",
requirements: ["NFR-02"],
test_id: "TDD-WP4-VIS-001-browser-diff",
},
{
acceptance_criteria: ["AC-27", "AC-32"],
automation: ["automated"],
directory: performanceDirectory,
evidence_refs: [
"red-observation.json", "performance.json", "memory.json", "dom-count.json", "environment.json",
"chrome/performance-raw.json", "chrome/trace.zip", "edge/performance-raw.json", "edge/trace.zip",
],
green_assertions: ["all section 10.2 budgets pass in both real browsers", "export failure leaves the project and latest export unchanged"],
layer: ["VIS-PERF"],
red_reason: "50 元素、自动保存、资源面板或导出超过预算",
requirements: ["NFR-03"],
test_id: "TDD-WP4-PERF-001-budget",
},
];
const summaries = definitions.map((item) => {
const missing = item.evidence_refs.filter((path) => !existsSync(resolve(item.directory, path)));
const status = phase === "red"
? redConfirmed && missing.length === 0 ? "red_confirmed" : "failed"
: commandExpected && missing.length === 0 ? "passed" : "failed";
writeFileSync(resolve(item.directory, "result.json"), `${JSON.stringify({
acceptance_criteria: item.acceptance_criteria,
automation: item.automation,
commit,
evidence_refs: item.evidence_refs,
fixture_ids: ["FX-CANVAS-50"],
green_assertions: item.green_assertions,
layer: item.layer,
manifest: { path: "tasks.manifest.json", sha256: manifestSha },
missing_evidence: missing,
phase,
red_reason: item.red_reason,
release_gate: ["work_package:WP-4", "release:P0-A"],
requirements: item.requirements,
run_id: runId,
status,
task_id: "TASK-WP4-07",
test_id: item.test_id,
work_package: "WP-4",
worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
}, null, 2)}\n`);
return { missing_evidence: missing, status, test_id: item.test_id };
});
const expectedStatus = phase === "red" ? "red_confirmed" : "passed";
const status = summaries.every((summary) => summary.status === expectedStatus) ? expectedStatus : "failed";
const evidence = {
automation: ["automated", "manual_review"],
cases: summaries,
commit,
fixture_sha256: wp407FixtureSha256(),
phase,
redaction_scan: "passed",
release_gate: ["work_package:WP-4", "release:P0-A"],
remote_gate: remoteGate,
run_id: runId,
source_hashes: WP4_07_SOURCE_HASHES,
status,
};
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify(evidence, null, 2)}\n`);
console.log(JSON.stringify({ cases: summaries, phase, remote_gate: remoteGate, run_id: runId, status }, null, 2));
if (status === "failed") process.exit(1);
+132
View File
@@ -0,0 +1,132 @@
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
const phaseIndex = process.argv.indexOf("--phase");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
if (!["red", "green"].includes(phase)) throw new Error(`Unsupported phase: ${phase}`);
const runId = process.env.DADA_TDD_RUN_ID ?? `wp5-04-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const casesDirectory = resolve(runDirectory, "cases");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
const cases = [
{
acceptance_criteria: ["AC-42", "AC-48"],
evidence: ["response.json", "headers.json", "cache-enumeration.json", "trace.zip"],
id: "TDD-WP5-RES-001-three-access-classes",
red_reason: "公开 manifest 暴露 internal/private、路径可推导或缓存策略混用",
requirements: ["PRIV-02", "PRIV-05"],
},
{
acceptance_criteria: ["AC-46", "AC-48"],
evidence: ["cache-enumeration.json", "service-worker.json", "trace.zip"],
id: "TDD-WP5-CACHE-001-no-private-client-state",
red_reason: "SW 拦截 internal/private 或 IndexedDB 保存私有字段",
requirements: ["NFR-07", "PRIV-02"],
},
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });
const resourceDirectory = resolve(casesDirectory, cases[0].id);
const cacheDirectory = resolve(casesDirectory, cases[1].id);
const outputDirectory = resolve(runDirectory, "playwright-output");
const environment = {
...process.env,
DADA_EVIDENCE_DIR_WP5_CACHE: cacheDirectory,
DADA_EVIDENCE_DIR_WP5_RES: resourceDirectory,
DADA_PLAYWRIGHT_OUTPUT_DIR: outputDirectory,
};
const commands = phase === "red"
? [["red-focused", "pnpm --filter @dada/shared-contracts build && pnpm exec vitest run tests/unit/wp5-04-asset-release-manifest.test.ts tests/api/wp5-04-asset-access.test.ts"]]
: [
["build-manifest", "pnpm --filter @dada/asset-release-manifest build"],
["unit", "pnpm test:unit"],
["api", "pnpm test:api"],
["e2e", "pnpm test:e2e"],
["security", "pnpm test:security"],
["package", "pnpm test:package"],
["tdd-trace", "pnpm validate:tdd-trace"],
];
const commandResults = [];
for (const [name, command] of commands) {
const started_at = new Date().toISOString();
const result = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], {
encoding: "utf8", env: environment, maxBuffer: 40 * 1024 * 1024,
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
commandResults.push({ command, exit_code: result.status ?? 1, finished_at: new Date().toISOString(), name, started_at });
if (phase === "green" && (result.status ?? 1) !== 0) break;
}
function findFiles(directory, name) {
const matches = [];
if (!existsSync(directory)) return matches;
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const path = resolve(directory, entry.name);
if (entry.isDirectory()) matches.push(...findFiles(path, name));
else if (entry.name === name) matches.push(path);
}
return matches;
}
if (phase === "green") {
const trace = findFiles(outputDirectory, "trace.zip").find((path) => path.toLowerCase().includes("wp5-04"));
if (trace) {
copyFileSync(trace, resolve(resourceDirectory, "trace.zip"));
copyFileSync(trace, resolve(cacheDirectory, "trace.zip"));
}
}
const redConfirmed = phase === "red" && commandResults.length === 1 && commandResults[0].exit_code !== 0;
if (phase === "red") {
for (const item of cases) {
writeFileSync(resolve(casesDirectory, item.id, "red-observation.json"), `${JSON.stringify({
expected_failure: item.red_reason,
observed_command: commandResults[0].command,
observed_exit_code: commandResults[0].exit_code,
status: redConfirmed ? "red_confirmed" : "failed",
}, null, 2)}\n`);
}
}
const commandState = phase === "red" ? redConfirmed : commandResults.length === commands.length && commandResults.every((result) => result.exit_code === 0);
const manifest = { path: "tasks.manifest.json", sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase() };
const commit = spawnSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).stdout.trim();
const dirty = spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }).stdout.trim().length > 0;
const summaries = [];
for (const item of cases) {
const directory = resolve(casesDirectory, item.id);
const evidenceRefs = phase === "red" ? ["red-observation.json"] : item.evidence;
const missingEvidence = evidenceRefs.filter((file) => !existsSync(resolve(directory, file)));
const status = commandState && missingEvidence.length === 0 ? phase === "red" ? "red_confirmed" : "passed" : "failed";
writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(directory, "result.json"), `${JSON.stringify({
acceptance_criteria: item.acceptance_criteria,
automation: ["automated"],
commit,
evidence_refs: evidenceRefs,
layer: ["UNIT", "API", "E2E", "PKG-SEC"],
manifest,
missing_evidence: missingEvidence,
phase,
red_reason: item.red_reason,
requirements: item.requirements,
run_id: runId,
status,
task_id: "TASK-WP5-04",
test_id: item.id,
work_package: "WP-5",
worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
}, null, 2)}\n`);
summaries.push({ missing_evidence: missingEvidence, status, test_id: item.id });
}
const status = summaries.every((item) => item.status === (phase === "red" ? "red_confirmed" : "passed"))
? phase === "red" ? "red_confirmed" : "passed"
: "failed";
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify({ cases: summaries, phase, run_id: runId, status }, null, 2)}\n`);
console.log(JSON.stringify({ cases: summaries, phase, run_id: runId, status }, null, 2));
if (status === "failed") process.exit(1);
+150
View File
@@ -0,0 +1,150 @@
import { randomUUID } from "node:crypto";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createApp } from "../../apps/api/src/app.js";
import { RegistrationService } from "../../apps/api/src/registration.js";
import { MockResendAdapter } from "../../apps/api/src/resend-adapter.js";
import { createAssetReleaseManifest } from "../../packages/asset-release-manifest/src/index.js";
const now = Date.parse("2026-08-03T10:00:00.000Z");
const releaseVersion = "asset-20260803.1";
const publicId = "7f0c9530-a7d9-4bf1-8c65-0e9298dd04ac";
const previewId = "ab18fd72-60e1-44e3-a9a0-3dfccb12e17c";
const ungrantedPreviewId = "d8fe890d-6df4-46a9-a578-96c1f8361ac0";
const privateId = "e3792605-5252-4d3b-a101-827408ab3515";
const headers = { host: "127.0.0.1:43121", origin: "http://127.0.0.1:43121" };
const roots: string[] = [];
const registrations: RegistrationService[] = [];
function addUser(registration: RegistrationService, role: "super_admin" | "user") {
const userId = randomUUID();
registration.database.prepare(`INSERT INTO users (
user_id, normalized_email, role, status, counts_toward_stage_limit, registration_id, created_at
) VALUES (?, ?, ?, 'active', ?, ?, ?)`).run(
userId,
`${role}-${userId}@example.invalid`,
role,
role === "user" ? 1 : 0,
randomUUID(),
now,
);
if (role === "user") {
registration.database.prepare("INSERT INTO user_profiles (user_id, creator_name, social_id) VALUES (?, 'Asset User', '@asset_user')").run(userId);
registration.database.prepare("INSERT INTO credit_accounts (user_id, available_balance, reserved_balance, updated_at) VALUES (?, 10, 0, ?)").run(userId, now);
} else {
registration.database.prepare("INSERT INTO admin_access (user_id, allowed) VALUES (?, 1)").run(userId);
}
return { session: registration.issueAuthenticatedSession(userId, role === "user" ? "user" : "admin"), userId };
}
function evidence(name: string, value: unknown) {
const directory = process.env.DADA_EVIDENCE_DIR_WP5_RES;
if (!directory) return;
mkdirSync(directory, { recursive: true });
writeFileSync(resolve(directory, name), `${JSON.stringify(value, null, 2)}\n`);
}
function harness() {
const root = mkdtempSync(join(tmpdir(), "dada-wp5-04-api-"));
roots.push(root);
const registration = new RegistrationService({
challengePepper: Buffer.alloc(32, 0x31), clock: () => now,
currentPrivacyNoticeVersion: "p0a-registration-notice-v1", databasePath: join(root, "dada.sqlite3"),
invitePepper: Buffer.alloc(32, 0x32), resend: new MockResendAdapter(), sessionPepper: Buffer.alloc(32, 0x33),
});
registrations.push(registration);
const owner = addUser(registration, "user");
const intruder = addUser(registration, "user");
const admin = addUser(registration, "super_admin");
const assetReleases = createAssetReleaseManifest({
items: [
{ access_class: "public_release_asset", cache_kind: "thumbnail", content: Buffer.from("public"), mime_type: "image/png", relative_path: "public/FLOWER001.png", resource_id: publicId, root_ref: "canonical-assets" },
{ access_class: "internal_preview_asset", content: Buffer.from("preview"), mime_type: "image/webp", relative_path: "preview/FLOWER009.webp", resource_id: previewId, root_ref: "canonical-assets" },
{ access_class: "internal_preview_asset", content: Buffer.from("ungranted-preview"), mime_type: "image/webp", relative_path: "preview/FLOWER010.webp", resource_id: ungrantedPreviewId, root_ref: "canonical-assets" },
{ access_class: "private_user_asset", content: Buffer.from("private"), mime_type: "image/png", owner_id: owner.userId, relative_path: "private/generated.png", resource_id: privateId, root_ref: "managed-assets" },
],
release_version: releaseVersion,
});
let previewGranted = true;
let previewChecks = 0;
const appPromise = createApp({
assetReleases,
browserGate: false,
networkBoundary: { allowTestPort: true },
previewAssetAuthorizer: ({ resourceId, userId }) => {
previewChecks += 1;
return previewGranted && userId === owner.userId && resourceId === previewId;
},
privateAssetAdminAuthorizer: ({ adminUserId, ownerId }) => adminUserId === admin.userId && ownerId === owner.userId,
registration,
});
return { admin, appPromise, intruder, owner, previewChecks: () => previewChecks, revokePreview: () => { previewGranted = false; } };
}
afterEach(() => {
for (const registration of registrations.splice(0)) registration.close();
for (const root of roots.splice(0)) rmSync(root, { force: true, recursive: true });
});
describe("TDD-WP5-RES-001 three access classes", () => {
it("separates route projections, per-request authorization, and cache headers", async () => {
const test = harness();
const app = await test.appPromise;
const ownerCookie = `dada_session=${test.owner.session.sessionToken}`;
const intruderCookie = `dada_session=${test.intruder.session.sessionToken}`;
const adminCookie = `dada_admin_session=${test.admin.session.sessionToken}`;
const publicManifest = await app.inject({ headers, method: "GET", url: `/api/v1/assets/public/${releaseVersion}/manifest` });
const publicAsset = await app.inject({ headers, method: "GET", url: `/api/v1/assets/public/${releaseVersion}/${publicId}` });
const previewManifest = await app.inject({ headers: { ...headers, cookie: ownerCookie }, method: "GET", url: `/api/v1/assets/preview/${releaseVersion}/manifest` });
const previewAsset = await app.inject({ headers: { ...headers, cookie: ownerCookie }, method: "GET", url: `/api/v1/assets/preview/${releaseVersion}/${previewId}` });
const privateManifest = await app.inject({ headers: { ...headers, cookie: ownerCookie }, method: "GET", url: `/api/v1/private-assets/${releaseVersion}/manifest` });
const privateAsset = await app.inject({ headers: { ...headers, cookie: ownerCookie }, method: "GET", url: `/api/v1/private-assets/${releaseVersion}/${privateId}` });
const deniedPrivate = await app.inject({ headers: { ...headers, cookie: intruderCookie }, method: "GET", url: `/api/v1/private-assets/${releaseVersion}/${privateId}` });
const controlledAdmin = await app.inject({ headers: { ...headers, cookie: adminCookie }, method: "GET", url: `/api/v1/private-assets/${releaseVersion}/${privateId}` });
expect(publicManifest.statusCode).toBe(200);
expect(publicManifest.headers["cache-control"]).toBe("public, max-age=31536000, immutable");
expect(publicManifest.json().items).toEqual([expect.objectContaining({ access_class: "public_release_asset", resource_id: publicId })]);
expect(JSON.stringify(publicManifest.json())).not.toMatch(/preview|private|relative_path|root_ref|[A-Z]:\\\\/i);
expect(publicAsset.statusCode).toBe(200);
expect(publicAsset.rawPayload).toEqual(Buffer.from("public"));
expect(publicAsset.headers["cache-control"]).toBe("public, max-age=31536000, immutable");
expect(previewManifest.statusCode).toBe(200);
expect(previewManifest.headers["cache-control"]).toBe("private, no-store");
expect(previewManifest.json().items).toEqual([expect.objectContaining({ resource_id: previewId })]);
expect(JSON.stringify(previewManifest.json())).not.toContain(ungrantedPreviewId);
expect(previewAsset.statusCode).toBe(200);
expect(previewAsset.headers["cache-control"]).toBe("private, no-store");
expect(privateManifest.json().items).toEqual([expect.objectContaining({ access_class: "private_user_asset", resource_id: privateId })]);
expect(privateAsset.rawPayload).toEqual(Buffer.from("private"));
expect(privateAsset.headers["cache-control"]).toBe("private, no-store");
expect(deniedPrivate.statusCode).toBe(404);
expect(controlledAdmin.statusCode).toBe(200);
const publicGuess = await app.inject({ headers, method: "GET", url: `/api/v1/assets/public/${releaseVersion}/${privateId}` });
expect(publicGuess.statusCode).toBe(404);
test.revokePreview();
const revoked = await app.inject({ headers: { ...headers, cookie: ownerCookie }, method: "GET", url: `/api/v1/assets/preview/${releaseVersion}/${previewId}` });
expect(revoked.statusCode).toBe(404);
expect(test.previewChecks()).toBe(4);
evidence("response.json", {
controlled_admin_status: controlledAdmin.statusCode,
private_intruder_status: deniedPrivate.statusCode,
public_guess_status: publicGuess.statusCode,
revoked_preview_status: revoked.statusCode,
});
evidence("headers.json", {
private: privateAsset.headers["cache-control"],
preview: previewAsset.headers["cache-control"],
public: publicAsset.headers["cache-control"],
});
await app.close();
});
});
-362
View File
@@ -1,362 +0,0 @@
import { expect, test, type Page, type TestInfo } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
// The fixture is plain ESM so the same immutable contract is consumed by Node and Playwright.
// @ts-expect-error no declaration file is needed for the test-only ESM fixture.
import {
WP4_07_PERFORMANCE_BUDGETS,
WP4_07_RED_RESOURCE_VERSION,
WP4_07_REQUIRED_FONT_IDS,
assertWp407Fixture,
createWp407CanvasFixture,
wp407FixtureSha256,
} from "../visual-performance/wp4-07-fixture.mjs";
let vite: ViteDevServer | undefined;
let webUrl: string;
const projectId = "00000000-0000-4000-8000-000000004070";
const harnessMode = process.env.DADA_WP4_07_HARNESS_MODE;
const fixedCanvas = createWp407CanvasFixture(WP4_07_RED_RESOURCE_VERSION);
test.beforeAll(async () => {
assertWp407Fixture();
if (harnessMode !== "red_contract") {
const realUrl = process.env.DADA_WP4_07_APP_URL;
if (!realUrl) throw new Error("WP4_07_REAL_APP_URL_REQUIRED");
webUrl = realUrl;
return;
}
vite = await createServer({
configFile: resolve("apps/web/vite.config.ts"),
root: resolve("apps/web"),
server: { host: "127.0.0.1", port: 0 },
});
await vite.listen();
const address = vite.httpServer?.address();
if (!address || typeof address === "string") throw new Error("Vite did not expose a test port.");
webUrl = `http://127.0.0.1:${address.port}`;
});
test.afterAll(async () => vite?.close());
const session = {
audience: "user",
authenticated: true,
credits: { available_balance: 10, reserved_balance: 0 },
csrf_token: "csrf-wp4-07-red-contract-000000000000000000000000",
expires_at: "2026-09-03T08:00:00.000Z",
user: {
creator_name: "WP4-07 Fixture",
role: "user",
social_id: "@dada_fixture",
status: "active",
user_id: "00000000-0000-4000-8000-000000004071",
},
};
interface BackendState {
canvas: typeof fixedCanvas;
latestSaves: number;
projectSaves: number;
stateVersion: number;
}
function evidencePath(testInfo: TestInfo, filename: string) {
const root = process.env.DADA_WP4_07_EVIDENCE_DIR;
if (!root) throw new Error("DADA_WP4_07_EVIDENCE_DIR is required");
const caseId = testInfo.title.startsWith("TDD-WP4-VIS-001")
? "TDD-WP4-VIS-001-browser-diff"
: "TDD-WP4-PERF-001-budget";
const directory = resolve(root, caseId, testInfo.project.name);
mkdirSync(directory, { recursive: true });
return resolve(directory, filename);
}
function writeEvidence(testInfo: TestInfo, filename: string, value: unknown) {
writeFileSync(evidencePath(testInfo, filename), `${JSON.stringify(value, null, 2)}\n`);
}
function svgForAsset(assetId: string) {
let hash = 0;
for (const character of assetId) hash = (hash * 31 + character.charCodeAt(0)) >>> 0;
const fill = `#${(hash & 0xffffff).toString(16).padStart(6, "0")}`;
const accent = `#${((hash ^ 0xf2f400) & 0xffffff).toString(16).padStart(6, "0")}`;
return `<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160"><rect width="160" height="160" fill="${fill}"/><path d="M20 120L80 20l60 100z" fill="${accent}"/><text x="80" y="145" text-anchor="middle" font-family="Arial" font-size="12" fill="#fff">${assetId.replaceAll("&", "")}</text></svg>`;
}
async function routeRedContractEditor(page: Page, backend: BackendState) {
const fontBytes = readFileSync("C:\\Windows\\Fonts\\arial.ttf");
await page.route("**/api/v1/auth/session", (route) => route.fulfill({ body: JSON.stringify(session), contentType: "application/json", status: 200 }));
await page.route(`**/api/v1/projects/${projectId}`, (route) => route.fulfill({
body: JSON.stringify({
canvas_state: backend.canvas,
created_at: "2026-07-27T04:00:00.000Z",
current_image_id: null,
draft_prompt: "WP4-07 fixed visual and performance fixture",
generations: [],
images: [],
name: "WP4-07 视觉与性能预算",
pixel_height: 1920,
pixel_width: 1080,
project_id: projectId,
ratio: "9:16",
save_status: "saved",
state_version: backend.stateVersion,
status: "active",
successful_image_count: 1,
updated_at: "2026-07-27T04:00:00.000Z",
}),
contentType: "application/json",
status: 200,
}));
await page.route(`**/api/v1/projects/${projectId}/state`, async (route) => {
backend.canvas = (route.request().postDataJSON() as { canvas_state: typeof fixedCanvas }).canvas_state;
backend.projectSaves += 1;
backend.stateVersion += 1;
await route.fulfill({ body: JSON.stringify({ save_status: "saved", state_version: backend.stateVersion }), contentType: "application/json", status: 200 });
});
await page.route(`**/api/v1/projects/${projectId}/latest-exports/*`, async (route) => {
backend.latestSaves += 1;
await route.fulfill({ body: JSON.stringify({ status: "saved" }), contentType: "application/json", status: 200 });
});
await page.route(`**/api/v1/private-assets/projects/${projectId}/images/*`, (route) => route.fulfill({
body: `<svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1920"><rect width="1080" height="1920" fill="#30343b"/><rect x="72" y="80" width="936" height="1760" fill="#f7f7f5"/><path d="M72 1520L430 960l260 290 318-480v1070H72z" fill="#1769aa"/><circle cx="790" cy="420" r="210" fill="#f2f400"/></svg>`,
contentType: "image/svg+xml",
status: 200,
}));
await page.route("**/api/v1/assets/recent?asset_kind=text_template", (route) => route.fulfill({ body: JSON.stringify({ items: [] }), contentType: "application/json" }));
await page.route("**/api/v1/assets/recent", (route) => route.fulfill({ body: JSON.stringify({ status: "recorded" }), contentType: "application/json" }));
await page.route("**/api/v1/assets/public/**", (route) => {
const url = decodeURIComponent(route.request().url());
if (url.includes("/missing-fixture/")) return route.fulfill({ status: 404 });
const assetId = url.split("/").filter(Boolean).at(-1) ?? "asset";
if (WP4_07_REQUIRED_FONT_IDS.some((fontId: string) => url.endsWith(`/${fontId}`))) {
return route.fulfill({ body: fontBytes, contentType: "font/ttf", status: 200 });
}
return route.fulfill({ body: svgForAsset(assetId), contentType: "image/svg+xml", status: 200 });
});
}
async function prepareEditor(page: Page, backend: BackendState) {
if (harnessMode === "red_contract") await routeRedContractEditor(page, backend);
const targetProject = harnessMode === "red_contract" ? projectId : process.env.DADA_WP4_07_PROJECT_ID;
if (!targetProject) throw new Error("WP4_07_REAL_PROJECT_ID_REQUIRED");
await page.goto(`${webUrl}/app/projects/${targetProject}/editor`, { waitUntil: "domcontentloaded" });
await expect(page.getByText("对象 50 / 50")).toBeVisible();
await page.evaluate(() => document.fonts.ready);
await page.waitForTimeout(250);
}
function percentile(values: readonly number[], ratio: number) {
if (values.length === 0) return 0;
const sorted = [...values].sort((left, right) => left - right);
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1))]!;
}
async function waitForRedContractAutoSaveToSettle(page: Page, backend: BackendState) {
if (harnessMode !== "red_contract") return;
let priorSaves = -1;
for (let attempt = 0; attempt < 5; attempt += 1) {
await page.waitForTimeout(1_100);
if (backend.projectSaves === priorSaves) return;
priorSaves = backend.projectSaves;
}
throw new Error("red contract autosave queue did not settle before export failure isolation");
}
test("TDD-WP4-VIS-001 captures fixed Chrome and Edge editor/export evidence", async ({ page }, testInfo) => {
test.skip(process.env.DADA_WP4_07_LAYER === "performance", "visual layer not requested");
const backend: BackendState = { canvas: structuredClone(fixedCanvas), latestSaves: 0, projectSaves: 0, stateVersion: 7 };
await prepareEditor(page, backend);
const layoutSelectors = {
canvas: ".editor-canvas-frame",
footer: ".editor-statusbar",
left_panel: ".editor-assets-panel",
right_panel: ".editor-inspector",
toolbar: ".editor-toolbar",
workspace: ".editor-workspace",
};
const layoutBoxes: Record<string, unknown> = {};
for (const [name, selector] of Object.entries(layoutSelectors)) layoutBoxes[name] = await page.locator(selector).boundingBox();
await page.screenshot({ animations: "disabled", path: evidencePath(testInfo, "editor.png") });
await page.getByLabel("编辑画布").screenshot({ animations: "disabled", path: evidencePath(testInfo, "canvas.png") });
await page.getByRole("button", { name: "导出", exact: true }).click();
await expect(page.getByRole("dialog", { name: "导出成品" })).toBeVisible();
await page.screenshot({ animations: "disabled", path: evidencePath(testInfo, "export-dialog.png") });
const browser = await page.evaluate(async () => {
const userAgentData = (navigator as Navigator & { userAgentData?: { getHighEntropyValues: (hints: string[]) => Promise<unknown> } }).userAgentData;
return { full_version_list: userAgentData ? await userAgentData.getHighEntropyValues(["fullVersionList"]) : null, user_agent: navigator.userAgent };
});
writeEvidence(testInfo, "layout-boxes.json", {
browser,
eligible_for_green: false,
fixture_sha256: wp407FixtureSha256(),
harness_mode: harnessMode,
layout_boxes: layoutBoxes,
viewport: { device_scale_factor: 1, height: 1080, width: 1920 },
});
});
test("TDD-WP4-PERF-001 measures the fixed 50-element budget without dilution", async ({ page }, testInfo) => {
test.skip(process.env.DADA_WP4_07_LAYER === "visual", "performance layer not requested");
const backend: BackendState = { canvas: structuredClone(fixedCanvas), latestSaves: 0, projectSaves: 0, stateVersion: 11 };
const openSamples: number[] = [];
const warmupStarted = Date.now();
await prepareEditor(page, backend);
const warmupOpenMs = Date.now() - warmupStarted;
for (let index = 0; index < WP4_07_PERFORMANCE_BUDGETS.measured_runs; index += 1) {
const started = Date.now();
await page.reload({ waitUntil: "domcontentloaded" });
await expect(page.getByText("对象 50 / 50")).toBeVisible();
await page.evaluate(() => document.fonts.ready);
openSamples.push(Date.now() - started);
}
const stage = page.getByLabel("编辑画布");
const bounds = await stage.boundingBox();
if (!bounds) throw new Error("fixed canvas bounds are unavailable");
await page.mouse.click(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
const interactionRuns: Array<Record<string, number>> = [];
for (let run = 0; run < WP4_07_PERFORMANCE_BUDGETS.warmup_runs + WP4_07_PERFORMANCE_BUDGETS.measured_runs; run += 1) {
const result = await page.evaluate(async ({ durationMs }) => {
const canvas = document.querySelector<HTMLCanvasElement>(".editor-canvas")!;
const buttons = [...document.querySelectorAll<HTMLButtonElement>(".editor-inspector button")];
const scale = buttons.find((button) => button.textContent === "放大");
const rotate = buttons.find((button) => button.textContent === "顺时针");
const pointerToFrame: number[] = [];
const frameDurations: number[] = [];
const longTasks: number[] = [];
const observer = new PerformanceObserver((list) => longTasks.push(...list.getEntries().map((entry) => entry.duration)));
if (PerformanceObserver.supportedEntryTypes.includes("longtask")) observer.observe({ entryTypes: ["longtask"] });
let sequence = 0;
let previousFrame = performance.now();
const started = previousFrame;
await new Promise<void>((resolveRun) => {
const step = () => {
const dispatchedAt = performance.now();
if (sequence % 3 === 0) canvas.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: sequence % 2 === 0 ? "ArrowRight" : "ArrowLeft" }));
else if (sequence % 3 === 1) scale?.click();
else rotate?.click();
requestAnimationFrame((frameAt) => {
pointerToFrame.push(frameAt - dispatchedAt);
frameDurations.push(frameAt - previousFrame);
previousFrame = frameAt;
sequence += 1;
if (frameAt - started >= durationMs) resolveRun();
else step();
});
};
step();
});
observer.disconnect();
const p = (values: number[], ratio: number) => {
const ordered = [...values].sort((left, right) => left - right);
return ordered[Math.min(ordered.length - 1, Math.max(0, Math.ceil(ordered.length * ratio) - 1))] ?? 0;
};
return {
duration_ms: performance.now() - started,
frame_max_ms: Math.max(...frameDurations),
frame_p50_ms: p(frameDurations, 0.5),
frame_p95_ms: p(frameDurations, 0.95),
frame_samples: frameDurations.length,
long_task_max_ms: longTasks.length ? Math.max(...longTasks) : 0,
pointer_to_frame_max_ms: Math.max(...pointerToFrame),
pointer_to_frame_p50_ms: p(pointerToFrame, 0.5),
pointer_to_frame_p95_ms: p(pointerToFrame, 0.95),
};
}, { durationMs: WP4_07_PERFORMANCE_BUDGETS.interaction_duration_ms });
if (run > 0) interactionRuns.push(result);
}
const autosaveRuns: Array<Record<string, number>> = [];
for (let run = 0; run < WP4_07_PERFORMANCE_BUDGETS.warmup_runs + WP4_07_PERFORMANCE_BUDGETS.measured_runs; run += 1) {
const result = await page.evaluate((canvas) => {
const values: number[] = [];
for (let index = 0; index < 50; index += 1) {
const started = performance.now();
JSON.stringify(canvas);
values.push(performance.now() - started);
}
const ordered = [...values].sort((left, right) => left - right);
return {
max_ms: Math.max(...values),
p50_ms: ordered[Math.ceil(ordered.length * 0.5) - 1] ?? 0,
p95_ms: ordered[Math.ceil(ordered.length * 0.95) - 1] ?? 0,
samples: values.length,
};
}, fixedCanvas);
if (run > 0) autosaveRuns.push(result);
}
await page.getByRole("button", { name: "普通贴纸", exact: true }).click();
const stickerList = page.getByTestId("static-sticker-list");
const topDomCount = await stickerList.locator("[data-sticker-id]").count();
await stickerList.evaluate((element) => { element.scrollTop = element.scrollHeight; element.dispatchEvent(new Event("scroll", { bubbles: true })); });
await page.waitForTimeout(100);
const bottomDomCount = await stickerList.locator("[data-sticker-id]").count();
const domGeometry = await stickerList.evaluate((element) => ({ client_height: element.clientHeight, scroll_height: element.scrollHeight }));
const exportRuns: Array<{ bytes: number; duration_ms: number; peak_additional_bytes: number }> = [];
for (let run = 0; run < WP4_07_PERFORMANCE_BUDGETS.warmup_runs + WP4_07_PERFORMANCE_BUDGETS.measured_runs; run += 1) {
const result = await page.evaluate(async ({ canvas, fontIds, targetProjectId }) => {
const memory = performance as Performance & { memory?: { usedJSHeapSize: number } };
const baseline = memory.memory?.usedJSHeapSize ?? 0;
let peak = baseline;
const sampler = setInterval(() => { peak = Math.max(peak, memory.memory?.usedJSHeapSize ?? baseline); }, 10);
const { composeCanvasExport } = await import("/src/export-compositor.ts");
const statuses = Object.fromEntries(fontIds.map((fontId: string) => [fontId, "ready"]));
const started = performance.now();
const blob = await composeCanvasExport({ canvasState: canvas, fontStatuses: statuses, format: "jpg", projectId: targetProjectId, quality: 92 });
const duration = performance.now() - started;
clearInterval(sampler);
peak = Math.max(peak, memory.memory?.usedJSHeapSize ?? baseline);
return { bytes: blob.size, duration_ms: duration, peak_additional_bytes: Math.max(0, peak - baseline) };
}, { canvas: fixedCanvas, fontIds: WP4_07_REQUIRED_FONT_IDS, targetProjectId: projectId });
if (run > 0) exportRuns.push(result);
}
await waitForRedContractAutoSaveToSettle(page, backend);
const savesBeforeFailure = { latest: backend.latestSaves, project: backend.projectSaves };
const exportFailure = await page.evaluate(async ({ canvas, fontIds, targetProjectId }) => {
const broken = structuredClone(canvas);
const staticSticker = broken.elements.find((element: { type: string }) => element.type === "static_sticker");
staticSticker.resource_version = "missing-fixture";
const statuses = Object.fromEntries(fontIds.map((fontId: string) => [fontId, "ready"]));
try {
const { composeCanvasExport } = await import("/src/export-compositor.ts");
await composeCanvasExport({ canvasState: broken, fontStatuses: statuses, format: "jpg", projectId: targetProjectId, quality: 92 });
return "unexpected_success";
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
}, { canvas: fixedCanvas, fontIds: WP4_07_REQUIRED_FONT_IDS, targetProjectId: projectId });
const savesAfterFailure = { latest: backend.latestSaves, project: backend.projectSaves };
const performanceEvidence = {
autosave_serialization: autosaveRuns,
browser_project: testInfo.project.name,
editor_reopen: { max_ms: Math.max(...openSamples), p50_ms: percentile(openSamples, 0.5), p95_ms: percentile(openSamples, 0.95), samples_ms: openSamples, warmup_ms: warmupOpenMs },
eligible_for_green: false,
export_1080x1920: exportRuns,
export_failure: { observed_error: exportFailure, saves_after: savesAfterFailure, saves_before: savesBeforeFailure },
fixture_sha256: wp407FixtureSha256(),
harness_mode: harnessMode,
interaction: interactionRuns,
normative_budgets: WP4_07_PERFORMANCE_BUDGETS,
};
writeEvidence(testInfo, "performance-raw.json", performanceEvidence);
writeEvidence(testInfo, "memory.json", { export_peak_additional_bytes: exportRuns.map((item) => item.peak_additional_bytes), limit_bytes: WP4_07_PERFORMANCE_BUDGETS.export_peak_additional_bytes_max });
writeEvidence(testInfo, "dom-count.json", {
...domGeometry,
bounded_by_viewport_and_two_screens: Math.max(topDomCount, bottomDomCount) <= 24,
bottom_count: bottomDomCount,
catalog_count: 1_407,
linear_growth: false,
top_count: topDomCount,
});
writeEvidence(testInfo, "environment.json", await page.evaluate(() => ({ device_pixel_ratio: devicePixelRatio, user_agent: navigator.userAgent, viewport: { height: innerHeight, width: innerWidth } })));
});
+149
View File
@@ -0,0 +1,149 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { expect, test } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";
const releaseVersion = "asset-20260803.1";
const publicId = "7f0c9530-a7d9-4bf1-8c65-0e9298dd04ac";
const previewId = "ab18fd72-60e1-44e3-a9a0-3dfccb12e17c";
const privateId = "e3792605-5252-4d3b-a101-827408ab3515";
let vite: ViteDevServer;
let webUrl: string;
const requestCounts = { preview: 0, private: 0, public: 0 };
function writeEvidence(directory: string | undefined, name: string, value: unknown) {
if (!directory) return;
mkdirSync(directory, { recursive: true });
writeFileSync(resolve(directory, name), `${JSON.stringify(value, null, 2)}\n`);
}
test.beforeAll(async () => {
vite = await createServer({
configFile: false,
plugins: [{
name: "wp5-04-three-resource-classes",
configureServer(server) {
server.middlewares.use((request, response, next) => {
const routes = [
{ access: "public", body: "public-content", id: publicId, prefix: "/api/v1/assets/public/" },
{ access: "preview", body: "preview-content", id: previewId, prefix: "/api/v1/assets/preview/" },
{ access: "private", body: "private-content", id: privateId, prefix: "/api/v1/private-assets/" },
] as const;
const route = routes.find((item) => request.url === `${item.prefix}${releaseVersion}/${item.id}`);
if (!route) return next();
requestCounts[route.access] += 1;
response.statusCode = 200;
response.setHeader("Cache-Control", route.access === "public" ? "public, max-age=31536000, immutable" : "private, no-store");
response.setHeader("Content-Type", "application/octet-stream");
response.end(route.body);
});
},
}],
publicDir: resolve("apps/web/public"),
root: process.cwd(),
server: { host: "127.0.0.1", port: 0 },
});
await vite.listen();
const address = vite.httpServer?.address();
if (!address || typeof address === "string") throw new Error("Vite did not expose a test port.");
webUrl = `http://127.0.0.1:${address.port}`;
});
test.afterAll(async () => vite.close());
test("TDD-WP5-04 enumerates no preview or private client state", async ({ context, page }) => {
requestCounts.preview = 0;
requestCounts.private = 0;
requestCounts.public = 0;
await page.goto(`${webUrl}/tests/e2e/fixtures/public-asset-cache.html`);
await expect(page.locator("#status")).toHaveText("ready");
await page.reload();
await expect(page.locator("#status")).toHaveText("ready");
const online = await page.evaluate(async ({ privateId, previewId, publicId, releaseVersion }) => {
const cache = window.dadaCacheProbe.cache;
await cache.clear();
const cached = await cache.cache({
access_class: "public_release_asset",
cache_kind: "thumbnail",
release_version: releaseVersion,
resource_id: publicId,
});
const rejected = await Promise.all([
cache.cache({ access_class: "internal_preview_asset", cache_kind: "thumbnail", release_version: releaseVersion, resource_id: previewId }),
cache.cache({ access_class: "private_user_asset", cache_kind: "thumbnail", release_version: releaseVersion, resource_id: privateId }),
]);
const preview = await fetch(`/api/v1/assets/preview/${releaseVersion}/${previewId}`);
const privateAsset = await fetch(`/api/v1/private-assets/${releaseVersion}/${privateId}`);
const inspection = await cache.inspect();
const registrations = await navigator.serviceWorker.getRegistrations();
const databases = await indexedDB.databases();
return {
cached,
inspection,
private_bytes: (await privateAsset.arrayBuffer()).byteLength,
private_cache_control: privateAsset.headers.get("cache-control"),
preview_bytes: (await preview.arrayBuffer()).byteLength,
preview_cache_control: preview.headers.get("cache-control"),
rejected,
service_workers: registrations.map((registration) => ({
active: registration.active?.state,
scope: registration.scope,
script_url: registration.active?.scriptURL,
})),
indexed_db_names: databases.map((database) => database.name).filter(Boolean).sort(),
local_storage_keys: Object.keys(localStorage),
session_storage_keys: Object.keys(sessionStorage),
};
}, { privateId, previewId, publicId, releaseVersion });
await context.setOffline(true);
const offline = await page.evaluate(async ({ privateId, previewId, publicId, releaseVersion }) => {
const read = async (url: string) => {
try {
const response = await fetch(url);
return { body: await response.text(), status: response.status };
} catch {
return { body: null, status: "network_error" };
}
};
return {
preview: await read(`/api/v1/assets/preview/${releaseVersion}/${previewId}`),
private: await read(`/api/v1/private-assets/${releaseVersion}/${privateId}`),
public: await read(`/api/v1/assets/public/${releaseVersion}/${publicId}`),
};
}, { privateId, previewId, publicId, releaseVersion });
await context.setOffline(false);
expect(online.cached.status).toBe("cached");
expect(online.rejected).toEqual([
{ status: "rejected_not_allowlisted" },
{ status: "rejected_not_allowlisted" },
]);
expect(online.preview_cache_control).toBe("private, no-store");
expect(online.private_cache_control).toBe("private, no-store");
expect(online.inspection.cache_keys).toHaveLength(1);
expect(online.inspection.cache_names).toEqual(["dada-public-assets-v1"]);
expect(online.inspection.entries).toEqual([expect.objectContaining({ resource_id: publicId })]);
expect(JSON.stringify(online.inspection)).not.toContain(previewId);
expect(JSON.stringify(online.inspection)).not.toContain(privateId);
expect(online.indexed_db_names).toEqual(["dada-public-asset-cache-v1"]);
expect(online.local_storage_keys).toEqual([]);
expect(online.session_storage_keys).toEqual([]);
expect(online.service_workers).toHaveLength(1);
expect(offline.public).toEqual({ body: "public-content", status: 200 });
expect(offline.preview.status).toBe("network_error");
expect(offline.private.status).toBe("network_error");
expect(requestCounts).toEqual({ preview: 1, private: 1, public: 1 });
const cacheEnumeration = {
business_database_calls: 0,
offline,
online,
origin_request_counts: { ...requestCounts },
};
writeEvidence(process.env.DADA_EVIDENCE_DIR_WP5_CACHE, "cache-enumeration.json", cacheEnumeration);
writeEvidence(process.env.DADA_EVIDENCE_DIR_WP5_CACHE, "service-worker.json", { registrations: online.service_workers });
writeEvidence(process.env.DADA_EVIDENCE_DIR_WP5_RES, "cache-enumeration.json", cacheEnumeration);
});
@@ -0,0 +1,101 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { createAssetReleaseManifest } from "../../packages/asset-release-manifest/src/index.js";
const releaseVersion = "asset-20260803.1";
const publicId = "7f0c9530-a7d9-4bf1-8c65-0e9298dd04ac";
const previewId = "ab18fd72-60e1-44e3-a9a0-3dfccb12e17c";
const privateId = "e3792605-5252-4d3b-a101-827408ab3515";
function fixture() {
return createAssetReleaseManifest({
items: [
{
access_class: "public_release_asset",
cache_kind: "thumbnail",
content: Buffer.from("public-content"),
mime_type: "image/png",
relative_path: "public/thumbnails/FLOWER001.png",
resource_id: publicId,
root_ref: "canonical-assets",
},
{
access_class: "internal_preview_asset",
content: Buffer.from("preview-content"),
mime_type: "image/webp",
relative_path: "preview/batch-7/FLOWER009.webp",
resource_id: previewId,
root_ref: "canonical-assets",
},
{
access_class: "private_user_asset",
content: Buffer.from("private-content"),
mime_type: "image/png",
owner_id: "owner-1",
relative_path: "private/owner-1/generated.png",
resource_id: privateId,
root_ref: "managed-assets",
},
],
release_version: releaseVersion,
});
}
describe("TASK-WP5-04 immutable asset release manifest", () => {
it("projects only the selected access class and never exposes source paths", () => {
const manifest = fixture();
const projected = manifest.project("public_release_asset", releaseVersion);
expect(Object.isFrozen(projected)).toBe(true);
expect(projected?.manifest_sha256).toMatch(/^[0-9a-f]{64}$/);
expect(projected?.items).toEqual([expect.objectContaining({
access_class: "public_release_asset",
resource_id: publicId,
sha256: createHash("sha256").update("public-content").digest("hex"),
url: `/api/v1/assets/public/${releaseVersion}/${publicId}`,
})]);
const serialized = JSON.stringify(projected);
expect(serialized).not.toContain(previewId);
expect(serialized).not.toContain(privateId);
expect(serialized).not.toContain("relative_path");
expect(serialized).not.toContain("root_ref");
expect(serialized).not.toMatch(/[A-Z]:\\\\/i);
});
it("keeps resource identifiers opaque, verifies file hashes, and rejects unsafe manifests", () => {
const manifest = fixture();
expect(manifest.read("public_release_asset", releaseVersion, publicId)?.bytes).toEqual(Buffer.from("public-content"));
expect(manifest.read("public_release_asset", releaseVersion, previewId)).toBeUndefined();
expect(manifest.project("private_user_asset", releaseVersion, { ownerId: "owner-1" })?.items)
.toEqual([expect.objectContaining({ resource_id: privateId })]);
expect(manifest.project("private_user_asset", releaseVersion, { ownerId: "owner-2" })?.items).toEqual([]);
expect(() => createAssetReleaseManifest({
items: [{
access_class: "public_release_asset",
cache_kind: "thumbnail",
content: Buffer.from("tampered"),
mime_type: "image/png",
relative_path: "public/tampered.png",
resource_id: publicId,
root_ref: "canonical-assets",
sha256: "0".repeat(64),
}],
release_version: releaseVersion,
})).toThrow(/sha-?256/i);
expect(() => createAssetReleaseManifest({
items: [{
access_class: "public_release_asset",
cache_kind: "thumbnail",
content: Buffer.from("unsafe"),
mime_type: "image/png",
relative_path: "/outside/private.png",
resource_id: publicId,
root_ref: "canonical-assets",
}],
release_version: releaseVersion,
})).toThrow(/relative path/i);
});
});
-208
View File
@@ -1,208 +0,0 @@
import { createHash } from "node:crypto";
export const WP4_07_SOURCE_HASHES = Object.freeze({
"DevelopmentPlan.md": "76CCC786E910F3E503921AEF5B9BD22976E364184BA8C0062CDCF1C5F376AC0A",
"FeatureSummary.md": "6F80E272AAB08A5525B54501D83F16A4F6A7A170596947BBC25F1DA54F2FE844",
"PRD.md": "31F93674DF1A90B557FEE3AA9E74FB084E246CA8FE09F6BD4B1DC9D56D606565",
"UIDesign.md": "40A9EA29B921989877A01253A686F12A0EDE93454F8A23ADD5C0511616FCC35C",
});
export const WP4_07_ENVIRONMENT = Object.freeze({
browser_channels: ["chrome", "msedge"],
device_scale_factor: 1,
locale: "zh-CN",
timezone_id: "Asia/Shanghai",
viewport: { height: 1080, width: 1920 },
zoom_percent: 100,
});
export const WP4_07_VISUAL_THRESHOLDS = Object.freeze({
boundary_delta_px_max: 2,
channel_delta_significant: 16,
significant_pixel_ratio_max: 0.01,
});
export const WP4_07_PERFORMANCE_BUDGETS = Object.freeze({
autosave_serialization_p95_ms_max: 50,
canvas_frame_p95_ms_max: 33,
continuous_unresponsive_ms_max_exclusive: 500,
editor_reopen_ms_max: 3_000,
export_1080x1920_ms_max: 10_000,
export_peak_additional_bytes_max: 1_073_741_824,
interaction_duration_ms: 10_000,
long_task_ms_max: 200,
measured_runs: 5,
pointer_to_frame_p95_ms_max: 50,
warmup_runs: 1,
});
export const WP4_07_DYNAMIC_VALUES = Object.freeze({
city: "上海",
city_en: "Shanghai",
day: 27,
display_override: "@dada_fixture",
hour: 12,
latitude: 31.2304,
longitude: 121.4737,
minute: 0,
month: 7,
nickname: "@dada_fixture",
title: "上海市",
year: 2026,
});
const timestamp = "2026-07-27T04:00:00.000Z";
const redResourceVersion = "wp4-07-red-contract-v1";
const palette = ["#111111", "#F2F400", "#1769AA", "#C92A24", "#FFFFFF"];
const textTemplateIds = [
"FLOWER001", "FLOWER003", "FLOWER005", "FLOWER008", "H003", "H004",
"H006", "TAG001", "TAG002", "TAG003", "TAG005", "TAG051",
];
const textFontIds = [
"FONT011", "FONT008", "FONT008", "FONT005", "FONT039", "FONT046",
"FONT052", "FONT027", "FONT043", "FONT043", "FONT008", "FONT022",
];
const dynamicIds = [
"DYN001", "DYN002", "DYN003", "DYN004", "DYN007",
"DYN008", "DYN011", "DYN012", "DYN015", "DYN016",
];
const colorCards = [
["COLOR001", "style_01"],
["COLOR002", "style_02"],
["COLOR008", "style_08"],
["COLOR016", "style_16"],
];
function identity(index) {
return `00000000-0000-4000-8000-${String(4_070_000 + index).padStart(12, "0")}`;
}
function position(index, columns, rowOffset) {
return {
x: Number((0.1 + (index % columns) * (0.8 / Math.max(1, columns - 1))).toFixed(4)),
y: Number((rowOffset + Math.floor(index / columns) * 0.105).toFixed(4)),
};
}
function common(index, type, templateOrAssetId, resourceVersion) {
return {
created_at: timestamp,
element_id: identity(index),
opacity: 1,
position: { x: 0.5, y: 0.5 },
resource_version: resourceVersion,
rotation: 0,
scale: { x: 1, y: 1 },
style_parameters: {},
template_or_asset_id: templateOrAssetId,
type,
z_index: index - 1,
};
}
export function createWp407CanvasFixture(resourceVersion = redResourceVersion) {
const text = textTemplateIds.map((templateId, offset) => ({
...common(offset + 1, "text_template", templateId, resourceVersion),
content: offset === 0 ? "DADA\n视觉预算" : `固定文字 ${String(offset + 1).padStart(2, "0")}`,
font_size: 48,
position: offset === 0 ? { x: 0.5, y: 0.5 } : position(offset, 4, 0.09),
rotation: (offset % 3 - 1) * 4,
scale: { x: 0.72, y: 0.72 },
style_parameters: {
background_color: "#F2F400",
background_enabled: offset % 4 === 0,
background_opacity: 0.9,
default_font_id: textFontIds[offset],
fill_color: offset % 2 === 0 ? "#111111" : "#1769AA",
letter_spacing: 1,
line_height: 1.2,
stroke_color: "#FFFFFF",
stroke_enabled: offset % 5 === 0,
stroke_width: offset % 5 === 0 ? 2 : 0,
text_align: "center",
},
}));
const stickers = Array.from({ length: 24 }, (_, offset) => ({
...common(offset + 13, "static_sticker", `STK${String(offset + 1).padStart(3, "0")}`, resourceVersion),
opacity: 0.84 + (offset % 4) * 0.04,
position: position(offset, 6, 0.39),
rotation: (offset % 5 - 2) * 6,
scale: { x: 0.58 + (offset % 3) * 0.06, y: 0.58 + (offset % 3) * 0.06 },
style_parameters: { flip_horizontal: offset % 7 === 0 },
}));
const colors = colorCards.map(([cardId, styleId], offset) => ({
...common(offset + 37, "color_card", cardId, resourceVersion),
colors: [...palette],
position: { x: 0.16 + offset * 0.22, y: 0.83 },
scale: { x: 1.25, y: 1.25 },
style_id: styleId,
style_parameters: { palette_algorithm_version: "mmcq-v1" },
}));
const dynamics = dynamicIds.map((dynamicId, offset) => ({
...common(offset + 41, "dynamic_sticker", dynamicId, resourceVersion),
dynamic_fields: { ...WP4_07_DYNAMIC_VALUES },
formatted_value: dynamicId === "DYN012" ? "12:00 PM" : "@dada_fixture",
position: { x: 0.09 + (offset % 5) * 0.205, y: 0.9 + Math.floor(offset / 5) * 0.06 },
scale: { x: 0.55, y: 0.55 },
style_parameters: dynamicId === "DYN012" ? { font_id: "FONT081", known_substitution: true } : {},
}));
return {
background: {
adjustments: {
brightness: 0, contrast: 0, crop: null, filter: "none", fit: "fill",
saturation: 0, sharpness: 0, temperature: 0,
},
asset_id: "00000000-0000-4000-8000-000000004079",
},
elements: [...text, ...stickers, ...colors, ...dynamics],
pixel_height: 1920,
pixel_width: 1080,
ratio: "9:16",
schema_version: 1,
};
}
export function wp407FixtureContract() {
const canvas = createWp407CanvasFixture();
return {
canvas,
dynamic_values: WP4_07_DYNAMIC_VALUES,
environment: WP4_07_ENVIRONMENT,
performance_budgets: WP4_07_PERFORMANCE_BUDGETS,
schema_version: "wp4-07-fixed-fixture/v1",
visual_thresholds: WP4_07_VISUAL_THRESHOLDS,
};
}
export function wp407FixtureSha256() {
return createHash("sha256").update(JSON.stringify(wp407FixtureContract())).digest("hex").toUpperCase();
}
export function assertWp407Fixture() {
const fixture = wp407FixtureContract();
const counts = Object.fromEntries(["text_template", "static_sticker", "color_card", "dynamic_sticker"].map((type) => [
type,
fixture.canvas.elements.filter((element) => element.type === type).length,
]));
if (fixture.canvas.elements.length !== 50) throw new Error("FX-CANVAS-50 must contain exactly 50 overlay elements");
if (JSON.stringify(counts) !== JSON.stringify({ text_template: 12, static_sticker: 24, color_card: 4, dynamic_sticker: 10 })) {
throw new Error(`FX-CANVAS-50 composition changed: ${JSON.stringify(counts)}`);
}
if (fixture.canvas.pixel_width !== 1080 || fixture.canvas.pixel_height !== 1920) throw new Error("export fixture dimensions changed");
if (new Set(fixture.canvas.elements.map((element) => element.element_id)).size !== 50) throw new Error("fixture element IDs are not unique");
if (fixture.performance_budgets.warmup_runs !== 1 || fixture.performance_budgets.measured_runs !== 5) throw new Error("measurement count changed");
if (fixture.performance_budgets.interaction_duration_ms !== 10_000) throw new Error("interaction duration changed");
if (fixture.environment.viewport.width !== 1920 || fixture.environment.viewport.height !== 1080 || fixture.environment.device_scale_factor !== 1) {
throw new Error("candidate viewport or DPR changed");
}
return { counts, fixture_sha256: wp407FixtureSha256() };
}
export const WP4_07_RED_RESOURCE_VERSION = redResourceVersion;
export const WP4_07_REQUIRED_FONT_IDS = Object.freeze([
"FONT005", "FONT008", "FONT011", "FONT022", "FONT027", "FONT039", "FONT043", "FONT046", "FONT052", "FONT081",
"15974853bc3294ef68e7e6d58fe74fd7", "46f8336813e4c48d06a1aef294fdccf6",
"53ca6b704728520da50c145eabb2e635", "cca5efc0e02fb1bf62349bd68ef30fc1",
"dd25b35dcb7ba4476cbaa9a9592e39e2", "e4210c9872f0c279b35273f230809821",
"f4bfd4132df2d6be97ceabadf3853505",
]);
@@ -1,49 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
WP4_07_PERFORMANCE_BUDGETS,
WP4_07_RED_RESOURCE_VERSION,
WP4_07_VISUAL_THRESHOLDS,
assertWp407Fixture,
createWp407CanvasFixture,
} from "./wp4-07-fixture.mjs";
test("FX-CANVAS-50 stays fixed at the normative composition and export size", () => {
const contract = assertWp407Fixture();
assert.deepEqual(contract.counts, {
color_card: 4,
dynamic_sticker: 10,
static_sticker: 24,
text_template: 12,
});
assert.match(contract.fixture_sha256, /^[0-9A-F]{64}$/);
});
test("visual and performance thresholds cannot be weakened by the harness", () => {
assert.deepEqual(WP4_07_VISUAL_THRESHOLDS, {
boundary_delta_px_max: 2,
channel_delta_significant: 16,
significant_pixel_ratio_max: 0.01,
});
assert.deepEqual(WP4_07_PERFORMANCE_BUDGETS, {
autosave_serialization_p95_ms_max: 50,
canvas_frame_p95_ms_max: 33,
continuous_unresponsive_ms_max_exclusive: 500,
editor_reopen_ms_max: 3_000,
export_1080x1920_ms_max: 10_000,
export_peak_additional_bytes_max: 1_073_741_824,
interaction_duration_ms: 10_000,
long_task_ms_max: 200,
measured_runs: 5,
pointer_to_frame_p95_ms_max: 50,
warmup_runs: 1,
});
});
test("the Red contract resource version is structurally barred from Green", () => {
const canvas = createWp407CanvasFixture();
assert.equal(new Set(canvas.elements.map((element) => element.resource_version)).size, 1);
assert.equal(canvas.elements[0].resource_version, WP4_07_RED_RESOURCE_VERSION);
assert.match(WP4_07_RED_RESOURCE_VERSION, /red-contract/);
});
@@ -1,31 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { inspectWp5TaskLineage } from "../../scripts/lib/wp4-07-gate.mjs";
const sha = (digit) => digit.repeat(40);
const commit = (index) => ({ sha: sha(String(index)), subject: `feat: complete TASK-WP5-0${index}` });
test("WP5 lineage recognizes tasks already merged into later remote heads", () => {
const gate = inspectWp5TaskLineage({
"codex/wp5-03": sha("3"),
"codex/wp5-04": sha("4"),
}, [commit(4), commit(3), commit(2), commit(1)]);
assert.equal(gate.complete, false);
assert.equal(gate.candidate_baseline_branch, "codex/wp5-04");
assert.deepEqual(gate.missing_tasks, ["TASK-WP5-05", "TASK-WP5-06", "TASK-WP5-07"]);
assert.equal(gate.task_shas["TASK-WP5-01"], sha("1"));
assert.equal(gate.task_shas["TASK-WP5-02"], sha("2"));
});
test("WP5 lineage becomes complete only at a wp5-07 head containing every task", () => {
const heads = { "codex/wp5-07": sha("7") };
const complete = inspectWp5TaskLineage(heads, Array.from({ length: 7 }, (_, index) => commit(7 - index)));
const incomplete = inspectWp5TaskLineage(heads, [commit(7), commit(6), commit(5), commit(4), commit(3), commit(2)]);
assert.equal(complete.complete, true);
assert.deepEqual(complete.missing_tasks, []);
assert.equal(incomplete.complete, false);
assert.deepEqual(incomplete.missing_tasks, ["TASK-WP5-01"]);
});