Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08e9c39e49 | ||
|
|
ffd1643848 | ||
|
|
95ab0cb93b | ||
|
|
b2793a2392 | ||
|
|
a7140e99e1 | ||
|
|
76b4f93709 | ||
|
|
bc6fa3d517 | ||
|
|
f4fabb66e5 | ||
|
|
4a0fb1bfae | ||
|
|
f7bed92e61 | ||
|
|
d03b491d2f | ||
|
|
8c349fb56c | ||
|
|
55646ba1b4 | ||
|
|
8abf1397a6 | ||
|
|
e0e101ef28 | ||
|
|
33f87f8db3 | ||
|
|
a7772a7e92 | ||
|
|
2bfb5f2953 | ||
|
|
4ec8327f5e | ||
|
|
cca0a38ada | ||
|
|
d474768a2b |
@@ -1,5 +1,31 @@
|
|||||||
|
import { request as httpsRequest } from "node:https";
|
||||||
|
|
||||||
|
const amapHostname = "restapi.amap.com" as const;
|
||||||
|
const amapMaxResponseBytes = 65_536;
|
||||||
|
const amapTimeoutMs = 15_000;
|
||||||
|
|
||||||
|
export interface AmapHttpRequest {
|
||||||
|
allowRedirects: false;
|
||||||
|
hostname: typeof amapHostname;
|
||||||
|
maxResponseBytes: number;
|
||||||
|
method: "GET";
|
||||||
|
path: string;
|
||||||
|
protocol: "https:";
|
||||||
|
rejectUnauthorized: true;
|
||||||
|
timeoutMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type AmapRequester = (request: AmapHttpRequest) => Promise<unknown>;
|
||||||
|
|
||||||
|
export class AmapAdapterError extends Error {
|
||||||
|
constructor(readonly code: "amap_adapter_disposed" | "amap_invalid_request" | "amap_invalid_response" | "amap_provider_rejected" | "amap_provider_unavailable" | "amap_redirect_rejected" | "amap_request_timeout" | "amap_response_too_large") {
|
||||||
|
super(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export interface AmapAdapter {
|
export interface AmapAdapter {
|
||||||
reverseGeocode(coordinates: { latitude: number; longitude: number }): Promise<{ formattedValue: string; serviceMode: "mock" }>;
|
dispose?(): void;
|
||||||
|
reverseGeocode(coordinates: { latitude: number; longitude: number }): Promise<{ formattedValue: string; serviceMode: "mock" | "real" }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class MockAmapAdapter implements AmapAdapter {
|
export class MockAmapAdapter implements AmapAdapter {
|
||||||
@@ -13,3 +39,126 @@ export class MockAmapAdapter implements AmapAdapter {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function requestAmapJson(input: AmapHttpRequest) {
|
||||||
|
return new Promise<unknown>((resolve, reject) => {
|
||||||
|
if (input.protocol !== "https:" || input.hostname !== amapHostname || input.allowRedirects || !input.rejectUnauthorized) {
|
||||||
|
reject(new AmapAdapterError("amap_invalid_request"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let settled = false;
|
||||||
|
const finish = (callback: () => void) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
callback();
|
||||||
|
};
|
||||||
|
const request = httpsRequest({
|
||||||
|
headers: { Accept: "application/json" },
|
||||||
|
hostname: input.hostname,
|
||||||
|
method: input.method,
|
||||||
|
path: input.path,
|
||||||
|
port: 443,
|
||||||
|
protocol: input.protocol,
|
||||||
|
rejectUnauthorized: input.rejectUnauthorized,
|
||||||
|
servername: input.hostname,
|
||||||
|
}, (response) => {
|
||||||
|
const statusCode = response.statusCode ?? 0;
|
||||||
|
if (statusCode >= 300 && statusCode < 400) {
|
||||||
|
response.resume();
|
||||||
|
finish(() => reject(new AmapAdapterError("amap_redirect_rejected")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (statusCode !== 200) {
|
||||||
|
response.resume();
|
||||||
|
finish(() => reject(new AmapAdapterError("amap_provider_unavailable")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const declaredLength = Number(response.headers["content-length"] ?? 0);
|
||||||
|
if (Number.isFinite(declaredLength) && declaredLength > input.maxResponseBytes) {
|
||||||
|
response.destroy();
|
||||||
|
finish(() => reject(new AmapAdapterError("amap_response_too_large")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let receivedBytes = 0;
|
||||||
|
response.on("data", (chunk: Buffer | string) => {
|
||||||
|
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||||
|
receivedBytes += bytes.length;
|
||||||
|
if (receivedBytes > input.maxResponseBytes) {
|
||||||
|
response.destroy();
|
||||||
|
finish(() => reject(new AmapAdapterError("amap_response_too_large")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(bytes);
|
||||||
|
});
|
||||||
|
response.on("end", () => {
|
||||||
|
finish(() => {
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||||
|
} catch {
|
||||||
|
reject(new AmapAdapterError("amap_invalid_response"));
|
||||||
|
} finally {
|
||||||
|
for (const chunk of chunks) chunk.fill(0);
|
||||||
|
chunks.length = 0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
request.setTimeout(input.timeoutMs, () => request.destroy(new AmapAdapterError("amap_request_timeout")));
|
||||||
|
request.on("error", (error) => finish(() => reject(error instanceof AmapAdapterError ? error : new AmapAdapterError("amap_provider_unavailable"))));
|
||||||
|
request.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RealAmapAdapter implements AmapAdapter {
|
||||||
|
private readonly credential: Buffer;
|
||||||
|
private readonly requester: AmapRequester;
|
||||||
|
private disposed = false;
|
||||||
|
|
||||||
|
constructor(value: string, options: { request?: AmapRequester } = {}) {
|
||||||
|
if (!value.trim()) throw new AmapAdapterError("amap_invalid_request");
|
||||||
|
this.credential = Buffer.from(value, "utf8");
|
||||||
|
this.requester = options.request ?? requestAmapJson;
|
||||||
|
}
|
||||||
|
|
||||||
|
async reverseGeocode(coordinates: { latitude: number; longitude: number }) {
|
||||||
|
if (this.disposed) throw new AmapAdapterError("amap_adapter_disposed");
|
||||||
|
if (!Number.isFinite(coordinates.latitude) || coordinates.latitude < -90 || coordinates.latitude > 90
|
||||||
|
|| !Number.isFinite(coordinates.longitude) || coordinates.longitude < -180 || coordinates.longitude > 180) {
|
||||||
|
throw new AmapAdapterError("amap_invalid_request");
|
||||||
|
}
|
||||||
|
const query = new URLSearchParams({
|
||||||
|
extensions: "base",
|
||||||
|
key: this.credential.toString("utf8"),
|
||||||
|
location: `${coordinates.longitude},${coordinates.latitude}`,
|
||||||
|
});
|
||||||
|
const response = await this.requester({
|
||||||
|
allowRedirects: false,
|
||||||
|
hostname: amapHostname,
|
||||||
|
maxResponseBytes: amapMaxResponseBytes,
|
||||||
|
method: "GET",
|
||||||
|
path: `/v3/geocode/regeo?${query.toString()}`,
|
||||||
|
protocol: "https:",
|
||||||
|
rejectUnauthorized: true,
|
||||||
|
timeoutMs: amapTimeoutMs,
|
||||||
|
});
|
||||||
|
if (!isRecord(response) || response.status !== "1" || !isRecord(response.regeocode)) {
|
||||||
|
throw new AmapAdapterError("amap_provider_rejected");
|
||||||
|
}
|
||||||
|
const formattedValue = typeof response.regeocode.formatted_address === "string"
|
||||||
|
? response.regeocode.formatted_address.trim()
|
||||||
|
: "";
|
||||||
|
if (!formattedValue || formattedValue.length > 200) throw new AmapAdapterError("amap_invalid_response");
|
||||||
|
return { formattedValue, serviceMode: "real" as const };
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose() {
|
||||||
|
if (this.disposed) return;
|
||||||
|
this.disposed = true;
|
||||||
|
this.credential.fill(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import { readSecureConfigCandidate } from "./secure-config.js";
|
|||||||
import { StructuredJsonlLogger } from "./structured-log.js";
|
import { StructuredJsonlLogger } from "./structured-log.js";
|
||||||
import { attachApiSupervisorControl, initializeApiCredentialClients, receiveApiCredentials } from "./supervisor-channel.js";
|
import { attachApiSupervisorControl, initializeApiCredentialClients, receiveApiCredentials } from "./supervisor-channel.js";
|
||||||
import { ModelConfigurationService } from "./model-configuration.js";
|
import { ModelConfigurationService } from "./model-configuration.js";
|
||||||
import { MockAmapAdapter } from "./amap-adapter.js";
|
import { MockAmapAdapter, type AmapAdapter } from "./amap-adapter.js";
|
||||||
import { StickerReleaseService } from "./sticker-releases.js";
|
import { StickerReleaseService } from "./sticker-releases.js";
|
||||||
import { createAdminDiagnosticsProvider, createAdminServicesStorageProvider } from "./admin-state.js";
|
import { createAdminDiagnosticsProvider, createAdminServicesStorageProvider } from "./admin-state.js";
|
||||||
|
|
||||||
@@ -30,10 +30,12 @@ let latestExports: LatestExportService | undefined;
|
|||||||
let models: ModelConfigurationService | undefined;
|
let models: ModelConfigurationService | undefined;
|
||||||
let recentAssets: RecentAssetService | undefined;
|
let recentAssets: RecentAssetService | undefined;
|
||||||
let stickers: StickerReleaseService | undefined;
|
let stickers: StickerReleaseService | undefined;
|
||||||
|
let amap: AmapAdapter = new MockAmapAdapter();
|
||||||
const instanceConfigPath = process.env.DADA_INSTANCE_CONFIG_PATH ?? defaultInstanceConfigPath();
|
const instanceConfigPath = process.env.DADA_INSTANCE_CONFIG_PATH ?? defaultInstanceConfigPath();
|
||||||
if (credentialChannelEnabled) {
|
if (credentialChannelEnabled) {
|
||||||
const clients = initializeApiCredentialClients(await receiveApiCredentials());
|
const clients = initializeApiCredentialClients(await receiveApiCredentials());
|
||||||
try {
|
try {
|
||||||
|
amap = clients.amap;
|
||||||
const derivePepper = (purpose: string) => createHmac("sha256", clients.adminAllowlistPepper)
|
const derivePepper = (purpose: string) => createHmac("sha256", clients.adminAllowlistPepper)
|
||||||
.update(`Dada/P0A/${purpose}/v1`, "utf8")
|
.update(`Dada/P0A/${purpose}/v1`, "utf8")
|
||||||
.digest();
|
.digest();
|
||||||
@@ -57,6 +59,8 @@ if (credentialChannelEnabled) {
|
|||||||
recentAssets = new RecentAssetService({ database: registration.database });
|
recentAssets = new RecentAssetService({ database: registration.database });
|
||||||
registration.applySecureConfig(readSecureConfigCandidate(instanceConfigPath));
|
registration.applySecureConfig(readSecureConfigCandidate(instanceConfigPath));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
amap.dispose?.();
|
||||||
|
amap = new MockAmapAdapter();
|
||||||
stickers?.close();
|
stickers?.close();
|
||||||
stickers = undefined;
|
stickers = undefined;
|
||||||
latestExports?.close();
|
latestExports?.close();
|
||||||
@@ -92,7 +96,7 @@ const adminDiagnostics = adminServicesStorage
|
|||||||
const app = await createApp({
|
const app = await createApp({
|
||||||
...(adminServicesStorage ? { adminServicesStorage } : {}),
|
...(adminServicesStorage ? { adminServicesStorage } : {}),
|
||||||
...(adminDiagnostics ? { adminDiagnostics } : {}),
|
...(adminDiagnostics ? { adminDiagnostics } : {}),
|
||||||
amap: new MockAmapAdapter(),
|
amap,
|
||||||
...(browserSupportRelease ? { browserSupportRelease } : {}),
|
...(browserSupportRelease ? { browserSupportRelease } : {}),
|
||||||
...(credits ? { credits } : {}),
|
...(credits ? { credits } : {}),
|
||||||
...(latestExports ? { latestExports } : {}),
|
...(latestExports ? { latestExports } : {}),
|
||||||
@@ -115,6 +119,7 @@ if (controlPipeIndex >= 0) {
|
|||||||
if (!controlPipe) throw new Error("Supervisor control pipe name is required.");
|
if (!controlPipe) throw new Error("Supervisor control pipe name is required.");
|
||||||
const control = attachApiSupervisorControl(controlPipe, async () => {
|
const control = attachApiSupervisorControl(controlPipe, async () => {
|
||||||
await app.close();
|
await app.close();
|
||||||
|
amap.dispose?.();
|
||||||
latestExports?.close();
|
latestExports?.close();
|
||||||
credits?.close();
|
credits?.close();
|
||||||
projects?.close();
|
projects?.close();
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { createConnection } from "node:net";
|
import { createConnection } from "node:net";
|
||||||
|
|
||||||
|
import { RealAmapAdapter } from "./amap-adapter.js";
|
||||||
|
|
||||||
const API_CREDENTIALS = ["Dada/P0A/api/resend", "Dada/P0A/api/amap", "Dada/P0A/admin/pepper"] as const;
|
const API_CREDENTIALS = ["Dada/P0A/api/resend", "Dada/P0A/api/amap", "Dada/P0A/admin/pepper"] as const;
|
||||||
|
|
||||||
export async function receiveApiCredentials(input: NodeJS.ReadableStream = process.stdin) {
|
export async function receiveApiCredentials(input: NodeJS.ReadableStream = process.stdin) {
|
||||||
@@ -26,10 +28,15 @@ export async function receiveApiCredentials(input: NodeJS.ReadableStream = proce
|
|||||||
|
|
||||||
export function initializeApiCredentialClients(credentials: Record<(typeof API_CREDENTIALS)[number], string>) {
|
export function initializeApiCredentialClients(credentials: Record<(typeof API_CREDENTIALS)[number], string>) {
|
||||||
const configured = API_CREDENTIALS.every((name) => credentials[name].length > 0);
|
const configured = API_CREDENTIALS.every((name) => credentials[name].length > 0);
|
||||||
const adminPepperValue = credentials["Dada/P0A/admin/pepper"];
|
try {
|
||||||
for (const name of API_CREDENTIALS) credentials[name] = "";
|
|
||||||
if (!configured) throw new Error("API credential client initialization failed.");
|
if (!configured) throw new Error("API credential client initialization failed.");
|
||||||
return { adminAllowlistPepper: Buffer.from(adminPepperValue, "utf8") };
|
return {
|
||||||
|
adminAllowlistPepper: Buffer.from(credentials["Dada/P0A/admin/pepper"], "utf8"),
|
||||||
|
amap: new RealAmapAdapter(credentials["Dada/P0A/api/amap"]),
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
for (const name of API_CREDENTIALS) credentials[name] = "";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function attachApiSupervisorControl(pipeName: string, shutdown: () => Promise<void>) {
|
export function attachApiSupervisorControl(pipeName: string, shutdown: () => Promise<void>) {
|
||||||
|
|||||||
@@ -922,7 +922,7 @@ export type ReverseGeocodeRequest = {
|
|||||||
|
|
||||||
export type ReverseGeocodeResponse = {
|
export type ReverseGeocodeResponse = {
|
||||||
"formatted_value": string;
|
"formatted_value": string;
|
||||||
"service_mode": "mock";
|
"service_mode": "mock" | "real";
|
||||||
"status": "resolved";
|
"status": "resolved";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -5621,11 +5621,21 @@
|
|||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"service_mode": {
|
"service_mode": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
"enum": [
|
"enum": [
|
||||||
"mock"
|
"mock"
|
||||||
],
|
],
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"enum": [
|
||||||
|
"real"
|
||||||
|
],
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
"status": {
|
"status": {
|
||||||
"enum": [
|
"enum": [
|
||||||
"resolved"
|
"resolved"
|
||||||
|
|||||||
+8
-1
@@ -109,7 +109,14 @@
|
|||||||
"review:wp7-01": "node scripts/record-wp7-01-manual-review.mjs",
|
"review:wp7-01": "node scripts/record-wp7-01-manual-review.mjs",
|
||||||
"test:wp7-02": "node scripts/run-wp7-02-validation.mjs",
|
"test:wp7-02": "node scripts/run-wp7-02-validation.mjs",
|
||||||
"test:wp7-02:controlled": "node scripts/run-wp7-02-validation.mjs --controlled-real",
|
"test:wp7-02:controlled": "node scripts/run-wp7-02-validation.mjs --controlled-real",
|
||||||
"review:wp7-02": "node scripts/record-wp7-02-manual-review.mjs"
|
"review:wp7-02": "node scripts/record-wp7-02-manual-review.mjs",
|
||||||
|
"test:wp7-03": "node scripts/run-wp7-03-validation.mjs --phase green",
|
||||||
|
"test:wp7-03:red": "node scripts/run-wp7-03-validation.mjs --phase red",
|
||||||
|
"test:wp7-04": "node scripts/run-wp7-04-validation.mjs",
|
||||||
|
"test:wp7-05": "node scripts/run-wp7-05-validation.mjs",
|
||||||
|
"test:wp7-05:unit": "node --test tests/package/wp7-05-ui-gate.test.mjs tests/package/wp7-05-coverage.test.mjs",
|
||||||
|
"test:wp7-06": "node scripts/run-wp7-06-validation.mjs",
|
||||||
|
"test:wp7-06:unit": "node --test tests/package/wp7-06-prefreeze.test.mjs"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@playwright/test": "1.62.0",
|
"@playwright/test": "1.62.0",
|
||||||
|
|||||||
@@ -228,7 +228,13 @@ function readCsv(tracker: SourceTracker, path: string, label: string): CsvRow[]
|
|||||||
|
|
||||||
function itemDirectoryFor(collection: CollectionConfig, catalogPath: string, row: CsvRow): { directory: string; metadataPath: string } {
|
function itemDirectoryFor(collection: CollectionConfig, catalogPath: string, row: CsvRow): { directory: string; metadataPath: string } {
|
||||||
if (collection.id === "font_panel") {
|
if (collection.id === "font_panel") {
|
||||||
const resourceDir = requireString(row.resource_dir, "font resource_dir");
|
const configuredResourceDir = requireString(row.resource_dir, "font resource_dir");
|
||||||
|
const normalizedResourceDir = configuredResourceDir.replaceAll("\\", "/");
|
||||||
|
const relocationMarker = "/resources/font_packages/";
|
||||||
|
const markerIndex = normalizedResourceDir.lastIndexOf(relocationMarker);
|
||||||
|
const resourceDir = isAbsolute(configuredResourceDir) && !inside(configuredResourceDir, collection.root.path) && markerIndex >= 0
|
||||||
|
? relativeReference(normalizedResourceDir.slice(markerIndex + 1), "font resource_dir relocation")
|
||||||
|
: configuredResourceDir;
|
||||||
const directory = resolveSourcePath(resourceDir, collection.root.path, collection.root.path, "font resource_dir");
|
const directory = resolveSourcePath(resourceDir, collection.root.path, collection.root.path, "font resource_dir");
|
||||||
return { directory, metadataPath: resolveSourcePath("metadata.json", directory, collection.root.path, "font metadata") };
|
return { directory, metadataPath: resolveSourcePath("metadata.json", directory, collection.root.path, "font metadata") };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export const ReverseGeocodeRequestSchema = Type.Object({
|
|||||||
|
|
||||||
export const ReverseGeocodeResponseSchema = Type.Object({
|
export const ReverseGeocodeResponseSchema = Type.Object({
|
||||||
formatted_value: Type.String({ maxLength: 200, minLength: 1 }),
|
formatted_value: Type.String({ maxLength: 200, minLength: 1 }),
|
||||||
service_mode: Type.Literal("mock"),
|
service_mode: Type.Union([Type.Literal("mock"), Type.Literal("real")]),
|
||||||
status: Type.Literal("resolved"),
|
status: Type.Literal("resolved"),
|
||||||
}, { additionalProperties: false, $id: "ReverseGeocodeResponse" });
|
}, { additionalProperties: false, $id: "ReverseGeocodeResponse" });
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { join, resolve } from "node:path";
|
import { dirname, join, resolve } from "node:path";
|
||||||
|
|
||||||
import { compileAssetArchive, compileStaticStickerCatalog } from "../packages/asset-compiler/dist/index.js";
|
import { compileAssetArchive, compileStaticStickerCatalog } from "../packages/asset-compiler/dist/index.js";
|
||||||
import { createP0aColorCardRenderPlans } from "../packages/asset-renderer/dist/index.js";
|
import { createP0aColorCardRenderPlans } from "../packages/asset-renderer/dist/index.js";
|
||||||
@@ -18,18 +18,38 @@ import {
|
|||||||
const runDirectory = resolve(process.env.DADA_WP5_03_RUN_DIRECTORY ?? "artifacts/tdd/wp5-03-local");
|
const runDirectory = resolve(process.env.DADA_WP5_03_RUN_DIRECTORY ?? "artifacts/tdd/wp5-03-local");
|
||||||
const whiteDirectory = resolve(process.env.DADA_WP5_03_WHITE_EVIDENCE_DIR ?? join(runDirectory, "cases", "TDD-WP5-WHITE-001-p0a-allowlist"));
|
const whiteDirectory = resolve(process.env.DADA_WP5_03_WHITE_EVIDENCE_DIR ?? join(runDirectory, "cases", "TDD-WP5-WHITE-001-p0a-allowlist"));
|
||||||
const colorDirectory = resolve(process.env.DADA_WP5_03_COLOR_EVIDENCE_DIR ?? join(runDirectory, "cases", "TDD-WP5-COL-001-four-layouts"));
|
const colorDirectory = resolve(process.env.DADA_WP5_03_COLOR_EVIDENCE_DIR ?? join(runDirectory, "cases", "TDD-WP5-COL-001-four-layouts"));
|
||||||
const handoffManifest = resolve(process.env.DADA_COMPLEX_ASSET_MANIFEST ?? join(homedir(), "Desktop", "sticker_web_handoff", "sticker_web_catalog_manifest.json"));
|
const replicationRoot = resolve(process.env.DADA_REPLICATION_ASSET_ROOT ?? join(homedir(), "Desktop", "sticker_web_replication_assets"));
|
||||||
const stickerRoot = resolve(process.env.DADA_STATIC_STICKER_ROOT ?? join(homedir(), "Desktop", "贴纸素材"));
|
const handoffManifest = resolve(process.env.DADA_COMPLEX_ASSET_MANIFEST ?? join(replicationRoot, "sticker_web_handoff", "sticker_web_catalog_manifest.json"));
|
||||||
|
const stickerRoot = resolve(process.env.DADA_STATIC_STICKER_ROOT ?? join(replicationRoot, "sticker_normal"));
|
||||||
if (!existsSync(handoffManifest)) throw new Error("normalized complex asset handoff is unavailable");
|
if (!existsSync(handoffManifest)) throw new Error("normalized complex asset handoff is unavailable");
|
||||||
if (!existsSync(stickerRoot)) throw new Error("static sticker source is unavailable");
|
if (!existsSync(stickerRoot)) throw new Error("static sticker source is unavailable");
|
||||||
|
|
||||||
const complexDirectory = resolve(runDirectory, "inputs", "complex");
|
const complexDirectory = resolve(runDirectory, "inputs", "complex");
|
||||||
const staticDirectory = resolve(runDirectory, "inputs", "static");
|
const staticDirectory = resolve(runDirectory, "inputs", "static");
|
||||||
|
const normalizedHandoffDirectory = resolve(runDirectory, "inputs", "normalized-handoff");
|
||||||
mkdirSync(whiteDirectory, { recursive: true });
|
mkdirSync(whiteDirectory, { recursive: true });
|
||||||
mkdirSync(colorDirectory, { recursive: true });
|
mkdirSync(colorDirectory, { recursive: true });
|
||||||
|
|
||||||
|
const sourceHandoff = JSON.parse(readFileSync(handoffManifest, "utf8"));
|
||||||
|
const normalizedHandoff = {
|
||||||
|
...sourceHandoff,
|
||||||
|
web_handoff: "STICKER_WEB_REPLICATION_HANDOFF.md",
|
||||||
|
validation: "sticker_archive_validation_20260722.json",
|
||||||
|
collections: sourceHandoff.collections
|
||||||
|
.filter((collection) => collection.id !== "normal_stickers")
|
||||||
|
.map((collection) => ({
|
||||||
|
...collection,
|
||||||
|
root: resolve(dirname(handoffManifest), collection.root),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
const normalizedHandoffPath = resolve(normalizedHandoffDirectory, "sticker_web_catalog_manifest.normalized.json");
|
||||||
|
mkdirSync(normalizedHandoffDirectory, { recursive: true });
|
||||||
|
copyFileSync(resolve(dirname(handoffManifest), sourceHandoff.web_handoff), resolve(normalizedHandoffDirectory, normalizedHandoff.web_handoff));
|
||||||
|
copyFileSync(resolve(dirname(handoffManifest), sourceHandoff.validation), resolve(normalizedHandoffDirectory, normalizedHandoff.validation));
|
||||||
|
writeFileSync(normalizedHandoffPath, `${JSON.stringify(normalizedHandoff, null, 2)}\n`);
|
||||||
|
|
||||||
const complex = compileAssetArchive({
|
const complex = compileAssetArchive({
|
||||||
manifestPath: handoffManifest,
|
manifestPath: normalizedHandoffPath,
|
||||||
outputDirectory: complexDirectory,
|
outputDirectory: complexDirectory,
|
||||||
releaseVersion: P0A_COMPLEX_RELEASE_VERSION,
|
releaseVersion: P0A_COMPLEX_RELEASE_VERSION,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
import { validateReleaseCandidateRecord } from "./release-candidate.mjs";
|
||||||
|
|
||||||
|
export const RESEND_DAILY_LIMIT = 80;
|
||||||
|
export const RESEND_MONTHLY_LIMIT = 2_400;
|
||||||
|
export const DELIVERY_CATEGORIES = Object.freeze(["qq", "163", "enterprise"]);
|
||||||
|
export const DELIVERY_SAMPLE_SIZE = 20;
|
||||||
|
export const DELIVERY_MINIMUM_WITHIN_TWO_MINUTES = 19;
|
||||||
|
export const DELIVERY_WINDOW_SECONDS = 120;
|
||||||
|
export const EXPECTED_WP7_01_COMMIT = "623cad25b2a2a9a003502c9a92ebd318dad06248";
|
||||||
|
|
||||||
|
const emailPattern = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i;
|
||||||
|
const absolutePathPattern = /(?:[A-Z]:[\\/]|\\\\|\/Users\/|\/home\/)/i;
|
||||||
|
const sensitiveKeyPattern = /"(?:api[_ -]?key|secret|password|authorization|bearer|cookie|session[_ -]?token|verification[_ -]?code|private[_ -]?content|prompt|image)"\s*:/i;
|
||||||
|
|
||||||
|
function object(value) {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorList(...values) {
|
||||||
|
return [...new Set(values.flat().filter((value) => typeof value === "string" && value.length > 0))];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateDomainCheck(value) {
|
||||||
|
const item = object(value);
|
||||||
|
const freeRules = object(item?.free_rules);
|
||||||
|
const spf = object(item?.spf);
|
||||||
|
const dkim = object(item?.dkim);
|
||||||
|
const errors = [];
|
||||||
|
if (item?.schema_version !== "1.0") errors.push("schema_version");
|
||||||
|
if (item?.service !== "resend") errors.push("service");
|
||||||
|
if (item?.source !== "human_controlled_real") errors.push("source");
|
||||||
|
if (item?.status !== "verified") errors.push("status");
|
||||||
|
if (item?.domain_controlled !== true) errors.push("domain_controlled");
|
||||||
|
if (spf?.status !== "pass") errors.push("spf");
|
||||||
|
if (dkim?.status !== "pass") errors.push("dkim");
|
||||||
|
if (freeRules?.status !== "verified") errors.push("free_rules.status");
|
||||||
|
if (freeRules?.daily_limit !== RESEND_DAILY_LIMIT) errors.push("free_rules.daily_limit");
|
||||||
|
if (freeRules?.monthly_limit !== RESEND_MONTHLY_LIMIT) errors.push("free_rules.monthly_limit");
|
||||||
|
if (freeRules?.paid_fallback_enabled !== false) errors.push("free_rules.paid_fallback_enabled");
|
||||||
|
return errorList(errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateDeliverySummary(value) {
|
||||||
|
const item = object(value);
|
||||||
|
const errors = [];
|
||||||
|
if (item?.schema_version !== "1.0") errors.push("schema_version");
|
||||||
|
if (item?.service !== "resend") errors.push("service");
|
||||||
|
if (item?.source !== "human_controlled_real") errors.push("source");
|
||||||
|
if (item?.status !== "verified") errors.push("status");
|
||||||
|
if (!Array.isArray(item?.categories) || item.categories.length !== DELIVERY_CATEGORIES.length) {
|
||||||
|
errors.push("categories");
|
||||||
|
} else {
|
||||||
|
const categories = item.categories.map((entry) => entry?.category).sort();
|
||||||
|
if (categories.join("|") !== DELIVERY_CATEGORIES.slice().sort().join("|")) errors.push("categories.names");
|
||||||
|
for (const entry of item.categories) {
|
||||||
|
if (!Number.isInteger(entry?.sent_count) || entry.sent_count !== DELIVERY_SAMPLE_SIZE) errors.push(`${entry?.category ?? "unknown"}.sent_count`);
|
||||||
|
if (!Number.isInteger(entry?.delivered_within_120_seconds)
|
||||||
|
|| entry.delivered_within_120_seconds < DELIVERY_MINIMUM_WITHIN_TWO_MINUTES
|
||||||
|
|| entry.delivered_within_120_seconds > DELIVERY_SAMPLE_SIZE) {
|
||||||
|
errors.push(`${entry?.category ?? "unknown"}.delivered_within_120_seconds`);
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(entry?.max_latency_seconds) || entry.max_latency_seconds > DELIVERY_WINDOW_SECONDS) errors.push(`${entry?.category ?? "unknown"}.max_latency_seconds`);
|
||||||
|
if (entry?.mock_used !== false) errors.push(`${entry?.category ?? "unknown"}.mock_used`);
|
||||||
|
if (entry?.preseeded_account_used !== false) errors.push(`${entry?.category ?? "unknown"}.preseeded_account_used`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errorList(errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateAuthResult(value) {
|
||||||
|
const item = object(value);
|
||||||
|
const ordinary = object(item?.ordinary);
|
||||||
|
const admin = object(item?.admin);
|
||||||
|
const errors = [];
|
||||||
|
if (item?.schema_version !== "1.0") errors.push("schema_version");
|
||||||
|
if (item?.service !== "resend") errors.push("service");
|
||||||
|
if (item?.source !== "human_controlled_real") errors.push("source");
|
||||||
|
if (item?.status !== "verified") errors.push("status");
|
||||||
|
if (item?.mock_used !== false) errors.push("mock_used");
|
||||||
|
if (item?.preseeded_account_used !== false) errors.push("preseeded_account_used");
|
||||||
|
for (const [name, auth] of [["ordinary", ordinary], ["admin", admin]]) {
|
||||||
|
if (auth?.status !== "passed") errors.push(`${name}.status`);
|
||||||
|
if (auth?.chain !== "formal") errors.push(`${name}.chain`);
|
||||||
|
if (auth?.verification_code_source !== "real_delivery") errors.push(`${name}.verification_code_source`);
|
||||||
|
}
|
||||||
|
return errorList(errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateRedaction(value, serializedEvidence = "") {
|
||||||
|
const item = object(value);
|
||||||
|
const errors = [];
|
||||||
|
if (item?.schema_version !== "1.0") errors.push("schema_version");
|
||||||
|
if (item?.status !== "passed") errors.push("status");
|
||||||
|
if (item?.forbidden_matches !== 0) errors.push("forbidden_matches");
|
||||||
|
if (item?.credentials_in_evidence !== false) errors.push("credentials_in_evidence");
|
||||||
|
if (item?.mailboxes_in_evidence !== false) errors.push("mailboxes_in_evidence");
|
||||||
|
if (item?.private_content_in_evidence !== false) errors.push("private_content_in_evidence");
|
||||||
|
if (item?.absolute_paths_in_evidence !== false) errors.push("absolute_paths_in_evidence");
|
||||||
|
if (emailPattern.test(serializedEvidence)) errors.push("email_value");
|
||||||
|
if (absolutePathPattern.test(serializedEvidence)) errors.push("absolute_path");
|
||||||
|
if (sensitiveKeyPattern.test(serializedEvidence)) errors.push("sensitive_value");
|
||||||
|
return errorList(errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateCandidateReference(record) {
|
||||||
|
try {
|
||||||
|
validateReleaseCandidateRecord(record);
|
||||||
|
} catch (error) {
|
||||||
|
return [error instanceof Error ? "candidate_record_invalid" : "candidate_record_invalid"];
|
||||||
|
}
|
||||||
|
const errors = [];
|
||||||
|
if (record.build_commit !== EXPECTED_WP7_01_COMMIT) errors.push("candidate_build_commit");
|
||||||
|
const versions = new Map((record.browsers ?? []).map((browser) => [browser.brand, browser.full_version]));
|
||||||
|
if (versions.get("Google Chrome") !== "150.0.7871.187") errors.push("chrome_full_version");
|
||||||
|
if (versions.get("Microsoft Edge") !== "151.0.4129.59") errors.push("edge_full_version");
|
||||||
|
return errorList(errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readJson(path) {
|
||||||
|
if (!path || !existsSync(path)) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(path, "utf8"));
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fileSha256(path) {
|
||||||
|
return createHash("sha256").update(readFileSync(path)).digest("hex").toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateResendEvidence({ candidate, domainCheck, deliverySummary, authResult, redaction }) {
|
||||||
|
const serializedEvidence = JSON.stringify({ domainCheck, deliverySummary, authResult });
|
||||||
|
const errors = [
|
||||||
|
...validateCandidateReference(candidate),
|
||||||
|
...validateDomainCheck(domainCheck),
|
||||||
|
...validateDeliverySummary(deliverySummary),
|
||||||
|
...validateAuthResult(authResult),
|
||||||
|
...validateRedaction(redaction, serializedEvidence),
|
||||||
|
];
|
||||||
|
return errorList(errors);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import path from 'node:path';
|
||||||
|
import { REQUIRED_COVERAGE_UNITS } from './wp7-05-ui-gate.mjs';
|
||||||
|
|
||||||
|
const ABSOLUTE_PATH = /^(?:[A-Za-z]:[\\/]|[\\/]{2}|\\\\)/;
|
||||||
|
|
||||||
|
function assertSafeRelative(value, field) {
|
||||||
|
if (typeof value !== 'string' || !value || ABSOLUTE_PATH.test(value) || path.isAbsolute(value)) {
|
||||||
|
throw new Error(`WP7_05_UNSAFE_${field}`);
|
||||||
|
}
|
||||||
|
const normalized = value.replaceAll('\\', '/');
|
||||||
|
if (normalized.split('/').includes('..')) throw new Error(`WP7_05_UNSAFE_${field}`);
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCoverageEvidence({ runId, candidateSha256, coverageUnits, viewports }) {
|
||||||
|
if (!runId || !/^[A-Za-z0-9._-]+$/.test(runId)) throw new Error('WP7_05_INVALID_RUN_ID');
|
||||||
|
if (!/^[A-Fa-f0-9]{64}$/.test(candidateSha256 ?? '')) throw new Error('WP7_05_INVALID_CANDIDATE_HASH');
|
||||||
|
if (!Array.isArray(coverageUnits)) throw new Error('WP7_05_COVERAGE_UNITS_REQUIRED');
|
||||||
|
|
||||||
|
const byPage = new Map();
|
||||||
|
for (const unit of coverageUnits) {
|
||||||
|
if (!REQUIRED_COVERAGE_UNITS.includes(unit.page_id)) throw new Error('WP7_05_UNKNOWN_PAGE');
|
||||||
|
if (byPage.has(unit.page_id)) throw new Error('WP7_05_DUPLICATE_PAGE');
|
||||||
|
if (!Array.isArray(unit.states) || unit.states.length === 0) throw new Error('WP7_05_STATES_REQUIRED');
|
||||||
|
const states = unit.states.map((state) => ({
|
||||||
|
state: assertSafeRelative(state.state, 'STATE'),
|
||||||
|
screenshot_100pct: assertSafeRelative(state.screenshot_100pct, 'SCREENSHOT'),
|
||||||
|
screenshot_200pct: assertSafeRelative(state.screenshot_200pct, 'SCREENSHOT'),
|
||||||
|
trace: assertSafeRelative(state.trace, 'TRACE'),
|
||||||
|
}));
|
||||||
|
byPage.set(unit.page_id, { page_id: unit.page_id, states });
|
||||||
|
}
|
||||||
|
const missing = REQUIRED_COVERAGE_UNITS.filter((page) => !byPage.has(page));
|
||||||
|
if (missing.length) throw new Error(`WP7_05_MISSING_PAGES:${missing.join(',')}`);
|
||||||
|
if (!Array.isArray(viewports) || viewports.length !== 2) throw new Error('WP7_05_VIEWPORTS_REQUIRED');
|
||||||
|
|
||||||
|
return {
|
||||||
|
schema_version: '1.0',
|
||||||
|
task: 'TASK-WP7-05',
|
||||||
|
run_id: runId,
|
||||||
|
candidate_sha256: candidateSha256.toUpperCase(),
|
||||||
|
viewports,
|
||||||
|
coverage_units: REQUIRED_COVERAGE_UNITS.map((page) => byPage.get(page)),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
|
||||||
|
export const REQUIRED_COVERAGE_UNITS = Object.freeze([
|
||||||
|
'support-gate', 'user-auth', 'workspace', 'current-task', 'projects',
|
||||||
|
'project-detail', 'editor', 'export', 'credits', 'settings',
|
||||||
|
'preview-user-variant', 'admin-auth', 'admin-overview', 'admin-users',
|
||||||
|
'admin-invites', 'admin-models', 'admin-assets', 'admin-preview',
|
||||||
|
'admin-generations', 'admin-services-storage', 'admin-audit', 'system-ui',
|
||||||
|
]);
|
||||||
|
|
||||||
|
const REQUIRED_VIEWPORTS = Object.freeze([
|
||||||
|
{ width: 1920, height: 1080, deviceScaleFactor: 1, zoom: 100 },
|
||||||
|
{ width: 1920, height: 1080, deviceScaleFactor: 1, zoom: 200 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
function blocked(code, details = {}) {
|
||||||
|
return { status: 'externally_blocked', code, ...details };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadCandidateRecord(path) {
|
||||||
|
if (!path || !fs.existsSync(path)) return blocked('candidate_record_missing');
|
||||||
|
try {
|
||||||
|
const record = JSON.parse(fs.readFileSync(path, 'utf8'));
|
||||||
|
if (!Array.isArray(record.browsers) || record.browsers.length !== 2) {
|
||||||
|
return blocked('candidate_browser_record_incomplete');
|
||||||
|
}
|
||||||
|
const brands = new Set(record.browsers.map((browser) => browser.brand));
|
||||||
|
if (brands.size !== 2 || !brands.has('Google Chrome') || !brands.has('Microsoft Edge')) {
|
||||||
|
return blocked('candidate_browser_pair_invalid');
|
||||||
|
}
|
||||||
|
if (record.windows?.build == null || !record.candidate_package?.sha256 || !record.candidate_package?.fixed_port) {
|
||||||
|
return blocked('candidate_identity_incomplete');
|
||||||
|
}
|
||||||
|
if (record.browsers.some((browser) => !browser.full_version || !browser.major)) {
|
||||||
|
return blocked('candidate_full_version_missing');
|
||||||
|
}
|
||||||
|
return { status: 'ready', record };
|
||||||
|
} catch {
|
||||||
|
return blocked('candidate_record_invalid');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateCoverageEvidence(evidence) {
|
||||||
|
if (!evidence || !Array.isArray(evidence.coverage_units)) {
|
||||||
|
return blocked('coverage_evidence_missing');
|
||||||
|
}
|
||||||
|
const actual = new Set(evidence.coverage_units.map((unit) => unit.page_id));
|
||||||
|
const missing = REQUIRED_COVERAGE_UNITS.filter((unit) => !actual.has(unit));
|
||||||
|
if (missing.length) return blocked('coverage_units_incomplete', { missing });
|
||||||
|
const missingStates = evidence.coverage_units
|
||||||
|
.filter((unit) => REQUIRED_COVERAGE_UNITS.includes(unit.page_id))
|
||||||
|
.filter((unit) => !Array.isArray(unit.states) || unit.states.length === 0)
|
||||||
|
.map((unit) => unit.page_id);
|
||||||
|
if (missingStates.length) return blocked('coverage_states_incomplete', { missingStates });
|
||||||
|
const viewportKeys = new Set((evidence.viewports ?? []).map((viewport) => JSON.stringify(viewport)));
|
||||||
|
const missingViewports = REQUIRED_VIEWPORTS.filter((viewport) => !viewportKeys.has(JSON.stringify(viewport)));
|
||||||
|
if (missingViewports.length) return blocked('candidate_viewports_incomplete', { missingViewports });
|
||||||
|
return { status: 'ready' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runWp705Gate({ candidatePath, evidence, dependencies = {} }) {
|
||||||
|
const candidate = loadCandidateRecord(candidatePath);
|
||||||
|
if (candidate.status !== 'ready') return candidate;
|
||||||
|
const coverage = validateCoverageEvidence(evidence);
|
||||||
|
if (coverage.status !== 'ready') return coverage;
|
||||||
|
const externalBlockers = Object.entries(dependencies)
|
||||||
|
.filter(([, status]) => status === 'externally_blocked')
|
||||||
|
.map(([task]) => task);
|
||||||
|
if (externalBlockers.length) return blocked('upstream_external_blocked', { externalBlockers });
|
||||||
|
return { status: 'ready_for_execution' };
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
const EXPECTED_TRACE_SUMMARY = Object.freeze({
|
||||||
|
acceptanceCriteria: 52,
|
||||||
|
errorCategories: 9,
|
||||||
|
featureModules: 13,
|
||||||
|
parentFamilies: 89,
|
||||||
|
penProductFrames: 18,
|
||||||
|
productContracts: 19,
|
||||||
|
requirements: 109,
|
||||||
|
tasks: 52,
|
||||||
|
testCases: 117,
|
||||||
|
uiPages: 22,
|
||||||
|
});
|
||||||
|
|
||||||
|
const REQUIRED_UPSTREAM = Object.freeze({
|
||||||
|
"TASK-WP7-01": "passed",
|
||||||
|
"TASK-WP7-02": "passed",
|
||||||
|
"TASK-WP7-03": "deferred_nonblocking_first_version",
|
||||||
|
"TASK-WP7-04": "deferred_nonblocking_first_version",
|
||||||
|
"TASK-WP7-05": "passed",
|
||||||
|
});
|
||||||
|
|
||||||
|
const shaPattern = /^[0-9a-f]{40}$/i;
|
||||||
|
|
||||||
|
export function buildWp706PrefreezeReport({ currentCommit, releaseExists, trace, upstream }) {
|
||||||
|
if (releaseExists) throw new Error("WP7_06_RELEASE_WRITTEN_PREMATURELY");
|
||||||
|
if (!shaPattern.test(currentCommit ?? "")) throw new Error("WP7_06_CURRENT_COMMIT_INVALID");
|
||||||
|
if (trace?.status !== "passed" || !Array.isArray(trace?.errors) || trace.errors.length > 0) {
|
||||||
|
throw new Error("WP7_06_TRACE_VALIDATION_FAILED");
|
||||||
|
}
|
||||||
|
for (const [key, expected] of Object.entries(EXPECTED_TRACE_SUMMARY)) {
|
||||||
|
if (trace.summary?.[key] !== expected) throw new Error(`WP7_06_TRACE_COUNT_MISMATCH:${key}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [taskId, expectedStatus] of Object.entries(REQUIRED_UPSTREAM)) {
|
||||||
|
const item = upstream?.[taskId];
|
||||||
|
if (!item || !shaPattern.test(item.head ?? "")) throw new Error(`WP7_06_UPSTREAM_HEAD_INVALID:${taskId}`);
|
||||||
|
if (item.merged !== true) throw new Error(`WP7_06_UPSTREAM_NOT_MERGED:${taskId}`);
|
||||||
|
if (item.status !== expectedStatus) throw new Error(`WP7_06_UNSUPPORTED_STATUS:${taskId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
schema_version: "1.0",
|
||||||
|
task_id: "TASK-WP7-06",
|
||||||
|
status: "passed",
|
||||||
|
current_commit: currentCommit.toLowerCase(),
|
||||||
|
release_json_written: false,
|
||||||
|
trace_summary: { ...EXPECTED_TRACE_SUMMARY },
|
||||||
|
upstream: Object.fromEntries(Object.entries(REQUIRED_UPSTREAM).map(([taskId]) => [taskId, {
|
||||||
|
branch: upstream[taskId].branch,
|
||||||
|
head: upstream[taskId].head.toLowerCase(),
|
||||||
|
merged: true,
|
||||||
|
status: upstream[taskId].status,
|
||||||
|
}])),
|
||||||
|
deferred_external_tasks: Object.entries(REQUIRED_UPSTREAM)
|
||||||
|
.filter(([, status]) => status === "deferred_nonblocking_first_version")
|
||||||
|
.map(([taskId]) => taskId),
|
||||||
|
final_release_allowed: false,
|
||||||
|
next_task: "TASK-WP7-07",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { EXPECTED_TRACE_SUMMARY, REQUIRED_UPSTREAM };
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||||
import { resolve } from "node:path";
|
import { homedir } from "node:os";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
|
||||||
const phaseIndex = process.argv.indexOf("--phase");
|
const phaseIndex = process.argv.indexOf("--phase");
|
||||||
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
|
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
|
||||||
@@ -10,6 +11,7 @@ if (!new Set(["red", "green"]).has(phase)) throw new Error(`Unsupported phase: $
|
|||||||
const runId = process.env.DADA_TDD_RUN_ID ?? `wp6-04-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
|
const runId = process.env.DADA_TDD_RUN_ID ?? `wp6-04-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
|
||||||
const runDirectory = resolve("artifacts", "tdd", runId);
|
const runDirectory = resolve("artifacts", "tdd", runId);
|
||||||
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP6-AUD-001-sensitive-operations");
|
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP6-AUD-001-sensitive-operations");
|
||||||
|
const replicationRoot = resolve(process.env.DADA_REPLICATION_ASSET_ROOT ?? join(homedir(), "Desktop", "sticker_web_replication_assets"));
|
||||||
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
|
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
|
||||||
mkdirSync(caseDirectory, { recursive: true });
|
mkdirSync(caseDirectory, { recursive: true });
|
||||||
|
|
||||||
@@ -17,6 +19,9 @@ const environment = {
|
|||||||
...process.env,
|
...process.env,
|
||||||
DADA_EVIDENCE_DIR_WP6_AUD: caseDirectory,
|
DADA_EVIDENCE_DIR_WP6_AUD: caseDirectory,
|
||||||
DADA_PLAYWRIGHT_OUTPUT_DIR: resolve(runDirectory, "playwright-output"),
|
DADA_PLAYWRIGHT_OUTPUT_DIR: resolve(runDirectory, "playwright-output"),
|
||||||
|
DADA_STATIC_STICKER_ROOT: process.env.DADA_STATIC_STICKER_ROOT ?? join(replicationRoot, "sticker_normal"),
|
||||||
|
DADA_DYNAMIC_ASSET_ROOT: process.env.DADA_DYNAMIC_ASSET_ROOT ?? join(replicationRoot, "sticker_interactive", "单模板归档", "templates"),
|
||||||
|
DADA_TEXT_ASSET_ROOT: process.env.DADA_TEXT_ASSET_ROOT ?? join(replicationRoot, "sticker_text"),
|
||||||
};
|
};
|
||||||
const commands = phase === "red"
|
const commands = phase === "red"
|
||||||
? [
|
? [
|
||||||
@@ -25,8 +30,8 @@ const commands = phase === "red"
|
|||||||
["e2e-red", ".\\node_modules\\.bin\\playwright.CMD test tests/e2e/wp6-04-audit.spec.ts --config playwright.config.ts"],
|
["e2e-red", ".\\node_modules\\.bin\\playwright.CMD test tests/e2e/wp6-04-audit.spec.ts --config playwright.config.ts"],
|
||||||
]
|
]
|
||||||
: [
|
: [
|
||||||
["integration", "pnpm.cmd test:integration"],
|
["integration", "pnpm.cmd exec vitest run tests/integration --testTimeout=20000"],
|
||||||
["api", "pnpm.cmd test:api"],
|
["api", "pnpm.cmd check:openapi && pnpm.cmd exec vitest run tests/api --testTimeout=20000"],
|
||||||
["worker", "pnpm.cmd test:worker"],
|
["worker", "pnpm.cmd test:worker"],
|
||||||
["e2e", "pnpm.cmd test:e2e"],
|
["e2e", "pnpm.cmd test:e2e"],
|
||||||
["tdd-trace", "pnpm.cmd validate:tdd-trace"],
|
["tdd-trace", "pnpm.cmd validate:tdd-trace"],
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
|
||||||
|
import {
|
||||||
|
fileSha256,
|
||||||
|
readJson,
|
||||||
|
validateCandidateReference,
|
||||||
|
validateResendEvidence,
|
||||||
|
} from "./lib/resend-release-gate.mjs";
|
||||||
|
|
||||||
|
const phaseIndex = process.argv.indexOf("--phase");
|
||||||
|
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
|
||||||
|
if (!new Set(["red", "green"]).has(phase)) throw new Error(`Unsupported phase: ${phase}`);
|
||||||
|
|
||||||
|
const candidateRunId = process.env.DADA_WP7_01_RUN_ID ?? "wp7-01-candidate-20260804052447717";
|
||||||
|
const runId = process.env.DADA_TDD_RUN_ID ?? `wp7-03-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
|
||||||
|
const runDirectory = resolve("artifacts", "tdd", runId);
|
||||||
|
const caseId = "TDD-WP7-EXT-002-real-resend";
|
||||||
|
const caseDirectory = resolve(runDirectory, "cases", caseId);
|
||||||
|
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
|
||||||
|
mkdirSync(caseDirectory, { recursive: true });
|
||||||
|
|
||||||
|
function writeJson(path, value) {
|
||||||
|
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runCommand(name, command) {
|
||||||
|
const startedAt = new Date().toISOString();
|
||||||
|
const result = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], {
|
||||||
|
encoding: "utf8",
|
||||||
|
env: process.env,
|
||||||
|
maxBuffer: 40 * 1024 * 1024,
|
||||||
|
stdio: "inherit",
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
command,
|
||||||
|
exit_code: result.status ?? 1,
|
||||||
|
finished_at: new Date().toISOString(),
|
||||||
|
name,
|
||||||
|
started_at: startedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidateEvidenceRoot = resolve(
|
||||||
|
process.env.DADA_WP7_01_EVIDENCE_DIR ?? join("artifacts", "tdd", candidateRunId),
|
||||||
|
);
|
||||||
|
const candidate = readJson(join(candidateEvidenceRoot, "release-candidate.json"));
|
||||||
|
const candidateErrors = candidate ? validateCandidateReference(candidate) : ["candidate_record_missing"];
|
||||||
|
writeJson(resolve(caseDirectory, "candidate-reference.json"), candidate ? {
|
||||||
|
browsers: candidate.browsers.map(({ brand, full_version: fullVersion, major }) => ({ brand, full_version: fullVersion, major })),
|
||||||
|
build_commit: candidate.build_commit,
|
||||||
|
candidate_status: candidate.status,
|
||||||
|
final_release: candidate.final_release,
|
||||||
|
fixed_port: candidate.fixed_port,
|
||||||
|
run_id: candidateRunId,
|
||||||
|
schema_version: "1.0",
|
||||||
|
} : {
|
||||||
|
candidate_status: "not_available",
|
||||||
|
reason: "candidate_record_missing",
|
||||||
|
run_id: candidateRunId,
|
||||||
|
schema_version: "1.0",
|
||||||
|
});
|
||||||
|
|
||||||
|
const commands = phase === "red" ? [] : [
|
||||||
|
["workspace-build", "pnpm build:workspace-packages"],
|
||||||
|
["integration", "pnpm test:integration"],
|
||||||
|
["api", "pnpm check:openapi && pnpm exec vitest run tests/api --maxWorkers=1"],
|
||||||
|
["security", "pnpm test:security"],
|
||||||
|
["tdd-trace", "pnpm validate:tdd-trace"],
|
||||||
|
].map(([name, command]) => runCommand(name, command));
|
||||||
|
const localGatePassed = phase === "red" || commands.length > 0 && commands.every(({ exit_code }) => exit_code === 0);
|
||||||
|
|
||||||
|
const redaction = {
|
||||||
|
absolute_paths_in_evidence: false,
|
||||||
|
credentials_in_evidence: false,
|
||||||
|
forbidden_matches: 0,
|
||||||
|
mailboxes_in_evidence: false,
|
||||||
|
private_content_in_evidence: false,
|
||||||
|
schema_version: "1.0",
|
||||||
|
status: "passed",
|
||||||
|
};
|
||||||
|
const externalRoot = process.env.DADA_RESEND_EVIDENCE_DIR ? resolve(process.env.DADA_RESEND_EVIDENCE_DIR) : undefined;
|
||||||
|
const realAuthorized = process.env.DADA_RESEND_REAL_AUTHORIZED === "1";
|
||||||
|
const externalFiles = ["domain-check.json", "delivery-summary.json", "auth-result.json", "redaction.json"];
|
||||||
|
const externalEvidence = externalRoot
|
||||||
|
? Object.fromEntries(externalFiles.map((file) => [file, readJson(join(externalRoot, file))]))
|
||||||
|
: {};
|
||||||
|
const externalEvidenceMissing = externalRoot ? externalFiles.filter((file) => !externalEvidence[file]) : externalFiles;
|
||||||
|
const externalErrors = externalRoot && externalEvidenceMissing.length === 0 && candidate
|
||||||
|
? validateResendEvidence({
|
||||||
|
authResult: externalEvidence["auth-result.json"],
|
||||||
|
candidate,
|
||||||
|
deliverySummary: externalEvidence["delivery-summary.json"],
|
||||||
|
domainCheck: externalEvidence["domain-check.json"],
|
||||||
|
redaction: externalEvidence["redaction.json"],
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const externalBlockers = [];
|
||||||
|
if (candidateErrors.length > 0) externalBlockers.push("candidate_record_unavailable_or_drifted");
|
||||||
|
if (!realAuthorized) externalBlockers.push("controlled_domain_or_real_mailbox_authorization_absent");
|
||||||
|
if (!externalRoot) externalBlockers.push("real_resend_evidence_not_supplied");
|
||||||
|
if (externalRoot && externalEvidenceMissing.length > 0) externalBlockers.push("real_resend_evidence_incomplete");
|
||||||
|
if (externalErrors.length > 0) externalBlockers.push("real_resend_evidence_invalid");
|
||||||
|
|
||||||
|
if (phase === "red") {
|
||||||
|
writeJson(resolve(caseDirectory, "red-observation.json"), {
|
||||||
|
expected_failure: "Resend SPF/DKIM, free-rule, delivery, and formal authentication evidence is absent before TASK-WP7-03.",
|
||||||
|
observed_commands: ["pnpm test:wp7-03:red"],
|
||||||
|
red_reason: "TDD-WP7-EXT-002 requires controlled real domain/mailbox evidence; mock or pre-seeded accounts are not release evidence.",
|
||||||
|
status: "red_confirmed",
|
||||||
|
});
|
||||||
|
} else if (externalRoot && externalEvidenceMissing.length === 0 && candidateErrors.length === 0 && realAuthorized && externalErrors.length === 0) {
|
||||||
|
for (const file of externalFiles) writeJson(resolve(caseDirectory, file), externalEvidence[file]);
|
||||||
|
writeJson(resolve(caseDirectory, "source-hashes.json"), {
|
||||||
|
files: Object.fromEntries(externalFiles.map((file) => [file, fileSha256(join(externalRoot, file))])),
|
||||||
|
schema_version: "1.0",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
writeJson(resolve(caseDirectory, "blocker.json"), {
|
||||||
|
blockers: externalErrors.length > 0 ? ["real_resend_evidence_invalid"] : externalBlockers,
|
||||||
|
mock_accepted_as_evidence: false,
|
||||||
|
paid_fallback_enabled: false,
|
||||||
|
preseeded_accounts_accepted_as_evidence: false,
|
||||||
|
real_calls_started: false,
|
||||||
|
schema_version: "1.0",
|
||||||
|
status: "externally_blocked",
|
||||||
|
});
|
||||||
|
writeJson(resolve(caseDirectory, "redaction.json"), redaction);
|
||||||
|
writeJson(resolve(caseDirectory, "source-hashes.json"), { files: {}, schema_version: "1.0" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedEvidence = phase === "red"
|
||||||
|
? ["candidate-reference.json", "red-observation.json"]
|
||||||
|
: externalRoot && externalEvidenceMissing.length === 0 && candidateErrors.length === 0 && realAuthorized && externalErrors.length === 0
|
||||||
|
? ["candidate-reference.json", "domain-check.json", "delivery-summary.json", "auth-result.json", "redaction.json", "source-hashes.json"]
|
||||||
|
: ["candidate-reference.json", "blocker.json", "redaction.json", "source-hashes.json"];
|
||||||
|
const missingEvidence = expectedEvidence.filter((file) => !existsSync(resolve(caseDirectory, file)));
|
||||||
|
const status = phase === "red"
|
||||||
|
? localGatePassed && missingEvidence.length === 0 ? "red_confirmed" : "failed"
|
||||||
|
: !localGatePassed || missingEvidence.length > 0 ? "failed"
|
||||||
|
: realAuthorized && (!externalRoot || externalEvidenceMissing.length > 0 || externalErrors.length > 0) ? "failed"
|
||||||
|
: externalRoot && externalEvidenceMissing.length === 0 && candidateErrors.length === 0 && realAuthorized && externalErrors.length === 0 ? "passed"
|
||||||
|
: "externally_blocked";
|
||||||
|
const manifest = {
|
||||||
|
path: "tasks.manifest.json",
|
||||||
|
sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase(),
|
||||||
|
};
|
||||||
|
const result = {
|
||||||
|
acceptance_criteria: ["AC-01", "AC-33", "AC-41", "AC-47", "AC-49"],
|
||||||
|
automation: ["controlled_real", "manual_review"],
|
||||||
|
candidate_run_id: candidateRunId,
|
||||||
|
commit: spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim(),
|
||||||
|
evidence_refs: expectedEvidence,
|
||||||
|
external_blockers: phase === "green" && status === "externally_blocked" ? externalBlockers : [],
|
||||||
|
finished_at: new Date().toISOString(),
|
||||||
|
layer: ["EXT-REAL", "MANUAL"],
|
||||||
|
manifest,
|
||||||
|
missing_evidence: missingEvidence,
|
||||||
|
phase,
|
||||||
|
requirements: ["AUTH-01", "AUTH-02", "AUTH-07"],
|
||||||
|
run_id: runId,
|
||||||
|
schema_version: "1.0",
|
||||||
|
status,
|
||||||
|
task_id: "TASK-WP7-03",
|
||||||
|
test_id: caseId,
|
||||||
|
work_package: "WP-7",
|
||||||
|
};
|
||||||
|
writeJson(resolve(caseDirectory, "commands.json"), { commands, phase, run_id: runId, schema_version: "1.0" });
|
||||||
|
writeJson(resolve(caseDirectory, "result.json"), result);
|
||||||
|
writeJson(resolve(runDirectory, "evidence.json"), { cases: [{ external_blockers: result.external_blockers, missing_evidence: missingEvidence, status, test_id: caseId }], phase, run_id: runId, status });
|
||||||
|
console.log(JSON.stringify({ external_blockers: result.external_blockers, phase, run_id: runId, status }, null, 2));
|
||||||
|
if (status === "failed") process.exit(1);
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
|
||||||
|
const runId = process.env.DADA_TDD_RUN_ID ?? `wp7-04-amap-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
|
||||||
|
const runDirectory = resolve("artifacts", "tdd", runId);
|
||||||
|
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP7-EXT-003-real-amap");
|
||||||
|
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
|
||||||
|
mkdirSync(caseDirectory, { recursive: true });
|
||||||
|
|
||||||
|
function run(command, args, evidenceCommand = [command, ...args].join(" ")) {
|
||||||
|
const startedAt = new Date().toISOString();
|
||||||
|
const executable = process.platform === "win32" ? (process.env.ComSpec ?? "cmd.exe") : command;
|
||||||
|
const actualArgs = process.platform === "win32" ? ["/d", "/s", "/c", [command, ...args].join(" ")] : args;
|
||||||
|
const result = spawnSync(executable, actualArgs, { encoding: "utf8" });
|
||||||
|
return {
|
||||||
|
command: evidenceCommand,
|
||||||
|
exit_code: result.status ?? 1,
|
||||||
|
finished_at: new Date().toISOString(),
|
||||||
|
stderr: result.stderr ?? "",
|
||||||
|
stdout: result.stdout ?? "",
|
||||||
|
started_at: startedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function skipped(command) {
|
||||||
|
const timestamp = new Date().toISOString();
|
||||||
|
return { command, exit_code: 1, finished_at: timestamp, started_at: timestamp, stderr: "prerequisite_failed", stdout: "" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function readConsoleReview() {
|
||||||
|
const raw = process.env.DADA_AMAP_CONSOLE_REVIEW_JSON;
|
||||||
|
const fallback = {
|
||||||
|
allowlist: "not_verified",
|
||||||
|
auto_scaling: "not_verified",
|
||||||
|
paid_fallback: "not_verified",
|
||||||
|
qps: "not_verified",
|
||||||
|
qps_limit_per_second: null,
|
||||||
|
reviewed_at: null,
|
||||||
|
security_restriction: "not_verified",
|
||||||
|
service_binding: "not_verified",
|
||||||
|
source: "not_supplied",
|
||||||
|
valid: true,
|
||||||
|
};
|
||||||
|
if (!raw) return fallback;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
const requiredKeys = ["allowlist", "auto_scaling", "paid_fallback", "qps", "qps_limit_per_second", "reviewed_at", "security_restriction", "service_binding", "source"];
|
||||||
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).sort().join("|") !== requiredKeys.sort().join("|")) {
|
||||||
|
return { ...fallback, source: "invalid_input", valid: false };
|
||||||
|
}
|
||||||
|
const statusFields = ["allowlist", "qps", "security_restriction", "service_binding"];
|
||||||
|
const statusValid = statusFields.every((field) => ["failed", "not_verified", "passed"].includes(parsed[field]));
|
||||||
|
const disabledFieldsValid = ["auto_scaling", "paid_fallback"].every((field) => ["disabled", "not_verified"].includes(parsed[field]));
|
||||||
|
const qpsLimitValid = parsed.qps === "passed"
|
||||||
|
? Number.isSafeInteger(parsed.qps_limit_per_second) && parsed.qps_limit_per_second >= 1 && parsed.qps_limit_per_second <= 1_000
|
||||||
|
: parsed.qps_limit_per_second === null;
|
||||||
|
const reviewedAtValid = typeof parsed.reviewed_at === "string" && Number.isFinite(Date.parse(parsed.reviewed_at));
|
||||||
|
if (!statusValid || !disabledFieldsValid || !qpsLimitValid || !reviewedAtValid || parsed.source !== "amap_console_manual_review") {
|
||||||
|
return { ...fallback, source: "invalid_input", valid: false };
|
||||||
|
}
|
||||||
|
return { ...parsed, valid: true };
|
||||||
|
} catch {
|
||||||
|
return { ...fallback, source: "invalid_input", valid: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeJson(path, value) {
|
||||||
|
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function probeCode(value) {
|
||||||
|
return typeof value === "string" && /^[a-z0-9_]{1,64}$/.test(value) ? value : "invalid_output";
|
||||||
|
}
|
||||||
|
|
||||||
|
function containsForbiddenEvidence(value) {
|
||||||
|
const serialized = JSON.stringify(value);
|
||||||
|
return [
|
||||||
|
/[A-Za-z]:[\\/](?:Users|Documents)[\\/]/i,
|
||||||
|
/"(?:api[_-]?key|credential|secret_value|latitude|longitude|coordinates|email_address|ip_address)"\s*:/i,
|
||||||
|
/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/,
|
||||||
|
].some((pattern) => pattern.test(serialized));
|
||||||
|
}
|
||||||
|
|
||||||
|
const consoleReview = readConsoleReview();
|
||||||
|
const build = run("pnpm", ["build:workspace-packages"]);
|
||||||
|
const locationRegression = build.exit_code === 0
|
||||||
|
? run("pnpm", ["exec", "vitest", "run", "tests/api/wp4-04-location.test.ts"])
|
||||||
|
: skipped("pnpm exec vitest run tests/api/wp4-04-location.test.ts");
|
||||||
|
const serviceRegression = build.exit_code === 0
|
||||||
|
? run("pnpm", ["exec", "vitest", "run", "tests/api/wp6-03-services.test.ts"])
|
||||||
|
: skipped("pnpm exec vitest run tests/api/wp6-03-services.test.ts");
|
||||||
|
const localHardStop = build.exit_code === 0
|
||||||
|
? run("pnpm", ["exec", "vitest", "run", "tests/api/wp7-04-amap-release-gate.test.ts"])
|
||||||
|
: skipped("pnpm exec vitest run tests/api/wp7-04-amap-release-gate.test.ts");
|
||||||
|
const productionAdapter = build.exit_code === 0
|
||||||
|
? run("pnpm", ["exec", "vitest", "run", "tests/api/wp7-04-amap-production-adapter.test.ts"])
|
||||||
|
: skipped("pnpm exec vitest run tests/api/wp7-04-amap-production-adapter.test.ts");
|
||||||
|
const consentFlow = build.exit_code === 0
|
||||||
|
? run("pnpm", ["exec", "vitest", "run", "tests/unit/wp4-04-palette-dynamic.test.ts"])
|
||||||
|
: skipped("pnpm exec vitest run tests/unit/wp4-04-palette-dynamic.test.ts");
|
||||||
|
const supervisorBuild = run("dotnet", ["build", "supervisor/Dada.Supervisor/Dada.Supervisor.csproj", "--configuration", "Release"]);
|
||||||
|
const supervisorSecurity = supervisorBuild.exit_code === 0
|
||||||
|
? run("dotnet", ["run", "--project", "supervisor/Dada.Supervisor.Tests/Dada.Supervisor.Tests.csproj", "--configuration", "Release"])
|
||||||
|
: skipped("dotnet run --project supervisor/Dada.Supervisor.Tests/Dada.Supervisor.Tests.csproj --configuration Release");
|
||||||
|
const supervisorExe = resolve("supervisor", "Dada.Supervisor", "bin", "Release", "net8.0-windows", "Dada.Supervisor.exe");
|
||||||
|
const external = supervisorBuild.exit_code === 0 && existsSync(supervisorExe)
|
||||||
|
? run(supervisorExe, ["secrets", "probe", "api-amap"], "Dada.Supervisor.exe secrets probe api-amap")
|
||||||
|
: skipped("Dada.Supervisor.exe secrets probe api-amap");
|
||||||
|
const trace = run("pnpm", ["validate:tdd-trace"]);
|
||||||
|
const security = run("pnpm", ["test:security"]);
|
||||||
|
const commands = [build, locationRegression, serviceRegression, localHardStop, productionAdapter, consentFlow, supervisorBuild, supervisorSecurity, external, trace, security]
|
||||||
|
.map(({ command, exit_code, finished_at, started_at }) => ({ command, exit_code, finished_at, started_at }));
|
||||||
|
const parsedExternal = (() => {
|
||||||
|
try { return JSON.parse(external.stdout.trim().split(/\r?\n/).at(-1) ?? ""); } catch { return {}; }
|
||||||
|
})();
|
||||||
|
const safeProbeCode = probeCode(parsedExternal.code);
|
||||||
|
const realCalls = Number.isSafeInteger(parsedExternal.real_calls) && parsedExternal.real_calls >= 0 && parsedExternal.real_calls <= 2
|
||||||
|
? parsedExternal.real_calls
|
||||||
|
: 0;
|
||||||
|
const probePassed = external.exit_code === 0 && safeProbeCode === "amap_probe_passed" && realCalls === 2;
|
||||||
|
const hardStopPassed = localHardStop.exit_code === 0;
|
||||||
|
const productionAdapterPassed = productionAdapter.exit_code === 0;
|
||||||
|
const consentPassed = consentFlow.exit_code === 0;
|
||||||
|
const supervisorSecurityPassed = supervisorSecurity.exit_code === 0;
|
||||||
|
const regressionPassed = locationRegression.exit_code === 0 && serviceRegression.exit_code === 0;
|
||||||
|
const automatedPassed = build.exit_code === 0 && hardStopPassed && productionAdapterPassed && consentPassed && supervisorSecurityPassed && regressionPassed && trace.exit_code === 0 && security.exit_code === 0;
|
||||||
|
const manualReviewPassed = consoleReview.valid
|
||||||
|
&& consoleReview.service_binding === "passed"
|
||||||
|
&& consoleReview.qps === "passed"
|
||||||
|
&& consoleReview.allowlist === "passed"
|
||||||
|
&& consoleReview.security_restriction === "passed"
|
||||||
|
&& consoleReview.paid_fallback === "disabled"
|
||||||
|
&& consoleReview.auto_scaling === "disabled";
|
||||||
|
|
||||||
|
const requiredBeforeRelease = [];
|
||||||
|
if (!probePassed) requiredBeforeRelease.push("real_location_and_reverse_geocode");
|
||||||
|
if (consoleReview.service_binding !== "passed") requiredBeforeRelease.push("service_binding");
|
||||||
|
if (consoleReview.qps !== "passed") requiredBeforeRelease.push("qps_confirmation");
|
||||||
|
if (consoleReview.allowlist !== "passed") requiredBeforeRelease.push("allowlist_confirmation");
|
||||||
|
if (consoleReview.security_restriction !== "passed") requiredBeforeRelease.push("security_restriction");
|
||||||
|
if (consoleReview.paid_fallback !== "disabled") requiredBeforeRelease.push("paid_fallback_disabled");
|
||||||
|
if (consoleReview.auto_scaling !== "disabled") requiredBeforeRelease.push("auto_scaling_disabled");
|
||||||
|
if (!hardStopPassed) requiredBeforeRelease.push("monthly_1000_hard_stop");
|
||||||
|
if (!productionAdapterPassed) requiredBeforeRelease.push("production_amap_adapter");
|
||||||
|
if (!consentPassed) requiredBeforeRelease.push("dyn004_confirmation");
|
||||||
|
if (!supervisorSecurityPassed) requiredBeforeRelease.push("controlled_probe_security");
|
||||||
|
|
||||||
|
const blocker = !automatedPassed
|
||||||
|
? "automated_regression_failed"
|
||||||
|
: !probePassed
|
||||||
|
? safeProbeCode
|
||||||
|
: !consoleReview.valid
|
||||||
|
? "manual_review_invalid"
|
||||||
|
: consoleReview.allowlist === "failed"
|
||||||
|
? "amap_allowlist_unconfigured"
|
||||||
|
: consoleReview.security_restriction === "failed"
|
||||||
|
? "amap_security_restriction_unconfigured"
|
||||||
|
: !manualReviewPassed
|
||||||
|
? "manual_acceptance_required"
|
||||||
|
: null;
|
||||||
|
const status = !automatedPassed ? "failed" : probePassed && manualReviewPassed ? "passed" : "externally_blocked";
|
||||||
|
|
||||||
|
const contractEvidence = {
|
||||||
|
blocker,
|
||||||
|
checks: {
|
||||||
|
allowlist: consoleReview.allowlist === "passed" ? "manual_console_passed" : consoleReview.allowlist,
|
||||||
|
auto_scaling: consoleReview.auto_scaling,
|
||||||
|
client_security_controls: productionAdapterPassed && supervisorSecurityPassed ? "automated_passed" : "failed",
|
||||||
|
controlled_probe_security: supervisorSecurityPassed ? "automated_passed" : "failed",
|
||||||
|
dyn004_hard_stop: consentPassed ? "confirmation_contract_passed" : "failed",
|
||||||
|
location_and_reverse_geocode: probePassed ? "real_probe_passed" : "not_verified",
|
||||||
|
monthly_hard_limit_1000: hardStopPassed ? "local_pre_egress_passed" : "failed",
|
||||||
|
paid_fallback: consoleReview.paid_fallback,
|
||||||
|
production_adapter: productionAdapterPassed ? "credential_channel_real_adapter_passed" : "failed",
|
||||||
|
provider_qps: consoleReview.qps === "passed" ? "manual_console_passed" : consoleReview.qps,
|
||||||
|
provider_qps_limit_per_second: consoleReview.qps_limit_per_second,
|
||||||
|
security_binding: consoleReview.security_restriction === "passed" ? "manual_console_passed" : consoleReview.security_restriction,
|
||||||
|
service_binding: consoleReview.service_binding === "passed" ? "manual_console_passed" : consoleReview.service_binding,
|
||||||
|
},
|
||||||
|
mode: probePassed ? "controlled_real" : "blocked",
|
||||||
|
real_calls: realCalls,
|
||||||
|
status,
|
||||||
|
schema_version: "1.1",
|
||||||
|
};
|
||||||
|
const externalCallsEvidence = {
|
||||||
|
blocker,
|
||||||
|
mode: probePassed ? "controlled_real" : "blocked",
|
||||||
|
real_calls: realCalls,
|
||||||
|
request_scope: ["geocoding", "reverse_geocoding"],
|
||||||
|
service: "amap",
|
||||||
|
source_command_status: safeProbeCode,
|
||||||
|
status,
|
||||||
|
schema_version: "1.1",
|
||||||
|
};
|
||||||
|
const manualReviewEvidence = {
|
||||||
|
blocker,
|
||||||
|
checks: {
|
||||||
|
allowlist: consoleReview.allowlist,
|
||||||
|
auto_scaling: consoleReview.auto_scaling,
|
||||||
|
paid_fallback: consoleReview.paid_fallback,
|
||||||
|
qps: consoleReview.qps,
|
||||||
|
qps_limit_per_second: consoleReview.qps_limit_per_second,
|
||||||
|
security_restriction: consoleReview.security_restriction,
|
||||||
|
service_binding: consoleReview.service_binding,
|
||||||
|
},
|
||||||
|
required_before_release: requiredBeforeRelease,
|
||||||
|
reviewed_at: consoleReview.reviewed_at,
|
||||||
|
source: consoleReview.source,
|
||||||
|
status,
|
||||||
|
schema_version: "1.1",
|
||||||
|
};
|
||||||
|
const result = {
|
||||||
|
acceptance_criteria: ["AC-17", "AC-41", "AC-47"],
|
||||||
|
automation: ["controlled_real", "manual_review"],
|
||||||
|
blocker,
|
||||||
|
contract_regression: automatedPassed ? "passed" : "failed",
|
||||||
|
external_calls: realCalls,
|
||||||
|
finished_at: new Date().toISOString(),
|
||||||
|
manifest: { path: "tasks.manifest.json", sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase() },
|
||||||
|
missing_evidence: requiredBeforeRelease,
|
||||||
|
parent_family: "TDD-WP7-EXT-003",
|
||||||
|
phase: "green",
|
||||||
|
release_gate: ["release:P0-A"],
|
||||||
|
requirements: ["DYN-04", "PRIV-03"],
|
||||||
|
run_id: runId,
|
||||||
|
schema_version: "1.1",
|
||||||
|
status,
|
||||||
|
task_id: "TASK-WP7-04",
|
||||||
|
test_id: "TDD-WP7-EXT-003-real-amap",
|
||||||
|
work_package: "WP-7",
|
||||||
|
};
|
||||||
|
const commandsEvidence = { commands, run_id: runId, schema_version: "1.1" };
|
||||||
|
const evidenceIndex = { cases: [{ status: result.status, test_id: result.test_id }], run_id: runId, status: result.status, schema_version: "1.1" };
|
||||||
|
const redactionInputs = [contractEvidence, externalCallsEvidence, manualReviewEvidence, result, commandsEvidence, evidenceIndex];
|
||||||
|
const evidenceRedactionPassed = !redactionInputs.some(containsForbiddenEvidence);
|
||||||
|
const redactionEvidence = {
|
||||||
|
findings: evidenceRedactionPassed ? [] : ["forbidden_evidence_field"],
|
||||||
|
forbidden_fields_present: !evidenceRedactionPassed,
|
||||||
|
source_security_scan: security.exit_code === 0 ? "passed" : "failed",
|
||||||
|
status: evidenceRedactionPassed && security.exit_code === 0 ? "passed" : "failed",
|
||||||
|
stored_fields: ["service", "status", "logical_limit", "manual_review_status", "qps_limit_per_second"],
|
||||||
|
schema_version: "1.1",
|
||||||
|
};
|
||||||
|
if (redactionEvidence.status !== "passed") {
|
||||||
|
result.status = "failed";
|
||||||
|
result.blocker = "redaction_failed";
|
||||||
|
evidenceIndex.status = "failed";
|
||||||
|
evidenceIndex.cases[0].status = "failed";
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJson(resolve(caseDirectory, "amap-contract.json"), contractEvidence);
|
||||||
|
writeJson(resolve(caseDirectory, "external-calls.json"), externalCallsEvidence);
|
||||||
|
writeJson(resolve(caseDirectory, "redaction.json"), redactionEvidence);
|
||||||
|
writeJson(resolve(caseDirectory, "manual-review.json"), manualReviewEvidence);
|
||||||
|
writeJson(resolve(caseDirectory, "commands.json"), commandsEvidence);
|
||||||
|
writeJson(resolve(caseDirectory, "result.json"), result);
|
||||||
|
writeJson(resolve(runDirectory, "evidence.json"), evidenceIndex);
|
||||||
|
console.log(JSON.stringify(result, null, 2));
|
||||||
|
if (result.status === "failed") process.exit(1);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { runWp705Gate } from './lib/wp7-05-ui-gate.mjs';
|
||||||
|
|
||||||
|
const result = runWp705Gate({
|
||||||
|
candidatePath: process.env.WP7_01_CANDIDATE_RECORD,
|
||||||
|
evidence: null,
|
||||||
|
dependencies: {
|
||||||
|
'TASK-WP7-03': 'externally_blocked',
|
||||||
|
'TASK-WP7-04': 'externally_blocked',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(JSON.stringify({ task: 'TASK-WP7-05', ...result }));
|
||||||
|
process.exitCode = result.status === 'ready_for_execution' ? 0 : 3;
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
|
||||||
|
import { validateTddTrace } from "./lib/tdd-trace.mjs";
|
||||||
|
import { buildWp706PrefreezeReport, REQUIRED_UPSTREAM } from "./lib/wp7-06-prefreeze.mjs";
|
||||||
|
|
||||||
|
const runId = process.env.DADA_TDD_RUN_ID ?? `wp7-06-prefreeze-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
|
||||||
|
const runDirectory = resolve("artifacts", "tdd", runId);
|
||||||
|
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP7-AC-001-trace-structure");
|
||||||
|
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
|
||||||
|
mkdirSync(caseDirectory, { recursive: true });
|
||||||
|
|
||||||
|
function writeJson(path, value) {
|
||||||
|
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function git(args) {
|
||||||
|
const result = spawnSync("git", args, { encoding: "utf8", timeout: 60_000 });
|
||||||
|
if ((result.status ?? 1) !== 0) throw new Error(`WP7_06_GIT_COMMAND_FAILED:${args[0]}`);
|
||||||
|
return result.stdout.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function runCommand(name, command) {
|
||||||
|
const startedAt = new Date().toISOString();
|
||||||
|
const result = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], {
|
||||||
|
encoding: "utf8",
|
||||||
|
env: process.env,
|
||||||
|
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,
|
||||||
|
finished_at: new Date().toISOString(),
|
||||||
|
name,
|
||||||
|
started_at: startedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const commands = [
|
||||||
|
runCommand("prefreeze-unit", "node --test tests/package/wp7-06-prefreeze.test.mjs"),
|
||||||
|
runCommand("tdd-trace", "pnpm validate:tdd-trace"),
|
||||||
|
];
|
||||||
|
if (commands.some((command) => command.exit_code !== 0)) {
|
||||||
|
writeJson(resolve(caseDirectory, "commands.json"), { commands, run_id: runId, schema_version: "1.0" });
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const trace = validateTddTrace();
|
||||||
|
const currentCommit = git(["rev-parse", "HEAD"]);
|
||||||
|
const remoteLines = git(["ls-remote", "--heads", "origin", "codex/wp7-01", "codex/wp7-02", "codex/wp7-03", "codex/wp7-04", "codex/wp7-05"])
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.filter(Boolean);
|
||||||
|
const remoteHeads = Object.fromEntries(remoteLines.map((line) => {
|
||||||
|
const [head, reference] = line.split(/\s+/);
|
||||||
|
return [reference.replace("refs/heads/", ""), head];
|
||||||
|
}));
|
||||||
|
const upstream = Object.fromEntries(Object.entries(REQUIRED_UPSTREAM).map(([taskId, status]) => {
|
||||||
|
const branch = taskId.replace("TASK-", "codex/").toLowerCase();
|
||||||
|
const head = remoteHeads[branch];
|
||||||
|
const ancestry = spawnSync("git", ["merge-base", "--is-ancestor", head ?? "missing", "HEAD"], { encoding: "utf8", timeout: 30_000 });
|
||||||
|
return [taskId, { branch, head, merged: ancestry.status === 0, status }];
|
||||||
|
}));
|
||||||
|
const report = buildWp706PrefreezeReport({
|
||||||
|
currentCommit,
|
||||||
|
releaseExists: existsSync(resolve("RELEASE.json")),
|
||||||
|
trace,
|
||||||
|
upstream,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
acceptance_criteria: Array.from({ length: 56 }, (_, index) => index + 1)
|
||||||
|
.filter((number) => ![8, 26, 37, 54].includes(number))
|
||||||
|
.map((number) => `AC-${String(number).padStart(2, "0")}`),
|
||||||
|
automation: ["automated", "manual_review"],
|
||||||
|
commit: currentCommit,
|
||||||
|
evidence_refs: ["commands.json", "trace-summary.json", "upstream-lineage.json", "deferred-external.json"],
|
||||||
|
finished_at: new Date().toISOString(),
|
||||||
|
manifest: {
|
||||||
|
path: "tasks.manifest.json",
|
||||||
|
sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase(),
|
||||||
|
},
|
||||||
|
missing_evidence: [],
|
||||||
|
release_gate: ["release:P0-A"],
|
||||||
|
requirements: ["NFR-05"],
|
||||||
|
run_id: runId,
|
||||||
|
schema_version: "1.0",
|
||||||
|
status: report.status,
|
||||||
|
task_id: "TASK-WP7-06",
|
||||||
|
test_id: "TDD-WP7-AC-001-trace-structure",
|
||||||
|
work_package: "WP-7",
|
||||||
|
};
|
||||||
|
|
||||||
|
writeJson(resolve(caseDirectory, "commands.json"), { commands, run_id: runId, schema_version: "1.0" });
|
||||||
|
writeJson(resolve(caseDirectory, "trace-summary.json"), { status: trace.status, summary: trace.summary, schema_version: "1.0" });
|
||||||
|
writeJson(resolve(caseDirectory, "upstream-lineage.json"), { current_commit: currentCommit, tasks: report.upstream, schema_version: "1.0" });
|
||||||
|
writeJson(resolve(caseDirectory, "deferred-external.json"), {
|
||||||
|
policy: "product_owner_first_version_nonblocking",
|
||||||
|
tasks: report.deferred_external_tasks,
|
||||||
|
treated_as_real_provider_pass: false,
|
||||||
|
schema_version: "1.0",
|
||||||
|
});
|
||||||
|
writeJson(resolve(caseDirectory, "result.json"), result);
|
||||||
|
writeJson(resolve(runDirectory, "evidence.json"), { cases: [{ missing_evidence: [], status: result.status, test_id: result.test_id }], run_id: runId, status: result.status, schema_version: "1.0" });
|
||||||
|
console.log(JSON.stringify({ deferred_external_tasks: report.deferred_external_tasks, next_task: report.next_task, run_id: runId, status: report.status }, null, 2));
|
||||||
@@ -38,6 +38,7 @@ internal static class Program
|
|||||||
{
|
{
|
||||||
var security = await TestCredentialBoundaryAsync();
|
var security = await TestCredentialBoundaryAsync();
|
||||||
var supervisor = await TestSupervisorLifecycleAsync();
|
var supervisor = await TestSupervisorLifecycleAsync();
|
||||||
|
await TestAmapProbeSecurityAsync();
|
||||||
TestSecureConfigurationPersistence();
|
TestSecureConfigurationPersistence();
|
||||||
TestStructuredLogging();
|
TestStructuredLogging();
|
||||||
WriteEvidence(Environment.GetEnvironmentVariable("DADA_EVIDENCE_DIR_SEC"), security);
|
WriteEvidence(Environment.GetEnvironmentVariable("DADA_EVIDENCE_DIR_SEC"), security);
|
||||||
@@ -52,6 +53,20 @@ internal static class Program
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task TestAmapProbeSecurityAsync()
|
||||||
|
{
|
||||||
|
using var handler = AmapProbe.CreateHandler();
|
||||||
|
False(handler.AllowAutoRedirect, "Amap probe redirects disabled");
|
||||||
|
Equal(1, handler.MaxConnectionsPerServer, "Amap probe per-server connection cap");
|
||||||
|
True(AmapProbe.IsAllowedEndpoint(new Uri("https://restapi.amap.com/v3/geocode/regeo")), "Amap fixed HTTPS endpoint accepted");
|
||||||
|
False(AmapProbe.IsAllowedEndpoint(new Uri("http://restapi.amap.com/v3/geocode/regeo")), "Amap HTTP endpoint rejected");
|
||||||
|
False(AmapProbe.IsAllowedEndpoint(new Uri("https://example.invalid/v3/geocode/regeo")), "Amap alternate host rejected");
|
||||||
|
using var oversized = new ByteArrayContent(new byte[AmapProbe.MaximumResponseBytes + 1]);
|
||||||
|
await ThrowsAsync<InvalidDataException>(
|
||||||
|
() => AmapProbe.ReadBoundedJsonAsync(oversized),
|
||||||
|
"Amap oversized response must be rejected before parsing");
|
||||||
|
}
|
||||||
|
|
||||||
private static void TestStructuredLogging()
|
private static void TestStructuredLogging()
|
||||||
{
|
{
|
||||||
Equal(10 * 1024 * 1024L, StructuredJsonlLogger.SizeLimitBytes, "Supervisor log byte limit");
|
Equal(10 * 1024 * 1024L, StructuredJsonlLogger.SizeLimitBytes, "Supervisor log byte limit");
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Dada.Supervisor;
|
||||||
|
|
||||||
|
internal static class AmapProbe
|
||||||
|
{
|
||||||
|
internal const int MaximumResponseBytes = 65_536;
|
||||||
|
private const string ProviderHostname = "restapi.amap.com";
|
||||||
|
private static readonly HttpClient Client = new(CreateHandler()) { Timeout = TimeSpan.FromSeconds(15) };
|
||||||
|
|
||||||
|
internal static SocketsHttpHandler CreateHandler() => new()
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
AutomaticDecompression = DecompressionMethods.None,
|
||||||
|
ConnectTimeout = TimeSpan.FromSeconds(10),
|
||||||
|
MaxConnectionsPerServer = 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
internal static bool IsAllowedEndpoint(Uri endpoint) =>
|
||||||
|
endpoint.Scheme == Uri.UriSchemeHttps
|
||||||
|
&& endpoint.Host.Equals(ProviderHostname, StringComparison.OrdinalIgnoreCase)
|
||||||
|
&& (endpoint.IsDefaultPort || endpoint.Port == 443)
|
||||||
|
&& string.IsNullOrEmpty(endpoint.UserInfo)
|
||||||
|
&& endpoint.AbsolutePath is "/v3/geocode/regeo" or "/v3/geocode/geo";
|
||||||
|
|
||||||
|
internal static int Run(string? key)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(key))
|
||||||
|
{
|
||||||
|
Write("amap_credentials_missing", false, 0, null, null);
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
var realCalls = 0;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
realCalls += 1;
|
||||||
|
var reverse = Call("https://restapi.amap.com/v3/geocode/regeo?location=120.6994,27.9943&extensions=base", key).GetAwaiter().GetResult();
|
||||||
|
realCalls += 1;
|
||||||
|
var geocode = Call($"https://restapi.amap.com/v3/geocode/geo?address={Uri.EscapeDataString("北京市天安门")}", key).GetAwaiter().GetResult();
|
||||||
|
var success = reverse.Status == "1" && geocode.Status == "1";
|
||||||
|
Write(success ? "amap_probe_passed" : "amap_provider_rejected", success, realCalls, reverse.Status, geocode.Status);
|
||||||
|
return success ? 0 : 3;
|
||||||
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
Write("amap_probe_timeout", false, realCalls, null, null);
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
catch (HttpRequestException exception)
|
||||||
|
{
|
||||||
|
Write($"amap_probe_network_{exception.StatusCode?.ToString() ?? "error"}", false, realCalls, null, null);
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
catch (Exception exception) when (exception is JsonException or InvalidDataException)
|
||||||
|
{
|
||||||
|
Write("amap_probe_invalid_response", false, realCalls, null, null);
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<ProbeResponse> Call(string endpoint, string key)
|
||||||
|
{
|
||||||
|
var requestUri = new Uri($"{endpoint}&key={Uri.EscapeDataString(key)}", UriKind.Absolute);
|
||||||
|
if (!IsAllowedEndpoint(requestUri)) throw new InvalidDataException("amap_endpoint_rejected");
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
|
||||||
|
using var response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
using var document = await ReadBoundedJsonAsync(response.Content);
|
||||||
|
var root = document.RootElement;
|
||||||
|
return new ProbeResponse(root.GetProperty("status").GetString() ?? "", root.TryGetProperty("infocode", out var code) ? code.GetString() : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static async Task<JsonDocument> ReadBoundedJsonAsync(HttpContent content)
|
||||||
|
{
|
||||||
|
if (content.Headers.ContentLength is > MaximumResponseBytes) throw new InvalidDataException("amap_response_too_large");
|
||||||
|
await using var stream = await content.ReadAsStreamAsync();
|
||||||
|
using var buffered = new MemoryStream();
|
||||||
|
var buffer = ArrayPool<byte>.Shared.Rent(4_096);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var total = 0;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var read = await stream.ReadAsync(buffer);
|
||||||
|
if (read == 0) break;
|
||||||
|
total += read;
|
||||||
|
if (total > MaximumResponseBytes) throw new InvalidDataException("amap_response_too_large");
|
||||||
|
await buffered.WriteAsync(buffer.AsMemory(0, read));
|
||||||
|
}
|
||||||
|
buffered.Position = 0;
|
||||||
|
return await JsonDocument.ParseAsync(buffered);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Array.Clear(buffer);
|
||||||
|
ArrayPool<byte>.Shared.Return(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Write(string code, bool success, int realCalls, string? reverseStatus, string? geocodeStatus) =>
|
||||||
|
Console.WriteLine(JsonSerializer.Serialize(new { code, success, real_calls = realCalls, reverse_status = reverseStatus, geocode_status = geocodeStatus }));
|
||||||
|
|
||||||
|
private sealed record ProbeResponse(string Status, string? InfoCode);
|
||||||
|
}
|
||||||
@@ -84,6 +84,8 @@ internal static class OfflineCommandRouter
|
|||||||
store.Write(target, value);
|
store.Write(target, value);
|
||||||
WriteResult("credential_saved", true);
|
WriteResult("credential_saved", true);
|
||||||
return 0;
|
return 0;
|
||||||
|
case "probe" when target == CredentialCatalog.ApiAmap:
|
||||||
|
return AmapProbe.Run(store.Read(target));
|
||||||
default:
|
default:
|
||||||
return Usage();
|
return Usage();
|
||||||
}
|
}
|
||||||
@@ -199,7 +201,7 @@ internal static class OfflineCommandRouter
|
|||||||
|
|
||||||
private static int Usage()
|
private static int Usage()
|
||||||
{
|
{
|
||||||
WriteResult("usage: configure init|data-root|asset-root; secrets set|status|clear; admin-allowlist add|remove|status; doctor; validate-external", false);
|
WriteResult("usage: configure init|data-root|asset-root; secrets set|status|clear|probe; admin-allowlist add|remove|status; doctor; validate-external", false);
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { RealAmapAdapter } from "../../apps/api/src/amap-adapter.js";
|
||||||
|
import { initializeApiCredentialClients } from "../../apps/api/src/supervisor-channel.js";
|
||||||
|
|
||||||
|
describe("TDD-WP7-EXT-003 production Amap adapter", () => {
|
||||||
|
it("uses the fixed HTTPS provider boundary and returns only the formatted location", async () => {
|
||||||
|
const request = vi.fn(async () => ({
|
||||||
|
regeocode: { formatted_address: "模拟省模拟市" },
|
||||||
|
status: "1",
|
||||||
|
}));
|
||||||
|
const adapter = new RealAmapAdapter("fixture-amap-value", { request });
|
||||||
|
|
||||||
|
await expect(adapter.reverseGeocode({ latitude: 12.3456, longitude: 65.4321 })).resolves.toEqual({
|
||||||
|
formattedValue: "模拟省模拟市",
|
||||||
|
serviceMode: "real",
|
||||||
|
});
|
||||||
|
expect(request).toHaveBeenCalledOnce();
|
||||||
|
expect(request.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
allowRedirects: false,
|
||||||
|
hostname: "restapi.amap.com",
|
||||||
|
maxResponseBytes: 65_536,
|
||||||
|
method: "GET",
|
||||||
|
protocol: "https:",
|
||||||
|
rejectUnauthorized: true,
|
||||||
|
timeoutMs: 15_000,
|
||||||
|
});
|
||||||
|
expect(request.mock.calls[0]?.[0].path).toContain("/v3/geocode/regeo?");
|
||||||
|
expect(request.mock.calls[0]?.[0].path).toContain("location=65.4321%2C12.3456");
|
||||||
|
adapter.dispose();
|
||||||
|
await expect(adapter.reverseGeocode({ latitude: 0, longitude: 0 })).rejects.toThrow("amap_adapter_disposed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("constructs the real client from the API credential channel and clears the source values", () => {
|
||||||
|
const credentials = {
|
||||||
|
"Dada/P0A/admin/pepper": "fixture-admin-value",
|
||||||
|
"Dada/P0A/api/amap": "fixture-amap-value",
|
||||||
|
"Dada/P0A/api/resend": "fixture-resend-value",
|
||||||
|
};
|
||||||
|
|
||||||
|
const clients = initializeApiCredentialClients(credentials);
|
||||||
|
expect(clients.amap).toBeInstanceOf(RealAmapAdapter);
|
||||||
|
expect(Object.values(credentials)).toEqual(["", "", ""]);
|
||||||
|
clients.amap.dispose();
|
||||||
|
clients.adminAllowlistPepper.fill(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { MockAmapAdapter } from "../../apps/api/src/amap-adapter.js";
|
||||||
|
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";
|
||||||
|
|
||||||
|
const roots: string[] = [];
|
||||||
|
const registrations: RegistrationService[] = [];
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const registration of registrations.splice(0)) registration.close();
|
||||||
|
for (const root of roots.splice(0)) rmSync(root, { force: true, recursive: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function createRegistration() {
|
||||||
|
const now = Date.parse("2026-08-04T09:00:00.000Z");
|
||||||
|
const root = mkdtempSync(join(tmpdir(), "dada-wp7-04-amap-"));
|
||||||
|
roots.push(root);
|
||||||
|
const registration = new RegistrationService({
|
||||||
|
challengePepper: Buffer.alloc(32, 0xa1),
|
||||||
|
clock: () => now,
|
||||||
|
currentPrivacyNoticeVersion: "p0a-registration-notice-v1",
|
||||||
|
databasePath: join(root, "dada.sqlite3"),
|
||||||
|
invitePepper: Buffer.alloc(32, 0xa2),
|
||||||
|
resend: new MockResendAdapter(),
|
||||||
|
sessionPepper: Buffer.alloc(32, 0xa3),
|
||||||
|
});
|
||||||
|
registrations.push(registration);
|
||||||
|
|
||||||
|
const userId = randomUUID();
|
||||||
|
registration.database.prepare(`
|
||||||
|
INSERT INTO users (user_id, normalized_email, role, status, counts_toward_stage_limit, registration_id, created_at)
|
||||||
|
VALUES (?, ?, 'user', 'active', 1, ?, ?)
|
||||||
|
`).run(userId, `${userId}@example.invalid`, randomUUID(), now);
|
||||||
|
registration.database.prepare("INSERT INTO user_profiles (user_id, creator_name, social_id) VALUES (?, 'Release Gate User', '@release_gate')").run(userId);
|
||||||
|
registration.database.prepare("INSERT INTO credit_accounts (user_id, available_balance, reserved_balance, updated_at) VALUES (?, 10, 0, ?)").run(userId, now);
|
||||||
|
return { registration, session: registration.issueAuthenticatedSession(userId, "user") };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("TDD-WP7-EXT-003 Amap release hard stop", () => {
|
||||||
|
it("admits the simulated 1000th request and blocks the 1001st before provider egress", async () => {
|
||||||
|
const { registration, session } = createRegistration();
|
||||||
|
registration.database.prepare(`
|
||||||
|
UPDATE external_service_usage
|
||||||
|
SET used_count = 999, service_status = 'active', pause_reason = NULL
|
||||||
|
WHERE service_id = 'amap_web_service' AND period_type = 'monthly'
|
||||||
|
`).run();
|
||||||
|
|
||||||
|
const amap = new MockAmapAdapter();
|
||||||
|
const app = await createApp({ amap, browserGate: false, networkBoundary: { allowTestPort: true }, registration });
|
||||||
|
const headers = {
|
||||||
|
cookie: `dada_session=${session.sessionToken}`,
|
||||||
|
host: "127.0.0.1:43121",
|
||||||
|
origin: "http://127.0.0.1:43121",
|
||||||
|
"x-csrf-token": registration.issueUserCsrfToken(session.sessionToken),
|
||||||
|
};
|
||||||
|
|
||||||
|
const thousandth = await app.inject({
|
||||||
|
headers,
|
||||||
|
method: "POST",
|
||||||
|
payload: { latitude: 0, longitude: 0 },
|
||||||
|
url: "/api/v1/location/reverse-geocode",
|
||||||
|
});
|
||||||
|
const thousandAndFirst = await app.inject({
|
||||||
|
headers,
|
||||||
|
method: "POST",
|
||||||
|
payload: { latitude: 0, longitude: 0 },
|
||||||
|
url: "/api/v1/location/reverse-geocode",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(thousandth.statusCode).toBe(200);
|
||||||
|
expect(thousandAndFirst.statusCode).toBe(503);
|
||||||
|
expect(amap.calls).toHaveLength(1);
|
||||||
|
expect(registration.serviceUsage.read("amap_web_service")).toEqual([
|
||||||
|
expect.objectContaining({ hardLimit: 1_000, status: "paused_quota", usedCount: 1_000 }),
|
||||||
|
]);
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
|
||||||
|
import {
|
||||||
|
validateAuthResult,
|
||||||
|
validateDeliverySummary,
|
||||||
|
validateDomainCheck,
|
||||||
|
validateRedaction,
|
||||||
|
} from "../../scripts/lib/resend-release-gate.mjs";
|
||||||
|
|
||||||
|
const realEvidence = {
|
||||||
|
source: "human_controlled_real",
|
||||||
|
service: "resend",
|
||||||
|
status: "verified",
|
||||||
|
schema_version: "1.0",
|
||||||
|
};
|
||||||
|
|
||||||
|
test("requires SPF, DKIM, exact free limits, and no paid fallback", () => {
|
||||||
|
assert.deepEqual(validateDomainCheck({
|
||||||
|
...realEvidence,
|
||||||
|
dkim: { status: "pass" },
|
||||||
|
domain_controlled: true,
|
||||||
|
free_rules: { daily_limit: 80, monthly_limit: 2400, paid_fallback_enabled: false, status: "verified" },
|
||||||
|
spf: { status: "pass" },
|
||||||
|
}), []);
|
||||||
|
assert.ok(validateDomainCheck({ ...realEvidence, domain_controlled: true, spf: { status: "pass" }, dkim: { status: "fail" }, free_rules: { status: "unknown" } }).includes("dkim"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires exactly three 20-message delivery cohorts with 19 within 120 seconds", () => {
|
||||||
|
const summary = {
|
||||||
|
...realEvidence,
|
||||||
|
categories: ["qq", "163", "enterprise"].map((category) => ({
|
||||||
|
category,
|
||||||
|
delivered_within_120_seconds: 19,
|
||||||
|
max_latency_seconds: 120,
|
||||||
|
mock_used: false,
|
||||||
|
preseeded_account_used: false,
|
||||||
|
sent_count: 20,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
assert.deepEqual(validateDeliverySummary(summary), []);
|
||||||
|
assert.ok(validateDeliverySummary({ ...summary, categories: summary.categories.map((item) => item.category === "163" ? { ...item, delivered_within_120_seconds: 18 } : item) }).some((error) => error.includes("163")));
|
||||||
|
assert.ok(validateDeliverySummary({ ...summary, categories: summary.categories.map((item) => item.category === "enterprise" ? { ...item, max_latency_seconds: undefined } : item) }).some((error) => error.includes("enterprise")));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("requires formal ordinary and admin authentication chains", () => {
|
||||||
|
assert.deepEqual(validateAuthResult({
|
||||||
|
...realEvidence,
|
||||||
|
admin: { chain: "formal", status: "passed", verification_code_source: "real_delivery" },
|
||||||
|
mock_used: false,
|
||||||
|
ordinary: { chain: "formal", status: "passed", verification_code_source: "real_delivery" },
|
||||||
|
preseeded_account_used: false,
|
||||||
|
}), []);
|
||||||
|
assert.ok(validateAuthResult({ ...realEvidence, admin: { chain: "mock", status: "passed", verification_code_source: "fixture" }, ordinary: { status: "failed" } }).length > 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects credentials, mailboxes, private values, and paths from evidence", () => {
|
||||||
|
assert.deepEqual(validateRedaction({
|
||||||
|
absolute_paths_in_evidence: false,
|
||||||
|
credentials_in_evidence: false,
|
||||||
|
forbidden_matches: 0,
|
||||||
|
mailboxes_in_evidence: false,
|
||||||
|
private_content_in_evidence: false,
|
||||||
|
schema_version: "1.0",
|
||||||
|
status: "passed",
|
||||||
|
}, JSON.stringify({ category: "qq", delivered_within_120_seconds: 20 })), []);
|
||||||
|
assert.ok(validateRedaction({
|
||||||
|
absolute_paths_in_evidence: false,
|
||||||
|
credentials_in_evidence: false,
|
||||||
|
forbidden_matches: 0,
|
||||||
|
mailboxes_in_evidence: false,
|
||||||
|
private_content_in_evidence: false,
|
||||||
|
schema_version: "1.0",
|
||||||
|
status: "passed",
|
||||||
|
}, JSON.stringify({ mailbox: "recipient@example.invalid" })).includes("email_value"));
|
||||||
|
});
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { buildCoverageEvidence } from '../../scripts/lib/wp7-05-coverage.mjs';
|
||||||
|
import { REQUIRED_COVERAGE_UNITS } from '../../scripts/lib/wp7-05-ui-gate.mjs';
|
||||||
|
|
||||||
|
const viewports = [
|
||||||
|
{ width: 1920, height: 1080, deviceScaleFactor: 1, zoom: 100 },
|
||||||
|
{ width: 1920, height: 1080, deviceScaleFactor: 1, zoom: 200 },
|
||||||
|
];
|
||||||
|
|
||||||
|
function completeUnits() {
|
||||||
|
return REQUIRED_COVERAGE_UNITS.map((page_id) => ({
|
||||||
|
page_id,
|
||||||
|
states: [{
|
||||||
|
state: 'normal',
|
||||||
|
screenshot_100pct: `ui/${page_id}/normal/100pct.png`,
|
||||||
|
screenshot_200pct: `ui/${page_id}/normal/200pct.png`,
|
||||||
|
trace: `ui/${page_id}/normal/trace.zip`,
|
||||||
|
}],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
test('builds ordered, sanitized evidence for all 22 coverage units', () => {
|
||||||
|
const evidence = buildCoverageEvidence({
|
||||||
|
runId: 'wp7-05-red-001',
|
||||||
|
candidateSha256: 'a'.repeat(64),
|
||||||
|
coverageUnits: completeUnits(),
|
||||||
|
viewports,
|
||||||
|
});
|
||||||
|
assert.equal(evidence.coverage_units.length, 22);
|
||||||
|
assert.equal(evidence.coverage_units[0].page_id, 'support-gate');
|
||||||
|
assert.equal(evidence.candidate_sha256, 'A'.repeat(64));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects absolute evidence paths and incomplete page state', () => {
|
||||||
|
const units = completeUnits();
|
||||||
|
units[0].states[0].trace = 'C:\\secret\\trace.zip';
|
||||||
|
assert.throws(() => buildCoverageEvidence({
|
||||||
|
runId: 'wp7-05-red-001', candidateSha256: 'a'.repeat(64), coverageUnits: units, viewports,
|
||||||
|
}), /WP7_05_UNSAFE_TRACE/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { loadCandidateRecord, validateCoverageEvidence, runWp705Gate, REQUIRED_COVERAGE_UNITS } from '../../scripts/lib/wp7-05-ui-gate.mjs';
|
||||||
|
|
||||||
|
test('WP7-05 accepts the WP7-01 candidate record schema', () => {
|
||||||
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wp7-05-'));
|
||||||
|
const file = path.join(directory, 'release-candidate.json');
|
||||||
|
fs.writeFileSync(file, JSON.stringify({
|
||||||
|
browsers: [
|
||||||
|
{ brand: 'Google Chrome', full_version: '150.0.0', major: 150 },
|
||||||
|
{ brand: 'Microsoft Edge', full_version: '151.0.0', major: 151 },
|
||||||
|
],
|
||||||
|
windows: { build: '26200.8875' },
|
||||||
|
candidate_package: { fixed_port: 43121, sha256: 'A'.repeat(64) },
|
||||||
|
}));
|
||||||
|
assert.equal(loadCandidateRecord(file).status, 'ready');
|
||||||
|
fs.rmSync(directory, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WP7-05 requires all 22 coverage units and both exact candidate viewports', () => {
|
||||||
|
const result = validateCoverageEvidence({ coverage_units: [], viewports: [] });
|
||||||
|
assert.equal(result.status, 'externally_blocked');
|
||||||
|
assert.equal(result.code, 'coverage_units_incomplete');
|
||||||
|
assert.equal(result.missing.length, REQUIRED_COVERAGE_UNITS.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WP7-05 requires state evidence for every listed coverage unit', () => {
|
||||||
|
const result = validateCoverageEvidence({
|
||||||
|
coverage_units: REQUIRED_COVERAGE_UNITS.map((page_id) => ({ page_id, states: [] })),
|
||||||
|
viewports: [],
|
||||||
|
});
|
||||||
|
assert.equal(result.code, 'coverage_states_incomplete');
|
||||||
|
assert.equal(result.missingStates.length, REQUIRED_COVERAGE_UNITS.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('WP7-05 preserves upstream external blockers instead of declaring Green', () => {
|
||||||
|
const result = runWp705Gate({
|
||||||
|
candidatePath: 'missing-release-candidate.json',
|
||||||
|
evidence: null,
|
||||||
|
dependencies: { 'TASK-WP7-03': 'externally_blocked' },
|
||||||
|
});
|
||||||
|
assert.equal(result.status, 'externally_blocked');
|
||||||
|
assert.equal(result.code, 'candidate_record_missing');
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
import { buildWp706PrefreezeReport } from "../../scripts/lib/wp7-06-prefreeze.mjs";
|
||||||
|
|
||||||
|
const expectedTrace = {
|
||||||
|
errors: [],
|
||||||
|
status: "passed",
|
||||||
|
summary: {
|
||||||
|
acceptanceCriteria: 52,
|
||||||
|
errorCategories: 9,
|
||||||
|
featureModules: 13,
|
||||||
|
parentFamilies: 89,
|
||||||
|
penProductFrames: 18,
|
||||||
|
productContracts: 19,
|
||||||
|
requirements: 109,
|
||||||
|
tasks: 52,
|
||||||
|
testCases: 117,
|
||||||
|
uiPages: 22,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const upstream = {
|
||||||
|
"TASK-WP7-01": { branch: "codex/wp7-01", head: "1".repeat(40), merged: true, status: "passed" },
|
||||||
|
"TASK-WP7-02": { branch: "codex/wp7-02", head: "2".repeat(40), merged: true, status: "passed" },
|
||||||
|
"TASK-WP7-03": { branch: "codex/wp7-03", head: "3".repeat(40), merged: true, status: "deferred_nonblocking_first_version" },
|
||||||
|
"TASK-WP7-04": { branch: "codex/wp7-04", head: "4".repeat(40), merged: true, status: "deferred_nonblocking_first_version" },
|
||||||
|
"TASK-WP7-05": { branch: "codex/wp7-05", head: "5".repeat(40), merged: true, status: "passed" },
|
||||||
|
};
|
||||||
|
|
||||||
|
test("builds the exact WP7-06 pre-freeze closure without pretending deferred suppliers passed", () => {
|
||||||
|
const report = buildWp706PrefreezeReport({
|
||||||
|
currentCommit: "a".repeat(40),
|
||||||
|
releaseExists: false,
|
||||||
|
trace: expectedTrace,
|
||||||
|
upstream,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(report.status, "passed");
|
||||||
|
assert.equal(report.release_json_written, false);
|
||||||
|
assert.deepEqual(report.trace_summary, expectedTrace.summary);
|
||||||
|
assert.deepEqual(report.deferred_external_tasks, ["TASK-WP7-03", "TASK-WP7-04"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects missing lineage and premature RELEASE.json", () => {
|
||||||
|
assert.throws(() => buildWp706PrefreezeReport({
|
||||||
|
currentCommit: "a".repeat(40),
|
||||||
|
releaseExists: false,
|
||||||
|
trace: expectedTrace,
|
||||||
|
upstream: { ...upstream, "TASK-WP7-05": { ...upstream["TASK-WP7-05"], merged: false } },
|
||||||
|
}), /WP7_06_UPSTREAM_NOT_MERGED:TASK-WP7-05/);
|
||||||
|
|
||||||
|
assert.throws(() => buildWp706PrefreezeReport({
|
||||||
|
currentCommit: "a".repeat(40),
|
||||||
|
releaseExists: true,
|
||||||
|
trace: expectedTrace,
|
||||||
|
upstream,
|
||||||
|
}), /WP7_06_RELEASE_WRITTEN_PREMATURELY/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects trace drift and unsupported upstream statuses", () => {
|
||||||
|
assert.throws(() => buildWp706PrefreezeReport({
|
||||||
|
currentCommit: "a".repeat(40),
|
||||||
|
releaseExists: false,
|
||||||
|
trace: { ...expectedTrace, summary: { ...expectedTrace.summary, testCases: 116 } },
|
||||||
|
upstream,
|
||||||
|
}), /WP7_06_TRACE_COUNT_MISMATCH:testCases/);
|
||||||
|
|
||||||
|
assert.throws(() => buildWp706PrefreezeReport({
|
||||||
|
currentCommit: "a".repeat(40),
|
||||||
|
releaseExists: false,
|
||||||
|
trace: expectedTrace,
|
||||||
|
upstream: { ...upstream, "TASK-WP7-03": { ...upstream["TASK-WP7-03"], status: "passed" } },
|
||||||
|
}), /WP7_06_UNSUPPORTED_STATUS:TASK-WP7-03/);
|
||||||
|
});
|
||||||
@@ -190,6 +190,27 @@ describe("TDD-WP5-MAN-001 readonly asset compiler", () => {
|
|||||||
expect(repeated.report.derived_files).toEqual({ created: 0, reused: 4, total: 4 });
|
expect(repeated.report.derived_files).toEqual({ created: 0, reused: 4, total: 4 });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("safely relocates legacy absolute font package paths after an archive move", () => {
|
||||||
|
const fixture = createFixture();
|
||||||
|
const catalogPath = join(fixture.sourceRoot, "fonts", "reports", "font_panel_catalog.csv");
|
||||||
|
const metadata = JSON.parse(readFileSync(join(fixture.sourceRoot, "fonts", "resources", "font_packages", "FONT001_Test", "metadata.json"), "utf8")) as { local_sha256: string };
|
||||||
|
csv(catalogPath, [{
|
||||||
|
candidate_id: "FONT001",
|
||||||
|
display_name: "Test Font",
|
||||||
|
font_family: "Dada Test",
|
||||||
|
local_sha256: metadata.local_sha256,
|
||||||
|
panel_order: "1",
|
||||||
|
resource_dir: "C:/Users/legacy/Desktop/sticker_text/fonts/resources/font_packages/FONT001_Test",
|
||||||
|
resource_status: "verified_extracted",
|
||||||
|
}]);
|
||||||
|
|
||||||
|
expect(() => compileAssetArchive({
|
||||||
|
manifestPath: fixture.manifestPath,
|
||||||
|
outputDirectory: fixture.outputRoot,
|
||||||
|
releaseVersion: "fixture-v1",
|
||||||
|
})).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
it("rejects evidence collections, traversal and output inside a source root", () => {
|
it("rejects evidence collections, traversal and output inside a source root", () => {
|
||||||
const fixture = createFixture();
|
const fixture = createFixture();
|
||||||
const manifest = JSON.parse(readFileSync(fixture.manifestPath, "utf8")) as { collections: unknown[] };
|
const manifest = JSON.parse(readFileSync(fixture.manifestPath, "utf8")) as { collections: unknown[] };
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||||
|
|
||||||
import { WP4_07_REAL_RESOURCE_VERSIONS } from "./wp4-07-fixture.mjs";
|
import { WP4_07_REAL_RESOURCE_VERSIONS } from "./wp4-07-fixture.mjs";
|
||||||
|
|
||||||
@@ -74,15 +74,16 @@ function assetRecord(assetId, path, sourceReference, expectedSha256) {
|
|||||||
export function loadWp407RealAssets() {
|
export function loadWp407RealAssets() {
|
||||||
const manifestPath = resolve(process.env.DADA_WP4_07_FINAL_ASSET_MANIFEST ?? "");
|
const manifestPath = resolve(process.env.DADA_WP4_07_FINAL_ASSET_MANIFEST ?? "");
|
||||||
if (!process.env.DADA_WP4_07_FINAL_ASSET_MANIFEST || !existsSync(manifestPath)) throw new Error("WP4_07_FINAL_ASSET_MANIFEST_REQUIRED");
|
if (!process.env.DADA_WP4_07_FINAL_ASSET_MANIFEST || !existsSync(manifestPath)) throw new Error("WP4_07_FINAL_ASSET_MANIFEST_REQUIRED");
|
||||||
const handoffPath = resolve(process.env.DADA_COMPLEX_ASSET_MANIFEST ?? join(homedir(), "Desktop", "sticker_web_handoff", "sticker_web_catalog_manifest.json"));
|
const replicationRoot = resolve(process.env.DADA_REPLICATION_ASSET_ROOT ?? join(homedir(), "Desktop", "sticker_web_replication_assets"));
|
||||||
const staticRoot = resolve(process.env.DADA_STATIC_STICKER_ROOT ?? join(homedir(), "Desktop", "贴纸素材"));
|
const handoffPath = resolve(process.env.DADA_COMPLEX_ASSET_MANIFEST ?? join(replicationRoot, "sticker_web_handoff", "sticker_web_catalog_manifest.json"));
|
||||||
|
const staticRoot = resolve(process.env.DADA_STATIC_STICKER_ROOT ?? join(replicationRoot, "sticker_normal"));
|
||||||
const backgroundPath = resolve(process.env.DADA_WP4_07_BACKGROUND_PATH ?? join(homedir(), "Documents", "贴纸脚本", "time_01_input_20260716.png"));
|
const backgroundPath = resolve(process.env.DADA_WP4_07_BACKGROUND_PATH ?? join(homedir(), "Documents", "贴纸脚本", "time_01_input_20260716.png"));
|
||||||
if (!existsSync(handoffPath) || !existsSync(staticRoot)) throw new Error("WP4_07_REAL_ARCHIVE_ROOT_REQUIRED");
|
if (!existsSync(handoffPath) || !existsSync(staticRoot)) throw new Error("WP4_07_REAL_ARCHIVE_ROOT_REQUIRED");
|
||||||
|
|
||||||
const manifestRaw = readFileSync(manifestPath, "utf8");
|
const manifestRaw = readFileSync(manifestPath, "utf8");
|
||||||
const manifest = JSON.parse(manifestRaw);
|
const manifest = JSON.parse(manifestRaw);
|
||||||
const handoff = JSON.parse(readFileSync(handoffPath, "utf8"));
|
const handoff = JSON.parse(readFileSync(handoffPath, "utf8"));
|
||||||
const collectionRoots = Object.fromEntries(handoff.collections.map((collection) => [collection.id, resolve(collection.root)]));
|
const collectionRoots = Object.fromEntries(handoff.collections.map((collection) => [collection.id, resolve(dirname(handoffPath), collection.root)]));
|
||||||
const fontRoot = collectionRoots.font_panel;
|
const fontRoot = collectionRoots.font_panel;
|
||||||
const dynamicRoot = collectionRoots.interactive_stickers;
|
const dynamicRoot = collectionRoots.interactive_stickers;
|
||||||
if (!fontRoot || !dynamicRoot) throw new Error("WP4_07_REAL_ARCHIVE_COLLECTION_REQUIRED");
|
if (!fontRoot || !dynamicRoot) throw new Error("WP4_07_REAL_ARCHIVE_COLLECTION_REQUIRED");
|
||||||
|
|||||||
Reference in New Issue
Block a user