@runeditrun/rer 0.2.42 → 0.2.44
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 +21 -15
- package/cli/README.md +3 -1
- package/cli/browser-runtime.mjs +17 -8
- 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-command.mjs +12 -0
- package/cli/deploy-readiness.mjs +2 -2
- package/cli/deploy.mjs +17 -4
- package/cli/hydration/browser.mjs +2 -2
- package/cli/lifecycle.mjs +18 -5
- package/cli/main.mjs +1 -0
- package/cli/parse.mjs +9 -3
- package/cli/port.mjs +3 -3
- package/cli/portability-worker.mjs +3 -1
- package/cli/portability.mjs +7 -3
- package/cli/sqlite-notice.mjs +11 -0
- package/global/CHANGELOG.md +20 -0
- package/global/README.md +21 -15
- package/global/cli/install.mjs +9 -4
- package/global/cli/path-link.mjs +42 -9
- package/global/cli/repository.mjs +4 -1
- package/global/launch/facts.mjs +3 -3
- package/global/main.mjs +5 -1
- package/global/rer.mjs +1 -1
- package/global/run.mjs +64 -0
- package/global/update/command.mjs +1 -1
- package/install.sh +8 -7
- 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 +1 -0
- package/modules/deploy-kit/owner-cli.mjs +8 -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 +23 -14
- package/modules/deploy-kit/provider.mjs +20 -3
- package/modules/operator-auth/README.md +5 -0
- package/modules/operator-auth/accounts/display-name.mjs +23 -0
- package/modules/operator-auth/identity/oidc/config.mjs +10 -8
- package/modules/operator-auth/index.d.mts +2 -0
- package/modules/operator-auth/routes.mjs +4 -3
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/operator-auth/signin/index.mjs +3 -3
- package/modules/portability/README.md +13 -1
- package/modules/portability/import.mjs +19 -7
- package/modules/portability/legacy-safety.mjs +4 -20
- package/modules/portability/restore-safety.mjs +23 -0
- package/modules/release/catalogue.mjs +1 -1
- package/onboarding/port-probe.mjs +4 -2
- package/onboarding/process-diagnostics.mjs +4 -1
- 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
|
@@ -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);
|
|
@@ -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
|
}
|
|
@@ -133,6 +133,7 @@ version), domain rules in `oa_domain_rules`. `auth.accounts` exposes it and
|
|
|
133
133
|
| `/auth/owner-signin?token=…` | GET/HEAD | 200 owner sign-in confirmation for a live `rer signin` link, or 400 invalid/used/expired; **no writes** |
|
|
134
134
|
| `/auth/owner-signin` | POST | token; consume once for the active owner it names, 303 with cookie; see "Owner sign-in without mail" |
|
|
135
135
|
| `/auth/email` | POST | email; the signed-in operator's own sign-in email; fresh step-up proof; 409 `email_in_use` |
|
|
136
|
+
| `/auth/display-name` | POST | displayName; the signed-in operator's own name (1-120 characters); no step-up |
|
|
136
137
|
|
|
137
138
|
Unknown `/auth/*` paths return 404. Unsupported methods return 405. Except for invalid/expired confirmation GET/HEAD documents, known public
|
|
138
139
|
errors are JSON `{error:code}`: invalid input 400, unauthenticated 401, policy/host/
|
|
@@ -476,6 +477,10 @@ link). It revokes unused links sent to the old address and keeps sessions and
|
|
|
476
477
|
provider bindings. An address another operator holds is refused with
|
|
477
478
|
`email_in_use`. `STEP_UP_ACTIONS` gains `email:change`.
|
|
478
479
|
|
|
480
|
+
A name is corrected the same way, without a step-up: `POST /auth/display-name
|
|
481
|
+
{displayName}`. First-run `/setup` shows the owner's name as an editable field
|
|
482
|
+
that saves through it. Native accounts do not mount this route.
|
|
483
|
+
|
|
479
484
|
## Local dev identity and the key gate
|
|
480
485
|
|
|
481
486
|
`dev-gate.mjs` (exported as `devGate`, production-safe) is the per-checkout key
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// A signed-in operator corrects the name shown for them: at first-run setup
|
|
2
|
+
// (/setup) and later from the app's settings. It is not a credential, so no
|
|
3
|
+
// fresh proof is needed; the change is fenced to this session and operator version.
|
|
4
|
+
import { deny } from '../errors.mjs';
|
|
5
|
+
import { requirePost } from '../http.mjs';
|
|
6
|
+
import { displayName } from './admin.mjs';
|
|
7
|
+
|
|
8
|
+
export function displayNameChange({ config, store, clock, authenticate }) {
|
|
9
|
+
return {
|
|
10
|
+
async changeDisplayName(request, input) {
|
|
11
|
+
requirePost(request, config);
|
|
12
|
+
const actor = await authenticate(request);
|
|
13
|
+
if (!actor) deny('unauthenticated', 401);
|
|
14
|
+
const name = displayName(input?.displayName);
|
|
15
|
+
if (name !== actor.operator.displayName) {
|
|
16
|
+
const fence = store.actorFence(actor, clock());
|
|
17
|
+
const [changed] = await store.batch([[`UPDATE oa_operators SET display_name=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [name, actor.operator.id, actor.operator.version, ...fence.args]]]);
|
|
18
|
+
if (!changed.results.some(row => row.id === actor.operator.id)) deny('authority_changed', 409);
|
|
19
|
+
}
|
|
20
|
+
return store.operator(actor.operator.id);
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -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
|
}
|
|
@@ -196,6 +196,8 @@ export interface OperatorAuth<R extends string = Role> {
|
|
|
196
196
|
confirmOwnerSignIn?(request: Request, input: { token: string }): Promise<CompletedSession<R>>;
|
|
197
197
|
/** The signed-in operator's own sign-in email; needs a fresh step-up proof. */
|
|
198
198
|
changeEmail?(request: Request, input: { email: string }): Promise<Operator<R>>;
|
|
199
|
+
/** The signed-in operator's own display name (1-120 characters, trimmed). Absent with native accounts. */
|
|
200
|
+
changeDisplayName?(request: Request, input: { displayName: string }): Promise<Operator<R>>;
|
|
199
201
|
listDomainRules(request: Request): Promise<DomainRule[]>;
|
|
200
202
|
/** provider null lifts the rule. Needs a fresh step-up proof. */
|
|
201
203
|
setDomainRule(request: Request, input: { domain: string; provider: string | null }): Promise<DomainRule[]>;
|
|
@@ -41,8 +41,8 @@ export function createAuthHandler(auth) {
|
|
|
41
41
|
const preview = await auth.previewLink(request, token);
|
|
42
42
|
return await confirmationResponse({ branding: auth.presentation, preview, token, method: request.method });
|
|
43
43
|
}
|
|
44
|
-
// Composition without the owner link or
|
|
45
|
-
if ((path === OWNER_SIGNIN_PATH && !auth.confirmOwnerSignIn) || (path === '/auth/email' && !auth.changeEmail)) return json({ error: 'not_found' }, 404);
|
|
44
|
+
// Composition without the owner link, email or name change (native accounts) does not own these paths.
|
|
45
|
+
if ((path === OWNER_SIGNIN_PATH && !auth.confirmOwnerSignIn) || (path === '/auth/email' && !auth.changeEmail) || (path === '/auth/display-name' && !auth.changeDisplayName)) return json({ error: 'not_found' }, 404);
|
|
46
46
|
if (path === OWNER_SIGNIN_PATH && ['GET', 'HEAD'].includes(request.method)) {
|
|
47
47
|
const token = readParameters(url.searchParams).token ?? null;
|
|
48
48
|
const preview = await auth.previewOwnerSignIn(request, token);
|
|
@@ -65,7 +65,7 @@ export function createAuthHandler(auth) {
|
|
|
65
65
|
if (path === '/auth/settings/identity' && request.method === 'GET') {const value=await auth.identitySettings(request);return /text\/html/.test(request.headers.get('accept')??'')?await identitySettingsPage(value,auth.presentation):json(value);}
|
|
66
66
|
if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
|
|
67
67
|
const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
|
|
68
|
-
'/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email']);
|
|
68
|
+
'/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
|
|
69
69
|
if (!posts.has(path)) return json({ error: 'not_found' }, 404);
|
|
70
70
|
if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
|
|
71
71
|
const query = readParameters(url.searchParams);
|
|
@@ -93,6 +93,7 @@ export function createAuthHandler(auth) {
|
|
|
93
93
|
case '/auth/confirm': { const value = await auth.confirmLink(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
94
94
|
case OWNER_SIGNIN_PATH: { const value = await auth.confirmOwnerSignIn(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
95
95
|
case '/auth/email': return json(await auth.changeEmail(request, input));
|
|
96
|
+
case '/auth/display-name': return json(await auth.changeDisplayName(request, input));
|
|
96
97
|
case '/auth/review-session': { const value = await auth.issueReviewSession(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
97
98
|
case '/auth/step-up': {
|
|
98
99
|
const result = await auth.requestStepUp(request, input);
|
|
@@ -18,6 +18,7 @@ import { createAdmission, legacyAdmission } from './identity/admission.mjs';
|
|
|
18
18
|
import { createOidcProviders } from './identity/oidc/index.mjs';
|
|
19
19
|
import { ownerSignIn } from './accounts/owner-signin.mjs';
|
|
20
20
|
import { emailChange } from './accounts/email-change.mjs';
|
|
21
|
+
import { displayNameChange } from './accounts/display-name.mjs';
|
|
21
22
|
import { isLocalCli } from './local-cli.mjs';
|
|
22
23
|
import { devAdmitted } from './dev-admission.mjs';
|
|
23
24
|
import { oneClickAccounts } from './accounts/one-click.mjs';
|
|
@@ -79,6 +80,7 @@ export function createOperatorAuth(options) {
|
|
|
79
80
|
...fencedCredentials({store,authenticate,requireFreshProof,config,clock,hash}),
|
|
80
81
|
...ownerSignIn({ config, store, clock, sessions, limit }),
|
|
81
82
|
...emailChange({ config, store, clock, authenticate, requireFreshProof }),
|
|
83
|
+
...displayNameChange({ config, store, clock, authenticate }),
|
|
82
84
|
presentation: config.branding,
|
|
83
85
|
oneClick: oneClickAccounts({ config, store, clock, sessions, authorizedLink, requireRoute, afterConfirm: admission.afterConfirm }),
|
|
84
86
|
emailSignInAvailable: Boolean(mailSender),
|
|
@@ -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.'];
|
|
@@ -24,7 +24,7 @@ schema at construction. Apply the bookkeeping migration first. Policy fields:
|
|
|
24
24
|
| `derivedTables` | Virtual/FTS tables to regenerate; their shadow tables are excluded. |
|
|
25
25
|
| `secretColumns` | Per-table nullable base columns omitted at export and written as NULL. Primary keys and generated columns cannot be secret. |
|
|
26
26
|
| `exportRow(table,row)` | Pure, synchronous, idempotent transformation of encoded base cells. Restore writes its result verbatim; SQLite recomputes generated cells. |
|
|
27
|
-
| `replaceableTables` | Bootstrap
|
|
27
|
+
| `replaceableTables` | Bootstrap rows replaced in the atomic restore batch. Rows the destination's own migrations insert need no entry where the runner passes `migrations` (see "Migration-seeded rows"). Populated excluded dependents reachable through modifying FK actions refuse replacement. |
|
|
28
28
|
| `requiredConfiguration` | Setting names returned after restore for the owner to re-enter. |
|
|
29
29
|
| `validateStaged({db,tables,read,manifest})` | Read-only product validation before any object write; false or a thrown error refuses restore. `tables` names the staging tables for bounded SQL queries; `read` is a convenience for small tables. |
|
|
30
30
|
| `acceptedSchemas` | Map from an earlier full schema hash to `{upgradeRow(table,row)}`. Upgrade functions are pure and synchronous. No older schema is accepted by default. |
|
|
@@ -315,6 +315,18 @@ journal adoption and completion. FK cycles and self-references restore together.
|
|
|
315
315
|
An unsuccessful commit removes only owned objects. A lost commit acknowledgement
|
|
316
316
|
is resolved by reading durable completion before any cleanup.
|
|
317
317
|
|
|
318
|
+
### Migration-seeded rows
|
|
319
|
+
|
|
320
|
+
A fresh destination already holds the rows its own migrations insert, such as a
|
|
321
|
+
seed's default settings. When the runner passes `migrations` (Node runners: a
|
|
322
|
+
scratch replay of the destination's applied migrations), finalize treats a target
|
|
323
|
+
table holding exactly those rows as empty: the archive's rows replace them in the
|
|
324
|
+
restore batch, or they stay when the archive predates the table (an additive
|
|
325
|
+
bridge). The batch repeats the check. Any other row refuses with
|
|
326
|
+
`target_not_empty:<table>`, which the CLI reports with the table's name and the
|
|
327
|
+
export, reset and import commands to run. A Worker import has no replay, so a
|
|
328
|
+
hosted restore still needs such tables in `replaceableTables`.
|
|
329
|
+
|
|
318
330
|
An empty destination must be reserved for restore: pause destination writers and
|
|
319
331
|
serialize finalize/abort calls. Product writes to source tables can continue.
|
|
320
332
|
R2 has no compare-and-swap transaction covering bucket emptiness and writes.
|
|
@@ -8,7 +8,7 @@ import { checkManifest, checkPart, ContentVerifier, ArchiveVerifier } from './fo
|
|
|
8
8
|
import { fence, mergeJournal, tombstone } from './journal.mjs';
|
|
9
9
|
import { writeObject } from './payloads.mjs';
|
|
10
10
|
import { createCopy,sidecar,readCopy,restoreCopy } from './copies.mjs';
|
|
11
|
-
import { excludedDependentGuards } from './restore-safety.mjs';
|
|
11
|
+
import { excludedDependentGuards, migrationSeeded, seededCondition } from './restore-safety.mjs';
|
|
12
12
|
import { additiveBridge, sameSchemaMigrations, appliedMigrations } from './bridge.mjs';
|
|
13
13
|
import { legacyEmptyGuards, legacyAuditStatements, requireLegacyEmpty } from './legacy-safety.mjs';
|
|
14
14
|
export async function createImport(context,manifest,actor='direct',legacyRecovery) {
|
|
@@ -105,8 +105,20 @@ async function bucketsEmpty(context,row) {
|
|
|
105
105
|
}while(cursor);
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
|
-
function emptyGuards(context,row) {
|
|
109
|
-
return row.metadata.targets.filter(t=>!context.config.replaceableTables.includes(t.name)).map(t=>guard(context.db,`NOT EXISTS(SELECT 1 FROM ${quote(t.name)})`));
|
|
108
|
+
function emptyGuards(context,row,seeded) {
|
|
109
|
+
return row.metadata.targets.filter(t=>!context.config.replaceableTables.includes(t.name) && !seeded.some(s=>s.name===t.name)).map(t=>guard(context.db,`NOT EXISTS(SELECT 1 FROM ${quote(t.name)})`));
|
|
110
|
+
}
|
|
111
|
+
// A fresh installation already holds the rows its own migrations insert (settings and
|
|
112
|
+
// other seeded rows). A table holding exactly those, as a node runner's replay of the
|
|
113
|
+
// applied migrations shows, does not make it non-empty: the archive's rows replace
|
|
114
|
+
// them, or they stay when the archive predates the table. Any other row refuses.
|
|
115
|
+
async function destinationState(context,row) {
|
|
116
|
+
const {db,config}=context,filled=[];
|
|
117
|
+
for(const table of row.metadata.targets) if(!config.replaceableTables.includes(table.name) && await statement(db,`SELECT 1 FROM ${quote(table.name)} LIMIT 1`).first())filled.push(table.name);
|
|
118
|
+
const seeded=await migrationSeeded(db,filled,context.migrations);
|
|
119
|
+
for(const name of filled)insist(seeded.some(s=>s.name===name),'target_not_empty:'+name,409);
|
|
120
|
+
const archived=seeded.filter(s=>row.metadata.manifest.tables.some(t=>t.name===s.name)).map(s=>s.name);
|
|
121
|
+
return {seeded,replaced:[...config.replaceableTables,...archived]};
|
|
110
122
|
}
|
|
111
123
|
async function removeOwned(context,id) {
|
|
112
124
|
const owned=await all(context.db,'SELECT bucket,key FROM rer_portability_owned WHERE job=?',id);
|
|
@@ -137,8 +149,8 @@ export async function finalizeImport(context,id,{contentHash,archiveHash,laterJo
|
|
|
137
149
|
insist(archiveHash===archive.digest(),'archive_checksum',409);
|
|
138
150
|
const checked=await fence(db,manifest,row.metadata.copies,laterJournal);
|
|
139
151
|
if(row.metadata.legacyRecovery)await requireLegacyEmpty(context,row.metadata.legacyRecovery);
|
|
140
|
-
|
|
141
|
-
const dependentGuards=await excludedDependentGuards(db,row.metadata.targets,
|
|
152
|
+
const {seeded,replaced}=await destinationState(context,row);
|
|
153
|
+
const dependentGuards=await excludedDependentGuards(db,row.metadata.targets,replaced);
|
|
142
154
|
await bucketsEmpty(context,row);
|
|
143
155
|
await refuseDevData(db,row.metadata.copies,row.metadata.targets);
|
|
144
156
|
await refuseProviderData(db,row.metadata.copies,row.metadata.targets);
|
|
@@ -160,11 +172,11 @@ export async function finalizeImport(context,id,{contentHash,archiveHash,laterJo
|
|
|
160
172
|
}
|
|
161
173
|
for(const payload of manifest.payloads)await config.extraPayloads[payload.name].consume(binaryStream(context,id,payload,binaryIndexes),payload);
|
|
162
174
|
row.phase='complete';row.metadata.contentHash=digest;
|
|
163
|
-
await db.batch([db.prepare('PRAGMA defer_foreign_keys=ON'),...emptyGuards(context,row),...dependentGuards,...legacyEmptyGuards(db,row),
|
|
175
|
+
await db.batch([db.prepare('PRAGMA defer_foreign_keys=ON'),...emptyGuards(context,row,seeded),...seeded.map(t=>guard(db,...seededCondition(t))),...dependentGuards,...legacyEmptyGuards(db,row),
|
|
164
176
|
guard(db,'NOT EXISTS(SELECT 1 FROM rer_portability_epochs WHERE source=? AND epoch>?) AND NOT EXISTS(SELECT 1 FROM rer_portability_state WHERE source_identity=? AND epoch>?)',manifest.sourceIdentity,checked.epoch,manifest.sourceIdentity,checked.epoch),
|
|
165
177
|
...row.metadata.targets.map(t=>guard(db,`NOT EXISTS(SELECT 1 FROM ${quote(sidecar(row.metadata.copies[t.name]))} s JOIN rer_portability_journal j ON j.source=? AND j.tombstone=s.rer_portability_tombstone)`,manifest.sourceIdentity)),
|
|
166
178
|
...row.metadata.triggers.map(t=>db.prepare(`DROP TRIGGER ${quote(t.name)}`)),
|
|
167
|
-
...
|
|
179
|
+
...replaced.map(t=>db.prepare(`DELETE FROM ${quote(t)}`)),
|
|
168
180
|
...row.metadata.targets.flatMap(t=>restoreCopy(db,t,row.metadata.copies[t.name])),
|
|
169
181
|
...row.metadata.triggers.map(t=>db.prepare(t.sql)),...mergeJournal(db,manifest,checked),...legacyAuditStatements(db,row),save(db,row),
|
|
170
182
|
db.prepare('UPDATE rer_portability_state SET import_job=NULL,applying=0 WHERE id=1'),db.prepare('DELETE FROM rer_portability_guard')]);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { all, statement, guard, quote, insist } from './storage.mjs';
|
|
2
2
|
import { canonicalJson } from './hash.mjs';
|
|
3
|
+
import { migrationSeeded, seededCondition } from './restore-safety.mjs';
|
|
3
4
|
|
|
4
5
|
// Recovery requires a new installation, including excluded identity tables and
|
|
5
6
|
// normally replaceable product rows. Only SQLite/migration/transfer bookkeeping,
|
|
@@ -18,34 +19,17 @@ function shadowTables(tables) {
|
|
|
18
19
|
}
|
|
19
20
|
return shadows;
|
|
20
21
|
}
|
|
21
|
-
const imageSql=(table,columns)=>`SELECT json_array(${columns.map(c=>`quote(${quote(c)})`).join(',')}) AS image FROM ${quote(table)}`;
|
|
22
|
-
const MAX_SEED_ROWS=10000;
|
|
23
|
-
|
|
24
22
|
/** What the destination must still hold when the restore commits: `emptyTables` stay empty and
|
|
25
|
-
* each of `seededTables` keeps exactly the rows its migrations put there. A table with rows
|
|
26
|
-
*
|
|
27
|
-
* does not produce is listed as to-be-empty, so the preflight refuses it. */
|
|
23
|
+
* each of `seededTables` keeps exactly the rows its migrations put there. A table with other rows
|
|
24
|
+
* is listed as to-be-empty, so the preflight refuses it. */
|
|
28
25
|
export async function legacyTargetState(db,migrations) {
|
|
29
26
|
const tables=await all(db,"SELECT name,sql FROM sqlite_master WHERE type='table' AND sql IS NOT NULL ORDER BY name"),shadows=shadowTables(tables);
|
|
30
27
|
const names=tables.map(t=>t.name).filter(name=>!bookkeeping(name) && !shadows.has(name.toLowerCase()));
|
|
31
28
|
const filled=[];
|
|
32
29
|
for(const name of names)if(await statement(db,`SELECT 1 FROM ${quote(name)} LIMIT 1`).first())filled.push(name);
|
|
33
|
-
const seeded=
|
|
34
|
-
if(filled.length && migrations) {
|
|
35
|
-
const requests=[];
|
|
36
|
-
for(const name of filled)requests.push({name,columns:(await all(db,`SELECT name FROM pragma_table_info(?)`,name)).map(c=>c.name)});
|
|
37
|
-
// Without a usable replay no seed is vouched for, so those rows count as the installation's own.
|
|
38
|
-
const expected=await migrations().then(replay=>replay.rowImages(requests,MAX_SEED_ROWS),()=>new Map());
|
|
39
|
-
for(const {name,columns} of requests) {
|
|
40
|
-
const want=expected.get(name);
|
|
41
|
-
if(!want || (await statement(db,`SELECT count(*) AS n FROM ${quote(name)}`).first()).n!==want.length)continue;
|
|
42
|
-
const found=(await all(db,imageSql(name,columns))).map(r=>r.image).sort();
|
|
43
|
-
if(canonicalJson(found)===canonicalJson(want))seeded.push({name,columns,images:found});
|
|
44
|
-
}
|
|
45
|
-
}
|
|
30
|
+
const seeded=await migrationSeeded(db,filled,migrations);
|
|
46
31
|
return {emptyTables:names.filter(name=>!seeded.some(s=>s.name===name)),seededTables:seeded};
|
|
47
32
|
}
|
|
48
|
-
const seededCondition=table=>[`(SELECT count(*) FROM ${quote(table.name)})=? AND NOT EXISTS(SELECT 1 FROM (${imageSql(table.name,table.columns)}) WHERE image NOT IN (SELECT value FROM json_each(?)))`,table.images.length,JSON.stringify(table.images)];
|
|
49
33
|
export async function requireLegacyEmpty({db,buckets},{emptyTables,seededTables=[]}) {
|
|
50
34
|
for(const table of emptyTables)insist(!(await statement(db,`SELECT 1 FROM ${quote(table)} LIMIT 1`).first()),'legacy_target_not_empty:'+table,409);
|
|
51
35
|
for(const table of seededTables){const [condition,...values]=seededCondition(table);insist((await statement(db,`SELECT CASE WHEN (${condition}) THEN 1 ELSE 0 END AS ok`,...values).first()).ok===1,'legacy_target_not_empty:'+table.name,409);}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { all,statement,guard,quote,insist } from './storage.mjs';
|
|
2
|
+
import { canonicalJson } from './hash.mjs';
|
|
2
3
|
const identifier=value=>value.replace(/[A-Z]/g,c=>c.toLowerCase());
|
|
3
4
|
|
|
4
5
|
export async function excludedDependentGuards(db,targets,replaceable) {
|
|
@@ -28,3 +29,25 @@ export async function excludedDependentGuards(db,targets,replaceable) {
|
|
|
28
29
|
}
|
|
29
30
|
return guards;
|
|
30
31
|
}
|
|
32
|
+
const imageSql=(table,columns)=>`SELECT json_array(${columns.map(c=>`quote(${quote(c)})`).join(',')}) AS image FROM ${quote(table)}`;
|
|
33
|
+
const MAX_SEED_ROWS=10000;
|
|
34
|
+
|
|
35
|
+
/** Of the filled tables `names`, those holding exactly the rows the replay of the destination's
|
|
36
|
+
* applied migrations (migrations(), a node runner's scratch database) leaves there: the settings
|
|
37
|
+
* and other rows a fresh installation's own migrations seed. Without a usable replay none is. */
|
|
38
|
+
export async function migrationSeeded(db,names,migrations) {
|
|
39
|
+
if(!names.length || !migrations)return [];
|
|
40
|
+
const requests=[];
|
|
41
|
+
for(const name of names)requests.push({name,columns:(await all(db,`SELECT name FROM pragma_table_info(?)`,name)).map(c=>c.name)});
|
|
42
|
+
// Without a usable replay no seed is vouched for, so those rows count as the installation's own.
|
|
43
|
+
const expected=await migrations().then(replay=>replay.rowImages(requests,MAX_SEED_ROWS),()=>new Map()),seeded=[];
|
|
44
|
+
for(const {name,columns} of requests) {
|
|
45
|
+
const want=expected.get(name);
|
|
46
|
+
if(!want || (await statement(db,`SELECT count(*) AS n FROM ${quote(name)}`).first()).n!==want.length)continue;
|
|
47
|
+
const found=(await all(db,imageSql(name,columns))).map(r=>r.image).sort();
|
|
48
|
+
if(canonicalJson(found)===canonicalJson(want))seeded.push({name,columns,images:found});
|
|
49
|
+
}
|
|
50
|
+
return seeded;
|
|
51
|
+
}
|
|
52
|
+
/** The SQL condition (with its values) that `table` still holds exactly its seeded rows. */
|
|
53
|
+
export const seededCondition=table=>[`(SELECT count(*) FROM ${quote(table.name)})=? AND NOT EXISTS(SELECT 1 FROM (${imageSql(table.name,table.columns)}) WHERE image NOT IN (SELECT value FROM json_each(?)))`,table.images.length,JSON.stringify(table.images)];
|
|
@@ -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)) }));
|
|
@@ -16,13 +16,15 @@ async function bind(host, port) {
|
|
|
16
16
|
// A failed diagnostic is unknown, never evidence of a foreign owner. A real
|
|
17
17
|
// bind can still prove availability. If a bind loses a race but inspection
|
|
18
18
|
// finds no listener, retry the bind within the same inspection deadline.
|
|
19
|
-
|
|
19
|
+
// A free-port search (`searching`) only needs to move on from a port in use:
|
|
20
|
+
// it skips one on the failed bind alone, without the slow ownership check.
|
|
21
|
+
export async function probePort(host, port, { context = inspectionContext({ port }), hosts = [host], anyAddress = false, searching = false } = {}) {
|
|
20
22
|
const bindings = async () => {
|
|
21
23
|
for (const address of hosts) { const result = await bind(address, port); if (!result.available) return result; }
|
|
22
24
|
return { available: true };
|
|
23
25
|
};
|
|
24
26
|
let bound = await bindings(), listener, unchecked;
|
|
25
|
-
if (!bound.available && bound.code !== 'EADDRINUSE') return bound;
|
|
27
|
+
if (!bound.available && (bound.code !== 'EADDRINUSE' || searching)) return bound;
|
|
26
28
|
try { listener = await portListener(port, anyAddress ? undefined : host, context); }
|
|
27
29
|
catch (error) { if (!uncheckedInspection(error)) throw error; unchecked = error; }
|
|
28
30
|
if (listener) return { available: false, listener };
|
|
@@ -2,7 +2,7 @@ import {execFile} from 'node:child_process';
|
|
|
2
2
|
import {promisify} from 'node:util';
|
|
3
3
|
import {lstat,realpath,readFile,readdir,readlink} from 'node:fs/promises';
|
|
4
4
|
import {basename,join} from 'node:path';
|
|
5
|
-
import {homedir} from 'node:os';
|
|
5
|
+
import {availableParallelism,homedir,loadavg} from 'node:os';
|
|
6
6
|
import {isIP} from 'node:net';
|
|
7
7
|
import {setTimeout as delay} from 'node:timers/promises';
|
|
8
8
|
import {commandFailure,approvedFailure} from './failures.mjs';
|
|
@@ -13,6 +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
|
+
// A free-port search on a busy computer gets longer, still bounded: the budget
|
|
17
|
+
// grows with the 1-minute load per CPU, up to four times.
|
|
18
|
+
export const searchContext=(details={})=>inspectionContext({budgetMs:Math.round(15000*Math.min(4,Math.max(1,loadavg()[0]/availableParallelism()))),...details});
|
|
16
19
|
export const uncheckedInspection=error=>approvedFailure(error)?.ownershipUnchecked===true;
|
|
17
20
|
const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,noMatch=false,positiveResult}={})=>{
|
|
18
21
|
const invocation=[command,...args].join(' ').replaceAll(homedir(),'~');
|
|
@@ -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); }
|