import { jsonToLex, Lexicons, lexiconDoc } from "@atproto/lexicon"; import { p256 } from "@noble/curves/nist.js"; import { secp256k1 } from "@noble/curves/secp256k1.js"; import { expect, onTestFinished, vi } from "vitest"; import type { PublicKey } from "../src/auth"; import approvePipeline from "./fixtures/lexicons/org.tangled.ci.approvePipeline.json"; import defs from "./fixtures/lexicons/org.tangled.ci.defs.json"; import getPipeline from "./fixtures/lexicons/org.tangled.ci.getPipeline.json"; import getWorkflowDefinition from "./fixtures/lexicons/org.tangled.ci.getWorkflowDefinition.json"; import listWorkflowDefinitions from "./fixtures/lexicons/org.tangled.ci.listWorkflowDefinitions.json"; import queryPipelines from "./fixtures/lexicons/org.tangled.ci.queryPipelines.json"; import retryPipeline from "./fixtures/lexicons/org.tangled.ci.retryPipeline.json"; import manual from "./fixtures/lexicons/org.tangled.ci.trigger.manual.json"; import pullRequest from "./fixtures/lexicons/org.tangled.event.pullRequest.json"; import push from "./fixtures/lexicons/org.tangled.event.push.json"; import listSecrets from "./fixtures/lexicons/org.tangled.secret.listSecrets.json"; import createWebhook from "./fixtures/lexicons/org.tangled.webhook.createWebhook.json"; import webhookDefs from "./fixtures/lexicons/org.tangled.webhook.defs.json"; import deleteWebhook from "./fixtures/lexicons/org.tangled.webhook.deleteWebhook.json"; import listWebhookDeliveries from "./fixtures/lexicons/org.tangled.webhook.listWebhookDeliveries.json"; import listWebhooks from "./fixtures/lexicons/org.tangled.webhook.listWebhooks.json"; import retryWebhookDelivery from "./fixtures/lexicons/org.tangled.webhook.retryWebhookDelivery.json"; import updateWebhook from "./fixtures/lexicons/org.tangled.webhook.updateWebhook.json"; type Curve = PublicKey["curve"]; const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; function base58(bytes: Uint8Array): string { let n = 0n; for (const byte of bytes) { n = n * 256n + BigInt(byte); } let out = ""; while (n > 0n) { out = alphabet.charAt(Number(n % 58n)) + out; n /= 58n; } for (const byte of bytes) { if (byte !== 0) { break; } out = "1" + out; } return out; } export function base64url(data: Uint8Array | string): string { const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data; return bytes.toBase64({ alphabet: "base64url", omitPadding: true }); } export function multikey(curve: Curve, publicKey: Uint8Array): string { const prefix = curve === "secp256k1" ? [0xe7, 0x01] : [0x80, 0x24]; return "z" + base58(Uint8Array.from([...prefix, ...publicKey])); } export interface Keypair { curve: Curve; secretKey: Uint8Array; multikey: string; } export function keypair(curve: Curve = "secp256k1"): Keypair { const impl = curve === "secp256k1" ? secp256k1 : p256; const secretKey = impl.utils.randomSecretKey(); return { curve, secretKey, multikey: multikey(curve, impl.getPublicKey(secretKey, true)) }; } export function signJwt(key: Keypair, claims: object, alg?: string): string { const impl = key.curve === "secp256k1" ? secp256k1 : p256; const header = { alg: alg ?? (key.curve === "secp256k1" ? "ES256K" : "ES256"), typ: "JWT" }; const input = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(claims))}`; const sig = impl.sign(new TextEncoder().encode(input), key.secretKey); return `${input}.${base64url(sig)}`; } export function didDoc(did: string, key?: Keypair, services: object[] = []): object { return { "@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"], id: did, verificationMethod: key === undefined ? [] : [ { id: `${did}#atproto`, type: "Multikey", controller: did, publicKeyMultibase: key.multikey, }, ], service: services, }; } export interface SeedRun { workflow: string; status: string; triggers?: string[]; buildUuid?: string; buildNumber?: number | undefined; error?: string; startedAt?: string; finishedAt?: string; eventAt?: number; attempts?: number; } export interface SeedPipeline { rkey: string; repo: string; trigger: object; commit: string; createdAt: string; runs: SeedRun[]; } export function seed(storage: DurableObjectStorage, pipelines: SeedPipeline[]): void { const sql = storage.sql; sql.exec("DELETE FROM workflow_runs; DELETE FROM pipelines"); for (const p of pipelines) { sql.exec( `INSERT INTO pipelines (rkey, repo, trigger, commit_sha, branch, created_at) VALUES (?, ?, ?, ?, 'main', ?)`, p.rkey, p.repo, JSON.stringify(p.trigger), p.commit, p.createdAt, ); for (const run of p.runs) { sql.exec( `INSERT INTO workflow_runs (pipeline, workflow, raw, bk_org, bk_pipeline, triggers, build_uuid, build_number, status, error, started_at, finished_at, event_at, attempts) VALUES (?, ?, '', 'gpanders', 'treadle', ?, ?, ?, ?, ?, ?, ?, ?, ?)`, p.rkey, run.workflow, JSON.stringify(run.triggers ?? []), run.buildUuid ?? null, run.buildNumber ?? null, run.status, run.error ?? null, run.startedAt ?? null, run.finishedAt ?? null, run.eventAt ?? null, run.attempts ?? 0, ); } } } const lexicons = new Lexicons( [ defs, getPipeline, queryPipelines, manual, push, pullRequest, retryPipeline, approvePipeline, getWorkflowDefinition, listWorkflowDefinitions, listSecrets, webhookDefs, createWebhook, updateWebhook, deleteWebhook, listWebhooks, listWebhookDeliveries, retryWebhookDelivery, ].map((doc) => lexiconDoc.parse(doc)), ); export function assertOutput(nsid: string, value: unknown): void { lexicons.assertValidXrpcOutput(nsid, jsonToLex(value)); } export async function signature(body: string, timestamp: number, secret: string): Promise { const key = await crypto.subtle.importKey( "raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"], ); const mac = await crypto.subtle.sign( "HMAC", key, new TextEncoder().encode(`${timestamp}.${body}`), ); return `timestamp=${timestamp},signature=${new Uint8Array(mac).toHex()}`; } export const jetstreamUrl = "https://jetstream.us-west.bsky.network/xrpc/network.bsky.jetstream.subscribeEvents"; export function commitMessage( seq: number, did: string, rkey: string, operation = "create", collection = "org.tangled.review.patch", ): object { return { $type: "network.bsky.jetstream.subscribeEvents#event", payload: { $type: "network.bsky.jetstream.subscribeEvents#commit", did, collection, rkey, cid: "bafy", rev: "3abc", operation, seq, time: 1_800_000_000_000_000, record: {}, }, }; } // Jetstream sends no end marker, so an open socket ends only when it goes idle. export function jetstreamSocket(messages: unknown[], close = true): Response { const { 0: client, 1: server } = new WebSocketPair(); server.accept(); for (const message of messages) { server.send(typeof message === "string" ? message : JSON.stringify(message)); } if (close) { server.close(1000, "done"); } return new Response(null, { status: 101, webSocket: client }); } export const repoDid = "did:plc:rrrrrrrrrrrrrrrrrrrrrrrr"; export const spindle = "did:web:treadle.example.com"; export const knot = "https://knot.example.com"; export const pds = "https://pds.example.com"; export const knotService = { id: "#tangled_knot", type: "TangledKnot", serviceEndpoint: knot }; export const pdsService = { id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: pds, }; export function declarationsRoute(owner: string): string { return `GET ${pds}/xrpc/com.atproto.repo.listRecords?repo=${encodeURIComponent(owner)}&collection=org.tangled.repo.declaration&limit=100`; } export function sha(n: number): string { return n.toString(16).padStart(40, "0"); } export function record(value: object): Response { return Response.json({ uri: "at://x", cid: "bafy", value }); } export function getRecordRoute(base: string, repo: string, collection: string, rkey: string) { return `GET ${base}/xrpc/com.atproto.repo.getRecord?${new URLSearchParams({ repo, collection, rkey }).toString()}`; } export interface TokenOptions { iss: string; lxm: string; aud?: string; jti?: string | null; lifetime?: number; act?: object; } export function serviceToken( key: Keypair, { iss, lxm, aud = spindle, jti = crypto.randomUUID(), lifetime = 60, act }: TokenOptions, ): string { const now = Math.floor(Date.now() / 1000); return signJwt(key, { iss, aud, exp: now + lifetime, iat: now, lxm, ...(jti === null ? {} : { jti }), ...(act === undefined ? {} : { act }), }); } export type Route = (url: URL, request: Request) => Response | Promise; const networkError = new TypeError("offline"); export function offline(): Promise { return Promise.reject(networkError); } // Answers each request from the route for "METHOD url" or "METHOD origin/path". An unknown // request, or a route that throws anything but offline(), fails the test. export function routeFetch( routes: Record, seen?: (request: Request) => void | Promise, ): void { const problems: string[] = []; onTestFinished(() => { expect(problems).toEqual([]); }); vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { const request = new Request(input, init); const url = new URL(request.url); const route = routes[`${request.method} ${url.href}`] ?? routes[`${request.method} ${url.origin}${url.pathname}`]; if (route === undefined) { problems.push(`unexpected request: ${request.method} ${url.href}`); return new Response("unexpected", { status: 599 }); } try { await seen?.(request); return await route(url, request); } catch (error) { if (error !== networkError) { problems.push(`${request.method} ${url.href}: ${String(error)}`); } throw error; } }); }