@bongos/core 1.19.1080 → 1.19.1081

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 (31) hide show
  1. package/.bongos-core.json +78 -28
  2. package/clients/bongos-client/README.md +1 -1
  3. package/clients/bongos-client/bongos-client.global.js +2 -0
  4. package/clients/bongos-client/index.cjs +2 -0
  5. package/clients/bongos-client/index.d.ts +4 -0
  6. package/clients/bongos-client/index.mjs +2 -0
  7. package/docs/adr/0343-a-module-score-is-a-security-gate-then-an-average-of-visible-parts.md +2 -0
  8. package/docs/adr/0347-every-store-module-ships-a-how-to.md +135 -0
  9. package/docs/adr/README.md +1 -0
  10. package/docs/api/openapi.json +126 -3
  11. package/docs/api-reference.md +3 -2
  12. package/docs/module-api-changelog.md +2 -0
  13. package/modules/provisioning/migrations/provisioning_028_render_standup.sql +46 -0
  14. package/modules/provisioning/module.json +2 -1
  15. package/modules/provisioning/provisioning.js +5 -5
  16. package/modules/provisioning/render-standup.js +91 -0
  17. package/modules/provisioning/routes/render-standup.js +90 -0
  18. package/package-lock.json +2 -2
  19. package/package.json +1 -1
  20. package/release-notes.json +10 -0
  21. package/scripts/gds/provision-render.js +158 -0
  22. package/scripts/gds/provision-teardown.js +2 -0
  23. package/scripts/gds/provision.js +2 -2
  24. package/scripts/gds/render-api.js +178 -0
  25. package/scripts/gds/render-payload.js +110 -0
  26. package/src/module-api.js +1 -1
  27. package/tests/provision_render.mjs +269 -0
  28. package/tests/provisioning_render_route.mjs +216 -0
  29. package/tests/provisioning_settings_apply.mjs +1 -1
  30. package/tests/provisioning_teardown_intent.mjs +2 -2
  31. package/tests/render_api.mjs +153 -0
