Spaces:
Running

WorkPilot-AI / web /e2e /helpers.ts
Aynkhn's picture
Deploy WorkPilot demo (part 2)
0776bd5 verified
Raw History Blame Contribute Delete
2.94 kB
import { createHmac } from "node:crypto";
import { expect, type APIRequestContext, type Page } from "@playwright/test";
export const API = `http://127.0.0.1:${process.env.E2E_API_PORT ?? 8765}`;
export interface Seeded {
email: string;
password: string;
tenant_id: string;
runs: Record<string, string>;
}
/** A fresh workspace with a pending refund (step-up) and two pending cancellations. */
export async function seed(request: APIRequestContext): Promise<Seeded> {
const r = await request.post(`${API}/__e2e/seed`, { data: {} });
expect(r.ok()).toBeTruthy();
return (await r.json()) as Seeded;
}
export async function apiToken(request: APIRequestContext, s: Seeded): Promise<string> {
const r = await request.post(`${API}/auth/login`, {
data: { email: s.email, password: s.password },
});
expect(r.ok()).toBeTruthy();
return ((await r.json()) as { access_token: string }).access_token;
}
/** Enroll TOTP for the seeded user (as a user would with their authenticator app). */
export async function enrollTotp(request: APIRequestContext, s: Seeded): Promise<string> {
const token = await apiToken(request, s);
const r = await request.post(`${API}/auth/totp/enroll`, {
headers: { Authorization: `Bearer ${token}` },
});
expect(r.ok()).toBeTruthy();
return ((await r.json()) as { secret: string }).secret;
}
function base32Decode(input: string): Buffer {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let bits = "";
for (const c of input.replace(/=+$/, "").toUpperCase()) {
const v = alphabet.indexOf(c);
if (v < 0) throw new Error(`bad base32 char ${c}`);
bits += v.toString(2).padStart(5, "0");
}
const bytes = [];
for (let i = 0; i + 8 <= bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8), 2));
return Buffer.from(bytes);
}
/** RFC 6238 TOTP (SHA-1, 30 s, 6 digits), the same as pyotp's default. */
export function totp(secret: string, now = Date.now()): string {
const counter = Math.floor(now / 1000 / 30);
const msg = Buffer.alloc(8);
msg.writeBigUInt64BE(BigInt(counter));
const h = createHmac("sha1", base32Decode(secret)).update(msg).digest();
const off = h[h.length - 1] & 0xf;
const code = (h.readUInt32BE(off) & 0x7fffffff) % 1_000_000;
return code.toString().padStart(6, "0");
}
export async function login(page: Page, s: Seeded, next = "/inbox"): Promise<void> {
await page.goto(`/login?next=${encodeURIComponent(next)}`);
await page.getByLabel(/email/i).fill(s.email);
await page.getByLabel(/password/i).fill(s.password);
await page.getByRole("button", { name: /sign in/i }).click();
await page.waitForURL((u) => u.pathname === next);
}
export function card(page: Page, tool: string, text?: string) {
const c = page.locator(`[data-testid="approval-card"][data-tool="${tool}"]`);
return text ? c.filter({ hasText: text }) : c;
}