@runeditrun/rer 0.2.19 → 0.2.21
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 -7
- package/cli/README.md +22 -21
- package/cli/adapter.mjs +5 -0
- package/cli/container.mjs +7 -2
- package/cli/contract.mjs +3 -4
- package/cli/delivery-declarations.mjs +36 -0
- package/cli/demo-host.mjs +6 -5
- package/cli/demo-removal-provider.mjs +24 -0
- package/cli/demo.mjs +16 -5
- package/cli/deploy-command.mjs +11 -5
- package/cli/deploy-hook.mjs +10 -14
- package/cli/deploy.mjs +4 -1
- package/cli/detached-server.mjs +2 -2
- package/cli/dev-identity.mjs +1 -1
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +13 -13
- package/cli/lifecycle.mjs +16 -49
- package/cli/listen.mjs +31 -0
- package/cli/local.mjs +12 -18
- package/cli/main.mjs +5 -0
- package/cli/managed-server.mjs +26 -44
- package/cli/output.mjs +1 -1
- package/cli/parse.mjs +3 -3
- package/cli/port.mjs +20 -20
- package/cli/production-auth.mjs +38 -0
- package/cli/server-proxy.mjs +2 -6
- package/cli/server-registry.mjs +7 -2
- package/cli/setup-input.mjs +3 -0
- package/global/CHANGELOG.md +15 -0
- package/global/README.md +7 -7
- package/global/cli/install.mjs +4 -28
- package/global/cli/path-link.mjs +25 -21
- package/global/launch/dev.mjs +1 -1
- package/global/launch/facts.mjs +11 -14
- package/global/launch/failure.mjs +20 -0
- package/global/launch/render.mjs +2 -6
- package/global/launch/worker.mjs +3 -3
- package/global/main.mjs +1 -1
- package/modules/container/build.mjs +5 -3
- package/modules/container/demo-egress.mjs +35 -0
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/d1-transport/index.d.mts +9 -0
- package/modules/d1-transport/index.mjs +124 -0
- package/modules/delivery-producer/bindings.mjs +140 -0
- package/modules/delivery-producer/declarations.mjs +49 -0
- package/modules/demo/README.md +34 -0
- package/modules/demo/effects.mjs +73 -0
- package/modules/demo/index.d.mts +15 -0
- package/modules/demo/index.mjs +63 -0
- package/modules/demo/label.d.mts +2 -0
- package/modules/demo/label.mjs +24 -0
- package/modules/demo/responses.mjs +26 -0
- package/modules/demo/sockets.mjs +13 -0
- package/modules/demo/vite.d.mts +2 -0
- package/modules/demo/vite.mjs +19 -0
- package/modules/demo-host/README.md +14 -1
- package/modules/demo-host/container.mjs +17 -11
- package/modules/demo-host/diagnostics.mjs +1 -0
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/placement.mjs +23 -0
- package/modules/demo-host/plan.mjs +1 -1
- package/modules/demo-host/startup.mjs +1 -1
- package/modules/demo-host/worker.mjs +2 -2
- package/modules/deploy-kit/README.md +12 -0
- package/modules/deploy-kit/health-request.mjs +7 -5
- package/modules/deploy-kit/owner.mjs +2 -2
- package/modules/deploy-kit/r2-objects.mjs +8 -5
- package/modules/job-queue/storage.mjs +4 -1
- package/modules/mail/README.md +19 -86
- package/modules/mail/src/core/validation.mjs +0 -1
- package/modules/mail/src/development/index.d.mts +1 -6
- package/modules/mail/src/development/index.mjs +3 -16
- package/modules/operator-auth/README.md +10 -9
- package/modules/operator-auth/csp.mjs +1 -2
- package/modules/operator-auth/dev/cli-session.mjs +32 -0
- package/modules/operator-auth/dev/index.mjs +18 -11
- package/modules/operator-auth/identity/email-link/index.mjs +3 -0
- package/modules/operator-auth/page.mjs +1 -1
- package/modules/operator-auth/signin/index.d.mts +1 -1
- package/modules/portability/README.md +6 -0
- package/modules/portability/catalogue.mjs +1 -1
- package/modules/portability/copies.mjs +17 -2
- package/modules/portability/index.mjs +2 -0
- package/modules/portability/storage.mjs +5 -1
- package/onboarding/README.md +8 -11
- package/onboarding/adapter-auth.mjs +6 -38
- package/onboarding/adapter-labels.mjs +1 -1
- package/onboarding/adapter.mjs +8 -11
- package/onboarding/app-fetch.mjs +1 -1
- package/onboarding/dependency-approval.mjs +5 -15
- package/onboarding/dev-identity.mjs +1 -1
- package/onboarding/operator-install.mjs +6 -7
- package/onboarding/operator-installer.mjs +5 -5
- package/onboarding/operator-prerequisites.mjs +4 -5
- package/onboarding/port-probe.mjs +38 -0
- package/onboarding/process-diagnostics.mjs +36 -20
- package/onboarding/server.mjs +1 -1
- package/onboarding/ui/app.js +1 -1
- package/operations/README.md +3 -0
- package/package.json +4 -2
- package/scripts/publish-check/public_hygiene.py +31 -10
- package/modules/mail/src/development/viewer-html.mjs +0 -42
- package/modules/mail/src/development/viewer.mjs +0 -72
- package/modules/operator-auth/dev/badge.mjs +0 -44
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { isLocalCli } from '../local-cli.mjs';
|
|
2
|
+
import { requireLoopback, requirePost, sessionCookie } from '../http.mjs';
|
|
3
|
+
import { opaqueToken } from '../crypto.mjs';
|
|
4
|
+
import { safeReturnTo } from '../policy.mjs';
|
|
5
|
+
import { isActiveOperator } from '../accounts/roles.mjs';
|
|
6
|
+
import { AuthError } from '../errors.mjs';
|
|
7
|
+
import { devNotFound } from '../dev-gate.mjs';
|
|
8
|
+
import { readInput } from '../input.mjs';
|
|
9
|
+
|
|
10
|
+
// Owner-side local tooling proves possession of this installation's session
|
|
11
|
+
// secret. This endpoint exists only in the local dev entry, never production.
|
|
12
|
+
export async function cliSession(request, { config, store, hash, everyone }, headers) {
|
|
13
|
+
requireLoopback(request);
|
|
14
|
+
requirePost(request, config);
|
|
15
|
+
if (!await isLocalCli(request, config)) return devNotFound();
|
|
16
|
+
const input = await readInput(request);
|
|
17
|
+
const ownerEmail = (await everyone()).find(persona => persona.as === 'owner')?.email;
|
|
18
|
+
const operator = ownerEmail ? await store.byEmail(ownerEmail) : null;
|
|
19
|
+
if (operator?.role !== 'owner' || !isActiveOperator(operator, config.allowList)) throw new AuthError('owner_required', 403);
|
|
20
|
+
const now = Date.now(), token = opaqueToken();
|
|
21
|
+
const session = { id: crypto.randomUUID(), hash: await hash(token), expiresAt: now + config.sessionSeconds * 1000 };
|
|
22
|
+
const record = await store.issue({ operatorId: operator.id, expectedVersion: operator.version, session, now, kind: 'native' });
|
|
23
|
+
if (!record || record.operator.role !== 'owner') throw new AuthError('authority_changed', 409);
|
|
24
|
+
// A local owner proof uses the existing durable, version-fenced proof ledger.
|
|
25
|
+
// It can authorize setup linking without manufacturing an email credential.
|
|
26
|
+
const inserted = await store.run(`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at,consumed_at)
|
|
27
|
+
SELECT ?,?,?,?,?,?,?,?,?,? WHERE EXISTS(SELECT 1 FROM oa_sessions s JOIN oa_operators o ON o.id=s.operator_id
|
|
28
|
+
WHERE s.id=? AND s.revoked_at IS NULL AND o.role='owner' AND o.status='active' AND o.version=?)`,
|
|
29
|
+
[crypto.randomUUID(), await hash(opaqueToken()), record.id, operator.id, operator.version, 'local-cli', '/', now, session.expiresAt, now, record.id, operator.version]);
|
|
30
|
+
if (inserted.meta.changes !== 1) throw new AuthError('authority_changed', 409);
|
|
31
|
+
return new Response(null, { status: 303, headers: { ...headers, location: safeReturnTo(input.returnTo), 'set-cookie': sessionCookie(token, config) } });
|
|
32
|
+
}
|
|
@@ -7,13 +7,15 @@ import { AuthStore } from '../accounts/store.mjs';
|
|
|
7
7
|
import { createOperatorAuth } from '../service.mjs';
|
|
8
8
|
import { AuthError } from '../errors.mjs';
|
|
9
9
|
import { hashToken, opaqueToken } from '../crypto.mjs';
|
|
10
|
-
import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
|
|
10
|
+
import { readCookie, sessionCookie, isLoopbackHost, escapeHtml } from '../http.mjs';
|
|
11
11
|
import { safeReturnTo } from '../policy.mjs';
|
|
12
12
|
import { isActiveOperator, defaultRolePolicy } from '../accounts/roles.mjs';
|
|
13
13
|
import { devGate, devNotFound } from '../dev-gate.mjs';
|
|
14
14
|
import { registerDevAdmission } from '../dev-admission.mjs';
|
|
15
15
|
import { definePersonas } from './personas.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import { cliSession } from './cli-session.mjs';
|
|
17
|
+
import { decorateLabel } from '../../demo/label.mjs';
|
|
18
|
+
import { pageResponse } from '../page.mjs';
|
|
17
19
|
|
|
18
20
|
export const DEV_LAYER_MARKER = 'rer-dev-layer:local-only-never-deploy';
|
|
19
21
|
const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-rer-dev-layer': DEV_LAYER_MARKER };
|
|
@@ -28,7 +30,7 @@ export function managedInstallation(env) {
|
|
|
28
30
|
|
|
29
31
|
/**
|
|
30
32
|
* Wraps a seed's Worker with dev sign-in (`/auth/dev/enter?as=…`), the persona
|
|
31
|
-
* list (`/__dev/personas`)
|
|
33
|
+
* list (`/__dev/personas`). Every identity surface needs the key
|
|
32
34
|
* gate and answers 404 without it. `config(env)` is the seed's own AuthConfig
|
|
33
35
|
* and `personas()` its devPersonas() declaration.
|
|
34
36
|
*/
|
|
@@ -42,16 +44,24 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
42
44
|
// Never admit a dev credential here; with dev identity on, serve nothing.
|
|
43
45
|
registerDevAdmission(null);
|
|
44
46
|
if (env.RER_DEV_IDENTITY !== 'off') return rejectedResponse(request, text(503, 'Dev identity refuses to run beside RER_INSTALLATION_ID with a non-loopback RER_MANAGEMENT_ORIGIN. Remove those bindings from local settings or use rer dev --login.'));
|
|
45
|
-
return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
|
|
47
|
+
return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' || new URL(request.url).pathname === '/auth/local/cli-session' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
|
|
46
48
|
}
|
|
47
49
|
const gate = devGate({ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, local: env.AUTH_LOCAL === 'true' });
|
|
48
50
|
registerDevAdmission(gate ? r => gate.admits(r) : null);
|
|
49
51
|
const path = new URL(request.url).pathname;
|
|
50
|
-
if (path === '/
|
|
51
|
-
|
|
52
|
+
if (path === '/__dev/key') return gate ? gate.exchange(request) : devNotFound();
|
|
53
|
+
if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && request.method === 'GET') {
|
|
54
|
+
if (!await gate.admits(request)) return new Response(null, { status: 303, headers: { ...headers, location: '/__dev/key' } });
|
|
55
|
+
const { config } = identity(env, authConfig, declared);
|
|
56
|
+
const returnTo = safeReturnTo(new URL(request.url).searchParams.get('returnTo'));
|
|
57
|
+
const href = `/auth/dev/enter?as=owner&returnTo=${encodeURIComponent(returnTo)}`;
|
|
58
|
+
return decorateLabel(await pageResponse({ branding: config.branding, heading: 'Open your local app', content: `<a class="action" href="${escapeHtml(href)}">Continue as owner</a>` }), env.RER_DEMO === '1' ? 'Demo' : 'Dev');
|
|
59
|
+
}
|
|
60
|
+
if (path === '/auth/dev/enter' || path === '/__dev/personas' || path === '/auth/local/cli-session') {
|
|
61
|
+
if (!gate || env.RER_DEV_IDENTITY === 'off' || (path !== '/auth/local/cli-session' && !await gate.admits(request))) return rejectedResponse(request, devNotFound());
|
|
52
62
|
const context = identity(env, authConfig, declared);
|
|
53
63
|
try {
|
|
54
|
-
const response = path === '/__dev/personas' ? Response.json(await context.list(), { headers }) : await enter(request, gate, context);
|
|
64
|
+
const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(), { headers }) : await enter(request, gate, context);
|
|
55
65
|
return rejectedResponse(request, response);
|
|
56
66
|
} catch (error) {
|
|
57
67
|
if (error instanceof AuthError) return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
|
|
@@ -60,9 +70,7 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
60
70
|
}
|
|
61
71
|
const response = await worker.fetch(request, original, execution);
|
|
62
72
|
if (!gate || request.method !== 'GET' || path.startsWith('/__dev/')) return response;
|
|
63
|
-
|
|
64
|
-
const badge = admitted && env.RER_DEV_IDENTITY !== 'off' ? await identity(env, authConfig, declared).badge(request) : null;
|
|
65
|
-
return decorate(response, { exchange: path === '/', badge });
|
|
73
|
+
return decorateLabel(response, env.RER_DEMO === '1' ? 'Demo' : 'Dev');
|
|
66
74
|
},
|
|
67
75
|
};
|
|
68
76
|
}
|
|
@@ -97,7 +105,6 @@ function identity(env, authConfig, declared) {
|
|
|
97
105
|
return { ...actor, hash: await hash(readCookie(request, config)) };
|
|
98
106
|
},
|
|
99
107
|
list: async () => [...(await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) })), { as: 'signed-out' }],
|
|
100
|
-
async badge(request) { return { session: await current(request), choices: (await everyone()).filter(persona => persona.email) }; },
|
|
101
108
|
};
|
|
102
109
|
}
|
|
103
110
|
|
|
@@ -55,6 +55,9 @@ export function createEmailLinkLifecycle({ config: input, clock = Date.now, mail
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
async function requireFreshProof(actor) {
|
|
58
|
+
// Authentication already required the local key gate for this session.
|
|
59
|
+
// Dev confirms actions directly rather than sending an unusable mail link.
|
|
60
|
+
if (config.local && actor.kind === 'dev') return;
|
|
58
61
|
if (!await store.steppedUp(actor, clock() - STEP_UP_SECONDS * 1000, clock())) deny('step_up_required', 403);
|
|
59
62
|
}
|
|
60
63
|
const authenticate = request => store.authenticate(request);
|
|
@@ -23,7 +23,7 @@ export async function pageResponse({ branding, title, heading, content, status =
|
|
|
23
23
|
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(css)));
|
|
24
24
|
const hash = btoa(String.fromCharCode(...digest));
|
|
25
25
|
const product = escapeHtml(branding.productName);
|
|
26
|
-
const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand"><span class="mark" aria-hidden="true"></span>${product}</p><h1>${heading}</h1>${content}</main></body></html>`;
|
|
26
|
+
const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand"><span class="mark" aria-hidden="true"></span><span data-rer-name>${product}</span></p><h1>${heading}</h1>${content}</main></body></html>`;
|
|
27
27
|
const headers = { ...securityHeaders(), 'Content-Type': 'text/html; charset=utf-8' };
|
|
28
28
|
// A form may post to this origin only, plus any origin its own redirect must reach (a provider's authorization endpoint).
|
|
29
29
|
if (formTargets.length) headers['Content-Security-Policy'] = headers['Content-Security-Policy'].replace("form-action 'self'", `form-action 'self' ${formTargets.join(' ')}`);
|
|
@@ -3,7 +3,7 @@ import type { OperatorAuth } from '../index.mjs';
|
|
|
3
3
|
export interface SignInPageOptions {
|
|
4
4
|
/** While the first owner is unclaimed: the setup form and its instructions. */
|
|
5
5
|
setup?: (request: Request) => null | false | undefined | { instructions?: string } | Promise<null | false | undefined | { instructions?: string }>;
|
|
6
|
-
/** Extra same-origin links under the form
|
|
6
|
+
/** Extra same-origin links under the form. */
|
|
7
7
|
links?: (request: Request) => Array<{ href: string; label: string }> | Promise<Array<{ href: string; label: string }>>;
|
|
8
8
|
defaultReturnTo?: string;
|
|
9
9
|
}
|
|
@@ -292,6 +292,10 @@ by table name. Product-only staging keeps restore queries small even with long
|
|
|
292
292
|
column names.
|
|
293
293
|
Advance normalizes the durable snapshot, sorts archived keys and checks attachment
|
|
294
294
|
references again before completing the archive.
|
|
295
|
+
The shared D1 transport preserves mixed-script text through SQLite decoding and
|
|
296
|
+
accounts for workerd's whole-call string width. Snapshot and archive-segment
|
|
297
|
+
reads are bounded before crossing the provider boundary; staging and restore
|
|
298
|
+
transactions remain atomic.
|
|
295
299
|
`exports.advance(id,{expectedPart,maxParts})` commits durable bounded parts;
|
|
296
300
|
`expectedPart` makes a lost-acknowledgement retry a no-op. Status reports progress;
|
|
297
301
|
download streams completed jobs. Abort removes snapshots and stored parts.
|
|
@@ -417,6 +421,8 @@ executes the copied Worker and CLI. Tests and development fixtures are not copie
|
|
|
417
421
|
|
|
418
422
|
```text
|
|
419
423
|
modules/portability/index.mjs
|
|
424
|
+
modules/d1-transport/index.mjs
|
|
425
|
+
modules/d1-transport/index.d.mts
|
|
420
426
|
modules/portability/index.d.mts
|
|
421
427
|
modules/portability/lines.mjs
|
|
422
428
|
modules/portability/hash.mjs
|
|
@@ -52,7 +52,7 @@ export async function catalogue(db,config) {
|
|
|
52
52
|
columns.forEach(c=>{if(c.hidden)c.generated=c.hidden===2?'virtual':'stored';delete c.hidden;});
|
|
53
53
|
// Both archived base cells and visible staging reads must fit D1's SQL
|
|
54
54
|
// limit, with room for copy names and joins.
|
|
55
|
-
insist([false,true].every(encoded=>utf8(projectedColumns({columns},encoded)).length+1024<=100000),'transfer_sql_limit:'+entry.name);
|
|
55
|
+
insist([false,true].every(encoded=>utf8(projectedColumns({columns},encoded)).length+1024+columns.length*64<=100000),'transfer_sql_limit:'+entry.name);
|
|
56
56
|
const dependencies=[...new Set((await all(db,`PRAGMA foreign_key_list(${quote(entry.name)})`)).map(ref=>objects.find(x=>x.type==='table' && identifier(x.name)===identifier(ref.table))?.name??ref.table))].sort();
|
|
57
57
|
for(const parent of dependencies) insist(!excluded.some(x=>x.name===parent),'excluded_foreign_key:'+entry.name+':'+parent);
|
|
58
58
|
const rowidAlias=columns.some(c=>c.pk)?null:['rowid','_rowid_','oid'].find(alias=>!columns.some(c=>c.name.toLowerCase()===alias));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { all,statement,quote,insist } from './storage.mjs';
|
|
2
2
|
import { projectedColumns,encodedRow,mapRow,bindCell,writableColumns } from './catalogue.mjs';
|
|
3
|
-
import { canonicalJson } from './hash.mjs';
|
|
3
|
+
import { canonicalJson, utf8 } from './hash.mjs';
|
|
4
4
|
import { generatedCopySQL } from './generated.mjs';
|
|
5
5
|
|
|
6
6
|
export const sidecar=copy=>copy+'_meta';
|
|
@@ -10,6 +10,7 @@ export function copyRowid(table) {
|
|
|
10
10
|
}
|
|
11
11
|
const keys=table=>table.columns.filter(c=>c.pk).sort((a,b)=>a.pk-b.pk);
|
|
12
12
|
const order=table=>keys(table).length?keys(table).map(c=>quote(c.name)).join(','):quote(table.rowidAlias);
|
|
13
|
+
const sum=terms=>terms.length<2?(terms[0]??'0'):`(${sum(terms.slice(0,terms.length>>1))}+${sum(terms.slice(terms.length>>1))})`;
|
|
13
14
|
export function createCopy(db,table,copy,snapshot=false) {
|
|
14
15
|
const ordering=order(table),meta=quote(sidecar(copy));
|
|
15
16
|
const columns=writableColumns(table).map(c=>quote(c.name)).join(',');
|
|
@@ -22,7 +23,21 @@ export function createCopy(db,table,copy,snapshot=false) {
|
|
|
22
23
|
}
|
|
23
24
|
export async function readCopy(db,table,copy,offset,limit,encoded=false) {
|
|
24
25
|
const columns=projectedColumns(table,encoded);
|
|
25
|
-
const
|
|
26
|
+
const selected=encoded?writableColumns(table):table.columns;
|
|
27
|
+
const from=`FROM ${quote(copy)} s JOIN ${quote(sidecar(copy))} m ON s.${copyRowid(table)}=m.rer_portability_copy_rowid ORDER BY m.rer_portability_row_order LIMIT ? OFFSET ?`;
|
|
28
|
+
// Read sizes first, never discover a large row by overflowing the RPC result.
|
|
29
|
+
// 12x covers JSON control escapes (6x), binary arrays (4x), and whole-string
|
|
30
|
+
// two-byte workerd serialization. Names and scalar framing count separately.
|
|
31
|
+
const overhead=selected.reduce((n,c)=>n+utf8(c.name).length*12+128,256);
|
|
32
|
+
const weight=sum(selected.map(c=>`COALESCE(length(CAST(s.${quote(c.name)} AS BLOB)),0)`));
|
|
33
|
+
const sizes=await all(db,`SELECT (${weight})*12+${overhead} AS bytes ${from}`,limit,offset);
|
|
34
|
+
const raw=[];
|
|
35
|
+
for(let start=0;start<sizes.length;) {
|
|
36
|
+
let end=start,bytes=0;
|
|
37
|
+
while(end<sizes.length && bytes+sizes[end].bytes<30*1024*1024){bytes+=sizes[end].bytes;end++;}
|
|
38
|
+
insist(end>start,'row_part_too_large:'+table.name);
|
|
39
|
+
raw.push(...await all(db,`SELECT ${columns} ${from}`,end-start,offset+start));start=end;
|
|
40
|
+
}
|
|
26
41
|
const meta=await all(db,`SELECT * FROM ${quote(sidecar(copy))} ORDER BY rer_portability_row_order LIMIT ? OFFSET ?`,limit,offset);
|
|
27
42
|
insist(raw.length===meta.length,'copy_inventory:'+table.name);
|
|
28
43
|
return raw.map((row,i)=>({row,meta:meta[i]}));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { policy, catalogue } from './catalogue.mjs';
|
|
2
|
+
import { wireDatabase } from '../d1-transport/index.mjs';
|
|
2
3
|
import { insist, job } from './storage.mjs';
|
|
3
4
|
import { createExport, advanceExport, exportStatus, downloadExport, abortExport } from './export.mjs';
|
|
4
5
|
import { createImport, uploadPart, finalizeImport, importStatus, abortImport } from './import.mjs';
|
|
@@ -10,6 +11,7 @@ export { canonicalJson, sha256 } from './hash.mjs';
|
|
|
10
11
|
export { PortabilityError } from './storage.mjs';
|
|
11
12
|
export { createPortabilityHandler } from './http.mjs';
|
|
12
13
|
export async function createPortability({db,buckets={},policy:input,migrations}) {
|
|
14
|
+
db=wireDatabase(db);
|
|
13
15
|
const config=policy(input);await catalogue(db,config);
|
|
14
16
|
for(const name of Object.keys(config.buckets))insist(buckets[name] && typeof buckets[name].get==='function','missing_bucket:'+name);
|
|
15
17
|
const context={db,buckets,config,migrations};
|
|
@@ -36,7 +36,11 @@ export function partStatements(db,id,part) {
|
|
|
36
36
|
return result;
|
|
37
37
|
}
|
|
38
38
|
export async function readPart(db,id,index) {
|
|
39
|
-
const rows=
|
|
39
|
+
const rows=[];
|
|
40
|
+
for(let offset=0;;offset+=64) {
|
|
41
|
+
const page=await all(db,'SELECT data FROM rer_portability_segments WHERE job=? AND part=? ORDER BY segment LIMIT 64 OFFSET ?',id,index,offset);
|
|
42
|
+
rows.push(...page);if(page.length<64)break;
|
|
43
|
+
}
|
|
40
44
|
insist(rows.length,'part_missing');
|
|
41
45
|
return JSON.parse(rows.map(x=>x.data).join(''));
|
|
42
46
|
}
|
package/onboarding/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
First-party seeds expose public operations through the RER dispatcher. From a
|
|
4
4
|
runnable seed checkout, the supported local sequence begins with
|
|
5
5
|
`rer install`, `rer setup` and
|
|
6
|
-
`rer dev`; owner sign-in uses the
|
|
6
|
+
`rer dev`; owner sign-in uses the one-click `RER_OPEN` link. The
|
|
7
7
|
command contract and flags are documented in the runnable checkout's root
|
|
8
8
|
`RUN-LOCALLY.md`.
|
|
9
9
|
|
|
@@ -48,9 +48,8 @@ A seed that declares `devIdentity` on its command adapter gets the key-gated way
|
|
|
48
48
|
in from the installer without declaring anything more: before setup the installer
|
|
49
49
|
creates the checkout's dev key (as `rer setup` does) and passes it to the hooks as
|
|
50
50
|
`context.devKey`. The `start` hook must give it to the temporary app (an
|
|
51
|
-
`RER_DEV_KEY` binding),
|
|
52
|
-
|
|
53
|
-
key exchange (`RER_OPEN`); the key never enters saved state or logs. A seed
|
|
51
|
+
`RER_DEV_KEY` binding). When setup completes, the installer page offers the app
|
|
52
|
+
through the key exchange and dev owner entry (`RER_OPEN`); the key never enters saved state or logs. A seed
|
|
54
53
|
without `devIdentity` gets no key and its installer is unchanged.
|
|
55
54
|
|
|
56
55
|
`rer-setup.json` is the only setup schema. Its fields, groups, defaults,
|
|
@@ -104,8 +103,7 @@ Declare the theme in two places that name the same file:
|
|
|
104
103
|
and `firstRunResponse(request, bindings, auth, { theme: { href:
|
|
105
104
|
'/rer-theme.css', productName, accentColor? } })` from `src/base/setup` for
|
|
106
105
|
`/setup`; the foundation sign-in uses `themeFrame` from
|
|
107
|
-
`src/base/theme-frame` the same way
|
|
108
|
-
`createDevelopmentOutboxHandler({ ..., theme: '/rer-theme.css' })`.
|
|
106
|
+
`src/base/theme-frame` the same way.
|
|
109
107
|
`accentColor` colours buttons when the theme declares no accent. A seed's own
|
|
110
108
|
pages may read the same tokens by linking the file.
|
|
111
109
|
|
|
@@ -116,12 +114,11 @@ and the foundation template's `public/rer-theme.css` are worked examples.
|
|
|
116
114
|
|
|
117
115
|
Setup validates answers before effects, then uses the declared lifecycle to
|
|
118
116
|
prepare local state, private settings, build and migrations, start the real
|
|
119
|
-
application briefly
|
|
120
|
-
the loopback development outbox. It stops the temporary app before returning.
|
|
117
|
+
application briefly and prepare the first owner. It stops the temporary app before returning.
|
|
121
118
|
Reruns preserve an existing owner, data and exact settings bytes; setup does
|
|
122
119
|
not create a second owner or rotate secrets. Dev and preview use the saved
|
|
123
|
-
owner and canonical durable state.
|
|
124
|
-
|
|
120
|
+
owner and canonical durable state. Dev opens through the local identity entry;
|
|
121
|
+
application mail is silently suppressed in development and demo.
|
|
125
122
|
|
|
126
123
|
Adapters use the shared captured command store for child work. It redacts
|
|
127
124
|
registered credential values from terminal output and private logs, records
|
|
@@ -145,7 +142,7 @@ exports and deployment receipts.
|
|
|
145
142
|
Each first-party adapter declares which resources local export/import supports.
|
|
146
143
|
Every first-party seed verifies a complete local export/import/export round
|
|
147
144
|
trip across those resources. Archives are private and integrity-checked;
|
|
148
|
-
owner/auth,
|
|
145
|
+
owner/auth, historical development mail, private settings and transient runtime state remain
|
|
149
146
|
excluded. Import validates and restores atomically into an empty destination.
|
|
150
147
|
Remote transfer is supported only when every required resource has a complete
|
|
151
148
|
adapter implementation; unsupported targets fail visibly.
|
|
@@ -3,7 +3,6 @@ import { appFetch } from './app-fetch.mjs';
|
|
|
3
3
|
import { createHmac } from 'node:crypto';
|
|
4
4
|
import {commandFailure,installationFailure} from './failures.mjs';
|
|
5
5
|
import { labels } from './adapter-labels.mjs';
|
|
6
|
-
const outboxPath = '/__dev/outbox'; // modules/mail/src/development default path
|
|
7
6
|
|
|
8
7
|
// The CLI's own requests to its loopback server prove they come from the
|
|
9
8
|
// installation's owner-side tooling (modules/operator-auth/local-cli.mjs), so
|
|
@@ -27,11 +26,11 @@ const errorCode = async response => { try { const code = (await response.json())
|
|
|
27
26
|
export async function owner(context, hook) {
|
|
28
27
|
const { store } = context;
|
|
29
28
|
await store.step(labels.owner);
|
|
30
|
-
await approveSetupDependencies(context, post
|
|
29
|
+
await approveSetupDependencies(context, post);
|
|
31
30
|
if(context.ownerClaim?.mode==='idp'){context.ownerClaimed='pending-idp';await store.step('The linked provider must grant the designated installation owner');return;}
|
|
32
31
|
const { path = '/auth/bootstrap', tokenKey = context.ownerClaim?.tokenField ?? 'SETUP_TOKEN', displayName = input => input.displayName || input.name || 'Owner', returnTo = '/' } = hook;
|
|
33
32
|
const token = context.vars[tokenKey];
|
|
34
|
-
if (!token && hook.existingOwnerViaSignIn) { await store.step('
|
|
33
|
+
if (!token && hook.existingOwnerViaSignIn) { await store.step('Keeping the existing owner'); return; }
|
|
35
34
|
if (!token) {
|
|
36
35
|
throw authFailure(context,labels.owner,`${tokenKey} is missing from the private settings.`);
|
|
37
36
|
}
|
|
@@ -46,44 +45,13 @@ export async function owner(context, hook) {
|
|
|
46
45
|
throw authFailure(context,labels.owner,`HTTP ${response.status} (${code}).`);
|
|
47
46
|
}
|
|
48
47
|
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
// needs no mail provider and no email is sent.
|
|
48
|
+
// Keep only the destination in installer state. The browser obtains its
|
|
49
|
+
// one-click dev identity through the authenticated /api/open-app response.
|
|
52
50
|
export async function signIn(context, hook) {
|
|
53
|
-
const { store } = context;
|
|
54
51
|
if(context.ownerClaim?.mode==='idp' && context.ownerClaimed==='pending-idp')return;
|
|
55
|
-
await store.step(labels.signIn);
|
|
52
|
+
await context.store.step(labels.signIn);
|
|
56
53
|
if (typeof hook === 'function') { context.appUrl = await hook(context); return; }
|
|
57
|
-
|
|
58
|
-
const address = context.signInEmail ?? (emailKey ? context.vars[emailKey] : email(context.input));
|
|
59
|
-
if (typeof address !== 'string' || !address.includes('@')) { throw authFailure(context,labels.signIn,'no owner email.'); }
|
|
60
|
-
const before = new Set(await outboxMessages(context, outbox, address, true));
|
|
61
|
-
let response;
|
|
62
|
-
try { response = await post(context, magicLink, { email: address, returnTo }); } catch (error) {
|
|
63
|
-
if (context.signal?.aborted) throw error;
|
|
64
|
-
throw authFailure(context,labels.signIn,'the application did not answer.');
|
|
65
|
-
}
|
|
66
|
-
if (response.status !== 202) { throw authFailure(context,labels.signIn,`HTTP ${response.status} (${await errorCode(response)}).`); }
|
|
67
|
-
await response.body?.cancel();
|
|
68
|
-
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
69
|
-
const id = (await outboxMessages(context, outbox, address)).find(message => !before.has(message));
|
|
70
|
-
if (id) { context.appUrl = new URL(`${outbox}?message=${encodeURIComponent(id)}`, context.origin).href; await store.step('Your sign-in link is waiting in the development outbox'); return; }
|
|
71
|
-
await new Promise(resolve => setTimeout(resolve, 200));
|
|
72
|
-
}
|
|
73
|
-
throw authFailure(context,labels.signIn,'no message reached the development outbox. Check that the retained database owner matches the private owner settings; preserve data or run rer reset --yes.');
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
async function outboxMessages(context, path, address, required = false) {
|
|
77
|
-
let response;
|
|
78
|
-
// A dev-identity seed gates its outbox with the checkout's key; present it.
|
|
79
|
-
try { response = await appFetch(new URL(path, context.origin), { signal: context.signal, headers: context.devKey ? { 'x-rer-dev-key': context.devKey } : {} }); } catch (error) {
|
|
80
|
-
if (context.signal?.aborted) throw error;
|
|
81
|
-
if(required){context.store.report?.('Local development outbox is unavailable. Run rer setup before requesting sign-in.');throw context.fail('setup');}
|
|
82
|
-
return [];
|
|
83
|
-
}
|
|
84
|
-
if (!response.ok) { await response.body?.cancel();if(required){context.store.report?.('Local development outbox is unavailable. Run rer setup before requesting sign-in.');throw context.fail('setup');}return []; }
|
|
85
|
-
const html = await response.text(), wanted = `To: ${address.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))}</p>`;
|
|
86
|
-
return html.split('<article>').slice(1).filter(article => article.toLowerCase().includes(wanted.toLowerCase())).map(article => /\?message=([^"&]+)"/.exec(article)?.[1]).filter(Boolean).map(decodeURIComponent);
|
|
54
|
+
context.appUrl = new URL(hook.returnTo ?? '/', context.origin).href;
|
|
87
55
|
}
|
|
88
56
|
|
|
89
57
|
function authFailure(context,label,reason){const message=context.store.redact?.(`${label}: ${reason}`)??`${label}: ${reason}`;context.store.report?.(message);return installationFailure('command_failed',{step:'setup',diagnostic:commandFailure(message)});}
|
|
@@ -6,7 +6,7 @@ export const labels = Object.freeze({
|
|
|
6
6
|
migrate: 'Applying database migrations',
|
|
7
7
|
start: 'Starting your application on this computer',
|
|
8
8
|
owner: 'Claiming the first owner',
|
|
9
|
-
signIn: 'Opening
|
|
9
|
+
signIn: 'Opening your application',
|
|
10
10
|
hosting: 'Deploying to your Cloudflare account',
|
|
11
11
|
complete: 'Your application is running locally',
|
|
12
12
|
built: 'Your application is built',
|
package/onboarding/adapter.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { credentialValues } from './redaction.mjs';
|
|
|
10
10
|
import { dependencyEnvironment } from './dependency-environment.mjs';
|
|
11
11
|
import { labels } from './adapter-labels.mjs';
|
|
12
12
|
import { chooseOrigin, prepareSettings, readSettings } from './adapter-settings.mjs';
|
|
13
|
-
import {listenerPorts,listenerOwnership} from './process-diagnostics.mjs';
|
|
13
|
+
import {listenerPorts,listenerOwnership,inspectionContext} from './process-diagnostics.mjs';
|
|
14
14
|
import { appFetch } from './app-fetch.mjs';
|
|
15
15
|
import { owner, signIn } from './adapter-auth.mjs';
|
|
16
16
|
import { installerDevKey } from './dev-identity.mjs';
|
|
@@ -34,11 +34,10 @@ const hookNames = ['node', 'tools', 'prepare', 'prepareData', 'dependencies', 'o
|
|
|
34
34
|
|
|
35
35
|
// Feature flags shown by the shared browser flow must describe what this
|
|
36
36
|
// adapter really does. localTrialWithoutEmail claims that sign-in works with no
|
|
37
|
-
// mail provider
|
|
38
|
-
// outbox; hosting needs a hosting hook.
|
|
37
|
+
// mail provider; hosting needs a hosting hook.
|
|
39
38
|
export function adapterFeatures(hooks, features = {}) {
|
|
40
39
|
const result = { hosting: false, github: false, artwork: false, ...features };
|
|
41
|
-
if (result.localTrialWithoutEmail === true && !hooks.signIn) throw new TypeError('localTrialWithoutEmail needs a signIn hook
|
|
40
|
+
if (result.localTrialWithoutEmail === true && !hooks.signIn) throw new TypeError('localTrialWithoutEmail needs a signIn hook.');
|
|
42
41
|
if (result.hosting === true && !hooks.hosting) throw new TypeError('features.hosting needs a hosting hook.');
|
|
43
42
|
if (hooks.hosting && result.hosting !== true) throw new TypeError('A hosting hook must be declared with features.hosting.');
|
|
44
43
|
return Object.freeze(result);
|
|
@@ -57,7 +56,7 @@ export function localInstaller(hooks = {}) {
|
|
|
57
56
|
context.ownerClaim=context.manifest?.steps.find(step=>step.type==='owner-claim');
|
|
58
57
|
options.onContext?.(context);
|
|
59
58
|
const verb = options.verb ?? 'installer';
|
|
60
|
-
|
|
59
|
+
await store.configureQueue?.({verb});
|
|
61
60
|
await requirements(context, hooks);
|
|
62
61
|
if (['installer', 'setup'].includes(verb) && hooks.prepare) await hooks.prepare(context);
|
|
63
62
|
if (verb === 'installer' && hooks.dependencies !== false) await phase(context, hooks, 'dependencies', hooks.dependencies ?? ['pnpm', ['install', '--frozen-lockfile']]);
|
|
@@ -76,9 +75,7 @@ export function localInstaller(hooks = {}) {
|
|
|
76
75
|
if (typeof hooks.owner === 'function' || Array.isArray(hooks.owner)) await phase(context, hooks, 'owner', hooks.owner);
|
|
77
76
|
else await owner(context, hooks.owner);
|
|
78
77
|
}
|
|
79
|
-
|
|
80
|
-
const devIdentity = verb === 'dev' && options.devKey && !options.devLogin;
|
|
81
|
-
if ((['installer', 'setup', 'dev', 'preview'].includes(verb) || (verb === 'outbox' && options.requestSignIn)) && hooks.signIn && !devIdentity) await signIn(context, hooks.signIn);
|
|
78
|
+
if (['installer', 'setup', 'dev', 'preview'].includes(verb) && hooks.signIn) await signIn(context, hooks.signIn);
|
|
82
79
|
if (verb === 'installer' && hooks.hosting) await hosting(context, hooks.hosting);
|
|
83
80
|
store.state.appUrl = context.appUrl ?? (context.app ? context.origin : context.hostedUrl ?? context.origin);
|
|
84
81
|
if (context.hostedUrl) store.state.hostedUrl = context.hostedUrl;
|
|
@@ -91,7 +88,7 @@ export function localInstaller(hooks = {}) {
|
|
|
91
88
|
try {
|
|
92
89
|
let operation;
|
|
93
90
|
if(store.ownCleanup){operation=await recoverInterrupted(root)??await localOperation(root);let released=false;release=async()=>{if(!released){released=true;await operation.release();}};store.ownCleanup(signal,release);}
|
|
94
|
-
//
|
|
91
|
+
// The installer page offers the checkout's one-click dev entry after setup.
|
|
95
92
|
const devKey = await installerDevKey(root);
|
|
96
93
|
if (devKey) store.addSecrets?.([devKey]);
|
|
97
94
|
await run(root, input, store, child => { app = child; onApp(child); }, signal, { operationToken:operation?.token,devKey:devKey??undefined,onContext(value) { context = value; } });
|
|
@@ -233,12 +230,12 @@ async function start(context, hooks) {
|
|
|
233
230
|
// its /health would pass. Claim and sign in only against the process this
|
|
234
231
|
// setup started.
|
|
235
232
|
let ownership;
|
|
236
|
-
try { ownership=await listenerOwnership(child.pid,expectedPort,context.runtimePort?'127.0.0.1':new URL(url).hostname); }
|
|
233
|
+
try { ownership=await listenerOwnership(child.pid,expectedPort,context.runtimePort?'127.0.0.1':new URL(url).hostname,inspectionContext({port:expectedPort,verb:context.verb??'setup'})); }
|
|
237
234
|
catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
|
|
238
235
|
if (ownership.status !== 'owned') {
|
|
239
236
|
const message = (store.redact??(value=>value))(ownership.status==='other'
|
|
240
237
|
? `Another process answered on port ${expectedPort}; the application did not bind it. Listener PID ${ownership.pid}. Nothing was sent. Stop that process or choose another port, then run setup again.`
|
|
241
|
-
: `
|
|
238
|
+
: `Could not confirm the application on port ${expectedPort}: repeated inspection found no listener on the health address. Nothing was sent. Check the application binding, then run rer ${context.verb??'setup'} again.`);
|
|
242
239
|
store.report?.(message);
|
|
243
240
|
throw installationFailure('command_failed', { step: 'start', diagnostic: commandFailure(message, {}) });
|
|
244
241
|
}
|
package/onboarding/app-fetch.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Requests rer itself makes to a local app's own origin (health, sign-in,
|
|
2
|
-
//
|
|
2
|
+
// dev identity). A directly served origin uses fetch. A front-door
|
|
3
3
|
// origin (http://NAME.localhost:PORT) is never resolved and never goes through
|
|
4
4
|
// the door: rer connects with node:http to that checkout's own proxy on
|
|
5
5
|
// 127.0.0.1, which keeps the Host header (fetch drops a Host override, and musl
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { appFetch } from './app-fetch.mjs';
|
|
2
2
|
// Setup opens app-local approvals before native bootstrap. Existing owners must
|
|
3
|
-
// prove
|
|
4
|
-
export async function approveSetupDependencies(context, post
|
|
3
|
+
// prove possession of their private local session secret through the dev entry.
|
|
4
|
+
export async function approveSetupDependencies(context, post) {
|
|
5
5
|
const selected=(context.manifest?.dependencies??[]).filter(d=>context.input[d.address]);
|
|
6
6
|
if(!selected.length)return;
|
|
7
7
|
const failure=()=>Error('Application dependency approval failed. Complete fresh app-owner approval before linking.');
|
|
@@ -16,19 +16,9 @@ export async function approveSetupDependencies(context, post, messages) {
|
|
|
16
16
|
if(setup.status!==409)throw failure();
|
|
17
17
|
await setup.body?.cancel();
|
|
18
18
|
if(!cookie) {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
let id;
|
|
23
|
-
for(let attempt=0;attempt<50 && !id;attempt++) {id=(await messages(context,path,email)).find(value=>!before.has(value));if(!id)await new Promise(resolve=>setTimeout(resolve,200));}
|
|
24
|
-
if(!id)throw failure();
|
|
25
|
-
const response=await appFetch(new URL(path+'?message='+encodeURIComponent(id),context.origin),{signal:context.signal,headers:context.devKey?{'x-rer-dev-key':context.devKey}:{}});
|
|
26
|
-
if(!response.ok)throw failure();
|
|
27
|
-
const html=await response.text(),href=/<a\b[^>]*class="open"[^>]*href="([^"]+)"/.exec(html)?.[1];
|
|
28
|
-
if(!href)throw failure();
|
|
29
|
-
const url=new URL(href.replaceAll('&','&'));if(url.origin!==context.origin || url.pathname!=='/auth/confirm')throw failure();
|
|
30
|
-
const confirmed=await post(context,'/auth/confirm',{token:url.searchParams.get('token')});
|
|
31
|
-
if(confirmed.status!==303)throw failure();cookie=confirmed.headers.get('set-cookie')?.split(';')[0];await confirmed.body?.cancel();
|
|
19
|
+
const confirmed=await post(context,'/auth/local/cli-session',{});
|
|
20
|
+
if(confirmed.status!==303)throw failure();
|
|
21
|
+
cookie=confirmed.headers.get('set-cookie')?.split(';')[0];await confirmed.body?.cancel();
|
|
32
22
|
if(!cookie)throw failure();context.store.addSecrets?.([cookie]);
|
|
33
23
|
}
|
|
34
24
|
const approved=await appFetch(new URL('/auth/dependencies/relink',context.origin),{method:'POST',redirect:'manual',signal:context.signal,headers:{Origin:context.origin,'Content-Type':'application/json',Cookie:cookie},body:JSON.stringify(body)});
|
|
@@ -17,7 +17,7 @@ export async function declaresDevIdentity(root) {
|
|
|
17
17
|
|
|
18
18
|
// The checkout's dev key for a devIdentity seed's installer, created as rer setup
|
|
19
19
|
// does, or null for any other seed. The temporary app must receive it (the start
|
|
20
|
-
// hook's context.devKey)
|
|
20
|
+
// hook's context.devKey) for its one-click development sign-in.
|
|
21
21
|
export async function installerDevKey(root) {
|
|
22
22
|
return await declaresDevIdentity(root) ? (await keys()).ensureDevKey(root) : null;
|
|
23
23
|
}
|
|
@@ -13,7 +13,7 @@ import { labels } from './adapter-labels.mjs';
|
|
|
13
13
|
const rerEntry=root=>existsSync(join(root,'scripts/rer.mjs'))?'scripts/rer.mjs':fileURLToPath(new URL('../bin/rer.mjs',import.meta.url));
|
|
14
14
|
|
|
15
15
|
// The browser and terminal use the same bounded setup journey. Its temporary
|
|
16
|
-
// runtime is gone before that lease releases. The foreground
|
|
16
|
+
// runtime is gone before that lease releases. The foreground development server belongs
|
|
17
17
|
// to the installer process, outside the bounded job's descendant tree.
|
|
18
18
|
export async function installOperator(root,input,store,onApp,signal,hooks){
|
|
19
19
|
let answer,app,step='setup';
|
|
@@ -30,20 +30,19 @@ export async function installOperator(root,input,store,onApp,signal,hooks){
|
|
|
30
30
|
step='dependencies';await store.step(labels.dependencies);await run(labels.dependencies,['install']);
|
|
31
31
|
step='setup';await store.step(labels.build);await run(labels.build,['setup','--answers',relative(root,answer),'--host',address.hostname.replace(/^\[|\]$/g,''),'--port',address.port]);
|
|
32
32
|
await unlink(answer);answer=undefined;
|
|
33
|
-
//
|
|
33
|
+
// Dev's ready event carries RER_OPEN; keep the checkout's dev key out of this log.
|
|
34
34
|
const devKey=/^RER_DEV_KEY=(\S+)$/m.exec(await readFile(join(root,'.rer/local/dev-key.env'),'utf8').catch(()=>''))?.[1];if(devKey)store.addSecrets?.([devKey]);
|
|
35
35
|
step='start';await store.step(labels.start);
|
|
36
|
-
app=store.spawn(labels.start,process.execPath,[rerEntry(root),'
|
|
36
|
+
app=store.spawn(labels.start,process.execPath,[rerEntry(root),'dev','--non-interactive','--json'],{cwd:root,signal,env});onApp(app);
|
|
37
37
|
let buffer='',ready=false,openUrl;
|
|
38
|
-
app.stdout.on('data',chunk=>{buffer+=chunk;let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);try{const event=JSON.parse(line);if(event.version===1&&event.verb==='
|
|
38
|
+
app.stdout.on('data',chunk=>{buffer+=chunk;let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);try{const event=JSON.parse(line);if(event.version===1&&event.verb==='dev'&&event.event==='ready'&&event.url===origin){ready=true;openUrl=event.openUrl;}}catch{}}});
|
|
39
39
|
await store.waitForReady(labels.start,app,async probeSignal=>{
|
|
40
40
|
if(!ready)return {ready:false,message:'Waiting for managed application readiness'};
|
|
41
41
|
const response=await fetch(origin+'/health',{signal:probeSignal});
|
|
42
42
|
return {ready:response.ok&&(await response.json()).status==='ok'};
|
|
43
43
|
},{signal,timeoutMs:1200000});
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
store.state.appUrl=origin+'/__dev/outbox';store.state.devOpen=Boolean(openUrl?.startsWith(origin+'/'));await store.step(labels.complete);await store.phase('complete');
|
|
44
|
+
// State never holds the key; /api/open-app supplies the browser entry.
|
|
45
|
+
store.state.appUrl=origin+'/setup';store.state.devOpen=Boolean(openUrl?.startsWith(origin+'/'));await store.step(labels.complete);await store.phase('complete');
|
|
47
46
|
}catch(error){
|
|
48
47
|
if(app)await store.stop(app);await store.stopCommands?.(signal);
|
|
49
48
|
store.state.error=installationFailureMessage(installationFailure('command_failed',{step,diagnostic:error}));await store.phase('failed');
|
|
@@ -21,25 +21,25 @@ export function operatorInstaller({ database, features, prepare, prepareData })
|
|
|
21
21
|
build: ['pnpm', ['run', 'build:app']],
|
|
22
22
|
// A demo migrates its own fresh state folder, never the checkout's.
|
|
23
23
|
migrate: ({ demo }) => ['pnpm', ['exec', 'wrangler', 'd1', 'migrations', 'apply', database, '--local', '--persist-to', demo?.state ?? '.wrangler/state', '--config', 'dist/server/wrangler.json']],
|
|
24
|
-
// Setup uses
|
|
25
|
-
start:
|
|
24
|
+
// Setup uses the local entry for owner-side dependency approval without mail.
|
|
25
|
+
start: developmentTarget,
|
|
26
26
|
owner: { existingOwnerViaSignIn: true, displayName: input => input.displayName || 'Owner' },
|
|
27
27
|
signIn: { emailKey: 'OWNER_EMAIL', returnTo: '/setup' },
|
|
28
28
|
});
|
|
29
29
|
// A demo migrates and claims the owner in its own state, so it never opens the
|
|
30
30
|
// checkout's database: even read-only, SQLite rewrites its -shm index.
|
|
31
|
-
return {...lifecycle,localPrerequisites:async({root,vars,
|
|
31
|
+
return {...lifecycle,localPrerequisites:async({root,vars,demo})=>vars.AUTH_LOCAL==='true'&&vars.MAIL_PROVIDER==='development'&&Boolean(vars.SESSION_SECRET)&&(demo||await operatorPrerequisites(root)),install:(root,input,store,onApp,signal)=>installOperator(root,input,store,onApp,signal,lifecycle.hooks)};
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
// Only local runtimes receive the dev key; vite.config.ts passes it to `vite dev` alone.
|
|
35
35
|
// No runtime rer starts serves the Local Explorer: it reads and writes the store
|
|
36
36
|
// without the key. trafficProxy also refuses /cdn-cgi/* on the public listener.
|
|
37
|
-
const devBindings =
|
|
37
|
+
const devBindings = devKey => devKey ? { RER_DEV_KEY: devKey, RER_DEV_IDENTITY: 'on' } : {};
|
|
38
38
|
const internalPort = port => { if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('A local runtime requires the traffic proxy internal port.'); return String(port); };
|
|
39
39
|
const developmentEnvironment = () => { const { RER_MODELS_SERVICE, RER_MODELS_KEY, RER_DEMO, RER_DEMO_EXPIRES, RER_STATE_DIR, ...env } = process.env; return env; };
|
|
40
40
|
// A demo's Vite persists to its own folder (the seed's vite.config reads RER_STATE_DIR)
|
|
41
41
|
// and its Worker sees RER_DEMO=1 and the demo's end (modules/demo).
|
|
42
42
|
const demoBindings = demo => demo ? { RER_DEMO: '1', RER_DEMO_EXPIRES: demo.ends, RER_STATE_DIR: demo.state } : {};
|
|
43
|
-
export const developmentTarget = ({ root, origin, runtimePort, devKey,
|
|
43
|
+
export const developmentTarget = ({ root, origin, runtimePort, devKey, modelsLive, demo }) => [process.execPath, [projectViteBinary(root), 'dev', '--host', '127.0.0.1', '--port', internalPort(runtimePort), '--strictPort'], { env: { ...developmentEnvironment(), PATH: join(root, 'node_modules', '.bin') + delimiter + (process.env.PATH ?? ''), RER_DEV_ORIGIN: origin, WRANGLER_SEND_METRICS: 'false', X_LOCAL_EXPLORER: 'false', ...devBindings(devKey), ...(modelsLive ? { RER_MODELS_SERVICE: modelsLive.baseUrl, RER_MODELS_KEY: modelsLive.apiKey } : {}), ...demoBindings(demo) } }];
|
|
44
44
|
|
|
45
45
|
export const previewTarget = ({ origin, runtimePort, devKey, scheduled }) => [process.execPath, [fileURLToPath(new URL('./production-runtime.mjs', import.meta.url))], { env: { ...process.env, RER_DEV_ORIGIN: origin, RER_RUNTIME_HOST: '127.0.0.1', RER_RUNTIME_PORT: internalPort(runtimePort), WRANGLER_SEND_METRICS: 'false', CLOUDFLARE_INCLUDE_PROCESS_ENV: 'false', X_LOCAL_EXPLORER: 'false', RER_RUNTIME_TRIGGERS: scheduled ? '1' : '0', ...(devKey ? { RER_DEV_KEY: devKey } : {}) } }];
|
|
@@ -5,7 +5,7 @@ import { DatabaseSync } from 'node:sqlite';
|
|
|
5
5
|
// A read-only preflight prevents an empty resource directory from being treated
|
|
6
6
|
// as completed setup. Ordinary application sign-in then verifies the actual
|
|
7
7
|
// configured binding before readiness; no database or owner is created here.
|
|
8
|
-
export async function operatorPrerequisites(root
|
|
8
|
+
export async function operatorPrerequisites(root){
|
|
9
9
|
const migrations=(await readdir(join(root,'migrations/core'))).filter(name=>name.endsWith('.sql'));
|
|
10
10
|
const directory=join(root,'.wrangler/state/v3/d1/miniflare-D1DatabaseObject');
|
|
11
11
|
let files;try{
|
|
@@ -18,11 +18,10 @@ export async function operatorPrerequisites(root,email){
|
|
|
18
18
|
db=new DatabaseSync(join(directory,file.name),{readOnly:true});
|
|
19
19
|
const applied=new Set(db.prepare('SELECT name FROM d1_migrations').all().map(row=>row.name));
|
|
20
20
|
const claimed=db.prepare('SELECT COUNT(*) AS count FROM oa_bootstrap').get().count;
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
const saved=db.prepare('SELECT COUNT(*) AS count FROM oa_operators WHERE email=?').get(email).count;
|
|
21
|
+
// The durable claim survives email corrections and owner transfers. Dev
|
|
22
|
+
// signs in as the active owner selected by its owner persona.
|
|
24
23
|
const owners=db.prepare("SELECT COUNT(*) AS count FROM oa_operators WHERE role='owner' AND status='active'").get().count;
|
|
25
|
-
if(claimed===1&&
|
|
24
|
+
if(claimed===1&&owners>0&&migrations.every(name=>applied.has(name)))return true;
|
|
26
25
|
}catch{/* A missing/corrupt/unrelated database cannot prove prior setup. */}
|
|
27
26
|
finally{db?.close();}
|
|
28
27
|
}
|