@@ -0,0 +1,158 @@
1
+ 'use strict';
2
+ // provision-render.js — the Render standup leg: the runner half of the `render-standup`
3
+ // intent (task 1004183; ADR 0327, ADR 0345). Its own file because provision.js sits at
4
+ // the size ratchet; the dispatch there requires it inline.
5
+ //
6
+ // WHAT IT DOES. Stands a project up on its OWNER's Render account, with a key the owner
7
+ // lent for this one run:
8
+ // - ADOPT links a Render service the owner already runs. It reads that service through
9
+ // the workspace guard and records it. It makes NO write call to their account.
10
+ // - GREENFIELD creates the Postgres and the web service (render-payload.js decides what
11
+ // they are), sets the env vars that need the service's URL, and asks for a deploy.
12
+ // Ids are written to the row as each resource is created, so an owner who re-enters their
13
+ // key after a failure resumes onto what already exists instead of creating a second one.
14
+ //
15
+ // THE KEY IS BORROWED, NEVER STORED (ADR 0327 §2). It reaches this leg encrypted on the
16
+ // intent (provisioning_intents.borrowed_key_enc). It is decrypted here, used for this run
17
+ // only, and the column is cleared in a `finally` — on success, on a refusal and on a
18
+ // throw. resolveIntent clears it again, and the table's CHECK refuses a resolved intent
19
+ // that still holds one. What the encryption buys, said plainly: it protects the key from
20
+ // a database dump or a nightly backup while the intent waits. It does NOT defend against
21
+ // a compromised web tier — the key arrives there in plaintext before anything can
22
+ // encrypt it.
23
+ //
24
+ // A FAILURE IS TERMINAL. Every failure returns `terminal: true`, so the runner retires the
25
+ // intent instead of re-queuing it. There is no key left to retry with, and an unattended
26
+ // retry holding someone else's cloud credential is not a thing this platform does: the
27
+ // owner retries by entering their key again.
28
+ //
29
+ // Every Render call goes through scripts/gds/render-api.js, which pins the workspace and
30
+ // asserts it on every response, and which cannot delete.
31
+
32
+ const { RenderApi } = require('./render-api.js');
33
+ const payload = require('./render-payload.js');
34
+ const { parseTargetRef } = require('./provision-repo-auth.js');
35
+ const { provisionedEnvPrefix } = require('./provision-units.js');
36
+
37
+ // A key waiting longer than this was lent for a run that never came. It is refused and
38
+ // cleared rather than spent late.
39
+ const KEY_TTL_MS = 30 * 60 * 1000;
40
+
41
+ function renderApiFor(deps, token, ownerId) {
42
+ if (deps.renderApiFactory) return deps.renderApiFactory({ token, ownerId });
43
+ return new RenderApi({ token, ownerId, dryRun: !deps.apply, fetchImpl: deps.fetchImpl, log: deps.log });
44
+ }
45
+
46
+ // Merge `patch` into the row's app_host. The runner is the only writer while an intent
47
+ // runs, and the web tier only writes it when enqueuing, which the open-intent index
48
+ // serialises — so a merge needs no read-modify-write.
49
+ async function recordAppHost(db, instId, patch) {
50
+ await db.query(
51
+ `UPDATE provisioning_instances SET app_host = COALESCE(app_host, '{}'::jsonb) || $2::jsonb WHERE id = $1`,
52
+ [instId, JSON.stringify({ ...patch, updatedAt: new Date().toISOString() })]);
53
+ }
54
+
55
+ async function clearBorrowedKey(db, intentId) {
56
+ await db.query(`UPDATE provisioning_intents SET borrowed_key_enc = NULL WHERE id = $1`, [intentId]);
57
+ }
58
+
59
+ async function ownerLoginOf(db, inst) {
60
+ if (!inst.owner_builder_id) return null;
61
+ const { rows } = await db.query(`SELECT github_login FROM builders WHERE id = $1`, [inst.owner_builder_id]);
62
+ return (rows[0] && rows[0].github_login) || null;
63
+ }
64
+
65
+ async function adopt(api, inst, host, { db, log }) {
66
+ if (!host.serviceId) throw new Error('adopting needs the id of the Render service to link');
67
+ const svc = await api.getService(host.serviceId);
68
+ const url = (svc.serviceDetails && svc.serviceDetails.url) || null;
69
+ await recordAppHost(db, inst.id, { state: 'linked', serviceUrl: url, error: null });
70
+ log(` [render] linked ${inst.slug} to service ${svc.id}${url ? ` (${url})` : ''} — nothing created or changed on Render`);
71
+ return { ok: true };
72
+ }
73
+
74
+ async function greenfield(api, inst, host, deps) {
75
+ const { db, log } = deps;
76
+ const plans = payload.plansFor(host);
77
+ const repo = parseTargetRef(inst.target_ref);
78
+ if (!repo) throw new Error('the project has no GitHub repository for Render to build from');
79
+ const envPrefix = deps.envPrefix || provisionedEnvPrefix();
80
+
81
+ // 1. The database — reused if a previous run got this far.
82
+ let pg = host.postgresId ? await api.getPostgres(host.postgresId) : null;
83
+ if (!pg) {
84
+ pg = await api.createPostgres(payload.renderPostgresPayload(inst, { ownerId: api.ownerId, dbPlan: plans.dbPlan, region: plans.region }));
85
+ await recordAppHost(db, inst.id, { postgresId: pg.id, dbPlan: plans.dbPlan, state: 'creating' });
86
+ log(` [render] created database ${pg.id} (${plans.dbPlan})`);
87
+ }
88
+ await api.settlePostgres(pg.id, { sleepFn: deps.sleepFn });
89
+ const conn = await api.postgresConnectionInfo(pg.id);
90
+ const dbUrl = conn && conn.internalConnectionString;
91
+ if (!dbUrl) throw new Error(`Render gave database ${pg.id} no internal connection string`);
92
+
93
+ // 2. The web service — reused likewise.
94
+ let svc = host.serviceId ? await api.getService(host.serviceId) : null;
95
+ if (!svc) {
96
+ const firstAdmin = (await ownerLoginOf(db, inst)) || repo.owner;
97
+ const created = await api.createService(payload.renderServicePayload(inst, {
98
+ ownerId: api.ownerId, repoUrl: `https://github.com/${repo.owner}/${repo.name}`, branch: host.branch,
99
+ webPlan: plans.webPlan, region: plans.region, dbUrl, secretKey: payload.freshSecretKey(), envPrefix, firstAdmin,
100
+ }));
101
+ svc = created.service;
102
+ await recordAppHost(db, inst.id, { serviceId: svc.id, webPlan: plans.webPlan, region: plans.region, state: 'creating' });
103
+ log(` [render] created web service ${svc.id} (${plans.webPlan})`);
104
+ }
105
+ const url = (svc.serviceDetails && svc.serviceDetails.url) || null;
106
+
107
+ // 3. What needs the URL, then one deploy that picks it all up.
108
+ for (const { key, value } of payload.renderAfterCreateEnv(url, { envPrefix })) await api.putEnvVar(svc.id, key, value);
109
+ await api.triggerDeploy(svc.id);
110
+ await recordAppHost(db, inst.id, { state: 'deploying', serviceUrl: url, error: null });
111
+ log(` [render] ${inst.slug} is deploying at ${url}`);
112
+ return { ok: true };
113
+ }
114
+
115
+ async function renderStandupInstance(inst, deps, intent) {
116
+ const { db, log } = deps;
117
+ const secretBox = deps.secretBox || require('../../src/bongos/secret-box');
118
+ const host = inst.app_host || {};
119
+ try {
120
+ if (!intent || !intent.borrowed_key_enc) return refuse('no Render key came with this request — enter it again to retry');
121
+ if (host.platform !== 'render') return refuse(`this project's app is not set to run on Render (platform '${host.platform || 'none'}')`);
122
+ if (!host.ownerId) return refuse('no Render workspace was chosen');
123
+ const age = Date.now() - new Date(intent.created_at || 0).getTime();
124
+ if (!(age < KEY_TTL_MS)) return refuse('the Render key waited too long to be used and was cleared — enter it again to retry');
125
+ if (host.mode !== 'adopt' && host.mode !== 'greenfield') return refuse(`unknown Render setup mode '${host.mode}'`);
126
+
127
+ const api = renderApiFor(deps, secretBox.decrypt(intent.borrowed_key_enc), host.ownerId);
128
+ // Membership, never selection: the workspace is the one the owner named, and it must
129
+ // be one this key can act in.
130
+ const owners = await api.listOwners();
131
+ if (!owners.some((o) => o.id === host.ownerId)) return refuse(`this Render key cannot reach workspace ${host.ownerId}`);
132
+
133
+ return host.mode === 'adopt' ? await adopt(api, inst, host, deps) : await greenfield(api, inst, host, deps);
134
+ } catch (e) {
135
+ return refuse(e && e.message ? e.message : String(e));
136
+ } finally {
137
+ if (intent && intent.id != null) await clearBorrowedKey(db, intent.id);
138
+ }
139
+
140
+ async function refuse(error) {
141
+ await recordAppHost(db, inst.id, { state: 'failed', error }).catch(() => {});
142
+ log(` ✖ [render] ${inst.slug}: ${error}`);
143
+ return { ok: false, terminal: true, error };
144
+ }
145
+ }
146
+
147
+ // Teardown's half (ADR 0327 §3): forget the Render app, never delete it. The ids stay on
148
+ // the row so an operator can still say which services were the project's; the owner
149
+ // deletes them in their own Render dashboard if they want to stop paying.
150
+ async function forgetRenderApp(inst, { db, log, apply }) {
151
+ const host = inst.app_host;
152
+ if (!host || host.platform !== 'render') return;
153
+ const what = [host.serviceId && `service ${host.serviceId}`, host.postgresId && `database ${host.postgresId}`].filter(Boolean).join(' and ') || 'nothing yet';
154
+ log(` [render] ${apply ? 'disconnected' : 'would disconnect'} from Render (${what}); nothing on Render is deleted — the owner removes it in their own dashboard`);
155
+ if (apply) await recordAppHost(db, inst.id, { state: 'disconnected' });
156
+ }
157
+
158
+ module.exports = { renderStandupInstance, forgetRenderApp, clearBorrowedKey, recordAppHost, KEY_TTL_MS };
@@ -42,6 +42,8 @@ async function teardownInstance(inst, deps) {
42
42
  await deps.doApi.deleteDroplet(inst.droplet_id);
43
43
  }
