@open-qa/qa 0.0.0-stage → 0.1.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +204 -0
- package/NOTICE +7 -0
- package/THIRD_PARTY.md +12 -0
- package/THIRD_PARTY_NOTICES.md +11 -0
- package/drizzle/0000_qa_core.sql +158 -0
- package/drizzle/0001_run_health.sql +3 -0
- package/drizzle/0002_bounded_cleanup.sql +5 -0
- package/drizzle/0003_step_replay_cache.sql +9 -0
- package/drizzle/0004_credential_expiry.sql +1 -0
- package/drizzle/0005_server_api.sql +19 -0
- package/drizzle/0006_submission_created.sql +3 -0
- package/drizzle/0007_findings.sql +19 -0
- package/drizzle/0008_classification_labels.sql +14 -0
- package/drizzle/0009_job_queue.sql +20 -0
- package/drizzle/0010_result_notifications.sql +13 -0
- package/drizzle/0011_result_notification_retries.sql +5 -0
- package/drizzle/0012_result_notification_flows.sql +44 -0
- package/drizzle/0013_flow_quarantine.sql +35 -0
- package/drizzle/0014_run_budgets.sql +2 -0
- package/drizzle/0015_flow_lifecycle.sql +9 -0
- package/drizzle/0016_open_qa_classification.sql +28 -0
- package/drizzle/meta/0000_snapshot.json +1002 -0
- package/drizzle/meta/0001_snapshot.json +1021 -0
- package/drizzle/meta/0002_snapshot.json +1027 -0
- package/drizzle/meta/0003_snapshot.json +1081 -0
- package/drizzle/meta/0004_snapshot.json +1087 -0
- package/drizzle/meta/0005_snapshot.json +1210 -0
- package/drizzle/meta/0006_snapshot.json +1244 -0
- package/drizzle/meta/0007_snapshot.json +1353 -0
- package/drizzle/meta/0008_snapshot.json +1435 -0
- package/drizzle/meta/0009_snapshot.json +1587 -0
- package/drizzle/meta/0010_snapshot.json +1675 -0
- package/drizzle/meta/0011_snapshot.json +1692 -0
- package/drizzle/meta/0012_snapshot.json +1818 -0
- package/drizzle/meta/0013_snapshot.json +2016 -0
- package/drizzle/meta/0014_snapshot.json +2028 -0
- package/drizzle/meta/0015_snapshot.json +2064 -0
- package/drizzle/meta/0016_snapshot.json +2076 -0
- package/drizzle/meta/_journal.json +125 -0
- package/package.json +118 -4
- package/problem-matcher.json +32 -0
- package/src/adapters/db-lease-pool.d.ts +25 -0
- package/src/adapters/db-lease-pool.js +293 -0
- package/src/adapters/dir-artifact-store.d.ts +9 -0
- package/src/adapters/dir-artifact-store.js +64 -0
- package/src/adapters/e2b-agent.d.ts +7 -0
- package/src/adapters/e2b-agent.js +94 -0
- package/src/adapters/e2b-artifacts.d.ts +3 -0
- package/src/adapters/e2b-artifacts.js +66 -0
- package/src/adapters/e2b-bounded.d.ts +1 -0
- package/src/adapters/e2b-bounded.js +19 -0
- package/src/adapters/e2b-client.d.ts +33 -0
- package/src/adapters/e2b-client.js +114 -0
- package/src/adapters/e2b-executor.d.ts +26 -0
- package/src/adapters/e2b-executor.js +194 -0
- package/src/adapters/e2b-lifetime.d.ts +20 -0
- package/src/adapters/e2b-lifetime.js +73 -0
- package/src/adapters/e2b-prune.d.ts +13 -0
- package/src/adapters/e2b-prune.js +42 -0
- package/src/adapters/file-replay-cache.d.ts +14 -0
- package/src/adapters/file-replay-cache.js +120 -0
- package/src/adapters/file-run-store.d.ts +175 -0
- package/src/adapters/file-run-store.js +280 -0
- package/src/adapters/fixed-lease-pool.d.ts +10 -0
- package/src/adapters/fixed-lease-pool.js +237 -0
- package/src/adapters/gcs/artifact-store.d.ts +49 -0
- package/src/adapters/gcs/artifact-store.js +247 -0
- package/src/adapters/gcs/client.d.ts +22 -0
- package/src/adapters/gcs/client.js +106 -0
- package/src/adapters/gcs/download.d.ts +9 -0
- package/src/adapters/gcs/download.js +43 -0
- package/src/adapters/gcs/index.d.ts +8 -0
- package/src/adapters/gcs/index.js +23 -0
- package/src/adapters/gcs/periodic-flush.d.ts +5 -0
- package/src/adapters/gcs/periodic-flush.js +16 -0
- package/src/adapters/gcs/pg-catalog.d.ts +16 -0
- package/src/adapters/gcs/pg-catalog.js +149 -0
- package/src/adapters/gcs/replay-completeness.d.ts +1 -0
- package/src/adapters/gcs/replay-completeness.js +65 -0
- package/src/adapters/gcs/scan-upload.d.ts +10 -0
- package/src/adapters/gcs/scan-upload.js +26 -0
- package/src/adapters/index.d.ts +5 -0
- package/src/adapters/index.js +12 -0
- package/src/adapters/lease-transaction.d.ts +2 -0
- package/src/adapters/lease-transaction.js +61 -0
- package/src/adapters/local-credential-resolver.d.ts +5 -0
- package/src/adapters/local-credential-resolver.js +15 -0
- package/src/adapters/local-env.d.ts +1 -0
- package/src/adapters/local-env.js +37 -0
- package/src/adapters/local-files.d.ts +17 -0
- package/src/adapters/local-files.js +150 -0
- package/src/adapters/pg-classification-store.d.ts +58 -0
- package/src/adapters/pg-classification-store.js +112 -0
- package/src/adapters/pg-replay-cache.d.ts +16 -0
- package/src/adapters/pg-replay-cache.js +111 -0
- package/src/adapters/pg-run-store.d.ts +58 -0
- package/src/adapters/pg-run-store.js +399 -0
- package/src/adapters/resource-pools.d.ts +2 -0
- package/src/adapters/resource-pools.js +28 -0
- package/src/adapters/secret-manager-credential-resolver.d.ts +44 -0
- package/src/adapters/secret-manager-credential-resolver.js +102 -0
- package/src/artifact-scan.d.ts +21 -0
- package/src/artifact-scan.js +139 -0
- package/src/budget-confirmation.d.ts +23 -0
- package/src/budget-confirmation.js +43 -0
- package/src/cache-command.d.ts +7 -0
- package/src/cache-command.js +107 -0
- package/src/classification-command.d.ts +14 -0
- package/src/classification-command.js +72 -0
- package/src/classification-diff.d.ts +10 -0
- package/src/classification-diff.js +47 -0
- package/src/classification-model.d.ts +17 -0
- package/src/classification-model.js +51 -0
- package/src/classification-notifier.d.ts +21 -0
- package/src/classification-notifier.js +34 -0
- package/src/classify-runs.d.ts +31 -0
- package/src/classify-runs.js +138 -0
- package/src/cli-program.d.ts +9 -0
- package/src/cli-program.js +172 -0
- package/src/cli.d.ts +2 -0
- package/src/cli.js +12 -0
- package/src/commands.d.ts +7 -0
- package/src/commands.js +17 -0
- package/src/credential-references.d.ts +24 -0
- package/src/credential-references.js +33 -0
- package/src/db/commands.d.ts +1 -0
- package/src/db/commands.js +34 -0
- package/src/db/credentials.d.ts +16 -0
- package/src/db/credentials.js +73 -0
- package/src/db/database.d.ts +12 -0
- package/src/db/database.js +135 -0
- package/src/db/event-chunks.d.ts +405 -0
- package/src/db/event-chunks.js +74 -0
- package/src/db/fencing.d.ts +8 -0
- package/src/db/fencing.js +16 -0
- package/src/db/flow-status.d.ts +41 -0
- package/src/db/flow-status.js +208 -0
- package/src/db/index.d.ts +12 -0
- package/src/db/index.js +24 -0
- package/src/db/queries.d.ts +73 -0
- package/src/db/queries.js +122 -0
- package/src/db/resources.d.ts +14 -0
- package/src/db/resources.js +61 -0
- package/src/db/schema.d.ts +3532 -0
- package/src/db/schema.js +501 -0
- package/src/demo-command.d.ts +1 -0
- package/src/demo-command.js +50 -0
- package/src/doctor-command.d.ts +15 -0
- package/src/doctor-command.js +275 -0
- package/src/doctor-summary.d.ts +2 -0
- package/src/doctor-summary.js +31 -0
- package/src/draft-api.d.ts +460 -0
- package/src/draft-api.js +333 -0
- package/src/draft-command.d.ts +10 -0
- package/src/draft-command.js +73 -0
- package/src/draft-hooks.d.ts +3 -0
- package/src/draft-hooks.js +33 -0
- package/src/draft-pages.d.ts +11 -0
- package/src/draft-pages.js +82 -0
- package/src/engine.d.ts +105 -0
- package/src/engine.js +323 -0
- package/src/execution-snapshot.d.ts +21 -0
- package/src/execution-snapshot.js +141 -0
- package/src/flow-check.d.ts +9 -0
- package/src/flow-check.js +68 -0
- package/src/flow-lifecycle.d.ts +6 -0
- package/src/flow-lifecycle.js +61 -0
- package/src/flow-lint.d.ts +8 -0
- package/src/flow-lint.js +73 -0
- package/src/flow-loader.d.ts +219 -0
- package/src/flow-loader.js +236 -0
- package/src/flow-source.d.ts +2 -0
- package/src/flow-source.js +6 -0
- package/src/flows-api.d.ts +1 -0
- package/src/flows-api.js +12 -0
- package/src/heal-notification.d.ts +16 -0
- package/src/heal-notification.js +62 -0
- package/src/hooks/api.d.ts +29 -0
- package/src/hooks/api.js +15 -0
- package/src/hooks/consumer.d.ts +18 -0
- package/src/hooks/consumer.js +98 -0
- package/src/hooks/loader.d.ts +6 -0
- package/src/hooks/loader.js +28 -0
- package/src/hooks/registry.d.ts +22 -0
- package/src/hooks/registry.js +23 -0
- package/src/hooks/runner.d.ts +19 -0
- package/src/hooks/runner.js +279 -0
- package/src/hooks/session-cache.d.ts +16 -0
- package/src/hooks/session-cache.js +42 -0
- package/src/hooks/session-store.d.ts +20 -0
- package/src/hooks/session-store.js +95 -0
- package/src/hooks/worker.d.ts +1 -0
- package/src/hooks/worker.js +84 -0
- package/src/http-stage-client.d.ts +367 -0
- package/src/http-stage-client.js +190 -0
- package/src/independent-model.d.ts +22 -0
- package/src/independent-model.js +215 -0
- package/src/lifecycle-command.d.ts +15 -0
- package/src/lifecycle-command.js +190 -0
- package/src/local-command.d.ts +3 -0
- package/src/local-command.js +27 -0
- package/src/local-host-executor.d.ts +38 -0
- package/src/local-host-executor.js +196 -0
- package/src/open-command.d.ts +7 -0
- package/src/open-command.js +39 -0
- package/src/operations-api.d.ts +2 -0
- package/src/operations-api.js +6 -0
- package/src/personas.d.ts +2 -0
- package/src/personas.js +61 -0
- package/src/program-runner.d.ts +3 -0
- package/src/program-runner.js +263 -0
- package/src/program-sandbox.py +75 -0
- package/src/program-scratch.d.ts +2 -0
- package/src/program-scratch.js +48 -0
- package/src/program-worker.mjs +101 -0
- package/src/public-id.d.ts +2 -0
- package/src/public-id.js +5 -0
- package/src/public-report-url.d.ts +1 -0
- package/src/public-report-url.js +18 -0
- package/src/publication-check.d.ts +1 -0
- package/src/publication-check.js +31 -0
- package/src/quarantine-command.d.ts +9 -0
- package/src/quarantine-command.js +69 -0
- package/src/remote-command.d.ts +30 -0
- package/src/remote-command.js +156 -0
- package/src/replay-image.d.ts +1 -0
- package/src/replay-image.js +35 -0
- package/src/report/assets.d.ts +1 -0
- package/src/report/assets.js +5 -0
- package/src/report/browser.css +414 -0
- package/src/report/browser.d.ts +1 -0
- package/src/report/browser.js +219 -0
- package/src/report/data.d.ts +1 -0
- package/src/report/data.js +4 -0
- package/src/report/generate.d.ts +1 -0
- package/src/report/generate.js +54 -0
- package/src/report/load.d.ts +870 -0
- package/src/report/load.js +139 -0
- package/src/report/resource-table.d.ts +2 -0
- package/src/report/resource-table.js +4 -0
- package/src/report/status-icon.d.ts +2 -0
- package/src/report/status-icon.js +20 -0
- package/src/report/style.css +413 -0
- package/src/result-notifier.d.ts +121 -0
- package/src/result-notifier.js +230 -0
- package/src/result-transports.d.ts +12 -0
- package/src/result-transports.js +150 -0
- package/src/run-command.d.ts +32 -0
- package/src/run-command.js +493 -0
- package/src/run-setup-error.d.ts +11 -0
- package/src/run-setup-error.js +18 -0
- package/src/sandboxes-command.d.ts +9 -0
- package/src/sandboxes-command.js +29 -0
- package/src/screen-proxy.d.ts +5 -0
- package/src/screen-proxy.js +79 -0
- package/src/screen-url.d.ts +18 -0
- package/src/screen-url.js +54 -0
- package/src/server/app.d.ts +29 -0
- package/src/server/app.js +350 -0
- package/src/server/auth.d.ts +33 -0
- package/src/server/auth.js +113 -0
- package/src/server/credentials.d.ts +30 -0
- package/src/server/credentials.js +77 -0
- package/src/server/errors.d.ts +9 -0
- package/src/server/errors.js +26 -0
- package/src/server/index.d.ts +35 -0
- package/src/server/index.js +96 -0
- package/src/server/maintenance.d.ts +13 -0
- package/src/server/maintenance.js +54 -0
- package/src/server/repository.d.ts +534 -0
- package/src/server/repository.js +219 -0
- package/src/setup-command.d.ts +10 -0
- package/src/setup-command.js +52 -0
- package/src/stage-environment.d.ts +1 -0
- package/src/stage-environment.js +35 -0
- package/src/stage-supervisor.mjs +95 -0
- package/src/studio-command.d.ts +7 -0
- package/src/studio-command.js +47 -0
- package/src/studio-control.d.ts +5 -0
- package/src/studio-control.js +207 -0
- package/src/studio-review.d.ts +24 -0
- package/src/studio-review.js +64 -0
- package/src/studio-worker.d.ts +1 -0
- package/src/studio-worker.js +48 -0
- package/src/system-config.d.ts +7 -0
- package/src/system-config.js +70 -0
- package/src/terminal-reporter.d.ts +13 -0
- package/src/terminal-reporter.js +93 -0
- package/src/vendor/gmail.d.ts +45 -0
- package/src/vendor/gmail.js +193 -0
- package/src/watch-command.d.ts +16 -0
- package/src/watch-command.js +93 -0
- package/src/watch-state.d.ts +4 -0
- package/src/watch-state.js +53 -0
- package/src/worker/execution-error.d.ts +5 -0
- package/src/worker/execution-error.js +10 -0
- package/src/worker/execution.d.ts +24 -0
- package/src/worker/execution.js +190 -0
- package/src/worker/index.d.ts +8 -0
- package/src/worker/index.js +40 -0
- package/src/worker/prune.d.ts +3 -0
- package/src/worker/prune.js +22 -0
- package/src/worker/quarantine-notifications.d.ts +8 -0
- package/src/worker/quarantine-notifications.js +89 -0
- package/src/worker/queue.d.ts +65 -0
- package/src/worker/queue.js +438 -0
- package/src/worker/result-notifications.d.ts +28 -0
- package/src/worker/result-notifications.js +347 -0
- package/src/worker/store.d.ts +4 -0
- package/src/worker/store.js +46 -0
- package/src/worker/worker.d.ts +21 -0
- package/src/worker/worker.js +140 -0
- package/README.md +0 -3
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const screenUrlSchema = z.url().refine((value) => {
|
|
3
|
+
const url = new URL(value);
|
|
4
|
+
return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && url.pathname === "/watch";
|
|
5
|
+
});
|
|
6
|
+
const screenAccessSchema = z.strictObject({
|
|
7
|
+
url: screenUrlSchema,
|
|
8
|
+
token: z.string().regex(/^[a-f0-9]{64}$/)
|
|
9
|
+
});
|
|
10
|
+
const screenResponseSchema = z.strictObject({ available: z.boolean() });
|
|
11
|
+
const screenFramesSchema = z.array(
|
|
12
|
+
z.strictObject({
|
|
13
|
+
view: z.string().max(128),
|
|
14
|
+
png: z.string().max(2 * 1048576)
|
|
15
|
+
})
|
|
16
|
+
).max(6);
|
|
17
|
+
async function readScreenFrames(access, signal) {
|
|
18
|
+
const selected = screenAccessSchema.safeParse(access);
|
|
19
|
+
if (!selected.success) throw new Error("Invalid private screen access");
|
|
20
|
+
try {
|
|
21
|
+
const response = await fetch(`${selected.data.url}/frames`, {
|
|
22
|
+
headers: { Authorization: `Bearer ${selected.data.token}` },
|
|
23
|
+
redirect: "error",
|
|
24
|
+
cache: "no-store",
|
|
25
|
+
signal
|
|
26
|
+
});
|
|
27
|
+
if (!response.ok || !response.body) throw new Error("Screen unavailable");
|
|
28
|
+
const reader = response.body.getReader();
|
|
29
|
+
const chunks = [];
|
|
30
|
+
let size = 0;
|
|
31
|
+
try {
|
|
32
|
+
while (true) {
|
|
33
|
+
const { done, value } = await reader.read();
|
|
34
|
+
if (done) break;
|
|
35
|
+
size += value.byteLength;
|
|
36
|
+
if (size > 16 * 1048576) throw new Error("Screen response exceeds size limit");
|
|
37
|
+
chunks.push(value);
|
|
38
|
+
}
|
|
39
|
+
} finally {
|
|
40
|
+
await reader.cancel();
|
|
41
|
+
reader.releaseLock();
|
|
42
|
+
}
|
|
43
|
+
return screenFramesSchema.parse(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
44
|
+
} catch {
|
|
45
|
+
throw new Error("Screen unavailable or access expired");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export {
|
|
49
|
+
readScreenFrames,
|
|
50
|
+
screenAccessSchema,
|
|
51
|
+
screenFramesSchema,
|
|
52
|
+
screenResponseSchema,
|
|
53
|
+
screenUrlSchema
|
|
54
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type ScreenAccess } from "../screen-url.js";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
import { SecretRedactor, type ClassificationStore, type ReplayCache } from "@open-qa/qa-engine";
|
|
4
|
+
import { type AuthPolicy, type Principal } from "./auth.js";
|
|
5
|
+
import { type ServerRepository } from "./repository.js";
|
|
6
|
+
import { type CredentialService } from "./credentials.js";
|
|
7
|
+
type Env = {
|
|
8
|
+
Variables: {
|
|
9
|
+
principal: Principal;
|
|
10
|
+
project: string;
|
|
11
|
+
repository: ServerRepository;
|
|
12
|
+
userId: string;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
export interface QaServerOptions {
|
|
16
|
+
auth: AuthPolicy;
|
|
17
|
+
repository: (project: string) => ServerRepository;
|
|
18
|
+
credentials: (project: string) => CredentialService;
|
|
19
|
+
replayCache?: (project: string) => ReplayCache;
|
|
20
|
+
classifications?: (project: string) => ClassificationStore;
|
|
21
|
+
redactor?: SecretRedactor;
|
|
22
|
+
/** Worker-owned, project-scoped ephemeral screen capabilities; never run metadata. */
|
|
23
|
+
screenAccess?: (project: string, runId: string) => Promise<ScreenAccess | undefined>;
|
|
24
|
+
livePollMs?: number;
|
|
25
|
+
liveMaxMs?: number;
|
|
26
|
+
liveConnectionsPerPrincipal?: number;
|
|
27
|
+
}
|
|
28
|
+
export declare function createQaServer(options: QaServerOptions): Hono<Env, import("hono/types").BlankSchema, "/">;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { readScreenFrames } from "../screen-url.js";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
import { bodyLimit } from "hono/body-limit";
|
|
4
|
+
import { streamSSE } from "hono/streaming";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import {
|
|
7
|
+
replayCacheId,
|
|
8
|
+
parseReplayCacheId,
|
|
9
|
+
SecretRedactor
|
|
10
|
+
} from "@open-qa/qa-engine";
|
|
11
|
+
import {
|
|
12
|
+
classificationPatchSchema,
|
|
13
|
+
serverIdSchema,
|
|
14
|
+
submitBatchSchema,
|
|
15
|
+
credentialConnectSchema,
|
|
16
|
+
publicationKinds,
|
|
17
|
+
publicationSchemas,
|
|
18
|
+
artifactPathSchema,
|
|
19
|
+
eventsPageSchema
|
|
20
|
+
} from "@open-qa/qa-engine/protocol";
|
|
21
|
+
import { authenticate } from "./auth.js";
|
|
22
|
+
import { Conflict } from "./repository.js";
|
|
23
|
+
import { projectUserId } from "./credentials.js";
|
|
24
|
+
import { InvalidRequest, logFailure, ServerFailure } from "./errors.js";
|
|
25
|
+
const cursor = z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
26
|
+
const limit = z.coerce.number().int().min(1).max(1e3);
|
|
27
|
+
const keySchema = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/);
|
|
28
|
+
function createQaServer(options) {
|
|
29
|
+
const app = new Hono();
|
|
30
|
+
const redactor = options.redactor ?? new SecretRedactor();
|
|
31
|
+
const liveLimit = options.liveConnectionsPerPrincipal ?? 2;
|
|
32
|
+
if (!Number.isSafeInteger(liveLimit) || liveLimit < 1)
|
|
33
|
+
throw new Error("Invalid live connection limit");
|
|
34
|
+
const liveConnections = /* @__PURE__ */ new Map();
|
|
35
|
+
app.use("*", async (c, next) => {
|
|
36
|
+
c.header("Cache-Control", "private, no-store");
|
|
37
|
+
c.header("Vary", "Authorization, CF-Access-JWT-Assertion, X-QA-Project");
|
|
38
|
+
c.header("X-Content-Type-Options", "nosniff");
|
|
39
|
+
let principal;
|
|
40
|
+
try {
|
|
41
|
+
principal = await authenticate(c.req.raw, options.auth);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
logFailure(
|
|
44
|
+
error instanceof ServerFailure ? error.category : "identity-rejected",
|
|
45
|
+
"authentication"
|
|
46
|
+
);
|
|
47
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
48
|
+
}
|
|
49
|
+
const scoped = c.req.path.startsWith("/projects/") ? c.req.path.split("/")[2] : void 0;
|
|
50
|
+
const header = c.req.header("X-QA-Project");
|
|
51
|
+
const project = serverIdSchema.safeParse(scoped ?? header);
|
|
52
|
+
if (!project.success || scoped && header && header !== scoped || !Object.hasOwn(principal.grants, project.data))
|
|
53
|
+
return c.json({ error: "Forbidden" }, 403);
|
|
54
|
+
if (!["GET", "HEAD"].includes(c.req.method) && c.req.header("X-QA-Request") !== "1")
|
|
55
|
+
return c.json({ error: "Missing request intent" }, 403);
|
|
56
|
+
c.set("principal", principal);
|
|
57
|
+
c.set("project", project.data);
|
|
58
|
+
c.set("userId", projectUserId(principal.id, project.data));
|
|
59
|
+
c.set("repository", options.repository(project.data));
|
|
60
|
+
await next();
|
|
61
|
+
});
|
|
62
|
+
app.use(
|
|
63
|
+
"*",
|
|
64
|
+
bodyLimit({
|
|
65
|
+
maxSize: 1024 * 1024,
|
|
66
|
+
onError: (c) => c.json({ error: "Request is too large" }, 413)
|
|
67
|
+
})
|
|
68
|
+
);
|
|
69
|
+
app.onError((error, c) => {
|
|
70
|
+
logFailure(
|
|
71
|
+
error instanceof ServerFailure ? error.category : error instanceof z.ZodError || error instanceof SyntaxError || error instanceof InvalidRequest ? "invalid-request" : error instanceof Conflict ? "conflict" : "repository",
|
|
72
|
+
c.req.routePath,
|
|
73
|
+
c.get("project")
|
|
74
|
+
);
|
|
75
|
+
if (error instanceof z.ZodError || error instanceof SyntaxError || error instanceof InvalidRequest)
|
|
76
|
+
return c.json({ error: "Invalid request" }, 400);
|
|
77
|
+
if (error instanceof Conflict) return c.json({ error: "Conflicting request" }, 409);
|
|
78
|
+
return c.json({ error: "QA service unavailable" }, 503);
|
|
79
|
+
});
|
|
80
|
+
const api = new Hono();
|
|
81
|
+
const allowed = (c, permission) => c.get("principal").grants[c.get("project")]?.includes(permission);
|
|
82
|
+
api.use("*", async (c, next) => {
|
|
83
|
+
const path = c.req.path.replace(/^\/projects\/[^/]+(?=\/|$)/, "");
|
|
84
|
+
const permission = path.endsWith("/classification") && c.req.method === "PATCH" || path === "/cache" || path.startsWith("/cache/") ? "review" : path === "/credentials" || path.startsWith("/credentials/") ? "credentials" : path.startsWith("/publications/") && c.req.method === "PUT" ? "publish" : c.req.method === "GET" || c.req.method === "HEAD" ? "read" : path.endsWith("/cancel") ? "cancel" : "submit";
|
|
85
|
+
if (!allowed(c, permission) || ["credentials", "review"].includes(permission) && c.get("principal").kind !== "human")
|
|
86
|
+
return c.json({ error: "Forbidden" }, 403);
|
|
87
|
+
await next();
|
|
88
|
+
});
|
|
89
|
+
const json = (c, data) => c.json(redactor.json(data));
|
|
90
|
+
const missing = (c) => c.json({ error: "Not found" }, 404);
|
|
91
|
+
api.get("/cache/pending", async (c) => {
|
|
92
|
+
const cache = options.replayCache?.(c.get("project"));
|
|
93
|
+
if (!cache?.pending) throw new ServerFailure("repository");
|
|
94
|
+
return json(
|
|
95
|
+
c,
|
|
96
|
+
(await cache.pending()).map((entry) => ({ id: replayCacheId(entry), ...entry }))
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
for (const action of ["approve", "reject"])
|
|
100
|
+
api.post(`/cache/:id/${action}`, async (c) => {
|
|
101
|
+
const id = c.req.param("id");
|
|
102
|
+
try {
|
|
103
|
+
parseReplayCacheId(id);
|
|
104
|
+
} catch {
|
|
105
|
+
throw new InvalidRequest();
|
|
106
|
+
}
|
|
107
|
+
const cache = options.replayCache?.(c.get("project"));
|
|
108
|
+
if (!cache || (action === "approve" ? !cache.approve : !cache.reject))
|
|
109
|
+
throw new ServerFailure("repository");
|
|
110
|
+
try {
|
|
111
|
+
const entry = action === "approve" && cache.approve ? await cache.approve(id, {
|
|
112
|
+
approvedBy: c.get("principal").id,
|
|
113
|
+
requireIndependentReview: true
|
|
114
|
+
}) : await cache.reject?.(id, c.get("principal").id);
|
|
115
|
+
if (!entry) throw new Conflict();
|
|
116
|
+
return json(c, {
|
|
117
|
+
id: replayCacheId(entry),
|
|
118
|
+
approval: entry.approval,
|
|
119
|
+
approvedBy: entry.approvedBy,
|
|
120
|
+
approvedAt: entry.approvedAt,
|
|
121
|
+
rejectedBy: entry.rejectedBy,
|
|
122
|
+
rejectedAt: entry.rejectedAt
|
|
123
|
+
});
|
|
124
|
+
} catch {
|
|
125
|
+
throw new Conflict();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
api.get("/usage", async (c) => {
|
|
129
|
+
const flow = serverIdSchema.parse(c.req.query("flow"));
|
|
130
|
+
const repository = c.get("repository");
|
|
131
|
+
if (!repository.recentUsage) return c.json({ error: "Usage history unavailable" }, 503);
|
|
132
|
+
return json(c, { samples: await repository.recentUsage(flow) });
|
|
133
|
+
});
|
|
134
|
+
api.post("/batches", async (c) => {
|
|
135
|
+
const input = submitBatchSchema.parse(await c.req.json());
|
|
136
|
+
const key = keySchema.parse(c.req.header("Idempotency-Key"));
|
|
137
|
+
const kind = c.get("principal").kind;
|
|
138
|
+
if (kind !== "human" && input.modelAccess !== "team")
|
|
139
|
+
return c.json({ error: "Automation requires team credentials" }, 400);
|
|
140
|
+
const batch = await c.get("repository").submit(
|
|
141
|
+
c.get("userId"),
|
|
142
|
+
kind === "human" ? "developer" : kind === "github" ? "pr-label" : "schedule",
|
|
143
|
+
key,
|
|
144
|
+
input
|
|
145
|
+
);
|
|
146
|
+
return json(c, batch);
|
|
147
|
+
});
|
|
148
|
+
api.get(
|
|
149
|
+
"/batches",
|
|
150
|
+
async (c) => json(c, {
|
|
151
|
+
schemaVersion: 1,
|
|
152
|
+
projectId: c.get("project"),
|
|
153
|
+
batches: await c.get("repository").batches(limit.parse(c.req.query("limit") ?? 20), cursor.parse(c.req.query("offset") ?? 0))
|
|
154
|
+
})
|
|
155
|
+
);
|
|
156
|
+
api.get("/batches/:id", async (c) => {
|
|
157
|
+
const batch = await c.get("repository").batch(serverIdSchema.parse(c.req.param("id")));
|
|
158
|
+
return batch ? json(c, batch) : missing(c);
|
|
159
|
+
});
|
|
160
|
+
api.get("/runs/:id", async (c) => {
|
|
161
|
+
const run = await c.get("repository").run(serverIdSchema.parse(c.req.param("id")));
|
|
162
|
+
return run ? json(c, run) : missing(c);
|
|
163
|
+
});
|
|
164
|
+
api.get("/runs/:id/screen", async (c) => {
|
|
165
|
+
const id = serverIdSchema.parse(c.req.param("id"));
|
|
166
|
+
const run = await c.get("repository").run(id);
|
|
167
|
+
if (!run) return missing(c);
|
|
168
|
+
const access = !run.result && await options.screenAccess?.(c.get("project"), id);
|
|
169
|
+
return c.json({ available: !!access });
|
|
170
|
+
});
|
|
171
|
+
api.get("/runs/:id/screen/frames", async (c) => {
|
|
172
|
+
const id = serverIdSchema.parse(c.req.param("id"));
|
|
173
|
+
const run = await c.get("repository").run(id);
|
|
174
|
+
if (!run) return missing(c);
|
|
175
|
+
const access = !run.result && await options.screenAccess?.(c.get("project"), id);
|
|
176
|
+
if (!access) return c.json({ error: "Screen unavailable" }, 404);
|
|
177
|
+
try {
|
|
178
|
+
return c.json(
|
|
179
|
+
await readScreenFrames(
|
|
180
|
+
access,
|
|
181
|
+
AbortSignal.any([c.req.raw.signal, AbortSignal.timeout(1e4)])
|
|
182
|
+
)
|
|
183
|
+
);
|
|
184
|
+
} catch {
|
|
185
|
+
return c.json({ error: "Screen unavailable or access expired" }, 503);
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
api.get("/runs/:id/classification", async (c) => {
|
|
189
|
+
const store = options.classifications?.(c.get("project"));
|
|
190
|
+
if (!store) throw new ServerFailure("repository");
|
|
191
|
+
const record = await store.getClassification(serverIdSchema.parse(c.req.param("id")));
|
|
192
|
+
return record ? json(c, record) : missing(c);
|
|
193
|
+
});
|
|
194
|
+
api.patch("/runs/:id/classification", async (c) => {
|
|
195
|
+
const id = serverIdSchema.parse(c.req.param("id"));
|
|
196
|
+
const input = classificationPatchSchema.parse(await c.req.json());
|
|
197
|
+
const store = options.classifications?.(c.get("project"));
|
|
198
|
+
if (!store) throw new ServerFailure("repository");
|
|
199
|
+
if (!await store.getClassification(id)) return missing(c);
|
|
200
|
+
return json(
|
|
201
|
+
c,
|
|
202
|
+
await store.labelClassification(id, { ...input, modifiedBy: c.get("principal").id })
|
|
203
|
+
);
|
|
204
|
+
});
|
|
205
|
+
api.get("/runs/:id/events", async (c) => {
|
|
206
|
+
const id = serverIdSchema.parse(c.req.param("id"));
|
|
207
|
+
const after = cursor.parse(c.req.query("after") ?? 0);
|
|
208
|
+
const pageLimit = limit.parse(c.req.query("limit") ?? 100);
|
|
209
|
+
if (!await c.get("repository").run(id)) return missing(c);
|
|
210
|
+
const events = await c.get("repository").events(id, after, pageLimit);
|
|
211
|
+
return json(
|
|
212
|
+
c,
|
|
213
|
+
eventsPageSchema.parse({
|
|
214
|
+
schemaVersion: 1,
|
|
215
|
+
projectId: c.get("project"),
|
|
216
|
+
runId: id,
|
|
217
|
+
events,
|
|
218
|
+
next: events.at(-1)?.seq ?? after
|
|
219
|
+
})
|
|
220
|
+
);
|
|
221
|
+
});
|
|
222
|
+
api.get("/runs/:id/live", async (c) => {
|
|
223
|
+
const id = serverIdSchema.parse(c.req.param("id"));
|
|
224
|
+
let after = cursor.parse(c.req.query("after") ?? c.req.header("Last-Event-ID") ?? 0);
|
|
225
|
+
const repository = c.get("repository");
|
|
226
|
+
if (!await repository.run(id)) return missing(c);
|
|
227
|
+
const principalId = c.get("principal").id;
|
|
228
|
+
const count = liveConnections.get(principalId) ?? 0;
|
|
229
|
+
if (count >= liveLimit) {
|
|
230
|
+
c.header("Retry-After", "1");
|
|
231
|
+
return c.json({ error: "Live connection limit reached" }, 429);
|
|
232
|
+
}
|
|
233
|
+
liveConnections.set(principalId, count + 1);
|
|
234
|
+
let released = false;
|
|
235
|
+
const release = () => {
|
|
236
|
+
if (released) return;
|
|
237
|
+
released = true;
|
|
238
|
+
const remaining = (liveConnections.get(principalId) ?? 1) - 1;
|
|
239
|
+
if (remaining) liveConnections.set(principalId, remaining);
|
|
240
|
+
else liveConnections.delete(principalId);
|
|
241
|
+
};
|
|
242
|
+
return streamSSE(c, async (stream) => {
|
|
243
|
+
stream.onAbort(release);
|
|
244
|
+
const deadline = Math.min(
|
|
245
|
+
c.get("principal").expiresAt,
|
|
246
|
+
Date.now() + (options.liveMaxMs ?? 3e4)
|
|
247
|
+
);
|
|
248
|
+
try {
|
|
249
|
+
while (!stream.aborted && !c.req.raw.signal.aborted && Date.now() < deadline) {
|
|
250
|
+
const events = await repository.events(id, after, 1e3);
|
|
251
|
+
for (const event of events) {
|
|
252
|
+
await stream.writeSSE({
|
|
253
|
+
id: String(event.seq),
|
|
254
|
+
event: "run-event",
|
|
255
|
+
data: JSON.stringify(redactor.json(event))
|
|
256
|
+
});
|
|
257
|
+
after = event.seq;
|
|
258
|
+
}
|
|
259
|
+
if (events.length === 1e3) continue;
|
|
260
|
+
const run = await repository.run(id);
|
|
261
|
+
if (!run || run.result && after >= run.lastSeq) break;
|
|
262
|
+
await stream.writeSSE({ event: "cursor", data: JSON.stringify({ after }) });
|
|
263
|
+
await stream.sleep(options.livePollMs ?? 1e3);
|
|
264
|
+
}
|
|
265
|
+
} catch (error) {
|
|
266
|
+
logFailure(
|
|
267
|
+
error instanceof ServerFailure ? error.category : "repository",
|
|
268
|
+
"/runs/:id/live",
|
|
269
|
+
c.get("project")
|
|
270
|
+
);
|
|
271
|
+
if (!stream.aborted)
|
|
272
|
+
await stream.writeSSE({ event: "error", data: '{"error":"QA service unavailable"}' });
|
|
273
|
+
} finally {
|
|
274
|
+
release();
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
api.post("/runs/:id/cancel", async (c) => {
|
|
279
|
+
const success = await c.get("repository").cancel(serverIdSchema.parse(c.req.param("id")), c.get("userId"));
|
|
280
|
+
return success ? json(c, { state: "cancel-requested" }) : missing(c);
|
|
281
|
+
});
|
|
282
|
+
api.post("/runs/:id/rerun", async (c) => {
|
|
283
|
+
if (c.get("principal").kind !== "human") return c.json({ error: "Forbidden" }, 403);
|
|
284
|
+
const batch = await c.get("repository").rerun(
|
|
285
|
+
serverIdSchema.parse(c.req.param("id")),
|
|
286
|
+
c.get("userId"),
|
|
287
|
+
keySchema.parse(c.req.header("Idempotency-Key"))
|
|
288
|
+
);
|
|
289
|
+
return batch ? json(c, batch) : missing(c);
|
|
290
|
+
});
|
|
291
|
+
api.get(
|
|
292
|
+
"/credentials",
|
|
293
|
+
async (c) => json(c, {
|
|
294
|
+
schemaVersion: 1,
|
|
295
|
+
projectId: c.get("project"),
|
|
296
|
+
credentials: await options.credentials(c.get("project")).list(c.get("userId"))
|
|
297
|
+
})
|
|
298
|
+
);
|
|
299
|
+
api.post("/credentials", async (c) => {
|
|
300
|
+
const input = credentialConnectSchema.parse(await c.req.json());
|
|
301
|
+
await options.credentials(c.get("project")).connect(c.get("userId"), input);
|
|
302
|
+
return json(c, { state: "connected" });
|
|
303
|
+
});
|
|
304
|
+
api.delete("/credentials/:id", async (c) => {
|
|
305
|
+
await options.credentials(c.get("project")).revoke(c.get("userId"), z.enum(["claude-code", "pi"]).parse(c.req.param("id")));
|
|
306
|
+
return json(c, { state: "revoked" });
|
|
307
|
+
});
|
|
308
|
+
api.get(
|
|
309
|
+
"/leases",
|
|
310
|
+
async (c) => json(c, {
|
|
311
|
+
schemaVersion: 1,
|
|
312
|
+
projectId: c.get("project"),
|
|
313
|
+
leases: await c.get("repository").leases()
|
|
314
|
+
})
|
|
315
|
+
);
|
|
316
|
+
for (const kind of publicationKinds) {
|
|
317
|
+
api.put(`/publications/${kind}`, async (c) => {
|
|
318
|
+
const input = publicationSchemas[kind].parse(await c.req.json());
|
|
319
|
+
if (input.projectId !== c.get("project")) return c.json({ error: "Forbidden" }, 403);
|
|
320
|
+
await c.get("repository").publish(kind, input);
|
|
321
|
+
return json(c, { state: "recorded" });
|
|
322
|
+
});
|
|
323
|
+
api.get(`/${kind}`, async (c) => json(c, await c.get("repository").published(kind)));
|
|
324
|
+
}
|
|
325
|
+
api.get("/targets", async (c) => json(c, await c.get("repository").published("configuration")));
|
|
326
|
+
api.get("/runs/:id/snapshot", async (c) => {
|
|
327
|
+
const snapshot = await c.get("repository").snapshot(serverIdSchema.parse(c.req.param("id")));
|
|
328
|
+
return snapshot ? json(c, snapshot) : missing(c);
|
|
329
|
+
});
|
|
330
|
+
api.get("/runs/:id/artifacts/*", async (c) => {
|
|
331
|
+
const path = artifactPathSchema.parse(c.req.path.split("/artifacts/")[1]);
|
|
332
|
+
const data = await c.get("repository").artifact(serverIdSchema.parse(c.req.param("id")), path);
|
|
333
|
+
if (!data) return missing(c);
|
|
334
|
+
return new Response(data, {
|
|
335
|
+
headers: {
|
|
336
|
+
"Content-Type": "application/octet-stream",
|
|
337
|
+
"Content-Disposition": "attachment",
|
|
338
|
+
"Content-Security-Policy": "sandbox; default-src 'none'",
|
|
339
|
+
"Cache-Control": "private, no-store",
|
|
340
|
+
"X-Content-Type-Options": "nosniff"
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
app.route("/projects/:projectId", api);
|
|
345
|
+
app.route("/", api);
|
|
346
|
+
return app;
|
|
347
|
+
}
|
|
348
|
+
export {
|
|
349
|
+
createQaServer
|
|
350
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type JWTVerifyGetKey, type JWTVerifyOptions, type CryptoKey } from "jose";
|
|
2
|
+
export type Permission = "read" | "submit" | "cancel" | "credentials" | "publish" | "review";
|
|
3
|
+
export type Grants = Readonly<Record<string, readonly Permission[]>>;
|
|
4
|
+
export type Principal = {
|
|
5
|
+
id: string;
|
|
6
|
+
kind: "human" | "github" | "google";
|
|
7
|
+
grants: Grants;
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
};
|
|
10
|
+
export type VerifyIdentity = (token: string) => Promise<unknown>;
|
|
11
|
+
export interface AuthPolicy {
|
|
12
|
+
proxy?: {
|
|
13
|
+
verify: VerifyIdentity;
|
|
14
|
+
users: Readonly<Record<string, Grants>>;
|
|
15
|
+
emailVerification: Readonly<Record<string, {
|
|
16
|
+
claim: string;
|
|
17
|
+
} | {
|
|
18
|
+
verifiedByIssuer: true;
|
|
19
|
+
}>>;
|
|
20
|
+
};
|
|
21
|
+
github?: {
|
|
22
|
+
verify: VerifyIdentity;
|
|
23
|
+
workflows: Readonly<Record<string, Grants>>;
|
|
24
|
+
};
|
|
25
|
+
google?: {
|
|
26
|
+
verify: VerifyIdentity;
|
|
27
|
+
subjects: Readonly<Record<string, Grants>>;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export declare function jwtVerifier(key: CryptoKey | JWTVerifyGetKey, options: JWTVerifyOptions): VerifyIdentity;
|
|
31
|
+
export declare function remoteVerifier(jwks: string, issuer: string, audience: string, algorithms?: string[]): VerifyIdentity;
|
|
32
|
+
export declare function authenticate(request: Request, policy: AuthPolicy): Promise<Principal>;
|
|
33
|
+
export declare function validateProjectGrants(policy: AuthPolicy, projects: Readonly<Record<string, unknown>>): void;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
createRemoteJWKSet,
|
|
4
|
+
jwtVerify,
|
|
5
|
+
errors
|
|
6
|
+
} from "jose";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { backend, ServerFailure } from "./errors.js";
|
|
9
|
+
const claimsSchema = z.object({
|
|
10
|
+
iss: z.string().min(1),
|
|
11
|
+
sub: z.string().min(1),
|
|
12
|
+
exp: z.number().positive().refine((value) => value * 1e3 > Date.now())
|
|
13
|
+
}).passthrough();
|
|
14
|
+
function jwtVerifier(key, options) {
|
|
15
|
+
if (!options.issuer || !options.audience)
|
|
16
|
+
throw new Error("Identity issuer and audience are required");
|
|
17
|
+
return async (token) => (await jwtVerify(token, key, {
|
|
18
|
+
...options,
|
|
19
|
+
requiredClaims: ["iss", "sub", "aud", "exp"],
|
|
20
|
+
algorithms: options.algorithms ?? ["RS256"]
|
|
21
|
+
})).payload;
|
|
22
|
+
}
|
|
23
|
+
function remoteVerifier(jwks, issuer, audience, algorithms = ["RS256"]) {
|
|
24
|
+
const url = new URL(jwks);
|
|
25
|
+
if (url.protocol !== "https:" || url.username || url.password)
|
|
26
|
+
throw new Error("Invalid identity key endpoint");
|
|
27
|
+
const keys = createRemoteJWKSet(url);
|
|
28
|
+
return jwtVerifier((header, token) => backend("identity-keys", () => keys(header, token)), {
|
|
29
|
+
issuer,
|
|
30
|
+
audience,
|
|
31
|
+
algorithms
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async function authenticate(request, policy) {
|
|
35
|
+
let dependencyFailure;
|
|
36
|
+
try {
|
|
37
|
+
const proxy = request.headers.get("cf-access-jwt-assertion");
|
|
38
|
+
const authorization = request.headers.get("authorization");
|
|
39
|
+
if (!!proxy === !!authorization) throw new Error();
|
|
40
|
+
if (proxy && policy.proxy) {
|
|
41
|
+
if (proxy.length > 32768) throw new Error();
|
|
42
|
+
const claims = claimsSchema.extend({ email: z.email() }).parse(await verify(policy.proxy.verify, proxy));
|
|
43
|
+
const emailPolicy = Object.hasOwn(policy.proxy.emailVerification, claims.iss) ? policy.proxy.emailVerification[claims.iss] : void 0;
|
|
44
|
+
if (!emailPolicy || "claim" in emailPolicy && claims[emailPolicy.claim] !== true)
|
|
45
|
+
throw new Error();
|
|
46
|
+
const grants = Object.hasOwn(policy.proxy.users, claims.email) ? policy.proxy.users[claims.email] : void 0;
|
|
47
|
+
if (!grants) throw new Error();
|
|
48
|
+
return {
|
|
49
|
+
id: identityId(claims.iss, claims.sub),
|
|
50
|
+
kind: "human",
|
|
51
|
+
grants,
|
|
52
|
+
expiresAt: claims.exp * 1e3
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const token = /^Bearer ([^\s,]+)$/.exec(authorization ?? "")?.[1];
|
|
56
|
+
if (!token || token.length > 32768) throw new Error();
|
|
57
|
+
if (policy.github) {
|
|
58
|
+
try {
|
|
59
|
+
const claims = claimsSchema.extend({ repository: z.string(), workflow_ref: z.string(), ref: z.string() }).parse(await verify(policy.github.verify, token));
|
|
60
|
+
const grants = Object.hasOwn(policy.github.workflows, claims.workflow_ref) ? policy.github.workflows[claims.workflow_ref] : void 0;
|
|
61
|
+
if (!grants || !claims.workflow_ref.startsWith(`${claims.repository}/.github/workflows/`) || !claims.workflow_ref.endsWith(`@${claims.ref}`))
|
|
62
|
+
throw new Error();
|
|
63
|
+
return {
|
|
64
|
+
id: identityId(claims.iss, claims.sub),
|
|
65
|
+
kind: "github",
|
|
66
|
+
grants,
|
|
67
|
+
expiresAt: claims.exp * 1e3
|
|
68
|
+
};
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error instanceof ServerFailure) dependencyFailure = error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (policy.google) {
|
|
74
|
+
const claims = claimsSchema.parse(await verify(policy.google.verify, token));
|
|
75
|
+
if ("repository" in claims || "workflow_ref" in claims) throw new Error();
|
|
76
|
+
const grants = Object.hasOwn(policy.google.subjects, claims.sub) ? policy.google.subjects[claims.sub] : void 0;
|
|
77
|
+
if (!grants) throw new Error();
|
|
78
|
+
return {
|
|
79
|
+
id: identityId(claims.iss, claims.sub),
|
|
80
|
+
kind: "google",
|
|
81
|
+
grants,
|
|
82
|
+
expiresAt: claims.exp * 1e3
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
} catch (error) {
|
|
86
|
+
throw error instanceof ServerFailure ? error : dependencyFailure ?? new ServerFailure("identity-rejected");
|
|
87
|
+
}
|
|
88
|
+
throw dependencyFailure ?? new ServerFailure("identity-rejected");
|
|
89
|
+
}
|
|
90
|
+
async function verify(verifier, token) {
|
|
91
|
+
try {
|
|
92
|
+
return await verifier(token);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error instanceof ServerFailure || error instanceof errors.JOSEError) throw error;
|
|
95
|
+
throw new ServerFailure("identity-verifier");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function validateProjectGrants(policy, projects) {
|
|
99
|
+
for (const identities of [policy.proxy?.users, policy.github?.workflows, policy.google?.subjects])
|
|
100
|
+
for (const grants of Object.values(identities ?? {}))
|
|
101
|
+
for (const project of Object.keys(grants))
|
|
102
|
+
if (!Object.hasOwn(projects, project))
|
|
103
|
+
throw new Error("Identity grant references an unconfigured QA project");
|
|
104
|
+
}
|
|
105
|
+
function identityId(issuer, subject) {
|
|
106
|
+
return createHash("sha256").update(JSON.stringify([issuer, subject])).digest("hex");
|
|
107
|
+
}
|
|
108
|
+
export {
|
|
109
|
+
authenticate,
|
|
110
|
+
jwtVerifier,
|
|
111
|
+
remoteVerifier,
|
|
112
|
+
validateProjectGrants
|
|
113
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
import type { credentialConnectSchema, CredentialDto } from "@open-qa/qa-engine/protocol";
|
|
3
|
+
import { type CloudRuntime } from "../credential-references.js";
|
|
4
|
+
import type { QaDatabase } from "../db/database.js";
|
|
5
|
+
export interface CredentialSecrets {
|
|
6
|
+
addVersion(name: string, payload: string): Promise<string>;
|
|
7
|
+
revoke(name: string): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export interface CredentialService {
|
|
10
|
+
list(userId: string): Promise<CredentialDto[]>;
|
|
11
|
+
connect(userId: string, input: z.infer<typeof credentialConnectSchema>): Promise<void>;
|
|
12
|
+
revoke(userId: string, runtime: CloudRuntime): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export declare class PgCredentialService implements CredentialService {
|
|
15
|
+
private readonly db;
|
|
16
|
+
private readonly project;
|
|
17
|
+
private readonly secretProject;
|
|
18
|
+
private readonly secrets;
|
|
19
|
+
private readonly links;
|
|
20
|
+
constructor(db: QaDatabase, project: string, secretProject: string, secrets: CredentialSecrets);
|
|
21
|
+
list(userId: string): Promise<{
|
|
22
|
+
id: "claude-code" | "pi";
|
|
23
|
+
expiresAt: number | null;
|
|
24
|
+
state: "connected" | "expired";
|
|
25
|
+
}[]>;
|
|
26
|
+
connect(userId: string, input: z.infer<typeof credentialConnectSchema>): Promise<void>;
|
|
27
|
+
revoke(userId: string, runtime: CloudRuntime): Promise<void>;
|
|
28
|
+
private lock;
|
|
29
|
+
}
|
|
30
|
+
export declare function projectUserId(identity: string, project: string): string;
|