@wtfalch/foundry 0.48.0 → 0.50.0

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 (38) hide show
  1. package/dist/bootstrap/declare.js +1 -0
  2. package/dist/index.d.ts +8 -3
  3. package/dist/index.js +5 -2
  4. package/dist/migrations/0060_hosting_repos.sql +7 -0
  5. package/dist/org.d.ts +9 -1
  6. package/dist/org.js +27 -0
  7. package/dist/plan/archon-blue-green.js +1 -0
  8. package/dist/plan/blue-green-apply.d.ts +9 -0
  9. package/dist/plan/blue-green-apply.js +86 -2
  10. package/dist/plan/blue-green.d.ts +8 -0
  11. package/dist/plan/blue-green.js +18 -1
  12. package/dist/plan/call-timeout.d.ts +6 -0
  13. package/dist/plan/call-timeout.js +27 -0
  14. package/dist/plan/diff.d.ts +2 -0
  15. package/dist/plan/diff.js +1 -0
  16. package/dist/plan/executor.d.ts +2 -0
  17. package/dist/plan/executor.js +25 -1
  18. package/dist/plan/github-release-hook.d.ts +81 -0
  19. package/dist/plan/github-release-hook.js +159 -0
  20. package/dist/plan/index.d.ts +7 -1
  21. package/dist/plan/index.js +4 -1
  22. package/dist/plan/live.d.ts +1 -1
  23. package/dist/plan/plan-apply.d.ts +2 -0
  24. package/dist/plan/plan-apply.js +8 -3
  25. package/dist/plan/platform-diff.d.ts +59 -0
  26. package/dist/plan/platform-diff.js +98 -1
  27. package/dist/plan/platform-providers.d.ts +10 -0
  28. package/dist/plan/platform-providers.js +71 -1
  29. package/dist/plan/stage-copy-port.d.ts +62 -0
  30. package/dist/plan/stage-copy-port.js +208 -0
  31. package/dist/plan/stage-copy.d.ts +140 -0
  32. package/dist/plan/stage-copy.js +538 -0
  33. package/dist/plan/stage-sink.d.ts +37 -0
  34. package/dist/plan/stage-sink.js +33 -0
  35. package/dist/store/postgres.js +13 -2
  36. package/dist/store/schema.d.ts +19 -0
  37. package/dist/store/schema.js +2 -0
  38. package/package.json +1 -1
