@catamorphic/work-server 0.1.0-alpha.31 → 0.1.0-alpha.32
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/README.md +88 -38
- package/dist/auth/auth-database.d.ts +1 -0
- package/dist/auth/auth-database.d.ts.map +1 -1
- package/dist/auth/fastify-auth.d.ts.map +1 -1
- package/dist/auth/migrate-legacy-oauth.d.ts +14 -0
- package/dist/auth/migrate-legacy-oauth.d.ts.map +1 -0
- package/dist/auth/work-auth-types.d.ts +4 -0
- package/dist/auth/work-auth-types.d.ts.map +1 -1
- package/dist/auth/work-auth.d.ts +2 -0
- package/dist/auth/work-auth.d.ts.map +1 -1
- package/dist/config.d.ts +2 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +594 -324
- package/dist/index.js.map +12 -11
- package/dist/server.d.ts +4 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/test-support.d.ts +6 -0
- package/dist/test-support.d.ts.map +1 -1
- package/dist/workers/install-script.d.ts +2 -3
- package/dist/workers/install-script.d.ts.map +1 -1
- package/dist/workers/machine-rules.d.ts.map +1 -1
- package/package.json +21 -19
- package/src/auth/auth-database.ts +33 -3
- package/src/auth/fastify-auth.ts +116 -41
- package/src/auth/migrate-legacy-oauth.ts +238 -0
- package/src/auth/work-auth-types.ts +2 -0
- package/src/auth/work-auth.ts +114 -25
- package/src/config.ts +3 -10
- package/src/index.ts +5 -4
- package/src/server.ts +7 -1
- package/src/test-support.ts +51 -7
- package/src/workers/install-script.ts +4 -5
- package/src/workers/machine-rules.ts +28 -24
package/dist/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
ConnectionActionRefusedError
|
|
4
4
|
} from "@catamorphic/core";
|
|
5
5
|
import {
|
|
6
|
+
defineCapability,
|
|
6
7
|
defineGitConnectionProvider as defineGitConnectionProvider2,
|
|
7
8
|
defineHttpApiConnectionProvider as defineHttpApiConnectionProvider2,
|
|
8
9
|
defineModelConnectionProvider as defineModelConnectionProvider2,
|
|
@@ -1059,9 +1060,7 @@ function machineSettingsFromEnv(env) {
|
|
|
1059
1060
|
if (problem)
|
|
1060
1061
|
throw new Error(problem);
|
|
1061
1062
|
}
|
|
1062
|
-
const
|
|
1063
|
-
const version = env.WORK_VERSION?.trim();
|
|
1064
|
-
const workerImage = env.WORK_WORKER_IMAGE?.trim() || (repository && version ? `${repository}:${version}` : undefined);
|
|
1063
|
+
const workerImage = env.WORK_WORKER_IMAGE?.trim();
|
|
1065
1064
|
return {
|
|
1066
1065
|
...machines ? { machines } : {},
|
|
1067
1066
|
...hetznerToken ? { hetznerToken } : {},
|
|
@@ -1430,7 +1429,7 @@ function startMdnsResponder(hostname, log = () => {}) {
|
|
|
1430
1429
|
};
|
|
1431
1430
|
}
|
|
1432
1431
|
// src/server.ts
|
|
1433
|
-
import { createHash as
|
|
1432
|
+
import { createHash as createHash9, randomUUID as randomUUID7 } from "node:crypto";
|
|
1434
1433
|
import fs12 from "node:fs";
|
|
1435
1434
|
import path9 from "node:path";
|
|
1436
1435
|
import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
|
|
@@ -1478,8 +1477,8 @@ import { PROJECT_AGENTS_DIR } from "@catamorphic/workflow/project-layout";
|
|
|
1478
1477
|
import { PGlite as PGlite2 } from "@electric-sql/pglite";
|
|
1479
1478
|
import { pgcrypto } from "@electric-sql/pglite/contrib/pgcrypto";
|
|
1480
1479
|
import Fastify from "fastify";
|
|
1481
|
-
import { Kysely, PGliteDialect as PGliteDialect2, sql as
|
|
1482
|
-
import { z as
|
|
1480
|
+
import { Kysely as Kysely2, PGliteDialect as PGliteDialect2, sql as sql8, WithSchemaPlugin } from "kysely";
|
|
1481
|
+
import { z as z25 } from "zod";
|
|
1483
1482
|
|
|
1484
1483
|
// src/admission/admission-service.ts
|
|
1485
1484
|
import {
|
|
@@ -2552,14 +2551,155 @@ import path4 from "node:path";
|
|
|
2552
2551
|
import { PGlite } from "@electric-sql/pglite";
|
|
2553
2552
|
import { getMigrations } from "better-auth/db/migration";
|
|
2554
2553
|
import {
|
|
2554
|
+
Kysely,
|
|
2555
2555
|
PGliteDialect
|
|
2556
2556
|
} from "kysely";
|
|
2557
2557
|
import { Pool, types } from "pg";
|
|
2558
2558
|
|
|
2559
|
+
// src/auth/migrate-legacy-oauth.ts
|
|
2560
|
+
import { createHash, randomUUID as randomUUID3 } from "node:crypto";
|
|
2561
|
+
import { jsonbText } from "@catamorphic/db";
|
|
2562
|
+
import { symmetricEncrypt } from "better-auth/crypto";
|
|
2563
|
+
import { sql } from "kysely";
|
|
2564
|
+
import { z as z8 } from "zod";
|
|
2565
|
+
var LegacyClient = z8.object({
|
|
2566
|
+
id: z8.string(),
|
|
2567
|
+
clientId: z8.string(),
|
|
2568
|
+
clientSecret: z8.string().nullish(),
|
|
2569
|
+
name: z8.string().nullish(),
|
|
2570
|
+
icon: z8.string().nullish(),
|
|
2571
|
+
metadata: z8.string().nullish(),
|
|
2572
|
+
redirectUrls: z8.string(),
|
|
2573
|
+
type: z8.string(),
|
|
2574
|
+
disabled: z8.boolean().nullish(),
|
|
2575
|
+
userId: z8.string().nullish(),
|
|
2576
|
+
createdAt: z8.coerce.date().nullable(),
|
|
2577
|
+
updatedAt: z8.coerce.date().nullable()
|
|
2578
|
+
});
|
|
2579
|
+
var LegacyGrant = z8.object({
|
|
2580
|
+
id: z8.string(),
|
|
2581
|
+
clientId: z8.string(),
|
|
2582
|
+
userId: z8.string().nullable(),
|
|
2583
|
+
accessToken: z8.string(),
|
|
2584
|
+
refreshToken: z8.string(),
|
|
2585
|
+
accessTokenExpiresAt: z8.coerce.date(),
|
|
2586
|
+
refreshTokenExpiresAt: z8.coerce.date(),
|
|
2587
|
+
scopes: z8.string(),
|
|
2588
|
+
createdAt: z8.coerce.date()
|
|
2589
|
+
});
|
|
2590
|
+
var LegacyConsent = z8.object({
|
|
2591
|
+
id: z8.string(),
|
|
2592
|
+
clientId: z8.string(),
|
|
2593
|
+
userId: z8.string(),
|
|
2594
|
+
scopes: z8.string(),
|
|
2595
|
+
consentGiven: z8.boolean(),
|
|
2596
|
+
createdAt: z8.coerce.date(),
|
|
2597
|
+
updatedAt: z8.coerce.date()
|
|
2598
|
+
});
|
|
2599
|
+
async function migrateLegacyOAuth(args) {
|
|
2600
|
+
const tables = await args.db.introspection.getTables();
|
|
2601
|
+
if (!tables.some((table) => table.name === "oauthApplication")) {
|
|
2602
|
+
return async () => {
|
|
2603
|
+
return;
|
|
2604
|
+
};
|
|
2605
|
+
}
|
|
2606
|
+
const { resource, secret } = args;
|
|
2607
|
+
if (!resource || typeof secret !== "string") {
|
|
2608
|
+
throw new Error("The OAuth upgrade requires Work's resource and auth secret");
|
|
2609
|
+
}
|
|
2610
|
+
const clients = z8.array(LegacyClient).parse((await sql`SELECT * FROM "oauthApplication"`.execute(args.db)).rows);
|
|
2611
|
+
const grants = z8.array(LegacyGrant).parse((await sql`SELECT * FROM "oauthAccessToken"`.execute(args.db)).rows);
|
|
2612
|
+
const consents = z8.array(LegacyConsent).parse((await sql`SELECT * FROM "oauthConsent"`.execute(args.db)).rows);
|
|
2613
|
+
const migratedClients = await Promise.all(clients.map(async (client) => {
|
|
2614
|
+
const metadata = client.metadata ? JSON.parse(client.metadata) : null;
|
|
2615
|
+
return {
|
|
2616
|
+
id: client.id,
|
|
2617
|
+
clientId: client.clientId,
|
|
2618
|
+
clientSecret: client.type === "public" || !client.clientSecret ? null : await symmetricEncrypt({
|
|
2619
|
+
key: secret,
|
|
2620
|
+
data: client.clientSecret
|
|
2621
|
+
}),
|
|
2622
|
+
name: client.name ?? null,
|
|
2623
|
+
icon: client.icon ?? null,
|
|
2624
|
+
metadata: jsonColumn(metadata),
|
|
2625
|
+
redirectUris: jsonColumn(client.redirectUrls.split(",").filter(Boolean)),
|
|
2626
|
+
tokenEndpointAuthMethod: client.type === "public" ? "none" : "client_secret_basic",
|
|
2627
|
+
requirePKCE: true,
|
|
2628
|
+
grantTypes: jsonColumn(["authorization_code", "refresh_token"]),
|
|
2629
|
+
responseTypes: jsonColumn(["code"]),
|
|
2630
|
+
disabled: client.disabled ?? false,
|
|
2631
|
+
userId: client.userId ?? null,
|
|
2632
|
+
createdAt: client.createdAt,
|
|
2633
|
+
updatedAt: client.updatedAt
|
|
2634
|
+
};
|
|
2635
|
+
}));
|
|
2636
|
+
await args.db.schema.dropTable("oauthAccessToken").execute();
|
|
2637
|
+
await args.db.schema.dropTable("oauthConsent").execute();
|
|
2638
|
+
await args.db.schema.dropTable("oauthApplication").execute();
|
|
2639
|
+
return async () => {
|
|
2640
|
+
const db = args.db.withTables();
|
|
2641
|
+
await db.insertInto("oauthResource").values({
|
|
2642
|
+
id: randomUUID3(),
|
|
2643
|
+
identifier: resource,
|
|
2644
|
+
name: "Work API",
|
|
2645
|
+
disabled: false
|
|
2646
|
+
}).onConflict((conflict) => conflict.column("identifier").doNothing()).execute();
|
|
2647
|
+
for (const client of migratedClients) {
|
|
2648
|
+
await db.insertInto("oauthClient").values(client).execute();
|
|
2649
|
+
await db.insertInto("oauthClientResource").values({
|
|
2650
|
+
id: randomUUID3(),
|
|
2651
|
+
clientId: client.clientId,
|
|
2652
|
+
resourceId: resource
|
|
2653
|
+
}).execute();
|
|
2654
|
+
}
|
|
2655
|
+
for (const grant of grants) {
|
|
2656
|
+
const common = {
|
|
2657
|
+
id: grant.id,
|
|
2658
|
+
clientId: grant.clientId,
|
|
2659
|
+
userId: grant.userId,
|
|
2660
|
+
sessionId: null,
|
|
2661
|
+
resources: jsonColumn([resource]),
|
|
2662
|
+
scopes: jsonColumn(grant.scopes.split(/\s+/).filter(Boolean)),
|
|
2663
|
+
createdAt: grant.createdAt
|
|
2664
|
+
};
|
|
2665
|
+
if (!grant.userId)
|
|
2666
|
+
throw new Error("Legacy OAuth grant has no user");
|
|
2667
|
+
await db.insertInto("oauthRefreshToken").values({
|
|
2668
|
+
...common,
|
|
2669
|
+
token: tokenHash(grant.refreshToken),
|
|
2670
|
+
expiresAt: grant.refreshTokenExpiresAt
|
|
2671
|
+
}).execute();
|
|
2672
|
+
await db.insertInto("oauthAccessToken").values({
|
|
2673
|
+
...common,
|
|
2674
|
+
token: tokenHash(grant.accessToken),
|
|
2675
|
+
expiresAt: grant.accessTokenExpiresAt,
|
|
2676
|
+
refreshId: grant.id
|
|
2677
|
+
}).execute();
|
|
2678
|
+
}
|
|
2679
|
+
for (const consent of consents.filter((row) => row.consentGiven)) {
|
|
2680
|
+
await db.insertInto("oauthConsent").values({
|
|
2681
|
+
id: consent.id,
|
|
2682
|
+
clientId: consent.clientId,
|
|
2683
|
+
userId: consent.userId,
|
|
2684
|
+
scopes: jsonColumn(consent.scopes.split(/\s+/).filter(Boolean)),
|
|
2685
|
+
resources: jsonColumn([resource]),
|
|
2686
|
+
createdAt: consent.createdAt,
|
|
2687
|
+
updatedAt: consent.updatedAt
|
|
2688
|
+
}).execute();
|
|
2689
|
+
}
|
|
2690
|
+
};
|
|
2691
|
+
}
|
|
2692
|
+
function jsonColumn(value) {
|
|
2693
|
+
return sql`${jsonbText(value)}::jsonb`;
|
|
2694
|
+
}
|
|
2695
|
+
function tokenHash(token) {
|
|
2696
|
+
return createHash("sha256").update(token).digest("base64url");
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2559
2699
|
// src/auth/schema-scoped-postgres-dialect.ts
|
|
2560
2700
|
import {
|
|
2561
2701
|
PostgresDialect,
|
|
2562
|
-
sql
|
|
2702
|
+
sql as sql2
|
|
2563
2703
|
} from "kysely";
|
|
2564
2704
|
|
|
2565
2705
|
class SchemaScopedPostgresDialect {
|
|
@@ -2594,7 +2734,7 @@ class SchemaScopedPostgresIntrospector {
|
|
|
2594
2734
|
return [{ name: this.schema }];
|
|
2595
2735
|
}
|
|
2596
2736
|
async getTables(options = { withInternalKyselyTables: false }) {
|
|
2597
|
-
const result = await
|
|
2737
|
+
const result = await sql2`
|
|
2598
2738
|
SELECT
|
|
2599
2739
|
a.attname AS column,
|
|
2600
2740
|
a.attnotnull AS not_null,
|
|
@@ -2664,9 +2804,16 @@ async function openWorkAuthDatabase(options) {
|
|
|
2664
2804
|
dialect: new BetterAuthTypeNames(new PGliteDialect({ pglite })),
|
|
2665
2805
|
type: "postgres"
|
|
2666
2806
|
};
|
|
2807
|
+
const db = new Kysely({ dialect: database.dialect });
|
|
2667
2808
|
return {
|
|
2668
2809
|
database,
|
|
2669
|
-
migrate: migrateBetterAuth
|
|
2810
|
+
migrate: (args) => db.transaction().execute((transaction) => migrateBetterAuth({
|
|
2811
|
+
...args,
|
|
2812
|
+
options: {
|
|
2813
|
+
...args.options,
|
|
2814
|
+
database: { db: transaction, type: "postgres" }
|
|
2815
|
+
}
|
|
2816
|
+
})),
|
|
2670
2817
|
close: () => pglite.close()
|
|
2671
2818
|
};
|
|
2672
2819
|
}
|
|
@@ -2717,6 +2864,7 @@ async function openPostgresAuthDatabase(connectionString, authSchema) {
|
|
|
2717
2864
|
`catamorphic-auth:${authSchema}`
|
|
2718
2865
|
]);
|
|
2719
2866
|
await migrateBetterAuth({
|
|
2867
|
+
resource: args.resource,
|
|
2720
2868
|
options: {
|
|
2721
2869
|
...args.options,
|
|
2722
2870
|
database: {
|
|
@@ -2742,8 +2890,19 @@ async function openPostgresAuthDatabase(connectionString, authSchema) {
|
|
|
2742
2890
|
};
|
|
2743
2891
|
}
|
|
2744
2892
|
async function migrateBetterAuth(args) {
|
|
2893
|
+
const database = args.options.database;
|
|
2894
|
+
if (!database || !(("db" in database) || ("dialect" in database))) {
|
|
2895
|
+
throw new Error("Work auth migrations require a Kysely database");
|
|
2896
|
+
}
|
|
2897
|
+
const db = "db" in database ? database.db : new Kysely({ dialect: database.dialect });
|
|
2898
|
+
const restore = await migrateLegacyOAuth({
|
|
2899
|
+
db,
|
|
2900
|
+
resource: args.resource,
|
|
2901
|
+
secret: args.options.secret
|
|
2902
|
+
});
|
|
2745
2903
|
const migrations = await getMigrations(args.options);
|
|
2746
2904
|
await migrations.runMigrations();
|
|
2905
|
+
await restore();
|
|
2747
2906
|
}
|
|
2748
2907
|
function onConnection(client) {
|
|
2749
2908
|
return {
|
|
@@ -2823,7 +2982,11 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2823
2982
|
method: ["GET", "POST", "OPTIONS"],
|
|
2824
2983
|
url: "/api/auth/*",
|
|
2825
2984
|
handler: async (request, reply) => {
|
|
2826
|
-
|
|
2985
|
+
const rawPath = request.url.split("?")[0];
|
|
2986
|
+
if (new URL(request.url, options.baseURL).pathname !== rawPath) {
|
|
2987
|
+
return reply.status(404).send();
|
|
2988
|
+
}
|
|
2989
|
+
if (request.method === "GET" && request.url.startsWith("/api/auth/callback/")) {
|
|
2827
2990
|
const response = await callBetterAuth(routed, request, {});
|
|
2828
2991
|
if (response.status === 429) {
|
|
2829
2992
|
return reply.redirect("/login?error=limited");
|
|
@@ -2837,10 +3000,8 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2837
3000
|
return forward(request, reply);
|
|
2838
3001
|
}
|
|
2839
3002
|
});
|
|
2840
|
-
|
|
3003
|
+
const token = async (request, reply) => {
|
|
2841
3004
|
const gate = options.tokenGate;
|
|
2842
|
-
if (!gate)
|
|
2843
|
-
return forward(request, reply);
|
|
2844
3005
|
const form = tokenRequestFields(request);
|
|
2845
3006
|
const keys = [...form.keys()];
|
|
2846
3007
|
if (new Set(keys).size !== keys.length) {
|
|
@@ -2864,15 +3025,27 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2864
3025
|
description: "refresh_token is required"
|
|
2865
3026
|
});
|
|
2866
3027
|
}
|
|
2867
|
-
const decision = await gate
|
|
3028
|
+
const decision = await gate?.beforeRefresh({
|
|
2868
3029
|
refreshToken,
|
|
2869
3030
|
clientId: form.get("client_id") ?? undefined
|
|
2870
3031
|
});
|
|
2871
|
-
if (!decision.allow)
|
|
3032
|
+
if (decision && !decision.allow)
|
|
2872
3033
|
return sendTokenError(reply, decision);
|
|
2873
3034
|
}
|
|
2874
|
-
const
|
|
2875
|
-
|
|
3035
|
+
const legacySecret = request.url.split("?")[0] === "/api/auth/mcp/token" && !request.headers.authorization ? form.get("client_secret") : null;
|
|
3036
|
+
const legacyClient = form.get("client_id");
|
|
3037
|
+
const legacyAuthorization = legacySecret && legacyClient ? `Basic ${Buffer.from(`${encodeURIComponent(legacyClient)}:${encodeURIComponent(legacySecret)}`).toString("base64")}` : undefined;
|
|
3038
|
+
if (legacyAuthorization)
|
|
3039
|
+
form.delete("client_secret");
|
|
3040
|
+
const response = await callBetterAuth(routed, request, {
|
|
3041
|
+
pathname: "/api/auth/oauth2/token",
|
|
3042
|
+
...legacyAuthorization ? {
|
|
3043
|
+
authorization: legacyAuthorization,
|
|
3044
|
+
body: form.toString(),
|
|
3045
|
+
contentType: "application/x-www-form-urlencoded"
|
|
3046
|
+
} : {}
|
|
3047
|
+
});
|
|
3048
|
+
if (!response.ok || !gate)
|
|
2876
3049
|
return sendResponse(response, reply);
|
|
2877
3050
|
const body = await response.clone().json().catch(() => null);
|
|
2878
3051
|
if (typeof body !== "object" || body === null) {
|
|
@@ -2886,25 +3059,30 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2886
3059
|
if (!decision.allow)
|
|
2887
3060
|
return sendTokenError(reply, decision);
|
|
2888
3061
|
return sendResponse(response, reply);
|
|
2889
|
-
}
|
|
3062
|
+
};
|
|
3063
|
+
app.post("/api/auth/oauth2/token", token);
|
|
3064
|
+
app.post("/api/auth/mcp/token", token);
|
|
2890
3065
|
app.get("/.well-known/oauth-authorization-server", (request, reply) => forward(request, reply, "/api/auth/.well-known/oauth-authorization-server"));
|
|
2891
|
-
app.get("/.well-known/oauth-
|
|
3066
|
+
app.get("/.well-known/oauth-authorization-server/api/auth", (request, reply) => forward(request, reply));
|
|
3067
|
+
app.get("/.well-known/oauth-protected-resource", (request, reply) => forward(request, reply));
|
|
3068
|
+
app.get("/.well-known/oauth-protected-resource/api", (request, reply) => forward(request, reply));
|
|
2892
3069
|
app.get("/login", (request, reply) => {
|
|
2893
3070
|
const error = new URLSearchParams(request.url.split("?")[1] ?? "").get("error");
|
|
2894
3071
|
return sendAuthPage(reply, (nonce) => loginPage(methodsFor(request), continuationQuery(request), error === "account" || error === "limited" ? error : error ? "credentials" : undefined, nonce));
|
|
2895
3072
|
});
|
|
2896
3073
|
app.post("/login/local", async (request, reply) => {
|
|
2897
3074
|
const form = formBody(request.body);
|
|
3075
|
+
const query = continuationQuery(request);
|
|
2898
3076
|
const response = await callBetterAuth(routed, request, {
|
|
2899
3077
|
pathname: "/api/auth/sign-in/username",
|
|
2900
3078
|
body: JSON.stringify({
|
|
2901
3079
|
username: form.get("username") ?? "",
|
|
2902
|
-
password: form.get("password") ?? ""
|
|
3080
|
+
password: form.get("password") ?? "",
|
|
3081
|
+
...new URLSearchParams(query).has("sig") ? { oauth_query: query } : {}
|
|
2903
3082
|
}),
|
|
2904
3083
|
contentType: "application/json"
|
|
2905
3084
|
});
|
|
2906
3085
|
copyCookies(response, reply);
|
|
2907
|
-
const query = continuationQuery(request);
|
|
2908
3086
|
if (response.status === 429) {
|
|
2909
3087
|
return reply.redirect(`/login?${query}&error=limited`);
|
|
2910
3088
|
}
|
|
@@ -2915,19 +3093,23 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2915
3093
|
const next = shareNext(request);
|
|
2916
3094
|
if (response.ok && next)
|
|
2917
3095
|
return reply.redirect(next);
|
|
2918
|
-
|
|
3096
|
+
const redirect = response.ok ? await authorizationRedirect(response) : undefined;
|
|
3097
|
+
if (redirect)
|
|
3098
|
+
return reply.redirect(redirect);
|
|
3099
|
+
return response.ok ? reply.redirect(`/api/auth/oauth2/authorize?${query}`) : reply.redirect(`/login?${query}&error=1`);
|
|
2919
3100
|
});
|
|
2920
3101
|
app.post("/login/provider/:providerId", async (request, reply) => {
|
|
2921
3102
|
if (!methodsFor(request).providers.some((provider) => provider.id === request.params.providerId)) {
|
|
2922
3103
|
return reply.status(404).send("Provider not found");
|
|
2923
3104
|
}
|
|
2924
3105
|
const query = continuationQuery(request);
|
|
2925
|
-
const callbackURL = new URL(shareNext(request) ?? `/api/auth/
|
|
3106
|
+
const callbackURL = new URL(shareNext(request) ?? `/api/auth/oauth2/authorize?${query}`, options.baseURL).toString();
|
|
2926
3107
|
const response = await callBetterAuth(routed, request, {
|
|
2927
|
-
pathname: "/api/auth/sign-in/
|
|
3108
|
+
pathname: "/api/auth/sign-in/social",
|
|
2928
3109
|
body: JSON.stringify({
|
|
2929
|
-
|
|
2930
|
-
callbackURL
|
|
3110
|
+
provider: request.params.providerId,
|
|
3111
|
+
callbackURL,
|
|
3112
|
+
...!shareNext(request) && new URLSearchParams(query).has("sig") ? { oauth_query: query } : {}
|
|
2931
3113
|
}),
|
|
2932
3114
|
contentType: "application/json"
|
|
2933
3115
|
});
|
|
@@ -2935,22 +3117,35 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2935
3117
|
const result = await response.json().catch(() => ({}));
|
|
2936
3118
|
return response.ok && typeof result.url === "string" ? reply.redirect(result.url) : reply.redirect(`/login?${query}&error=${response.status === 429 ? "limited" : "1"}`);
|
|
2937
3119
|
});
|
|
2938
|
-
app.get("/oauth/consent", (request, reply) =>
|
|
3120
|
+
app.get("/oauth/consent", async (request, reply) => {
|
|
3121
|
+
const query = new URL(request.raw.url ?? "/", options.baseURL).search.slice(1);
|
|
3122
|
+
if (!await options.auth.verifyAuthorizationQuery({ query })) {
|
|
3123
|
+
return authorizationFailed(reply);
|
|
3124
|
+
}
|
|
3125
|
+
return sendAuthPage(reply, (nonce) => consentPage(query, nonce));
|
|
3126
|
+
});
|
|
2939
3127
|
app.post("/oauth/consent", async (request, reply) => {
|
|
2940
3128
|
const form = formBody(request.body);
|
|
2941
3129
|
const response = await callBetterAuth(routed, request, {
|
|
2942
3130
|
pathname: "/api/auth/oauth2/consent",
|
|
2943
3131
|
body: JSON.stringify({
|
|
2944
3132
|
accept: form.get("accept") === "true",
|
|
2945
|
-
|
|
3133
|
+
oauth_query: form.get("oauth_query") ?? ""
|
|
2946
3134
|
}),
|
|
2947
3135
|
contentType: "application/json"
|
|
2948
3136
|
});
|
|
2949
3137
|
copyCookies(response, reply);
|
|
2950
|
-
const
|
|
2951
|
-
return
|
|
3138
|
+
const redirect = response.ok ? await authorizationRedirect(response) : undefined;
|
|
3139
|
+
return redirect ? reply.redirect(redirect) : authorizationFailed(reply);
|
|
2952
3140
|
});
|
|
2953
3141
|
}
|
|
3142
|
+
async function authorizationRedirect(response) {
|
|
3143
|
+
const result = await response.json().catch(() => null);
|
|
3144
|
+
return typeof result === "object" && result !== null && "redirect" in result && result.redirect === true && "url" in result && typeof result.url === "string" ? result.url : undefined;
|
|
3145
|
+
}
|
|
3146
|
+
function authorizationFailed(reply) {
|
|
3147
|
+
return sendAuthPage(reply.status(400), (nonce) => messagePage("Authorization could not be completed", "Return to Work and try connecting again.", nonce));
|
|
3148
|
+
}
|
|
2954
3149
|
async function forwardToBetterAuth(options, request, reply, pathname) {
|
|
2955
3150
|
return sendResponse(await callBetterAuth(options, request, { pathname }), reply);
|
|
2956
3151
|
}
|
|
@@ -3001,6 +3196,8 @@ async function callBetterAuth(options, request, overrides) {
|
|
|
3001
3196
|
if (overrides.contentType) {
|
|
3002
3197
|
headers.set("content-type", overrides.contentType);
|
|
3003
3198
|
}
|
|
3199
|
+
if (overrides.authorization)
|
|
3200
|
+
headers.set("authorization", overrides.authorization);
|
|
3004
3201
|
if (overrides.body !== undefined) {
|
|
3005
3202
|
headers.delete("content-length");
|
|
3006
3203
|
headers.delete("content-encoding");
|
|
@@ -3075,10 +3272,10 @@ function loginPage(methods, continuation, failure, nonce) {
|
|
|
3075
3272
|
</section>${script}`
|
|
3076
3273
|
});
|
|
3077
3274
|
}
|
|
3078
|
-
function consentPage(
|
|
3079
|
-
const
|
|
3080
|
-
const client = escapeHtml(query.client_id ?? "this client");
|
|
3081
|
-
const scopes = (query.scope ?? "basic identity").split(/\s+/).filter(Boolean).map((scope) => `<li>${escapeHtml(scope.replaceAll("_", " "))}</li>`).join("");
|
|
3275
|
+
function consentPage(signedQuery, nonce) {
|
|
3276
|
+
const query = new URLSearchParams(signedQuery);
|
|
3277
|
+
const client = escapeHtml(query.get("client_id") ?? "this client");
|
|
3278
|
+
const scopes = (query.get("scope") ?? "basic identity").split(/\s+/).filter(Boolean).map((scope) => `<li>${escapeHtml(scope.replaceAll("_", " "))}</li>`).join("");
|
|
3082
3279
|
return authPage({
|
|
3083
3280
|
title: "Review access | Work",
|
|
3084
3281
|
nonce,
|
|
@@ -3095,7 +3292,7 @@ function consentPage(query, nonce) {
|
|
|
3095
3292
|
<ul class="scope-list">${scopes}</ul>
|
|
3096
3293
|
</div>
|
|
3097
3294
|
<form class="consent-actions" action="/oauth/consent" method="post">
|
|
3098
|
-
<input type="hidden" name="
|
|
3295
|
+
<input type="hidden" name="oauth_query" value="${escapeHtml(signedQuery)}">
|
|
3099
3296
|
<button class="button button-secondary" name="accept" value="false">Deny</button>
|
|
3100
3297
|
<button class="button button-primary" name="accept" value="true">Allow access</button>
|
|
3101
3298
|
</form>
|
|
@@ -3375,11 +3572,14 @@ function escapeHtml(value) {
|
|
|
3375
3572
|
}
|
|
3376
3573
|
|
|
3377
3574
|
// src/auth/work-auth.ts
|
|
3378
|
-
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
3575
|
+
import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
|
|
3379
3576
|
import fs8 from "node:fs";
|
|
3380
3577
|
import path5 from "node:path";
|
|
3578
|
+
import { mcp } from "@better-auth/mcp";
|
|
3579
|
+
import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
|
|
3381
3580
|
import { betterAuth } from "better-auth";
|
|
3382
|
-
import { bearer, genericOAuth,
|
|
3581
|
+
import { bearer, genericOAuth, username } from "better-auth/plugins";
|
|
3582
|
+
import { z as z9 } from "zod";
|
|
3383
3583
|
var PROVIDER_SIGN_IN_LIMIT = { window: 10, max: 30 };
|
|
3384
3584
|
function createWorkAuth(options) {
|
|
3385
3585
|
const config = options.config ?? parseWorkAuthConfig({});
|
|
@@ -3394,11 +3594,13 @@ function createWorkAuth(options) {
|
|
|
3394
3594
|
enabled: options.rateLimit ?? true,
|
|
3395
3595
|
storage: "database",
|
|
3396
3596
|
customRules: {
|
|
3397
|
-
"/sign-in/oauth2": PROVIDER_SIGN_IN_LIMIT,
|
|
3398
3597
|
"/sign-in/social": PROVIDER_SIGN_IN_LIMIT
|
|
3399
3598
|
}
|
|
3400
3599
|
},
|
|
3401
|
-
advanced: {
|
|
3600
|
+
advanced: {
|
|
3601
|
+
ipAddress: { ipAddressHeaders: [CLIENT_ADDRESS_HEADER] },
|
|
3602
|
+
database: { validateSchema: false }
|
|
3603
|
+
},
|
|
3402
3604
|
plugins: [
|
|
3403
3605
|
username(),
|
|
3404
3606
|
bearer(),
|
|
@@ -3429,21 +3631,29 @@ function createWorkAuth(options) {
|
|
|
3429
3631
|
}),
|
|
3430
3632
|
mcp({
|
|
3431
3633
|
loginPage: `${options.baseURL}/login`,
|
|
3634
|
+
consentPage: `${options.baseURL}/oauth/consent`,
|
|
3432
3635
|
resource: `${options.baseURL}/api`,
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3636
|
+
disableJwtPlugin: true,
|
|
3637
|
+
allowDynamicClientRegistration: true,
|
|
3638
|
+
allowUnauthenticatedClientRegistration: true,
|
|
3639
|
+
clientRegistrationDefaultApplicationType: "infer",
|
|
3640
|
+
clientRegistrationRequirePKCE: true,
|
|
3641
|
+
grantTypes: ["authorization_code", "refresh_token"],
|
|
3642
|
+
accessTokenExpiresIn: config.sessions.accessTokenSeconds,
|
|
3643
|
+
refreshTokenExpiresIn: config.sessions.idleSeconds,
|
|
3644
|
+
refreshTokenReuseInterval: 0
|
|
3442
3645
|
})
|
|
3443
3646
|
]
|
|
3444
3647
|
});
|
|
3445
3648
|
return {
|
|
3446
|
-
|
|
3649
|
+
verifyAuthorizationQuery: ({ query }) => verifyOAuthQueryParams(query, options.secret),
|
|
3650
|
+
migrate: async () => {
|
|
3651
|
+
await options.database.migrate({
|
|
3652
|
+
options: auth.options,
|
|
3653
|
+
resource: `${options.baseURL}/api`
|
|
3654
|
+
});
|
|
3655
|
+
await (await auth.$context).explicitSchemaCheck?.();
|
|
3656
|
+
},
|
|
3447
3657
|
createLocalUser: async (args) => {
|
|
3448
3658
|
if (!config.local.enabled) {
|
|
3449
3659
|
throw new Error("Local username and password authentication is disabled");
|
|
@@ -3492,20 +3702,33 @@ function createWorkAuth(options) {
|
|
|
3492
3702
|
return found ? workAuthUser(found.user) : null;
|
|
3493
3703
|
},
|
|
3494
3704
|
resolveAccessToken: async ({ authorization }) => {
|
|
3495
|
-
const
|
|
3496
|
-
|
|
3497
|
-
});
|
|
3498
|
-
if (!result?.userId)
|
|
3705
|
+
const bearerToken = /^Bearer ([^\s]+)$/i.exec(authorization)?.[1];
|
|
3706
|
+
if (!bearerToken)
|
|
3499
3707
|
return null;
|
|
3500
3708
|
const context = await auth.$context;
|
|
3501
|
-
const
|
|
3709
|
+
const parsed = AccessGrant.safeParse(await context.adapter.findOne({
|
|
3710
|
+
model: "oauthAccessToken",
|
|
3711
|
+
where: [{ field: "token", value: authTokenHash(bearerToken) }]
|
|
3712
|
+
}));
|
|
3713
|
+
if (!parsed.success)
|
|
3714
|
+
return null;
|
|
3715
|
+
const grant = parsed.data;
|
|
3716
|
+
if (!grant.userId || grant.revoked || !grant.resources?.includes(`${options.baseURL}/api`) || grant.confirmation != null || grant.expiresAt.getTime() <= Date.now())
|
|
3717
|
+
return null;
|
|
3718
|
+
const client = z9.object({ disabled: z9.boolean().nullish() }).safeParse(await context.adapter.findOne({
|
|
3719
|
+
model: "oauthClient",
|
|
3720
|
+
where: [{ field: "clientId", value: grant.clientId }]
|
|
3721
|
+
}));
|
|
3722
|
+
if (!client.success || client.data.disabled === true)
|
|
3723
|
+
return null;
|
|
3724
|
+
const user = await context.internalAdapter.findUserById(grant.userId);
|
|
3502
3725
|
if (!user)
|
|
3503
3726
|
return null;
|
|
3504
3727
|
return {
|
|
3505
|
-
userId:
|
|
3728
|
+
userId: grant.userId,
|
|
3506
3729
|
email: user.email,
|
|
3507
3730
|
emailVerified: user.emailVerified,
|
|
3508
|
-
scopes:
|
|
3731
|
+
scopes: grant.scopes
|
|
3509
3732
|
};
|
|
3510
3733
|
},
|
|
3511
3734
|
accountsFor: async ({ userId }) => {
|
|
@@ -3520,24 +3743,45 @@ function createWorkAuth(options) {
|
|
|
3520
3743
|
const context = await auth.$context;
|
|
3521
3744
|
return toGrant(await context.adapter.findOne({
|
|
3522
3745
|
model: "oauthAccessToken",
|
|
3523
|
-
where: [{ field: "
|
|
3746
|
+
where: [{ field: "token", value: authTokenHash(accessToken) }]
|
|
3524
3747
|
}));
|
|
3525
3748
|
},
|
|
3526
3749
|
grantByRefreshToken: async ({ refreshToken }) => {
|
|
3527
3750
|
const context = await auth.$context;
|
|
3751
|
+
const refresh = z9.object({ id: z9.string() }).safeParse(await context.adapter.findOne({
|
|
3752
|
+
model: "oauthRefreshToken",
|
|
3753
|
+
where: [{ field: "token", value: authTokenHash(refreshToken) }]
|
|
3754
|
+
}));
|
|
3755
|
+
if (!refresh.success)
|
|
3756
|
+
return null;
|
|
3528
3757
|
return toGrant(await context.adapter.findOne({
|
|
3529
3758
|
model: "oauthAccessToken",
|
|
3530
|
-
where: [{ field: "
|
|
3759
|
+
where: [{ field: "refreshId", value: refresh.data.id }]
|
|
3531
3760
|
}));
|
|
3532
3761
|
},
|
|
3533
3762
|
deleteGrants: async ({ ids }) => {
|
|
3534
3763
|
if (ids.length === 0)
|
|
3535
3764
|
return;
|
|
3536
3765
|
const context = await auth.$context;
|
|
3766
|
+
const grants = await context.adapter.findMany({
|
|
3767
|
+
model: "oauthAccessToken",
|
|
3768
|
+
where: [{ field: "id", operator: "in", value: [...ids] }]
|
|
3769
|
+
});
|
|
3770
|
+
const refreshIds = grants.flatMap((grant) => typeof grant === "object" && grant !== null && ("refreshId" in grant) && typeof grant.refreshId === "string" ? [grant.refreshId] : []);
|
|
3537
3771
|
await context.adapter.deleteMany({
|
|
3538
3772
|
model: "oauthAccessToken",
|
|
3539
3773
|
where: [{ field: "id", operator: "in", value: [...ids] }]
|
|
3540
3774
|
});
|
|
3775
|
+
if (refreshIds.length) {
|
|
3776
|
+
await context.adapter.deleteMany({
|
|
3777
|
+
model: "oauthAccessToken",
|
|
3778
|
+
where: [{ field: "refreshId", operator: "in", value: refreshIds }]
|
|
3779
|
+
});
|
|
3780
|
+
await context.adapter.deleteMany({
|
|
3781
|
+
model: "oauthRefreshToken",
|
|
3782
|
+
where: [{ field: "id", operator: "in", value: refreshIds }]
|
|
3783
|
+
});
|
|
3784
|
+
}
|
|
3541
3785
|
},
|
|
3542
3786
|
signOutEverywhere: async ({ userId }) => {
|
|
3543
3787
|
const context = await auth.$context;
|
|
@@ -3545,6 +3789,10 @@ function createWorkAuth(options) {
|
|
|
3545
3789
|
model: "oauthAccessToken",
|
|
3546
3790
|
where: [{ field: "userId", value: userId }]
|
|
3547
3791
|
});
|
|
3792
|
+
await context.adapter.deleteMany({
|
|
3793
|
+
model: "oauthRefreshToken",
|
|
3794
|
+
where: [{ field: "userId", value: userId }]
|
|
3795
|
+
});
|
|
3548
3796
|
await context.internalAdapter.deleteUserSessions(userId);
|
|
3549
3797
|
},
|
|
3550
3798
|
usersSignedIn: async () => {
|
|
@@ -3552,9 +3800,10 @@ function createWorkAuth(options) {
|
|
|
3552
3800
|
const now = new Date;
|
|
3553
3801
|
const [grants, sessions] = await Promise.all([
|
|
3554
3802
|
context.adapter.findMany({
|
|
3555
|
-
model: "
|
|
3803
|
+
model: "oauthRefreshToken",
|
|
3556
3804
|
where: [
|
|
3557
|
-
{ field: "
|
|
3805
|
+
{ field: "expiresAt", operator: "gt", value: now },
|
|
3806
|
+
{ field: "revoked", value: null }
|
|
3558
3807
|
]
|
|
3559
3808
|
}),
|
|
3560
3809
|
context.adapter.findMany({
|
|
@@ -3582,6 +3831,19 @@ function createWorkAuth(options) {
|
|
|
3582
3831
|
close: () => options.database.close()
|
|
3583
3832
|
};
|
|
3584
3833
|
}
|
|
3834
|
+
var AccessGrant = z9.object({
|
|
3835
|
+
id: z9.string(),
|
|
3836
|
+
userId: z9.string().nullish(),
|
|
3837
|
+
clientId: z9.string(),
|
|
3838
|
+
expiresAt: z9.coerce.date(),
|
|
3839
|
+
revoked: z9.coerce.date().nullish(),
|
|
3840
|
+
scopes: z9.array(z9.string()),
|
|
3841
|
+
resources: z9.array(z9.string()).nullish(),
|
|
3842
|
+
confirmation: z9.unknown().nullish()
|
|
3843
|
+
});
|
|
3844
|
+
function authTokenHash(token) {
|
|
3845
|
+
return createHash2("sha256").update(token).digest("base64url");
|
|
3846
|
+
}
|
|
3585
3847
|
function toGrant(row) {
|
|
3586
3848
|
if (typeof row !== "object" || row === null)
|
|
3587
3849
|
return null;
|
|
@@ -3668,7 +3930,7 @@ function isNodeError2(error) {
|
|
|
3668
3930
|
}
|
|
3669
3931
|
|
|
3670
3932
|
// src/cluster.ts
|
|
3671
|
-
import { createECDH, createHash as
|
|
3933
|
+
import { createECDH, createHash as createHash4 } from "node:crypto";
|
|
3672
3934
|
import {
|
|
3673
3935
|
capacityFits,
|
|
3674
3936
|
cleanupWorkerAllocations as cleanupWorkerAllocations2,
|
|
@@ -3683,10 +3945,10 @@ import {
|
|
|
3683
3945
|
placementOrder,
|
|
3684
3946
|
poolMatches
|
|
3685
3947
|
} from "@catamorphic/sandbox";
|
|
3686
|
-
import { sql as
|
|
3948
|
+
import { sql as sql4 } from "kysely";
|
|
3687
3949
|
|
|
3688
3950
|
// src/workers/worker-registry.ts
|
|
3689
|
-
import { createHash, randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
|
|
3951
|
+
import { createHash as createHash3, randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
|
|
3690
3952
|
import {
|
|
3691
3953
|
cleanupWorkerAllocations,
|
|
3692
3954
|
forgetExecutorKey,
|
|
@@ -3702,17 +3964,17 @@ import {
|
|
|
3702
3964
|
import {
|
|
3703
3965
|
ExecutorPublicKeySchema
|
|
3704
3966
|
} from "@catamorphic/sandbox";
|
|
3705
|
-
import { sql as
|
|
3706
|
-
import { z as
|
|
3967
|
+
import { sql as sql3 } from "kysely";
|
|
3968
|
+
import { z as z10 } from "zod";
|
|
3707
3969
|
var WORKER_NODE_PREFIX = "worker.";
|
|
3708
|
-
var WorkerName =
|
|
3709
|
-
var WorkerOfferSchema =
|
|
3710
|
-
isolation:
|
|
3711
|
-
resourceLimits:
|
|
3712
|
-
workspaceRoot:
|
|
3713
|
-
processes:
|
|
3714
|
-
capabilities:
|
|
3715
|
-
|
|
3970
|
+
var WorkerName = z10.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/, "Use lowercase letters, digits, dashes");
|
|
3971
|
+
var WorkerOfferSchema = z10.strictObject({
|
|
3972
|
+
isolation: z10.enum(["process", "sandbox"]),
|
|
3973
|
+
resourceLimits: z10.array(z10.enum(["cpuMillis", "memoryMb", "storageMb", "gpu"])).default([]),
|
|
3974
|
+
workspaceRoot: z10.string().startsWith("/"),
|
|
3975
|
+
processes: z10.boolean().default(false),
|
|
3976
|
+
capabilities: z10.array(z10.union([
|
|
3977
|
+
z10.enum([
|
|
3716
3978
|
"images",
|
|
3717
3979
|
"images.build",
|
|
3718
3980
|
"containers",
|
|
@@ -3724,26 +3986,26 @@ var WorkerOfferSchema = z8.strictObject({
|
|
|
3724
3986
|
"harness.codex",
|
|
3725
3987
|
"sign-ins"
|
|
3726
3988
|
]),
|
|
3727
|
-
|
|
3989
|
+
z10.string().regex(/^sign-in:(claude-code|codex):\S{1,255}$/)
|
|
3728
3990
|
])).max(1e4).default([]),
|
|
3729
|
-
capacity:
|
|
3730
|
-
workspaces:
|
|
3731
|
-
cpuMillis:
|
|
3732
|
-
memoryMb:
|
|
3991
|
+
capacity: z10.strictObject({
|
|
3992
|
+
workspaces: z10.number().int().positive().max(1000),
|
|
3993
|
+
cpuMillis: z10.number().int().positive().optional(),
|
|
3994
|
+
memoryMb: z10.number().int().positive().optional()
|
|
3733
3995
|
}),
|
|
3734
|
-
defaults:
|
|
3735
|
-
cpuMillis:
|
|
3736
|
-
memoryMb:
|
|
3996
|
+
defaults: z10.strictObject({
|
|
3997
|
+
cpuMillis: z10.number().int().positive().optional(),
|
|
3998
|
+
memoryMb: z10.number().int().positive().optional()
|
|
3737
3999
|
}).default({}),
|
|
3738
|
-
version:
|
|
3739
|
-
backend:
|
|
3740
|
-
kind:
|
|
3741
|
-
runtime:
|
|
3742
|
-
reason:
|
|
4000
|
+
version: z10.string().max(100).optional(),
|
|
4001
|
+
backend: z10.strictObject({
|
|
4002
|
+
kind: z10.enum(["microsandbox", "container", "local-process"]),
|
|
4003
|
+
runtime: z10.enum(["runsc", "runc"]).optional(),
|
|
4004
|
+
reason: z10.string().max(1000)
|
|
3743
4005
|
}).optional()
|
|
3744
4006
|
});
|
|
3745
|
-
var WorkerConnectSchema =
|
|
3746
|
-
session:
|
|
4007
|
+
var WorkerConnectSchema = z10.strictObject({
|
|
4008
|
+
session: z10.string().regex(REMOTE_EPOCH_PATTERN, "Use a UUIDv7 epoch"),
|
|
3747
4009
|
offer: WorkerOfferSchema,
|
|
3748
4010
|
publicKey: ExecutorPublicKeySchema
|
|
3749
4011
|
});
|
|
@@ -3756,7 +4018,7 @@ class WorkerIsolationError extends Error {
|
|
|
3756
4018
|
}
|
|
3757
4019
|
}
|
|
3758
4020
|
var NOBODY = { nobody: true };
|
|
3759
|
-
var releasedFor =
|
|
4021
|
+
var releasedFor = sql3`(extract(epoch from (now() - released_at)) * 1000)::float8`;
|
|
3760
4022
|
|
|
3761
4023
|
class WorkerDisabledError extends Error {
|
|
3762
4024
|
constructor() {
|
|
@@ -3842,9 +4104,9 @@ class WorkWorkerRegistry {
|
|
|
3842
4104
|
throw await this.ended(args);
|
|
3843
4105
|
}
|
|
3844
4106
|
async seen(nodeId) {
|
|
3845
|
-
await this.deps.db.updateTable("work_workers").set({ last_seen_at:
|
|
4107
|
+
await this.deps.db.updateTable("work_workers").set({ last_seen_at: sql3`now()` }).where("node_id", "=", nodeId).where((eb) => eb.or([
|
|
3846
4108
|
eb("last_seen_at", "is", null),
|
|
3847
|
-
eb("last_seen_at", "<",
|
|
4109
|
+
eb("last_seen_at", "<", sql3`now() - interval '5 seconds'`)
|
|
3848
4110
|
])).execute();
|
|
3849
4111
|
}
|
|
3850
4112
|
async ended(args) {
|
|
@@ -3870,7 +4132,7 @@ class WorkWorkerRegistry {
|
|
|
3870
4132
|
const name = WorkerName.parse(args.name);
|
|
3871
4133
|
const placement = WorkerPlacementSchema.parse(args.placement ?? {});
|
|
3872
4134
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
3873
|
-
await
|
|
4135
|
+
await sql3`SELECT pg_advisory_xact_lock(hashtext(${`work-worker-name:${this.deps.tenantId}:${name}`}))`.execute(trx);
|
|
3874
4136
|
const enrolled = await trx.selectFrom("work_workers").select("node_id").where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).where("revoked_at", "is", null).executeTakeFirst();
|
|
3875
4137
|
if (enrolled)
|
|
3876
4138
|
return null;
|
|
@@ -3899,7 +4161,7 @@ class WorkWorkerRegistry {
|
|
|
3899
4161
|
async enroll(args) {
|
|
3900
4162
|
const publicKey = ExecutorPublicKeySchema.parse(args.publicKey);
|
|
3901
4163
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
3902
|
-
const enrollment = await trx.updateTable("work_worker_enrollments").set({ used_at:
|
|
4164
|
+
const enrollment = await trx.updateTable("work_worker_enrollments").set({ used_at: sql3`now()` }).where("code_hash", "=", hash(args.code)).where("tenant_id", "=", this.deps.tenantId).where("used_at", "is", null).where("expires_at", ">", sql3`now()`).returning([
|
|
3903
4165
|
"name",
|
|
3904
4166
|
"labels",
|
|
3905
4167
|
"access",
|
|
@@ -3945,7 +4207,7 @@ class WorkWorkerRegistry {
|
|
|
3945
4207
|
return;
|
|
3946
4208
|
const nodeId = match[1];
|
|
3947
4209
|
const presented = hash(match[2]);
|
|
3948
|
-
const row = await this.deps.db.selectFrom("work_workers").select(["name", "credential_hash", "pending_credential_hash"]).select(
|
|
4210
|
+
const row = await this.deps.db.selectFrom("work_workers").select(["name", "credential_hash", "pending_credential_hash"]).select(sql3`rotation_requested_at IS NOT NULL OR credential_issued_at < now() - make_interval(days => ${WORKER_CREDENTIAL_MAX_AGE_DAYS})`.as("rotate")).where("node_id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).where("revoked_at", "is", null).executeTakeFirst();
|
|
3949
4211
|
if (!row)
|
|
3950
4212
|
return;
|
|
3951
4213
|
if (sameHash(row.credential_hash, presented))
|
|
@@ -3970,13 +4232,13 @@ class WorkWorkerRegistry {
|
|
|
3970
4232
|
return;
|
|
3971
4233
|
const promoted = await trx.updateTable("work_workers").set({
|
|
3972
4234
|
credential_hash: args.credentialHash,
|
|
3973
|
-
credential_issued_at:
|
|
4235
|
+
credential_issued_at: sql3`COALESCE(pending_issued_at, now())`,
|
|
3974
4236
|
pending_credential_hash: null,
|
|
3975
4237
|
pending_public_key: null,
|
|
3976
4238
|
pending_issued_at: null,
|
|
3977
4239
|
pending_rotation: null,
|
|
3978
|
-
rotation_requested_at:
|
|
3979
|
-
}).where("node_id", "=", args.nodeId).returning(
|
|
4240
|
+
rotation_requested_at: sql3`CASE WHEN rotation_requested_at <= pending_issued_at THEN NULL ELSE rotation_requested_at END`
|
|
4241
|
+
}).where("node_id", "=", args.nodeId).returning(sql3`rotation_requested_at IS NOT NULL`.as("rotate")).executeTakeFirstOrThrow();
|
|
3980
4242
|
await registerExecutorKey({
|
|
3981
4243
|
db: trx,
|
|
3982
4244
|
executor: nodeExecutor(args.nodeId),
|
|
@@ -4000,14 +4262,14 @@ class WorkWorkerRegistry {
|
|
|
4000
4262
|
await trx.updateTable("work_workers").set({
|
|
4001
4263
|
pending_credential_hash: hash(secret),
|
|
4002
4264
|
pending_public_key: publicKey,
|
|
4003
|
-
pending_issued_at:
|
|
4265
|
+
pending_issued_at: sql3`now()`,
|
|
4004
4266
|
pending_rotation: args.rotation
|
|
4005
4267
|
}).where("node_id", "=", args.nodeId).execute();
|
|
4006
4268
|
});
|
|
4007
4269
|
return { credential: `${args.nodeId}:${secret}` };
|
|
4008
4270
|
}
|
|
4009
4271
|
async requestRotation(args) {
|
|
4010
|
-
const row = await this.deps.db.updateTable("work_workers").set({ rotation_requested_at:
|
|
4272
|
+
const row = await this.deps.db.updateTable("work_workers").set({ rotation_requested_at: sql3`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", WorkerName.parse(args.name)).where("revoked_at", "is", null).returning("node_id").executeTakeFirst();
|
|
4011
4273
|
return Boolean(row);
|
|
4012
4274
|
}
|
|
4013
4275
|
async connect(args) {
|
|
@@ -4133,7 +4395,7 @@ class WorkWorkerRegistry {
|
|
|
4133
4395
|
}
|
|
4134
4396
|
async revoke(args) {
|
|
4135
4397
|
const row = await this.deps.db.updateTable("work_workers").set({
|
|
4136
|
-
revoked_at:
|
|
4398
|
+
revoked_at: sql3`now()`,
|
|
4137
4399
|
pending_credential_hash: null,
|
|
4138
4400
|
pending_public_key: null,
|
|
4139
4401
|
pending_issued_at: null,
|
|
@@ -4156,17 +4418,17 @@ class WorkWorkerRegistry {
|
|
|
4156
4418
|
async drain(args) {
|
|
4157
4419
|
const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
|
|
4158
4420
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
4159
|
-
const node = await trx.selectFrom("worker_nodes").select(
|
|
4421
|
+
const node = await trx.selectFrom("worker_nodes").select(sql3`enabled AND lease_expires_at > now()`.as("live")).where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).forUpdate().executeTakeFirst();
|
|
4160
4422
|
const held = await trx.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", nodeId).where("capacity_released_at", "is", null).executeTakeFirst();
|
|
4161
4423
|
if (Number(held?.count ?? 0) > 0) {
|
|
4162
4424
|
if (node?.live)
|
|
4163
4425
|
return false;
|
|
4164
|
-
const lost = await trx.selectFrom("work_workers").select("node_id").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where(
|
|
4426
|
+
const lost = await trx.selectFrom("work_workers").select("node_id").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where(sql3`coalesce(last_seen_at, enrolled_at) <= now() - make_interval(secs => ${args.unseenForMs / 1000})`).executeTakeFirst();
|
|
4165
4427
|
if (!lost)
|
|
4166
4428
|
return false;
|
|
4167
4429
|
}
|
|
4168
4430
|
const revoked = await trx.updateTable("work_workers").set({
|
|
4169
|
-
revoked_at:
|
|
4431
|
+
revoked_at: sql3`now()`,
|
|
4170
4432
|
pending_credential_hash: null,
|
|
4171
4433
|
pending_public_key: null,
|
|
4172
4434
|
pending_issued_at: null,
|
|
@@ -4183,17 +4445,17 @@ class WorkWorkerRegistry {
|
|
|
4183
4445
|
const machines = this.deps.db.selectFrom("work_workers").select("node_id").where("tenant_id", "=", this.deps.tenantId).where("machine_rule", "is not", null).where("revoked_at", "is", null);
|
|
4184
4446
|
const load = this.deps.db.selectFrom("execution_allocations").select([
|
|
4185
4447
|
"worker_node_id",
|
|
4186
|
-
|
|
4187
|
-
|
|
4448
|
+
sql3`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as("holding"),
|
|
4449
|
+
sql3`max(capacity_released_at)`.as("last_released")
|
|
4188
4450
|
]).where("worker_node_id", "in", machines).groupBy("worker_node_id").as("load");
|
|
4189
4451
|
const [rows, nodes] = await Promise.all([
|
|
4190
4452
|
this.deps.db.selectFrom("work_workers").leftJoin(load, "load.worker_node_id", "work_workers.node_id").select([
|
|
4191
4453
|
"work_workers.name",
|
|
4192
4454
|
"work_workers.node_id",
|
|
4193
4455
|
"load.holding",
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4456
|
+
sql3`work_workers.last_seen_at IS NULL`.as("never_connected"),
|
|
4457
|
+
sql3`(extract(epoch from (now() - greatest(work_workers.enrolled_at, load.last_released))) * 1000)::float8`.as("idle_for_ms"),
|
|
4458
|
+
sql3`(extract(epoch from (now() - coalesce(work_workers.last_seen_at, work_workers.enrolled_at))) * 1000)::float8`.as("unseen_for_ms")
|
|
4197
4459
|
]).where("work_workers.tenant_id", "=", this.deps.tenantId).where("work_workers.machine_rule", "is not", null).where("work_workers.revoked_at", "is", null).execute(),
|
|
4198
4460
|
this.deps.nodes.list({
|
|
4199
4461
|
tenantId: this.deps.tenantId,
|
|
@@ -4254,7 +4516,7 @@ class WorkWorkerRegistry {
|
|
|
4254
4516
|
"labels",
|
|
4255
4517
|
"access",
|
|
4256
4518
|
"trusted",
|
|
4257
|
-
|
|
4519
|
+
sql3`expires_at <= now()`.as("expired")
|
|
4258
4520
|
]).where("tenant_id", "=", this.deps.tenantId).where("machine_rule", "is not", null).where("used_at", "is", null).execute()
|
|
4259
4521
|
]);
|
|
4260
4522
|
return [
|
|
@@ -4314,7 +4576,7 @@ class WorkWorkerRegistry {
|
|
|
4314
4576
|
return Boolean(assigned);
|
|
4315
4577
|
}
|
|
4316
4578
|
async release(args) {
|
|
4317
|
-
await this.deps.db.updateTable("work_workers").set({ released_at:
|
|
4579
|
+
await this.deps.db.updateTable("work_workers").set({ released_at: sql3`now()`, retain_days: args.retainDays }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("revoked_at", "is", null).where("released_at", "is", null).execute();
|
|
4318
4580
|
}
|
|
4319
4581
|
async reassign(args) {
|
|
4320
4582
|
await this.deps.db.updateTable("work_workers").set({
|
|
@@ -4375,11 +4637,11 @@ class WorkWorkerRegistry {
|
|
|
4375
4637
|
}).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("pool", "=", true).where("machine_rule", "is", null).execute();
|
|
4376
4638
|
}
|
|
4377
4639
|
async forgetMachine(args) {
|
|
4378
|
-
await this.deps.db.updateTable("work_workers").set({ machine_destroyed_at:
|
|
4640
|
+
await this.deps.db.updateTable("work_workers").set({ machine_destroyed_at: sql3`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("machine_rule", "is not", null).where("revoked_at", "is not", null).where("machine_destroyed_at", "is", null).execute();
|
|
4379
4641
|
await this.cancelEnrollments({ name: args.name });
|
|
4380
4642
|
}
|
|
4381
4643
|
async expireEnrollments(args) {
|
|
4382
|
-
await this.deps.db.updateTable("work_worker_enrollments").set({ expires_at:
|
|
4644
|
+
await this.deps.db.updateTable("work_worker_enrollments").set({ expires_at: sql3`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("used_at", "is", null).where("expires_at", ">", sql3`now()`).execute();
|
|
4383
4645
|
}
|
|
4384
4646
|
async cancelEnrollments(args) {
|
|
4385
4647
|
await this.deps.db.deleteFrom("work_worker_enrollments").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("used_at", "is", null).execute();
|
|
@@ -4408,7 +4670,7 @@ class WorkWorkerRegistry {
|
|
|
4408
4670
|
}
|
|
4409
4671
|
}
|
|
4410
4672
|
function hash(value) {
|
|
4411
|
-
return
|
|
4673
|
+
return createHash3("sha256").update(value).digest("hex");
|
|
4412
4674
|
}
|
|
4413
4675
|
function workerState(row) {
|
|
4414
4676
|
if (row.revoked_at)
|
|
@@ -4643,7 +4905,7 @@ async function registerWorkMachine(args) {
|
|
|
4643
4905
|
if (JSON.stringify(next) === JSON.stringify(signIns))
|
|
4644
4906
|
return;
|
|
4645
4907
|
signIns = next;
|
|
4646
|
-
refreshing = args.db.updateTable("worker_nodes").set({ descriptor: JSON.stringify(describe()), updated_at:
|
|
4908
|
+
refreshing = args.db.updateTable("worker_nodes").set({ descriptor: JSON.stringify(describe()), updated_at: sql4`now()` }).where("id", "=", lease.id).where("lease_token", "=", lease.token).execute().catch((error) => console.warn("[catamorphic] Could not refresh this machine's sign-ins", error)).finally(() => {
|
|
4647
4909
|
refreshing = undefined;
|
|
4648
4910
|
if (!again)
|
|
4649
4911
|
return;
|
|
@@ -4672,12 +4934,12 @@ async function registerWorkMachine(args) {
|
|
|
4672
4934
|
};
|
|
4673
4935
|
}
|
|
4674
4936
|
function workAuthorityId(publicBase) {
|
|
4675
|
-
return `work:${
|
|
4937
|
+
return `work:${createHash4("sha256").update(publicBase).digest("hex").slice(0, 24)}`;
|
|
4676
4938
|
}
|
|
4677
4939
|
function workPushKeys(secret) {
|
|
4678
4940
|
const ecdh = createECDH("prime256v1");
|
|
4679
4941
|
for (let counter = 0;counter < 10; counter += 1) {
|
|
4680
|
-
const key =
|
|
4942
|
+
const key = createHash4("sha256").update(`catamorphic/push/v1/${counter}\x00`).update(secret).digest();
|
|
4681
4943
|
try {
|
|
4682
4944
|
ecdh.setPrivateKey(key);
|
|
4683
4945
|
return {
|
|
@@ -4783,7 +5045,7 @@ function startCompanyProjectSync(input) {
|
|
|
4783
5045
|
}
|
|
4784
5046
|
|
|
4785
5047
|
// src/credential-vault.ts
|
|
4786
|
-
import { createHash as
|
|
5048
|
+
import { createHash as createHash5, randomBytes as randomBytes4, randomUUID as randomUUID4 } from "node:crypto";
|
|
4787
5049
|
import fs9 from "node:fs";
|
|
4788
5050
|
import path6 from "node:path";
|
|
4789
5051
|
import { EncryptedCredentialVault } from "@catamorphic/core";
|
|
@@ -4805,7 +5067,7 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4805
5067
|
const records = path6.join(directory, "records");
|
|
4806
5068
|
fs9.mkdirSync(records, { recursive: true, mode: 448 });
|
|
4807
5069
|
fs9.chmodSync(records, 448);
|
|
4808
|
-
const file = (key) => path6.join(records, `${
|
|
5070
|
+
const file = (key) => path6.join(records, `${createHash5("sha256").update(key).digest("hex")}.json`);
|
|
4809
5071
|
super({
|
|
4810
5072
|
keys: configuredKeys.length > 0 ? configuredKeys : [fs9.readFileSync(keyFile)],
|
|
4811
5073
|
store: {
|
|
@@ -4814,7 +5076,7 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4814
5076
|
const data = fs9.readFileSync(file(key));
|
|
4815
5077
|
return {
|
|
4816
5078
|
data,
|
|
4817
|
-
etag:
|
|
5079
|
+
etag: createHash5("sha256").update(data).digest("hex")
|
|
4818
5080
|
};
|
|
4819
5081
|
} catch (error) {
|
|
4820
5082
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
@@ -4824,7 +5086,7 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4824
5086
|
},
|
|
4825
5087
|
put: async (key, data) => {
|
|
4826
5088
|
const target = file(key);
|
|
4827
|
-
const temporary = `${target}.${
|
|
5089
|
+
const temporary = `${target}.${randomUUID4()}.tmp`;
|
|
4828
5090
|
fs9.writeFileSync(temporary, data, { mode: 384, flag: "wx" });
|
|
4829
5091
|
fs9.renameSync(temporary, target);
|
|
4830
5092
|
},
|
|
@@ -4837,14 +5099,14 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4837
5099
|
}
|
|
4838
5100
|
|
|
4839
5101
|
// src/identity/account-lifecycle.ts
|
|
4840
|
-
import { createHash as
|
|
5102
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
4841
5103
|
import { getTracer, withSpan } from "@catamorphic/otel";
|
|
4842
5104
|
import {
|
|
4843
5105
|
DIRECTORY_EVENT_KINDS,
|
|
4844
5106
|
DIRECTORY_EVENT_SOURCE,
|
|
4845
5107
|
directoryProjectEvent
|
|
4846
5108
|
} from "@catamorphic/server-sdk";
|
|
4847
|
-
import { sql as
|
|
5109
|
+
import { sql as sql5 } from "kysely";
|
|
4848
5110
|
var tracer = getTracer("@catamorphic/work-server");
|
|
4849
5111
|
|
|
4850
5112
|
class AccountLifecycle {
|
|
@@ -5052,7 +5314,7 @@ class AccountLifecycle {
|
|
|
5052
5314
|
let claimed;
|
|
5053
5315
|
try {
|
|
5054
5316
|
return await this.deps.db.transaction().execute(async (trx) => {
|
|
5055
|
-
const row = await trx.selectFrom("work_directory_announcements as event").selectAll("event").where("event.next_attempt_at", "<=",
|
|
5317
|
+
const row = await trx.selectFrom("work_directory_announcements as event").selectAll("event").where("event.next_attempt_at", "<=", sql5`now()`).$if(input.externalId !== undefined, (query) => query.where("event.external_id", "=", input.externalId ?? "")).where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_directory_announcements as earlier").select("earlier.id").whereRef("earlier.user_id", "=", "event.user_id").whereRef("earlier.revision", "<", "event.revision")))).orderBy("event.created_at").limit(1).forUpdate().skipLocked().executeTakeFirst();
|
|
5056
5318
|
if (!row)
|
|
5057
5319
|
return "none";
|
|
5058
5320
|
claimed = {
|
|
@@ -5080,7 +5342,7 @@ class AccountLifecycle {
|
|
|
5080
5342
|
await this.deps.db.updateTable("work_directory_announcements").set({
|
|
5081
5343
|
attempts: attempts + 1,
|
|
5082
5344
|
last_error: message,
|
|
5083
|
-
next_attempt_at:
|
|
5345
|
+
next_attempt_at: sql5`now() + make_interval(secs => ${Math.min(300, 2 ** attempts)})`
|
|
5084
5346
|
}).where("id", "=", claimed.id).execute();
|
|
5085
5347
|
this.deps.log?.(`Directory event ${claimed.externalId} did not reach its projects (attempt ${attempts + 1}): ${message}`);
|
|
5086
5348
|
return "failed";
|
|
@@ -5277,7 +5539,7 @@ class AccountLifecycle {
|
|
|
5277
5539
|
}
|
|
5278
5540
|
}
|
|
5279
5541
|
function hashToken(token) {
|
|
5280
|
-
return
|
|
5542
|
+
return createHash6("sha256").update(token).digest("hex");
|
|
5281
5543
|
}
|
|
5282
5544
|
function jsonObject(value) {
|
|
5283
5545
|
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
@@ -5293,7 +5555,7 @@ function groupList(value) {
|
|
|
5293
5555
|
}
|
|
5294
5556
|
|
|
5295
5557
|
// src/identity/administrator-routes.ts
|
|
5296
|
-
import { z as
|
|
5558
|
+
import { z as z11 } from "zod";
|
|
5297
5559
|
|
|
5298
5560
|
// src/identity/administrators.ts
|
|
5299
5561
|
var ADMINISTRATOR_PERMISSIONS = [
|
|
@@ -5380,7 +5642,7 @@ function registerAdministratorRoutes(app, options) {
|
|
|
5380
5642
|
const caller = await administrator(request);
|
|
5381
5643
|
if (caller.status !== 200)
|
|
5382
5644
|
return reply.status(caller.status).send(refusal(caller.status));
|
|
5383
|
-
const body =
|
|
5645
|
+
const body = z11.strictObject({ email: z11.email() }).safeParse(request.body);
|
|
5384
5646
|
if (!body.success)
|
|
5385
5647
|
return reply.status(400).send({ error: "An email address is required" });
|
|
5386
5648
|
try {
|
|
@@ -5398,7 +5660,7 @@ function registerAdministratorRoutes(app, options) {
|
|
|
5398
5660
|
const caller = await administrator(request);
|
|
5399
5661
|
if (caller.status !== 200)
|
|
5400
5662
|
return reply.status(caller.status).send(refusal(caller.status));
|
|
5401
|
-
const { userId } =
|
|
5663
|
+
const { userId } = z11.object({ userId: z11.string().min(1) }).parse(request.params);
|
|
5402
5664
|
try {
|
|
5403
5665
|
await options.administrators.set({ userId, administrator: false });
|
|
5404
5666
|
return reply.status(204).send();
|
|
@@ -5419,7 +5681,7 @@ import {
|
|
|
5419
5681
|
ConnectionPermissionDeniedError,
|
|
5420
5682
|
ConnectionUnavailableError
|
|
5421
5683
|
} from "@catamorphic/core";
|
|
5422
|
-
import { z as
|
|
5684
|
+
import { z as z12 } from "zod";
|
|
5423
5685
|
|
|
5424
5686
|
// src/setup/operator-access.ts
|
|
5425
5687
|
import { randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
@@ -5474,18 +5736,18 @@ function isNodeError3(error) {
|
|
|
5474
5736
|
}
|
|
5475
5737
|
|
|
5476
5738
|
// src/setup/connections.ts
|
|
5477
|
-
var ServiceConnectionInput =
|
|
5478
|
-
name:
|
|
5479
|
-
providerKind:
|
|
5480
|
-
principalKind:
|
|
5481
|
-
projectId:
|
|
5482
|
-
label:
|
|
5739
|
+
var ServiceConnectionInput = z12.strictObject({
|
|
5740
|
+
name: z12.string().regex(CONNECTION_NAME_PATTERN),
|
|
5741
|
+
providerKind: z12.string().min(1),
|
|
5742
|
+
principalKind: z12.enum(["tenant_service", "project_service"]).default("tenant_service"),
|
|
5743
|
+
projectId: z12.string().uuid().optional(),
|
|
5744
|
+
label: z12.string().min(1).max(200).optional()
|
|
5483
5745
|
});
|
|
5484
|
-
var CompletionInput =
|
|
5485
|
-
authorizationId:
|
|
5486
|
-
fields:
|
|
5746
|
+
var CompletionInput = z12.strictObject({
|
|
5747
|
+
authorizationId: z12.string().min(1),
|
|
5748
|
+
fields: z12.record(z12.string(), z12.string()).default({})
|
|
5487
5749
|
});
|
|
5488
|
-
var Params =
|
|
5750
|
+
var Params = z12.object({ connectionId: z12.string().uuid() });
|
|
5489
5751
|
function registerConnectionSetup(args) {
|
|
5490
5752
|
args.app.register(async (app) => {
|
|
5491
5753
|
app.addHook("onRequest", async (request, reply) => {
|
|
@@ -5585,7 +5847,7 @@ function registerConnectionSetup(args) {
|
|
|
5585
5847
|
administrators: await args.administrators.list()
|
|
5586
5848
|
}));
|
|
5587
5849
|
app.post("/_work/operator/administrators", async (request, reply) => {
|
|
5588
|
-
const body =
|
|
5850
|
+
const body = z12.strictObject({ email: z12.email() }).safeParse(request.body);
|
|
5589
5851
|
if (!body.success)
|
|
5590
5852
|
return reply.status(400).send({ error: "An email address is required" });
|
|
5591
5853
|
try {
|
|
@@ -5604,7 +5866,7 @@ function registerConnectionSetup(args) {
|
|
|
5604
5866
|
}
|
|
5605
5867
|
});
|
|
5606
5868
|
app.delete("/_work/operator/administrators/:userId", async (request, reply) => {
|
|
5607
|
-
const { userId } =
|
|
5869
|
+
const { userId } = z12.object({ userId: z12.string().min(1) }).parse(request.params);
|
|
5608
5870
|
await args.administrators.set({
|
|
5609
5871
|
userId,
|
|
5610
5872
|
administrator: false,
|
|
@@ -5635,7 +5897,7 @@ function firstIssue(error) {
|
|
|
5635
5897
|
}
|
|
5636
5898
|
|
|
5637
5899
|
// src/setup/github-app.ts
|
|
5638
|
-
import { createHash as
|
|
5900
|
+
import { createHash as createHash7, randomBytes as randomBytes6 } from "node:crypto";
|
|
5639
5901
|
import {
|
|
5640
5902
|
UndeclaredSecretError
|
|
5641
5903
|
} from "@catamorphic/core";
|
|
@@ -5644,7 +5906,7 @@ import {
|
|
|
5644
5906
|
convertGithubAppManifest,
|
|
5645
5907
|
githubAppManifestForm
|
|
5646
5908
|
} from "@catamorphic/server-sdk";
|
|
5647
|
-
import { z as
|
|
5909
|
+
import { z as z13 } from "zod";
|
|
5648
5910
|
var WORK_GITHUB_APP_PERMISSIONS = {
|
|
5649
5911
|
contents: "write",
|
|
5650
5912
|
pull_requests: "write",
|
|
@@ -5663,28 +5925,28 @@ var WORK_GITHUB_APP_EVENTS = [
|
|
|
5663
5925
|
"push"
|
|
5664
5926
|
];
|
|
5665
5927
|
var GITHUB_WEBHOOK_SECRET = "GITHUB_WEBHOOK_SECRET";
|
|
5666
|
-
var StartInput =
|
|
5667
|
-
name:
|
|
5668
|
-
organization:
|
|
5669
|
-
projectId:
|
|
5670
|
-
connection:
|
|
5671
|
-
public:
|
|
5928
|
+
var StartInput = z13.strictObject({
|
|
5929
|
+
name: z13.string().trim().min(1).max(34),
|
|
5930
|
+
organization: z13.string().regex(/^[\w.-]+$/).optional(),
|
|
5931
|
+
projectId: z13.string().uuid().optional(),
|
|
5932
|
+
connection: z13.string().regex(/^[a-z0-9][a-z0-9._-]{0,62}$/).default("github"),
|
|
5933
|
+
public: z13.boolean().default(false)
|
|
5672
5934
|
});
|
|
5673
5935
|
var StoredInput = StartInput;
|
|
5674
|
-
var StoredApp =
|
|
5675
|
-
appId:
|
|
5676
|
-
slug:
|
|
5677
|
-
name:
|
|
5678
|
-
owner:
|
|
5679
|
-
htmlUrl:
|
|
5680
|
-
clientId:
|
|
5681
|
-
clientSecret:
|
|
5682
|
-
webhookSecret:
|
|
5683
|
-
privateKey:
|
|
5936
|
+
var StoredApp = z13.object({
|
|
5937
|
+
appId: z13.string(),
|
|
5938
|
+
slug: z13.string(),
|
|
5939
|
+
name: z13.string(),
|
|
5940
|
+
owner: z13.string().nullable(),
|
|
5941
|
+
htmlUrl: z13.string(),
|
|
5942
|
+
clientId: z13.string(),
|
|
5943
|
+
clientSecret: z13.string(),
|
|
5944
|
+
webhookSecret: z13.string().nullable(),
|
|
5945
|
+
privateKey: z13.string()
|
|
5684
5946
|
});
|
|
5685
5947
|
var TTL_MS = 60 * 60 * 1000;
|
|
5686
5948
|
function stateHash(state) {
|
|
5687
|
-
return
|
|
5949
|
+
return createHash7("sha256").update(state).digest("hex");
|
|
5688
5950
|
}
|
|
5689
5951
|
function registrationStore(args) {
|
|
5690
5952
|
const { db, vault, tenantId } = args;
|
|
@@ -5777,7 +6039,7 @@ function registerGithubAppSetup(args) {
|
|
|
5777
6039
|
expiresAt: expiresAt.toISOString()
|
|
5778
6040
|
});
|
|
5779
6041
|
});
|
|
5780
|
-
const Params =
|
|
6042
|
+
const Params = z13.object({ state: z13.string().min(20) });
|
|
5781
6043
|
args.publicApp.get(`${base}/:state`, async (request, reply) => {
|
|
5782
6044
|
const params = Params.safeParse(request.params);
|
|
5783
6045
|
const input = params.success ? await registrations.pending(params.data.state) : undefined;
|
|
@@ -5822,7 +6084,7 @@ function registerGithubAppSetup(args) {
|
|
|
5822
6084
|
});
|
|
5823
6085
|
args.publicApp.get(`${base}/:state/created`, async (request, reply) => {
|
|
5824
6086
|
const params = Params.safeParse(request.params);
|
|
5825
|
-
const query =
|
|
6087
|
+
const query = z13.object({ code: z13.string().min(1), state: z13.string().min(1) }).safeParse(request.query);
|
|
5826
6088
|
if (!params.success || !query.success || query.data.state !== params.data.state || !await registrations.claimCreation(params.data.state))
|
|
5827
6089
|
return expired(reply);
|
|
5828
6090
|
const state = params.data.state;
|
|
@@ -5845,7 +6107,7 @@ function registerGithubAppSetup(args) {
|
|
|
5845
6107
|
});
|
|
5846
6108
|
args.publicApp.get(`${base}/:state/installed`, async (request, reply) => {
|
|
5847
6109
|
const params = Params.safeParse(request.params);
|
|
5848
|
-
const query =
|
|
6110
|
+
const query = z13.object({ installation_id: z13.coerce.number().int().positive() }).safeParse(request.query);
|
|
5849
6111
|
const claimed = params.success && query.success ? await registrations.claimInstallation(params.data.state) : undefined;
|
|
5850
6112
|
if (!params.success || !query.success || !claimed)
|
|
5851
6113
|
return expired(reply);
|
|
@@ -5940,9 +6202,9 @@ function escapeHtml2(value) {
|
|
|
5940
6202
|
}
|
|
5941
6203
|
|
|
5942
6204
|
// src/setup/machines.ts
|
|
5943
|
-
import { z as
|
|
5944
|
-
var MachineParams =
|
|
5945
|
-
var MachineUpdate =
|
|
6205
|
+
import { z as z14 } from "zod";
|
|
6206
|
+
var MachineParams = z14.object({ nodeId: z14.string().min(1) });
|
|
6207
|
+
var MachineUpdate = z14.strictObject({ enabled: z14.boolean() });
|
|
5946
6208
|
function registerMachineSetup(args) {
|
|
5947
6209
|
args.app.register(async (app) => {
|
|
5948
6210
|
app.addHook("onRequest", async (request, reply) => {
|
|
@@ -5997,13 +6259,13 @@ function machineRoutes(args) {
|
|
|
5997
6259
|
operator: "/_work/operator/workers",
|
|
5998
6260
|
admin: "/api/work/machines/workers",
|
|
5999
6261
|
handler: async (request, reply) => {
|
|
6000
|
-
const body =
|
|
6001
|
-
name:
|
|
6002
|
-
ttlMinutes:
|
|
6003
|
-
labels:
|
|
6004
|
-
access:
|
|
6005
|
-
trusted:
|
|
6006
|
-
pool:
|
|
6262
|
+
const body = z14.strictObject({
|
|
6263
|
+
name: z14.string().min(1),
|
|
6264
|
+
ttlMinutes: z14.number().int().positive().max(1440).optional(),
|
|
6265
|
+
labels: z14.unknown().optional(),
|
|
6266
|
+
access: z14.unknown().optional(),
|
|
6267
|
+
trusted: z14.boolean().optional(),
|
|
6268
|
+
pool: z14.boolean().optional()
|
|
6007
6269
|
}).safeParse(request.body);
|
|
6008
6270
|
if (!body.success)
|
|
6009
6271
|
return reply.status(400).send({ error: firstIssue2(body.error) });
|
|
@@ -6057,11 +6319,11 @@ function machineRoutes(args) {
|
|
|
6057
6319
|
operator: "/_work/operator/workers/:name",
|
|
6058
6320
|
admin: "/api/work/machines/workers/:name",
|
|
6059
6321
|
handler: async (request, reply) => {
|
|
6060
|
-
const params =
|
|
6061
|
-
const body =
|
|
6062
|
-
labels:
|
|
6063
|
-
access:
|
|
6064
|
-
trusted:
|
|
6322
|
+
const params = z14.object({ name: z14.string().min(1) }).safeParse(request.params);
|
|
6323
|
+
const body = z14.strictObject({
|
|
6324
|
+
labels: z14.unknown().optional(),
|
|
6325
|
+
access: z14.unknown().optional(),
|
|
6326
|
+
trusted: z14.boolean().optional()
|
|
6065
6327
|
}).safeParse(request.body);
|
|
6066
6328
|
if (!params.success || !body.success)
|
|
6067
6329
|
return reply.status(400).send({ error: "Provide labels, access, or trusted" });
|
|
@@ -6082,7 +6344,7 @@ function machineRoutes(args) {
|
|
|
6082
6344
|
operator: "/_work/operator/workers/:name/rotate",
|
|
6083
6345
|
admin: "/api/work/machines/workers/:name/rotate",
|
|
6084
6346
|
handler: async (request, reply) => {
|
|
6085
|
-
const params =
|
|
6347
|
+
const params = z14.object({ name: z14.string().min(1) }).safeParse(request.params);
|
|
6086
6348
|
if (!params.success)
|
|
6087
6349
|
return reply.status(400).send({ error: "Provide a worker name" });
|
|
6088
6350
|
return await args.workers.requestRotation(params.data) ? { ok: true } : reply.status(404).send({ error: "Worker not found" });
|
|
@@ -6093,7 +6355,7 @@ function machineRoutes(args) {
|
|
|
6093
6355
|
operator: "/_work/operator/workers/:name",
|
|
6094
6356
|
admin: "/api/work/machines/workers/:name",
|
|
6095
6357
|
handler: async (request, reply) => {
|
|
6096
|
-
const params =
|
|
6358
|
+
const params = z14.object({ name: z14.string().min(1) }).safeParse(request.params);
|
|
6097
6359
|
if (!params.success)
|
|
6098
6360
|
return reply.status(400).send({ error: "Provide a worker name" });
|
|
6099
6361
|
return await args.workers.revoke(params.data) ? { ok: true } : reply.status(404).send({ error: "Worker not found" });
|
|
@@ -6113,7 +6375,7 @@ function machineRoutes(args) {
|
|
|
6113
6375
|
operator: "/_work/operator/machine-rules/:name",
|
|
6114
6376
|
admin: "/api/work/machines/rules/:name",
|
|
6115
6377
|
handler: (request, reply) => withRules(reply, async (machines) => {
|
|
6116
|
-
const { name } =
|
|
6378
|
+
const { name } = z14.object({ name: z14.string() }).parse(request.params);
|
|
6117
6379
|
const rule = await machines.setRule({ name, rule: request.body });
|
|
6118
6380
|
machines.reconcileSoon();
|
|
6119
6381
|
return { rule };
|
|
@@ -6124,7 +6386,7 @@ function machineRoutes(args) {
|
|
|
6124
6386
|
operator: "/_work/operator/machine-rules/:name",
|
|
6125
6387
|
admin: "/api/work/machines/rules/:name",
|
|
6126
6388
|
handler: (request, reply) => withRules(reply, async (machines) => {
|
|
6127
|
-
const { name } =
|
|
6389
|
+
const { name } = z14.object({ name: z14.string() }).parse(request.params);
|
|
6128
6390
|
if (!await machines.deleteRule(name))
|
|
6129
6391
|
return reply.status(404).send({ error: "Rule not found" });
|
|
6130
6392
|
machines.reconcileSoon();
|
|
@@ -6165,11 +6427,11 @@ function machineRoutes(args) {
|
|
|
6165
6427
|
method: "POST",
|
|
6166
6428
|
operator: "/_work/operator/machines/:nodeId/workspaces/:allocationId/confirm-destroyed",
|
|
6167
6429
|
handler: async (request, reply) => {
|
|
6168
|
-
const params =
|
|
6169
|
-
nodeId:
|
|
6170
|
-
allocationId:
|
|
6430
|
+
const params = z14.object({
|
|
6431
|
+
nodeId: z14.string().min(1),
|
|
6432
|
+
allocationId: z14.string().uuid()
|
|
6171
6433
|
}).safeParse(request.params);
|
|
6172
|
-
const body =
|
|
6434
|
+
const body = z14.strictObject({ confirmedDestroyed: z14.literal(true) }).safeParse(request.body);
|
|
6173
6435
|
if (!params.success || !body.success)
|
|
6174
6436
|
return reply.status(400).send({
|
|
6175
6437
|
error: "Inspect the physical backend and confirm this retired workspace was destroyed"
|
|
@@ -6204,7 +6466,7 @@ function machineRoutes(args) {
|
|
|
6204
6466
|
];
|
|
6205
6467
|
}
|
|
6206
6468
|
function errorMessage(error, fallback) {
|
|
6207
|
-
return error instanceof
|
|
6469
|
+
return error instanceof z14.ZodError ? firstIssue2(error) : error instanceof Error ? error.message : fallback;
|
|
6208
6470
|
}
|
|
6209
6471
|
function firstIssue2(error) {
|
|
6210
6472
|
const issue = error.issues[0];
|
|
@@ -6212,17 +6474,17 @@ function firstIssue2(error) {
|
|
|
6212
6474
|
}
|
|
6213
6475
|
|
|
6214
6476
|
// src/setup/provision.ts
|
|
6215
|
-
import { z as
|
|
6216
|
-
var ProvisionWorkUserInputSchema =
|
|
6217
|
-
username:
|
|
6218
|
-
name:
|
|
6219
|
-
password:
|
|
6220
|
-
email:
|
|
6221
|
-
administrator:
|
|
6222
|
-
memberships:
|
|
6223
|
-
projectId:
|
|
6224
|
-
roles:
|
|
6225
|
-
grants:
|
|
6477
|
+
import { z as z15 } from "zod";
|
|
6478
|
+
var ProvisionWorkUserInputSchema = z15.strictObject({
|
|
6479
|
+
username: z15.string().trim().min(3).max(30),
|
|
6480
|
+
name: z15.string().trim().min(1).max(200),
|
|
6481
|
+
password: z15.string().min(8).max(128),
|
|
6482
|
+
email: z15.email().optional(),
|
|
6483
|
+
administrator: z15.boolean().optional(),
|
|
6484
|
+
memberships: z15.array(z15.strictObject({
|
|
6485
|
+
projectId: z15.string().min(1),
|
|
6486
|
+
roles: z15.array(z15.string().min(1)).min(1),
|
|
6487
|
+
grants: z15.record(z15.string(), z15.array(z15.string())).optional()
|
|
6226
6488
|
})).optional()
|
|
6227
6489
|
});
|
|
6228
6490
|
async function provisionWorkUser(args) {
|
|
@@ -6247,11 +6509,11 @@ async function provisionWorkUser(args) {
|
|
|
6247
6509
|
})));
|
|
6248
6510
|
return { user, memberships };
|
|
6249
6511
|
}
|
|
6250
|
-
var GrantWorkMembershipInputSchema =
|
|
6251
|
-
email:
|
|
6252
|
-
projectId:
|
|
6253
|
-
roles:
|
|
6254
|
-
grants:
|
|
6512
|
+
var GrantWorkMembershipInputSchema = z15.strictObject({
|
|
6513
|
+
email: z15.email(),
|
|
6514
|
+
projectId: z15.string().min(1),
|
|
6515
|
+
roles: z15.array(z15.string().min(1)).min(1),
|
|
6516
|
+
grants: z15.record(z15.string(), z15.array(z15.string())).optional()
|
|
6255
6517
|
});
|
|
6256
6518
|
async function grantWorkMembership(args) {
|
|
6257
6519
|
await assertCommittedRoles({
|
|
@@ -6289,23 +6551,23 @@ import {
|
|
|
6289
6551
|
RoleDefinitionSchema
|
|
6290
6552
|
} from "@catamorphic/core";
|
|
6291
6553
|
import { PROJECT_ROLES_DIR } from "@catamorphic/workflow/project-layout";
|
|
6292
|
-
import { z as
|
|
6293
|
-
var RoleSlugSchema =
|
|
6294
|
-
var ProvisionWorkProjectInputSchema =
|
|
6295
|
-
name:
|
|
6296
|
-
repository:
|
|
6297
|
-
codeHost:
|
|
6298
|
-
roles:
|
|
6554
|
+
import { z as z16 } from "zod";
|
|
6555
|
+
var RoleSlugSchema = z16.string().min(1).max(100).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
|
|
6556
|
+
var ProvisionWorkProjectInputSchema = z16.strictObject({
|
|
6557
|
+
name: z16.string().trim().min(1).max(200),
|
|
6558
|
+
repository: z16.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).optional(),
|
|
6559
|
+
codeHost: z16.string().regex(/^[a-z0-9][a-z0-9._-]*$/).default("github"),
|
|
6560
|
+
roles: z16.array(z16.strictObject({
|
|
6299
6561
|
slug: RoleSlugSchema,
|
|
6300
6562
|
definition: RoleDefinitionSchema
|
|
6301
6563
|
})).min(1).optional(),
|
|
6302
|
-
admission:
|
|
6303
|
-
mode:
|
|
6564
|
+
admission: z16.strictObject({
|
|
6565
|
+
mode: z16.enum(["invitation_only", "approved_domain", "request", "open"]),
|
|
6304
6566
|
defaultRole: RoleSlugSchema,
|
|
6305
|
-
approvedDomains:
|
|
6306
|
-
directoryRoles:
|
|
6307
|
-
group:
|
|
6308
|
-
roles:
|
|
6567
|
+
approvedDomains: z16.array(z16.string().trim().min(1)).default([]),
|
|
6568
|
+
directoryRoles: z16.array(z16.strictObject({
|
|
6569
|
+
group: z16.string().trim().toLowerCase().min(3),
|
|
6570
|
+
roles: z16.array(RoleSlugSchema).min(1)
|
|
6309
6571
|
})).default([])
|
|
6310
6572
|
})
|
|
6311
6573
|
}).superRefine((input, context) => {
|
|
@@ -6426,7 +6688,7 @@ async function provisionWorkProject(args) {
|
|
|
6426
6688
|
import { randomBytes as randomBytes8 } from "node:crypto";
|
|
6427
6689
|
import { appGuestCsp, buildAppGuestDocument } from "@catamorphic/app";
|
|
6428
6690
|
import { micromark } from "micromark";
|
|
6429
|
-
import { z as
|
|
6691
|
+
import { z as z18 } from "zod";
|
|
6430
6692
|
|
|
6431
6693
|
// src/shares/shares-service.ts
|
|
6432
6694
|
import { randomBytes as randomBytes7 } from "node:crypto";
|
|
@@ -6435,18 +6697,18 @@ import {
|
|
|
6435
6697
|
identityMayUseEnvironment,
|
|
6436
6698
|
normalizeDocumentPath
|
|
6437
6699
|
} from "@catamorphic/core";
|
|
6438
|
-
import { sql as
|
|
6439
|
-
import { z as
|
|
6440
|
-
var CreateShareSchema =
|
|
6441
|
-
kind:
|
|
6442
|
-
target:
|
|
6443
|
-
environment:
|
|
6444
|
-
title:
|
|
6445
|
-
audience:
|
|
6446
|
-
emails:
|
|
6447
|
-
domains:
|
|
6700
|
+
import { sql as sql6 } from "kysely";
|
|
6701
|
+
import { z as z17 } from "zod";
|
|
6702
|
+
var CreateShareSchema = z17.strictObject({
|
|
6703
|
+
kind: z17.enum(["document", "folder", "app"]),
|
|
6704
|
+
target: z17.string().trim().min(1).max(512),
|
|
6705
|
+
environment: z17.string().trim().min(1).optional(),
|
|
6706
|
+
title: z17.string().trim().min(1).max(200).optional(),
|
|
6707
|
+
audience: z17.strictObject({
|
|
6708
|
+
emails: z17.array(z17.email().toLowerCase()).max(200).default([]),
|
|
6709
|
+
domains: z17.array(z17.string().trim().toLowerCase().regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/)).max(50).default([])
|
|
6448
6710
|
}).refine((audience) => audience.emails.length + audience.domains.length > 0, "Name at least one email or domain"),
|
|
6449
|
-
expiresAt:
|
|
6711
|
+
expiresAt: z17.iso.datetime().optional()
|
|
6450
6712
|
});
|
|
6451
6713
|
|
|
6452
6714
|
class ShareAccessError extends Error {
|
|
@@ -6501,7 +6763,7 @@ class WorkSharesService {
|
|
|
6501
6763
|
if (!hasProjectPermission3(args.identity, args.projectId, "publications:write")) {
|
|
6502
6764
|
throw new ShareAccessError("Revoking shares needs publications:write");
|
|
6503
6765
|
}
|
|
6504
|
-
const row = await this.deps.db.updateTable("work_shares").set({ revoked_at:
|
|
6766
|
+
const row = await this.deps.db.updateTable("work_shares").set({ revoked_at: sql6`now()` }).where("id", "=", args.shareId).where("project_id", "=", args.projectId).where("revoked_at", "is", null).returning("id").executeTakeFirst();
|
|
6505
6767
|
return Boolean(row);
|
|
6506
6768
|
}
|
|
6507
6769
|
async isGuest(userId) {
|
|
@@ -6514,7 +6776,7 @@ class WorkSharesService {
|
|
|
6514
6776
|
async open(args) {
|
|
6515
6777
|
const row = await this.deps.db.selectFrom("work_shares").innerJoin("projects", "projects.id", "work_shares.project_id").selectAll("work_shares").where("work_shares.id", "=", args.shareId).where("projects.tenant_id", "=", this.deps.tenantId).where("work_shares.revoked_at", "is", null).where(({ or, eb }) => or([
|
|
6516
6778
|
eb("work_shares.expires_at", "is", null),
|
|
6517
|
-
eb("work_shares.expires_at", ">",
|
|
6779
|
+
eb("work_shares.expires_at", ">", sql6`now()`)
|
|
6518
6780
|
])).executeTakeFirst();
|
|
6519
6781
|
if (!row)
|
|
6520
6782
|
return null;
|
|
@@ -6624,10 +6886,10 @@ class WorkSharesService {
|
|
|
6624
6886
|
}
|
|
6625
6887
|
|
|
6626
6888
|
// src/shares/share-routes.ts
|
|
6627
|
-
var CallSchema =
|
|
6628
|
-
workflowName:
|
|
6629
|
-
mode:
|
|
6630
|
-
input:
|
|
6889
|
+
var CallSchema = z18.strictObject({
|
|
6890
|
+
workflowName: z18.string().min(1).max(200),
|
|
6891
|
+
mode: z18.enum(["invoke", "start"]),
|
|
6892
|
+
input: z18.json()
|
|
6631
6893
|
});
|
|
6632
6894
|
function registerShareRoutes(app, options) {
|
|
6633
6895
|
const { core, shares } = options;
|
|
@@ -6874,7 +7136,7 @@ function registerShareRoutes(app, options) {
|
|
|
6874
7136
|
const context = await appContext(request, reply);
|
|
6875
7137
|
if (!context)
|
|
6876
7138
|
return reply;
|
|
6877
|
-
const data =
|
|
7139
|
+
const data = z18.record(z18.string(), z18.string()).safeParse(request.body?.data);
|
|
6878
7140
|
if (!data.success)
|
|
6879
7141
|
return reply.status(400).send();
|
|
6880
7142
|
await core.appStorage.put(context.identity, context.share.projectId, context.share.target, data.data).catch(() => {
|
|
@@ -6992,7 +7254,7 @@ function escapeHtml3(value) {
|
|
|
6992
7254
|
}
|
|
6993
7255
|
|
|
6994
7256
|
// src/shares/share-tools.ts
|
|
6995
|
-
import { z as
|
|
7257
|
+
import { z as z19 } from "zod";
|
|
6996
7258
|
function shareTools(shares, args) {
|
|
6997
7259
|
const { identity, projectId } = args;
|
|
6998
7260
|
return [
|
|
@@ -7000,7 +7262,7 @@ function shareTools(shares, args) {
|
|
|
7000
7262
|
definition: {
|
|
7001
7263
|
name: "share_create",
|
|
7002
7264
|
description: "Share a document, a folder, or a published app with people outside the company. They sign in with their own account at the returned url and see only this. App shares name the Environment the app's workflows run in.",
|
|
7003
|
-
inputSchema:
|
|
7265
|
+
inputSchema: z19.toJSONSchema(CreateShareSchema, { io: "input" })
|
|
7004
7266
|
},
|
|
7005
7267
|
call: async (input) => shares.create({
|
|
7006
7268
|
identity,
|
|
@@ -7041,23 +7303,23 @@ function shareTools(shares, args) {
|
|
|
7041
7303
|
|
|
7042
7304
|
// src/workers/codex-sign-ins.ts
|
|
7043
7305
|
import { spawn } from "node:child_process";
|
|
7044
|
-
import { randomUUID as
|
|
7306
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
7045
7307
|
import fs11 from "node:fs";
|
|
7046
7308
|
import path8 from "node:path";
|
|
7047
|
-
import { z as
|
|
7048
|
-
var CodexSignInStartedSchema =
|
|
7049
|
-
attempt:
|
|
7050
|
-
verificationUrl:
|
|
7051
|
-
userCode:
|
|
7052
|
-
expiresAt:
|
|
7309
|
+
import { z as z20 } from "zod";
|
|
7310
|
+
var CodexSignInStartedSchema = z20.strictObject({
|
|
7311
|
+
attempt: z20.string().uuid(),
|
|
7312
|
+
verificationUrl: z20.string().url(),
|
|
7313
|
+
userCode: z20.string().min(1).max(32),
|
|
7314
|
+
expiresAt: z20.string().datetime()
|
|
7053
7315
|
});
|
|
7054
|
-
var CodexSignInStatusSchema =
|
|
7055
|
-
state:
|
|
7056
|
-
message:
|
|
7316
|
+
var CodexSignInStatusSchema = z20.strictObject({
|
|
7317
|
+
state: z20.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
|
|
7318
|
+
message: z20.string().max(400).optional()
|
|
7057
7319
|
});
|
|
7058
|
-
var CodexSignedOutSchema =
|
|
7059
|
-
var CodexSignInRefusedSchema =
|
|
7060
|
-
refused:
|
|
7320
|
+
var CodexSignedOutSchema = z20.strictObject({ signedOut: z20.boolean() });
|
|
7321
|
+
var CodexSignInRefusedSchema = z20.strictObject({
|
|
7322
|
+
refused: z20.string().min(1).max(400)
|
|
7061
7323
|
});
|
|
7062
7324
|
var CODE_TIMEOUT_MS = 30000;
|
|
7063
7325
|
var DEFAULT_CODE_MINUTES = 15;
|
|
@@ -7156,7 +7418,7 @@ class CodexSignIns {
|
|
|
7156
7418
|
},
|
|
7157
7419
|
stdio: ["ignore", "pipe", "pipe"]
|
|
7158
7420
|
});
|
|
7159
|
-
const id =
|
|
7421
|
+
const id = randomUUID5();
|
|
7160
7422
|
let output = "";
|
|
7161
7423
|
return new Promise((resolve, reject) => {
|
|
7162
7424
|
let settled = false;
|
|
@@ -7283,7 +7545,7 @@ class CodexSignIns {
|
|
|
7283
7545
|
function installTarget(args) {
|
|
7284
7546
|
if (!args.workerImage)
|
|
7285
7547
|
return {
|
|
7286
|
-
unavailable: "This server does not know which worker image machines should run. Set WORK_WORKER_IMAGE to
|
|
7548
|
+
unavailable: "This server does not know which worker image machines should run. Set WORK_WORKER_IMAGE to your deployment's pinned worker image (see @catamorphic/work-server deployment guidance)."
|
|
7287
7549
|
};
|
|
7288
7550
|
if (isLoopback2(args.publicBase))
|
|
7289
7551
|
return {
|
|
@@ -7325,7 +7587,7 @@ usage() {
|
|
|
7325
7587
|
Usage: install.sh --code <code> [--image <image>] [--data-dir <dir>] [--name <name>] [--sandbox <backend>]
|
|
7326
7588
|
|
|
7327
7589
|
--code <code> the one-time enrollment code from the Work server (required)
|
|
7328
|
-
--image <image> the worker image (default:
|
|
7590
|
+
--image <image> the worker image (default: the deployment's configured worker image)
|
|
7329
7591
|
--data-dir <dir> where the worker keeps its credential, sandboxes and
|
|
7330
7592
|
members' sign-ins (default: ${DEFAULT_WORKER_DATA_DIR}): a new
|
|
7331
7593
|
directory, or one under /var/lib, /srv, /opt, /data or
|
|
@@ -7594,7 +7856,7 @@ function isLoopback2(base) {
|
|
|
7594
7856
|
}
|
|
7595
7857
|
|
|
7596
7858
|
// src/workers/machine-rules.ts
|
|
7597
|
-
import { createHash as
|
|
7859
|
+
import { createHash as createHash8, randomUUID as randomUUID6 } from "node:crypto";
|
|
7598
7860
|
import {
|
|
7599
7861
|
PLACEMENT_WAIT_FRESH_SECONDS,
|
|
7600
7862
|
releaseReplicaClaim,
|
|
@@ -7606,35 +7868,35 @@ import {
|
|
|
7606
7868
|
} from "@catamorphic/hetzner";
|
|
7607
7869
|
import { getTracer as getTracer2, withSpan as withSpan2 } from "@catamorphic/otel";
|
|
7608
7870
|
import { environmentSatisfies as environmentSatisfies2, poolMatches as poolMatches2 } from "@catamorphic/sandbox";
|
|
7609
|
-
import { sql as
|
|
7610
|
-
import { z as
|
|
7871
|
+
import { sql as sql7 } from "kysely";
|
|
7872
|
+
import { z as z21 } from "zod";
|
|
7611
7873
|
var tracer2 = getTracer2("@catamorphic/work-server");
|
|
7612
7874
|
var DEFAULT_RETAIN_DAYS = 7;
|
|
7613
7875
|
var DEFAULT_IDLE_MINUTES = 10;
|
|
7614
7876
|
var DEFAULT_ENROLL_MINUTES = 15;
|
|
7615
7877
|
var DAY_MS = 24 * 60 * 60000;
|
|
7616
|
-
var DemandSchema =
|
|
7617
|
-
max:
|
|
7618
|
-
min:
|
|
7619
|
-
idleMinutes:
|
|
7620
|
-
enrollMinutes:
|
|
7878
|
+
var DemandSchema = z21.strictObject({
|
|
7879
|
+
max: z21.number().int().positive().max(100),
|
|
7880
|
+
min: z21.number().int().min(0).max(100).default(0),
|
|
7881
|
+
idleMinutes: z21.number().int().min(1).max(24 * 60).default(DEFAULT_IDLE_MINUTES),
|
|
7882
|
+
enrollMinutes: z21.number().int().positive().max(24 * 60).default(DEFAULT_ENROLL_MINUTES)
|
|
7621
7883
|
}).refine((demand) => demand.min <= demand.max, {
|
|
7622
7884
|
message: "min may not be more than max",
|
|
7623
7885
|
path: ["min"]
|
|
7624
7886
|
});
|
|
7625
|
-
var RuleMachinesSchema =
|
|
7626
|
-
|
|
7627
|
-
|
|
7628
|
-
|
|
7887
|
+
var RuleMachinesSchema = z21.union([
|
|
7888
|
+
z21.literal("each-member"),
|
|
7889
|
+
z21.strictObject({ shared: z21.number().int().positive().max(100) }),
|
|
7890
|
+
z21.strictObject({ demand: DemandSchema })
|
|
7629
7891
|
]);
|
|
7630
|
-
var MachineRuleSchema =
|
|
7631
|
-
group:
|
|
7632
|
-
projects:
|
|
7892
|
+
var MachineRuleSchema = z21.strictObject({
|
|
7893
|
+
group: z21.email().toLowerCase().optional(),
|
|
7894
|
+
projects: z21.array(z21.uuid()).min(1).max(100).optional(),
|
|
7633
7895
|
machines: RuleMachinesSchema,
|
|
7634
|
-
class:
|
|
7896
|
+
class: z21.string().min(1).max(64),
|
|
7635
7897
|
labels: NodeLabelsSchema.default({}),
|
|
7636
|
-
trusted:
|
|
7637
|
-
retainDays:
|
|
7898
|
+
trusted: z21.boolean().default(false),
|
|
7899
|
+
retainDays: z21.number().int().min(0).max(365).optional()
|
|
7638
7900
|
}).superRefine((rule, context) => {
|
|
7639
7901
|
const demand = demandOf(rule) !== undefined;
|
|
7640
7902
|
if (rule.group === undefined === (rule.projects === undefined))
|
|
@@ -7669,25 +7931,25 @@ class MachineProvisioningRefusedError extends Error {
|
|
|
7669
7931
|
this.name = "MachineProvisioningRefusedError";
|
|
7670
7932
|
}
|
|
7671
7933
|
}
|
|
7672
|
-
var DemandWaitPool =
|
|
7673
|
-
var DemandWaitRequirements =
|
|
7674
|
-
resources:
|
|
7675
|
-
cpuMillis:
|
|
7676
|
-
memoryMb:
|
|
7677
|
-
storageMb:
|
|
7678
|
-
gpu:
|
|
7934
|
+
var DemandWaitPool = z21.record(z21.string(), z21.string());
|
|
7935
|
+
var DemandWaitRequirements = z21.object({
|
|
7936
|
+
resources: z21.object({
|
|
7937
|
+
cpuMillis: z21.number().optional(),
|
|
7938
|
+
memoryMb: z21.number().optional(),
|
|
7939
|
+
storageMb: z21.number().optional(),
|
|
7940
|
+
gpu: z21.boolean().optional()
|
|
7679
7941
|
}).default({}),
|
|
7680
|
-
capabilities:
|
|
7681
|
-
trust:
|
|
7682
|
-
isolation:
|
|
7683
|
-
topology:
|
|
7942
|
+
capabilities: z21.array(z21.string()).default([]),
|
|
7943
|
+
trust: z21.enum(["local", "managed"]).optional(),
|
|
7944
|
+
isolation: z21.enum(["none", "process", "sandbox"]).optional(),
|
|
7945
|
+
topology: z21.enum(["controller", "contained", "native", "external"]).optional()
|
|
7684
7946
|
});
|
|
7685
7947
|
var HETZNER_REF = "hcloud:";
|
|
7686
7948
|
|
|
7687
7949
|
class MachineReconciler {
|
|
7688
7950
|
deps;
|
|
7689
7951
|
running;
|
|
7690
|
-
holder =
|
|
7952
|
+
holder = randomUUID6();
|
|
7691
7953
|
constructor(deps) {
|
|
7692
7954
|
this.deps = deps;
|
|
7693
7955
|
}
|
|
@@ -7713,7 +7975,7 @@ class MachineReconciler {
|
|
|
7713
7975
|
definition: JSON.stringify(rule)
|
|
7714
7976
|
}).onConflict((oc) => oc.columns(["tenant_id", "name"]).doUpdateSet({
|
|
7715
7977
|
definition: JSON.stringify(rule),
|
|
7716
|
-
updated_at:
|
|
7978
|
+
updated_at: sql7`now()`
|
|
7717
7979
|
})).execute();
|
|
7718
7980
|
return rule;
|
|
7719
7981
|
}
|
|
@@ -7871,7 +8133,7 @@ class MachineReconciler {
|
|
|
7871
8133
|
await this.deps.db.updateTable("work_machine_rules").set(failures.length > 0 ? {
|
|
7872
8134
|
last_failure: failures.map((failure) => failure.name === rule ? failure.error : `${failure.name}: ${failure.error}`).join(`
|
|
7873
8135
|
`).slice(0, 4000),
|
|
7874
|
-
last_failure_at:
|
|
8136
|
+
last_failure_at: sql7`now()`
|
|
7875
8137
|
} : { last_failure: null, last_failure_at: null }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", rule).execute();
|
|
7876
8138
|
}
|
|
7877
8139
|
}
|
|
@@ -8172,7 +8434,7 @@ class MachineReconciler {
|
|
|
8172
8434
|
async provision(args) {
|
|
8173
8435
|
const { machine, code } = args;
|
|
8174
8436
|
const machineClass = this.classOf(machine.class);
|
|
8175
|
-
const idempotencyKey =
|
|
8437
|
+
const idempotencyKey = createHash8("sha256").update(code).digest("hex");
|
|
8176
8438
|
const cloudInit = "target" in this.deps.install ? workerCloudInit({
|
|
8177
8439
|
script: workerInstallScript(this.deps.install.target),
|
|
8178
8440
|
code,
|
|
@@ -8252,7 +8514,7 @@ class MachineReconciler {
|
|
|
8252
8514
|
return (demand?.enrollMinutes ?? DEFAULT_ENROLL_MINUTES) * 60000;
|
|
8253
8515
|
}
|
|
8254
8516
|
async runsPlainProcesses(machineClass) {
|
|
8255
|
-
const row = await this.deps.db.selectFrom("work_workers").innerJoin("worker_nodes", "worker_nodes.id", "work_workers.node_id").select("work_workers.name").where("work_workers.tenant_id", "=", this.deps.tenantId).where(
|
|
8517
|
+
const row = await this.deps.db.selectFrom("work_workers").innerJoin("worker_nodes", "worker_nodes.id", "work_workers.node_id").select("work_workers.name").where("work_workers.tenant_id", "=", this.deps.tenantId).where(sql7`work_workers.labels ->> 'class' = ${machineClass}`).where(sql7`worker_nodes.descriptor ->> 'isolation' = 'process'`).executeTakeFirst();
|
|
8256
8518
|
return Boolean(row);
|
|
8257
8519
|
}
|
|
8258
8520
|
classOf(name) {
|
|
@@ -8396,13 +8658,13 @@ class MachineReconciler {
|
|
|
8396
8658
|
"placement_waits.requirements",
|
|
8397
8659
|
"work_accounts.directory_groups",
|
|
8398
8660
|
"work_accounts.disabled_at"
|
|
8399
|
-
]).where("placement_waits.tenant_id", "=", this.deps.tenantId).where("placement_waits.last_tried_at", ">", waitFresh()).where((
|
|
8661
|
+
]).where("placement_waits.tenant_id", "=", this.deps.tenantId).where("placement_waits.last_tried_at", ">", waitFresh()).where(queuedPlacementWait(this.deps.db)).orderBy("placement_waits.waiting_since").execute(),
|
|
8400
8662
|
this.deps.workers.machines(),
|
|
8401
8663
|
this.deps.workers.machineLoad(),
|
|
8402
8664
|
this.deps.db.selectFrom("work_workers").innerJoin("work_machine_rules", (join) => join.onRef("work_machine_rules.tenant_id", "=", "work_workers.tenant_id").onRef("work_machine_rules.name", "=", "work_workers.machine_rule")).select([
|
|
8403
8665
|
"work_workers.machine_rule",
|
|
8404
8666
|
"work_workers.name",
|
|
8405
|
-
|
|
8667
|
+
sql7`(extract(epoch from (now() - work_workers.enrolled_at)) * 1000)::float8`.as("enrolled_for_ms")
|
|
8406
8668
|
]).where("work_workers.tenant_id", "=", this.deps.tenantId).where("work_workers.pool", "=", false).where("work_workers.last_seen_at", "is", null).whereRef("work_workers.enrolled_at", ">", "work_machine_rules.updated_at").orderBy("work_workers.enrolled_at").execute()
|
|
8407
8669
|
]);
|
|
8408
8670
|
const waits = [];
|
|
@@ -8441,16 +8703,16 @@ class MachineReconciler {
|
|
|
8441
8703
|
demandSeen;
|
|
8442
8704
|
async demandSignature() {
|
|
8443
8705
|
const row = await this.deps.db.selectNoFrom((eb) => [
|
|
8444
|
-
eb.exists(eb.selectFrom("work_machine_rules").select("name").where("tenant_id", "=", this.deps.tenantId).where(
|
|
8445
|
-
eb.selectFrom("placement_waits").select(
|
|
8446
|
-
eb.selectFrom("execution_allocations").select(
|
|
8706
|
+
eb.exists(eb.selectFrom("work_machine_rules").select("name").where("tenant_id", "=", this.deps.tenantId).where(sql7`definition -> 'machines' ? 'demand'`)).as("demand"),
|
|
8707
|
+
eb.selectFrom("placement_waits").select(sql7`count(*)::text || '/' || coalesce(max(waiting_since)::text, '')`.as("waits")).where("tenant_id", "=", this.deps.tenantId).where("last_tried_at", ">", waitFresh()).where(queuedPlacementWait(this.deps.db)).as("waits"),
|
|
8708
|
+
eb.selectFrom("execution_allocations").select(sql7`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as("work")).where("worker_node_id", "in", eb.selectFrom("work_workers").select("node_id").where("tenant_id", "=", this.deps.tenantId).where("machine_rule", "is not", null).where("revoked_at", "is", null)).as("work")
|
|
8447
8709
|
]).executeTakeFirst();
|
|
8448
8710
|
if (!row?.demand)
|
|
8449
8711
|
return;
|
|
8450
8712
|
return `${row.waits ?? ""}|${row.work ?? ""}`;
|
|
8451
8713
|
}
|
|
8452
8714
|
async members(group) {
|
|
8453
|
-
const rows = await this.deps.db.selectFrom("work_accounts").select("user_id").where("disabled_at", "is", null).where(
|
|
8715
|
+
const rows = await this.deps.db.selectFrom("work_accounts").select("user_id").where("disabled_at", "is", null).where(sql7`directory_groups @> ${JSON.stringify([group])}::jsonb`).orderBy("user_id").execute();
|
|
8454
8716
|
const members = [];
|
|
8455
8717
|
for (const row of rows) {
|
|
8456
8718
|
const email = await this.deps.emailOf(row.user_id);
|
|
@@ -8501,7 +8763,7 @@ function demandWaitMatches(rule, wait) {
|
|
|
8501
8763
|
return wait.owner !== null && rule.group !== undefined && wait.groups.includes(rule.group);
|
|
8502
8764
|
}
|
|
8503
8765
|
function waitFresh() {
|
|
8504
|
-
return
|
|
8766
|
+
return sql7`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
|
|
8505
8767
|
}
|
|
8506
8768
|
function servesSeveral(rule) {
|
|
8507
8769
|
return rule.group !== undefined || (rule.projects?.length ?? 0) > 1;
|
|
@@ -8636,7 +8898,7 @@ function demandMachines(args) {
|
|
|
8636
8898
|
return machines;
|
|
8637
8899
|
}
|
|
8638
8900
|
function digest(value, length) {
|
|
8639
|
-
return
|
|
8901
|
+
return createHash8("sha256").update(value).digest("hex").slice(0, length);
|
|
8640
8902
|
}
|
|
8641
8903
|
function message(error) {
|
|
8642
8904
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -8644,10 +8906,16 @@ function message(error) {
|
|
|
8644
8906
|
function canonical(value) {
|
|
8645
8907
|
return JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).sort(([left], [right]) => left.localeCompare(right))) : entry);
|
|
8646
8908
|
}
|
|
8909
|
+
function queuedPlacementWait(db) {
|
|
8910
|
+
const turns = db.selectFrom("agent_turns").select("id").where("session_id", "=", sql7`placement_waits.root_workload_id`).where("status", "=", "queued");
|
|
8911
|
+
const jobs = db.selectFrom("workflow_runs as root").innerJoin("workflow_runs as run", "run.allocation_id", "root.allocation_id").innerJoin("execution_jobs as job", "job.workflow_run_id", "run.id").select("job.id").where("root.id", "=", sql7`placement_waits.root_workload_id`).where("root.status", "in", ["pending", "running", "waiting"]).where("run.status", "in", ["pending", "running", "waiting"]).where("job.status", "=", "pending").where("job.kind", "!=", "durable_pause_timeout").where("job.available_at", "<=", sql7`now()`);
|
|
8912
|
+
return sql7`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
|
|
8913
|
+
(placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})))`;
|
|
8914
|
+
}
|
|
8647
8915
|
|
|
8648
8916
|
// src/workers/member-machine-routes.ts
|
|
8649
8917
|
import { ExecutorNotConnectedError } from "@catamorphic/core";
|
|
8650
|
-
import { z as
|
|
8918
|
+
import { z as z23 } from "zod";
|
|
8651
8919
|
|
|
8652
8920
|
// src/workers/member-machines.ts
|
|
8653
8921
|
import {
|
|
@@ -8656,7 +8924,7 @@ import {
|
|
|
8656
8924
|
parseSignInCapability,
|
|
8657
8925
|
signInCapability as signInCapability2
|
|
8658
8926
|
} from "@catamorphic/sandbox";
|
|
8659
|
-
import { z as
|
|
8927
|
+
import { z as z22 } from "zod";
|
|
8660
8928
|
class NotYourMachineError extends Error {
|
|
8661
8929
|
constructor() {
|
|
8662
8930
|
super("This is not a machine of your own, so your Codex sign-in cannot go on it");
|
|
@@ -8681,7 +8949,7 @@ class MemberMachines {
|
|
|
8681
8949
|
}));
|
|
8682
8950
|
}
|
|
8683
8951
|
async begin(args) {
|
|
8684
|
-
const answer =
|
|
8952
|
+
const answer = z22.union([CodexSignInStartedSchema, CodexSignInRefusedSchema]).parse(await this.send(args, {
|
|
8685
8953
|
action: "begin",
|
|
8686
8954
|
member: args.identity.externalUserId
|
|
8687
8955
|
}));
|
|
@@ -8753,8 +9021,8 @@ class MemberMachines {
|
|
|
8753
9021
|
|
|
8754
9022
|
// src/workers/member-machine-routes.ts
|
|
8755
9023
|
function registerMemberMachineRoutes(app, options) {
|
|
8756
|
-
const machineParams =
|
|
8757
|
-
const attemptParams = machineParams.extend({ attempt:
|
|
9024
|
+
const machineParams = z23.object({ id: z23.string().min(1).max(200) });
|
|
9025
|
+
const attemptParams = machineParams.extend({ attempt: z23.string().uuid() });
|
|
8758
9026
|
const member = async (request, reply) => {
|
|
8759
9027
|
const identity = await options.caller(request);
|
|
8760
9028
|
if (!identity) {
|
|
@@ -8869,7 +9137,7 @@ import {
|
|
|
8869
9137
|
RemoteReceiptRefusedError
|
|
8870
9138
|
} from "@catamorphic/core";
|
|
8871
9139
|
import { ExecutorPublicKeySchema as ExecutorPublicKeySchema2 } from "@catamorphic/sandbox";
|
|
8872
|
-
import { z as
|
|
9140
|
+
import { z as z24 } from "zod";
|
|
8873
9141
|
|
|
8874
9142
|
// src/workers/worker-protocol.ts
|
|
8875
9143
|
var WORKER_PROTOCOL_HEADER = "work-protocol";
|
|
@@ -8895,16 +9163,16 @@ function upgradeMessage(input) {
|
|
|
8895
9163
|
}
|
|
8896
9164
|
|
|
8897
9165
|
// src/workers/worker-routes.ts
|
|
8898
|
-
var Session =
|
|
9166
|
+
var Session = z24.strictObject({ session: z24.string().uuid() });
|
|
8899
9167
|
var Poll = Session.extend({
|
|
8900
|
-
pollId:
|
|
8901
|
-
max:
|
|
9168
|
+
pollId: z24.string().uuid(),
|
|
9169
|
+
max: z24.number().int().min(1).max(64).default(1)
|
|
8902
9170
|
});
|
|
8903
|
-
var Completion =
|
|
8904
|
-
session:
|
|
8905
|
-
jobId:
|
|
8906
|
-
response:
|
|
8907
|
-
error:
|
|
9171
|
+
var Completion = z24.strictObject({
|
|
9172
|
+
session: z24.string().uuid(),
|
|
9173
|
+
jobId: z24.string().uuid(),
|
|
9174
|
+
response: z24.unknown().optional(),
|
|
9175
|
+
error: z24.string().max(1e4).optional()
|
|
8908
9176
|
});
|
|
8909
9177
|
function registerWorkerRoutes(app, registry) {
|
|
8910
9178
|
const authenticated = async (request, reply) => {
|
|
@@ -8921,8 +9189,8 @@ function registerWorkerRoutes(app, registry) {
|
|
|
8921
9189
|
app.post("/api/workers/enroll", async (request, reply) => {
|
|
8922
9190
|
if (await refusedProtocol(request, reply))
|
|
8923
9191
|
return reply;
|
|
8924
|
-
const body =
|
|
8925
|
-
code:
|
|
9192
|
+
const body = z24.strictObject({
|
|
9193
|
+
code: z24.string().min(10),
|
|
8926
9194
|
publicKey: ExecutorPublicKeySchema2
|
|
8927
9195
|
}).safeParse(request.body);
|
|
8928
9196
|
if (!body.success) {
|
|
@@ -8969,9 +9237,9 @@ function registerWorkerRoutes(app, registry) {
|
|
|
8969
9237
|
const worker = await authenticated(request, reply);
|
|
8970
9238
|
if (!worker)
|
|
8971
9239
|
return reply;
|
|
8972
|
-
const body =
|
|
9240
|
+
const body = z24.strictObject({
|
|
8973
9241
|
publicKey: ExecutorPublicKeySchema2,
|
|
8974
|
-
rotation:
|
|
9242
|
+
rotation: z24.string().regex(REMOTE_EPOCH_PATTERN2, "Use a UUIDv7 rotation id")
|
|
8975
9243
|
}).safeParse(request.body);
|
|
8976
9244
|
if (!body.success)
|
|
8977
9245
|
return reply.status(400).send({ error: "Provide the new public key and a rotation id" });
|
|
@@ -9131,7 +9399,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9131
9399
|
}
|
|
9132
9400
|
const disposable = Boolean(config.databaseUrl);
|
|
9133
9401
|
const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path9.join(data, "host-id"));
|
|
9134
|
-
const nodeId = disposable ? `node.${
|
|
9402
|
+
const nodeId = disposable ? `node.${randomUUID7()}` : `node.${createHash9("sha256").update(hostId).digest("hex").slice(0, 24)}`;
|
|
9135
9403
|
const authSecret = loadWorkAuthSecret({
|
|
9136
9404
|
dataDir: data,
|
|
9137
9405
|
...config.secret ? { configuredSecret: config.secret } : {}
|
|
@@ -9151,12 +9419,12 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9151
9419
|
const pglite = new PGlite2(path9.join(data, "db"), {
|
|
9152
9420
|
extensions: { pgcrypto }
|
|
9153
9421
|
});
|
|
9154
|
-
ownDb = withStorableParameters(new
|
|
9422
|
+
ownDb = withStorableParameters(new Kysely2({
|
|
9155
9423
|
dialect: new PGliteDialect2({ pglite }),
|
|
9156
9424
|
plugins: [new WithSchemaPlugin(DEFAULT_SCHEMA)]
|
|
9157
9425
|
}));
|
|
9158
9426
|
disposers.push(() => ownDb.destroy());
|
|
9159
|
-
await
|
|
9427
|
+
await sql8.raw(`SET search_path TO "${DEFAULT_SCHEMA}", public`).execute(ownDb);
|
|
9160
9428
|
databaseConfig = { db: ownDb };
|
|
9161
9429
|
}
|
|
9162
9430
|
const agentsHere = config.execution.workloads.includes("agent") && !config.execution.trustControlPlaneAgents;
|
|
@@ -9192,7 +9460,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9192
9460
|
const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path9.join(data, "credentials"), vaultKeys);
|
|
9193
9461
|
if (objectStore) {
|
|
9194
9462
|
const key = "work/deployment-fingerprint";
|
|
9195
|
-
const fingerprint =
|
|
9463
|
+
const fingerprint = createHash9("sha256").update(publicBase).update("\x00").update(authSecret).update("\x00").update(JSON.stringify({
|
|
9196
9464
|
local: workAuthConfig.local,
|
|
9197
9465
|
providers: workAuthConfig.providers,
|
|
9198
9466
|
sessions: workAuthConfig.sessions,
|
|
@@ -9205,7 +9473,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9205
9473
|
}
|
|
9206
9474
|
});
|
|
9207
9475
|
const keysRecord = "work/vault-key-ids";
|
|
9208
|
-
const known = await objectStore.get(keysRecord).then((record) => record ?
|
|
9476
|
+
const known = await objectStore.get(keysRecord).then((record) => record ? z25.array(z25.string()).parse(JSON.parse(Buffer.from(record.data).toString())) : []);
|
|
9209
9477
|
const ids = credentialVault.keyIds;
|
|
9210
9478
|
if (known.length > 0 && !ids.some((id) => known.includes(id))) {
|
|
9211
9479
|
throw new Error("WORK_VAULT_KEY and WORK_VAULT_PREVIOUS_KEYS share no key with this Postgres deployment");
|
|
@@ -9269,6 +9537,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9269
9537
|
disposers.push(() => Promise.all(gatewayConnectionProviders.map((provider) => provider.close?.())));
|
|
9270
9538
|
const catamorphic = createCatamorphic({
|
|
9271
9539
|
hostId,
|
|
9540
|
+
...hooks.capabilityProviders ? { capabilityProviders: hooks.capabilityProviders } : {},
|
|
9272
9541
|
agentCapabilities: workAgentCapabilities({
|
|
9273
9542
|
core: () => catamorphic.core,
|
|
9274
9543
|
auth: () => workAuth,
|
|
@@ -9889,7 +10158,7 @@ function loadOrCreateHostId(file) {
|
|
|
9889
10158
|
if (existing)
|
|
9890
10159
|
return existing;
|
|
9891
10160
|
} catch {}
|
|
9892
|
-
const hostId = `server:${
|
|
10161
|
+
const hostId = `server:${randomUUID7()}`;
|
|
9893
10162
|
fs12.writeFileSync(file, `${hostId}
|
|
9894
10163
|
`, { mode: 384 });
|
|
9895
10164
|
return hostId;
|
|
@@ -9928,14 +10197,14 @@ import {
|
|
|
9928
10197
|
// src/workers/worker-identity.ts
|
|
9929
10198
|
import fs13 from "node:fs";
|
|
9930
10199
|
import path10 from "node:path";
|
|
9931
|
-
import { z as
|
|
10200
|
+
import { z as z26 } from "zod";
|
|
9932
10201
|
var CREDENTIAL_FILE = "worker-credential";
|
|
9933
10202
|
var KEY_FILE = "worker-key";
|
|
9934
10203
|
var PREVIOUS_FILE = "worker-identity.previous";
|
|
9935
10204
|
var NEXT_FILE = "worker-identity.next";
|
|
9936
|
-
var PairSchema =
|
|
9937
|
-
credential:
|
|
9938
|
-
privateKey:
|
|
10205
|
+
var PairSchema = z26.strictObject({
|
|
10206
|
+
credential: z26.string().min(1),
|
|
10207
|
+
privateKey: z26.string().min(1)
|
|
9939
10208
|
});
|
|
9940
10209
|
var NextIdentitySchema = PairSchema.extend({
|
|
9941
10210
|
previous: PairSchema.optional()
|
|
@@ -10541,6 +10810,7 @@ export {
|
|
|
10541
10810
|
WorkAuthConfigSchema,
|
|
10542
10811
|
WorkerUpgradeRequiredError,
|
|
10543
10812
|
createWorkServer,
|
|
10813
|
+
defineCapability,
|
|
10544
10814
|
defineGitConnectionProvider2 as defineGitConnectionProvider,
|
|
10545
10815
|
defineHttpApiConnectionProvider2 as defineHttpApiConnectionProvider,
|
|
10546
10816
|
defineModelConnectionProvider2 as defineModelConnectionProvider,
|
|
@@ -10558,5 +10828,5 @@ export {
|
|
|
10558
10828
|
workServerConfigFromEnv
|
|
10559
10829
|
};
|
|
10560
10830
|
|
|
10561
|
-
//# debugId=
|
|
10831
|
+
//# debugId=4358C2279529C80964756E2164756E21
|
|
10562
10832
|
//# sourceMappingURL=index.js.map
|