44
44
  parkAddress(inst, { controlExec, log, apply });
45
+ // The app's Render services are the OWNER's: forget them, never delete them (ADR 0327 §3, task 1004183).
46
+ await require('./provision-render.js').forgetRenderApp(inst, { db, log, apply });
45
47
  // Revoke the instance's deploy key (ADR 0176) and remove its local halves. The
46
48
  // checkout itself is deliberately left in place (data is precious), so the key
47
49
  // files must NOT ride along — and a revoke skip must be LOUD: a torn-down project
@@ -1293,10 +1293,10 @@ async function cmdRunIntents(deps) {
1293
1293
  else if (intent.action === 'disconnect') result = await disconnectInstance(inst, deps);
1294
1294
  else if (intent.action === 'core-upgrade') result = await coreUpgradeInstance(inst, deps, intent); // also reads the INTENT: the version the owner previewed (ADR 0293 D4)
1295
1295
  else if (intent.action === 'core-upgrade-preflight') result = await preflightCoreUpgrade(inst, deps, intent); // changes nothing; caches what the move WOULD say (task 1004121)
1296
- else if (intent.action === 'repo-private') result = await require('./provision-repo-private.js').repoPrivateInstance(inst, deps); // wire the deploy key, THEN flip (task 1004193); required here — this file is at the size ratchet
1296
+ else if (intent.action === 'repo-private' || intent.action === 'render-standup') result = intent.action === 'repo-private' ? await require('./provision-repo-private.js').repoPrivateInstance(inst, deps) : await require('./provision-render.js').renderStandupInstance(inst, deps, intent); // wire the deploy key, THEN flip (task 1004193) · spend the borrowed Render key once (task 1004183); required here — this file is at the size ratchet
1297
1297
  else result = { ok: false, error: `unknown_action '${intent.action}' — runner core ${coreVersionSafe() || '?'} does not know it (runner too old?); refusing to guess` };
1298
1298
  if (result && result.ok === false) {
1299
- if (intent.attempts >= MAX_INTENT_ATTEMPTS) {
1299
+ if (intent.attempts >= MAX_INTENT_ATTEMPTS || result.terminal) { // terminal: a leg that must not be retried unattended (the Render leg's key is already gone — task 1004183)
1300
1300
  await provisioning.resolveIntent(db, intent.id, 'error', result.error || 'op failed');
1301
1301
  // A retired intent stops silently otherwise (F19): record the reason
1302
1302
  // on the instance WITHOUT changing its lifecycle status — passing the
@@ -0,0 +1,178 @@
1
+ // scripts/gds/render-api.js — a thin Render API v1 client for the control plane, with
2
+ // the workspace (ownerId) guard (task 1004183; ADR 0327).
3
+ //
4
+ // Control-plane code, like its model scripts/gds/do-api.js: only the provisioning runner
5
+ // uses it, never the web tier (ADR 0111 §2). Same skeleton (JsonHttpApi): injectable
6
+ // transport, dry-run by default, and live mode refuses to start without a token.
7
+ //
8
+ // THE GUARD. A Render API key belongs to a USER, not a workspace, and carries that user's
9
+ // rights in every workspace they belong to — measured 2026-09-22: one owner's key reached
10
+ // three workspaces, one of them another builder's, holding live production services. So:
11
+ //
12
+ // - the client is built for ONE workspace (`ownerId`) and refuses to exist without it —
13
+ // never defaulted, and never derived by taking the first of GET /owners;
14
+ // - every call that names an owner sends this one;
15
+ // - every response that carries an owner is ASSERTED to carry this one, and a missing
16
+ // or different owner is a hard error (RenderOwnerMismatch). Assert on the response,
17
+ // not the request: a request you got right says nothing about a response that came
18
+ // from somewhere else. A list is checked element by element.
19
+ //
20
+ // Render's own shapes decide where the owner sits: a service carries `ownerId`, a
21
+ // Postgres carries `owner.id` (both measured by the pilot, task 1004142). A few calls
22
+ // answer with no owner at all (a database's connection-info, an env-var PUT, a deploy
23
+ // trigger). Those are only reachable through a method that first reads the parent
24
+ // resource through the guard, so nothing is ever sent to or read from a resource whose
25
+ // workspace was not checked.
26
+ //
27
+ // NO DELETE. The platform must not hold the ability to destroy infrastructure in an
28
+ // account it does not own (ADR 0327 §3). There is no delete method, and _req refuses the
29
+ // verb outright, so adding one later is a visible change to this file, not a one-liner.
30
+
31
+ 'use strict';
32
+
33
+ const { JsonHttpApi, makeApiError } = require('./http-api-client');
34
+
35
+ const RENDER_API_BASE = 'https://api.render.com/v1';
36
+
37
+ const RenderApiError = makeApiError('RenderApiError', 'RENDER_API_ERROR');
38
+ const RenderOwnerMismatch = makeApiError('RenderOwnerMismatch', 'RENDER_OWNER_MISMATCH');
39
+
40
+ // The owner id a Render resource carries, in either of the two shapes Render uses.
41
+ // null when it carries none.
42
+ function ownerOf(resource) {
43
+ if (!resource || typeof resource !== 'object') return null;
44
+ if (typeof resource.ownerId === 'string' && resource.ownerId) return resource.ownerId;
45
+ if (resource.owner && typeof resource.owner.id === 'string' && resource.owner.id) return resource.owner.id;
46
+ return null;
47
+ }
48
+
49
+ // Env var values are the owner's secrets on their way to Render. A dry-run log is the one
50
+ // place this client would otherwise print a request body, so it prints the names only.
51
+ function redact(body) {
52
+ if (!body || typeof body !== 'object') return body;
53
+ const out = { ...body };
54
+ if (Array.isArray(out.envVars)) out.envVars = out.envVars.map((v) => ({ key: v && v.key, value: '[redacted]' }));
55
+ if ('value' in out) out.value = '[redacted]';
56
+ return out;
57
+ }
58
+
59
+ class RenderApi extends JsonHttpApi {
60
+ // opts: { token, ownerId, dryRun=true, fetchImpl=globalThis.fetch, base, log }
61
+ constructor(opts = {}) {
62
+ super(opts, { base: RENDER_API_BASE, logTag: 'Render', ErrorClass: RenderApiError });
63
+ if (typeof opts.ownerId !== 'string' || !opts.ownerId.trim()) {
64
+ throw new RenderApiError('a Render client needs the workspace it acts in (ownerId) — it is never defaulted');
65
+ }
66
+ this.ownerId = opts.ownerId.trim();
67
+ if (!this.dryRun && !this.token) {
68
+ throw new RenderApiError('live Render call requested with no API key');
69
+ }
70
+ if (!this.dryRun && typeof this.fetchImpl !== 'function') {
71
+ throw new RenderApiError('no fetch implementation available for live mode');
72
+ }
73
+ }
74
+
75
+ async _req(method, path, body, opts = {}) {
76
+ if (method === 'DELETE') throw new RenderApiError(`refusing ${method} ${path}: the platform never deletes in an account it does not own (ADR 0327 §3)`);
77
+ if (this.dryRun) {
78
+ this.log(`[dry-run] Render ${method} ${path}${body ? ' ' + JSON.stringify(redact(body)) : ''}`);
79
+ return { dryRun: true, ...(opts.dryRunResult || {}) };
80
+ }
81
+ return super._req(method, path, body, opts);
82
+ }
83
+
84
+ // Throws unless `resource` carries exactly this client's workspace.
85
+ assertOwned(resource, what) {
86
+ const got = ownerOf(resource);
87
+ if (got !== this.ownerId) {
88
+ throw new RenderOwnerMismatch(
89
+ got
90
+ ? `Render answered ${what} from workspace ${got}, not ${this.ownerId} — refusing to go on`
91
+ : `Render answered ${what} with no workspace on it — refusing to go on`,
92
+ { body: null });
93
+ }
94
+ return resource;
95
+ }
96
+
97
+ // ---- workspaces ------------------------------------------------------------
98
+
99
+ // The workspaces the key can reach, as [{ id, name, type }]. Used for MEMBERSHIP only —
100
+ // "is the workspace the owner named one this key can act in" — never to pick one.
101
+ async listOwners() {
102
+ const json = await this._req('GET', '/owners?limit=100', null, {
103
+ dryRunResult: { items: [{ owner: { id: this.ownerId, name: '(dry-run)', type: 'team' } }] },
104
+ });
105
+ const items = Array.isArray(json) ? json : (json && json.items) || [];
106
+ return items.map((e) => (e && e.owner) || e).filter((o) => o && typeof o.id === 'string');
107
+ }
108
+
109
+ // ---- services --------------------------------------------------------------
110
+
111
+ async getService(serviceId) {
112
+ const json = await this._req('GET', `/services/${encodeURIComponent(serviceId)}`, null, {
113
+ dryRunResult: { id: serviceId, ownerId: this.ownerId, serviceDetails: { url: null } },
114
+ });
115
+ return this.assertOwned(json && json.service ? json.service : json, `service ${serviceId}`);
116
+ }
117
+
118
+ // payload: the POST /services body (render-payload.js). Its ownerId must be ours — the
119
+ // payload builder takes it as an argument, so this is checked, not overwritten.
120
+ async createService(payload) {
121
+ if (!payload || payload.ownerId !== this.ownerId) throw new RenderApiError('a service payload must name this client\'s workspace');
122
+ const json = await this._req('POST', '/services', payload, {
123
+ dryRunResult: { deployId: null, service: { id: `dryrun-srv-${payload.name}`, ownerId: this.ownerId, serviceDetails: { url: null } } },
124
+ });
125
+ return { deployId: (json && json.deployId) || null, service: this.assertOwned(json && json.service, 'the new service') };
126
+ }
127
+
128
+ // Set one env var on a service this workspace owns. The PUT answers with no owner, so
129
+ // the service is read through the guard first.
130
+ async putEnvVar(serviceId, key, value) {
131
+ await this.getService(serviceId);
132
+ return this._req('PUT', `/services/${encodeURIComponent(serviceId)}/env-vars/${encodeURIComponent(key)}`, { value }, { dryRunResult: { key } });
133
+ }
134
+
135
+ async triggerDeploy(serviceId) {
136
+ await this.getService(serviceId);
137
+ return this._req('POST', `/services/${encodeURIComponent(serviceId)}/deploys`, {}, { dryRunResult: { id: null } });
138
+ }
139
+
140
+ // ---- Postgres --------------------------------------------------------------
141
+
142
+ async createPostgres(payload) {
143
+ if (!payload || payload.ownerId !== this.ownerId) throw new RenderApiError('a Postgres payload must name this client\'s workspace');
144
+ const json = await this._req('POST', '/postgres', payload, {
145
+ dryRunResult: { id: `dryrun-pg-${payload.name}`, status: 'creating', owner: { id: this.ownerId } },
146
+ });
147
+ return this.assertOwned(json, 'the new database');
148
+ }
149
+
150
+ async getPostgres(postgresId) {
151
+ const json = await this._req('GET', `/postgres/${encodeURIComponent(postgresId)}`, null, {
152
+ dryRunResult: { id: postgresId, status: 'available', owner: { id: this.ownerId } },
153
+ });
154
+ return this.assertOwned(json, `database ${postgresId}`);
155
+ }
156
+
157
+ // The database's connection strings. The answer carries no owner, so the database is
158
+ // read through the guard first.
159
+ async postgresConnectionInfo(postgresId) {
160
+ await this.getPostgres(postgresId);
161
+ return this._req('GET', `/postgres/${encodeURIComponent(postgresId)}/connection-info`, null, {
162
+ dryRunResult: { internalConnectionString: 'postgres://dry-run' },
163
+ });
164
+ }
165
+
166
+ // Poll until a new database is 'available'. `sleepFn` lets tests drive it with no clock.
167
+ async settlePostgres(postgresId, { tries = 60, sleepMs = 5000, sleepFn } = {}) {
168
+ const sleep = sleepFn || ((ms) => new Promise((r) => setTimeout(r, ms)));
169
+ for (let i = 0; i < tries; i++) {
170
+ const pg = await this.getPostgres(postgresId);
171
+ if (pg.status === 'available') return pg;
172
+ await sleep(sleepMs);
173
+ }
174
+ throw new RenderApiError(`database ${postgresId} did not become available in time`);
175
+ }
176
+ }
177
+
178
+ module.exports = { RenderApi, RenderApiError, RenderOwnerMismatch, RENDER_API_BASE, ownerOf, redact };
@@ -0,0 +1,110 @@
1
+ // scripts/gds/render-payload.js — WHAT the Render standup leg creates, kept apart from
2
+ // HOW it creates it (scripts/gds/provision-render.js) (task 1004183).
3
+ //
4
+ // Pure functions, no I/O. They are separate so the thing being stood up can change
5
+ // without touching the guard or the key plumbing: this file builds the Bongos instance
6
+ // the Render pilot proved (task 1004142, docs/recipes/render-pilot.md §4 and its
7
+ // "Corrections" box), and task 1004350 retargets it at the project's own app, per
8
+ // ADR 0345 (we host the hall; the owner's app is what goes to their Render account).
9
+ //
10
+ // The plans are per-instance settings (ADR 0327 §5), never constants. The defaults are
11
+ // what the pilot measured as enough for a new instance at idle: a `starter` web service
12
+ // (48-62 MiB of 512) and a paid `basic_256mb` Postgres, because Render's free Postgres
13
+ // has no backups of any kind.
14
+
15
+ 'use strict';
16
+
17
+ const crypto = require('node:crypto');
18
+
19
+ // The vocabulary lives with the web tier's validation, so the two can never disagree.
20
+ const { WEB_PLANS, DB_PLANS, REGIONS } = require('../../modules/provisioning/render-standup.js');
21
+ const DEFAULTS = Object.freeze({ webPlan: 'starter', dbPlan: 'basic_256mb', region: 'virginia' });
22
+
23
+ // A Render resource name from the project's slug. Render allows letters, digits and
24
+ // dashes; the slug already is that, this only makes sure.
25
+ function resourceName(inst, suffix) {
26
+ const base = String(inst.slug || `project-${inst.id}`).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 50);
27
+ return suffix ? `${base}-${suffix}` : base;
28
+ }
29
+
30
+ // The plan and region an instance asked for, with the defaults filled in. A value outside
31
+ // the vocabulary is refused rather than passed through for Render to reject.
32
+ function plansFor(appHost) {
33
+ const h = appHost || {};
34
+ const out = {
35
+ webPlan: h.webPlan || DEFAULTS.webPlan,
36
+ dbPlan: h.dbPlan || DEFAULTS.dbPlan,
37
+ region: h.region || DEFAULTS.region,
38
+ };
39
+ if (!WEB_PLANS.includes(out.webPlan)) throw new Error(`unknown Render web plan '${out.webPlan}'`);
40
+ if (!DB_PLANS.includes(out.dbPlan)) throw new Error(`unknown Render database plan '${out.dbPlan}'`);
41
+ if (!REGIONS.includes(out.region)) throw new Error(`unknown Render region '${out.region}'`);
42
+ return out;
43
+ }
44
+
45
+ // POST /postgres. `plan` is never 'free' — see the header.
46
+ function renderPostgresPayload(inst, { ownerId, dbPlan, region }) {
47
+ return { name: resourceName(inst, 'db'), ownerId, plan: dbPlan, region, version: '16' };
48
+ }
49
+
50
+ // POST /services, for a Bongos instance from its repository. `dbUrl` is the database's
51
+ // internal connection string; `secretKey` is a fresh BUILDER_SECRET_KEY. Both are VALUES
52
+ // sent to Render and held there — the platform keeps neither.
53
+ //
54
+ // What each non-obvious line is for, from the pilot's corrections:
55
+ // - runtime + startCommand are explicit: a hybrid repo defaults to Python on Render, and
56
+ // an adopted instance has no `npm start`;
57
+ // - HOST=0.0.0.0: the server binds 127.0.0.1 otherwise and Render's router never reaches it;
58
+ // - PGDATABASE = the URL: migrate.sh addresses the database as `psql -d "$PGDATABASE"`;
59
+ // - BUILDER_SECRET_KEY: Render's disk is wiped each deploy, so the key-file fallback
60
+ // would mint a new key every time and orphan every stored per-builder secret;
61
+ // - no PORT: Render injects it.
62
+ // Bongos reads DATABASE_URL first (src/bongos/pool.js), so none of the PG* family the box
63
+ // writes is needed — the one simplification Render buys.
64
+ function renderServicePayload(inst, { ownerId, repoUrl, branch, webPlan, region, dbUrl, secretKey, envPrefix, firstAdmin }) {
65
+ const envVars = [
66
+ { key: 'NODE_VERSION', value: '22' },
67
+ { key: 'HOST', value: '0.0.0.0' },
68
+ { key: 'DATABASE_URL', value: dbUrl },
69
+ { key: 'PGDATABASE', value: dbUrl },
70
+ { key: 'PGPOOL_MAX', value: '5' },
71
+ { key: 'BUILDER_SECRET_KEY', value: secretKey },
72
+ ];
73
+ if (firstAdmin) envVars.push({ key: `${envPrefix}_FIRST_ADMIN`, value: firstAdmin });
74
+ return {
75
+ type: 'web_service',
76
+ name: resourceName(inst),
77
+ ownerId,
78
+ repo: repoUrl,
79
+ branch: branch || 'main',
80
+ autoDeploy: 'yes',
81
+ serviceDetails: {
82
+ runtime: 'node',
83
+ plan: webPlan,
84
+ region,
85
+ healthCheckPath: '/healthz',
86
+ envSpecificDetails: {
87
+ buildCommand: 'npm ci',
88
+ startCommand: 'node node_modules/@bongos/core/src/platform-server.js',
89
+ preDeployCommand: 'bash node_modules/@bongos/core/scripts/migrate.sh',
90
+ },
91
+ },
92
+ envVars,
93
+ };
94
+ }
95
+
96
+ // The env vars that can only be set once the service exists, because they name the URL
97
+ // Render gave it. The four origins must all be that one host: a single-host instance has
98
+ // no separate builders./status. subdomain, and without them the hall never loads.
99
+ function renderAfterCreateEnv(serviceUrl, { envPrefix }) {
100
+ const origin = String(serviceUrl || '').replace(/\/+$/, '');
101
+ if (!/^https:\/\//.test(origin)) throw new Error(`Render gave the service no https URL (${serviceUrl || 'none'})`);
102
+ return ['PUBLIC', 'BUILDERS', 'STATUS', 'OAUTH'].map((k) => ({ key: `${envPrefix}_${k}_ORIGIN`, value: origin }));
103
+ }
104
+
105
+ function freshSecretKey() { return crypto.randomBytes(32).toString('hex'); }
106
+
107
+ module.exports = {
108
+ WEB_PLANS, DB_PLANS, REGIONS, DEFAULTS,
109
+ resourceName, plansFor, renderPostgresPayload, renderServicePayload, renderAfterCreateEnv, freshSecretKey,
110
+ };
package/src/module-api.js CHANGED
@@ -75,7 +75,7 @@ const { responsibilityFor, ROLE_RESPONSIBILITIES } = require('./role-responsibil
75
75
  // MAJOR (see allowBoxScope below): passes the request through untouched.
76
76
  function deprecatedNoopMiddleware(_req, _res, next) { next(); }
77
77
 
78
- const CORE_VERSION = '1.19.1080'; // CI auto-patch carrier (ADR 0161); changelog: docs/module-api-changelog.md
78
+ const CORE_VERSION = '1.19.1081'; // CI auto-patch carrier (ADR 0161); changelog: docs/module-api-changelog.md
79
79
 
80
80
  // A namespaced logger so a module's log lines are attributable + consistent.
81
81
  // Usage: const log = api.logger('discord'); log.info('mounted');