@@ -0,0 +1,159 @@
1
+ import { GITHUB_RELEASE_HOOK_COOLIFY_READ_FAILED, GITHUB_RELEASE_HOOK_ORG, GITHUB_RELEASE_HOOK_TOKEN_MISSING, GITHUB_RELEASE_WEBHOOK_SECRET_ENV, PLATFORM_ARCHON_KEY, PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF, PLATFORM_GITHUB_RELEASE_HOOK_HASH_SCOPE_KEY, PLATFORM_GITHUB_RELEASE_HOOK_ID_SCOPE_KEY, githubReleaseHookHash, githubReleaseHookUrl, } from './platform-diff.js';
2
+ /** Every GitHub call is cut off after this long. */
3
+ export const GITHUB_API_TIMEOUT_MS = 20_000;
4
+ const GITHUB_API = 'https://api.github.com';
5
+ const PAGE_SIZE = 100;
6
+ const MAX_PAGES = 20;
7
+ /** A GitHub call that failed. The text is fixed: it never holds the token, the secret or a response body. */
8
+ export class GithubApiError extends Error {
9
+ operation;
10
+ status;
11
+ constructor(operation, status) {
12
+ super(status === null
13
+ ? `GitHub API ${operation} did not answer`
14
+ : `GitHub API ${operation} failed with status ${status}`);
15
+ this.operation = operation;
16
+ this.status = status;
17
+ this.name = 'GithubApiError';
18
+ }
19
+ }
20
+ /** The GitHub REST organisation-hooks calls, over `fetchImpl` (global fetch by default) with a timeout on each. */
21
+ export function createGithubHooksClient(options) {
22
+ const doFetch = options.fetchImpl ?? fetch;
23
+ const timeoutMs = options.timeoutMs ?? GITHUB_API_TIMEOUT_MS;
24
+ const call = async (operation, method, path, body) => {
25
+ let response;
26
+ try {
27
+ response = await doFetch(`${GITHUB_API}${path}`, {
28
+ method,
29
+ headers: {
30
+ Authorization: `Bearer ${options.token}`,
31
+ Accept: 'application/vnd.github+json',
32
+ 'X-GitHub-Api-Version': '2022-11-28',
33
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
34
+ },
35
+ ...(body ? { body: JSON.stringify(body) } : {}),
36
+ signal: AbortSignal.timeout(timeoutMs),
37
+ });
38
+ }
39
+ catch (error) {
40
+ console.error(`github release hook: ${operation} did not answer (${error instanceof Error ? error.name : 'error'})`);
41
+ throw new GithubApiError(operation, null);
42
+ }
43
+ if (!response.ok)
44
+ throw new GithubApiError(operation, response.status);
45
+ try {
46
+ return await response.json();
47
+ }
48
+ catch (error) {
49
+ console.error(`github release hook: ${operation} answered with unreadable JSON (${error instanceof Error ? error.name : 'error'})`);
50
+ throw new GithubApiError(operation, response.status);
51
+ }
52
+ };
53
+ const asHook = (operation, value) => {
54
+ const hook = value;
55
+ if (!hook || typeof hook.id !== 'number')
56
+ throw new GithubApiError(operation, 200);
57
+ return {
58
+ id: hook.id,
59
+ active: hook.active === true,
60
+ events: Array.isArray(hook.events) ? hook.events.map(String) : [],
61
+ config: {
62
+ ...(typeof hook.config?.url === 'string' ? { url: hook.config.url } : {}),
63
+ ...(typeof hook.config?.content_type === 'string'
64
+ ? { content_type: hook.config.content_type }
65
+ : {}),
66
+ },
67
+ };
68
+ };
69
+ return {
70
+ async list(org) {
71
+ const hooks = [];
72
+ for (let page = 1; page <= MAX_PAGES; page++) {
73
+ const value = await call('list hooks', 'GET', `/orgs/${org}/hooks?per_page=${PAGE_SIZE}&page=${page}`);
74
+ if (!Array.isArray(value))
75
+ throw new GithubApiError('list hooks', 200);
76
+ hooks.push(...value.map((v) => asHook('list hooks', v)));
77
+ if (value.length < PAGE_SIZE)
78
+ return hooks;
79
+ }
80
+ return hooks;
81
+ },
82
+ async create(org, body) {
83
+ return asHook('create hook', await call('create hook', 'POST', `/orgs/${org}/hooks`, body));
84
+ },
85
+ async update(org, id, body) {
86
+ return asHook('update hook', await call('update hook', 'PATCH', `/orgs/${org}/hooks/${id}`, body));
87
+ },
88
+ };
89
+ }
90
+ async function liveWebhookSecret(deps, recorded) {
91
+ const appId = recorded[`coolify:app:${PLATFORM_ARCHON_KEY}`];
92
+ if (!appId)
93
+ return undefined;
94
+ const envs = await deps.coolify.listEnvs(appId);
95
+ const value = envs.find((e) => e.key === GITHUB_RELEASE_WEBHOOK_SECRET_ENV && !e.is_preview)?.value;
96
+ return value || undefined;
97
+ }
98
+ /**
99
+ * What the planner needs: why the step is blocked (the token is not held), or `ready` (the token is
100
+ * held) with the hash of the hook's url and Archon's live secret when Archon already holds one. With no
101
+ * secret yet the step still plans: `platform:archon` mints it earlier in the same apply.
102
+ */
103
+ export async function githubReleaseHookPlanInputs(deps, hostname, recorded) {
104
+ const token = await deps.heldKeys.resolve(PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF);
105
+ if (!token)
106
+ return { blocked: GITHUB_RELEASE_HOOK_TOKEN_MISSING };
107
+ let secret;
108
+ try {
109
+ secret = await liveWebhookSecret(deps, recorded);
110
+ }
111
+ catch (error) {
112
+ console.error(`github release hook: could not read Archon's env from Coolify (${error instanceof Error ? error.name : 'error'})`);
113
+ return { blocked: GITHUB_RELEASE_HOOK_COOLIFY_READ_FAILED };
114
+ }
115
+ return secret
116
+ ? { ready: true, hash: githubReleaseHookHash(githubReleaseHookUrl(hostname), secret) }
117
+ : { ready: true };
118
+ }
119
+ /**
120
+ * Makes the organisation's release webhook. Adopts the hook whose url is Archon's, else creates one;
121
+ * an adopted hook is always written again, because GitHub never returns its secret.
122
+ *
123
+ * The secret is made here when Archon's app does not hold one yet (`ensureSecret`, which keeps a live
124
+ * value), so the step can run before `platform:archon`; that step then keeps the same value.
125
+ *
126
+ * A failure halfway: a hook made and not recorded is adopted by its url on the next run; a hook
127
+ * written and not recorded is written again. The id and the hash are recorded together, after the write.
128
+ */
129
+ export async function provisionGithubReleaseHook(context, deps, ensureSecret) {
130
+ const appId = context.recordedIds()[`coolify:app:${PLATFORM_ARCHON_KEY}`];
131
+ if (!appId) {
132
+ throw new Error("platform:github-release-hook: Archon's app is not recorded yet; platform:archon runs first");
133
+ }
134
+ const token = await deps.heldKeys.resolve(PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF);
135
+ if (!token)
136
+ throw new Error(`platform:github-release-hook: ${GITHUB_RELEASE_HOOK_TOKEN_MISSING}`);
137
+ const secret = await ensureSecret(appId);
138
+ deps.onSecret?.(secret);
139
+ deps.onSecret?.(token);
140
+ const url = githubReleaseHookUrl(context.platform.archon.hostname);
141
+ const body = {
142
+ name: 'web',
143
+ active: true,
144
+ events: ['release'],
145
+ config: { url, content_type: 'json', secret, insecure_ssl: '0' },
146
+ };
147
+ const client = createGithubHooksClient({
148
+ token,
149
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
150
+ });
151
+ const existing = (await client.list(GITHUB_RELEASE_HOOK_ORG)).find((h) => h.config.url === url);
152
+ const hook = existing
153
+ ? await client.update(GITHUB_RELEASE_HOOK_ORG, existing.id, body)
154
+ : await client.create(GITHUB_RELEASE_HOOK_ORG, body);
155
+ context.recordScopeId(PLATFORM_GITHUB_RELEASE_HOOK_ID_SCOPE_KEY, String(hook.id));
156
+ context.recordScopeId(PLATFORM_GITHUB_RELEASE_HOOK_HASH_SCOPE_KEY, githubReleaseHookHash(url, secret));
157
+ await context.persist?.();
158
+ return undefined;
159
+ }
@@ -5,7 +5,7 @@ export { computePlanDetail, toPlan } from './diff.js';
5
5
  export type { StepSystem } from './step-system.js';
6
6
  export { stepSystemOf } from './step-system.js';
7
7
  export type { PlatformPlanDetail, MailRoute } from './platform-diff.js';
