@leitwerk-dev/server 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/app-2TCRADVA.js +8 -0
  2. package/dist/app.d.ts.map +1 -1
  3. package/dist/auth/api-token-routes.d.ts.map +1 -1
  4. package/dist/auth/api-token-service.d.ts +4 -4
  5. package/dist/auth/api-token-service.d.ts.map +1 -1
  6. package/dist/auth/auth-client.d.ts +18 -11
  7. package/dist/auth/auth-client.d.ts.map +1 -1
  8. package/dist/auth/auth-service.d.ts +8 -10
  9. package/dist/auth/auth-service.d.ts.map +1 -1
  10. package/dist/auth/auth-test-helpers.d.ts +12 -5
  11. package/dist/auth/auth-test-helpers.d.ts.map +1 -1
  12. package/dist/auth/github-oauth-client.d.ts +3 -13
  13. package/dist/auth/github-oauth-client.d.ts.map +1 -1
  14. package/dist/auth/oidc-client.d.ts +6 -16
  15. package/dist/auth/oidc-client.d.ts.map +1 -1
  16. package/dist/auth/oidc-evidence.d.ts +8 -4
  17. package/dist/auth/oidc-evidence.d.ts.map +1 -1
  18. package/dist/{chunk-2OC3SK6F.js → chunk-6EEU4QOU.js} +52 -5
  19. package/dist/chunk-6EEU4QOU.js.map +1 -0
  20. package/dist/{chunk-SKQGTUDA.js → chunk-AJ2DQWI3.js} +162 -173
  21. package/dist/chunk-AJ2DQWI3.js.map +1 -0
  22. package/dist/index.js +2 -2
  23. package/dist/launch-pipeline.d.ts.map +1 -1
  24. package/dist/main.js +3 -3
  25. package/dist/process-launcher-registry.d.ts +3 -0
  26. package/dist/process-launcher-registry.d.ts.map +1 -1
  27. package/dist/routes/launchers.d.ts.map +1 -1
  28. package/dist/testing.js +1 -1
  29. package/package.json +12 -12
  30. package/src/app.ts +1 -0
  31. package/src/auth/api-token-routes.ts +17 -21
  32. package/src/auth/api-token-service.ts +4 -17
  33. package/src/auth/auth-client.ts +19 -19
  34. package/src/auth/auth-service.ts +34 -86
  35. package/src/auth/auth-test-helpers.ts +40 -10
  36. package/src/auth/github-oauth-client.ts +8 -22
  37. package/src/auth/oidc-client.ts +7 -19
  38. package/src/auth/oidc-evidence.ts +61 -6
  39. package/src/launch-pipeline.ts +6 -0
  40. package/src/process-launcher-registry.ts +56 -6
  41. package/src/routes/launchers.ts +35 -20
  42. package/dist/app-MELYT4QS.js +0 -8
  43. package/dist/chunk-2OC3SK6F.js.map +0 -1
  44. package/dist/chunk-SKQGTUDA.js.map +0 -1
  45. /package/dist/{app-MELYT4QS.js.map → app-2TCRADVA.js.map} +0 -0
