@runeditrun/rer 0.2.43 → 0.2.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -1
- package/cli/README.md +11 -1
- package/cli/business/command.mjs +1 -1
- package/cli/business/keychain.mjs +1 -1
- package/cli/business/lease.mjs +1 -1
- package/cli/business/questions.mjs +2 -2
- package/cli/contract.mjs +1 -1
- package/cli/deploy-readiness.mjs +2 -2
- package/cli/deploy.mjs +18 -5
- package/cli/local.mjs +6 -2
- package/cli/parse.mjs +9 -3
- package/cli/port.mjs +10 -11
- package/cli/server-limit-file.mjs +21 -0
- package/cli/server-registry.mjs +13 -6
- package/cli/server-resources.mjs +13 -2
- package/global/CHANGELOG.md +17 -0
- package/global/README.md +7 -1
- package/global/launch/capacity.mjs +9 -4
- package/global/launch/facts.mjs +11 -19
- package/modules/demo-host/README.md +3 -0
- package/modules/demo-host/build.mjs +3 -1
- package/modules/demo-host/native/config.mjs +2 -0
- package/modules/demo-host/native/prepare.mjs +3 -1
- package/modules/demo-host/native/warm.mjs +49 -0
- package/modules/demo-host/native/worker.mjs +4 -2
- package/modules/demo-host/pages.mjs +6 -1
- package/modules/dependencies/README.md +5 -2
- package/modules/dependencies/index.mjs +4 -3
- package/modules/dependencies/protocol.mjs +7 -5
- package/modules/deploy-kit/README.md +16 -1
- package/modules/deploy-kit/deploy.mjs +5 -3
- package/modules/deploy-kit/diagnostics.mjs +8 -0
- package/modules/deploy-kit/migration-ledger.mjs +28 -8
- package/modules/deploy-kit/migration-retry.mjs +32 -16
- package/modules/deploy-kit/migrations.mjs +10 -4
- package/modules/deploy-kit/owner-cli.mjs +9 -6
- package/modules/deploy-kit/owner-secret-copy.mjs +38 -0
- package/modules/deploy-kit/owner-secret-names.mjs +1 -1
- package/modules/deploy-kit/owner-secret.mjs +39 -18
- package/modules/deploy-kit/owner.mjs +25 -15
- package/modules/deploy-kit/provider.mjs +20 -3
- package/modules/operator-auth/identity/oidc/config.mjs +10 -8
- package/modules/operator-auth/signin/index.mjs +3 -3
- package/modules/release/catalogue.mjs +1 -1
- package/onboarding/port-probe.mjs +23 -1
- package/onboarding/process-diagnostics.mjs +3 -2
- package/onboarding/schema/setup-validation.mjs +1 -1
- package/onboarding/theme.mjs +1 -1
- package/onboarding/ui/app.js +1 -1
- package/package.json +1 -1
|
@@ -1,45 +1,64 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
1
2
|
import { assert, identifier } from './validation.mjs';
|
|
2
3
|
import { activeWorker } from './worker.mjs';
|
|
3
|
-
import { secretNames } from './owner-secret-names.mjs';
|
|
4
|
+
import { secretNames, validSecretNames } from './owner-secret-names.mjs';
|
|
4
5
|
import { waitHealth } from './health-request.mjs';
|
|
5
6
|
import { definiteProviderRefusal } from './provider.mjs';
|
|
6
7
|
import { readOwnerState, writeOwnerState, withStateLock, withScopeHints, sameDeployment, refuse, recordSecretChange, settlePendingSecret } from './owner.mjs';
|
|
8
|
+
import { uploadSecretCopy, deploySecretCopy } from './owner-secret-copy.mjs';
|
|
7
9
|
|
|
8
|
-
/** Set (`value` given) or remove
|
|
9
|
-
*
|
|
10
|
+
/** Set (each `value` given) or remove Worker secrets of the owner's last deployment as one
|
|
11
|
+
* new Worker version, then record that version in the state file, so the next deploy
|
|
10
12
|
* recognises its own Worker. A Worker someone else replaced is refused untouched.
|
|
13
|
+
* One secret uses Cloudflare's secret call; several are one copy of the live version
|
|
14
|
+
* (owner-secret-copy.mjs). Every change sets all its secrets or removes all of them.
|
|
11
15
|
* The change is recorded as pending first: if the provider applies it but rer never
|
|
12
16
|
* sees it settle, a later run can recognise its immediate successor (see settlePendingSecret).
|
|
13
17
|
* Both success and ambiguous failure read back for up to `windowMs`. An explicit refusal
|
|
14
18
|
* clears the pending record. An accepted write keeps its intent until confirmed.
|
|
15
19
|
* An ambiguous failure clears it only when readback corroborates that the receipt's
|
|
16
|
-
* deployment is still live. An ambiguous rotation
|
|
20
|
+
* deployment is still live. An ambiguous one-secret rotation
|
|
17
21
|
* re-PUTs the value before accepting its successor as proof of the rotation.
|
|
18
22
|
* A removed declared secret is retired: later plans omit it until it is set again. */
|
|
19
|
-
export async function ownerSecret({api: provider, target, statePath,
|
|
23
|
+
export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, windowMs = 30000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))}) {
|
|
20
24
|
const api = withScopeHints(provider);
|
|
21
|
-
|
|
22
|
-
assert(
|
|
25
|
+
const bindings = changes.map(change => change.binding), present = changes[0]?.value !== undefined;
|
|
26
|
+
assert(bindings.length && bindings.every(identifier) && validSecretNames(bindings), 'invalid-secret-name');
|
|
27
|
+
assert(changes.every(change => (change.value !== undefined) === present), 'mixed-secret-change');
|
|
28
|
+
for (const {binding, value} of changes) assert(value === undefined || typeof value === 'string' && value.trim(), `missing-secret-${binding}`);
|
|
23
29
|
return withStateLock(statePath, async () => {
|
|
24
30
|
const state = await readOwnerState(statePath, target);
|
|
25
31
|
assert(state.receipt && !state.pendingUpload, 'missing-owner-receipt');
|
|
26
|
-
|
|
32
|
+
// A copy uploaded but never deployed is that earlier change: finish it first.
|
|
33
|
+
const deployCopy = version => deploySecretCopy(api, target.worker, version);
|
|
34
|
+
if (await settlePendingSecret(api, target.worker, state, {preflight:true, deployCopy})) await writeOwnerState(statePath, state);
|
|
27
35
|
const live = await activeWorker(api, target.worker);
|
|
28
36
|
if (!live) throw refuse('owned-resource-missing', 'worker', target.worker);
|
|
29
37
|
if (!sameDeployment(live, state.receipt.provider)) throw refuse('owned-resource-replaced', 'worker', target.worker);
|
|
30
38
|
assert(!state.pendingSecret, 'secret-change-unsettled');
|
|
31
|
-
const path = `/workers/scripts/${target.worker}/secrets
|
|
39
|
+
const path = `/workers/scripts/${target.worker}/secrets`;
|
|
32
40
|
const names = secretNames(await api.request(path));
|
|
33
41
|
assert(names, 'invalid-secret-list');
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
42
|
+
// Removing secrets the Worker does not hold changes nothing; the rest of a removal still runs.
|
|
43
|
+
const writes = present ? changes : changes.filter(change => names.includes(change.binding));
|
|
44
|
+
const existed = writes.some(change => names.includes(change.binding)), changed = writes.length > 0, copy = writes.length > 1;
|
|
45
|
+
state.pendingSecret = {bindings, present, versionId:state.receipt.provider.versionId, names:names.filter(name => !bindings.includes(name)).sort(), ...(copy ? {copy:randomBytes(16).toString('hex')} : {})};
|
|
46
|
+
await writeOwnerState(statePath, state);
|
|
47
|
+
let failure, unchanged = false, confirming = false, uploaded = false;
|
|
48
|
+
const put = () => api.request(path, {method:'PUT', body:{name:writes[0].binding, text:writes[0].value, type:'secret_text'}});
|
|
38
49
|
try {
|
|
39
|
-
if (
|
|
40
|
-
|
|
50
|
+
if (copy) {
|
|
51
|
+
const version = await uploadSecretCopy(api, target.worker, live, {changes:writes, marker:state.pendingSecret.copy});
|
|
52
|
+
uploaded = true;
|
|
53
|
+
await deploySecretCopy(api, target.worker, version);
|
|
54
|
+
}
|
|
55
|
+
else if (present) await put();
|
|
56
|
+
else if (changed) await api.request(`${path}/${writes[0].binding}`, {method:'DELETE'});
|
|
41
57
|
} catch (error) {
|
|
42
|
-
|
|
58
|
+
// A refused upload changed nothing. A copy uploaded but refused deployment stays
|
|
59
|
+
// pending: the same command deploys it next time, as this change and no other.
|
|
60
|
+
if (definiteProviderRefusal(error) && !uploaded) { delete state.pendingSecret; await writeOwnerState(statePath, state); throw error; }
|
|
61
|
+
if (definiteProviderRefusal(error)) { await writeOwnerState(statePath, state); throw error; }
|
|
43
62
|
failure = error;
|
|
44
63
|
}
|
|
45
64
|
try {
|
|
@@ -48,7 +67,9 @@ export async function ownerSecret({api: provider, target, statePath, binding, va
|
|
|
48
67
|
try {
|
|
49
68
|
if (await settlePendingSecret(api, target.worker, state, {
|
|
50
69
|
observe: current => { unchanged = sameDeployment(current, state.receipt.provider); },
|
|
51
|
-
|
|
70
|
+
// A copy whose upload or deployment answer was lost is deployed here once it is found.
|
|
71
|
+
...(copy ? {deployCopy} : {}),
|
|
72
|
+
...(failure && present && existed && !copy ? {confirm: async current => {
|
|
52
73
|
confirming = true;
|
|
53
74
|
state.pendingSecret.repeatVersionId = current.versionId;
|
|
54
75
|
await writeOwnerState(statePath, state);
|
|
@@ -71,7 +92,7 @@ export async function ownerSecret({api: provider, target, statePath, binding, va
|
|
|
71
92
|
await writeOwnerState(statePath, state);
|
|
72
93
|
throw failure ?? error;
|
|
73
94
|
}
|
|
74
|
-
const result = {worker:target.worker,
|
|
95
|
+
const result = {worker:target.worker, bindings, present, versionId:state.receipt.provider.versionId};
|
|
75
96
|
// Settlement is durable before readiness: a failed hosted check must never
|
|
76
97
|
// erase the applied mutation or cause the next command to reject our version.
|
|
77
98
|
state.receipt.health = {ok:false,versionId:result.versionId};
|
|
@@ -12,6 +12,7 @@ import { validateMigrations } from './migrations.mjs';
|
|
|
12
12
|
import { deploy } from './deploy.mjs';
|
|
13
13
|
import { verifyHealth } from './health.mjs';
|
|
14
14
|
import { validSecretNames, secretNames, pendingSecretNames } from './owner-secret-names.mjs';
|
|
15
|
+
import { copyMessage, undeployedCopy } from './owner-secret-copy.mjs';
|
|
15
16
|
import { publicOrigin } from './public-origin.mjs';
|
|
16
17
|
|
|
17
18
|
/* Owner-account mode: the owner's own Cloudflare account, token and account id.
|
|
@@ -175,10 +176,14 @@ export async function readOwnerState(path, target) {
|
|
|
175
176
|
&& KINDS.every(kind => state.owned[kind] && typeof state.owned[kind] === 'object' && Object.values(state.owned[kind]).every(entry => ['pending','created'].includes(entry?.status))), 'invalid-owner-state');
|
|
176
177
|
assert(state.pendingUpload === undefined || typeof state.pendingUpload?.fingerprint === 'string', 'invalid-owner-state');
|
|
177
178
|
// Declared secrets rer removed on purpose (the spent setup token): later plans omit them.
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
179
|
+
// A change recorded by an older rer names one `binding`.
|
|
180
|
+
if (typeof state.pendingSecret?.binding === 'string' && state.pendingSecret.bindings === undefined) { const {binding, ...rest} = state.pendingSecret; state.pendingSecret = {...rest, bindings:[binding]}; }
|
|
181
|
+
const pending = state.pendingSecret;
|
|
182
|
+
assert(pending === undefined || Array.isArray(pending?.bindings) && pending.bindings.length > 0 && validSecretNames(pending.bindings) && typeof pending.present === 'boolean'
|
|
183
|
+
&& (pending.versionId === undefined || uuid(pending.versionId))
|
|
184
|
+
&& (pending.repeatVersionId === undefined || uuid(pending.repeatVersionId))
|
|
185
|
+
&& (pending.copy === undefined || /^[0-9a-f]{32}$/.test(pending.copy))
|
|
186
|
+
&& (pending.names === undefined || validSecretNames(pending.names) && !pending.names.some(name => pending.bindings.includes(name))), 'invalid-owner-state');
|
|
182
187
|
assert(state.ownerClaim === undefined || ['claimed','kept'].includes(state.ownerClaim?.outcome), 'invalid-owner-state');
|
|
183
188
|
assert(state.retiredSecrets === undefined || Array.isArray(state.retiredSecrets) && state.retiredSecrets.every(identifier), 'invalid-owner-state');
|
|
184
189
|
assert(state.accountId === target.accountId && state.project === target.project && state.environment === target.environment && state.worker === target.worker, 'owner-state-target-mismatch');
|
|
@@ -242,11 +247,11 @@ async function uploadFingerprint(body) {
|
|
|
242
247
|
return fingerprint;
|
|
243
248
|
}
|
|
244
249
|
/** Record a secret change's outcome on the receipt: the Worker version it made, and whether
|
|
245
|
-
*
|
|
246
|
-
export function recordSecretChange(state, current, {
|
|
250
|
+
* its secrets are now retired (a removed declared secret stays out of later plans). */
|
|
251
|
+
export function recordSecretChange(state, current, {bindings, present}) {
|
|
247
252
|
state.receipt.provider = {versionId:current.versionId, deploymentId:current.deploymentId, etag:current.etag};
|
|
248
253
|
const retired = new Set(state.retiredSecrets ?? []);
|
|
249
|
-
if (present) retired.delete(binding); else retired.add(binding);
|
|
254
|
+
for (const binding of bindings) if (present) retired.delete(binding); else retired.add(binding);
|
|
250
255
|
if (retired.size) state.retiredSecrets = [...retired].sort(); else delete state.retiredSecrets;
|
|
251
256
|
delete state.pendingSecret;
|
|
252
257
|
}
|
|
@@ -255,16 +260,19 @@ export function recordSecretChange(state, current, {binding, present}) {
|
|
|
255
260
|
* exactly one version after the recorded starting version and it is the live one, still running the receipt's
|
|
256
261
|
* exact script and build fingerprint, with the other secret names unchanged: adopt its version. A confirming PUT also records its
|
|
257
262
|
* own starting version before it writes; its immediate successor can be recovered by the
|
|
258
|
-
* same checks.
|
|
259
|
-
|
|
263
|
+
* same checks. A several-secret copy must also carry its marker; one uploaded but never deployed
|
|
264
|
+
* is deployed by `deployCopy` when given. Anything later is left to the identity check, which refuses it. */
|
|
265
|
+
export async function settlePendingSecret(api, worker, state, {preflight = false, observe, confirm, deployCopy} = {}) {
|
|
260
266
|
if (!state.pendingSecret || !state.receipt) return false;
|
|
261
267
|
const live = await activeWorker(api, worker);
|
|
262
268
|
if (sameDeployment(live, state.receipt.provider)) {
|
|
263
269
|
// Both deployment and newest version must corroborate an unapplied write.
|
|
264
270
|
// A stale deployment alone must not erase an accepted but unsettled intent.
|
|
265
271
|
const versions = (await api.request(`/workers/scripts/${worker}/versions`))?.items;
|
|
266
|
-
const
|
|
267
|
-
|
|
272
|
+
const listed = Array.isArray(versions) && versions.every(item => uuid(item?.id)) && new Set(versions.map(item => item.id)).size === versions.length;
|
|
273
|
+
const unchanged = listed && versions[0]?.id === live.versionId;
|
|
274
|
+
const copy = listed && !unchanged && deployCopy ? await undeployedCopy(api, worker, state, versions) : null;
|
|
275
|
+
if (copy) { await deployCopy(copy); return settlePendingSecret(api, worker, state, {preflight, observe, confirm}); }
|
|
268
276
|
observe?.(unchanged ? live : null);
|
|
269
277
|
if (!preflight || !unchanged) return false;
|
|
270
278
|
delete state.pendingSecret;
|
|
@@ -283,11 +291,12 @@ export async function settlePendingSecret(api, worker, state, {preflight = false
|
|
|
283
291
|
// Its starting version is saved before that PUT, so interruption can recover
|
|
284
292
|
// either the original immediate successor or the second write's successor.
|
|
285
293
|
if (ids[0] !== live.versionId || !(repeatVersionId ? repeated || preflight && immediate && live.versionId === repeatVersionId : immediate)) return false;
|
|
294
|
+
if (state.pendingSecret.copy && live.version?.annotations?.['workers/message'] !== copyMessage(state.pendingSecret.copy)) return false;
|
|
286
295
|
const rows = await api.request(`/workers/scripts/${worker}/secrets`);
|
|
287
|
-
const names = secretNames(rows);
|
|
288
|
-
if (!names || names.includes(
|
|
296
|
+
const names = secretNames(rows), {bindings, present} = state.pendingSecret;
|
|
297
|
+
if (!names || bindings.some(binding => names.includes(binding) !== present)) return false;
|
|
289
298
|
const priorNames = await pendingSecretNames(api, worker, state);
|
|
290
|
-
const otherNames = names.filter(name => name
|
|
299
|
+
const otherNames = names.filter(name => !bindings.includes(name));
|
|
291
300
|
if (!priorNames || priorNames.length !== otherNames.length || !priorNames.every(name => otherNames.includes(name))) return false;
|
|
292
301
|
if (confirm && !repeatVersionId) { await confirm(live); return false; }
|
|
293
302
|
recordSecretChange(state, live, state.pendingSecret);
|
|
@@ -406,7 +415,8 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
|
|
|
406
415
|
return result;
|
|
407
416
|
}};
|
|
408
417
|
const receipt = await deploy({api:observed, plan, artifact, artifactSha256:hash(artifact), previousReceipt:state.receipt ?? undefined,
|
|
409
|
-
|
|
418
|
+
// Migrations run inside this run's state lock: no other deploy of this install is running.
|
|
419
|
+
createResources:false, uploadWithoutReceipt:true, locked:true, env, fetch, healthOptions, readiness, declaredSecrets,
|
|
410
420
|
onReceipt: async candidate => { if (candidate.changed || !state.receipt) { state.receipt = candidate; delete state.pendingUpload; delete state.pendingSecret; await save(); } },
|
|
411
421
|
// Keep each first-health attempt beside the identity it belongs to.
|
|
412
422
|
onHealth: async candidate => { if (candidate.changed) { state.receipt = candidate; await save(); } }});
|
|
@@ -9,7 +9,7 @@ import { providerResponse, transportOutput, transportReason } from './provider-t
|
|
|
9
9
|
// A gateway/server error can arrive after a write. An explicit API refusal cannot.
|
|
10
10
|
export const definiteProviderRefusal = error => error.status === 200 || error.status >= 400 && error.status < 500;
|
|
11
11
|
|
|
12
|
-
async function
|
|
12
|
+
async function boundedBytes(response, limit, onReadError) {
|
|
13
13
|
assert(response.body, 'empty-response');
|
|
14
14
|
const reader = response.body.getReader(); const chunks = []; let length = 0;
|
|
15
15
|
try { while (true) {
|
|
@@ -20,8 +20,9 @@ async function boundedText(response, limit = 4 * 1024 * 1024, onReadError) {
|
|
|
20
20
|
length += value.length; assert(length <= limit, 'response-too-large'); chunks.push(value);
|
|
21
21
|
} }
|
|
22
22
|
finally { await reader.cancel().catch(() => {}); }
|
|
23
|
-
return Buffer.concat(chunks)
|
|
23
|
+
return Buffer.concat(chunks);
|
|
24
24
|
}
|
|
25
|
+
const boundedText = async (response, limit = 4 * 1024 * 1024, onReadError) => (await boundedBytes(response, limit, onReadError)).toString('utf8');
|
|
25
26
|
export async function boundedJSON(response, limit) {
|
|
26
27
|
try { return JSON.parse(await boundedText(response,limit)); } catch (error) { if (error instanceof SyntaxError) throw new Error('malformed-response'); throw error; }
|
|
27
28
|
}
|
|
@@ -117,6 +118,22 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
117
118
|
const shape = (!options.method || options.method === 'GET') && providerListShape(path);
|
|
118
119
|
return shape ? collect(path,{...shape,zone:options.zone,signal:options.signal}) : (await envelope(path,options)).result;
|
|
119
120
|
}
|
|
121
|
+
/** A Worker version's own modules, as Cloudflare keeps them: multipart parts and the entry module's name. */
|
|
122
|
+
async function workerContent(worker, versionId) {
|
|
123
|
+
assert(/^[a-z0-9-]{1,63}$/.test(worker) && /^[0-9a-f-]{36}$/.test(versionId), 'invalid-provider-path');
|
|
124
|
+
assert(++requests <= maxRequests, 'provider-request-budget');
|
|
125
|
+
const operation = 'GET /workers/scripts/[worker]/content/v2';
|
|
126
|
+
const {response,output} = await providerResponse({method:'GET',timeoutMs,reserveRetry:() => requests < maxRequests && (++requests, true),
|
|
127
|
+
send:signal => request(`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${worker}/content/v2?version=${versionId}`, {method:'GET',redirect:'error',signal,headers:{Authorization:`Bearer ${token}`}}),
|
|
128
|
+
consume:response => response.body ? boundedBytes(response, 64 * 1024 * 1024) : Buffer.alloc(0),
|
|
129
|
+
failure:(cause,attempts) => Object.assign(new Error('provider-transport-failed'), {providerTransport:{operation,endpoint:`https://api.cloudflare.com/client/v4/accounts/[REDACTED]/workers/scripts/${worker}/content/v2`,attempts,status:null,reason:transportReason(cause)}})});
|
|
130
|
+
if (!response.ok) throw Object.assign(new Error(`provider-http-${response.status}`), {status:response.status,providerCall:{operation,reason:`provider-http-${response.status}`}});
|
|
131
|
+
const type = response.headers.get('content-type') ?? '', entry = response.headers.get('cf-entrypoint');
|
|
132
|
+
assert(type.startsWith('multipart/form-data') && typeof entry === 'string' && entry, 'invalid-worker-content');
|
|
133
|
+
const parts = await new Response(output, {headers:{'content-type':type}}).formData();
|
|
134
|
+
assert(parts.has(entry), 'invalid-worker-content');
|
|
135
|
+
return {parts, entry};
|
|
136
|
+
}
|
|
120
137
|
async function upload(url, bytes, etag) {
|
|
121
138
|
const destination = importUploadURL(url);
|
|
122
139
|
assert(++requests <= maxRequests, 'provider-request-budget');
|
|
@@ -130,6 +147,6 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
|
|
|
130
147
|
assert(response.status === 200, 'd1-import-upload-failed');
|
|
131
148
|
assert(response.headers.get('etag')?.replace(/^"|"$/g, '') === etag, 'd1-import-upload-etag-mismatch');
|
|
132
149
|
}
|
|
133
|
-
return { accountId, envelope, list, importSql(id, sql) { return importD1({envelope,upload,redact:text => redactValues(text,[accountId,token])}, id, sql); }, request:requestResult,
|
|
150
|
+
return { accountId, envelope, list, importSql(id, sql) { return importD1({envelope,upload,redact:text => redactValues(text,[accountId,token])}, id, sql); }, request:requestResult, workerContent,
|
|
134
151
|
zoneRequest(path, options = {}) { return requestResult(path, { ...options, zone: true }); } };
|
|
135
152
|
}
|
|
@@ -8,9 +8,10 @@ function integer(value, defaultValue, min, max) {
|
|
|
8
8
|
const v = value ?? defaultValue;
|
|
9
9
|
check(Number.isSafeInteger(v) && v >= min && v <= max, 'oidc_invalid_configuration', 503); return v;
|
|
10
10
|
}
|
|
11
|
-
|
|
11
|
+
// https always; with `allowLoopbackHttp` (an RER provider under `rer dev`) also http to a loopback host.
|
|
12
|
+
function httpsUrl(value, allowLoopbackHttp = false) {
|
|
12
13
|
const u = new URL(value);
|
|
13
|
-
check(typeof value === 'string' && u.protocol === 'https:' && !u.username && !u.password && !u.search && !u.hash && !/[\s\\]/.test(value));
|
|
14
|
+
check(typeof value === 'string' && (u.protocol === 'https:' || allowLoopbackHttp && u.protocol === 'http:' && isLoopbackHost(u.hostname)) && !u.username && !u.password && !u.search && !u.hash && !/[\s\\]/.test(value));
|
|
14
15
|
return u;
|
|
15
16
|
}
|
|
16
17
|
// A private JWK for private_key_jwt. Its public half is what the provider holds.
|
|
@@ -20,7 +21,7 @@ function privateKey(jwk, algorithm) {
|
|
|
20
21
|
return Object.freeze({ ...jwk });
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
function provider(input, origin) {
|
|
24
|
+
function provider(input, origin, local) {
|
|
24
25
|
check(input && typeof input === 'object' && typeof input.id === 'string' && /^[a-z][a-z0-9-]{0,31}$/.test(input.id));
|
|
25
26
|
const preset = PRESETS[input.preset];
|
|
26
27
|
check(preset && Object.hasOwn(PRESETS, input.preset));
|
|
@@ -31,7 +32,8 @@ function provider(input, origin) {
|
|
|
31
32
|
issuer = preset.tenantIssuer(input.tenant);
|
|
32
33
|
}
|
|
33
34
|
check(input.issuer === undefined || input.issuer === issuer);
|
|
34
|
-
const
|
|
35
|
+
const loopbackHttp = local && !!preset.interface;
|
|
36
|
+
const issuerUrl = httpsUrl(issuer, loopbackHttp);
|
|
35
37
|
check(typeof input.clientId === 'string' && input.clientId.length > 0 && input.clientId.length <= 512 && !/[\x00-\x1f\x7f]/.test(input.clientId));
|
|
36
38
|
const tokenAuthMethod = input.tokenAuthMethod ?? preset.methods[0];
|
|
37
39
|
check(preset.methods.includes(tokenAuthMethod));
|
|
@@ -42,7 +44,7 @@ function provider(input, origin) {
|
|
|
42
44
|
const additionalAudiences = input.additionalAudiences ?? [];
|
|
43
45
|
check(Array.isArray(additionalAudiences) && additionalAudiences.length <= 10 && additionalAudiences.every(a => typeof a === 'string' && a.length > 0 && a.length <= 512));
|
|
44
46
|
const endpointOrigins = input.endpointOrigins ?? preset.endpointOrigins ?? [issuerUrl.origin];
|
|
45
|
-
check(Array.isArray(endpointOrigins) && endpointOrigins.length > 0 && endpointOrigins.every(o => { const u = new URL(o); return u.origin === o && u.protocol === 'https:'; }));
|
|
47
|
+
check(Array.isArray(endpointOrigins) && endpointOrigins.length > 0 && endpointOrigins.every(o => { const u = new URL(o); return u.origin === o && (u.protocol === 'https:' || loopbackHttp && u.protocol === 'http:' && isLoopbackHost(u.hostname)); }));
|
|
46
48
|
const subjectEmails = Object.fromEntries(Object.entries(input.subjectEmails ?? {}).map(([subject, email]) => {
|
|
47
49
|
check(subject.length > 0 && subject.length <= 255); return [subject, normalizeEmail(email)];
|
|
48
50
|
}));
|
|
@@ -69,7 +71,7 @@ function provider(input, origin) {
|
|
|
69
71
|
algorithms: Object.freeze([...preset.algorithms]), email: preset.email, scope: preset.scope, interface: preset.interface, minimumVersion,
|
|
70
72
|
additionalAudiences: Object.freeze([...new Set(additionalAudiences)]), endpointOrigins: Object.freeze([...new Set(endpointOrigins)]), subjectEmails: Object.freeze(subjectEmails),
|
|
71
73
|
// Each provider has its own redirect URI; its state is bound to it.
|
|
72
|
-
endpointPins, startPath: `/auth/oidc/${input.id}/start`, redirectUri });
|
|
74
|
+
endpointPins, local: loopbackHttp, startPath: `/auth/oidc/${input.id}/start`, redirectUri });
|
|
73
75
|
}
|
|
74
76
|
|
|
75
77
|
export function configure(input) {
|
|
@@ -81,7 +83,7 @@ export function configure(input) {
|
|
|
81
83
|
check(local ? isLoopbackHost(origin.hostname) && ['http:', 'https:'].includes(origin.protocol) : origin.protocol === 'https:');
|
|
82
84
|
check(typeof input.transactionSecret === 'string' && input.transactionSecret.length >= 32 && input.transactionSecret.length <= 1024);
|
|
83
85
|
check(Array.isArray(input.providers) && input.providers.length <= 8);
|
|
84
|
-
const providers = input.providers.map(entry => provider(entry, input.origin));
|
|
86
|
+
const providers = input.providers.map(entry => provider(entry, input.origin, local));
|
|
85
87
|
check(new Set(providers.map(p => p.id)).size === providers.length);
|
|
86
88
|
const callbacks = providers.map(p => new URL(p.redirectUri).pathname);
|
|
87
89
|
check(new Set(callbacks).size === providers.length);
|
|
@@ -99,6 +101,6 @@ export function configure(input) {
|
|
|
99
101
|
}
|
|
100
102
|
|
|
101
103
|
export function endpoint(value, provider) {
|
|
102
|
-
try { const u = new URL(value); check(typeof value === 'string' && u.href === value && u.protocol === 'https:' && !u.username && !u.password && !u.hash && !u.search && provider.endpointOrigins.includes(u.origin)); return u.href; }
|
|
104
|
+
try { const u = new URL(value); check(typeof value === 'string' && u.href === value && (u.protocol === 'https:' || provider.local === true && u.protocol === 'http:' && isLoopbackHost(u.hostname)) && !u.username && !u.password && !u.hash && !u.search && provider.endpointOrigins.includes(u.origin)); return u.href; }
|
|
103
105
|
catch { check(false, 'oidc_untrusted_endpoint', 503); }
|
|
104
106
|
}
|
|
@@ -15,10 +15,10 @@ const NOTICES = {
|
|
|
15
15
|
mail_unavailable: ['alert', 'Sign-in email is not available right now. Ask the person who runs this app to check its mail settings.'],
|
|
16
16
|
invalid_email: ['alert', 'Enter a complete email address.'],
|
|
17
17
|
invalid_input: ['alert', 'Enter a complete email address.'],
|
|
18
|
-
provider_required: ['alert', 'Your
|
|
19
|
-
oidc_provider_required: ['alert', 'Your
|
|
18
|
+
provider_required: ['alert', 'Your organization requires its own sign-in provider for this address.'],
|
|
19
|
+
oidc_provider_required: ['alert', 'Your organization requires its own sign-in provider for this address.'],
|
|
20
20
|
oidc_admission_denied: ['alert', 'That account cannot sign in here. Use the email link, or ask an owner of this app for an invitation.'],
|
|
21
|
-
oidc_provider_denied: ['alert', 'Sign-in was
|
|
21
|
+
oidc_provider_denied: ['alert', 'Sign-in was canceled at the provider.'],
|
|
22
22
|
};
|
|
23
23
|
const UNAVAILABLE = ['alert', 'That sign-in provider is not available right now. Use the email link instead.'];
|
|
24
24
|
const UNFINISHED = ['alert', 'Signing in with that provider did not finish. Try again, or use the email link.'];
|
|
@@ -42,7 +42,7 @@ export function catalogue(source, project, repository, gates, dryRun) {
|
|
|
42
42
|
if (typeof s[key] !== 'string' || !s[key]) throw Error('Incomplete seed listing metadata');
|
|
43
43
|
const contract = clauses(source.bytes('CONTRACT.md').toString());
|
|
44
44
|
const licence = source.bytes('LICENSE').toString();
|
|
45
|
-
if (!licence.includes('Permission is hereby granted, free of charge')) throw Error('Declare a supported listing
|
|
45
|
+
if (!licence.includes('Permission is hereby granted, free of charge')) throw Error('Declare a supported listing license');
|
|
46
46
|
const docs = ['seed.json', 'CONTRACT.md', 'AGENTS.md', 'LICENSE', 'RELEASE.json',
|
|
47
47
|
...['README.md', 'BASELINE.md', 'OPERATIONS.md', 'ACCEPTANCE.md'].filter(path => source.entries.has(path))];
|
|
48
48
|
const artifacts = docs.map(path => ({ path: `documents/${path}`, target: `agents/seeds/${s.id}/${path}`, sha256: sha256(source.bytes(path)) }));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createServer } from 'node:net';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
-
import { inspectionContext, portListener, uncheckedInspection } from './process-diagnostics.mjs';
|
|
3
|
+
import { inspectionContext, portListener, searchContext, uncheckedInspection } from './process-diagnostics.mjs';
|
|
4
4
|
|
|
5
5
|
async function bind(host, port) {
|
|
6
6
|
const socket = createServer();
|
|
@@ -38,3 +38,25 @@ export async function probePort(host, port, { context = inspectionContext({ port
|
|
|
38
38
|
await delay(Math.min(100, remaining));
|
|
39
39
|
} while (true);
|
|
40
40
|
}
|
|
41
|
+
|
|
42
|
+
// How many ports a free-port search tries, counting from its first one. The
|
|
43
|
+
// search is bounded by this count and by nothing else: a busy computer makes
|
|
44
|
+
// each bind slower, and the search waits for every bind's answer.
|
|
45
|
+
export const searchCandidates = 1000;
|
|
46
|
+
|
|
47
|
+
// The first port from `from` that probePort finds available and `claim` secures
|
|
48
|
+
// (claim may be omitted), among the next `searchCandidates` ports. A port in
|
|
49
|
+
// `skip` counts as tried and in use. Each candidate's ownership check has its
|
|
50
|
+
// own load-scaled budget, so no candidate can spend another's. Without a free
|
|
51
|
+
// port, the result says what was tried: { range: [first, last], tried }.
|
|
52
|
+
export async function searchPort({ host, from, hosts, skip = () => false, claim = async () => ({}), verb }) {
|
|
53
|
+
const last = Math.min(65535, from + searchCandidates - 1);
|
|
54
|
+
for (let port = from; port <= last; port++) {
|
|
55
|
+
if (skip(port)) continue;
|
|
56
|
+
const context = searchContext({ port, verb });
|
|
57
|
+
if (!(await probePort(host, port, { context, hosts, anyAddress: true, searching: true })).available) continue;
|
|
58
|
+
const claimed = await claim(port);
|
|
59
|
+
if (claimed) return { port, ...claimed };
|
|
60
|
+
}
|
|
61
|
+
return { range: [from, last], tried: last - from + 1 };
|
|
62
|
+
}
|
|
@@ -13,8 +13,9 @@ const exec=promisify(execFile);
|
|
|
13
13
|
const lsof=process.platform==='darwin'?'/usr/sbin/lsof':'lsof';
|
|
14
14
|
// One monotonic budget covers every command in an ownership decision.
|
|
15
15
|
export const inspectionContext=({budgetMs=15000,...details}={})=>({deadline:performance.now()+budgetMs,budgetMs,...details});
|
|
16
|
-
//
|
|
17
|
-
// grows with the 1-minute load per CPU, up to four
|
|
16
|
+
// The ownership check of one free-port candidate on a busy computer gets longer,
|
|
17
|
+
// still bounded: the budget grows with the 1-minute load per CPU, up to four
|
|
18
|
+
// times. The search itself is bounded by its candidate count, not by this.
|
|
18
19
|
export const searchContext=(details={})=>inspectionContext({budgetMs:Math.round(15000*Math.min(4,Math.max(1,loadavg()[0]/availableParallelism()))),...details});
|
|
19
20
|
export const uncheckedInspection=error=>approvedFailure(error)?.ownershipUnchecked===true;
|
|
20
21
|
const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,noMatch=false,positiveResult}={})=>{
|
|
@@ -28,7 +28,7 @@ export function validateSetupValue(field, value) {
|
|
|
28
28
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.href.includes('?') || url.href.includes('#')) throw Error();
|
|
29
29
|
} catch { throw Error(`Invalid URL for ${field.name}`); }
|
|
30
30
|
}
|
|
31
|
-
if (field.kind === 'colour' && !/^#[a-f\d]{6}$/i.test(value)) throw Error(`Invalid
|
|
31
|
+
if (field.kind === 'colour' && !/^#[a-f\d]{6}$/i.test(value)) throw Error(`Invalid color for ${field.name}`);
|
|
32
32
|
if (field.kind === 'timezone') {
|
|
33
33
|
try { new Intl.DateTimeFormat('en', {timeZone: value}); }
|
|
34
34
|
catch { throw Error(`Invalid timezone for ${field.name}`); }
|
package/onboarding/theme.mjs
CHANGED
|
@@ -87,7 +87,7 @@ export function readTheme(css, file = 'rer-theme.css') {
|
|
|
87
87
|
const kind = themeTokens[name];
|
|
88
88
|
if (!kind) throw Error(`${file}: ${name} is not a theme token. Use ${Object.keys(themeTokens).join(', ')}.`);
|
|
89
89
|
if (Object.hasOwn(tokens, name)) throw Error(`${file}: ${name} is declared twice.`);
|
|
90
|
-
if (kind === 'colour' && !colour.test(value)) throw Error(`${file}: ${name} must be a #rgb or #rrggbb
|
|
90
|
+
if (kind === 'colour' && !colour.test(value)) throw Error(`${file}: ${name} must be a #rgb or #rrggbb color.`);
|
|
91
91
|
if (kind === 'stack' && !stack.test(value)) throw Error(`${file}: ${name} must be a font stack of family names.`);
|
|
92
92
|
if (kind === 'radius' && !/^\d{1,2}(?:\.\d+)?(?:px|rem)$/.test(value)) throw Error(`${file}: ${name} must be a length in px or rem.`);
|
|
93
93
|
if (kind === 'logo') assets.add(asset(value, /\.(?:svg|png|webp)$/, name));
|
package/onboarding/ui/app.js
CHANGED
|
@@ -67,7 +67,7 @@ function inputFor(key, value) {
|
|
|
67
67
|
}
|
|
68
68
|
function appendInput(container, key, input, value) {
|
|
69
69
|
if (input.type === 'color') {
|
|
70
|
-
const wrap = node('div', 'colour-control'), selected = fields[key].valid(value), caption = node('span', 'colour-caption', selected ? value : 'Choose a
|
|
70
|
+
const wrap = node('div', 'colour-control'), selected = fields[key].valid(value), caption = node('span', 'colour-caption', selected ? value : 'Choose a color');
|
|
71
71
|
wrap.append(input, caption); input.addEventListener('input', () => { caption.textContent = input.value; });
|
|
72
72
|
container.append(wrap);
|
|
73
73
|
} else if (input.tagName === 'SELECT') { const wrap = node('div', 'select-wrap'); wrap.append(input); container.append(wrap); }
|