@catamorphic/work-server 0.1.0-alpha.31 → 0.1.0-alpha.33
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 +98 -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 +581 -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 +88 -40
- 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,17 @@ 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 response = await callBetterAuth(routed, request, {
|
|
2875
|
-
|
|
3035
|
+
const response = await callBetterAuth(routed, request, {
|
|
3036
|
+
pathname: "/api/auth/oauth2/token"
|
|
3037
|
+
});
|
|
3038
|
+
if (!response.ok || !gate)
|
|
2876
3039
|
return sendResponse(response, reply);
|
|
2877
3040
|
const body = await response.clone().json().catch(() => null);
|
|
2878
3041
|
if (typeof body !== "object" || body === null) {
|
|
@@ -2886,25 +3049,29 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2886
3049
|
if (!decision.allow)
|
|
2887
3050
|
return sendTokenError(reply, decision);
|
|
2888
3051
|
return sendResponse(response, reply);
|
|
2889
|
-
}
|
|
3052
|
+
};
|
|
3053
|
+
app.post("/api/auth/oauth2/token", token);
|
|
2890
3054
|
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-
|
|
3055
|
+
app.get("/.well-known/oauth-authorization-server/api/auth", (request, reply) => forward(request, reply));
|
|
3056
|
+
app.get("/.well-known/oauth-protected-resource", (request, reply) => forward(request, reply));
|
|
3057
|
+
app.get("/.well-known/oauth-protected-resource/api", (request, reply) => forward(request, reply));
|
|
2892
3058
|
app.get("/login", (request, reply) => {
|
|
2893
3059
|
const error = new URLSearchParams(request.url.split("?")[1] ?? "").get("error");
|
|
2894
3060
|
return sendAuthPage(reply, (nonce) => loginPage(methodsFor(request), continuationQuery(request), error === "account" || error === "limited" ? error : error ? "credentials" : undefined, nonce));
|
|
2895
3061
|
});
|
|
2896
3062
|
app.post("/login/local", async (request, reply) => {
|
|
2897
3063
|
const form = formBody(request.body);
|
|
3064
|
+
const query = continuationQuery(request);
|
|
2898
3065
|
const response = await callBetterAuth(routed, request, {
|
|
2899
3066
|
pathname: "/api/auth/sign-in/username",
|
|
2900
3067
|
body: JSON.stringify({
|
|
2901
3068
|
username: form.get("username") ?? "",
|
|
2902
|
-
password: form.get("password") ?? ""
|
|
3069
|
+
password: form.get("password") ?? "",
|
|
3070
|
+
...new URLSearchParams(query).has("sig") ? { oauth_query: query } : {}
|
|
2903
3071
|
}),
|
|
2904
3072
|
contentType: "application/json"
|
|
2905
3073
|
});
|
|
2906
3074
|
copyCookies(response, reply);
|
|
2907
|
-
const query = continuationQuery(request);
|
|
2908
3075
|
if (response.status === 429) {
|
|
2909
3076
|
return reply.redirect(`/login?${query}&error=limited`);
|
|
2910
3077
|
}
|
|
@@ -2915,19 +3082,23 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2915
3082
|
const next = shareNext(request);
|
|
2916
3083
|
if (response.ok && next)
|
|
2917
3084
|
return reply.redirect(next);
|
|
2918
|
-
|
|
3085
|
+
const redirect = response.ok ? await authorizationRedirect(response) : undefined;
|
|
3086
|
+
if (redirect)
|
|
3087
|
+
return reply.redirect(redirect);
|
|
3088
|
+
return response.ok ? reply.redirect(`/api/auth/oauth2/authorize?${query}`) : reply.redirect(`/login?${query}&error=1`);
|
|
2919
3089
|
});
|
|
2920
3090
|
app.post("/login/provider/:providerId", async (request, reply) => {
|
|
2921
3091
|
if (!methodsFor(request).providers.some((provider) => provider.id === request.params.providerId)) {
|
|
2922
3092
|
return reply.status(404).send("Provider not found");
|
|
2923
3093
|
}
|
|
2924
3094
|
const query = continuationQuery(request);
|
|
2925
|
-
const callbackURL = new URL(shareNext(request) ?? `/api/auth/
|
|
3095
|
+
const callbackURL = new URL(shareNext(request) ?? `/api/auth/oauth2/authorize?${query}`, options.baseURL).toString();
|
|
2926
3096
|
const response = await callBetterAuth(routed, request, {
|
|
2927
|
-
pathname: "/api/auth/sign-in/
|
|
3097
|
+
pathname: "/api/auth/sign-in/social",
|
|
2928
3098
|
body: JSON.stringify({
|
|
2929
|
-
|
|
2930
|
-
callbackURL
|
|
3099
|
+
provider: request.params.providerId,
|
|
3100
|
+
callbackURL,
|
|
3101
|
+
...!shareNext(request) && new URLSearchParams(query).has("sig") ? { oauth_query: query } : {}
|
|
2931
3102
|
}),
|
|
2932
3103
|
contentType: "application/json"
|
|
2933
3104
|
});
|
|
@@ -2935,22 +3106,35 @@ function registerWorkAuthRoutes(app, options) {
|
|
|
2935
3106
|
const result = await response.json().catch(() => ({}));
|
|
2936
3107
|
return response.ok && typeof result.url === "string" ? reply.redirect(result.url) : reply.redirect(`/login?${query}&error=${response.status === 429 ? "limited" : "1"}`);
|
|
2937
3108
|
});
|
|
2938
|
-
app.get("/oauth/consent", (request, reply) =>
|
|
3109
|
+
app.get("/oauth/consent", async (request, reply) => {
|
|
3110
|
+
const query = new URL(request.raw.url ?? "/", options.baseURL).search.slice(1);
|
|
3111
|
+
if (!await options.auth.verifyAuthorizationQuery({ query })) {
|
|
3112
|
+
return authorizationFailed(reply);
|
|
3113
|
+
}
|
|
3114
|
+
return sendAuthPage(reply, (nonce) => consentPage(query, nonce));
|
|
3115
|
+
});
|
|
2939
3116
|
app.post("/oauth/consent", async (request, reply) => {
|
|
2940
3117
|
const form = formBody(request.body);
|
|
2941
3118
|
const response = await callBetterAuth(routed, request, {
|
|
2942
3119
|
pathname: "/api/auth/oauth2/consent",
|
|
2943
3120
|
body: JSON.stringify({
|
|
2944
3121
|
accept: form.get("accept") === "true",
|
|
2945
|
-
|
|
3122
|
+
oauth_query: form.get("oauth_query") ?? ""
|
|
2946
3123
|
}),
|
|
2947
3124
|
contentType: "application/json"
|
|
2948
3125
|
});
|
|
2949
3126
|
copyCookies(response, reply);
|
|
2950
|
-
const
|
|
2951
|
-
return
|
|
3127
|
+
const redirect = response.ok ? await authorizationRedirect(response) : undefined;
|
|
3128
|
+
return redirect ? reply.redirect(redirect) : authorizationFailed(reply);
|
|
2952
3129
|
});
|
|
2953
3130
|
}
|
|
3131
|
+
async function authorizationRedirect(response) {
|
|
3132
|
+
const result = await response.json().catch(() => null);
|
|
3133
|
+
return typeof result === "object" && result !== null && "redirect" in result && result.redirect === true && "url" in result && typeof result.url === "string" ? result.url : undefined;
|
|
3134
|
+
}
|
|
3135
|
+
function authorizationFailed(reply) {
|
|
3136
|
+
return sendAuthPage(reply.status(400), (nonce) => messagePage("Authorization could not be completed", "Return to Work and try connecting again.", nonce));
|
|
3137
|
+
}
|
|
2954
3138
|
async function forwardToBetterAuth(options, request, reply, pathname) {
|
|
2955
3139
|
return sendResponse(await callBetterAuth(options, request, { pathname }), reply);
|
|
2956
3140
|
}
|
|
@@ -3075,10 +3259,10 @@ function loginPage(methods, continuation, failure, nonce) {
|
|
|
3075
3259
|
</section>${script}`
|
|
3076
3260
|
});
|
|
3077
3261
|
}
|
|
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("");
|
|
3262
|
+
function consentPage(signedQuery, nonce) {
|
|
3263
|
+
const query = new URLSearchParams(signedQuery);
|
|
3264
|
+
const client = escapeHtml(query.get("client_id") ?? "this client");
|
|
3265
|
+
const scopes = (query.get("scope") ?? "basic identity").split(/\s+/).filter(Boolean).map((scope) => `<li>${escapeHtml(scope.replaceAll("_", " "))}</li>`).join("");
|
|
3082
3266
|
return authPage({
|
|
3083
3267
|
title: "Review access | Work",
|
|
3084
3268
|
nonce,
|
|
@@ -3095,7 +3279,7 @@ function consentPage(query, nonce) {
|
|
|
3095
3279
|
<ul class="scope-list">${scopes}</ul>
|
|
3096
3280
|
</div>
|
|
3097
3281
|
<form class="consent-actions" action="/oauth/consent" method="post">
|
|
3098
|
-
<input type="hidden" name="
|
|
3282
|
+
<input type="hidden" name="oauth_query" value="${escapeHtml(signedQuery)}">
|
|
3099
3283
|
<button class="button button-secondary" name="accept" value="false">Deny</button>
|
|
3100
3284
|
<button class="button button-primary" name="accept" value="true">Allow access</button>
|
|
3101
3285
|
</form>
|
|
@@ -3375,11 +3559,14 @@ function escapeHtml(value) {
|
|
|
3375
3559
|
}
|
|
3376
3560
|
|
|
3377
3561
|
// src/auth/work-auth.ts
|
|
3378
|
-
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
3562
|
+
import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
|
|
3379
3563
|
import fs8 from "node:fs";
|
|
3380
3564
|
import path5 from "node:path";
|
|
3565
|
+
import { mcp } from "@better-auth/mcp";
|
|
3566
|
+
import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
|
|
3381
3567
|
import { betterAuth } from "better-auth";
|
|
3382
|
-
import { bearer, genericOAuth,
|
|
3568
|
+
import { bearer, genericOAuth, username } from "better-auth/plugins";
|
|
3569
|
+
import { z as z9 } from "zod";
|
|
3383
3570
|
var PROVIDER_SIGN_IN_LIMIT = { window: 10, max: 30 };
|
|
3384
3571
|
function createWorkAuth(options) {
|
|
3385
3572
|
const config = options.config ?? parseWorkAuthConfig({});
|
|
@@ -3394,11 +3581,13 @@ function createWorkAuth(options) {
|
|
|
3394
3581
|
enabled: options.rateLimit ?? true,
|
|
3395
3582
|
storage: "database",
|
|
3396
3583
|
customRules: {
|
|
3397
|
-
"/sign-in/oauth2": PROVIDER_SIGN_IN_LIMIT,
|
|
3398
3584
|
"/sign-in/social": PROVIDER_SIGN_IN_LIMIT
|
|
3399
3585
|
}
|
|
3400
3586
|
},
|
|
3401
|
-
advanced: {
|
|
3587
|
+
advanced: {
|
|
3588
|
+
ipAddress: { ipAddressHeaders: [CLIENT_ADDRESS_HEADER] },
|
|
3589
|
+
database: { validateSchema: false }
|
|
3590
|
+
},
|
|
3402
3591
|
plugins: [
|
|
3403
3592
|
username(),
|
|
3404
3593
|
bearer(),
|
|
@@ -3429,21 +3618,29 @@ function createWorkAuth(options) {
|
|
|
3429
3618
|
}),
|
|
3430
3619
|
mcp({
|
|
3431
3620
|
loginPage: `${options.baseURL}/login`,
|
|
3621
|
+
consentPage: `${options.baseURL}/oauth/consent`,
|
|
3432
3622
|
resource: `${options.baseURL}/api`,
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3623
|
+
disableJwtPlugin: true,
|
|
3624
|
+
allowDynamicClientRegistration: true,
|
|
3625
|
+
allowUnauthenticatedClientRegistration: true,
|
|
3626
|
+
clientRegistrationDefaultApplicationType: "infer",
|
|
3627
|
+
clientRegistrationRequirePKCE: true,
|
|
3628
|
+
grantTypes: ["authorization_code", "refresh_token"],
|
|
3629
|
+
accessTokenExpiresIn: config.sessions.accessTokenSeconds,
|
|
3630
|
+
refreshTokenExpiresIn: config.sessions.idleSeconds,
|
|
3631
|
+
refreshTokenReuseInterval: 0
|
|
3442
3632
|
})
|
|
3443
3633
|
]
|
|
3444
3634
|
});
|
|
3445
3635
|
return {
|
|
3446
|
-
|
|
3636
|
+
verifyAuthorizationQuery: ({ query }) => verifyOAuthQueryParams(query, options.secret),
|
|
3637
|
+
migrate: async () => {
|
|
3638
|
+
await options.database.migrate({
|
|
3639
|
+
options: auth.options,
|
|
3640
|
+
resource: `${options.baseURL}/api`
|
|
3641
|
+
});
|
|
3642
|
+
await (await auth.$context).explicitSchemaCheck?.();
|
|
3643
|
+
},
|
|
3447
3644
|
createLocalUser: async (args) => {
|
|
3448
3645
|
if (!config.local.enabled) {
|
|
3449
3646
|
throw new Error("Local username and password authentication is disabled");
|
|
@@ -3492,20 +3689,33 @@ function createWorkAuth(options) {
|
|
|
3492
3689
|
return found ? workAuthUser(found.user) : null;
|
|
3493
3690
|
},
|
|
3494
3691
|
resolveAccessToken: async ({ authorization }) => {
|
|
3495
|
-
const
|
|
3496
|
-
|
|
3497
|
-
});
|
|
3498
|
-
if (!result?.userId)
|
|
3692
|
+
const bearerToken = /^Bearer ([^\s]+)$/i.exec(authorization)?.[1];
|
|
3693
|
+
if (!bearerToken)
|
|
3499
3694
|
return null;
|
|
3500
3695
|
const context = await auth.$context;
|
|
3501
|
-
const
|
|
3696
|
+
const parsed = AccessGrant.safeParse(await context.adapter.findOne({
|
|
3697
|
+
model: "oauthAccessToken",
|
|
3698
|
+
where: [{ field: "token", value: authTokenHash(bearerToken) }]
|
|
3699
|
+
}));
|
|
3700
|
+
if (!parsed.success)
|
|
3701
|
+
return null;
|
|
3702
|
+
const grant = parsed.data;
|
|
3703
|
+
if (!grant.userId || grant.revoked || !grant.resources?.includes(`${options.baseURL}/api`) || grant.confirmation != null || grant.expiresAt.getTime() <= Date.now())
|
|
3704
|
+
return null;
|
|
3705
|
+
const client = z9.object({ disabled: z9.boolean().nullish() }).safeParse(await context.adapter.findOne({
|
|
3706
|
+
model: "oauthClient",
|
|
3707
|
+
where: [{ field: "clientId", value: grant.clientId }]
|
|
3708
|
+
}));
|
|
3709
|
+
if (!client.success || client.data.disabled === true)
|
|
3710
|
+
return null;
|
|
3711
|
+
const user = await context.internalAdapter.findUserById(grant.userId);
|
|
3502
3712
|
if (!user)
|
|
3503
3713
|
return null;
|
|
3504
3714
|
return {
|
|
3505
|
-
userId:
|
|
3715
|
+
userId: grant.userId,
|
|
3506
3716
|
email: user.email,
|
|
3507
3717
|
emailVerified: user.emailVerified,
|
|
3508
|
-
scopes:
|
|
3718
|
+
scopes: grant.scopes
|
|
3509
3719
|
};
|
|
3510
3720
|
},
|
|
3511
3721
|
accountsFor: async ({ userId }) => {
|
|
@@ -3520,24 +3730,45 @@ function createWorkAuth(options) {
|
|
|
3520
3730
|
const context = await auth.$context;
|
|
3521
3731
|
return toGrant(await context.adapter.findOne({
|
|
3522
3732
|
model: "oauthAccessToken",
|
|
3523
|
-
where: [{ field: "
|
|
3733
|
+
where: [{ field: "token", value: authTokenHash(accessToken) }]
|
|
3524
3734
|
}));
|
|
3525
3735
|
},
|
|
3526
3736
|
grantByRefreshToken: async ({ refreshToken }) => {
|
|
3527
3737
|
const context = await auth.$context;
|
|
3738
|
+
const refresh = z9.object({ id: z9.string() }).safeParse(await context.adapter.findOne({
|
|
3739
|
+
model: "oauthRefreshToken",
|
|
3740
|
+
where: [{ field: "token", value: authTokenHash(refreshToken) }]
|
|
3741
|
+
}));
|
|
3742
|
+
if (!refresh.success)
|
|
3743
|
+
return null;
|
|
3528
3744
|
return toGrant(await context.adapter.findOne({
|
|
3529
3745
|
model: "oauthAccessToken",
|
|
3530
|
-
where: [{ field: "
|
|
3746
|
+
where: [{ field: "refreshId", value: refresh.data.id }]
|
|
3531
3747
|
}));
|
|
3532
3748
|
},
|
|
3533
3749
|
deleteGrants: async ({ ids }) => {
|
|
3534
3750
|
if (ids.length === 0)
|
|
3535
3751
|
return;
|
|
3536
3752
|
const context = await auth.$context;
|
|
3753
|
+
const grants = await context.adapter.findMany({
|
|
3754
|
+
model: "oauthAccessToken",
|
|
3755
|
+
where: [{ field: "id", operator: "in", value: [...ids] }]
|
|
3756
|
+
});
|
|
3757
|
+
const refreshIds = grants.flatMap((grant) => typeof grant === "object" && grant !== null && ("refreshId" in grant) && typeof grant.refreshId === "string" ? [grant.refreshId] : []);
|
|
3537
3758
|
await context.adapter.deleteMany({
|
|
3538
3759
|
model: "oauthAccessToken",
|
|
3539
3760
|
where: [{ field: "id", operator: "in", value: [...ids] }]
|
|
3540
3761
|
});
|
|
3762
|
+
if (refreshIds.length) {
|
|
3763
|
+
await context.adapter.deleteMany({
|
|
3764
|
+
model: "oauthAccessToken",
|
|
3765
|
+
where: [{ field: "refreshId", operator: "in", value: refreshIds }]
|
|
3766
|
+
});
|
|
3767
|
+
await context.adapter.deleteMany({
|
|
3768
|
+
model: "oauthRefreshToken",
|
|
3769
|
+
where: [{ field: "id", operator: "in", value: refreshIds }]
|
|
3770
|
+
});
|
|
3771
|
+
}
|
|
3541
3772
|
},
|
|
3542
3773
|
signOutEverywhere: async ({ userId }) => {
|
|
3543
3774
|
const context = await auth.$context;
|
|
@@ -3545,6 +3776,10 @@ function createWorkAuth(options) {
|
|
|
3545
3776
|
model: "oauthAccessToken",
|
|
3546
3777
|
where: [{ field: "userId", value: userId }]
|
|
3547
3778
|
});
|
|
3779
|
+
await context.adapter.deleteMany({
|
|
3780
|
+
model: "oauthRefreshToken",
|
|
3781
|
+
where: [{ field: "userId", value: userId }]
|
|
3782
|
+
});
|
|
3548
3783
|
await context.internalAdapter.deleteUserSessions(userId);
|
|
3549
3784
|
},
|
|
3550
3785
|
usersSignedIn: async () => {
|
|
@@ -3552,9 +3787,10 @@ function createWorkAuth(options) {
|
|
|
3552
3787
|
const now = new Date;
|
|
3553
3788
|
const [grants, sessions] = await Promise.all([
|
|
3554
3789
|
context.adapter.findMany({
|
|
3555
|
-
model: "
|
|
3790
|
+
model: "oauthRefreshToken",
|
|
3556
3791
|
where: [
|
|
3557
|
-
{ field: "
|
|
3792
|
+
{ field: "expiresAt", operator: "gt", value: now },
|
|
3793
|
+
{ field: "revoked", value: null }
|
|
3558
3794
|
]
|
|
3559
3795
|
}),
|
|
3560
3796
|
context.adapter.findMany({
|
|
@@ -3582,6 +3818,19 @@ function createWorkAuth(options) {
|
|
|
3582
3818
|
close: () => options.database.close()
|
|
3583
3819
|
};
|
|
3584
3820
|
}
|
|
3821
|
+
var AccessGrant = z9.object({
|
|
3822
|
+
id: z9.string(),
|
|
3823
|
+
userId: z9.string().nullish(),
|
|
3824
|
+
clientId: z9.string(),
|
|
3825
|
+
expiresAt: z9.coerce.date(),
|
|
3826
|
+
revoked: z9.coerce.date().nullish(),
|
|
3827
|
+
scopes: z9.array(z9.string()),
|
|
3828
|
+
resources: z9.array(z9.string()).nullish(),
|
|
3829
|
+
confirmation: z9.unknown().nullish()
|
|
3830
|
+
});
|
|
3831
|
+
function authTokenHash(token) {
|
|
3832
|
+
return createHash2("sha256").update(token).digest("base64url");
|
|
3833
|
+
}
|
|
3585
3834
|
function toGrant(row) {
|
|
3586
3835
|
if (typeof row !== "object" || row === null)
|
|
3587
3836
|
return null;
|
|
@@ -3668,7 +3917,7 @@ function isNodeError2(error) {
|
|
|
3668
3917
|
}
|
|
3669
3918
|
|
|
3670
3919
|
// src/cluster.ts
|
|
3671
|
-
import { createECDH, createHash as
|
|
3920
|
+
import { createECDH, createHash as createHash4 } from "node:crypto";
|
|
3672
3921
|
import {
|
|
3673
3922
|
capacityFits,
|
|
3674
3923
|
cleanupWorkerAllocations as cleanupWorkerAllocations2,
|
|
@@ -3683,10 +3932,10 @@ import {
|
|
|
3683
3932
|
placementOrder,
|
|
3684
3933
|
poolMatches
|
|
3685
3934
|
} from "@catamorphic/sandbox";
|
|
3686
|
-
import { sql as
|
|
3935
|
+
import { sql as sql4 } from "kysely";
|
|
3687
3936
|
|
|
3688
3937
|
// src/workers/worker-registry.ts
|
|
3689
|
-
import { createHash, randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
|
|
3938
|
+
import { createHash as createHash3, randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
|
|
3690
3939
|
import {
|
|
3691
3940
|
cleanupWorkerAllocations,
|
|
3692
3941
|
forgetExecutorKey,
|
|
@@ -3702,17 +3951,17 @@ import {
|
|
|
3702
3951
|
import {
|
|
3703
3952
|
ExecutorPublicKeySchema
|
|
3704
3953
|
} from "@catamorphic/sandbox";
|
|
3705
|
-
import { sql as
|
|
3706
|
-
import { z as
|
|
3954
|
+
import { sql as sql3 } from "kysely";
|
|
3955
|
+
import { z as z10 } from "zod";
|
|
3707
3956
|
var WORKER_NODE_PREFIX = "worker.";
|
|
3708
|
-
var WorkerName =
|
|
3709
|
-
var WorkerOfferSchema =
|
|
3710
|
-
isolation:
|
|
3711
|
-
resourceLimits:
|
|
3712
|
-
workspaceRoot:
|
|
3713
|
-
processes:
|
|
3714
|
-
capabilities:
|
|
3715
|
-
|
|
3957
|
+
var WorkerName = z10.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/, "Use lowercase letters, digits, dashes");
|
|
3958
|
+
var WorkerOfferSchema = z10.strictObject({
|
|
3959
|
+
isolation: z10.enum(["process", "sandbox"]),
|
|
3960
|
+
resourceLimits: z10.array(z10.enum(["cpuMillis", "memoryMb", "storageMb", "gpu"])).default([]),
|
|
3961
|
+
workspaceRoot: z10.string().startsWith("/"),
|
|
3962
|
+
processes: z10.boolean().default(false),
|
|
3963
|
+
capabilities: z10.array(z10.union([
|
|
3964
|
+
z10.enum([
|
|
3716
3965
|
"images",
|
|
3717
3966
|
"images.build",
|
|
3718
3967
|
"containers",
|
|
@@ -3724,26 +3973,26 @@ var WorkerOfferSchema = z8.strictObject({
|
|
|
3724
3973
|
"harness.codex",
|
|
3725
3974
|
"sign-ins"
|
|
3726
3975
|
]),
|
|
3727
|
-
|
|
3976
|
+
z10.string().regex(/^sign-in:(claude-code|codex):\S{1,255}$/)
|
|
3728
3977
|
])).max(1e4).default([]),
|
|
3729
|
-
capacity:
|
|
3730
|
-
workspaces:
|
|
3731
|
-
cpuMillis:
|
|
3732
|
-
memoryMb:
|
|
3978
|
+
capacity: z10.strictObject({
|
|
3979
|
+
workspaces: z10.number().int().positive().max(1000),
|
|
3980
|
+
cpuMillis: z10.number().int().positive().optional(),
|
|
3981
|
+
memoryMb: z10.number().int().positive().optional()
|
|
3733
3982
|
}),
|
|
3734
|
-
defaults:
|
|
3735
|
-
cpuMillis:
|
|
3736
|
-
memoryMb:
|
|
3983
|
+
defaults: z10.strictObject({
|
|
3984
|
+
cpuMillis: z10.number().int().positive().optional(),
|
|
3985
|
+
memoryMb: z10.number().int().positive().optional()
|
|
3737
3986
|
}).default({}),
|
|
3738
|
-
version:
|
|
3739
|
-
backend:
|
|
3740
|
-
kind:
|
|
3741
|
-
runtime:
|
|
3742
|
-
reason:
|
|
3987
|
+
version: z10.string().max(100).optional(),
|
|
3988
|
+
backend: z10.strictObject({
|
|
3989
|
+
kind: z10.enum(["microsandbox", "container", "local-process"]),
|
|
3990
|
+
runtime: z10.enum(["runsc", "runc"]).optional(),
|
|
3991
|
+
reason: z10.string().max(1000)
|
|
3743
3992
|
}).optional()
|
|
3744
3993
|
});
|
|
3745
|
-
var WorkerConnectSchema =
|
|
3746
|
-
session:
|
|
3994
|
+
var WorkerConnectSchema = z10.strictObject({
|
|
3995
|
+
session: z10.string().regex(REMOTE_EPOCH_PATTERN, "Use a UUIDv7 epoch"),
|
|
3747
3996
|
offer: WorkerOfferSchema,
|
|
3748
3997
|
publicKey: ExecutorPublicKeySchema
|
|
3749
3998
|
});
|
|
@@ -3756,7 +4005,7 @@ class WorkerIsolationError extends Error {
|
|
|
3756
4005
|
}
|
|
3757
4006
|
}
|
|
3758
4007
|
var NOBODY = { nobody: true };
|
|
3759
|
-
var releasedFor =
|
|
4008
|
+
var releasedFor = sql3`(extract(epoch from (now() - released_at)) * 1000)::float8`;
|
|
3760
4009
|
|
|
3761
4010
|
class WorkerDisabledError extends Error {
|
|
3762
4011
|
constructor() {
|
|
@@ -3842,9 +4091,9 @@ class WorkWorkerRegistry {
|
|
|
3842
4091
|
throw await this.ended(args);
|
|
3843
4092
|
}
|
|
3844
4093
|
async seen(nodeId) {
|
|
3845
|
-
await this.deps.db.updateTable("work_workers").set({ last_seen_at:
|
|
4094
|
+
await this.deps.db.updateTable("work_workers").set({ last_seen_at: sql3`now()` }).where("node_id", "=", nodeId).where((eb) => eb.or([
|
|
3846
4095
|
eb("last_seen_at", "is", null),
|
|
3847
|
-
eb("last_seen_at", "<",
|
|
4096
|
+
eb("last_seen_at", "<", sql3`now() - interval '5 seconds'`)
|
|
3848
4097
|
])).execute();
|
|
3849
4098
|
}
|
|
3850
4099
|
async ended(args) {
|
|
@@ -3870,7 +4119,7 @@ class WorkWorkerRegistry {
|
|
|
3870
4119
|
const name = WorkerName.parse(args.name);
|
|
3871
4120
|
const placement = WorkerPlacementSchema.parse(args.placement ?? {});
|
|
3872
4121
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
3873
|
-
await
|
|
4122
|
+
await sql3`SELECT pg_advisory_xact_lock(hashtext(${`work-worker-name:${this.deps.tenantId}:${name}`}))`.execute(trx);
|
|
3874
4123
|
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
4124
|
if (enrolled)
|
|
3876
4125
|
return null;
|
|
@@ -3899,7 +4148,7 @@ class WorkWorkerRegistry {
|
|
|
3899
4148
|
async enroll(args) {
|
|
3900
4149
|
const publicKey = ExecutorPublicKeySchema.parse(args.publicKey);
|
|
3901
4150
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
3902
|
-
const enrollment = await trx.updateTable("work_worker_enrollments").set({ used_at:
|
|
4151
|
+
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
4152
|
"name",
|
|
3904
4153
|
"labels",
|
|
3905
4154
|
"access",
|
|
@@ -3945,7 +4194,7 @@ class WorkWorkerRegistry {
|
|
|
3945
4194
|
return;
|
|
3946
4195
|
const nodeId = match[1];
|
|
3947
4196
|
const presented = hash(match[2]);
|
|
3948
|
-
const row = await this.deps.db.selectFrom("work_workers").select(["name", "credential_hash", "pending_credential_hash"]).select(
|
|
4197
|
+
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
4198
|
if (!row)
|
|
3950
4199
|
return;
|
|
3951
4200
|
if (sameHash(row.credential_hash, presented))
|
|
@@ -3970,13 +4219,13 @@ class WorkWorkerRegistry {
|
|
|
3970
4219
|
return;
|
|
3971
4220
|
const promoted = await trx.updateTable("work_workers").set({
|
|
3972
4221
|
credential_hash: args.credentialHash,
|
|
3973
|
-
credential_issued_at:
|
|
4222
|
+
credential_issued_at: sql3`COALESCE(pending_issued_at, now())`,
|
|
3974
4223
|
pending_credential_hash: null,
|
|
3975
4224
|
pending_public_key: null,
|
|
3976
4225
|
pending_issued_at: null,
|
|
3977
4226
|
pending_rotation: null,
|
|
3978
|
-
rotation_requested_at:
|
|
3979
|
-
}).where("node_id", "=", args.nodeId).returning(
|
|
4227
|
+
rotation_requested_at: sql3`CASE WHEN rotation_requested_at <= pending_issued_at THEN NULL ELSE rotation_requested_at END`
|
|
4228
|
+
}).where("node_id", "=", args.nodeId).returning(sql3`rotation_requested_at IS NOT NULL`.as("rotate")).executeTakeFirstOrThrow();
|
|
3980
4229
|
await registerExecutorKey({
|
|
3981
4230
|
db: trx,
|
|
3982
4231
|
executor: nodeExecutor(args.nodeId),
|
|
@@ -4000,14 +4249,14 @@ class WorkWorkerRegistry {
|
|
|
4000
4249
|
await trx.updateTable("work_workers").set({
|
|
4001
4250
|
pending_credential_hash: hash(secret),
|
|
4002
4251
|
pending_public_key: publicKey,
|
|
4003
|
-
pending_issued_at:
|
|
4252
|
+
pending_issued_at: sql3`now()`,
|
|
4004
4253
|
pending_rotation: args.rotation
|
|
4005
4254
|
}).where("node_id", "=", args.nodeId).execute();
|
|
4006
4255
|
});
|
|
4007
4256
|
return { credential: `${args.nodeId}:${secret}` };
|
|
4008
4257
|
}
|
|
4009
4258
|
async requestRotation(args) {
|
|
4010
|
-
const row = await this.deps.db.updateTable("work_workers").set({ rotation_requested_at:
|
|
4259
|
+
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
4260
|
return Boolean(row);
|
|
4012
4261
|
}
|
|
4013
4262
|
async connect(args) {
|
|
@@ -4133,7 +4382,7 @@ class WorkWorkerRegistry {
|
|
|
4133
4382
|
}
|
|
4134
4383
|
async revoke(args) {
|
|
4135
4384
|
const row = await this.deps.db.updateTable("work_workers").set({
|
|
4136
|
-
revoked_at:
|
|
4385
|
+
revoked_at: sql3`now()`,
|
|
4137
4386
|
pending_credential_hash: null,
|
|
4138
4387
|
pending_public_key: null,
|
|
4139
4388
|
pending_issued_at: null,
|
|
@@ -4156,17 +4405,17 @@ class WorkWorkerRegistry {
|
|
|
4156
4405
|
async drain(args) {
|
|
4157
4406
|
const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
|
|
4158
4407
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
4159
|
-
const node = await trx.selectFrom("worker_nodes").select(
|
|
4408
|
+
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
4409
|
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
4410
|
if (Number(held?.count ?? 0) > 0) {
|
|
4162
4411
|
if (node?.live)
|
|
4163
4412
|
return false;
|
|
4164
|
-
const lost = await trx.selectFrom("work_workers").select("node_id").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where(
|
|
4413
|
+
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
4414
|
if (!lost)
|
|
4166
4415
|
return false;
|
|
4167
4416
|
}
|
|
4168
4417
|
const revoked = await trx.updateTable("work_workers").set({
|
|
4169
|
-
revoked_at:
|
|
4418
|
+
revoked_at: sql3`now()`,
|
|
4170
4419
|
pending_credential_hash: null,
|
|
4171
4420
|
pending_public_key: null,
|
|
4172
4421
|
pending_issued_at: null,
|
|
@@ -4183,17 +4432,17 @@ class WorkWorkerRegistry {
|
|
|
4183
4432
|
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
4433
|
const load = this.deps.db.selectFrom("execution_allocations").select([
|
|
4185
4434
|
"worker_node_id",
|
|
4186
|
-
|
|
4187
|
-
|
|
4435
|
+
sql3`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as("holding"),
|
|
4436
|
+
sql3`max(capacity_released_at)`.as("last_released")
|
|
4188
4437
|
]).where("worker_node_id", "in", machines).groupBy("worker_node_id").as("load");
|
|
4189
4438
|
const [rows, nodes] = await Promise.all([
|
|
4190
4439
|
this.deps.db.selectFrom("work_workers").leftJoin(load, "load.worker_node_id", "work_workers.node_id").select([
|
|
4191
4440
|
"work_workers.name",
|
|
4192
4441
|
"work_workers.node_id",
|
|
4193
4442
|
"load.holding",
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4443
|
+
sql3`work_workers.last_seen_at IS NULL`.as("never_connected"),
|
|
4444
|
+
sql3`(extract(epoch from (now() - greatest(work_workers.enrolled_at, load.last_released))) * 1000)::float8`.as("idle_for_ms"),
|
|
4445
|
+
sql3`(extract(epoch from (now() - coalesce(work_workers.last_seen_at, work_workers.enrolled_at))) * 1000)::float8`.as("unseen_for_ms")
|
|
4197
4446
|
]).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
4447
|
this.deps.nodes.list({
|
|
4199
4448
|
tenantId: this.deps.tenantId,
|
|
@@ -4254,7 +4503,7 @@ class WorkWorkerRegistry {
|
|
|
4254
4503
|
"labels",
|
|
4255
4504
|
"access",
|
|
4256
4505
|
"trusted",
|
|
4257
|
-
|
|
4506
|
+
sql3`expires_at <= now()`.as("expired")
|
|
4258
4507
|
]).where("tenant_id", "=", this.deps.tenantId).where("machine_rule", "is not", null).where("used_at", "is", null).execute()
|
|
4259
4508
|
]);
|
|
4260
4509
|
return [
|
|
@@ -4314,7 +4563,7 @@ class WorkWorkerRegistry {
|
|
|
4314
4563
|
return Boolean(assigned);
|
|
4315
4564
|
}
|
|
4316
4565
|
async release(args) {
|
|
4317
|
-
await this.deps.db.updateTable("work_workers").set({ released_at:
|
|
4566
|
+
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
4567
|
}
|
|
4319
4568
|
async reassign(args) {
|
|
4320
4569
|
await this.deps.db.updateTable("work_workers").set({
|
|
@@ -4375,11 +4624,11 @@ class WorkWorkerRegistry {
|
|
|
4375
4624
|
}).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("pool", "=", true).where("machine_rule", "is", null).execute();
|
|
4376
4625
|
}
|
|
4377
4626
|
async forgetMachine(args) {
|
|
4378
|
-
await this.deps.db.updateTable("work_workers").set({ machine_destroyed_at:
|
|
4627
|
+
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
4628
|
await this.cancelEnrollments({ name: args.name });
|
|
4380
4629
|
}
|
|
4381
4630
|
async expireEnrollments(args) {
|
|
4382
|
-
await this.deps.db.updateTable("work_worker_enrollments").set({ expires_at:
|
|
4631
|
+
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
4632
|
}
|
|
4384
4633
|
async cancelEnrollments(args) {
|
|
4385
4634
|
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 +4657,7 @@ class WorkWorkerRegistry {
|
|
|
4408
4657
|
}
|
|
4409
4658
|
}
|
|
4410
4659
|
function hash(value) {
|
|
4411
|
-
return
|
|
4660
|
+
return createHash3("sha256").update(value).digest("hex");
|
|
4412
4661
|
}
|
|
4413
4662
|
function workerState(row) {
|
|
4414
4663
|
if (row.revoked_at)
|
|
@@ -4643,7 +4892,7 @@ async function registerWorkMachine(args) {
|
|
|
4643
4892
|
if (JSON.stringify(next) === JSON.stringify(signIns))
|
|
4644
4893
|
return;
|
|
4645
4894
|
signIns = next;
|
|
4646
|
-
refreshing = args.db.updateTable("worker_nodes").set({ descriptor: JSON.stringify(describe()), updated_at:
|
|
4895
|
+
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
4896
|
refreshing = undefined;
|
|
4648
4897
|
if (!again)
|
|
4649
4898
|
return;
|
|
@@ -4672,12 +4921,12 @@ async function registerWorkMachine(args) {
|
|
|
4672
4921
|
};
|
|
4673
4922
|
}
|
|
4674
4923
|
function workAuthorityId(publicBase) {
|
|
4675
|
-
return `work:${
|
|
4924
|
+
return `work:${createHash4("sha256").update(publicBase).digest("hex").slice(0, 24)}`;
|
|
4676
4925
|
}
|
|
4677
4926
|
function workPushKeys(secret) {
|
|
4678
4927
|
const ecdh = createECDH("prime256v1");
|
|
4679
4928
|
for (let counter = 0;counter < 10; counter += 1) {
|
|
4680
|
-
const key =
|
|
4929
|
+
const key = createHash4("sha256").update(`catamorphic/push/v1/${counter}\x00`).update(secret).digest();
|
|
4681
4930
|
try {
|
|
4682
4931
|
ecdh.setPrivateKey(key);
|
|
4683
4932
|
return {
|
|
@@ -4783,7 +5032,7 @@ function startCompanyProjectSync(input) {
|
|
|
4783
5032
|
}
|
|
4784
5033
|
|
|
4785
5034
|
// src/credential-vault.ts
|
|
4786
|
-
import { createHash as
|
|
5035
|
+
import { createHash as createHash5, randomBytes as randomBytes4, randomUUID as randomUUID4 } from "node:crypto";
|
|
4787
5036
|
import fs9 from "node:fs";
|
|
4788
5037
|
import path6 from "node:path";
|
|
4789
5038
|
import { EncryptedCredentialVault } from "@catamorphic/core";
|
|
@@ -4805,7 +5054,7 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4805
5054
|
const records = path6.join(directory, "records");
|
|
4806
5055
|
fs9.mkdirSync(records, { recursive: true, mode: 448 });
|
|
4807
5056
|
fs9.chmodSync(records, 448);
|
|
4808
|
-
const file = (key) => path6.join(records, `${
|
|
5057
|
+
const file = (key) => path6.join(records, `${createHash5("sha256").update(key).digest("hex")}.json`);
|
|
4809
5058
|
super({
|
|
4810
5059
|
keys: configuredKeys.length > 0 ? configuredKeys : [fs9.readFileSync(keyFile)],
|
|
4811
5060
|
store: {
|
|
@@ -4814,7 +5063,7 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4814
5063
|
const data = fs9.readFileSync(file(key));
|
|
4815
5064
|
return {
|
|
4816
5065
|
data,
|
|
4817
|
-
etag:
|
|
5066
|
+
etag: createHash5("sha256").update(data).digest("hex")
|
|
4818
5067
|
};
|
|
4819
5068
|
} catch (error) {
|
|
4820
5069
|
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
@@ -4824,7 +5073,7 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4824
5073
|
},
|
|
4825
5074
|
put: async (key, data) => {
|
|
4826
5075
|
const target = file(key);
|
|
4827
|
-
const temporary = `${target}.${
|
|
5076
|
+
const temporary = `${target}.${randomUUID4()}.tmp`;
|
|
4828
5077
|
fs9.writeFileSync(temporary, data, { mode: 384, flag: "wx" });
|
|
4829
5078
|
fs9.renameSync(temporary, target);
|
|
4830
5079
|
},
|
|
@@ -4837,14 +5086,14 @@ class EncryptedFileCredentialVault extends EncryptedCredentialVault {
|
|
|
4837
5086
|
}
|
|
4838
5087
|
|
|
4839
5088
|
// src/identity/account-lifecycle.ts
|
|
4840
|
-
import { createHash as
|
|
5089
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
4841
5090
|
import { getTracer, withSpan } from "@catamorphic/otel";
|
|
4842
5091
|
import {
|
|
4843
5092
|
DIRECTORY_EVENT_KINDS,
|
|
4844
5093
|
DIRECTORY_EVENT_SOURCE,
|
|
4845
5094
|
directoryProjectEvent
|
|
4846
5095
|
} from "@catamorphic/server-sdk";
|
|
4847
|
-
import { sql as
|
|
5096
|
+
import { sql as sql5 } from "kysely";
|
|
4848
5097
|
var tracer = getTracer("@catamorphic/work-server");
|
|
4849
5098
|
|
|
4850
5099
|
class AccountLifecycle {
|
|
@@ -5052,7 +5301,7 @@ class AccountLifecycle {
|
|
|
5052
5301
|
let claimed;
|
|
5053
5302
|
try {
|
|
5054
5303
|
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", "<=",
|
|
5304
|
+
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
5305
|
if (!row)
|
|
5057
5306
|
return "none";
|
|
5058
5307
|
claimed = {
|
|
@@ -5080,7 +5329,7 @@ class AccountLifecycle {
|
|
|
5080
5329
|
await this.deps.db.updateTable("work_directory_announcements").set({
|
|
5081
5330
|
attempts: attempts + 1,
|
|
5082
5331
|
last_error: message,
|
|
5083
|
-
next_attempt_at:
|
|
5332
|
+
next_attempt_at: sql5`now() + make_interval(secs => ${Math.min(300, 2 ** attempts)})`
|
|
5084
5333
|
}).where("id", "=", claimed.id).execute();
|
|
5085
5334
|
this.deps.log?.(`Directory event ${claimed.externalId} did not reach its projects (attempt ${attempts + 1}): ${message}`);
|
|
5086
5335
|
return "failed";
|
|
@@ -5277,7 +5526,7 @@ class AccountLifecycle {
|
|
|
5277
5526
|
}
|
|
5278
5527
|
}
|
|
5279
5528
|
function hashToken(token) {
|
|
5280
|
-
return
|
|
5529
|
+
return createHash6("sha256").update(token).digest("hex");
|
|
5281
5530
|
}
|
|
5282
5531
|
function jsonObject(value) {
|
|
5283
5532
|
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
@@ -5293,7 +5542,7 @@ function groupList(value) {
|
|
|
5293
5542
|
}
|
|
5294
5543
|
|
|
5295
5544
|
// src/identity/administrator-routes.ts
|
|
5296
|
-
import { z as
|
|
5545
|
+
import { z as z11 } from "zod";
|
|
5297
5546
|
|
|
5298
5547
|
// src/identity/administrators.ts
|
|
5299
5548
|
var ADMINISTRATOR_PERMISSIONS = [
|
|
@@ -5380,7 +5629,7 @@ function registerAdministratorRoutes(app, options) {
|
|
|
5380
5629
|
const caller = await administrator(request);
|
|
5381
5630
|
if (caller.status !== 200)
|
|
5382
5631
|
return reply.status(caller.status).send(refusal(caller.status));
|
|
5383
|
-
const body =
|
|
5632
|
+
const body = z11.strictObject({ email: z11.email() }).safeParse(request.body);
|
|
5384
5633
|
if (!body.success)
|
|
5385
5634
|
return reply.status(400).send({ error: "An email address is required" });
|
|
5386
5635
|
try {
|
|
@@ -5398,7 +5647,7 @@ function registerAdministratorRoutes(app, options) {
|
|
|
5398
5647
|
const caller = await administrator(request);
|
|
5399
5648
|
if (caller.status !== 200)
|
|
5400
5649
|
return reply.status(caller.status).send(refusal(caller.status));
|
|
5401
|
-
const { userId } =
|
|
5650
|
+
const { userId } = z11.object({ userId: z11.string().min(1) }).parse(request.params);
|
|
5402
5651
|
try {
|
|
5403
5652
|
await options.administrators.set({ userId, administrator: false });
|
|
5404
5653
|
return reply.status(204).send();
|
|
@@ -5419,7 +5668,7 @@ import {
|
|
|
5419
5668
|
ConnectionPermissionDeniedError,
|
|
5420
5669
|
ConnectionUnavailableError
|
|
5421
5670
|
} from "@catamorphic/core";
|
|
5422
|
-
import { z as
|
|
5671
|
+
import { z as z12 } from "zod";
|
|
5423
5672
|
|
|
5424
5673
|
// src/setup/operator-access.ts
|
|
5425
5674
|
import { randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
@@ -5474,18 +5723,18 @@ function isNodeError3(error) {
|
|
|
5474
5723
|
}
|
|
5475
5724
|
|
|
5476
5725
|
// src/setup/connections.ts
|
|
5477
|
-
var ServiceConnectionInput =
|
|
5478
|
-
name:
|
|
5479
|
-
providerKind:
|
|
5480
|
-
principalKind:
|
|
5481
|
-
projectId:
|
|
5482
|
-
label:
|
|
5726
|
+
var ServiceConnectionInput = z12.strictObject({
|
|
5727
|
+
name: z12.string().regex(CONNECTION_NAME_PATTERN),
|
|
5728
|
+
providerKind: z12.string().min(1),
|
|
5729
|
+
principalKind: z12.enum(["tenant_service", "project_service"]).default("tenant_service"),
|
|
5730
|
+
projectId: z12.string().uuid().optional(),
|
|
5731
|
+
label: z12.string().min(1).max(200).optional()
|
|
5483
5732
|
});
|
|
5484
|
-
var CompletionInput =
|
|
5485
|
-
authorizationId:
|
|
5486
|
-
fields:
|
|
5733
|
+
var CompletionInput = z12.strictObject({
|
|
5734
|
+
authorizationId: z12.string().min(1),
|
|
5735
|
+
fields: z12.record(z12.string(), z12.string()).default({})
|
|
5487
5736
|
});
|
|
5488
|
-
var Params =
|
|
5737
|
+
var Params = z12.object({ connectionId: z12.string().uuid() });
|
|
5489
5738
|
function registerConnectionSetup(args) {
|
|
5490
5739
|
args.app.register(async (app) => {
|
|
5491
5740
|
app.addHook("onRequest", async (request, reply) => {
|
|
@@ -5585,7 +5834,7 @@ function registerConnectionSetup(args) {
|
|
|
5585
5834
|
administrators: await args.administrators.list()
|
|
5586
5835
|
}));
|
|
5587
5836
|
app.post("/_work/operator/administrators", async (request, reply) => {
|
|
5588
|
-
const body =
|
|
5837
|
+
const body = z12.strictObject({ email: z12.email() }).safeParse(request.body);
|
|
5589
5838
|
if (!body.success)
|
|
5590
5839
|
return reply.status(400).send({ error: "An email address is required" });
|
|
5591
5840
|
try {
|
|
@@ -5604,7 +5853,7 @@ function registerConnectionSetup(args) {
|
|
|
5604
5853
|
}
|
|
5605
5854
|
});
|
|
5606
5855
|
app.delete("/_work/operator/administrators/:userId", async (request, reply) => {
|
|
5607
|
-
const { userId } =
|
|
5856
|
+
const { userId } = z12.object({ userId: z12.string().min(1) }).parse(request.params);
|
|
5608
5857
|
await args.administrators.set({
|
|
5609
5858
|
userId,
|
|
5610
5859
|
administrator: false,
|
|
@@ -5635,7 +5884,7 @@ function firstIssue(error) {
|
|
|
5635
5884
|
}
|
|
5636
5885
|
|
|
5637
5886
|
// src/setup/github-app.ts
|
|
5638
|
-
import { createHash as
|
|
5887
|
+
import { createHash as createHash7, randomBytes as randomBytes6 } from "node:crypto";
|
|
5639
5888
|
import {
|
|
5640
5889
|
UndeclaredSecretError
|
|
5641
5890
|
} from "@catamorphic/core";
|
|
@@ -5644,7 +5893,7 @@ import {
|
|
|
5644
5893
|
convertGithubAppManifest,
|
|
5645
5894
|
githubAppManifestForm
|
|
5646
5895
|
} from "@catamorphic/server-sdk";
|
|
5647
|
-
import { z as
|
|
5896
|
+
import { z as z13 } from "zod";
|
|
5648
5897
|
var WORK_GITHUB_APP_PERMISSIONS = {
|
|
5649
5898
|
contents: "write",
|
|
5650
5899
|
pull_requests: "write",
|
|
@@ -5663,28 +5912,28 @@ var WORK_GITHUB_APP_EVENTS = [
|
|
|
5663
5912
|
"push"
|
|
5664
5913
|
];
|
|
5665
5914
|
var GITHUB_WEBHOOK_SECRET = "GITHUB_WEBHOOK_SECRET";
|
|
5666
|
-
var StartInput =
|
|
5667
|
-
name:
|
|
5668
|
-
organization:
|
|
5669
|
-
projectId:
|
|
5670
|
-
connection:
|
|
5671
|
-
public:
|
|
5915
|
+
var StartInput = z13.strictObject({
|
|
5916
|
+
name: z13.string().trim().min(1).max(34),
|
|
5917
|
+
organization: z13.string().regex(/^[\w.-]+$/).optional(),
|
|
5918
|
+
projectId: z13.string().uuid().optional(),
|
|
5919
|
+
connection: z13.string().regex(/^[a-z0-9][a-z0-9._-]{0,62}$/).default("github"),
|
|
5920
|
+
public: z13.boolean().default(false)
|
|
5672
5921
|
});
|
|
5673
5922
|
var StoredInput = StartInput;
|
|
5674
|
-
var StoredApp =
|
|
5675
|
-
appId:
|
|
5676
|
-
slug:
|
|
5677
|
-
name:
|
|
5678
|
-
owner:
|
|
5679
|
-
htmlUrl:
|
|
5680
|
-
clientId:
|
|
5681
|
-
clientSecret:
|
|
5682
|
-
webhookSecret:
|
|
5683
|
-
privateKey:
|
|
5923
|
+
var StoredApp = z13.object({
|
|
5924
|
+
appId: z13.string(),
|
|
5925
|
+
slug: z13.string(),
|
|
5926
|
+
name: z13.string(),
|
|
5927
|
+
owner: z13.string().nullable(),
|
|
5928
|
+
htmlUrl: z13.string(),
|
|
5929
|
+
clientId: z13.string(),
|
|
5930
|
+
clientSecret: z13.string(),
|
|
5931
|
+
webhookSecret: z13.string().nullable(),
|
|
5932
|
+
privateKey: z13.string()
|
|
5684
5933
|
});
|
|
5685
5934
|
var TTL_MS = 60 * 60 * 1000;
|
|
5686
5935
|
function stateHash(state) {
|
|
5687
|
-
return
|
|
5936
|
+
return createHash7("sha256").update(state).digest("hex");
|
|
5688
5937
|
}
|
|
5689
5938
|
function registrationStore(args) {
|
|
5690
5939
|
const { db, vault, tenantId } = args;
|
|
@@ -5777,7 +6026,7 @@ function registerGithubAppSetup(args) {
|
|
|
5777
6026
|
expiresAt: expiresAt.toISOString()
|
|
5778
6027
|
});
|
|
5779
6028
|
});
|
|
5780
|
-
const Params =
|
|
6029
|
+
const Params = z13.object({ state: z13.string().min(20) });
|
|
5781
6030
|
args.publicApp.get(`${base}/:state`, async (request, reply) => {
|
|
5782
6031
|
const params = Params.safeParse(request.params);
|
|
5783
6032
|
const input = params.success ? await registrations.pending(params.data.state) : undefined;
|
|
@@ -5822,7 +6071,7 @@ function registerGithubAppSetup(args) {
|
|
|
5822
6071
|
});
|
|
5823
6072
|
args.publicApp.get(`${base}/:state/created`, async (request, reply) => {
|
|
5824
6073
|
const params = Params.safeParse(request.params);
|
|
5825
|
-
const query =
|
|
6074
|
+
const query = z13.object({ code: z13.string().min(1), state: z13.string().min(1) }).safeParse(request.query);
|
|
5826
6075
|
if (!params.success || !query.success || query.data.state !== params.data.state || !await registrations.claimCreation(params.data.state))
|
|
5827
6076
|
return expired(reply);
|
|
5828
6077
|
const state = params.data.state;
|
|
@@ -5845,7 +6094,7 @@ function registerGithubAppSetup(args) {
|
|
|
5845
6094
|
});
|
|
5846
6095
|
args.publicApp.get(`${base}/:state/installed`, async (request, reply) => {
|
|
5847
6096
|
const params = Params.safeParse(request.params);
|
|
5848
|
-
const query =
|
|
6097
|
+
const query = z13.object({ installation_id: z13.coerce.number().int().positive() }).safeParse(request.query);
|
|
5849
6098
|
const claimed = params.success && query.success ? await registrations.claimInstallation(params.data.state) : undefined;
|
|
5850
6099
|
if (!params.success || !query.success || !claimed)
|
|
5851
6100
|
return expired(reply);
|
|
@@ -5940,9 +6189,9 @@ function escapeHtml2(value) {
|
|
|
5940
6189
|
}
|
|
5941
6190
|
|
|
5942
6191
|
// src/setup/machines.ts
|
|
5943
|
-
import { z as
|
|
5944
|
-
var MachineParams =
|
|
5945
|
-
var MachineUpdate =
|
|
6192
|
+
import { z as z14 } from "zod";
|
|
6193
|
+
var MachineParams = z14.object({ nodeId: z14.string().min(1) });
|
|
6194
|
+
var MachineUpdate = z14.strictObject({ enabled: z14.boolean() });
|
|
5946
6195
|
function registerMachineSetup(args) {
|
|
5947
6196
|
args.app.register(async (app) => {
|
|
5948
6197
|
app.addHook("onRequest", async (request, reply) => {
|
|
@@ -5997,13 +6246,13 @@ function machineRoutes(args) {
|
|
|
5997
6246
|
operator: "/_work/operator/workers",
|
|
5998
6247
|
admin: "/api/work/machines/workers",
|
|
5999
6248
|
handler: async (request, reply) => {
|
|
6000
|
-
const body =
|
|
6001
|
-
name:
|
|
6002
|
-
ttlMinutes:
|
|
6003
|
-
labels:
|
|
6004
|
-
access:
|
|
6005
|
-
trusted:
|
|
6006
|
-
pool:
|
|
6249
|
+
const body = z14.strictObject({
|
|
6250
|
+
name: z14.string().min(1),
|
|
6251
|
+
ttlMinutes: z14.number().int().positive().max(1440).optional(),
|
|
6252
|
+
labels: z14.unknown().optional(),
|
|
6253
|
+
access: z14.unknown().optional(),
|
|
6254
|
+
trusted: z14.boolean().optional(),
|
|
6255
|
+
pool: z14.boolean().optional()
|
|
6007
6256
|
}).safeParse(request.body);
|
|
6008
6257
|
if (!body.success)
|
|
6009
6258
|
return reply.status(400).send({ error: firstIssue2(body.error) });
|
|
@@ -6057,11 +6306,11 @@ function machineRoutes(args) {
|
|
|
6057
6306
|
operator: "/_work/operator/workers/:name",
|
|
6058
6307
|
admin: "/api/work/machines/workers/:name",
|
|
6059
6308
|
handler: async (request, reply) => {
|
|
6060
|
-
const params =
|
|
6061
|
-
const body =
|
|
6062
|
-
labels:
|
|
6063
|
-
access:
|
|
6064
|
-
trusted:
|
|
6309
|
+
const params = z14.object({ name: z14.string().min(1) }).safeParse(request.params);
|
|
6310
|
+
const body = z14.strictObject({
|
|
6311
|
+
labels: z14.unknown().optional(),
|
|
6312
|
+
access: z14.unknown().optional(),
|
|
6313
|
+
trusted: z14.boolean().optional()
|
|
6065
6314
|
}).safeParse(request.body);
|
|
6066
6315
|
if (!params.success || !body.success)
|
|
6067
6316
|
return reply.status(400).send({ error: "Provide labels, access, or trusted" });
|
|
@@ -6082,7 +6331,7 @@ function machineRoutes(args) {
|
|
|
6082
6331
|
operator: "/_work/operator/workers/:name/rotate",
|
|
6083
6332
|
admin: "/api/work/machines/workers/:name/rotate",
|
|
6084
6333
|
handler: async (request, reply) => {
|
|
6085
|
-
const params =
|
|
6334
|
+
const params = z14.object({ name: z14.string().min(1) }).safeParse(request.params);
|
|
6086
6335
|
if (!params.success)
|
|
6087
6336
|
return reply.status(400).send({ error: "Provide a worker name" });
|
|
6088
6337
|
return await args.workers.requestRotation(params.data) ? { ok: true } : reply.status(404).send({ error: "Worker not found" });
|
|
@@ -6093,7 +6342,7 @@ function machineRoutes(args) {
|
|
|
6093
6342
|
operator: "/_work/operator/workers/:name",
|
|
6094
6343
|
admin: "/api/work/machines/workers/:name",
|
|
6095
6344
|
handler: async (request, reply) => {
|
|
6096
|
-
const params =
|
|
6345
|
+
const params = z14.object({ name: z14.string().min(1) }).safeParse(request.params);
|
|
6097
6346
|
if (!params.success)
|
|
6098
6347
|
return reply.status(400).send({ error: "Provide a worker name" });
|
|
6099
6348
|
return await args.workers.revoke(params.data) ? { ok: true } : reply.status(404).send({ error: "Worker not found" });
|
|
@@ -6113,7 +6362,7 @@ function machineRoutes(args) {
|
|
|
6113
6362
|
operator: "/_work/operator/machine-rules/:name",
|
|
6114
6363
|
admin: "/api/work/machines/rules/:name",
|
|
6115
6364
|
handler: (request, reply) => withRules(reply, async (machines) => {
|
|
6116
|
-
const { name } =
|
|
6365
|
+
const { name } = z14.object({ name: z14.string() }).parse(request.params);
|
|
6117
6366
|
const rule = await machines.setRule({ name, rule: request.body });
|
|
6118
6367
|
machines.reconcileSoon();
|
|
6119
6368
|
return { rule };
|
|
@@ -6124,7 +6373,7 @@ function machineRoutes(args) {
|
|
|
6124
6373
|
operator: "/_work/operator/machine-rules/:name",
|
|
6125
6374
|
admin: "/api/work/machines/rules/:name",
|
|
6126
6375
|
handler: (request, reply) => withRules(reply, async (machines) => {
|
|
6127
|
-
const { name } =
|
|
6376
|
+
const { name } = z14.object({ name: z14.string() }).parse(request.params);
|
|
6128
6377
|
if (!await machines.deleteRule(name))
|
|
6129
6378
|
return reply.status(404).send({ error: "Rule not found" });
|
|
6130
6379
|
machines.reconcileSoon();
|
|
@@ -6165,11 +6414,11 @@ function machineRoutes(args) {
|
|
|
6165
6414
|
method: "POST",
|
|
6166
6415
|
operator: "/_work/operator/machines/:nodeId/workspaces/:allocationId/confirm-destroyed",
|
|
6167
6416
|
handler: async (request, reply) => {
|
|
6168
|
-
const params =
|
|
6169
|
-
nodeId:
|
|
6170
|
-
allocationId:
|
|
6417
|
+
const params = z14.object({
|
|
6418
|
+
nodeId: z14.string().min(1),
|
|
6419
|
+
allocationId: z14.string().uuid()
|
|
6171
6420
|
}).safeParse(request.params);
|
|
6172
|
-
const body =
|
|
6421
|
+
const body = z14.strictObject({ confirmedDestroyed: z14.literal(true) }).safeParse(request.body);
|
|
6173
6422
|
if (!params.success || !body.success)
|
|
6174
6423
|
return reply.status(400).send({
|
|
6175
6424
|
error: "Inspect the physical backend and confirm this retired workspace was destroyed"
|
|
@@ -6204,7 +6453,7 @@ function machineRoutes(args) {
|
|
|
6204
6453
|
];
|
|
6205
6454
|
}
|
|
6206
6455
|
function errorMessage(error, fallback) {
|
|
6207
|
-
return error instanceof
|
|
6456
|
+
return error instanceof z14.ZodError ? firstIssue2(error) : error instanceof Error ? error.message : fallback;
|
|
6208
6457
|
}
|
|
6209
6458
|
function firstIssue2(error) {
|
|
6210
6459
|
const issue = error.issues[0];
|
|
@@ -6212,17 +6461,17 @@ function firstIssue2(error) {
|
|
|
6212
6461
|
}
|
|
6213
6462
|
|
|
6214
6463
|
// 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:
|
|
6464
|
+
import { z as z15 } from "zod";
|
|
6465
|
+
var ProvisionWorkUserInputSchema = z15.strictObject({
|
|
6466
|
+
username: z15.string().trim().min(3).max(30),
|
|
6467
|
+
name: z15.string().trim().min(1).max(200),
|
|
6468
|
+
password: z15.string().min(8).max(128),
|
|
6469
|
+
email: z15.email().optional(),
|
|
6470
|
+
administrator: z15.boolean().optional(),
|
|
6471
|
+
memberships: z15.array(z15.strictObject({
|
|
6472
|
+
projectId: z15.string().min(1),
|
|
6473
|
+
roles: z15.array(z15.string().min(1)).min(1),
|
|
6474
|
+
grants: z15.record(z15.string(), z15.array(z15.string())).optional()
|
|
6226
6475
|
})).optional()
|
|
6227
6476
|
});
|
|
6228
6477
|
async function provisionWorkUser(args) {
|
|
@@ -6247,11 +6496,11 @@ async function provisionWorkUser(args) {
|
|
|
6247
6496
|
})));
|
|
6248
6497
|
return { user, memberships };
|
|
6249
6498
|
}
|
|
6250
|
-
var GrantWorkMembershipInputSchema =
|
|
6251
|
-
email:
|
|
6252
|
-
projectId:
|
|
6253
|
-
roles:
|
|
6254
|
-
grants:
|
|
6499
|
+
var GrantWorkMembershipInputSchema = z15.strictObject({
|
|
6500
|
+
email: z15.email(),
|
|
6501
|
+
projectId: z15.string().min(1),
|
|
6502
|
+
roles: z15.array(z15.string().min(1)).min(1),
|
|
6503
|
+
grants: z15.record(z15.string(), z15.array(z15.string())).optional()
|
|
6255
6504
|
});
|
|
6256
6505
|
async function grantWorkMembership(args) {
|
|
6257
6506
|
await assertCommittedRoles({
|
|
@@ -6289,23 +6538,23 @@ import {
|
|
|
6289
6538
|
RoleDefinitionSchema
|
|
6290
6539
|
} from "@catamorphic/core";
|
|
6291
6540
|
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:
|
|
6541
|
+
import { z as z16 } from "zod";
|
|
6542
|
+
var RoleSlugSchema = z16.string().min(1).max(100).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
|
|
6543
|
+
var ProvisionWorkProjectInputSchema = z16.strictObject({
|
|
6544
|
+
name: z16.string().trim().min(1).max(200),
|
|
6545
|
+
repository: z16.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).optional(),
|
|
6546
|
+
codeHost: z16.string().regex(/^[a-z0-9][a-z0-9._-]*$/).default("github"),
|
|
6547
|
+
roles: z16.array(z16.strictObject({
|
|
6299
6548
|
slug: RoleSlugSchema,
|
|
6300
6549
|
definition: RoleDefinitionSchema
|
|
6301
6550
|
})).min(1).optional(),
|
|
6302
|
-
admission:
|
|
6303
|
-
mode:
|
|
6551
|
+
admission: z16.strictObject({
|
|
6552
|
+
mode: z16.enum(["invitation_only", "approved_domain", "request", "open"]),
|
|
6304
6553
|
defaultRole: RoleSlugSchema,
|
|
6305
|
-
approvedDomains:
|
|
6306
|
-
directoryRoles:
|
|
6307
|
-
group:
|
|
6308
|
-
roles:
|
|
6554
|
+
approvedDomains: z16.array(z16.string().trim().min(1)).default([]),
|
|
6555
|
+
directoryRoles: z16.array(z16.strictObject({
|
|
6556
|
+
group: z16.string().trim().toLowerCase().min(3),
|
|
6557
|
+
roles: z16.array(RoleSlugSchema).min(1)
|
|
6309
6558
|
})).default([])
|
|
6310
6559
|
})
|
|
6311
6560
|
}).superRefine((input, context) => {
|
|
@@ -6426,7 +6675,7 @@ async function provisionWorkProject(args) {
|
|
|
6426
6675
|
import { randomBytes as randomBytes8 } from "node:crypto";
|
|
6427
6676
|
import { appGuestCsp, buildAppGuestDocument } from "@catamorphic/app";
|
|
6428
6677
|
import { micromark } from "micromark";
|
|
6429
|
-
import { z as
|
|
6678
|
+
import { z as z18 } from "zod";
|
|
6430
6679
|
|
|
6431
6680
|
// src/shares/shares-service.ts
|
|
6432
6681
|
import { randomBytes as randomBytes7 } from "node:crypto";
|
|
@@ -6435,18 +6684,18 @@ import {
|
|
|
6435
6684
|
identityMayUseEnvironment,
|
|
6436
6685
|
normalizeDocumentPath
|
|
6437
6686
|
} 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:
|
|
6687
|
+
import { sql as sql6 } from "kysely";
|
|
6688
|
+
import { z as z17 } from "zod";
|
|
6689
|
+
var CreateShareSchema = z17.strictObject({
|
|
6690
|
+
kind: z17.enum(["document", "folder", "app"]),
|
|
6691
|
+
target: z17.string().trim().min(1).max(512),
|
|
6692
|
+
environment: z17.string().trim().min(1).optional(),
|
|
6693
|
+
title: z17.string().trim().min(1).max(200).optional(),
|
|
6694
|
+
audience: z17.strictObject({
|
|
6695
|
+
emails: z17.array(z17.email().toLowerCase()).max(200).default([]),
|
|
6696
|
+
domains: z17.array(z17.string().trim().toLowerCase().regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/)).max(50).default([])
|
|
6448
6697
|
}).refine((audience) => audience.emails.length + audience.domains.length > 0, "Name at least one email or domain"),
|
|
6449
|
-
expiresAt:
|
|
6698
|
+
expiresAt: z17.iso.datetime().optional()
|
|
6450
6699
|
});
|
|
6451
6700
|
|
|
6452
6701
|
class ShareAccessError extends Error {
|
|
@@ -6501,7 +6750,7 @@ class WorkSharesService {
|
|
|
6501
6750
|
if (!hasProjectPermission3(args.identity, args.projectId, "publications:write")) {
|
|
6502
6751
|
throw new ShareAccessError("Revoking shares needs publications:write");
|
|
6503
6752
|
}
|
|
6504
|
-
const row = await this.deps.db.updateTable("work_shares").set({ revoked_at:
|
|
6753
|
+
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
6754
|
return Boolean(row);
|
|
6506
6755
|
}
|
|
6507
6756
|
async isGuest(userId) {
|
|
@@ -6514,7 +6763,7 @@ class WorkSharesService {
|
|
|
6514
6763
|
async open(args) {
|
|
6515
6764
|
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
6765
|
eb("work_shares.expires_at", "is", null),
|
|
6517
|
-
eb("work_shares.expires_at", ">",
|
|
6766
|
+
eb("work_shares.expires_at", ">", sql6`now()`)
|
|
6518
6767
|
])).executeTakeFirst();
|
|
6519
6768
|
if (!row)
|
|
6520
6769
|
return null;
|
|
@@ -6624,10 +6873,10 @@ class WorkSharesService {
|
|
|
6624
6873
|
}
|
|
6625
6874
|
|
|
6626
6875
|
// src/shares/share-routes.ts
|
|
6627
|
-
var CallSchema =
|
|
6628
|
-
workflowName:
|
|
6629
|
-
mode:
|
|
6630
|
-
input:
|
|
6876
|
+
var CallSchema = z18.strictObject({
|
|
6877
|
+
workflowName: z18.string().min(1).max(200),
|
|
6878
|
+
mode: z18.enum(["invoke", "start"]),
|
|
6879
|
+
input: z18.json()
|
|
6631
6880
|
});
|
|
6632
6881
|
function registerShareRoutes(app, options) {
|
|
6633
6882
|
const { core, shares } = options;
|
|
@@ -6874,7 +7123,7 @@ function registerShareRoutes(app, options) {
|
|
|
6874
7123
|
const context = await appContext(request, reply);
|
|
6875
7124
|
if (!context)
|
|
6876
7125
|
return reply;
|
|
6877
|
-
const data =
|
|
7126
|
+
const data = z18.record(z18.string(), z18.string()).safeParse(request.body?.data);
|
|
6878
7127
|
if (!data.success)
|
|
6879
7128
|
return reply.status(400).send();
|
|
6880
7129
|
await core.appStorage.put(context.identity, context.share.projectId, context.share.target, data.data).catch(() => {
|
|
@@ -6992,7 +7241,7 @@ function escapeHtml3(value) {
|
|
|
6992
7241
|
}
|
|
6993
7242
|
|
|
6994
7243
|
// src/shares/share-tools.ts
|
|
6995
|
-
import { z as
|
|
7244
|
+
import { z as z19 } from "zod";
|
|
6996
7245
|
function shareTools(shares, args) {
|
|
6997
7246
|
const { identity, projectId } = args;
|
|
6998
7247
|
return [
|
|
@@ -7000,7 +7249,7 @@ function shareTools(shares, args) {
|
|
|
7000
7249
|
definition: {
|
|
7001
7250
|
name: "share_create",
|
|
7002
7251
|
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:
|
|
7252
|
+
inputSchema: z19.toJSONSchema(CreateShareSchema, { io: "input" })
|
|
7004
7253
|
},
|
|
7005
7254
|
call: async (input) => shares.create({
|
|
7006
7255
|
identity,
|
|
@@ -7041,23 +7290,23 @@ function shareTools(shares, args) {
|
|
|
7041
7290
|
|
|
7042
7291
|
// src/workers/codex-sign-ins.ts
|
|
7043
7292
|
import { spawn } from "node:child_process";
|
|
7044
|
-
import { randomUUID as
|
|
7293
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
7045
7294
|
import fs11 from "node:fs";
|
|
7046
7295
|
import path8 from "node:path";
|
|
7047
|
-
import { z as
|
|
7048
|
-
var CodexSignInStartedSchema =
|
|
7049
|
-
attempt:
|
|
7050
|
-
verificationUrl:
|
|
7051
|
-
userCode:
|
|
7052
|
-
expiresAt:
|
|
7296
|
+
import { z as z20 } from "zod";
|
|
7297
|
+
var CodexSignInStartedSchema = z20.strictObject({
|
|
7298
|
+
attempt: z20.string().uuid(),
|
|
7299
|
+
verificationUrl: z20.string().url(),
|
|
7300
|
+
userCode: z20.string().min(1).max(32),
|
|
7301
|
+
expiresAt: z20.string().datetime()
|
|
7053
7302
|
});
|
|
7054
|
-
var CodexSignInStatusSchema =
|
|
7055
|
-
state:
|
|
7056
|
-
message:
|
|
7303
|
+
var CodexSignInStatusSchema = z20.strictObject({
|
|
7304
|
+
state: z20.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
|
|
7305
|
+
message: z20.string().max(400).optional()
|
|
7057
7306
|
});
|
|
7058
|
-
var CodexSignedOutSchema =
|
|
7059
|
-
var CodexSignInRefusedSchema =
|
|
7060
|
-
refused:
|
|
7307
|
+
var CodexSignedOutSchema = z20.strictObject({ signedOut: z20.boolean() });
|
|
7308
|
+
var CodexSignInRefusedSchema = z20.strictObject({
|
|
7309
|
+
refused: z20.string().min(1).max(400)
|
|
7061
7310
|
});
|
|
7062
7311
|
var CODE_TIMEOUT_MS = 30000;
|
|
7063
7312
|
var DEFAULT_CODE_MINUTES = 15;
|
|
@@ -7156,7 +7405,7 @@ class CodexSignIns {
|
|
|
7156
7405
|
},
|
|
7157
7406
|
stdio: ["ignore", "pipe", "pipe"]
|
|
7158
7407
|
});
|
|
7159
|
-
const id =
|
|
7408
|
+
const id = randomUUID5();
|
|
7160
7409
|
let output = "";
|
|
7161
7410
|
return new Promise((resolve, reject) => {
|
|
7162
7411
|
let settled = false;
|
|
@@ -7283,7 +7532,7 @@ class CodexSignIns {
|
|
|
7283
7532
|
function installTarget(args) {
|
|
7284
7533
|
if (!args.workerImage)
|
|
7285
7534
|
return {
|
|
7286
|
-
unavailable: "This server does not know which worker image machines should run. Set WORK_WORKER_IMAGE to
|
|
7535
|
+
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
7536
|
};
|
|
7288
7537
|
if (isLoopback2(args.publicBase))
|
|
7289
7538
|
return {
|
|
@@ -7325,7 +7574,7 @@ usage() {
|
|
|
7325
7574
|
Usage: install.sh --code <code> [--image <image>] [--data-dir <dir>] [--name <name>] [--sandbox <backend>]
|
|
7326
7575
|
|
|
7327
7576
|
--code <code> the one-time enrollment code from the Work server (required)
|
|
7328
|
-
--image <image> the worker image (default:
|
|
7577
|
+
--image <image> the worker image (default: the deployment's configured worker image)
|
|
7329
7578
|
--data-dir <dir> where the worker keeps its credential, sandboxes and
|
|
7330
7579
|
members' sign-ins (default: ${DEFAULT_WORKER_DATA_DIR}): a new
|
|
7331
7580
|
directory, or one under /var/lib, /srv, /opt, /data or
|
|
@@ -7594,7 +7843,7 @@ function isLoopback2(base) {
|
|
|
7594
7843
|
}
|
|
7595
7844
|
|
|
7596
7845
|
// src/workers/machine-rules.ts
|
|
7597
|
-
import { createHash as
|
|
7846
|
+
import { createHash as createHash8, randomUUID as randomUUID6 } from "node:crypto";
|
|
7598
7847
|
import {
|
|
7599
7848
|
PLACEMENT_WAIT_FRESH_SECONDS,
|
|
7600
7849
|
releaseReplicaClaim,
|
|
@@ -7606,35 +7855,35 @@ import {
|
|
|
7606
7855
|
} from "@catamorphic/hetzner";
|
|
7607
7856
|
import { getTracer as getTracer2, withSpan as withSpan2 } from "@catamorphic/otel";
|
|
7608
7857
|
import { environmentSatisfies as environmentSatisfies2, poolMatches as poolMatches2 } from "@catamorphic/sandbox";
|
|
7609
|
-
import { sql as
|
|
7610
|
-
import { z as
|
|
7858
|
+
import { sql as sql7 } from "kysely";
|
|
7859
|
+
import { z as z21 } from "zod";
|
|
7611
7860
|
var tracer2 = getTracer2("@catamorphic/work-server");
|
|
7612
7861
|
var DEFAULT_RETAIN_DAYS = 7;
|
|
7613
7862
|
var DEFAULT_IDLE_MINUTES = 10;
|
|
7614
7863
|
var DEFAULT_ENROLL_MINUTES = 15;
|
|
7615
7864
|
var DAY_MS = 24 * 60 * 60000;
|
|
7616
|
-
var DemandSchema =
|
|
7617
|
-
max:
|
|
7618
|
-
min:
|
|
7619
|
-
idleMinutes:
|
|
7620
|
-
enrollMinutes:
|
|
7865
|
+
var DemandSchema = z21.strictObject({
|
|
7866
|
+
max: z21.number().int().positive().max(100),
|
|
7867
|
+
min: z21.number().int().min(0).max(100).default(0),
|
|
7868
|
+
idleMinutes: z21.number().int().min(1).max(24 * 60).default(DEFAULT_IDLE_MINUTES),
|
|
7869
|
+
enrollMinutes: z21.number().int().positive().max(24 * 60).default(DEFAULT_ENROLL_MINUTES)
|
|
7621
7870
|
}).refine((demand) => demand.min <= demand.max, {
|
|
7622
7871
|
message: "min may not be more than max",
|
|
7623
7872
|
path: ["min"]
|
|
7624
7873
|
});
|
|
7625
|
-
var RuleMachinesSchema =
|
|
7626
|
-
|
|
7627
|
-
|
|
7628
|
-
|
|
7874
|
+
var RuleMachinesSchema = z21.union([
|
|
7875
|
+
z21.literal("each-member"),
|
|
7876
|
+
z21.strictObject({ shared: z21.number().int().positive().max(100) }),
|
|
7877
|
+
z21.strictObject({ demand: DemandSchema })
|
|
7629
7878
|
]);
|
|
7630
|
-
var MachineRuleSchema =
|
|
7631
|
-
group:
|
|
7632
|
-
projects:
|
|
7879
|
+
var MachineRuleSchema = z21.strictObject({
|
|
7880
|
+
group: z21.email().toLowerCase().optional(),
|
|
7881
|
+
projects: z21.array(z21.uuid()).min(1).max(100).optional(),
|
|
7633
7882
|
machines: RuleMachinesSchema,
|
|
7634
|
-
class:
|
|
7883
|
+
class: z21.string().min(1).max(64),
|
|
7635
7884
|
labels: NodeLabelsSchema.default({}),
|
|
7636
|
-
trusted:
|
|
7637
|
-
retainDays:
|
|
7885
|
+
trusted: z21.boolean().default(false),
|
|
7886
|
+
retainDays: z21.number().int().min(0).max(365).optional()
|
|
7638
7887
|
}).superRefine((rule, context) => {
|
|
7639
7888
|
const demand = demandOf(rule) !== undefined;
|
|
7640
7889
|
if (rule.group === undefined === (rule.projects === undefined))
|
|
@@ -7669,25 +7918,25 @@ class MachineProvisioningRefusedError extends Error {
|
|
|
7669
7918
|
this.name = "MachineProvisioningRefusedError";
|
|
7670
7919
|
}
|
|
7671
7920
|
}
|
|
7672
|
-
var DemandWaitPool =
|
|
7673
|
-
var DemandWaitRequirements =
|
|
7674
|
-
resources:
|
|
7675
|
-
cpuMillis:
|
|
7676
|
-
memoryMb:
|
|
7677
|
-
storageMb:
|
|
7678
|
-
gpu:
|
|
7921
|
+
var DemandWaitPool = z21.record(z21.string(), z21.string());
|
|
7922
|
+
var DemandWaitRequirements = z21.object({
|
|
7923
|
+
resources: z21.object({
|
|
7924
|
+
cpuMillis: z21.number().optional(),
|
|
7925
|
+
memoryMb: z21.number().optional(),
|
|
7926
|
+
storageMb: z21.number().optional(),
|
|
7927
|
+
gpu: z21.boolean().optional()
|
|
7679
7928
|
}).default({}),
|
|
7680
|
-
capabilities:
|
|
7681
|
-
trust:
|
|
7682
|
-
isolation:
|
|
7683
|
-
topology:
|
|
7929
|
+
capabilities: z21.array(z21.string()).default([]),
|
|
7930
|
+
trust: z21.enum(["local", "managed"]).optional(),
|
|
7931
|
+
isolation: z21.enum(["none", "process", "sandbox"]).optional(),
|
|
7932
|
+
topology: z21.enum(["controller", "contained", "native", "external"]).optional()
|
|
7684
7933
|
});
|
|
7685
7934
|
var HETZNER_REF = "hcloud:";
|
|
7686
7935
|
|
|
7687
7936
|
class MachineReconciler {
|
|
7688
7937
|
deps;
|
|
7689
7938
|
running;
|
|
7690
|
-
holder =
|
|
7939
|
+
holder = randomUUID6();
|
|
7691
7940
|
constructor(deps) {
|
|
7692
7941
|
this.deps = deps;
|
|
7693
7942
|
}
|
|
@@ -7713,7 +7962,7 @@ class MachineReconciler {
|
|
|
7713
7962
|
definition: JSON.stringify(rule)
|
|
7714
7963
|
}).onConflict((oc) => oc.columns(["tenant_id", "name"]).doUpdateSet({
|
|
7715
7964
|
definition: JSON.stringify(rule),
|
|
7716
|
-
updated_at:
|
|
7965
|
+
updated_at: sql7`now()`
|
|
7717
7966
|
})).execute();
|
|
7718
7967
|
return rule;
|
|
7719
7968
|
}
|
|
@@ -7871,7 +8120,7 @@ class MachineReconciler {
|
|
|
7871
8120
|
await this.deps.db.updateTable("work_machine_rules").set(failures.length > 0 ? {
|
|
7872
8121
|
last_failure: failures.map((failure) => failure.name === rule ? failure.error : `${failure.name}: ${failure.error}`).join(`
|
|
7873
8122
|
`).slice(0, 4000),
|
|
7874
|
-
last_failure_at:
|
|
8123
|
+
last_failure_at: sql7`now()`
|
|
7875
8124
|
} : { last_failure: null, last_failure_at: null }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", rule).execute();
|
|
7876
8125
|
}
|
|
7877
8126
|
}
|
|
@@ -8172,7 +8421,7 @@ class MachineReconciler {
|
|
|
8172
8421
|
async provision(args) {
|
|
8173
8422
|
const { machine, code } = args;
|
|
8174
8423
|
const machineClass = this.classOf(machine.class);
|
|
8175
|
-
const idempotencyKey =
|
|
8424
|
+
const idempotencyKey = createHash8("sha256").update(code).digest("hex");
|
|
8176
8425
|
const cloudInit = "target" in this.deps.install ? workerCloudInit({
|
|
8177
8426
|
script: workerInstallScript(this.deps.install.target),
|
|
8178
8427
|
code,
|
|
@@ -8252,7 +8501,7 @@ class MachineReconciler {
|
|
|
8252
8501
|
return (demand?.enrollMinutes ?? DEFAULT_ENROLL_MINUTES) * 60000;
|
|
8253
8502
|
}
|
|
8254
8503
|
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(
|
|
8504
|
+
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
8505
|
return Boolean(row);
|
|
8257
8506
|
}
|
|
8258
8507
|
classOf(name) {
|
|
@@ -8396,13 +8645,13 @@ class MachineReconciler {
|
|
|
8396
8645
|
"placement_waits.requirements",
|
|
8397
8646
|
"work_accounts.directory_groups",
|
|
8398
8647
|
"work_accounts.disabled_at"
|
|
8399
|
-
]).where("placement_waits.tenant_id", "=", this.deps.tenantId).where("placement_waits.last_tried_at", ">", waitFresh()).where((
|
|
8648
|
+
]).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
8649
|
this.deps.workers.machines(),
|
|
8401
8650
|
this.deps.workers.machineLoad(),
|
|
8402
8651
|
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
8652
|
"work_workers.machine_rule",
|
|
8404
8653
|
"work_workers.name",
|
|
8405
|
-
|
|
8654
|
+
sql7`(extract(epoch from (now() - work_workers.enrolled_at)) * 1000)::float8`.as("enrolled_for_ms")
|
|
8406
8655
|
]).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
8656
|
]);
|
|
8408
8657
|
const waits = [];
|
|
@@ -8441,16 +8690,16 @@ class MachineReconciler {
|
|
|
8441
8690
|
demandSeen;
|
|
8442
8691
|
async demandSignature() {
|
|
8443
8692
|
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(
|
|
8693
|
+
eb.exists(eb.selectFrom("work_machine_rules").select("name").where("tenant_id", "=", this.deps.tenantId).where(sql7`definition -> 'machines' ? 'demand'`)).as("demand"),
|
|
8694
|
+
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"),
|
|
8695
|
+
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
8696
|
]).executeTakeFirst();
|
|
8448
8697
|
if (!row?.demand)
|
|
8449
8698
|
return;
|
|
8450
8699
|
return `${row.waits ?? ""}|${row.work ?? ""}`;
|
|
8451
8700
|
}
|
|
8452
8701
|
async members(group) {
|
|
8453
|
-
const rows = await this.deps.db.selectFrom("work_accounts").select("user_id").where("disabled_at", "is", null).where(
|
|
8702
|
+
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
8703
|
const members = [];
|
|
8455
8704
|
for (const row of rows) {
|
|
8456
8705
|
const email = await this.deps.emailOf(row.user_id);
|
|
@@ -8501,7 +8750,7 @@ function demandWaitMatches(rule, wait) {
|
|
|
8501
8750
|
return wait.owner !== null && rule.group !== undefined && wait.groups.includes(rule.group);
|
|
8502
8751
|
}
|
|
8503
8752
|
function waitFresh() {
|
|
8504
|
-
return
|
|
8753
|
+
return sql7`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
|
|
8505
8754
|
}
|
|
8506
8755
|
function servesSeveral(rule) {
|
|
8507
8756
|
return rule.group !== undefined || (rule.projects?.length ?? 0) > 1;
|
|
@@ -8636,7 +8885,7 @@ function demandMachines(args) {
|
|
|
8636
8885
|
return machines;
|
|
8637
8886
|
}
|
|
8638
8887
|
function digest(value, length) {
|
|
8639
|
-
return
|
|
8888
|
+
return createHash8("sha256").update(value).digest("hex").slice(0, length);
|
|
8640
8889
|
}
|
|
8641
8890
|
function message(error) {
|
|
8642
8891
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -8644,10 +8893,16 @@ function message(error) {
|
|
|
8644
8893
|
function canonical(value) {
|
|
8645
8894
|
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
8895
|
}
|
|
8896
|
+
function queuedPlacementWait(db) {
|
|
8897
|
+
const turns = db.selectFrom("agent_turns").select("id").where("session_id", "=", sql7`placement_waits.root_workload_id`).where("status", "=", "queued");
|
|
8898
|
+
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()`);
|
|
8899
|
+
return sql7`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
|
|
8900
|
+
(placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})))`;
|
|
8901
|
+
}
|
|
8647
8902
|
|
|
8648
8903
|
// src/workers/member-machine-routes.ts
|
|
8649
8904
|
import { ExecutorNotConnectedError } from "@catamorphic/core";
|
|
8650
|
-
import { z as
|
|
8905
|
+
import { z as z23 } from "zod";
|
|
8651
8906
|
|
|
8652
8907
|
// src/workers/member-machines.ts
|
|
8653
8908
|
import {
|
|
@@ -8656,7 +8911,7 @@ import {
|
|
|
8656
8911
|
parseSignInCapability,
|
|
8657
8912
|
signInCapability as signInCapability2
|
|
8658
8913
|
} from "@catamorphic/sandbox";
|
|
8659
|
-
import { z as
|
|
8914
|
+
import { z as z22 } from "zod";
|
|
8660
8915
|
class NotYourMachineError extends Error {
|
|
8661
8916
|
constructor() {
|
|
8662
8917
|
super("This is not a machine of your own, so your Codex sign-in cannot go on it");
|
|
@@ -8681,7 +8936,7 @@ class MemberMachines {
|
|
|
8681
8936
|
}));
|
|
8682
8937
|
}
|
|
8683
8938
|
async begin(args) {
|
|
8684
|
-
const answer =
|
|
8939
|
+
const answer = z22.union([CodexSignInStartedSchema, CodexSignInRefusedSchema]).parse(await this.send(args, {
|
|
8685
8940
|
action: "begin",
|
|
8686
8941
|
member: args.identity.externalUserId
|
|
8687
8942
|
}));
|
|
@@ -8753,8 +9008,8 @@ class MemberMachines {
|
|
|
8753
9008
|
|
|
8754
9009
|
// src/workers/member-machine-routes.ts
|
|
8755
9010
|
function registerMemberMachineRoutes(app, options) {
|
|
8756
|
-
const machineParams =
|
|
8757
|
-
const attemptParams = machineParams.extend({ attempt:
|
|
9011
|
+
const machineParams = z23.object({ id: z23.string().min(1).max(200) });
|
|
9012
|
+
const attemptParams = machineParams.extend({ attempt: z23.string().uuid() });
|
|
8758
9013
|
const member = async (request, reply) => {
|
|
8759
9014
|
const identity = await options.caller(request);
|
|
8760
9015
|
if (!identity) {
|
|
@@ -8869,7 +9124,7 @@ import {
|
|
|
8869
9124
|
RemoteReceiptRefusedError
|
|
8870
9125
|
} from "@catamorphic/core";
|
|
8871
9126
|
import { ExecutorPublicKeySchema as ExecutorPublicKeySchema2 } from "@catamorphic/sandbox";
|
|
8872
|
-
import { z as
|
|
9127
|
+
import { z as z24 } from "zod";
|
|
8873
9128
|
|
|
8874
9129
|
// src/workers/worker-protocol.ts
|
|
8875
9130
|
var WORKER_PROTOCOL_HEADER = "work-protocol";
|
|
@@ -8895,16 +9150,16 @@ function upgradeMessage(input) {
|
|
|
8895
9150
|
}
|
|
8896
9151
|
|
|
8897
9152
|
// src/workers/worker-routes.ts
|
|
8898
|
-
var Session =
|
|
9153
|
+
var Session = z24.strictObject({ session: z24.string().uuid() });
|
|
8899
9154
|
var Poll = Session.extend({
|
|
8900
|
-
pollId:
|
|
8901
|
-
max:
|
|
9155
|
+
pollId: z24.string().uuid(),
|
|
9156
|
+
max: z24.number().int().min(1).max(64).default(1)
|
|
8902
9157
|
});
|
|
8903
|
-
var Completion =
|
|
8904
|
-
session:
|
|
8905
|
-
jobId:
|
|
8906
|
-
response:
|
|
8907
|
-
error:
|
|
9158
|
+
var Completion = z24.strictObject({
|
|
9159
|
+
session: z24.string().uuid(),
|
|
9160
|
+
jobId: z24.string().uuid(),
|
|
9161
|
+
response: z24.unknown().optional(),
|
|
9162
|
+
error: z24.string().max(1e4).optional()
|
|
8908
9163
|
});
|
|
8909
9164
|
function registerWorkerRoutes(app, registry) {
|
|
8910
9165
|
const authenticated = async (request, reply) => {
|
|
@@ -8921,8 +9176,8 @@ function registerWorkerRoutes(app, registry) {
|
|
|
8921
9176
|
app.post("/api/workers/enroll", async (request, reply) => {
|
|
8922
9177
|
if (await refusedProtocol(request, reply))
|
|
8923
9178
|
return reply;
|
|
8924
|
-
const body =
|
|
8925
|
-
code:
|
|
9179
|
+
const body = z24.strictObject({
|
|
9180
|
+
code: z24.string().min(10),
|
|
8926
9181
|
publicKey: ExecutorPublicKeySchema2
|
|
8927
9182
|
}).safeParse(request.body);
|
|
8928
9183
|
if (!body.success) {
|
|
@@ -8969,9 +9224,9 @@ function registerWorkerRoutes(app, registry) {
|
|
|
8969
9224
|
const worker = await authenticated(request, reply);
|
|
8970
9225
|
if (!worker)
|
|
8971
9226
|
return reply;
|
|
8972
|
-
const body =
|
|
9227
|
+
const body = z24.strictObject({
|
|
8973
9228
|
publicKey: ExecutorPublicKeySchema2,
|
|
8974
|
-
rotation:
|
|
9229
|
+
rotation: z24.string().regex(REMOTE_EPOCH_PATTERN2, "Use a UUIDv7 rotation id")
|
|
8975
9230
|
}).safeParse(request.body);
|
|
8976
9231
|
if (!body.success)
|
|
8977
9232
|
return reply.status(400).send({ error: "Provide the new public key and a rotation id" });
|
|
@@ -9131,7 +9386,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9131
9386
|
}
|
|
9132
9387
|
const disposable = Boolean(config.databaseUrl);
|
|
9133
9388
|
const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path9.join(data, "host-id"));
|
|
9134
|
-
const nodeId = disposable ? `node.${
|
|
9389
|
+
const nodeId = disposable ? `node.${randomUUID7()}` : `node.${createHash9("sha256").update(hostId).digest("hex").slice(0, 24)}`;
|
|
9135
9390
|
const authSecret = loadWorkAuthSecret({
|
|
9136
9391
|
dataDir: data,
|
|
9137
9392
|
...config.secret ? { configuredSecret: config.secret } : {}
|
|
@@ -9151,12 +9406,12 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9151
9406
|
const pglite = new PGlite2(path9.join(data, "db"), {
|
|
9152
9407
|
extensions: { pgcrypto }
|
|
9153
9408
|
});
|
|
9154
|
-
ownDb = withStorableParameters(new
|
|
9409
|
+
ownDb = withStorableParameters(new Kysely2({
|
|
9155
9410
|
dialect: new PGliteDialect2({ pglite }),
|
|
9156
9411
|
plugins: [new WithSchemaPlugin(DEFAULT_SCHEMA)]
|
|
9157
9412
|
}));
|
|
9158
9413
|
disposers.push(() => ownDb.destroy());
|
|
9159
|
-
await
|
|
9414
|
+
await sql8.raw(`SET search_path TO "${DEFAULT_SCHEMA}", public`).execute(ownDb);
|
|
9160
9415
|
databaseConfig = { db: ownDb };
|
|
9161
9416
|
}
|
|
9162
9417
|
const agentsHere = config.execution.workloads.includes("agent") && !config.execution.trustControlPlaneAgents;
|
|
@@ -9192,7 +9447,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9192
9447
|
const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path9.join(data, "credentials"), vaultKeys);
|
|
9193
9448
|
if (objectStore) {
|
|
9194
9449
|
const key = "work/deployment-fingerprint";
|
|
9195
|
-
const fingerprint =
|
|
9450
|
+
const fingerprint = createHash9("sha256").update(publicBase).update("\x00").update(authSecret).update("\x00").update(JSON.stringify({
|
|
9196
9451
|
local: workAuthConfig.local,
|
|
9197
9452
|
providers: workAuthConfig.providers,
|
|
9198
9453
|
sessions: workAuthConfig.sessions,
|
|
@@ -9205,7 +9460,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9205
9460
|
}
|
|
9206
9461
|
});
|
|
9207
9462
|
const keysRecord = "work/vault-key-ids";
|
|
9208
|
-
const known = await objectStore.get(keysRecord).then((record) => record ?
|
|
9463
|
+
const known = await objectStore.get(keysRecord).then((record) => record ? z25.array(z25.string()).parse(JSON.parse(Buffer.from(record.data).toString())) : []);
|
|
9209
9464
|
const ids = credentialVault.keyIds;
|
|
9210
9465
|
if (known.length > 0 && !ids.some((id) => known.includes(id))) {
|
|
9211
9466
|
throw new Error("WORK_VAULT_KEY and WORK_VAULT_PREVIOUS_KEYS share no key with this Postgres deployment");
|
|
@@ -9269,6 +9524,7 @@ async function createWorkServerInner(options, disposers, close) {
|
|
|
9269
9524
|
disposers.push(() => Promise.all(gatewayConnectionProviders.map((provider) => provider.close?.())));
|
|
9270
9525
|
const catamorphic = createCatamorphic({
|
|
9271
9526
|
hostId,
|
|
9527
|
+
...hooks.capabilityProviders ? { capabilityProviders: hooks.capabilityProviders } : {},
|
|
9272
9528
|
agentCapabilities: workAgentCapabilities({
|
|
9273
9529
|
core: () => catamorphic.core,
|
|
9274
9530
|
auth: () => workAuth,
|
|
@@ -9889,7 +10145,7 @@ function loadOrCreateHostId(file) {
|
|
|
9889
10145
|
if (existing)
|
|
9890
10146
|
return existing;
|
|
9891
10147
|
} catch {}
|
|
9892
|
-
const hostId = `server:${
|
|
10148
|
+
const hostId = `server:${randomUUID7()}`;
|
|
9893
10149
|
fs12.writeFileSync(file, `${hostId}
|
|
9894
10150
|
`, { mode: 384 });
|
|
9895
10151
|
return hostId;
|
|
@@ -9928,14 +10184,14 @@ import {
|
|
|
9928
10184
|
// src/workers/worker-identity.ts
|
|
9929
10185
|
import fs13 from "node:fs";
|
|
9930
10186
|
import path10 from "node:path";
|
|
9931
|
-
import { z as
|
|
10187
|
+
import { z as z26 } from "zod";
|
|
9932
10188
|
var CREDENTIAL_FILE = "worker-credential";
|
|
9933
10189
|
var KEY_FILE = "worker-key";
|
|
9934
10190
|
var PREVIOUS_FILE = "worker-identity.previous";
|
|
9935
10191
|
var NEXT_FILE = "worker-identity.next";
|
|
9936
|
-
var PairSchema =
|
|
9937
|
-
credential:
|
|
9938
|
-
privateKey:
|
|
10192
|
+
var PairSchema = z26.strictObject({
|
|
10193
|
+
credential: z26.string().min(1),
|
|
10194
|
+
privateKey: z26.string().min(1)
|
|
9939
10195
|
});
|
|
9940
10196
|
var NextIdentitySchema = PairSchema.extend({
|
|
9941
10197
|
previous: PairSchema.optional()
|
|
@@ -10541,6 +10797,7 @@ export {
|
|
|
10541
10797
|
WorkAuthConfigSchema,
|
|
10542
10798
|
WorkerUpgradeRequiredError,
|
|
10543
10799
|
createWorkServer,
|
|
10800
|
+
defineCapability,
|
|
10544
10801
|
defineGitConnectionProvider2 as defineGitConnectionProvider,
|
|
10545
10802
|
defineHttpApiConnectionProvider2 as defineHttpApiConnectionProvider,
|
|
10546
10803
|
defineModelConnectionProvider2 as defineModelConnectionProvider,
|
|
@@ -10558,5 +10815,5 @@ export {
|
|
|
10558
10815
|
workServerConfigFromEnv
|
|
10559
10816
|
};
|
|
10560
10817
|
|
|
10561
|
-
//# debugId=
|
|
10818
|
+
//# debugId=DC1A8906FB3873F164756E2164756E21
|
|
10562
10819
|
//# sourceMappingURL=index.js.map
|