8
- export { planPlatform, toPlatformPlan, JOBS_INTERNAL_URL_SCOPE_KEY, JOBS_SCHEDULER_KEY, PLATFORM_AI_KEY, PLATFORM_AI_INTERNAL_URL_SCOPE_KEY, PLATFORM_AI_MANAGEMENT_KEY_SCOPE_KEY, PLATFORM_AI_ORGANISATION_SCOPE_KEY, PLATFORM_AUTH_KEY, PLATFORM_FILES_KEY, PLATFORM_FILES_INTERNAL_URL_SCOPE_KEY, PLATFORM_FILES_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_MAIL_KEY, PLATFORM_MAIL_RELAY_KEY, PLATFORM_MAIL_RELAY_ROUTES_SCOPE_KEY, PLATFORM_MAIL_INTERNAL_URL_SCOPE_KEY, PLATFORM_MAIL_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_EDGE_KEY, PLATFORM_EDGE_INTERNAL_URL_SCOPE_KEY, PLATFORM_EDGE_KEY_REF, PLATFORM_EDGE_CLOUDFLARE_TOKEN_REF, PLATFORM_SFU_APPLIED_SCOPE_KEY, } from './platform-diff.js';
8
+ export { planPlatform, toPlatformPlan, JOBS_INTERNAL_URL_SCOPE_KEY, JOBS_SCHEDULER_KEY, PLATFORM_AI_KEY, PLATFORM_AI_INTERNAL_URL_SCOPE_KEY, PLATFORM_AI_MANAGEMENT_KEY_SCOPE_KEY, PLATFORM_AI_ORGANISATION_SCOPE_KEY, PLATFORM_AUTH_KEY, PLATFORM_FILES_KEY, PLATFORM_FILES_INTERNAL_URL_SCOPE_KEY, PLATFORM_FILES_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_MAIL_KEY, PLATFORM_MAIL_RELAY_KEY, PLATFORM_MAIL_RELAY_ROUTES_SCOPE_KEY, PLATFORM_MAIL_INTERNAL_URL_SCOPE_KEY, PLATFORM_MAIL_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_EDGE_KEY, PLATFORM_EDGE_INTERNAL_URL_SCOPE_KEY, PLATFORM_EDGE_KEY_REF, PLATFORM_EDGE_CLOUDFLARE_TOKEN_REF, GITHUB_RELEASE_HOOK_ORG, GITHUB_RELEASE_HOOK_PATH, GITHUB_RELEASE_WEBHOOK_SECRET_ENV, PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF, PLATFORM_SFU_APPLIED_SCOPE_KEY, } from './platform-diff.js';
9
9
  export type { HeldKeyResolver, OrgPlatformReadiness } from './platform-org.js';
10
10
  export { DEFAULT_ORG_PLATFORM_READINESS, ORG_PLATFORM_KEY_REFS, agoraHostValuesForOwn, agoraHostValuesFromPlatform, heldOwnKeyRefs, heldPlatformKeyRefs, orgPlatformReadinessFor, orgPlatformReadinessFrom, } from './platform-org.js';
11
11
  export type { PlanOwnAuthOptions, PlanOwnFilesOptions, PlanOwnFilesR2Options, PlanOwnJobsOptions, } from './own-diff.js';
@@ -41,6 +41,11 @@ export { createZitadelOrgMetadata } from './zitadel-org-metadata.js';
41
41
  export { createZitadelProjectRoles } from './zitadel-project-roles.js';
42
42
  export { DumpError, dumpNow } from './database-dump.js';
43
43
  export type { DatabaseDump } from './database-dump.js';
44
+ export { STAGE_SINK_APPLIED_SCOPE_KEY, STAGE_SINK_IMAGE_REF, STAGE_SINK_SMTP_PORT, stageMailEnv, stageSinkAppName, stageSinkInternalUrl, } from './stage-sink.js';
45
+ export { STAGE_COPY_EXCLUDED_TABLES, StageCopyFailedError, StageCopyRefusedError, stageCopy, tableExcluded, undoStageCopy, } from './stage-copy.js';
46
+ export type { StageCopyInput, StageCopyPort, StageCopyProduction, StageCopyRefusalReason, StageCopyRunRecord, UndoStageCopyInput, } from './stage-copy.js';
47
+ export { StageRestoreError, StageRestoreRefusedError, createStageCopyPort, execRunner, } from './stage-copy-port.js';
48
+ export type { Runner, StageCopyPortDeps } from './stage-copy-port.js';
44
49
  export type { CallsSfuConnection, CallsSfuConnectionPort, CallsSfuKeysPort, CallsSfuSshConnector, CallsSfuPlatformDeps, } from './platform-sfu.js';
45
50
  export { MissingCallsSfuConnectionError, applyCallsSfuPlatformStep, callsSfuAppliedFingerprint, } from './platform-sfu.js';
46
51
  export type { MailCopyJob, MailCopyPort, MailCopyStepResult } from './mail-copy.js';
@@ -70,6 +75,7 @@ export { createEdgeAccess } from './edge-access.js';
70
75
  export type { AccessAppSummary, AccessDecision, AccessPolicyRule, AccessPort, EdgePlatformAccess, } from './edge-access.js';
71
76
  export { createEdgeWorkers } from './edge-workers.js';
72
77
  export type { EdgePlatformWorkers, EdgeWorkersOptions, PlatformWorkersPort, } from './edge-workers.js';
78
+ export type { PlatformGithubReleaseHookDeps } from './github-release-hook.js';
73
79
  export type { PlatformUptimeAccessFactory, PlatformUptimeAccessPort, PlatformUptimeChatDeps, PlatformUptimeDeps, PlatformWorkersFactory, } from './uptime-worker.js';
74
80
  export { createEdgeRateLimits } from './edge-ratelimits.js';
75
81
  export type { EdgePlatformRateLimits, EdgeRateLimitsOptions, RateLimitPort, RateLimitRuleInput, } from './edge-ratelimits.js';
@@ -1,7 +1,7 @@
1
1
  export { readLiveResources, readLivePlatformResources } from './live.js';
2
2
  export { computePlanDetail, toPlan } from './diff.js';
3
3
  export { stepSystemOf } from './step-system.js';