@@ -7,6 +7,7 @@ import {
7
7
  SAFE_SKILL_ID_PATTERN,
8
8
  SKILL_RESOURCE_OWNER,
9
9
  actorForRequest,
10
+ actorFromClaims,
10
11
  appendProcessEvent,
11
12
  applyMetadataPatch,
12
13
  applyProcessPatchField,
@@ -62,6 +63,7 @@ import {
62
63
  hasAuthorization,
63
64
  hasProcessGraph,
64
65
  hashOpaqueToken,
66
+ interpretOidcLogin,
65
67
  isHttpsOrLoopbackHttpUrl,
66
68
  isInternalEngineFailureCode,
67
69
  isLoopbackHttpUrl,
@@ -109,7 +111,6 @@ import {
109
111
  resolveRegisteredProviderOptions,
110
112
  resolveWorkerPiAgentDir,
111
113
  routeConfig,
112
- safeClaims,
113
114
  selectWorkerRuntimeProfile,
114
115
  sendActionRequestNormalizationError,
115
116
  sendLauncherLookupFailure,
@@ -132,7 +133,7 @@ import {
132
133
  verifyOpaqueToken,
133
134
  withTimeout,
134
135
  writeTurnWait
135
- } from "./chunk-2OC3SK6F.js";
136
+ } from "./chunk-6EEU4QOU.js";
136
137
 
137
138
  // src/app.ts
138
139
  import path10 from "node:path";
@@ -152,6 +153,9 @@ import {
152
153
  } from "@leitwerk-dev/worker-runners";
153
154
  import Fastify from "fastify";
154
155
 
156
+ // src/auth/auth-service.ts
157
+ import { ADMIN_ACTOR as ADMIN_ACTOR2 } from "@leitwerk-dev/domain";
158
+
155
159
  // src/auth/api-token-service.ts
156
160
  import { randomUUID } from "node:crypto";
157
161
  import { ADMIN_ACTOR } from "@leitwerk-dev/domain";
@@ -205,7 +209,7 @@ function isActorAllowedByConfig(actor, auth, evidence) {
205
209
  }
206
210
 
207
211
  // src/auth/api-token-service.ts
208
- function binding(provider) {
212
+ function tokenProviderBinding(provider) {
209
213
  return provider.kind === "oidc" ? {
210
214
  id: provider.id,
211
215
  kind: provider.kind,
@@ -229,20 +233,6 @@ function createApiTokenService(input) {
229
233
  if (auth.enabled) repo.revokeAnonymous((/* @__PURE__ */ new Date()).toISOString());
230
234
  return {
231
235
  policy,
232
- ownerForActor(actor, oidcEvidence) {
233
- if (!auth.enabled)
234
- return { kind: "anonymous", id: "anonymous", actor: ADMIN_ACTOR, providerBinding: null };
235
- const provider = auth.providers.find((p) => p.id === actor.provider);
236
- if (!provider || !isActorAllowedByConfig(actor, auth, oidcEvidence))
237
- throw new Error("Invalid token owner");
238
- return {
239
- kind: "user",
240
- id: actor.id,
241
- actor,
242
- providerBinding: binding(provider),
243
- oidcEvidence
244
- };
245
- },
246
236
  create(owner, name, expiresAt) {
247
237
  if (!policy.enabled) throw new ApiTokenValidationError("API token issuance is disabled");
248
238
  if (typeof name !== "string" || name.trim().length === 0 || name.trim().length > 100)
@@ -287,7 +277,7 @@ function createApiTokenService(input) {
287
277
  if (!auth.enabled || !isActorAllowedByConfig(token.owner.actor, auth, token.owner.oidcEvidence))
288
278
  return denied;
289
279
  const provider = auth.providers.find((p) => p.id === token.owner.actor.provider);
290
- if (!provider || JSON.stringify(binding(provider)) !== JSON.stringify(token.owner.providerBinding))
280
+ if (!provider || JSON.stringify(tokenProviderBinding(provider)) !== JSON.stringify(token.owner.providerBinding))
291
281
  return denied;
292
282
  }
293
283
  repo.touch(token.id, now2);
@@ -300,14 +290,10 @@ function createApiTokenService(input) {
300
290
  }
301
291
 
302
292
  // src/auth/github-oauth-client.ts
303
- import { randomBytes } from "node:crypto";
304
293
  var GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
305
294
  var GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
306
295
  var GITHUB_API_URL = "https://api.github.com";
307
296
  var GITHUB_API_VERSION = "2022-11-28";
308
- function opaqueValue() {
309
- return randomBytes(32).toString("base64url");
310
- }
311
297
  function githubHeaders(accessToken) {
312
298
  return {
313
299
  Accept: "application/vnd.github+json",
@@ -327,18 +313,17 @@ async function jsonObject(response, errorMessage3) {
327
313
  function createGithubOauthClient(fetchImpl = fetch) {
328
314
  return {
329
315
  async createAuthorizationRequest(provider) {
330
- const state = opaqueValue();
316
+ const state = generateOpaqueToken();
331
317
  const redirectUrl = new URL(GITHUB_AUTHORIZE_URL);
332
318
  redirectUrl.searchParams.set("client_id", provider.client_id);
333
319
  redirectUrl.searchParams.set("redirect_uri", provider.redirect_uri);
334
320
  redirectUrl.searchParams.set("scope", provider.scopes.join(" "));
335
321
  redirectUrl.searchParams.set("state", state);
336
322
  return {
337
- provider,
338
323
  state,
339
324
  // The persisted login-flow schema requires a verifier. GitHub OAuth Apps
340
325
  // authenticate this confidential client with its secret instead of PKCE.
341
- pkceVerifier: opaqueValue(),
326
+ pkceVerifier: generateOpaqueToken(),
342
327
  redirectUrl: redirectUrl.toString()
343
328
  };
344
329
  },
@@ -427,7 +412,7 @@ function createOpenIdClient() {
427
412
  code_challenge: codeChallenge,
428
413
  code_challenge_method: "S256"
429
414
  }).toString();
430
- return { provider, state, pkceVerifier, redirectUrl };
415
+ return { state, pkceVerifier, redirectUrl };
431
416
  },
432
417
  async exchangeCallback(input) {
433
418
  const config = await getConfiguration(input.provider);
@@ -456,7 +441,6 @@ function createOpenIdClient() {
456
441
  throw new Error("OIDC UserInfo subject mismatch");
457
442
  }
458
443
  return {
459
- claims: userInfo ? { ...idClaims, ...userInfo } : idClaims,
460
444
  idTokenClaims: idClaims,
461
445
  userInfoClaims: userInfo
462
446
  };
@@ -472,47 +456,23 @@ function createAuthClient(input) {
472
456
  createAuthorizationRequest(provider) {
473
457
  return provider.kind === "oidc" ? oidc.createAuthorizationRequest(provider) : github.createAuthorizationRequest(provider);
474
458
  },
475
- exchangeCallback(request) {
476
- return request.provider.kind === "oidc" ? oidc.exchangeCallback({ ...request, provider: request.provider }) : github.exchangeCallback({ ...request, provider: request.provider });
459
+ async exchangeCallback(request) {
460
+ if (request.provider.kind === "oidc")
461
+ return interpretOidcLogin(
462
+ request.provider,
463
+ await oidc.exchangeCallback({ ...request, provider: request.provider })
464
+ );
465
+ const { claims } = await github.exchangeCallback({ ...request, provider: request.provider });
466
+ return { actor: actorFromClaims(request.provider, claims), oidcEvidence: null };
477
467
  }
478
468
  };
479
469
  }
480
470
 
481
471
  // src/auth/auth-service.ts
482
- function pickDisplayName(claims, identity) {
483
- for (const key of ["name", "preferred_username", "email"]) {
484
- const value = claims[key];
485
- if (typeof value === "string" && value.trim() !== "") {
486
- return value;
487
- }
488
- }
489
- return identity;
490
- }
491
- function actorFromOidcClaims(input) {
492
- const rawIdentity = input.claims[input.provider.identity_claim];
493
- const identity = typeof rawIdentity === "string" ? rawIdentity.trim() : "";
494
- if (identity === "") {
495
- return null;
496
- }
497
- return {
498
- id: `${input.provider.id}:${identity}`,
499
- kind: "user",
500
- provider: input.provider.id,
501
- displayName: pickDisplayName(input.claims, identity)
502
- };
503
- }
504
472
  var DEFAULT_AUTH_SWEEP_INTERVAL_MS = 5 * 60 * 1e3;
505
- function consumeValidFlow(repos, cookieValue) {
506
- const idHash = hashOpaqueToken(cookieValue);
507
- const flow = repos.authLoginFlows.getValid(idHash);
508
- if (flow) {
509
- repos.authLoginFlows.delete(idHash);
510
- }
511
- return flow;
512
- }
513
473
  function createAuthService(input) {
514
474
  const auth = resolveAuthConfig(input.config);
515
- const authClient = input.authClient ?? createAuthClient({ oidc: input.oidcClient });
475
+ const authClient = createAuthClient({ oidc: input.oidcClient, github: input.githubClient });
516
476
  const sweepExpiredAuthState = () => ({
517
477
  sessions: input.repos.authSessions.deleteExpired(),
518
478
  loginFlows: input.repos.authLoginFlows.deleteExpired()
@@ -557,10 +517,12 @@ function createAuthService(input) {
557
517
  if (!auth.enabled) {
558
518
  throw new Error("Authentication is not enabled");
559
519
  }
560
- const flow = consumeValidFlow(input.repos, loginCookieValue);
520
+ const flowHash = hashOpaqueToken(loginCookieValue);
521
+ const flow = input.repos.authLoginFlows.getValid(flowHash);
561
522
  if (!flow) {
562
523
  throw new Error("Login flow expired or was not found");
563
524
  }
525
+ input.repos.authLoginFlows.delete(flowHash);
564
526
  const provider = auth.providers.find((p) => p.id === flow.providerId) ?? null;
565
527
  if (!provider) {
566
528
  throw new Error("Login provider is no longer configured");
@@ -568,40 +530,12 @@ function createAuthService(input) {
568
530
  if (callbackUrl.searchParams.get("state") !== flow.state) {
569
531
  throw new Error("Invalid authentication state");
570
532
  }
571
- const exchanged = await authClient.exchangeCallback({
533
+ const { actor, oidcEvidence } = await authClient.exchangeCallback({
572
534
  provider,
573
535
  callbackUrl,
574
536
  state: flow.state,
575
537
  pkceVerifier: flow.pkceVerifier
576
538
  });
577
- const actor = actorFromOidcClaims({ provider, claims: safeClaims(exchanged.claims) });
578
- if (!actor) {
579
- throw new Error(`Authentication identity claim ${provider.identity_claim} was not present`);
580
- }
581
- let oidcEvidence = null;
582
- if (provider.kind === "oidc") {
583
- const idTokenClaims = safeClaims(exchanged.idTokenClaims ?? {});
584
- const userInfoClaims = exchanged.userInfoClaims ? safeClaims(exchanged.userInfoClaims) : null;
585
- if (typeof idTokenClaims.sub !== "string" || !idTokenClaims.sub.trim() || userInfoClaims && userInfoClaims.sub !== idTokenClaims.sub)
586
- throw new Error("Invalid OIDC subject evidence");
587
- const claims = { ...idTokenClaims, ...userInfoClaims };
588
- const groups = claims[provider.access?.groups_claim ?? "groups"];
589
- oidcEvidence = {
590
- providerId: provider.id,
591
- issuer: provider.issuer,
592
- identityClaim: provider.identity_claim,
593
- subject: idTokenClaims.sub,
594
- loginAt: (/* @__PURE__ */ new Date()).toISOString(),
595
- idTokenClaims,
596
- userInfoClaims,
597
- facts: {
598
- identity: actor.id.slice(provider.id.length + 1),
599
- email: typeof claims.email === "string" ? claims.email : null,
600
- emailVerified: claims.email_verified === true,
601
- groups: Array.isArray(groups) && groups.every((group) => typeof group === "string") ? groups : []
602
- }
603
- };
604
- }
605
539
  if (!isActorAllowedByConfig(actor, auth, oidcEvidence)) {
606
540
  throw new Error("Authenticated user does not satisfy admission policy");
607
541
  }
@@ -618,6 +552,21 @@ function createAuthService(input) {
618
552
  resolveSession(cookieValue) {
619
553
  return resolveSessionRecord(cookieValue)?.actor ?? null;
620
554
  },
555
+ tokenOwnerForSession(cookieValue) {
556
+ if (!auth.enabled)
557
+ return { kind: "anonymous", id: "anonymous", actor: ADMIN_ACTOR2, providerBinding: null };
558
+ const session = resolveSessionRecord(cookieValue);
559
+ if (!session) return null;
560
+ const provider = auth.providers.find((p) => p.id === session.actor.provider);
561
+ if (!provider) return null;
562
+ return {
563
+ kind: "user",
564
+ id: session.actor.id,
565
+ actor: session.actor,
566
+ providerBinding: tokenProviderBinding(provider),
567
+ oidcEvidence: session.oidcEvidence
568
+ };
569
+ },
621
570
  userInformation(cookieValue) {
622
571
  return resolveSessionRecord(cookieValue)?.oidcEvidence ?? null;
623
572
  },
@@ -1826,8 +1775,8 @@ function createExternalSourceService(deps) {
1826
1775
  if (!processDef) {
1827
1776
  return null;
1828
1777
  }
1829
- for (const [turnId, binding2] of processDef.turns) {
1830
- const turnDef = binding2.definition;
1778
+ for (const [turnId, binding] of processDef.turns) {
1779
+ const turnDef = binding.definition;
1831
1780
  if (turnDef.kind !== "external") {
1832
1781
  for (const [externalActionId, action] of Object.entries(turnDef.externalActions ?? {})) {
1833
1782
  if (getExternalActionArmingId({ turnId, externalActionId }) === armingId) {
@@ -10095,13 +10044,13 @@ var ResolveTurnWait = defineOperation({
10095
10044
  if (input.nextStateJson !== void 0 && !["retry", "error"].includes(input.result))
10096
10045
  applyProcessPatchField(writes, process2, "stateJson", input.nextStateJson);
10097
10046
  if (input.result === "bind") {
10098
- const binding2 = input.initialBinding;
10099
- if (!binding2?.projects.length || !wait.initialSelection || process2.currentExecution || deps.projects.listByInstance(process2.id).length || deps.turnStarts.listByInstance(process2.id).length || deps.turnRecords.listByInstance(process2.id).length)
10047
+ const binding = input.initialBinding;
10048
+ if (!binding?.projects.length || !wait.initialSelection || process2.currentExecution || deps.projects.listByInstance(process2.id).length || deps.turnStarts.listByInstance(process2.id).length || deps.turnRecords.listByInstance(process2.id).length)
10100
10049
  return reject(
10101
10050
  "startup_binding_unavailable",
10102
10051
  "Initial bindings require a process without projects or execution history"
10103
10052
  );
10104
- if (Object.keys(binding2.metadata ?? {}).some(
10053
+ if (Object.keys(binding.metadata ?? {}).some(
10105
10054
  (key) => key === "turnWait" || Object.hasOwn(process2.metadata ?? {}, key)
10106
10055
  ))
10107
10056
  return reject(
@@ -10115,15 +10064,15 @@ var ResolveTurnWait = defineOperation({
10115
10064
  process2,
10116
10065
  "paramsJson",
10117
10066
  JSON.stringify(
10118
- definition.paramsCodec.serialize(definition.paramsCodec.parse(binding2.params))
10067
+ definition.paramsCodec.serialize(definition.paramsCodec.parse(binding.params))
10119
10068
  )
10120
10069
  );
10121
10070
  applyProcessPatchField(writes, process2, "metadata", {
10122
10071
  ...process2.metadata,
10123
- ...binding2.metadata,
10124
- ...binding2.settingsContext ? { settingsContext: binding2.settingsContext } : {}
10072
+ ...binding.metadata,
10073
+ ...binding.settingsContext ? { settingsContext: binding.settingsContext } : {}
10125
10074
  });
10126
- writes.initialProjects = binding2.projects.map((project) => ({
10075
+ writes.initialProjects = binding.projects.map((project) => ({
10127
10076
  ...project,
10128
10077
  instanceId: process2.id
10129
10078
  }));
@@ -10138,7 +10087,7 @@ var ResolveTurnWait = defineOperation({
10138
10087
  eventType: "initial_repositories_bound",
10139
10088
  level: "info",
10140
10089
  message: "Startup repository bindings resolved",
10141
- data: { projectKeys: binding2.projects.map((p) => p.key) }
10090
+ data: { projectKeys: binding.projects.map((p) => p.key) }
10142
10091
  });
10143
10092
  return accept({ writes });
10144
10093
  }
@@ -11447,7 +11396,8 @@ async function reconcileProcessesOnStartup(deps) {
11447
11396
  }
11448
11397
 
11449
11398
  // src/process-launcher-registry.ts
11450
- import { buildProcessLaunchers } from "@leitwerk-dev/process-sdk";
11399
+ import { randomUUID as randomUUID2 } from "node:crypto";
11400
+ import { buildProcessLaunchers, SafeLaunchPreparationError } from "@leitwerk-dev/process-sdk";
11451
11401
 
11452
11402
  // src/process-launch-plan.ts
11453
11403
  import {
@@ -11599,6 +11549,25 @@ function buildProcessLauncherRegistry(catalog, options = {}) {
11599
11549
  launcher: result
11600
11550
  };
11601
11551
  }
11552
+ function resolveUiReadiness(launcherId, input) {
11553
+ const { ui } = requireUiLauncher(launcherId);
11554
+ try {
11555
+ return ui.readiness?.(input) ?? { status: "ready", issues: [] };
11556
+ } catch {
11557
+ const correlationId = randomUUID2();
11558
+ options.logger?.warn(`Launcher readiness failed; correlationId=${correlationId}`);
11559
+ return {
11560
+ status: "blocked",
11561
+ issues: [
11562
+ {
11563
+ code: "launcher_readiness_failed",
11564
+ summary: "Configuration readiness could not be checked.",
11565
+ remediation: `Ask an operator to inspect the server logs. Reference: ${correlationId}`
11566
+ }
11567
+ ]
11568
+ };
11569
+ }
11570
+ }
11602
11571
  const uiLaunchers = [...launchers.values()].filter((launcher) => launcher.definition.ui).map(
11603
11572
  (launcher) => ({
11604
11573
  id: launcher.definition.id,
@@ -11616,8 +11585,12 @@ function buildProcessLauncherRegistry(catalog, options = {}) {
11616
11585
  ).sort((a, b) => a.label.localeCompare(b.label));
11617
11586
  return {
11618
11587
  listUiLaunchers() {
11619
- return uiLaunchers;
11588
+ return uiLaunchers.map((launcher) => ({
11589
+ ...launcher,
11590
+ ...requireUiLauncher(launcher.id).ui.readiness ? { readiness: resolveUiReadiness(launcher.id, {}) } : {}
11591
+ }));
11620
11592
  },
11593
+ resolveUiReadiness,
11621
11594
  async resolveUiDefaults(launcherId, ctx = {}) {
11622
11595
  const { launcher, ui } = requireUiLauncher(launcherId);
11623
11596
  return await ui.resolveDefaults?.(createLauncherContext(launcher.processId, ctx)) ?? {};
@@ -11636,10 +11609,24 @@ function buildProcessLauncherRegistry(catalog, options = {}) {
11636
11609
  },
11637
11610
  resolvePreparationChecks(launcherId, input, launchConfig) {
11638
11611
  const { ui } = requireUiLauncher(launcherId);
11639
- return validateLaunchPreparationChecks(
11640
- ui.preparationChecks?.(input, launchConfig),
11641
- `Launcher '${launcherId}'`
11642
- );
11612
+ const checks = [...ui.preparationChecks?.(input, launchConfig) ?? []];
11613
+ if (ui.readiness) {
11614
+ checks.unshift({
11615
+ id: "launcher-readiness",
11616
+ label: "Check launcher configuration",
11617
+ async run() {
11618
+ const readiness = resolveUiReadiness(launcherId, input);
11619
+ if (readiness.status !== "ready") {
11620
+ const summary = readiness.issues.map((issue) => `${issue.summary} ${issue.remediation}`).join(" ");
11621
+ throw new SafeLaunchPreparationError(
11622
+ "Launcher configuration is incomplete",
11623
+ summary || "Complete launcher configuration before launching."
11624
+ );
11625
+ }
11626
+ }
11627
+ });
11628
+ }
11629
+ return validateLaunchPreparationChecks(checks, `Launcher '${launcherId}'`);
11643
11630
  },
11644
11631
  async resolveUiLauncher(launcherId, input, ctx = {}) {
11645
11632
  return resolveUiLauncher(launcherId, input, ctx, false);
@@ -13045,7 +13032,7 @@ var RepositoryCredentialService = class {
13045
13032
  };
13046
13033
 
13047
13034
  // src/result-image-store.ts
13048
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
13035
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
13049
13036
  import { mkdir, readdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
13050
13037
  import path2 from "node:path";
13051
13038
  import {
@@ -13081,7 +13068,7 @@ var ResultImageStore = class {
13081
13068
  const digest = createHash2("sha256").update(input.bytes).digest("hex");
13082
13069
  const imageId = `img_${digest}.${EXTENSIONS[input.mimeType]}`;
13083
13070
  const destination = path2.join(dir, imageId);
13084
- const temporary = path2.join(dir, `.${imageId}.${randomUUID2()}.tmp`);
13071
+ const temporary = path2.join(dir, `.${imageId}.${randomUUID3()}.tmp`);
13085
13072
  try {
13086
13073
  await writeFile(temporary, input.bytes, { flag: "wx" });
13087
13074
  await rename(temporary, destination);
@@ -13208,8 +13195,8 @@ function createScopedSettingsService(input) {
13208
13195
  }
13209
13196
  }
13210
13197
  for (const process2 of catalog.processes.values())
13211
- for (const binding2 of process2.turns.values()) {
13212
- const def = binding2.definition;
13198
+ for (const binding of process2.turns.values()) {
13199
+ const def = binding.definition;
13213
13200
  if (def.kind === "llm" && def.executionPurpose && !purposes.has(def.executionPurpose))
13214
13201
  throw new Error(`Unknown execution purpose '${def.executionPurpose}'`);
13215
13202
  }
@@ -13348,10 +13335,10 @@ function createScopedSettingsService(input) {
13348
13335
  }
13349
13336
  function repository(project) {
13350
13337
  const locator = normalizeSettingsLocator(project.repoLocator);
13351
- const binding2 = project.metadata?.settingsRepository;
13352
- if (binding2 && typeof binding2 === "object" && "origin" in binding2 && "repositoryId" in binding2 && typeof binding2.origin === "string" && (typeof binding2.repositoryId === "string" || typeof binding2.repositoryId === "number")) {
13353
- const aliases = "aliases" in binding2 && Array.isArray(binding2.aliases) ? binding2.aliases.filter((alias) => typeof alias === "string") : [];
13354
- const identity = repositorySettingsIdentity(binding2.origin, binding2.repositoryId);
13338
+ const binding = project.metadata?.settingsRepository;
13339
+ if (binding && typeof binding === "object" && "origin" in binding && "repositoryId" in binding && typeof binding.origin === "string" && (typeof binding.repositoryId === "string" || typeof binding.repositoryId === "number")) {
13340
+ const aliases = "aliases" in binding && Array.isArray(binding.aliases) ? binding.aliases.filter((alias) => typeof alias === "string") : [];
13341
+ const identity = repositorySettingsIdentity(binding.origin, binding.repositoryId);
13355
13342
  const known2 = repos.scopedSettings.findIdentity("repository", identity);
13356
13343
  return discover({
13357
13344
  scopeType: "repository",
@@ -13710,7 +13697,7 @@ function createAppLifecycle(input) {
13710
13697
  let closePromise;
13711
13698
  let startupOperation;
13712
13699
  let startupPromise;
13713
- let binding2;
13700
+ let binding;
13714
13701
  let bindOperation;
13715
13702
  const cleanupErrors = [];
13716
13703
  function assertOpen() {
@@ -13740,9 +13727,9 @@ function createAppLifecycle(input) {
13740
13727
  }
13741
13728
  async function listen(options = {}) {
13742
13729
  assertOpen();
13743
- if (binding2) {
13730
+ if (binding) {
13744
13731
  for (const key of ["host", "port", "useBoundAddressAsBaseUrl"]) {
13745
- if (options[key] !== void 0 && options[key] !== binding2[key])
13732
+ if (options[key] !== void 0 && options[key] !== binding[key])
13746
13733
  throw new Error(`Conflicting listener option: ${key}`);
13747
13734
  }
13748
13735
  } else {
@@ -13754,7 +13741,7 @@ function createAppLifecycle(input) {
13754
13741
  };
13755
13742
  if (requested.useBoundAddressAsBaseUrl && (input.authEnabled || !["127.0.0.1", "::1", "localhost"].includes(requested.host)))
13756
13743
  throw new Error("Bound base URL requires an unauthenticated loopback listener");
13757
- binding2 = requested;
13744
+ binding = requested;
13758
13745
  bindOperation = (async () => {
13759
13746
  const started = performance.now();
13760
13747
  const address = await app.listen({ host: requested.host, port: requested.port });
@@ -13974,12 +13961,11 @@ function registerApiTokenAudit(app) {
13974
13961
  // src/auth/api-token-routes.ts
13975
13962
  import { createHmac, timingSafeEqual } from "node:crypto";
13976
13963
  function registerApiTokenRoutes(app, auth) {
13964
+ const owners = /* @__PURE__ */ new WeakMap();
13977
13965
  const ownerForRequest = (request) => {
13978
- if (!request.actor) throw new Error("Browser authentication context is missing");
13979
- return auth.apiTokens.ownerForActor(
13980
- request.actor,
13981
- auth.userInformation(request.cookies?.[auth.config.sessionCookieName])
13982
- );
13966
+ const owner = owners.get(request);
13967
+ if (!owner) throw new Error("Browser token owner is missing");
13968
+ return owner;
13983
13969
  };
13984
13970
  const csrfKey = generateOpaqueToken();
13985
13971
  const anonymousCookie = `${auth.config.sessionCookieName}_token_csrf`;
@@ -13992,10 +13978,12 @@ function registerApiTokenRoutes(app, auth) {
13992
13978
  request.tokenAudit = {
13993
13979
  operation: request.method === "POST" ? "token_issuance" : request.routeOptions.url?.endsWith(":id") ? "token_revocation" : "token_revoke_all"
13994
13980
  };
13995
- const actor = authenticateBrowserRequest(auth, request);
13996
- if (!actor) return reply.code(401).send({ error: "Browser access required" });
13997
- const owner = ownerForRequest(request);
13998
- if (request.tokenAudit) Object.assign(request.tokenAudit, { actor, ownerKind: owner.kind });
13981
+ const owner = hasAuthorization(request) ? null : auth.tokenOwnerForSession(request.cookies?.[auth.config.sessionCookieName]);
13982
+ if (!owner) return reply.code(401).send({ error: "Browser access required" });
13983
+ owners.set(request, owner);
13984
+ request.actor = owner.actor;
13985
+ if (request.tokenAudit)
13986
+ Object.assign(request.tokenAudit, { actor: owner.actor, ownerKind: owner.kind });
13999
13987
  if (request.method === "GET") return;
14000
13988
  const supplied = request.headers["x-csrf-token"];
14001
13989
  const credential = credentialFor(request);
@@ -14031,11 +14019,7 @@ function registerApiTokenRoutes(app, auth) {
14031
14019
  try {
14032
14020
  const input = body;
14033
14021
  const result = auth.apiTokens.create(ownerForRequest(request), input.name, input.expiresAt);
14034
- request.tokenAudit = {
14035
- ...request.tokenAudit,
14036
- operation: "token_issuance",
14037
- tokenId: result.token.id
14038
- };
14022
+ if (request.tokenAudit) request.tokenAudit.tokenId = result.token.id;
14039
14023
  return reply.code(201).send(result);
14040
14024
  } catch (error) {
14041
14025
  if (!(error instanceof ApiTokenValidationError)) throw error;
@@ -14047,17 +14031,13 @@ function registerApiTokenRoutes(app, auth) {
14047
14031
  async (request, reply) => {
14048
14032
  if (!auth.apiTokens.revoke(ownerForRequest(request), request.params.id))
14049
14033
  return reply.code(404).send({ error: "Token not found" });
14050
- request.tokenAudit = {
14051
- ...request.tokenAudit,
14052
- operation: "token_revocation",
14053
- tokenId: request.params.id
14054
- };
14034
+ if (request.tokenAudit) request.tokenAudit.tokenId = request.params.id;
14055
14035
  return { ok: true };
14056
14036
  }
14057
14037
  );
14058
14038
  management.delete("/api/auth/tokens", async (request) => {
14059
14039
  const count = auth.apiTokens.revokeAll(ownerForRequest(request));
14060
- request.tokenAudit = { ...request.tokenAudit, operation: "token_revoke_all", count };
14040
+ if (request.tokenAudit) request.tokenAudit.count = count;
14061
14041
  return { ok: true, count };
14062
14042
  });
14063
14043
  });
@@ -14903,27 +14883,35 @@ function registerLauncherRoutes(app, deps, futureExecutionLifecycle) {
14903
14883
  return body;
14904
14884
  }
14905
14885
  );
14906
- app.post(
14907
- "/api/launchers/:launcherId/options",
14908
- async (req, reply) => {
14909
- const normalized = normalizeLauncherRequest(req.body);
14910
- if (!normalized.ok) {
14911
- return sendLauncherRequestNormalizationError(reply, normalized.error);
14912
- }
14913
- try {
14914
- const options = await deps.launcherService.resolveUiOptions(
14915
- req.params.launcherId,
14916
- normalized.request.launcherInput
14917
- );
14918
- const body = { options };
14919
- return body;
14920
- } catch (error) {
14921
- if (sendLauncherLookupFailure(reply, error)) {
14922
- return;
14886
+ function postLauncherInput(path11, resolve) {
14887
+ app.post(
14888
+ `/api/launchers/:launcherId/${path11}`,
14889
+ async (req, reply) => {
14890
+ const normalized = normalizeLauncherRequest(req.body);
14891
+ if (!normalized.ok) return sendLauncherRequestNormalizationError(reply, normalized.error);
14892
+ try {
14893
+ return await resolve(req.params.launcherId, normalized.request.launcherInput);
14894
+ } catch (error) {
14895
+ if (sendLauncherLookupFailure(reply, error)) return;
14896
+ throw error;
14923
14897
  }
14924
- throw error;
14925
14898
  }
14926
- }
14899
+ );
14900
+ }
14901
+ postLauncherInput(
14902
+ "readiness",
14903
+ (launcherId, input) => ({
14904
+ readiness: deps.launcherService.resolveUiReadiness?.(launcherId, input) ?? {
14905
+ status: "ready",
14906
+ issues: []
14907
+ }
14908
+ })
14909
+ );
14910
+ postLauncherInput(
14911
+ "options",
14912
+ async (launcherId, input) => ({
14913
+ options: await deps.launcherService.resolveUiOptions(launcherId, input)
14914
+ })
14927
14915
  );
14928
14916
  app.post(
14929
14917
  "/api/launchers/:launcherId/launch-runs",
@@ -17281,7 +17269,7 @@ function resolveServerTlsOptions(config, readFile6 = defaultFileReader) {
17281
17269
  }
17282
17270
 
17283
17271
  // src/session-transfer-helper-relays.ts
17284
- import { randomBytes as randomBytes2 } from "node:crypto";
17272
+ import { randomBytes } from "node:crypto";
17285
17273
  import { PassThrough } from "node:stream";
17286
17274
  import {
17287
17275
  sessionTransferPreflightReportSchema
@@ -17329,7 +17317,7 @@ function createSessionTransferHelperRelays(deps) {
17329
17317
  if (!attempt || attempt.state !== "queued" && attempt.state !== "exporting") {
17330
17318
  throw new Error("No active session transfer can accept an export helper");
17331
17319
  }
17332
- const exportId2 = `exp_${randomBytes2(16).toString("base64url")}`;
17320
+ const exportId2 = `exp_${randomBytes(16).toString("base64url")}`;
17333
17321
  const credential = createOpaqueToken();
17334
17322
  const runtime = {
17335
17323
  attemptId: attempt.id,
@@ -18713,14 +18701,14 @@ function createIpcHandler(deps, callbacks) {
18713
18701
  import { parseDurationMs as parseDurationMs4 } from "@leitwerk-dev/watcher-utils";
18714
18702
 
18715
18703
  // src/supervisor/synthetic-worker-failure.ts
18716
- import { randomUUID as randomUUID3 } from "node:crypto";
18704
+ import { randomUUID as randomUUID4 } from "node:crypto";
18717
18705
  import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
18718
18706
  function createServerObservedWorkerFailedMessage(input) {
18719
18707
  return createIpcMessage({
18720
18708
  type: "worker.failed",
18721
18709
  instanceId: input.instanceId,
18722
18710
  workerId: input.workerId,
18723
- messageId: randomUUID3(),
18711
+ messageId: randomUUID4(),
18724
18712
  payload: {
18725
18713
  state: input.state ?? "absent",
18726
18714
  errorCode: input.errorCode,
@@ -18822,7 +18810,7 @@ function startStaleHeartbeatWatchdog(deps) {
18822
18810
  }
18823
18811
 
18824
18812
  // src/supervisor/worker-supervisor.ts
18825
- import { randomUUID as randomUUID6 } from "node:crypto";
18813
+ import { randomUUID as randomUUID7 } from "node:crypto";
18826
18814
  import {
18827
18815
  parseResolvedExtensionEntries,
18828
18816
  RUNTIME_EXTENSION_ALLOWED_ROOTS_ENV,
@@ -19200,7 +19188,7 @@ function createWorkerCapacityQueue(deps) {
19200
19188
  }
19201
19189
 
19202
19190
  // src/supervisor/worker-shutdown-controller.ts
19203
- import { randomUUID as randomUUID4 } from "node:crypto";
19191
+ import { randomUUID as randomUUID5 } from "node:crypto";
19204
19192
  import { setTimeout as sleep } from "node:timers/promises";
19205
19193
  import { parseDurationMs as parseDurationMs5 } from "@leitwerk-dev/watcher-utils";
19206
19194
  import { createIpcMessage as createIpcMessage2 } from "@leitwerk-dev/worker-protocol";
@@ -19232,7 +19220,7 @@ function createWorkerShutdownController(input) {
19232
19220
  type: "worker.stop",
19233
19221
  instanceId,
19234
19222
  workerId: handle.workerId,
19235
- messageId: randomUUID4(),
19223
+ messageId: randomUUID5(),
19236
19224
  payload: { reason }
19237
19225
  });
19238
19226
  handle.send(msg);
@@ -19266,7 +19254,7 @@ function createWorkerShutdownController(input) {
19266
19254
  }
19267
19255
 
19268
19256
  // src/supervisor/worker-start-payload-builder.ts
19269
- import { randomUUID as randomUUID5 } from "node:crypto";
19257
+ import { randomUUID as randomUUID6 } from "node:crypto";
19270
19258
  import path9 from "node:path";
19271
19259
  import { parseProductRefsFromStateJsonLenient } from "@leitwerk-dev/domain";
19272
19260
  import { parseDurationMs as parseDurationMs6 } from "@leitwerk-dev/watcher-utils";
@@ -19547,7 +19535,7 @@ function createWorkerStartPayloadBuilder(deps) {
19547
19535
  type: "worker.start",
19548
19536
  instanceId,
19549
19537
  workerId,
19550
- messageId: randomUUID5(),
19538
+ messageId: randomUUID6(),
19551
19539
  payload
19552
19540
  });
19553
19541
  }
@@ -19952,7 +19940,7 @@ function createWorkerSupervisor(deps) {
19952
19940
  worker.send(
19953
19941
  createIpcMessage4({
19954
19942
  ...message,
19955
- messageId: randomUUID6(),
19943
+ messageId: randomUUID7(),
19956
19944
  instanceId,
19957
19945
  workerId
19958
19946
  })
@@ -20102,7 +20090,7 @@ function createWorkerSupervisor(deps) {
20102
20090
  type: "input.batch",
20103
20091
  instanceId,
20104
20092
  workerId: handle.workerId,
20105
- messageId: randomUUID6(),
20093
+ messageId: randomUUID7(),
20106
20094
  payload: { inputs }
20107
20095
  });
20108
20096
  handle.send(msg);
@@ -20620,7 +20608,7 @@ function createWorkerSupervisor(deps) {
20620
20608
  createIpcMessage4({
20621
20609
  type: "worker.turn_terminal_recorded",
20622
20610
  payload,
20623
- messageId: randomUUID6(),
20611
+ messageId: randomUUID7(),
20624
20612
  instanceId,
20625
20613
  workerId
20626
20614
  })
@@ -20810,7 +20798,7 @@ function createTurnWaitService(deps) {
20810
20798
  complete: () => ({ kind: "complete" }),
20811
20799
  waiting: (message2) => ({ kind: "waiting", message: message2 }),
20812
20800
  abort: (message2) => ({ kind: "abort", message: message2 }),
20813
- bindInitialProjects: (binding2) => ({ kind: "bind", binding: binding2 })
20801
+ bindInitialProjects: (binding) => ({ kind: "bind", binding })
20814
20802
  };
20815
20803
  const timedOut = new Promise((_, reject2) => {
20816
20804
  onAbort = () => reject2(new RetryableWaitError("Waiting condition interrupted"));
@@ -21208,6 +21196,7 @@ ${configErrors.join("\n")}`);
21208
21196
  );
21209
21197
  };
21210
21198
  const launcherService = buildProcessLauncherRegistry(extensionCatalog, {
21199
+ logger: { warn: (message) => app.log.warn(message) },
21211
21200
  modelProfiles: launcherModelProfiles,
21212
21201
  commitMessages: config.commit_messages,
21213
21202
  getModelProfilesForProcess
@@ -21953,8 +21942,8 @@ ${configErrors.join("\n")}`);
21953
21942
  await polling.stop();
21954
21943
  });
21955
21944
  for (const process2 of extensionCatalog.processes.values()) {
21956
- for (const [turnId, binding2] of process2.turns) {
21957
- const definition = binding2.definition;
21945
+ for (const [turnId, binding] of process2.turns) {
21946
+ const definition = binding.definition;
21958
21947
  if (definition.kind !== "llm" || !definition.integrationTools?.length) continue;
21959
21948
  try {
21960
21949
  integrationTools.declarations(definition.integrationTools);
@@ -22062,4 +22051,4 @@ ${configErrors.join("\n")}`);
22062
22051
  export {
22063
22052
  createAppContext
22064
22053
  };
22065
- //# sourceMappingURL=chunk-SKQGTUDA.js.map
22054
+ //# sourceMappingURL=chunk-AJ2DQWI3.js.map