@runeditrun/rer 0.2.102 → 0.2.104
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/cli/container-policy-worker.mjs +14 -0
- package/cli/container-transfer.mjs +20 -5
- package/cli/hosted-output.mjs +7 -0
- package/cli/portability.mjs +2 -3
- package/global/CHANGELOG.md +21 -1
- package/modules/agent-door/conformance/business-stop.mjs +53 -0
- package/modules/agent-door/conformance/index.mjs +2 -2
- package/modules/agent-door/conformance/relay.mjs +34 -1
- package/modules/agent-door/conformance/unpair.mjs +5 -2
- package/modules/container/build.mjs +1 -1
- package/modules/container/transfer.mjs +52 -26
- package/modules/portability/README.md +12 -3
- package/onboarding/production-plan.mjs +4 -2
- package/onboarding/production-runtime.mjs +3 -3
- package/package.json +1 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { policyModuleURL } from './portability-policy.mjs';
|
|
5
|
+
|
|
6
|
+
// Packaging does not import the policy or run seed build configuration/plugins.
|
|
7
|
+
// Dependencies are compiled from this installation, never from archive metadata.
|
|
8
|
+
try {
|
|
9
|
+
const [root,entry,outfile]=process.argv.slice(2);
|
|
10
|
+
const require=createRequire(join(root,'package.json'));
|
|
11
|
+
const { build }=createRequire(require.resolve('wrangler/package.json'))('esbuild');
|
|
12
|
+
await build({absWorkingDir:root,entryPoints:[fileURLToPath(await policyModuleURL(root,entry))],outfile,
|
|
13
|
+
bundle:true,platform:'node',format:'esm',target:'node22',logLevel:'silent'});
|
|
14
|
+
}catch{process.exitCode=1;}
|
|
@@ -3,25 +3,40 @@ import { dirname, basename, join } from 'node:path';
|
|
|
3
3
|
import { createHash, randomUUID } from 'node:crypto';
|
|
4
4
|
import { execFile } from 'node:child_process';
|
|
5
5
|
import { promisify } from 'node:util';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
6
7
|
import { fileRecords } from '../modules/portability/files.mjs';
|
|
8
|
+
import { RerError, refuse } from './errors.mjs';
|
|
9
|
+
import { policyModuleURL } from './portability-policy.mjs';
|
|
7
10
|
const execute=promisify(execFile);
|
|
8
|
-
export async function containerTransfer({root,path,journal,store,signal,direction,binding,buckets,policy,transient,acknowledgeUnverifiedSchemaObjects}) {
|
|
11
|
+
export async function containerTransfer({root,path,journal,store,signal,direction,binding,buckets,policy,policyModule,transient,acknowledgeUnverifiedSchemaObjects}) {
|
|
9
12
|
if(direction==='import')for(const file of [path,journal].filter(Boolean))for await(const record of fileRecords(file)){}
|
|
10
|
-
const spec={acknowledgeUnverifiedSchemaObjects,direction,binding,buckets,policy,transient,file:basename(path),journal:journal?'/private/later.rer':undefined};
|
|
13
|
+
const spec={acknowledgeUnverifiedSchemaObjects,direction,binding,buckets,policy,...(policyModule===undefined?{}:{policyModule:'policy.mjs'}),transient,file:basename(path),journal:journal?'/private/later.rer':undefined};
|
|
11
14
|
const encoded=JSON.stringify(spec,(_key,value)=>{if(typeof value==='function')throw new Error('Container local transfer needs a serializable archive policy; use native remote transport for this product');return value;});
|
|
12
15
|
const configuration=join(root,'.rer/container/transfer.json');await mkdir(dirname(configuration),{recursive:true,mode:0o700});await mkdir(dirname(path),{recursive:true,mode:0o700});await writeFile(configuration,encoded,{mode:0o600});
|
|
13
16
|
const identity='rer-local-'+createHash('sha256').update(root).digest('hex').slice(0,16),image=identity+':candidate',name='rer-transfer-'+randomUUID();
|
|
14
|
-
let child,temporary;
|
|
17
|
+
let child,temporary,policyDirectory;
|
|
15
18
|
try {
|
|
19
|
+
if(policyModule!==undefined){
|
|
20
|
+
// Compile seed-owned imports, never evaluate seed code in the CLI. The
|
|
21
|
+
// resulting module runs only inside the existing transfer container.
|
|
22
|
+
const entry=await policyModuleURL(root,policyModule);
|
|
23
|
+
policyDirectory=await mkdtemp(join(root,'.rer/container/policy-'));
|
|
24
|
+
try{await execute(process.execPath,[fileURLToPath(new URL('./container-policy-worker.mjs',import.meta.url)),root,entry,join(policyDirectory,'policy.mjs')],{cwd:root,signal});}
|
|
25
|
+
catch{throw refuse('Local portability policy refused (invalid_policy_module). Executable policies require a seed-owned policyModule with a valid default policy export.');}
|
|
26
|
+
}
|
|
16
27
|
await execute('docker',['create','--name',name,'--entrypoint','sh','-v',identity+'-data:/data',image,'-c','umask 077; exec flock -n --no-fork /data/host.lock node /runtime/modules/container/transfer.mjs']);
|
|
17
28
|
await execute('docker',['cp',configuration,name+':/private/transfer.json']);
|
|
29
|
+
if(policyDirectory)await execute('docker',['cp',policyDirectory,name+':/private/policy']);
|
|
18
30
|
if(direction==='import'){
|
|
19
31
|
await execute('docker',['cp',path,name+':/archive/'+spec.file]);
|
|
20
32
|
if(journal)await execute('docker',['cp',journal,name+':/private/later.rer']);
|
|
21
33
|
}
|
|
22
34
|
child=store.spawn('Transferring container archive','docker',['start','--attach',name],{cwd:root,signal});
|
|
23
35
|
let output='';child.stdout.on('data',chunk=>output+=chunk);const code=await new Promise(resolve=>{child.once('error',()=>resolve(1));child.once('close',resolve);});await store.stop(child);
|
|
24
|
-
|
|
36
|
+
const receipt=JSON.parse(output.trim().split('\n').at(-1)||'null');
|
|
37
|
+
if(receipt?.ok===false)throw new RerError(receipt.refused?'restore_refused':'transfer_failed',`Container archive transfer refused or failed (${receipt.reason}).`,receipt.refused?4:1);
|
|
38
|
+
if(code!==0 || !receipt || typeof receipt!=='object')throw new Error('Container archive transfer failed');
|
|
39
|
+
delete receipt.ok;
|
|
25
40
|
if(direction==='export'){
|
|
26
41
|
temporary=await mkdtemp(join(dirname(path),'.rer-transfer-'));
|
|
27
42
|
const copied=join(temporary,'archive.rer');await execute('docker',['cp',name+':/archive/'+spec.file,copied]);
|
|
@@ -30,6 +45,6 @@ export async function containerTransfer({root,path,journal,store,signal,directio
|
|
|
30
45
|
}
|
|
31
46
|
return{target:'local',platform:'container',...receipt};
|
|
32
47
|
}finally{
|
|
33
|
-
await store.stop(child).catch(()=>{});await execute('docker',['stop','-t','10',name]).catch(()=>{});await execute('docker',['rm','-f',name]).catch(()=>{});if(temporary)await rm(temporary,{recursive:true,force:true});
|
|
48
|
+
await store.stop(child).catch(()=>{});await execute('docker',['stop','-t','10',name]).catch(()=>{});await execute('docker',['rm','-f',name]).catch(()=>{});if(temporary)await rm(temporary,{recursive:true,force:true});if(policyDirectory)await rm(policyDirectory,{recursive:true,force:true});
|
|
34
49
|
}
|
|
35
50
|
}
|
package/cli/hosted-output.mjs
CHANGED
|
@@ -196,9 +196,16 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
196
196
|
// Handles taken before it (preparation, history) end; take any later ones from the hosted object again.
|
|
197
197
|
rebind: async names => {
|
|
198
198
|
const app = options.workers.find(worker => worker.name === 'app');
|
|
199
|
+
const removed = Object.fromEntries(names.filter(name => Object.hasOwn(app.bindings, name)).map(name => [name, app.bindings[name]]));
|
|
199
200
|
for (const name of names) delete app.bindings[name];
|
|
200
201
|
await mf.setOptions(convertV4MiniflareOptions(options));
|
|
201
202
|
loopback = await mf.ready;
|
|
203
|
+
// A disposable conformance host can re-pair after proving unpaired behavior.
|
|
204
|
+
return async () => {
|
|
205
|
+
Object.assign(app.bindings, removed);
|
|
206
|
+
await mf.setOptions(convertV4MiniflareOptions(options));
|
|
207
|
+
loopback = await mf.ready;
|
|
208
|
+
};
|
|
202
209
|
},
|
|
203
210
|
close: () => { release(); return mf.dispose(); },
|
|
204
211
|
fetch: (path, { headers, origin = HOSTED_ORIGIN, ...init } = {}) => {
|
package/cli/portability.mjs
CHANGED
|
@@ -48,14 +48,13 @@ export function localPortability({ database, binding = 'DB', buckets = {}, polic
|
|
|
48
48
|
try {
|
|
49
49
|
if (policyModule !== undefined) {
|
|
50
50
|
if (policy !== undefined) throw new PortabilityError('ambiguous_policy', 409);
|
|
51
|
-
if (platform === 'container') throw new PortabilityError('container_policy_module_unsupported', 409);
|
|
52
51
|
declaration = { policyModule: await policyModuleURL(root, policyModule) };
|
|
53
52
|
} else declaration = { policy: serializablePolicy(policy) };
|
|
54
53
|
} catch (error) {
|
|
55
54
|
if (!(error instanceof PortabilityError)) throw error;
|
|
56
|
-
throw refuse(`Local portability policy refused (${error.code}). Executable policies require a seed-owned policyModule with a valid default policy export
|
|
55
|
+
throw refuse(`Local portability policy refused (${error.code}). Executable policies require a seed-owned policyModule with a valid default policy export.`);
|
|
57
56
|
}
|
|
58
|
-
if(platform==='container') return (await import('./container-transfer.mjs')).containerTransfer({root,path,journal,store,signal,direction,binding,buckets
|
|
57
|
+
if(platform==='container') return (await import('./container-transfer.mjs')).containerTransfer({root,path,journal,store,signal,direction,binding,buckets,...declaration,transient,acknowledgeUnverifiedSchemaObjects});
|
|
59
58
|
const input={ root, path, journal, binding, buckets, ...declaration, transient, legacyRecovery, acknowledgeUnverifiedSchemaObjects, platformMigrations };
|
|
60
59
|
// Check the executable policy before migrations; the transfer worker imports
|
|
61
60
|
// it again in its own process so module closures are retained during restore.
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.2.104
|
|
4
|
+
|
|
5
|
+
### Business authority and relay privacy
|
|
6
|
+
|
|
7
|
+
- Business token admission, `person:`/`role:` approver and reviewer references, held Business calls and signed decision-relay pulls now share one fail-closed stop check. They require `people.businessStopped()` to positively return `false`; a missing or non-function reader, a thrown or rejected read, or any other answer refuses Business authority. Tokens receive 401, references match nobody, held calls refuse `sponsor_unavailable`, and relay pulls return empty 404. Adoption conformance covers all four paths after signed detachment with the old policy and trust retained.
|
|
8
|
+
- Approval execution audits inherit their original decision's Business relay membership, including no membership, so an old Business's approval cannot enter a newly paired Business's feed. Forward migration `default-seed/migrations/core/0043_agent_door_relay_privacy.sql` replaces the old triggers and removes only provable cross-Business execution memberships while preserving every audit; the current schema in `modules/agent-door/schema/agent-door.sql` includes the corrected triggers.
|
|
9
|
+
- Adopting seeds, including Pencil and HappyToHelp, must copy migration 0043 into their own forward migration sequence and implement `people.businessStopped()` from their durable Business stop state. Without a reader that positively returns `false` while running, every Business token, Business `person:`/`role:` reference, held Business call and relay pull is refused. Base's `operatorAuthPeople` already reads durable `bs_settings.stopped`; custom adapters must supply the equivalent reader. Keep `sponsor()` resolving subjects after a stop so signed policy remains adoptable.
|
|
10
|
+
|
|
11
|
+
### Container archive policies
|
|
12
|
+
|
|
13
|
+
- `rer export --platform container` and `rer import --platform container` now honour a seed-owned `policyModule`, including executable redaction and restore validation. The module and its imports are compiled without evaluating policy code in the CLI, then run in the isolated transfer process with real D1 and bucket adapters. Archives carry no executable policy or policy entry point. After upgrading rer, rebuild any container image built by an earlier rer with `rer build --platform container` before using container export or import with a `policyModule`.
|
|
14
|
+
|
|
15
|
+
## 0.2.103
|
|
16
|
+
|
|
17
|
+
### Fixes
|
|
18
|
+
|
|
19
|
+
- Preview no longer fails to start when Wrangler prints stdout banners about `.dev.vars` or experimental features. The preview runtime reads its resolved Worker configuration from a dedicated pipe instead of parsing the planner child's entire stdout as JSON.
|
|
20
|
+
|
|
21
|
+
### Repository tooling
|
|
22
|
+
|
|
23
|
+
- Base CI's actionlint and Gitleaks installers retry failed downloads within a ten-minute retry window, cap each attempt at 60 seconds, and report the last HTTP status and curl exit code on failure. Pinned versions and checksum verification are unchanged. These repository-only scripts are not shipped in the rer package.
|
|
4
24
|
|
|
5
25
|
## 0.2.102
|
|
6
26
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { accessToken, autonomousPolicy } from './crypto.mjs';
|
|
3
|
+
import { APPROVAL, VERSION } from './protocol.mjs';
|
|
4
|
+
|
|
5
|
+
/** Retain exact approval choices while the Business is running, before detaching it. */
|
|
6
|
+
export async function prepareStoppedCalls(c) {
|
|
7
|
+
const held = [];
|
|
8
|
+
const tool = c.surface.witness;
|
|
9
|
+
for (const [label, ref] of [['person', `person:${c.person.sub}`], ['role', 'role:owner'], ['held', 'sponsor']]) {
|
|
10
|
+
await c.adopt({ ...autonomousPolicy(), rules: [{ id:'stop', class:'*', do:'approval', approver:[ref], wait:'PT1H' }] });
|
|
11
|
+
const pending = async () => {
|
|
12
|
+
const call = await c.tool(tool.tool, { ...c.resolve(tool.args), idempotency_key:randomUUID() });
|
|
13
|
+
const id = call.result?._meta?.[APPROVAL]?.id;
|
|
14
|
+
c.add(`BASE-AGENT-004.stop.${label}.pending`, call.status === 200 && !!id, 'A running Business must be able to hold a call before detachment.');
|
|
15
|
+
if (!id) return null;
|
|
16
|
+
const path = `/agents/api/approvals/${encodeURIComponent(id)}`;
|
|
17
|
+
const { approval } = await c.personJson(path);
|
|
18
|
+
return { path, choice: { revision:approval.revision, summary_sha256:approval.summary_sha256 } };
|
|
19
|
+
};
|
|
20
|
+
const before = await pending();
|
|
21
|
+
if (!before) continue;
|
|
22
|
+
// Reject without executing: prove each native reference resolves while paired.
|
|
23
|
+
const response = await c.personRequest(`${before.path}/reject`, { method:'POST', body:JSON.stringify(before.choice) });
|
|
24
|
+
const body = await response.json();
|
|
25
|
+
c.add(`BASE-AGENT-004.stop.${label}.before`, response.status === 200 && body.approval?.state === 'rejected', 'The paired native approver must resolve before detachment.');
|
|
26
|
+
const saved = await pending();
|
|
27
|
+
if (saved) held.push({ label, ...saved });
|
|
28
|
+
}
|
|
29
|
+
return held;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Use raw doors after detachment: neither token renewal nor repairing pairing can mask a stop. */
|
|
33
|
+
export async function stoppedCallsPhase(c, held) {
|
|
34
|
+
const params = { name:c.surface.witness.tool, arguments:c.resolve(c.surface.witness.args) };
|
|
35
|
+
const called = await c.fetch(new URL('/mcp', c.origin).href, {
|
|
36
|
+
method:'POST', headers:{ Origin:c.origin, 'Content-Type':'application/json', 'MCP-Protocol-Version':VERSION,
|
|
37
|
+
'Mcp-Method':'tools/call', 'Mcp-Name':params.name, Authorization:`Bearer ${await accessToken(c)}` },
|
|
38
|
+
body:JSON.stringify({ jsonrpc:'2.0', id:randomUUID(), method:'tools/call', params }), redirect:'manual',
|
|
39
|
+
});
|
|
40
|
+
c.add('BASE-AGENT-004.stop.token', called.status === 401 && /resource_metadata=/.test(called.headers.get('www-authenticate') ?? ''),
|
|
41
|
+
'A detached Business token must receive 401; people.businessStopped() must positively return false to admit it.');
|
|
42
|
+
await called.body?.cancel();
|
|
43
|
+
for (const { label, path, choice } of held) {
|
|
44
|
+
const response = await c.fetch(new URL(`${path}/approve`, c.origin).href, {
|
|
45
|
+
method:'POST', headers:{ Origin:c.origin, Cookie:c.person.cookie, 'Content-Type':'application/json' }, body:JSON.stringify(choice), redirect:'manual',
|
|
46
|
+
});
|
|
47
|
+
const body = await response.json();
|
|
48
|
+
c.add(`BASE-AGENT-004.stop.${label}`, label === 'held'
|
|
49
|
+
? response.status === 200 && body.approval?.state === 'refused' && body.approval?.code === 'sponsor_unavailable'
|
|
50
|
+
: response.status === 403 && body.code === 'forbidden',
|
|
51
|
+
label === 'held' ? 'A held Business call must refuse sponsor_unavailable after detachment.' : 'Business person: and role: refs must match nobody after detachment.');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -15,7 +15,7 @@ import { webhookPhase } from './webhooks.mjs';
|
|
|
15
15
|
import { recordSecurityPhase } from './security.mjs';
|
|
16
16
|
import { crossSponsorPhase } from './sponsors.mjs';
|
|
17
17
|
import { auditPhase, auditRows } from './audit.mjs';
|
|
18
|
-
import { relayPhase } from './relay.mjs';
|
|
18
|
+
import { relayPhase, relayStoppedPhase } from './relay.mjs';
|
|
19
19
|
import { invocationPhase } from './invocation.mjs';
|
|
20
20
|
|
|
21
21
|
export { validateAgentSurface } from './surface.mjs';
|
|
@@ -59,6 +59,6 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
|
|
|
59
59
|
await c.phase('BASE-AGENT-009.phase7', () => auditPhase(c));
|
|
60
60
|
await c.phase('BASE-AGENT-009.relay', () => relayPhase(c));
|
|
61
61
|
if (sponsors.length > 1) await c.phase('BASE-AGENT-004.cross-sponsor', () => crossSponsorPhase(c, sponsors, initializeAgent));
|
|
62
|
-
if (unpair) await c.phase('BASE-AGENT-004.7', () => unpairPhase(c, unpair, sponsors));
|
|
62
|
+
if (unpair) await c.phase('BASE-AGENT-004.7', () => unpairPhase(c, unpair, sponsors, () => relayStoppedPhase(c)));
|
|
63
63
|
return { ok: points.every(point => point.ok), points, capabilities };
|
|
64
64
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { prepareStoppedCalls, stoppedCallsPhase } from './business-stop.mjs';
|
|
1
2
|
import { randomUUID, webcrypto } from 'node:crypto';
|
|
2
3
|
import { isDeepStrictEqual } from 'node:util';
|
|
3
4
|
import { seconds, signJws } from './crypto.mjs';
|
|
@@ -14,7 +15,7 @@ export async function relayPhase(c) {
|
|
|
14
15
|
const sign = value => signJws(c.signer.privateKey, c.signer.kid, 'rer-agent-decisions+jwt', value);
|
|
15
16
|
const request = pull => c.request(path, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({pull}) });
|
|
16
17
|
const pull = await sign(payload), first = await request(pull), raw = await first.text();
|
|
17
|
-
c.add('BASE-AGENT-009.relay.route', first.status === 200, `Signed decision pull must return 200, got ${first.status}.`);
|
|
18
|
+
c.add('BASE-AGENT-009.relay.route', first.status === 200, `Signed decision pull must return 200, got ${first.status}; the people adapter must implement people.businessStopped() and positively return false while paired.`);
|
|
18
19
|
if (first.status !== 200) return;
|
|
19
20
|
let page = JSON.parse(raw), after = 0;
|
|
20
21
|
const projections = [];
|
|
@@ -61,3 +62,35 @@ export async function relayPhase(c) {
|
|
|
61
62
|
const refused = await request(await signJws(foreign.privateKey,c.signer.kid,'rer-agent-decisions+jwt',payload));
|
|
62
63
|
c.add('BASE-AGENT-009.relay.foreign', refused.status === 401 && isDeepStrictEqual(await refused.json(),{code:'relay_unauthenticated'}), 'A foreign signature must return only 401 relay_unauthenticated.');
|
|
63
64
|
}
|
|
65
|
+
|
|
66
|
+
/** Detach while relay trust and the old policy remain, then probe without renewal. */
|
|
67
|
+
export async function relayStoppedPhase(c) {
|
|
68
|
+
let held = [];
|
|
69
|
+
await c.phase('BASE-AGENT-004.stop.prepare', async () => { held = await prepareStoppedCalls(c); });
|
|
70
|
+
const iat = seconds(c.now);
|
|
71
|
+
const signed = (typ, payload) => signJws(c.signer.privateKey, c.signer.kid, typ, payload);
|
|
72
|
+
const request = (path, body) => c.fetch(new URL(path, c.origin).href, {
|
|
73
|
+
method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body), redirect:'manual',
|
|
74
|
+
});
|
|
75
|
+
const pull = await signed('rer-agent-decisions+jwt', {
|
|
76
|
+
v:1, iss:c.signer.issuer, aud:c.origin, sub:c.signer.installationId, business:c.business,
|
|
77
|
+
after:0, limit:200, iat, exp:iat+60, jti:randomUUID(),
|
|
78
|
+
});
|
|
79
|
+
const paired = await request('/api/rer/agent-decisions', {pull});
|
|
80
|
+
c.add('BASE-AGENT-009.relay.before-stop', paired.status === 200,
|
|
81
|
+
`Paired relay before detachment must return 200, got ${paired.status}; people.businessStopped() must positively return false.`);
|
|
82
|
+
await paired.body?.cancel();
|
|
83
|
+
const settingsIat = seconds();
|
|
84
|
+
const settings = await signed('rer-business-settings+jwt', {
|
|
85
|
+
v:1, iss:c.signer.issuer, aud:c.origin, sub:c.signer.installationId, business:c.business, email:c.person.email, owner_id:c.person.sub,
|
|
86
|
+
jti:randomUUID(), iat:settingsIat, exp:settingsIat+300, rev:2, values:{}, logo:null, team:null, detached:true,
|
|
87
|
+
});
|
|
88
|
+
const detached = await request('/api/rer/business-settings', {settings});
|
|
89
|
+
c.add('BASE-AGENT-009.relay.detach', detached.status === 200, `Signed Business detachment must be accepted before the stopped relay probe, got ${detached.status}.`);
|
|
90
|
+
await detached.body?.cancel();
|
|
91
|
+
if (detached.status !== 200) return;
|
|
92
|
+
await c.phase('BASE-AGENT-004.stop', () => stoppedCallsPhase(c, held));
|
|
93
|
+
const stopped = await request('/api/rer/agent-decisions', {pull});
|
|
94
|
+
c.add('BASE-AGENT-009.relay.stopped', stopped.status === 404 && await stopped.text() === '',
|
|
95
|
+
'A detached Business must receive empty 404 with its old policy and relay trust retained; people.businessStopped() must read the durable stop.');
|
|
96
|
+
}
|
|
@@ -7,7 +7,7 @@ const version = '2026-07-28';
|
|
|
7
7
|
|
|
8
8
|
/** After the driver unpairs the installation, Business tokens end and native access stays.
|
|
9
9
|
* Probes go straight to the origin: policy renewal is no longer possible once unpaired. */
|
|
10
|
-
export async function unpairPhase(c, unpair, sponsors) {
|
|
10
|
+
export async function unpairPhase(c, unpair, sponsors, afterRepair) {
|
|
11
11
|
if (typeof unpair !== 'function') throw new TypeError('Unpair conformance requires the driver to provide unpair().');
|
|
12
12
|
await c.adopt(autonomousPolicy());
|
|
13
13
|
await c.prepare('unpair');
|
|
@@ -32,7 +32,7 @@ export async function unpairPhase(c, unpair, sponsors) {
|
|
|
32
32
|
c.add(`BASE-AGENT-004.7.paired.${label}`, listed.response.status === 200 && Array.isArray(listed.body.result?.tools), 'A Business token must be admitted while the installation is paired.');
|
|
33
33
|
}
|
|
34
34
|
c.add('BASE-AGENT-004.7.paired.metadata', isDeepStrictEqual(await metadata(), [c.signer.issuer]), 'Paired metadata must name the Business issuer.');
|
|
35
|
-
await unpair();
|
|
35
|
+
const repair = await unpair();
|
|
36
36
|
for (const [label, token] of tokens) {
|
|
37
37
|
const listed = await rpc('tools/list', token), called = await rpc('tools/call', token, witness);
|
|
38
38
|
c.add(`BASE-AGENT-004.7.token.${label}`, challenged(listed.response) && challenged(called.response), 'After unpairing, a Business token from the same signer must receive 401 with a resource_metadata challenge on every method.');
|
|
@@ -44,4 +44,7 @@ export async function unpairPhase(c, unpair, sponsors) {
|
|
|
44
44
|
const listed = await rpc('tools/list', client.token);
|
|
45
45
|
c.add(`BASE-AGENT-004.7.native.${label}`, listed.response.status === 200 && Array.isArray(listed.body.result?.tools), 'After unpairing, a declared native fixture client must still be admitted.');
|
|
46
46
|
}
|
|
47
|
+
// Keep unpair checks independent of a stop. Restore only the disposable host's
|
|
48
|
+
// trust, then exercise durable detachment while paired again.
|
|
49
|
+
if (afterRepair && typeof repair === 'function') { await repair(); await afterRepair(); }
|
|
47
50
|
}
|
|
@@ -91,7 +91,7 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
91
91
|
for (const path of runner.files) await cp(within(path),join(output,'app/runner',path),{recursive:true,filter:path => !path.includes('/tests/') && !path.endsWith('/synthetic.mjs')});
|
|
92
92
|
}
|
|
93
93
|
const base = resolve(import.meta.dirname,'../..');
|
|
94
|
-
for (const path of ['modules/container','modules/portability','modules/d1-transport','modules/deploy-kit','cli/scheduled.mjs','cli/jsonc.mjs','modules/integrations/core/public-address.ts']) { await mkdir(join(output,'runtime',path,'..'),{recursive:true}); await cp(join(base,path),join(output,'runtime',path),{recursive:true,filter:path => !path.includes('/tests/')}); }
|
|
94
|
+
for (const path of ['modules/container','modules/portability','modules/d1-transport','modules/deploy-kit','cli/scheduled.mjs','cli/jsonc.mjs','cli/portability-policy.mjs','modules/integrations/core/public-address.ts']) { await mkdir(join(output,'runtime',path,'..'),{recursive:true}); await cp(join(base,path),join(output,'runtime',path),{recursive:true,filter:path => !path.includes('/tests/')}); }
|
|
95
95
|
const dependencies = { ws:'8.22.0', ...(engine === 'workerd' ? { miniflare:'5.20260907.0-alpha' } : {}) };
|
|
96
96
|
await writeFile(join(output,'runtime/package.json'),JSON.stringify({private:true,type:'module',dependencies}));
|
|
97
97
|
await writeFile(join(output,'Dockerfile'),`FROM node:26.8.1-bookworm-slim\nRUN apt-get update && apt-get install -y --no-install-recommends util-linux ca-certificates && apt-get clean\nRUN mkdir -p /private /archive\nWORKDIR /runtime\nCOPY runtime/package.json ./package.json\nRUN npm install --omit=dev --no-audit --no-fund\nCOPY runtime/ /runtime/\nCOPY app/ /app/\nENV NODE_ENV=production PORT=8080 WRANGLER_SEND_METRICS=false\nEXPOSE 8080\nVOLUME /data\nENTRYPOINT ["sh", "/runtime/modules/container/entrypoint.sh"]\n`);
|
|
@@ -1,36 +1,62 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
import { join } from 'node:path';
|
|
3
4
|
import { D1 } from './adapters/d1.mjs';
|
|
4
5
|
import { Objects } from './adapters/objects.mjs';
|
|
5
6
|
import { ensurePortabilitySchema } from './portability-schema.mjs';
|
|
6
7
|
import { migrate } from './migrations.mjs';
|
|
7
|
-
import { createPortability } from '../portability/index.mjs';
|
|
8
|
+
import { createPortability, PortabilityError } from '../portability/index.mjs';
|
|
8
9
|
import { migrationReplay } from '../portability/migration-history.mjs';
|
|
9
10
|
import { requireProductEmpty } from '../portability/legacy-safety.mjs';
|
|
10
11
|
import { destinationLedger } from '../portability/ledgers.mjs';
|
|
11
12
|
import { exportArchive, importArchive, fileRecords } from '../portability/files.mjs';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
|
|
13
|
+
import { loadPolicy } from '../../cli/portability-policy.mjs';
|
|
14
|
+
|
|
15
|
+
// The defaults are the existing container mounts. Tests replace only the engine
|
|
16
|
+
// boundary's filesystem roots; the transfer, policy and storage adapters are real.
|
|
17
|
+
export async function transfer(spec,{root='/app',data='/data',archive='/archive',policyRoot='/private/policy'}={}) {
|
|
18
|
+
let db,platform,worker;
|
|
19
|
+
try {
|
|
20
|
+
// Validate the default export before opening data, just as the native worker
|
|
21
|
+
// does. Neither the module nor its entry point ever comes from the archive.
|
|
22
|
+
let policy=await loadPolicy(policyRoot,spec.policy,spec.policyModule);
|
|
23
|
+
const manifest=JSON.parse(await readFile(join(root,'container.json'),'utf8'));
|
|
24
|
+
let unverified=false;
|
|
25
|
+
if(spec.direction==='import' && spec.acknowledgeUnverifiedSchemaObjects===true)for await(const record of fileRecords(join(archive,spec.file)))if(record.kind==='manifest')unverified=record.schemaObjects===undefined;
|
|
26
|
+
const preflight=async database=>{
|
|
27
|
+
if(!unverified)return;
|
|
28
|
+
const names=(await destinationLedger(database)??[]).map(m=>m.name);
|
|
29
|
+
await requireProductEmpty({db:database,policy,migrations:async()=>migrationReplay(manifest.migrations[spec.binding].filter(m=>names.includes(m.name)),policy)});
|
|
30
|
+
};
|
|
31
|
+
const buckets={};
|
|
32
|
+
if(manifest.engine==='node'){
|
|
33
|
+
db=new D1(join(data,spec.binding+'.sqlite'));
|
|
34
|
+
platform=new DatabaseSync(join(data,'platform.sqlite'));
|
|
35
|
+
for(const [name,binding]of Object.entries(spec.buckets))buckets[name]=new Objects(platform,join(data,'objects'),binding);
|
|
36
|
+
}else{
|
|
37
|
+
const {workerEngine}=await import('./worker-engine.mjs');
|
|
38
|
+
// Open the bindings without automatically applying migrations so the
|
|
39
|
+
// recovery preflight also uses the validated policy.
|
|
40
|
+
worker=await workerEngine({root,data,manifest,settings:{},applyMigrations:false});db=worker.databases[spec.binding];
|
|
41
|
+
for(const [name,binding]of Object.entries(spec.buckets))buckets[name]=worker.objects[binding];
|
|
42
|
+
}
|
|
43
|
+
if(unverified)policy=await loadPolicy(policyRoot,spec.policy,spec.policyModule,{db,buckets});
|
|
44
|
+
await preflight(db);
|
|
45
|
+
for(const [binding,plan]of Object.entries(manifest.migrations)){
|
|
46
|
+
const database=worker?worker.databases[binding]:binding===spec.binding?db:undefined;
|
|
47
|
+
if(database){await migrate(database,plan);await ensurePortabilitySchema(database,manifest.portabilityMigrations);}
|
|
48
|
+
}
|
|
49
|
+
policy=await loadPolicy(policyRoot,spec.policy,spec.policyModule,{db,buckets});
|
|
50
|
+
const service=await createPortability({db,buckets,policy,migrations:async()=>migrationReplay(manifest.migrations[spec.binding],policy)});
|
|
51
|
+
return await(spec.direction==='export'?exportArchive(service,join(archive,spec.file),spec.transient):importArchive(service,join(archive,spec.file),spec.transient,spec.journal,undefined,{acknowledgeUnverifiedSchemaObjects:spec.acknowledgeUnverifiedSchemaObjects}));
|
|
52
|
+
}finally{if(worker)await worker.close();else await db?.close?.();platform?.close();}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function transferFailure(cause){
|
|
56
|
+
const refused=cause instanceof PortabilityError && (cause.status===409 || ['wrong_product','schema_mismatch','staged_validation'].includes(cause.code.split(':')[0]));
|
|
57
|
+
return {ok:false,refused,reason:cause instanceof PortabilityError?cause.code.split(':')[0]:'transfer_failed'};
|
|
58
|
+
}
|
|
59
|
+
if(process.argv[1]===import.meta.filename){
|
|
60
|
+
try{console.log(JSON.stringify({ok:true,...await transfer(JSON.parse(await readFile('/private/transfer.json','utf8')))}));}
|
|
61
|
+
catch(cause){const failure=transferFailure(cause);console.log(JSON.stringify(failure));process.exitCode=failure.refused?4:1;}
|
|
62
|
+
}
|
|
@@ -86,7 +86,7 @@ delivery receipts and state in `rer_mail_event_receipts` and
|
|
|
86
86
|
`rer_mail_event_states` remain portable unless product policy excludes them.
|
|
87
87
|
Seed-owned tables are likewise discovered and remain portable by default.
|
|
88
88
|
|
|
89
|
-
For native local CLI transfers, declare executable policy through
|
|
89
|
+
For native and container local CLI transfers, declare executable policy through
|
|
90
90
|
`localPortability({database, buckets, policyModule})`. `policyModule` is a
|
|
91
91
|
seed-root-relative path or a `file:` URL (including `new URL('./archive-policy.mjs',
|
|
92
92
|
import.meta.url)` in the seed adapter). Its real path must be a file inside the
|
|
@@ -121,8 +121,17 @@ the atomic empty-table guards. Invalid paths, missing/invalid default exports,
|
|
|
121
121
|
and declaring both `policy` and `policyModule` fail closed. Serializable object
|
|
122
122
|
`policy` declarations remain supported; inline functions (including nested
|
|
123
123
|
schema-upgrade and payload callbacks) are refused instead of being dropped by
|
|
124
|
-
JSON transport. Container transfer
|
|
125
|
-
|
|
124
|
+
JSON transport. Container transfer compiles the seed-owned module and its imports
|
|
125
|
+
with the installation's Wrangler esbuild compiler, without evaluating policy code
|
|
126
|
+
or loading build plugins in the CLI. The policy must be bundleable for Node;
|
|
127
|
+
Node built-ins remain available inside the existing transfer container. Only the
|
|
128
|
+
compiled policy is copied into its private directory, with no additional host
|
|
129
|
+
filesystem mounts or network service. The transfer process resolves that private
|
|
130
|
+
entry through `policyModuleURL`, validates the default before opening data or
|
|
131
|
+
applying migrations, then supplies its real D1 and bucket adapters to
|
|
132
|
+
`createPolicy`. Both transports use the same archive format and policy hooks;
|
|
133
|
+
archives carry neither executable policy nor a policy entry point.
|
|
134
|
+
Malformed primary or later
|
|
126
135
|
journal JSON is reported once as `invalid_archive` with exit 2 and a re-export
|
|
127
136
|
recovery command, before local data
|
|
128
137
|
migrations, without echoing archive content or parser diagnostics.
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import {createWriteStream} from 'node:fs';
|
|
1
2
|
import {productionPlan,serializePlan} from './production-options.mjs';
|
|
2
3
|
|
|
3
4
|
// Short-lived: resolves the Worker's Miniflare options with Wrangler and writes
|
|
4
|
-
// them as JSON to
|
|
5
|
+
// them as JSON to fd 3, a pipe only the starting runtime reads. The plan holds
|
|
5
6
|
// private settings, so it is never written to a file or an argument.
|
|
6
7
|
if(process.env.RER_ORIGIN_KEY && !/^[A-Z][A-Z0-9_]*$/.test(process.env.RER_ORIGIN_KEY))throw Error('Invalid local origin setting name');
|
|
7
8
|
const plan=await productionPlan(process.cwd(),process.env.RER_DEV_ORIGIN,Number(process.env.RER_RUNTIME_PORT),process.env.RER_RUNTIME_HOST);
|
|
8
|
-
|
|
9
|
+
const output=createWriteStream(null,{fd:3});
|
|
10
|
+
await new Promise((done,fail)=>{output.once('error',fail);output.end(serializePlan(plan),done);});
|
|
@@ -13,12 +13,12 @@ const stop=()=>stopping??=(async()=>{planner?.kill('SIGTERM');await closeAssets?
|
|
|
13
13
|
process.on('SIGINT',()=>void stop());process.on('SIGTERM',()=>void stop());
|
|
14
14
|
async function plan(){
|
|
15
15
|
let text='';
|
|
16
|
-
planner=spawn(process.execPath,[fileURLToPath(new URL('./production-plan.mjs',import.meta.url))],{cwd:process.cwd(),env:process.env,stdio:['ignore','
|
|
17
|
-
planner.
|
|
16
|
+
planner=spawn(process.execPath,[fileURLToPath(new URL('./production-plan.mjs',import.meta.url))],{cwd:process.cwd(),env:process.env,stdio:['ignore',2,'inherit','pipe']});
|
|
17
|
+
planner.stdio[3].setEncoding('utf8').on('data',chunk=>{text+=chunk;});
|
|
18
18
|
const code=await new Promise((done,fail)=>{planner.once('error',fail);planner.once('close',done);});
|
|
19
19
|
if(stopping)return undefined;
|
|
20
20
|
if(code!==0)throw Error('Resolving the Worker configuration failed.');
|
|
21
|
-
return JSON.parse(text);
|
|
21
|
+
try{return JSON.parse(text);}catch{throw Error('Resolving the Worker configuration failed.');}
|
|
22
22
|
}
|
|
23
23
|
try{
|
|
24
24
|
const options=await plan();
|