4
- export { planPlatform, toPlatformPlan, JOBS_INTERNAL_URL_SCOPE_KEY, JOBS_SCHEDULER_KEY, PLATFORM_AI_KEY, PLATFORM_AI_INTERNAL_URL_SCOPE_KEY, PLATFORM_AI_MANAGEMENT_KEY_SCOPE_KEY, PLATFORM_AI_ORGANISATION_SCOPE_KEY, PLATFORM_AUTH_KEY, PLATFORM_FILES_KEY, PLATFORM_FILES_INTERNAL_URL_SCOPE_KEY, PLATFORM_FILES_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_MAIL_KEY, PLATFORM_MAIL_RELAY_KEY, PLATFORM_MAIL_RELAY_ROUTES_SCOPE_KEY, PLATFORM_MAIL_INTERNAL_URL_SCOPE_KEY, PLATFORM_MAIL_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_EDGE_KEY, PLATFORM_EDGE_INTERNAL_URL_SCOPE_KEY, PLATFORM_EDGE_KEY_REF, PLATFORM_EDGE_CLOUDFLARE_TOKEN_REF, PLATFORM_SFU_APPLIED_SCOPE_KEY, } from './platform-diff.js';
4
+ export { planPlatform, toPlatformPlan, JOBS_INTERNAL_URL_SCOPE_KEY, JOBS_SCHEDULER_KEY, PLATFORM_AI_KEY, PLATFORM_AI_INTERNAL_URL_SCOPE_KEY, PLATFORM_AI_MANAGEMENT_KEY_SCOPE_KEY, PLATFORM_AI_ORGANISATION_SCOPE_KEY, PLATFORM_AUTH_KEY, PLATFORM_FILES_KEY, PLATFORM_FILES_INTERNAL_URL_SCOPE_KEY, PLATFORM_FILES_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_MAIL_KEY, PLATFORM_MAIL_RELAY_KEY, PLATFORM_MAIL_RELAY_ROUTES_SCOPE_KEY, PLATFORM_MAIL_INTERNAL_URL_SCOPE_KEY, PLATFORM_MAIL_ZITADEL_PROJECT_SCOPE_KEY, PLATFORM_EDGE_KEY, PLATFORM_EDGE_INTERNAL_URL_SCOPE_KEY, PLATFORM_EDGE_KEY_REF, PLATFORM_EDGE_CLOUDFLARE_TOKEN_REF, GITHUB_RELEASE_HOOK_ORG, GITHUB_RELEASE_HOOK_PATH, GITHUB_RELEASE_WEBHOOK_SECRET_ENV, PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF, PLATFORM_SFU_APPLIED_SCOPE_KEY, } from './platform-diff.js';
5
5
  export { DEFAULT_ORG_PLATFORM_READINESS, ORG_PLATFORM_KEY_REFS, agoraHostValuesForOwn, agoraHostValuesFromPlatform, heldOwnKeyRefs, heldPlatformKeyRefs, orgPlatformReadinessFor, orgPlatformReadinessFrom, } from './platform-org.js';
6
6
  export { OWN_AUTH_APPLIED_GIT_REF_SCOPE_KEY, OWN_AUTH_APPLIED_HOSTNAME_SCOPE_KEY, OWN_AUTH_BLOCKED_KEY, OWN_FILES_BLOCKED_KEY, OWN_FILES_R2_BLOCKED_KEY, OWN_JOBS_BLOCKED_KEY, OWN_MAIL_BLOCKED_KEY, planOwnAuth, planOwnFiles, planOwnFilesR2, planOwnJobs, planOwnMail, } from './own-diff.js';
7
7
  export { OWN_SFU_BLOCKED_KEY, OWN_SFU_FIREWALL_KEY, planOwnSfu } from './own-diff.js';
@@ -26,6 +26,9 @@ export { createZitadelProjectRoles } from './zitadel-project-roles.js';
26
26
  // implements over held keys and its own SSH client, the same shape the rest
27
27
  // of `platform-providers.ts` uses for Cloudflare.
28
28
  export { DumpError, dumpNow } from './database-dump.js';
29
+ export { STAGE_SINK_APPLIED_SCOPE_KEY, STAGE_SINK_IMAGE_REF, STAGE_SINK_SMTP_PORT, stageMailEnv, stageSinkAppName, stageSinkInternalUrl, } from './stage-sink.js';
30
+ export { STAGE_COPY_EXCLUDED_TABLES, StageCopyFailedError, StageCopyRefusedError, stageCopy, tableExcluded, undoStageCopy, } from './stage-copy.js';
31
+ export { StageRestoreError, StageRestoreRefusedError, createStageCopyPort, execRunner, } from './stage-copy-port.js';
29
32
  export { MissingCallsSfuConnectionError, applyCallsSfuPlatformStep, callsSfuAppliedFingerprint, } from './platform-sfu.js';
30
33
  export { MAIL_COPY_COMPLETED_SCOPE_KEY, MAIL_COPY_DONE_SCOPE_KEY, MissingMailCopyAccountsError, MissingMailCopySourceTokenError, MissingMailCopyStalwartTokenError, parseMailCopyCompleted, runMailCopyStep, } from './mail-copy.js';
31
34
  export { ProvidersAiReader, ProvidersCloudflareReader, ProvidersCmsReader, ProvidersCoolifyReader, ProvidersZitadelReader, storeLoginHostResolver, storeScopeResolver, storeRecordedIds, } from './providers-readers.js';
