Files
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

228 lines
7.1 KiB
TypeScript

/**
* Worker-targeted e2e API client.
*
* Configuration (env):
* TEST_API_BASE_URL — defaults to TEST_BASE_URL, then http://localhost:8787
* (wrangler dev). Set this to point tests at a running
* Worker.
* TEST_API_KEY — bootstrapped by `ensureLocalTestAuth()` in preload.
* CRON_SECRET — for cron-route tests; defaults to "test-cron-secret".
* TEST_REQUEST_TIMEOUT_MS — per-request timeout; defaults to 30000.
*
* The helpers throw if you call them before `ensureLocalTestAuth()` has run.
* The preload is `packages/cloud/api/test/e2e/preload.ts`, which seeds
* the DB and exports `TEST_API_KEY`.
*/
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
function resolveRequestTimeoutMs(): number {
const parsed = Number(process.env.TEST_REQUEST_TIMEOUT_MS);
return Number.isFinite(parsed) && parsed > 0
? parsed
: DEFAULT_REQUEST_TIMEOUT_MS;
}
const REQUEST_TIMEOUT_MS = resolveRequestTimeoutMs();
export function getBaseUrl(): string {
return (
process.env.TEST_API_BASE_URL?.trim() ||
process.env.TEST_BASE_URL?.trim() ||
"http://localhost:8787"
);
}
export function url(path: string): string {
return `${getBaseUrl()}${path}`;
}
/**
* True when the e2e target is a LOCAL dev Worker (which shares our `.env`, so
* INTERNAL_SECRET / test-only routes line up). Against a DEPLOYED target
* (staging/prod) the Worker's INTERNAL_SECRET is a server-side secret we can't
* supply, so internal-bearer-authenticated tests must skip rather than fail.
* The unauthenticated 401 auth-gate assertions still run everywhere.
*/
export function isLocalTarget(): boolean {
return /\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:|\/|$)/.test(getBaseUrl());
}
function timeoutSignal(): AbortSignal {
return AbortSignal.timeout(REQUEST_TIMEOUT_MS);
}
export function getApiKey(): string {
const key = process.env.TEST_API_KEY?.trim();
if (!key) {
throw new Error(
"TEST_API_KEY is not set. Run with the e2e preload " +
"(packages/cloud/api/test/e2e/preload.ts) so ensureLocalTestAuth() seeds the DB " +
"and exports the bootstrapped key.",
);
}
return key;
}
export function getMemberApiKey(): string {
const key = process.env.TEST_MEMBER_API_KEY?.trim();
if (!key) {
throw new Error(
"TEST_MEMBER_API_KEY is not set. Run with the e2e preload " +
"(packages/cloud/api/test/e2e/preload.ts) so ensureLocalTestAuth() seeds the DB " +
"and exports the bootstrapped member key.",
);
}
return key;
}
export function bearerHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${getApiKey()}`,
"Content-Type": "application/json",
};
}
export function memberBearerHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${getMemberApiKey()}`,
"Content-Type": "application/json",
};
}
export function getAffiliateApiKey(): string {
// Fall back to the regular bootstrapped key when the preload didn't seed a
// separate affiliate user — the affiliate group reuses the same auth path.
const key =
process.env.TEST_AFFILIATE_API_KEY?.trim() ??
process.env.TEST_API_KEY?.trim();
if (!key) {
throw new Error(
"TEST_AFFILIATE_API_KEY (or TEST_API_KEY) is not set. Run with the e2e preload " +
"(packages/cloud/api/test/e2e/preload.ts) so ensureLocalTestAuth() seeds the DB " +
"and exports the bootstrapped affiliate key.",
);
}
return key;
}
export function affiliateBearerHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${getAffiliateApiKey()}`,
"Content-Type": "application/json",
};
}
export function apiKeyHeaders(): Record<string, string> {
return {
"X-API-Key": getApiKey(),
"Content-Type": "application/json",
};
}
export function cronHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${process.env.CRON_SECRET ?? "test-cron-secret"}`,
"Content-Type": "application/json",
};
}
export interface FetchOptions {
headers?: Record<string, string>;
body?: unknown;
}
async function request(
method: string,
path: string,
opts: FetchOptions = {},
): Promise<Response> {
const init: RequestInit = {
method,
signal: timeoutSignal(),
headers: opts.headers ?? {},
};
if (opts.body !== undefined) {
(init.headers as Record<string, string>)["Content-Type"] ??=
"application/json";
init.body =
typeof opts.body === "string" ? opts.body : JSON.stringify(opts.body);
}
const res = await fetch(url(path), init);
recordStatus(method, path, res.status);
return res;
}
/**
* Optional per-request status recorder for contract audits: set
* E2E_STATUS_LOG=<file> to append one `METHOD path -> status` line per
* request. No-op when unset.
*/
function recordStatus(method: string, path: string, status: number): void {
const logPath = process.env.E2E_STATUS_LOG;
if (!logPath) return;
const { appendFileSync } = require("node:fs") as typeof import("node:fs");
appendFileSync(logPath, `${method} ${path} -> ${status}\n`);
}
export const api = {
get: (path: string, opts?: FetchOptions) => request("GET", path, opts),
post: (path: string, body?: unknown, opts?: FetchOptions) =>
request("POST", path, { ...opts, body }),
put: (path: string, body: unknown, opts?: FetchOptions) =>
request("PUT", path, { ...opts, body }),
patch: (path: string, body: unknown, opts?: FetchOptions) =>
request("PATCH", path, { ...opts, body }),
delete: (path: string, opts?: FetchOptions) => request("DELETE", path, opts),
};
/**
* Probe `/api/health` to confirm the target server is up. Returns true if it
* answers 2xx within 5 seconds. Used by tests to skip cleanly when the
* Worker isn't running.
*/
export async function isServerReachable(): Promise<boolean> {
try {
const res = await fetch(url("/api/health"), {
signal: AbortSignal.timeout(5_000),
});
if (!res.ok && process.env.REQUIRE_E2E_SERVER !== "0") {
throw new Error(`GET ${url("/api/health")} returned ${res.status}`);
}
return res.ok;
} catch (error) {
if (process.env.REQUIRE_E2E_SERVER !== "0") {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`Worker e2e target is not reachable at ${getBaseUrl()}: ${message}`,
);
}
return false;
}
}
/**
* Exchange the bootstrapped API key for a session cookie via
* `POST /api/test/auth/session`. The Worker must have `PLAYWRIGHT_TEST_AUTH=true`
* in its env for this to be enabled.
*
* Returns `Cookie` header value ready to attach to subsequent requests.
*/
export async function exchangeApiKeyForSession(): Promise<string> {
const res = await api.post("/api/test/auth/session", undefined, {
headers: bearerHeaders(),
});
if (!res.ok) {
const body = await res.text();
throw new Error(
`POST /api/test/auth/session failed: ${res.status} ${body.slice(0, 200)}`,
);
}
const json = (await res.json()) as { token?: string; cookieName?: string };
if (!json.token) {
throw new Error("Test session response missing token");
}
const name = json.cookieName ?? "eliza-test-session";
return `${name}=${json.token}`;
}