chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:32:57 +08:00
commit cd420f9332
4811 changed files with 884702 additions and 0 deletions
@@ -0,0 +1,47 @@
// Inserts a `Session` row directly via Prisma so route auth tests can
// exercise routes that resolve a session by friendlyId or externalId.
//
// Note: not to be confused with `seedTestSession` in this directory —
// that helper builds a *dashboard cookie session* for cookie-auth tests.
// This helper builds an *agent-stream Session row* (the chat.agent
// runtime concept).
import type { PrismaClient, Session } from "@trigger.dev/database";
import { randomBytes } from "node:crypto";
function randomHex(len = 12): string {
return randomBytes(Math.ceil(len / 2))
.toString("hex")
.slice(0, len);
}
export async function seedTestApiSession(
prisma: PrismaClient,
env: {
id: string;
type: string;
organizationId: string;
projectId: string;
},
overrides?: { taskIdentifier?: string; externalId?: string | null }
): Promise<Session> {
const suffix = randomHex(8);
return prisma.session.create({
data: {
id: `session_${suffix}`,
friendlyId: `session_${suffix}`,
// `null` lets a caller exercise the externalId-absent code path
// (single-id auth resource); omit the override to get a unique
// externalId for the multi-key path.
externalId:
overrides?.externalId === null ? null : (overrides?.externalId ?? `ext_${suffix}`),
type: "chat.agent",
projectId: env.projectId,
runtimeEnvironmentId: env.id,
environmentType: env.type as Session["environmentType"],
organizationId: env.organizationId,
taskIdentifier: overrides?.taskIdentifier ?? `agent_${suffix}`,
triggerConfig: { basePayload: { messages: [], trigger: "preload" } },
},
});
}
@@ -0,0 +1,46 @@
import type { PrismaClient } from "@trigger.dev/database";
import { randomBytes } from "crypto";
function randomHex(len = 12): string {
return randomBytes(Math.ceil(len / 2))
.toString("hex")
.slice(0, len);
}
export async function seedTestEnvironment(prisma: PrismaClient) {
const suffix = randomHex(8);
const apiKey = `tr_dev_${randomHex(24)}`;
const pkApiKey = `pk_dev_${randomHex(24)}`;
const organization = await prisma.organization.create({
data: {
title: `e2e-test-org-${suffix}`,
slug: `e2e-org-${suffix}`,
isActivated: true,
},
});
const project = await prisma.project.create({
data: {
name: `e2e-test-project-${suffix}`,
slug: `e2e-proj-${suffix}`,
externalRef: `proj_${suffix}`,
organizationId: organization.id,
engine: "V2",
},
});
const environment = await prisma.runtimeEnvironment.create({
data: {
slug: "dev",
type: "DEVELOPMENT",
apiKey,
pkApiKey,
shortcode: suffix.slice(0, 4),
projectId: project.id,
organizationId: organization.id,
},
});
return { organization, project, environment, apiKey };
}
+59
View File
@@ -0,0 +1,59 @@
import type { PrismaClient } from "@trigger.dev/database";
import { createCipheriv, createHash, randomBytes } from "node:crypto";
// Must match ENCRYPTION_KEY in internal-packages/testcontainers/src/webapp.ts
const ENCRYPTION_KEY = "test-encryption-key-for-e2e!!!!!";
function hashToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
function encryptToken(value: string, key: string) {
const nonce = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", key, nonce);
let encrypted = cipher.update(value, "utf8", "hex");
encrypted += cipher.final("hex");
return {
nonce: nonce.toString("hex"),
ciphertext: encrypted,
tag: cipher.getAuthTag().toString("hex"),
};
}
function obfuscate(token: string): string {
return `${token.slice(0, 11)}${"•".repeat(20)}${token.slice(-4)}`;
}
export async function seedTestUser(prisma: PrismaClient, overrides?: { admin?: boolean }) {
const suffix = randomBytes(6).toString("hex");
return prisma.user.create({
data: {
email: `pat-user-${suffix}@test.local`,
authenticationMethod: "MAGIC_LINK",
admin: overrides?.admin ?? false,
},
});
}
// Seeds a PersonalAccessToken row using the same hashing/encryption scheme as
// webapp's services/personalAccessToken.server.ts so the webapp subprocess can
// authenticate against it.
export async function seedTestPAT(
prisma: PrismaClient,
userId: string,
opts: { revoked?: boolean } = {}
): Promise<{ token: string; id: string }> {
const token = `tr_pat_${randomBytes(20).toString("hex")}`;
const encrypted = encryptToken(token, ENCRYPTION_KEY);
const row = await prisma.personalAccessToken.create({
data: {
name: "e2e-test-pat",
userId,
encryptedToken: encrypted,
hashedToken: hashToken(token),
obfuscatedToken: obfuscate(token),
revokedAt: opts.revoked ? new Date() : null,
},
});
return { token, id: row.id };
}
+61
View File
@@ -0,0 +1,61 @@
import type { PrismaClient, TaskRun } from "@trigger.dev/database";
import { customAlphabet, nanoid } from "nanoid";
const idGenerator = customAlphabet("123456789abcdefghijkmnopqrstuvwxyz", 21);
export interface SeededRun {
run: TaskRun;
runFriendlyId: string; // `run_...`
batchFriendlyId?: string; // `batch_...` when { withBatch: true }
}
// Minimum-viable TaskRun for auth-layer e2e tests — enough fields for
// ApiRetrieveRunPresenter.findRun to return it and for the authorization.resource
// callback to populate `runs`, `tags`, `batch`, `tasks` keys.
export async function seedTestRun(
prisma: PrismaClient,
opts: {
environmentId: string;
projectId: string;
runTags?: string[];
withBatch?: boolean;
}
): Promise<SeededRun> {
const runInternalId = idGenerator();
const runFriendlyId = `run_${runInternalId}`;
let batchInternalId: string | undefined;
if (opts.withBatch) {
batchInternalId = idGenerator();
await prisma.batchTaskRun.create({
data: {
id: batchInternalId,
friendlyId: `batch_${batchInternalId}`,
runtimeEnvironmentId: opts.environmentId,
},
});
}
const run = await prisma.taskRun.create({
data: {
id: runInternalId,
friendlyId: runFriendlyId,
taskIdentifier: "test-task",
payload: "{}",
payloadType: "application/json",
traceId: nanoid(32),
spanId: nanoid(16),
queue: "task/test-task",
runtimeEnvironmentId: opts.environmentId,
projectId: opts.projectId,
runTags: opts.runTags ?? [],
batchId: batchInternalId,
},
});
return {
run,
runFriendlyId,
batchFriendlyId: batchInternalId ? `batch_${batchInternalId}` : undefined,
};
}
@@ -0,0 +1,58 @@
// Produces a `Cookie:` header value for an authenticated session that the
// webapp under test will accept. Mirrors the webapp's
// `services/sessionStorage.server.ts` config exactly — the SESSION_SECRET
// must match what the webapp container was started with (see
// `internal-packages/testcontainers/src/webapp.ts` — currently
// "test-session-secret-for-e2e-tests").
//
// Used by dashboard auth tests (TRI-8742). Each test seeds its own user +
// session so test order doesn't matter.
import { createCookieSessionStorage } from "@remix-run/node";
import type { PrismaClient } from "@trigger.dev/database";
import { randomBytes } from "node:crypto";
// Must match SESSION_SECRET in internal-packages/testcontainers/src/webapp.ts.
const SESSION_SECRET = "test-session-secret-for-e2e-tests";
// Shape of the session config in apps/webapp/app/services/sessionStorage.server.ts.
const sessionStorage = createCookieSessionStorage({
cookie: {
name: "__session",
sameSite: "lax",
path: "/",
httpOnly: true,
secrets: [SESSION_SECRET],
secure: false, // NODE_ENV is "test" in the spawned webapp.
maxAge: 60 * 60 * 24 * 365,
},
});
export async function seedTestUser(
prisma: PrismaClient,
overrides?: { admin?: boolean; email?: string }
) {
const suffix = randomBytes(6).toString("hex");
return prisma.user.create({
data: {
email: overrides?.email ?? `e2e-${suffix}@test.local`,
authenticationMethod: "MAGIC_LINK",
admin: overrides?.admin ?? false,
},
});
}
// Builds the `Cookie:` header value for a given user. Set this on test
// requests to the webapp to authenticate as that user.
//
// remix-auth's default sessionKey is "user" and stores AuthUser as
// { userId } — see apps/webapp/app/services/authUser.ts.
export async function seedTestSession(opts: { userId: string }): Promise<string> {
const session = await sessionStorage.getSession();
session.set("user", { userId: opts.userId });
const setCookie = await sessionStorage.commitSession(session);
// commitSession returns "__session=<value>; Path=/; ...". The Cookie
// header only needs the name=value pair.
const firstSegment = setCookie.split(";")[0];
return firstSegment;
}
@@ -0,0 +1,69 @@
import type { PrismaClient } from "@trigger.dev/database";
import { randomBytes } from "node:crypto";
import { seedTestPAT, seedTestUser } from "./seedTestPAT";
function randomHex(len = 12): string {
return randomBytes(Math.ceil(len / 2))
.toString("hex")
.slice(0, len);
}
// Composite test fixture: a User, an Organization with that user as a
// member, a Project owned by the org, a DEVELOPMENT environment, and a
// non-revoked PAT for the user.
//
// Used by the PAT-comprehensive matrix (TRI-8741) to exercise routes
// like GET /api/v1/projects/:projectRef/runs whose access check is
// `findProjectByRef(externalRef, userId)` — i.e. the project's org
// must have the userId in its members. seedTestEnvironment alone
// doesn't create the OrgMember link, which is why this helper exists.
//
// Caller passes `projectDeleted: true` to test the soft-deleted-
// project path; `userAdmin: true` to confirm the global admin flag
// doesn't add cross-org visibility (the route is per-user).
export async function seedTestUserProject(
prisma: PrismaClient,
opts: { userAdmin?: boolean; projectDeleted?: boolean } = {}
) {
const suffix = randomHex(8);
const apiKey = `tr_dev_${randomHex(24)}`;
const pkApiKey = `pk_dev_${randomHex(24)}`;
const user = await seedTestUser(prisma, { admin: opts.userAdmin ?? false });
const organization = await prisma.organization.create({
data: {
title: `e2e-pat-org-${suffix}`,
slug: `e2e-pat-org-${suffix}`,
isActivated: true,
members: { create: { userId: user.id, role: "ADMIN" } },
},
});
const project = await prisma.project.create({
data: {
name: `e2e-pat-project-${suffix}`,
slug: `e2e-pat-proj-${suffix}`,
externalRef: `proj_${suffix}`,
organizationId: organization.id,
engine: "V2",
deletedAt: opts.projectDeleted ? new Date() : null,
},
});
const environment = await prisma.runtimeEnvironment.create({
data: {
slug: "dev",
type: "DEVELOPMENT",
apiKey,
pkApiKey,
shortcode: suffix.slice(0, 4),
projectId: project.id,
organizationId: organization.id,
},
});
const pat = await seedTestPAT(prisma, user.id);
return { user, organization, project, environment, pat };
}
@@ -0,0 +1,29 @@
import type { PrismaClient } from "@trigger.dev/database";
import { customAlphabet } from "nanoid";
// Must match friendlyId.ts IdUtil alphabet so generated IDs are valid.
const idGenerator = customAlphabet("123456789abcdefghijkmnopqrstuvwxyz", 21);
// Seeds a Waitpoint already in COMPLETED status so the waitpoints/:id/complete
// handler short-circuits with { success: true }. That keeps the "auth passes"
// assertion independent of run-engine workers (which are disabled in e2e).
export async function seedTestWaitpoint(
prisma: PrismaClient,
opts: { environmentId: string; projectId: string }
): Promise<{ id: string; friendlyId: string }> {
const internalId = idGenerator();
const friendlyId = `waitpoint_${internalId}`;
await prisma.waitpoint.create({
data: {
id: internalId,
friendlyId,
type: "MANUAL",
status: "COMPLETED",
idempotencyKey: internalId,
userProvidedIdempotencyKey: false,
environmentId: opts.environmentId,
projectId: opts.projectId,
},
});
return { id: internalId, friendlyId };
}
@@ -0,0 +1,53 @@
// Per-worker access to the shared TestServer started by globalSetup. Each
// test file imports `getTestServer()` once at module top-level; the returned
// value is a singleton within that worker process.
//
// `webapp.fetch(path)` prepends the shared baseUrl. The PrismaClient is
// constructed lazily and disconnected on test-suite end via afterAll in the
// importing file (or left to the worker shutting down).
import { PrismaClient } from "@trigger.dev/database";
import { afterAll, inject } from "vitest";
interface SharedWebapp {
baseUrl: string;
fetch(path: string, init?: RequestInit): Promise<Response>;
}
interface SharedTestServer {
webapp: SharedWebapp;
prisma: PrismaClient;
}
let cached: SharedTestServer | undefined;
export function getTestServer(): SharedTestServer {
if (cached) return cached;
const baseUrl = inject("baseUrl");
const databaseUrl = inject("databaseUrl");
if (!baseUrl || !databaseUrl) {
throw new Error(
"globalSetup didn't provide baseUrl/databaseUrl — run via vitest.e2e.full.config.ts"
);
}
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
cached = {
webapp: {
baseUrl,
fetch: (path, init) => fetch(`${baseUrl}${path}`, init),
},
prisma,
};
// Disconnect the PrismaClient when the worker is done. globalSetup's
// teardown stops the container; this just releases the per-worker pool.
afterAll(async () => {
await prisma.$disconnect().catch(() => {});
});
return cached;
}