@@ -42,7 +42,7 @@ export interface LiveResource {
42
42
  * see that function's own doc comment for why "always planned" broke
43
43
  * `bootstrapPlatform`.
44
44
  */
45
- system: 'zitadel' | 'coolify' | 'cloudflare' | 'files' | 'ai' | 'cms' | 'jobs' | 'sfu' | 'edge' | 'heartbeats';
45
+ system: 'zitadel' | 'coolify' | 'cloudflare' | 'files' | 'ai' | 'cms' | 'jobs' | 'sfu' | 'edge' | 'heartbeats' | 'github';
46
46
  kind: string;
47
47
  key: string;
48
48
  config: Record<string, unknown>;
@@ -219,6 +219,8 @@ export interface StepExecutor {
219
219
  usable: boolean;
220
220
  reachable: boolean;
221
221
  }>>;
222
+ /** Whether the company's stage mail sink app (by Coolify id) is stopped or gone, read live. Optional: an executor without it reads the sink as up. */
223
+ stageSinkDown?(appId: string): Promise<boolean>;
222
224
  /**
223
225
  * The release runner's outside calls for one blue/green entry (`plan/release-host.ts`); `null` while its blue
224
226
  * copy is not recorded. Optional: an executor without it runs no release.
@@ -1313,6 +1313,10 @@ export class FoundryPlanApply {
1313
1313
  const blueGreenServers = declaresBlueGreen(org) && this.executor.blueGreenServers
1314
1314
  ? await this.executor.blueGreenServers().catch(() => undefined)
1315
1315
  : undefined;
1316
+ const sinkId = recorded.stage_sink_app;
1317
+ const stageSinkDown = sinkId && recorded.stage_sink_applied && declaresBlueGreen(org) && this.executor.stageSinkDown
1318
+ ? await this.executor.stageSinkDown(sinkId).catch(() => false)
1319
+ : false;
1316
1320
  const detail = computePlanDetail(org, live, applied?.serviceIds ?? {}, agoraHost, this.jobsScheduler, platformReadiness, {
1317
1321
  loginHostBindings: this.loginHostBindings,
1318
1322
  loginHostClientOrganizations: this.loginHostClientOrganizations,
@@ -1343,6 +1347,7 @@ export class FoundryPlanApply {
1343
1347
  customersDirectory: this.executor.customersDirectoryAvailable?.() ?? false,
1344
1348
  bouleArchonCredential: this.executor.bouleArchonCredentialAvailable?.() ?? false,
1345
1349
  ...(blueGreenServers ? { blueGreenServers } : {}),
1350
+ ...(stageSinkDown ? { stageSinkDown } : {}),
1346
1351
  ...(blueGreenServers && org.hosting.entries.some((e) => e.blueGreen && e.database)
1347
1352
  ? {
1348
1353
  remoteDatabase: remoteDatabaseFactsFrom({
@@ -2137,9 +2142,9 @@ function destroyStepDescriptions(targets) {
2137
2142
  'delete the declared org',
2138
2143
  ];
2139
2144
  }
2140
- /** Scope keys of the Coolify apps blue/green made: `bg.<entry>.app.<server>.<part>`, a database sidecar, a connector on another server. */
2141
- const BLUE_GREEN_APP_KEY = /^(bg\.[^.:]+\.app\.[^.:]+\.[a-z]+|bgdb\.[^.:]+\.sidecar\.[^.:]+|cloudflare_tunnel_connector_app\.[^.:]+)$/;
2142
- const BLUE_GREEN_DATABASE_KEY = /^bg\.[^.:]+\.stagedb$/;
2145
+ /** Scope keys of the Coolify apps blue/green made: `bg.<entry>.app.<server>.<part>`, a database sidecar, a connector on another server, the company's stage mail sink (`stage_sink_app`). */
2146
+ const BLUE_GREEN_APP_KEY = /^(bg\.[^.:]+\.app\.[^.:]+\.[a-z]+|bgdb\.[^.:]+\.sidecar\.[^.:]+|cloudflare_tunnel_connector_app\.[^.:]+|stage_sink_app)$/;
2147
+ const BLUE_GREEN_DATABASE_KEY = /^bg\.[^.:]+\.(stagedb|stagekept)$/;
2143
2148
  /** Stage's Access gate (`bg.<entry>.stagegate`), and the database route's Cloudflare parts: its Access app, its service token (also one minted and never delivered) and its DNS record (recorded as the route). */
2144
2149
  const BLUE_GREEN_EDGE_KEYS = [
2145
2150
  [/^bgdb\.[^.:]+\.access$/, 'bg-access'],
@@ -151,6 +151,13 @@ export declare const PLATFORM_ARCHON_INTEGRATIONS_KEY_SYNCED_SCOPE_KEY = "archon
151
151
  * values until someone redeploys by hand (#467).
152
152
  */
153
153
  export declare const PLATFORM_ARCHON_ENVS_DEPLOYED_SCOPE_KEY = "archon_envs_deployed_hash";
154
+ /**
155
+ * The sha256 of the `GITHUB_RELEASE_WEBHOOK_SECRET` Archon last deployed with, recorded by
156
+ * `platform:archon` after its deploy (never the secret). `driftedSteps` plans `platform:archon` again
157
+ * while the live secret is missing or hashes differently: the release hook step writes the secret into
158
+ * Coolify and nothing else redeploys an applied Archon.
159
+ */
160
+ export declare const PLATFORM_ARCHON_WEBHOOK_SECRET_DEPLOYED_SCOPE_KEY = "archon_webhook_secret_deployed_sha256";
154
161
  /**
155
162
  * The uuid of the deployment Archon's step triggered without waiting
156
163
  * (`PlatformArchonDeps.runsInsideApp`), `pending` between the trigger and the
@@ -412,6 +419,29 @@ export declare const PLATFORM_ARCHON_MASTER_CLOUDFLARE_TOKEN_REF = "platform:mas
412
419
  * already holds the same panel's address.
413
420
  */
414
421
  export declare const PLATFORM_ARCHON_COOLIFY_READ_TOKEN_REF = "platform:archon:coolify-read-token";
422
+ /**
423
+ * The held key (tenant `platform`) of a fine-grained GitHub token for the `wtfalch`
424
+ * organisation with Webhooks read and write. Foundry only reads it back; a person holds it in
425
+ * Archon, Shared, Keys. Until it is held, the `platform:github-release-hook` step is reported
426
+ * blocked and nothing else is.
427
+ */
428
+ export declare const PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF = "platform:github:org-hooks-token";
429
+ /** Archon's env name for the secret GitHub signs release webhooks with. Minted once by `platform:archon`, never rotated. */
430
+ export declare const GITHUB_RELEASE_WEBHOOK_SECRET_ENV = "GITHUB_RELEASE_WEBHOOK_SECRET";
431
+ /** The GitHub organisation whose release webhook `platform:github-release-hook` makes. */
432
+ export declare const GITHUB_RELEASE_HOOK_ORG = "wtfalch";
433
+ /** Archon's route that takes release webhooks, under its public host. */
434
+ export declare const GITHUB_RELEASE_HOOK_PATH = "/api/github/releases";
435
+ /** The step key. */
436
+ export declare const PLATFORM_GITHUB_RELEASE_HOOK_KEY = "platform:github-release-hook";
437
+ /** Scope key: the id of the organisation hook the step made or adopted. */
438
+ export declare const PLATFORM_GITHUB_RELEASE_HOOK_ID_SCOPE_KEY = "github_release_hook_id";
439
+ /** Scope key: the hash of the hook's url and secret as last written. The secret itself is never recorded. */
440
+ export declare const PLATFORM_GITHUB_RELEASE_HOOK_HASH_SCOPE_KEY = "github_release_hook_hash";
441
+ /** Why the step is blocked while Archon's env cannot be read from Coolify. */
442
+ export declare const GITHUB_RELEASE_HOOK_COOLIFY_READ_FAILED = "the GitHub release webhook is blocked, not planned: could not read Archon's env from Coolify";
443
+ /** Why the step is blocked while the token is not held. */
444
+ export declare const GITHUB_RELEASE_HOOK_TOKEN_MISSING = "the GitHub release webhook is blocked, not planned: hold the GitHub organisation webhooks token in Archon, Shared, Keys";
415
445
  /**
416
446
  * #169: `platform:<service>` for the platform's own mail server (Stalwart),
417
447
  * mirroring {@link PLATFORM_AUTH_KEY} exactly.
@@ -1248,6 +1278,14 @@ export interface PlanPlatformOptions {
1248
1278
  pending: boolean;
1249
1279
  blocked?: string;
1250
1280
  };
1281
+ /** Why the organisation's release webhook step cannot run (the token is not held), or absent. */
1282
+ githubReleaseHook?: string;
1283
+ /**
1284
+ * The token is held: the step may plan, also in the apply that makes Archon.
1285
+ */
1286
+ githubReleaseHookReady?: boolean;
1287
+ /** The hash of the hook's url and Archon's live webhook secret now (`githubReleaseHookHash`). Absent while Archon holds no secret. */
1288
+ githubReleaseHookHash?: string;
1251
1289
  /** Why Archon's step must wait: the deployment it triggered is still running. Blocks even an applied step. */
1252
1290
  archonDeployRunning?: string;
1253
1291
  /**
@@ -1448,6 +1486,27 @@ export declare const PLATFORM_INTEGRATIONS_KEY_ROTATION_PREVIOUS_SCOPE_KEY = "in
1448
1486
  * `''`) as soon as the mint is recorded, so one request is one rotation.
1449
1487
  */
1450
1488
  export declare const PLATFORM_INTEGRATIONS_KEY_ROTATION_REQUESTED_SCOPE_KEY = "integrations_management_key_rotation_requested";
1489
+ /**
1490
+ * foundry#542: the uptime Worker, one `cloudflare:worker` step. Blocked, not
1491
+ * planned (rule 2), while no artifact is pinned, Archon is not applied, the
1492
+ * executor lacks its dependencies, a Worker or Access token of the name exists
1493
+ * that foundry did not make. A lost Worker token or Access pair is not a
1494
+ * block: the step is planned and repairs it (rule 4). Planned again when the
1495
+ * pinned tag or sha256, the Archon hostname (`ARCHON_BASE_URL`), the plain
1496
+ * text variables or the set of secrets that can be set changed (rule 3), or
1497
+ * when a half-made deploy never recorded its applied values; it mints nothing
1498
+ * that is already held. When the platform no longer enables the Worker, a
1499
+ * destructive step removes whatever of it is recorded (edge removes its KV
1500
+ * namespace with the script).
1501
+ *
1502
+ * The returned `blocked` lines are reported in `unmanaged`. A secret whose
1503
+ * source does not exist yet blocks nothing: the step still delivers
1504
+ * everything that exists, so it comes back in `notes`.
1505
+ */
1506
+ /** The hash of a hook's url and secret. The planner and the step both compute it, and it is the only trace of the secret that is recorded. */
1507
+ export declare function githubReleaseHookHash(url: string, secret: string): string;
1508
+ /** The url GitHub delivers release webhooks to. */
1509
+ export declare function githubReleaseHookUrl(hostname: string): string;
1451
1510
  /**
1452
1511
  * #175: Archon (https://github.com/wtfalch/archon), the one shared console,
1453
1512
  * built fresh at `platform.archon.hostname` (`archon.<apex>`) rather than the
@@ -190,6 +190,13 @@ export const PLATFORM_ARCHON_INTEGRATIONS_KEY_SYNCED_SCOPE_KEY = 'archon_integra
190
190
  * values until someone redeploys by hand (#467).
191
191
  */
192
192
  export const PLATFORM_ARCHON_ENVS_DEPLOYED_SCOPE_KEY = 'archon_envs_deployed_hash';
193
+ /**
194
+ * The sha256 of the `GITHUB_RELEASE_WEBHOOK_SECRET` Archon last deployed with, recorded by
195
+ * `platform:archon` after its deploy (never the secret). `driftedSteps` plans `platform:archon` again
196
+ * while the live secret is missing or hashes differently: the release hook step writes the secret into
197
+ * Coolify and nothing else redeploys an applied Archon.
198
+ */
199
+ export const PLATFORM_ARCHON_WEBHOOK_SECRET_DEPLOYED_SCOPE_KEY = 'archon_webhook_secret_deployed_sha256';
193
200
  /**
194
201
  * The uuid of the deployment Archon's step triggered without waiting
195
202
  * (`PlatformArchonDeps.runsInsideApp`), `pending` between the trigger and the
@@ -464,6 +471,29 @@ export const PLATFORM_ARCHON_MASTER_CLOUDFLARE_TOKEN_REF = 'platform:master:clou
464
471
  * already holds the same panel's address.
465
472
  */
466
473
  export const PLATFORM_ARCHON_COOLIFY_READ_TOKEN_REF = 'platform:archon:coolify-read-token';
474
+ /**
475
+ * The held key (tenant `platform`) of a fine-grained GitHub token for the `wtfalch`
476
+ * organisation with Webhooks read and write. Foundry only reads it back; a person holds it in
477
+ * Archon, Shared, Keys. Until it is held, the `platform:github-release-hook` step is reported
478
+ * blocked and nothing else is.
479
+ */
480
+ export const PLATFORM_GITHUB_ORG_HOOKS_TOKEN_REF = 'platform:github:org-hooks-token';
481
+ /** Archon's env name for the secret GitHub signs release webhooks with. Minted once by `platform:archon`, never rotated. */
482
+ export const GITHUB_RELEASE_WEBHOOK_SECRET_ENV = 'GITHUB_RELEASE_WEBHOOK_SECRET';
483
+ /** The GitHub organisation whose release webhook `platform:github-release-hook` makes. */
484
+ export const GITHUB_RELEASE_HOOK_ORG = 'wtfalch';
485
+ /** Archon's route that takes release webhooks, under its public host. */
486
+ export const GITHUB_RELEASE_HOOK_PATH = '/api/github/releases';
487
+ /** The step key. */
488
+ export const PLATFORM_GITHUB_RELEASE_HOOK_KEY = 'platform:github-release-hook';
489
+ /** Scope key: the id of the organisation hook the step made or adopted. */
490
+ export const PLATFORM_GITHUB_RELEASE_HOOK_ID_SCOPE_KEY = 'github_release_hook_id';
491
+ /** Scope key: the hash of the hook's url and secret as last written. The secret itself is never recorded. */
492
+ export const PLATFORM_GITHUB_RELEASE_HOOK_HASH_SCOPE_KEY = 'github_release_hook_hash';
493
+ /** Why the step is blocked while Archon's env cannot be read from Coolify. */
494
+ export const GITHUB_RELEASE_HOOK_COOLIFY_READ_FAILED = "the GitHub release webhook is blocked, not planned: could not read Archon's env from Coolify";
495
+ /** Why the step is blocked while the token is not held. */
496
+ export const GITHUB_RELEASE_HOOK_TOKEN_MISSING = 'the GitHub release webhook is blocked, not planned: hold the GitHub organisation webhooks token in Archon, Shared, Keys';
467
497
  /**
468
498
  * #169: `platform:<service>` for the platform's own mail server (Stalwart),
469
499
  * mirroring {@link PLATFORM_AUTH_KEY} exactly.
@@ -1441,8 +1471,25 @@ export function planPlatform(platform, live, options = {}) {
1441
1471
  step: { description: archonBg.step.description, destroys: false, migrates: false },
1442
1472
  });
1443
1473
  }
1444
- if (archon.step && blocked.archonRunsInsideApp)
1474
+ let releaseHook;
1475
+ // The hook step makes the secret itself, so with the app recorded it goes before a last-placed
1476
+ // platform:archon (the host redeploys itself there and would stop before a later step). Without the
1477
+ // app it goes after platform:archon, which makes the app.
1478
+ if (archon.step && blocked.archonRunsInsideApp) {
1479
+ const hookFirst = Boolean(recordedIds[resourceKey('coolify', 'app', PLATFORM_ARCHON_KEY)]);
1480
+ const hookStep = () => planGithubReleaseHook(platform, recordedIds, blocked.githubReleaseHook, blocked.githubReleaseHookReady ?? false, blocked.githubReleaseHookHash, true);
1481
+ releaseHook = hookStep();
1482
+ if (hookFirst && releaseHook.step)
1483
+ plannedSteps.push(releaseHook.step);
1445
1484
  plannedSteps.push(archon.step);
1485
+ if (!hookFirst && releaseHook.step)
1486
+ plannedSteps.push(releaseHook.step);
1487
+ }
1488
+ else {
1489
+ releaseHook = planGithubReleaseHook(platform, recordedIds, blocked.githubReleaseHook, blocked.githubReleaseHookReady ?? false, blocked.githubReleaseHookHash, Boolean(archon.step));
1490
+ if (releaseHook.step)
1491
+ plannedSteps.push(releaseHook.step);
1492
+ }
1446
1493
  // After Archon's own step: a repair that fails must not hold up the work before it.
1447
1494
  const idTokenUserinfo = planArchonIdTokenUserinfo(platform, recordedIds, blocked.archonIdTokenUserinfo ?? false);
1448
1495
  if (idTokenUserinfo)
@@ -1575,6 +1622,9 @@ export function planPlatform(platform, live, options = {}) {
1575
1622
  unmanaged.push({ description: heartbeats.blocked, key: 'heartbeats' });
1576
1623
  for (const description of uptime.blocked)
1577
1624
  unmanaged.push({ description, key: 'uptime' });
1625
+ if (releaseHook.blocked) {
1626
+ unmanaged.push({ description: releaseHook.blocked, key: 'github-release-hook' });
1627
+ }
1578
1628
  return {
1579
1629
  plannedSteps: plannedSteps.map(withStepSystem),
1580
1630
  unmanaged,
@@ -2932,6 +2982,53 @@ function planHeartbeats(platform, recordedIds, hcReady, executorMissing, apiKeyM
2932
2982
  * source does not exist yet blocks nothing: the step still delivers
2933
2983
  * everything that exists, so it comes back in `notes`.
2934
2984
  */
2985
+ /** The hash of a hook's url and secret. The planner and the step both compute it, and it is the only trace of the secret that is recorded. */
2986
+ export function githubReleaseHookHash(url, secret) {
2987
+ return createHash('sha256').update(`${url}\n${secret}`).digest('hex');
2988
+ }
2989
+ /** The url GitHub delivers release webhooks to. */
2990
+ export function githubReleaseHookUrl(hostname) {
2991
+ return `https://${hostname}${GITHUB_RELEASE_HOOK_PATH}`;
2992
+ }
2993
+ /**
2994
+ * The organisation's release webhook, once the token is held and Archon is applied or planned in this
2995
+ * same plan (`platform:archon` runs first and mints the secret). Planned when no hook is recorded, or the
2996
+ * recorded hash of (url, secret) differs from the one now.
2997
+ * Blocked, not planned, while the token is not held; nothing else is held back by that.
2998
+ */
2999
+ function planGithubReleaseHook(platform, recordedIds, executorBlocked, tokenHeld, currentHash, archonPlanned) {
3000
+ if (!platform.archon.enabled)
3001
+ return { step: null, blocked: null };
3002
+ if (!recordedIds[resourceKey('coolify', 'app', PLATFORM_ARCHON_KEY)] && !archonPlanned) {
3003
+ return { step: null, blocked: null };
3004
+ }
3005
+ if (executorBlocked)
3006
+ return { step: null, blocked: executorBlocked };
3007
+ if (!tokenHeld)
3008
+ return { step: null, blocked: null };
3009
+ if (currentHash &&
3010
+ recordedIds[PLATFORM_GITHUB_RELEASE_HOOK_ID_SCOPE_KEY] &&
3011
+ recordedIds[PLATFORM_GITHUB_RELEASE_HOOK_HASH_SCOPE_KEY] === currentHash) {
3012
+ return { step: null, blocked: null };
3013
+ }
3014
+ const url = githubReleaseHookUrl(platform.archon.hostname);
3015
+ return {
3016
+ step: {
3017
+ action: {
3018
+ system: 'github',
3019
+ kind: 'release-hook',
3020
+ key: PLATFORM_GITHUB_RELEASE_HOOK_KEY,
3021
+ desired: { org: GITHUB_RELEASE_HOOK_ORG, url, events: ['release'] },
3022
+ },
3023
+ step: {
3024
+ description: `make the ${GITHUB_RELEASE_HOOK_ORG} organisation's release webhook to ${url}`,
3025
+ destroys: false,
3026
+ migrates: false,
3027
+ },
3028
+ },
3029
+ blocked: null,
3030
+ };
3031
+ }
2935
3032
  function planUptime(platform, recordedIds, executorBlocked, heldOptional, archonApplied, uptimeHeld = {
2936
3033
  token: true,
2937
3034
  access: true,
@@ -21,6 +21,7 @@ import { type BrokerDeployRecord, PLATFORM_ZITADEL_ORG_SCOPE_KEY } from './platf
21
21
  import type { PlatformOwnerInput } from './platform-org.js';
22
22
  import type { SigninDbBackupPort } from './signin-db-backup.js';
23
23
  export { PLATFORM_ZITADEL_ORG_SCOPE_KEY };
24
+ import { type PlatformGithubReleaseHookDeps } from './github-release-hook.js';
24
25
  import { type CallsSfuPlatformDeps } from './platform-sfu.js';
25
26
  import { type PlatformUptimeDeps } from './uptime-worker.js';
26
27
  /** The key `runPlatformSteps` records the apex zone's id under (`system:kind:key`). */
@@ -324,6 +325,11 @@ export interface FoundryPlatformStepExecutorOptions {
324
325
  * unset, the step is reported blocked.
325
326
  */
326
327
  oikosIngress?: PlatformOikosIngressDeps;
328
+ /**
329
+ * The `github:release-hook` step. Optional like `auth`; without it the step is not planned and
330
+ * nothing is reported.
331
+ */
332
+ githubReleaseHook?: PlatformGithubReleaseHookDeps;
327
333
  }
328
334
  export declare class FoundryPlatformStepExecutor implements PlatformStepExecutor {
329
335
  private readonly cloudflare;
@@ -345,6 +351,7 @@ export declare class FoundryPlatformStepExecutor implements PlatformStepExecutor
345
351
  private readonly uptime?;
346
352
  private readonly accessProvider?;
347
353
  private readonly oikosIngress?;
354
+ private readonly githubReleaseHook?;
348
355
  constructor(cloudflare: Pick<CloudflarePort, 'findZoneByApex' | 'createZone'>, declaredOrgStore: Pick<DeclaredOrgStore, 'findOrgIdForZone' | 'list' | 'get'>, options?: FoundryPlatformStepExecutorOptions);
349
356
  private readonly platformPorts;
350
357
  /** The port placed on the platform's destination, made once per port so a server is listed once. */
@@ -388,6 +395,9 @@ export declare class FoundryPlatformStepExecutor implements PlatformStepExecutor
388
395
  pending: boolean;
389
396
  blocked?: string;
390
397
  };
398
+ githubReleaseHook?: string;
399
+ githubReleaseHookReady?: boolean;
400
+ githubReleaseHookHash?: string;
391
401
  archonRunsInsideApp?: boolean;
392
402
  archonDeployRunning?: string;
393
403
  archonIdTokenUserinfo?: boolean;