@runeditrun/rer 0.2.84 → 0.2.86
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 +156 -50
- package/cli/README.md +78 -2
- package/cli/agent-door.mjs +149 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-mail.mjs +54 -0
- package/cli/agent-network.mjs +64 -0
- package/cli/agent-reviewers.mjs +110 -0
- package/cli/agent-secrets.mjs +23 -0
- package/cli/agent-sponsors.mjs +43 -0
- package/cli/agent-surface.mjs +34 -0
- package/cli/agent-webhooks.mjs +19 -0
- package/cli/authoring.mjs +2 -1
- package/cli/bounded.mjs +1 -1
- package/cli/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +151 -0
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +29 -6
- package/cli/business/connect.mjs +20 -8
- package/cli/business/detector.mjs +4 -1
- package/cli/business/device.mjs +13 -0
- package/cli/business/export-inputs.mjs +69 -0
- package/cli/business/export-task.mjs +17 -0
- package/cli/business/invocation.mjs +8 -1
- package/cli/business/keychain.mjs +8 -1
- package/cli/business/lease.mjs +11 -1
- package/cli/business/local-commands.mjs +80 -30
- package/cli/business/outbound.mjs +9 -4
- package/cli/business/parsers-config.mjs +8 -7
- package/cli/business/parsers-syntax.mjs +7 -3
- package/cli/business/permissions.mjs +2 -0
- package/cli/business/questions.mjs +89 -6
- package/cli/business/setup-command.mjs +49 -0
- package/cli/business/setup-company.json +15 -0
- package/cli/business/setup-demo.mjs +95 -0
- package/cli/business/state.mjs +44 -10
- package/cli/business/supervisor.mjs +97 -32
- package/cli/business/vendor-door.mjs +230 -0
- package/cli/business/vendors/README.md +29 -3
- package/cli/business/vendors/common.mjs +8 -6
- package/cli/business/vendors/index.mjs +22 -11
- package/cli/business/vendors/sorry.mjs +106 -0
- package/cli/container-transfer.mjs +2 -2
- package/cli/contract.mjs +7 -7
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +6 -2
- package/cli/deploy-command.mjs +6 -4
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +58 -0
- package/cli/deploy.mjs +9 -7
- package/cli/door-clauses.mjs +157 -0
- package/cli/errors.mjs +1 -1
- package/cli/export.mjs +16 -4
- package/cli/hosted-output.mjs +17 -7
- package/cli/human-error.mjs +20 -0
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +26 -6
- package/cli/main.mjs +2 -1
- package/cli/managed-data-schema.mjs +127 -0
- package/cli/managed-data-zip.mjs +116 -0
- package/cli/managed-data.mjs +110 -0
- package/cli/managed-server.mjs +25 -14
- package/cli/native-owner-entry.mjs +86 -0
- package/cli/output.mjs +3 -2
- package/cli/parse.mjs +2 -2
- package/cli/portability-empty.mjs +65 -0
- package/cli/portability-migrations.mjs +33 -9
- package/cli/portability-policy.mjs +5 -2
- package/cli/portability-worker.mjs +15 -6
- package/cli/portability.mjs +30 -8
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +8 -2
- package/cli/ready-summary.mjs +9 -0
- package/cli/run-transfers.mjs +37 -0
- package/cli/runtime-front-door.mjs +4 -4
- package/cli/server-proxy.mjs +4 -3
- package/cli/server-registry.mjs +13 -8
- package/cli/site.mjs +6 -1
- package/cli/transfers.mjs +17 -4
- package/edition-authoring/archive-source.mjs +59 -0
- package/edition-authoring/base-copies.mjs +147 -25
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/module-closure.mjs +2 -16
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +218 -34
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/foundation/runtime/run-data.d.mts +1 -0
- package/foundation/runtime/run-data.mjs +2 -0
- package/global/CHANGELOG.md +126 -0
- package/global/README.md +156 -50
- package/global/cli/command.mjs +8 -2
- package/global/cli/install.mjs +4 -5
- package/global/cli/path-link.mjs +3 -2
- package/global/cli/repo-command.mjs +3 -7
- package/global/door/command.mjs +3 -1
- package/global/launch/dev.mjs +12 -2
- package/global/launch/facts.mjs +2 -2
- package/global/launch/render.mjs +16 -9
- package/global/launch/state.mjs +4 -4
- package/global/main.mjs +13 -8
- package/install.sh +17 -6
- package/modules/agent-door/CLAUSES.md +215 -0
- package/modules/agent-door/conformance/audit.mjs +66 -0
- package/modules/agent-door/conformance/authority.d.mts +2 -0
- package/modules/agent-door/conformance/authority.mjs +17 -0
- package/modules/agent-door/conformance/crypto.mjs +36 -0
- package/modules/agent-door/conformance/discovery.mjs +61 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/invocation.mjs +32 -0
- package/modules/agent-door/conformance/journey.mjs +112 -0
- package/modules/agent-door/conformance/narrowing.d.mts +1 -0
- package/modules/agent-door/conformance/narrowing.mjs +21 -0
- package/modules/agent-door/conformance/negative.mjs +47 -0
- package/modules/agent-door/conformance/network-modules.mjs +86 -0
- package/modules/agent-door/conformance/network-runtime.mjs +46 -0
- package/modules/agent-door/conformance/policy-phases.mjs +75 -0
- package/modules/agent-door/conformance/protocol.mjs +145 -0
- package/modules/agent-door/conformance/replay.mjs +38 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +33 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/surface.mjs +89 -0
- package/modules/agent-door/conformance/target.mjs +18 -0
- package/modules/agent-door/conformance/tool-name.d.mts +1 -0
- package/modules/agent-door/conformance/tool-name.mjs +7 -0
- package/modules/agent-door/conformance/webhooks.mjs +30 -0
- package/modules/container/README.md +6 -1
- package/modules/container/adapters/d1-limits.mjs +286 -0
- package/modules/container/adapters/d1-sqlite.mjs +95 -0
- package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
- package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
- package/modules/container/adapters/d1-workerd.mjs +5 -0
- package/modules/container/adapters/sqlite-worker.mjs +5 -3
- package/modules/container/build.mjs +1 -0
- package/modules/container/image-variables.mjs +14 -3
- package/modules/container/transfer.mjs +14 -4
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/demo-host/README.md +6 -0
- package/modules/demo-host/build.mjs +1 -0
- package/modules/demo-host/native/prepare.mjs +2 -1
- package/modules/demo-host/native/sql.mjs +7 -2
- package/modules/demo-host/ownership.mjs +39 -0
- package/modules/demo-host/plan.mjs +2 -1
- package/modules/demo-host/remove.mjs +6 -1
- package/modules/deploy-kit/README.md +22 -2
- package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
- package/modules/deploy-kit/d1-import.mjs +17 -5
- package/modules/deploy-kit/diagnostics.mjs +29 -3
- package/modules/deploy-kit/owner-cli.mjs +20 -7
- package/modules/deploy-kit/provider-transport.mjs +19 -4
- package/modules/deploy-kit/provider.mjs +57 -22
- package/modules/deploy-kit/readiness-window.mjs +1 -1
- package/modules/deploy-kit/site.mjs +8 -3
- package/modules/deploy-kit/worker.mjs +4 -4
- package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
- package/modules/import-kit/schema/importers.schema.json +107 -0
- package/modules/import-kit/src/d1/README.md +23 -4
- package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
- package/modules/import-kit/src/d1/budget.ts +15 -7
- package/modules/import-kit/src/d1/column-layout.ts +5 -0
- package/modules/import-kit/src/d1/creation.ts +15 -8
- package/modules/import-kit/src/d1/database.ts +3 -3
- package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
- package/modules/import-kit/src/d1/erasure.ts +2 -2
- package/modules/import-kit/src/d1/jobs.ts +10 -6
- package/modules/import-kit/src/d1/plans.ts +14 -8
- package/modules/import-kit/src/d1/retirement.ts +2 -2
- package/modules/import-kit/src/d1/sets.ts +1 -3
- package/modules/import-kit/src/d1/staged-creation.ts +3 -3
- package/modules/import-kit/src/door/ADOPTING.md +20 -0
- package/modules/import-kit/src/door/README.md +2 -1
- package/modules/import-kit/src/door/admission.ts +5 -3
- package/modules/import-kit/src/door/archive.ts +5 -2
- package/modules/import-kit/src/door/authority.ts +1 -0
- package/modules/import-kit/src/door/grants.ts +1 -1
- package/modules/import-kit/src/door/handler.ts +14 -8
- package/modules/import-kit/src/door/index.ts +1 -1
- package/modules/import-kit/src/door/jobs.ts +40 -0
- package/modules/import-kit/src/door/limits.ts +1 -1
- package/modules/import-kit/src/door/operator.ts +3 -3
- package/modules/import-kit/src/door/planning.ts +10 -6
- package/modules/import-kit/src/door/protocol.ts +2 -2
- package/modules/import-kit/src/door/raw.ts +25 -0
- package/modules/import-kit/src/door/refusals.ts +2 -1
- package/modules/import-kit/src/door/types.ts +26 -6
- package/modules/import-kit/src/receipt/encoding.ts +37 -0
- package/modules/import-kit/src/receipt/index.ts +69 -0
- package/modules/import-kit/src/receipt/policy.ts +24 -0
- package/modules/import-kit/src/receipt/types.ts +64 -0
- package/modules/import-kit/src/receipt/uri.ts +45 -0
- package/modules/import-kit/src/receipt/validation.ts +87 -0
- package/modules/import-kit/src/status/encoding.ts +13 -0
- package/modules/import-kit/src/status/evidence.ts +218 -0
- package/modules/import-kit/src/status/index.ts +56 -0
- package/modules/import-kit/src/status/schema.ts +208 -0
- package/modules/import-kit/src/status/types.ts +86 -0
- package/modules/operator-auth/accounts/delegated.mjs +48 -0
- package/modules/operator-auth/index.d.mts +7 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +138 -9
- package/modules/portability/backfills.mjs +9 -8
- package/modules/portability/bridge.mjs +32 -5
- package/modules/portability/catalogue.mjs +12 -5
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/files.mjs +4 -3
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/http.mjs +3 -3
- package/modules/portability/import.mjs +29 -13
- package/modules/portability/index.d.mts +4 -3
- package/modules/portability/index.mjs +1 -1
- package/modules/portability/ledgers.mjs +3 -2
- package/modules/portability/legacy-safety.mjs +11 -2
- package/modules/portability/migration-history.mjs +2 -2
- package/modules/portability/progress.mjs +1 -0
- package/modules/portability/restore-empty.mjs +12 -0
- package/modules/release/github-verify.mjs +11 -2
- package/onboarding/adapter.mjs +35 -6
- package/onboarding/app-fetch.mjs +6 -4
- package/onboarding/development-runtime.mjs +19 -0
- package/onboarding/local/operation.mjs +45 -27
- package/onboarding/loopback-fetch.mjs +16 -0
- package/onboarding/operator-installer.mjs +2 -4
- package/onboarding/process-diagnostics.mjs +6 -2
- package/onboarding/production-runtime.mjs +4 -2
- package/onboarding/readiness.mjs +1 -0
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/scripts/publish-check/public_hygiene.py +1 -1
- package/cli/business/opt-ins.mjs +0 -33
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { validateNetworkAdapter, NetworkAdapterError } from '../modules/agent-door/conformance/network-modules.mjs';
|
|
3
|
+
import { isolatedNetworkAdapter } from '../modules/agent-door/conformance/network-runtime.mjs';
|
|
4
|
+
import { verificationSecrets } from './agent-secrets.mjs';
|
|
5
|
+
import { RerError } from './errors.mjs';
|
|
6
|
+
import { createCapturedMail } from './agent-mail.mjs';
|
|
7
|
+
import { createFixtureControl } from './agent-fixtures.mjs';
|
|
8
|
+
|
|
9
|
+
const denied = () => new Response('Conformance has no network adapter for this external effect.', { status: 502 });
|
|
10
|
+
|
|
11
|
+
// Conformance is a disposable installation. Replace only the paid mail network
|
|
12
|
+
// edge; native invitation preparation, authorization and D1 commits still run.
|
|
13
|
+
// No request leaves this verifier and no stand-in credential reaches a provider.
|
|
14
|
+
export async function agentConformanceNetwork(request) {
|
|
15
|
+
const url = new URL(request.url);
|
|
16
|
+
if (request.method === 'POST' && url.origin === 'https://api.resend.com' && url.pathname === '/emails') {
|
|
17
|
+
await request.arrayBuffer();
|
|
18
|
+
return Response.json({ id: randomUUID() });
|
|
19
|
+
}
|
|
20
|
+
if (request.method === 'POST' && url.origin === 'https://api.sendgrid.com' && url.pathname === '/v3/mail/send') {
|
|
21
|
+
await request.arrayBuffer();
|
|
22
|
+
return new Response(null, { status: 202, headers: { 'x-message-id': randomUUID() } });
|
|
23
|
+
}
|
|
24
|
+
if (request.method === 'POST' && url.origin === 'https://api.cloudflare.com' && /^\/client\/v4\/accounts\/[^/]+\/email\/sending\/send$/.test(url.pathname)) {
|
|
25
|
+
const body = await request.json();
|
|
26
|
+
return Response.json({ success: true, errors: [], result: { message_id: randomUUID(), accepted: body.to, rejected: [] } });
|
|
27
|
+
}
|
|
28
|
+
return denied();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Extend the paid network edge for declared origins, without running seed
|
|
32
|
+
* modules in this process or giving them any route to the real network. */
|
|
33
|
+
export async function createAgentConformanceNetwork(root, config, { email } = {}) {
|
|
34
|
+
const mail = createCapturedMail(email);
|
|
35
|
+
let declaration, adapter, fixtures;
|
|
36
|
+
try {
|
|
37
|
+
if (config !== undefined) {
|
|
38
|
+
declaration = validateNetworkAdapter(Object.fromEntries(Object.entries(config).filter(([key]) => key !== 'secretSource')));
|
|
39
|
+
adapter = await isolatedNetworkAdapter(root, declaration.module, denied);
|
|
40
|
+
}
|
|
41
|
+
fixtures = createFixtureControl(declaration?.origins ?? new Set());
|
|
42
|
+
} catch (error) {
|
|
43
|
+
mail.close();
|
|
44
|
+
if (error instanceof NetworkAdapterError) throw new RerError('agent_network_invalid', error.message, 1);
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
return { mail: { read: options => mail.read(options) }, fixtures: { set: (origin, value) => fixtures.set(origin, value) },
|
|
48
|
+
provision: async hosted => {
|
|
49
|
+
if (config?.secretSource === undefined) return {};
|
|
50
|
+
const secrets = await verificationSecrets(root, config.secretSource, hosted.database);
|
|
51
|
+
await adapter.provision(secrets);
|
|
52
|
+
return secrets;
|
|
53
|
+
},
|
|
54
|
+
close: async () => { mail.close(); fixtures.close(); await adapter?.close(); }, fetch: async request => {
|
|
55
|
+
const capture = request.clone(), origin = new URL(request.url).origin;
|
|
56
|
+
try {
|
|
57
|
+
const response = declaration?.origins.has(origin) ? await adapter.fetch(request, fixtures.get(origin)) : await agentConformanceNetwork(request);
|
|
58
|
+
if (response.ok) await mail.capture(capture);
|
|
59
|
+
else void capture.body?.cancel();
|
|
60
|
+
return response;
|
|
61
|
+
}
|
|
62
|
+
catch { void capture.body?.cancel(); throw new RerError('agent_network_failed', 'The isolated conformance network adapter failed to handle a provider request. Its default fetch export must return a Response.', 1); }
|
|
63
|
+
} };
|
|
64
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { contained } from './project.mjs';
|
|
5
|
+
import { RerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const invalid = () => new RerError('agent_reviewer_invalid', 'verification.reviewers must name at most eight unique {label,email,initializer} native reviewer lifecycles.', 1);
|
|
8
|
+
const failed = () => new RerError('agent_reviewer_failed', 'The native reviewer lifecycle did not return its confirmed session through the disposable installation.', 1);
|
|
9
|
+
const canonicalEmail = value => typeof value === 'string' && value === value.trim().toLowerCase() && /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(value);
|
|
10
|
+
const mailboxAge = 300_000, maxBytes = 65_536, maxMessages = 20;
|
|
11
|
+
const mailProvider = request => {
|
|
12
|
+
const url = new URL(request.url);
|
|
13
|
+
return request.method !== 'POST' ? null : url.origin === 'https://api.resend.com' && url.pathname === '/emails' ? 'resend'
|
|
14
|
+
: url.origin === 'https://api.sendgrid.com' && url.pathname === '/v3/mail/send' ? 'sendgrid'
|
|
15
|
+
: url.origin === 'https://api.cloudflare.com' && /^\/client\/v4\/accounts\/[^/]+\/email\/sending\/send$/.test(url.pathname) ? 'cloudflare' : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Test tooling only: observe accepted paid mail edges for explicitly declared
|
|
19
|
+
* reviewers. Native invitation, proof consumption and authority stay in the app. */
|
|
20
|
+
export async function verificationReviewers(root, declaration, ownerEmail) {
|
|
21
|
+
const entries = new Map(), messages = [], completed = new Set(), attempted = new Set();
|
|
22
|
+
let closed = false;
|
|
23
|
+
if (declaration !== undefined) {
|
|
24
|
+
if (!Array.isArray(declaration) || !declaration.length || declaration.length > 8) throw invalid();
|
|
25
|
+
for (const value of declaration) {
|
|
26
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !['label', 'email', 'initializer'].includes(key))
|
|
27
|
+
|| !/^[a-z][a-z0-9-]{0,63}$/.test(value.label) || !canonicalEmail(value.email) || value.email === ownerEmail
|
|
28
|
+
|| entries.has(value.label) || [...entries.values()].some(entry => entry.email === value.email) || typeof value.initializer !== 'string') throw invalid();
|
|
29
|
+
await contained(root, value.initializer);
|
|
30
|
+
let initialize;
|
|
31
|
+
try { initialize = (await import(pathToFileURL(resolve(root, value.initializer)))).default; }
|
|
32
|
+
catch { throw invalid(); }
|
|
33
|
+
if (typeof initialize !== 'function') throw invalid();
|
|
34
|
+
entries.set(value.label, { ...value, initialize });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function prune() {
|
|
38
|
+
const cutoff = Date.now() - mailboxAge;
|
|
39
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].at < cutoff) messages.splice(i, 1);
|
|
40
|
+
}
|
|
41
|
+
function read(email, options = {}) {
|
|
42
|
+
if (closed || !options || typeof options !== 'object' || Array.isArray(options) || Object.keys(options).some(key => !['limit', 'maxAgeMs', 'after'].includes(key))) throw failed();
|
|
43
|
+
const { limit = 10, maxAgeMs = mailboxAge, after = 0 } = options;
|
|
44
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > maxMessages || !Number.isInteger(maxAgeMs) || maxAgeMs < 1 || maxAgeMs > mailboxAge || !Number.isFinite(after) || after < 0) throw failed();
|
|
45
|
+
prune();
|
|
46
|
+
return messages.filter(message => message.to.includes(email) && message.at >= Math.max(after, Date.now() - maxAgeMs))
|
|
47
|
+
.slice(-limit).map(({ to: _to, ...message }) => ({ ...message }));
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
observes: request => !closed && entries.size > 0 && mailProvider(request) !== null,
|
|
51
|
+
// Read only clones, and never expose headers, provider credentials or another
|
|
52
|
+
// mailbox. A rejected submission cannot become a delivered invitation.
|
|
53
|
+
async capture(request, response) {
|
|
54
|
+
if (closed || !entries.size || request.method !== 'POST' || !response.ok) return;
|
|
55
|
+
const provider = mailProvider(request);
|
|
56
|
+
if (!provider || Number(request.headers.get('content-length')) > maxBytes) return;
|
|
57
|
+
const reader = request.body?.getReader();
|
|
58
|
+
if (!reader) return;
|
|
59
|
+
const chunks = []; let bytes = 0;
|
|
60
|
+
try {
|
|
61
|
+
for (;;) {
|
|
62
|
+
const { done, value } = await reader.read();
|
|
63
|
+
if (done) break;
|
|
64
|
+
bytes += value.byteLength;
|
|
65
|
+
if (bytes > maxBytes) { void reader.cancel().catch(() => {}); return; }
|
|
66
|
+
chunks.push(value);
|
|
67
|
+
}
|
|
68
|
+
} finally { reader.releaseLock(); }
|
|
69
|
+
let body, acknowledgement;
|
|
70
|
+
try {
|
|
71
|
+
body = JSON.parse(await new Blob(chunks).text());
|
|
72
|
+
if (provider !== 'sendgrid') acknowledgement = await response.json();
|
|
73
|
+
} catch { return; }
|
|
74
|
+
if (closed) return;
|
|
75
|
+
if (provider === 'resend' && typeof acknowledgement?.id !== 'string'
|
|
76
|
+
|| provider === 'sendgrid' && response.status !== 202
|
|
77
|
+
|| provider === 'cloudflare' && acknowledgement?.success !== true) return;
|
|
78
|
+
const array = value => Array.isArray(value) ? value : value ? [value] : [];
|
|
79
|
+
const recipients = provider === 'sendgrid' ? array(body?.personalizations).flatMap(item => array(item?.to).map(to => to?.email)) : array(body?.to);
|
|
80
|
+
const to = [...entries.values()].map(entry => entry.email).filter(email => recipients.includes(email)
|
|
81
|
+
&& (provider !== 'cloudflare' || array(acknowledgement.result?.accepted).includes(email)));
|
|
82
|
+
if (!to.length) return;
|
|
83
|
+
const content = provider === 'sendgrid' ? array(body?.content) : [];
|
|
84
|
+
const text = provider === 'sendgrid' ? content.find(item => item?.type === 'text/plain')?.value : body?.text;
|
|
85
|
+
const html = provider === 'sendgrid' ? content.find(item => item?.type === 'text/html')?.value : body?.html;
|
|
86
|
+
prune();
|
|
87
|
+
messages.push({ id: randomUUID(), at: Date.now(), to, subject: typeof body?.subject === 'string' ? body.subject : '',
|
|
88
|
+
text: typeof text === 'string' ? text : '', html: typeof html === 'string' ? html : '' });
|
|
89
|
+
if (messages.length > maxMessages) messages.shift();
|
|
90
|
+
},
|
|
91
|
+
async initialize(label, owner, { request, origin, returnTo = '/' }) {
|
|
92
|
+
if (closed || !entries.has(label) || attempted.has(label) || !owner || typeof owner.cookie !== 'string' || !owner.cookie || owner.cookie.length > 16_384) throw failed();
|
|
93
|
+
attempted.add(label);
|
|
94
|
+
const entry = entries.get(label);
|
|
95
|
+
try {
|
|
96
|
+
const response = await entry.initialize({ request, origin, label, email: entry.email, owner: { email: ownerEmail, cookie: owner.cookie },
|
|
97
|
+
returnTo, mail: Object.freeze({ read: options => read(entry.email, options) }) });
|
|
98
|
+
if (closed || !(response instanceof Response) || response.status !== 303 || response.redirected) throw failed();
|
|
99
|
+
const cookie = response.headers.getSetCookie().map(value => value.split(';', 1)[0]).join('; ');
|
|
100
|
+
await response.body?.cancel();
|
|
101
|
+
if (!cookie || cookie === owner.cookie) throw failed();
|
|
102
|
+
completed.add(label);
|
|
103
|
+
return { email: entry.email, cookie };
|
|
104
|
+
} catch { throw failed(); }
|
|
105
|
+
},
|
|
106
|
+
points: () => [...entries.keys()].map(label => ({ id: `BASE-AGENT-001.reviewer.${label}.native-session`, ok: completed.has(label),
|
|
107
|
+
...(!completed.has(label) ? { detail: 'Declared native reviewer lifecycle did not complete.' } : {}) })),
|
|
108
|
+
close() { closed = true; messages.length = 0; },
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { contained } from './project.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
// Trusted test tooling gets only this disposable installation's declared D1
|
|
7
|
+
// handles. Neither the accessor nor its values become an application route.
|
|
8
|
+
export async function verificationSecrets(root, source, database) {
|
|
9
|
+
if (source === undefined) return {};
|
|
10
|
+
try {
|
|
11
|
+
if (typeof source !== 'string' || !source.endsWith('.mjs')) throw new Error();
|
|
12
|
+
await contained(root, source);
|
|
13
|
+
const read = (await import(pathToFileURL(resolve(root, source)))).default;
|
|
14
|
+
if (typeof read !== 'function') throw new Error();
|
|
15
|
+
const values = await read({ database });
|
|
16
|
+
if (!values || typeof values !== 'object' || Array.isArray(values) || !Object.keys(values).length
|
|
17
|
+
|| Object.entries(values).some(([key, value]) => !/^[A-Z][A-Z0-9_]{0,63}$/.test(key) || typeof value !== 'string' || !value || value.length > 16384)) throw new Error();
|
|
18
|
+
return values;
|
|
19
|
+
} catch {
|
|
20
|
+
// Accessor errors may contain a secret or a database row. Never report them.
|
|
21
|
+
throw new RerError('agent_secret_source_invalid', 'verification.network.secretSource must be a contained .mjs accessor returning nonempty named string secrets from the disposable installation.', 1);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { contained } from './project.mjs';
|
|
5
|
+
import { RerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const defaultEmail = 'synthetic-base-1@example.com';
|
|
8
|
+
const ownerBindingValues = ['issuer', 'installationId', 'appOrigin', 'publicKeys', 'email', 'sub', 'token', 'sessionSecret'];
|
|
9
|
+
|
|
10
|
+
export async function verificationOwner(root, value = {}) {
|
|
11
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
12
|
+
|| Object.keys(value).some(key => !['email', 'emailField', 'tokenField', 'bindings', 'initializer'].includes(key))) throw new RerError('agent_owner_invalid', 'verification.owner must declare only email, emailField, tokenField, bindings and initializer.', 1);
|
|
13
|
+
const email = value.email ?? defaultEmail;
|
|
14
|
+
if (typeof email !== 'string' || email !== email.trim().toLowerCase() || !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new RerError('agent_owner_invalid', 'verification.owner.email must be a canonical owner email.', 1);
|
|
15
|
+
for (const key of ['emailField', 'tokenField']) if (value[key] !== undefined && !/^[A-Z][A-Z0-9_]{0,63}$/.test(value[key])) throw new RerError('agent_owner_invalid', `verification.owner.${key} must name a production binding.`, 1);
|
|
16
|
+
if (value.bindings !== undefined && (!value.bindings || typeof value.bindings !== 'object' || Array.isArray(value.bindings)
|
|
17
|
+
|| Object.entries(value.bindings).some(([name, source]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !ownerBindingValues.includes(source)))) throw new RerError('agent_owner_invalid', `verification.owner.bindings must map native binding names to ${ownerBindingValues.join(', ')}.`, 1);
|
|
18
|
+
let initialize;
|
|
19
|
+
if (value.initializer !== undefined) {
|
|
20
|
+
await contained(root, value.initializer);
|
|
21
|
+
initialize = (await import(pathToFileURL(resolve(root, value.initializer)))).default;
|
|
22
|
+
if (typeof initialize !== 'function') throw new RerError('agent_owner_invalid', 'verification.owner.initializer must default-export an async owner initializer.', 1);
|
|
23
|
+
}
|
|
24
|
+
return { ...value, email, initialize };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function verificationSponsors(root, verification) {
|
|
28
|
+
const owner = verification.owner ?? {};
|
|
29
|
+
if (verification.sponsors === undefined) return [{ ...await verificationOwner(root, owner), sub: randomUUID() }];
|
|
30
|
+
const values = verification.sponsors;
|
|
31
|
+
if (!Array.isArray(values) || !values.length || values.length > 16) throw new RerError('agent_sponsors_invalid', 'verification.sponsors must contain one to sixteen labelled principals.', 1);
|
|
32
|
+
const labels = new Set(), emails = new Set(), result = [];
|
|
33
|
+
for (const [index, value] of values.entries()) {
|
|
34
|
+
if (!value || typeof value !== 'object' || typeof value.label !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value.label) || labels.has(value.label)) throw new RerError('agent_sponsors_invalid', 'Every verification sponsor needs a unique stable label.', 1);
|
|
35
|
+
const { label, role = 'member', ...declaration } = value;
|
|
36
|
+
if (!['admin', 'member'].includes(role)) throw new RerError('agent_sponsors_invalid', 'Additional sponsor roles must be admin or member.', 1);
|
|
37
|
+
const native = await verificationOwner(root, { ...(index === 0 ? owner : {}), ...declaration });
|
|
38
|
+
if (emails.has(native.email) || index > 0 && !native.initialize) throw new RerError('agent_sponsors_invalid', 'Additional verification sponsors need distinct emails and a native lifecycle initializer.', 1);
|
|
39
|
+
labels.add(label); emails.add(native.email);
|
|
40
|
+
result.push({ ...native, label, role, sub: randomUUID() });
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { validateAgentSurface } from '../modules/agent-door/conformance/surface.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
/** Read only edition declarations; never import the application's tool code. */
|
|
7
|
+
export async function readAgentSurface(root) {
|
|
8
|
+
let source;
|
|
9
|
+
try { source = await readFile(join(root, 'agent-surface.json'), 'utf8'); }
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (error.code === 'ENOENT') return undefined;
|
|
12
|
+
throw new RerError('agent_surface_invalid', 'Cannot read agent-surface.json. Restore the edition\'s agent declaration.', 1);
|
|
13
|
+
}
|
|
14
|
+
let surface;
|
|
15
|
+
try { surface = JSON.parse(source); }
|
|
16
|
+
catch { throw new RerError('agent_surface_invalid', 'agent-surface.json must contain valid JSON.', 1); }
|
|
17
|
+
let contract;
|
|
18
|
+
try { contract = await readFile(join(root, 'CONTRACT.md'), 'utf8'); }
|
|
19
|
+
catch (error) { if (error.code !== 'ENOENT') throw new RerError('agent_surface_invalid', 'Cannot read CONTRACT.md to check the agent surface clauses.', 1); }
|
|
20
|
+
return { surface, contract };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function agentSurfaceClauses(root) {
|
|
24
|
+
let declaration;
|
|
25
|
+
try { declaration = await readAgentSurface(root); }
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (!(error instanceof RerError)) throw error;
|
|
28
|
+
return [{ id: 'SC-14.agents.declaration', ok: false, message: error.message }];
|
|
29
|
+
}
|
|
30
|
+
if (!declaration) return [{ id: 'SC-14.agents.undeclared', ok: true }];
|
|
31
|
+
return validateAgentSurface(declaration.surface, { contract: declaration.contract }).points.map(({ id, ok, detail }) => ({
|
|
32
|
+
id: `SC-14.agents.${id}`, ok, ...(!ok ? { message: detail } : {}),
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { contained } from './project.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
export async function verificationWebhooks(root, config, secrets) {
|
|
7
|
+
if (config === undefined) return undefined;
|
|
8
|
+
try {
|
|
9
|
+
if (!config || typeof config !== 'object' || Array.isArray(config) || Object.keys(config).some(key => !['module', 'prepare'].includes(key))
|
|
10
|
+
|| typeof config.module !== 'string' || !Array.isArray(config.prepare) || !config.prepare.length || !config.prepare.every(value => typeof value === 'string')) throw new Error();
|
|
11
|
+
await contained(root, config.module);
|
|
12
|
+
const build = (await import(pathToFileURL(resolve(root, config.module)))).default;
|
|
13
|
+
if (typeof build !== 'function') throw new Error();
|
|
14
|
+
return { prepare: config.prepare, requests: async context => {
|
|
15
|
+
try { return await build({ ...context, secrets }); }
|
|
16
|
+
catch { throw new Error('The seed webhook request builder could not construct its per-run signature probes.'); }
|
|
17
|
+
} };
|
|
18
|
+
} catch { throw new RerError('agent_webhooks_invalid', 'verification.webhooks must name a contained request-builder module and preparation journey steps.', 1); }
|
|
19
|
+
}
|
package/cli/authoring.mjs
CHANGED
|
@@ -9,7 +9,8 @@ export function authoringCommand(options) {
|
|
|
9
9
|
return options.verb === 'adopt-edition' ? adoptEdition(options.cwd) : refreshCopies(options.cwd, copyOptions([
|
|
10
10
|
...(options.editionMigration ? options.editionMigration.split(',').flatMap(id => ['--edition-migration', id]) : []),
|
|
11
11
|
options.ref, '--record', options.record ?? 'base-copies.json',
|
|
12
|
-
...(options.base ? ['--base', resolve(options.cwd, options.base)] : []),
|
|
12
|
+
...(options.base ? ['--base', resolve(options.cwd, options.base)] : []),
|
|
13
|
+
...(options.baseArchive ? ['--base-archive', resolve(options.cwd, options.baseArchive)] : []), ...(options.offline ? ['--offline'] : []),
|
|
13
14
|
], 1));
|
|
14
15
|
} catch (error) { throw refuse(error.message); }
|
|
15
16
|
}
|
package/cli/bounded.mjs
CHANGED
|
@@ -72,7 +72,7 @@ export async function boundedCommand(project,options,argv,out){
|
|
|
72
72
|
}else if(finalEvent&&finalEvent.exitCode===exitCode){
|
|
73
73
|
if(errorEvent){
|
|
74
74
|
let deployment={};
|
|
75
|
-
try{deployment=JSON.parse(store.redact(JSON.stringify({environment:errorEvent.environment,availableDeployments:errorEvent.availableDeployments,step:errorEvent.step})));}catch{}
|
|
75
|
+
try{deployment=JSON.parse(store.redact(JSON.stringify({environment:errorEvent.environment,availableDeployments:errorEvent.availableDeployments,step:errorEvent.step,...(!options.json&&errorEvent.humanMessage?{humanMessage:errorEvent.humanMessage}:{})})));}catch{}
|
|
76
76
|
out.error(new RerError(errorEvent.code,store.redact(errorEvent.message),exitCode,deployment));
|
|
77
77
|
}
|
|
78
78
|
const {version,verb,event,ok,exitCode:childExit,...details}=finalEvent;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { withUploadedBundle, door, DOOR_ID, count, plural } from './vendor-door.mjs';
|
|
2
|
+
|
|
3
|
+
// Key order is not part of the door's counts; compare them as values.
|
|
4
|
+
const stable = value => JSON.stringify(value, (_, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Perform a claimed switchoff.archive: the vendor's final export uploaded into
|
|
8
|
+
* the app's import door, kept there by the door's `archive` action as the tool's
|
|
9
|
+
* archive in the app's own storage (`business-archive/<tool>/<takenAt>`, the tool
|
|
10
|
+
* being the vendor's namespace), then read back by the door's `restore-check`,
|
|
11
|
+
* which parses it and writes nothing native. Run checks that the archive and its
|
|
12
|
+
* test-restore are exactly this bundle, then completes with the archive_id and
|
|
13
|
+
* the bundle's SHA-256; Business runs its own restore-check before the task is
|
|
14
|
+
* done. Returns the line to say.
|
|
15
|
+
*/
|
|
16
|
+
export function runArchive({ lease, task, grant, directory, say, ownerPage }) {
|
|
17
|
+
const takenAt = new Date().toISOString();
|
|
18
|
+
return withUploadedBundle({ lease, task, grant, directory, say,
|
|
19
|
+
doing: (name, origin, keyed) => `Archiving the final ${name} export through the shipped read-only adapter. ${keyed ? 'The key stays on this computer; the archive' : 'The archive'} goes only to the app's import door at ${origin} and stays in the app's own storage.` },
|
|
20
|
+
async ({ vendor, name, origin, uploadId, bundle, fresh }) => {
|
|
21
|
+
const kept = await door(await fresh('archive'), { uploadId, tool: vendor, takenAt }, lease.signal);
|
|
22
|
+
const [input, unique, rejected] = ['input', 'unique', 'rejected'].map(field => count(kept.counts?.[field]));
|
|
23
|
+
if (typeof kept.archiveId !== 'string' || !DOOR_ID.test(kept.archiveId) || kept.key !== `business-archive/${vendor}/${takenAt}` || kept.tool !== vendor
|
|
24
|
+
|| kept.takenAt !== takenAt || kept.bundleSha256 !== bundle.sha256 || kept.bytes !== bundle.size || [input, unique, rejected].includes(null)) throw Error("The app's import door returned an invalid archive answer.");
|
|
25
|
+
// The door reads its own copy back and parses it as a restore would, with no native writes.
|
|
26
|
+
const restored = await door(await fresh('restore-check'), { archiveId: kept.archiveId }, lease.signal);
|
|
27
|
+
if (restored.archiveId !== kept.archiveId || restored.key !== kept.key || restored.bundleSha256 !== bundle.sha256 || restored.bytes !== bundle.size
|
|
28
|
+
|| stable(restored.counts) !== stable(kept.counts) || !Array.isArray(restored.rejected)) throw Error(`The app's test-restore of the ${name} archive does not match the exported file. The archive was not reported.`);
|
|
29
|
+
return { outputs: { archive_id: kept.archiveId, bundle_sha256: bundle.sha256 },
|
|
30
|
+
said: `Archive kept in ${origin} as ${kept.key}: ${plural(bundle.size, 'byte')}, ${plural(unique, 'source record')}, test-restored with no writes (${rejected} rejected). Business test-restores it again itself; cancelling ${name} stays the owner's step in the browser: ${ownerPage}` };
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { Api } from './api.mjs';
|
|
5
|
+
import { createCredentialStore } from './keychain.mjs';
|
|
6
|
+
import { credentialHandle, loadState, stateDirectory } from './state.mjs';
|
|
7
|
+
import { localCause } from './errors.mjs';
|
|
8
|
+
import { serversDirectory } from '../server-registry.mjs';
|
|
9
|
+
import { alive } from '../../modules/job-queue/identity.mjs';
|
|
10
|
+
|
|
11
|
+
const carryPath = checkout => join(checkout, '.rer/local/business.json');
|
|
12
|
+
const launched = Symbol.for('rer.business.carry.launched');
|
|
13
|
+
|
|
14
|
+
async function readJson(path) {
|
|
15
|
+
try { return JSON.parse(await readFile(path, 'utf8')); }
|
|
16
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
17
|
+
}
|
|
18
|
+
async function atomicJson(path, value) {
|
|
19
|
+
const directory = dirname(path), temporary = join(directory, `${randomUUID()}.tmp`);
|
|
20
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
21
|
+
await chmod(directory, 0o700);
|
|
22
|
+
try {
|
|
23
|
+
await writeFile(temporary, JSON.stringify(value) + '\n', { flag: 'wx', mode: 0o600 });
|
|
24
|
+
await chmod(temporary, 0o600);
|
|
25
|
+
await rename(temporary, path);
|
|
26
|
+
} finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function buildCarry(state, self) {
|
|
30
|
+
const business = self?.business;
|
|
31
|
+
if (!business) return null; // Older platforms have no local identity to carry.
|
|
32
|
+
if (business.id !== state.businessId) throw Error('the response names another Business');
|
|
33
|
+
if (typeof business.name !== 'string' || [...business.name].length < 1 || [...business.name].length > 200
|
|
34
|
+
|| business.legal_name !== null && typeof business.legal_name !== 'string') throw Error('the Business profile is invalid');
|
|
35
|
+
let logo = null;
|
|
36
|
+
try {
|
|
37
|
+
const url = new URL(business.logo_url);
|
|
38
|
+
if (url.protocol === 'https:' && !url.username && !url.password) logo = business.logo_url;
|
|
39
|
+
} catch { /* An absent or invalid logo is carried as null. */ }
|
|
40
|
+
return { version: 1, origin: state.origin, business_id: state.businessId,
|
|
41
|
+
business_url: `${state.origin}/business/${encodeURIComponent(state.businessId)}`,
|
|
42
|
+
name: business.name, legal_name: business.legal_name,
|
|
43
|
+
accent: typeof business.brand_color === 'string' && /^#[0-9a-f]{6}$/i.test(business.brand_color) ? business.brand_color.toLowerCase() : null,
|
|
44
|
+
logo_url: logo };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function writeCarry(checkout, carry) {
|
|
48
|
+
const root = resolve(checkout), path = carryPath(root), record = join(stateDirectory(), 'carried.json');
|
|
49
|
+
const checkouts = await readJson(record) ?? [];
|
|
50
|
+
// Record custody before the write, so disconnect can clean up even after a crash.
|
|
51
|
+
if (!checkouts.includes(root)) await atomicJson(record, [...checkouts, root]);
|
|
52
|
+
let prior;
|
|
53
|
+
try { prior = await readJson(path); } catch (error) { if (!(error instanceof SyntaxError)) throw error; }
|
|
54
|
+
const values = { ...prior };
|
|
55
|
+
delete values.refreshed_at;
|
|
56
|
+
if (Object.keys(values).length === Object.keys(carry).length && Object.keys(carry).every(key => values[key] === carry[key])) {
|
|
57
|
+
for (const [file, mode] of [[dirname(path), 0o700], [path, 0o600]]) {
|
|
58
|
+
if (((await stat(file)).mode & 0o777) !== mode) await chmod(file, mode);
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
await atomicJson(path, { ...carry, refreshed_at: new Date().toISOString() });
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function firstParty(checkout) {
|
|
67
|
+
return typeof checkout === 'string' && isAbsolute(checkout)
|
|
68
|
+
&& (await readJson(join(checkout, 'OPERATIONS.json')))?.seedContract?.profile === 'first-party';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The same read-only registry view as the installed launcher's liveServers.
|
|
72
|
+
// Keep this reader in the exported CLI too: vendored Business commands have no global launcher files.
|
|
73
|
+
async function liveCheckouts() {
|
|
74
|
+
const registry = await readJson(join(serversDirectory(), 'state.json'));
|
|
75
|
+
const checkouts = [];
|
|
76
|
+
for (const record of registry?.running ?? []) {
|
|
77
|
+
let live = true;
|
|
78
|
+
try { live = await alive(record.owner); } catch { /* Unverifiable identities stay live, as in the registry. */ }
|
|
79
|
+
if (live) {
|
|
80
|
+
try { if (await firstParty(record.checkout)) checkouts.push(record.checkout); }
|
|
81
|
+
catch { /* A checkout with an unreadable descriptor is not a carry destination. */ }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return [...new Set(checkouts)];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function warning(origin, error) {
|
|
88
|
+
// Do not echo server text, response fields or transport messages: they can contain credentials.
|
|
89
|
+
const reason = error.status ? `the server refused the request (HTTP ${error.status})`
|
|
90
|
+
: error.name === 'TimeoutError' || error.name === 'AbortError' ? 'the server did not answer within 5 seconds'
|
|
91
|
+
: error.message?.startsWith('Could not reach the Business server at ') ? 'the server is unreachable'
|
|
92
|
+
: error.message === 'credential unavailable' ? 'the Business credential is unavailable in OS credential storage'
|
|
93
|
+
: localCause(error) ?? (['the response names another Business', 'the Business profile is invalid'].includes(error.message) ? error.message : 'the Business profile could not be refreshed');
|
|
94
|
+
process.stderr.write(`Business carry at ${origin}: ${reason}; keeping the local carry.\n`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function carryLive(state, self) {
|
|
98
|
+
try {
|
|
99
|
+
const carry = buildCarry(state, self);
|
|
100
|
+
if (!carry) return;
|
|
101
|
+
const checkouts = [];
|
|
102
|
+
for (const checkout of await liveCheckouts()) {
|
|
103
|
+
try { await writeCarry(checkout, carry); checkouts.push(checkout); } catch (error) { warning(state.origin, error); }
|
|
104
|
+
}
|
|
105
|
+
return { name: carry.name, checkouts };
|
|
106
|
+
} catch (error) { warning(state.origin, error); }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function refreshCarry(api, state, { checkout, signal } = {}) {
|
|
110
|
+
try {
|
|
111
|
+
const self = await api.request('GET', '/api/business/executors/self', undefined, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000) });
|
|
112
|
+
if (checkout) {
|
|
113
|
+
const carry = buildCarry(state, self);
|
|
114
|
+
if (carry) await writeCarry(checkout, carry);
|
|
115
|
+
} else await carryLive(state, self);
|
|
116
|
+
} catch (error) { if (!signal?.aborted) warning(state.origin, error); }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function refreshCheckout(checkout) {
|
|
120
|
+
if (process.env.RER_DEMO === '1' || globalThis[launched] === checkout) return;
|
|
121
|
+
globalThis[launched] = checkout; // The checkout's pinned launcher may enter main again in this process.
|
|
122
|
+
let state;
|
|
123
|
+
try {
|
|
124
|
+
if (!await firstParty(checkout)) return;
|
|
125
|
+
state = await loadState();
|
|
126
|
+
if (!state?.origin || !state.businessId || !state.executorId) return;
|
|
127
|
+
const credential = await createCredentialStore().get(credentialHandle(state.origin));
|
|
128
|
+
if (!credential) throw Error('credential unavailable');
|
|
129
|
+
await refreshCarry(new Api(state.origin, credential), state, { checkout });
|
|
130
|
+
} catch (error) { warning(state?.origin ?? 'the paired origin', error); }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// The supervisor's opt-in read has just carried live apps; refresh them every minute while it runs.
|
|
134
|
+
export async function startCarryRefresh(api, state, signal) {
|
|
135
|
+
const controller = new AbortController(), combined = AbortSignal.any([signal, controller.signal]);
|
|
136
|
+
let pending = Promise.resolve(), busy = false;
|
|
137
|
+
const timer = setInterval(() => {
|
|
138
|
+
if (busy || combined.aborted) return;
|
|
139
|
+
busy = true;
|
|
140
|
+
pending = refreshCarry(api, state, { signal: combined }).finally(() => { busy = false; });
|
|
141
|
+
}, 60_000);
|
|
142
|
+
return async () => { clearInterval(timer); controller.abort(); await pending; };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function removeCarry(checkout) {
|
|
146
|
+
await unlink(carryPath(checkout)).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
147
|
+
}
|
|
148
|
+
export async function removeCarries() {
|
|
149
|
+
const recorded = await readJson(join(stateDirectory(), 'carried.json')) ?? [];
|
|
150
|
+
for (const checkout of new Set([...recorded, ...await liveCheckouts()])) await removeCarry(checkout);
|
|
151
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { withUploadedBundle, door, checkedPreview, plural } from './vendor-door.mjs';
|
|
2
|
+
|
|
3
|
+
// Why the door refused a catch-up under the owner's standing approval
|
|
4
|
+
// (import-kit door, "Catch-up and recovery": `catchup_requires_proposal:<reason>`).
|
|
5
|
+
const beyond = {
|
|
6
|
+
empty_baseline: 'the app holds no earlier import to compare with',
|
|
7
|
+
source_records_gone: 'records were removed in the old tool',
|
|
8
|
+
native_or_mapping_conflict: 'records changed in the app since they were imported',
|
|
9
|
+
rejected_or_unmapped_records: 'some records cannot be brought over as they are',
|
|
10
|
+
change_must_be_under_five_percent: '5% or more of the records changed',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Perform a claimed catchup.vendor: the vendor's current export uploaded into the
|
|
15
|
+
* app's import door, then a catch-up plan of it (a zero-write preview of what
|
|
16
|
+
* changed since the import). Business mints the plan grant under the owner's
|
|
17
|
+
* standing catch-up approval when one covers this tool; the door then refuses a
|
|
18
|
+
* change at or above its bound, and run asks for a plan grant for the owner's
|
|
19
|
+
* review instead. Completion reports the door's upload_id and plan_id and the
|
|
20
|
+
* bundle's SHA-256; Business applies the plan under the standing approval or
|
|
21
|
+
* after the owner approves it. Returns the line to say.
|
|
22
|
+
*/
|
|
23
|
+
export function runCatchup({ lease, task, grant, directory, say, ownerPage }) {
|
|
24
|
+
return withUploadedBundle({ lease, task, grant, directory, say,
|
|
25
|
+
doing: (name, origin, keyed) => `Bringing over recent ${name} changes through the shipped read-only adapter. ${keyed ? 'The key stays on this computer; records' : 'Records'} go only to the app's import door at ${origin}.` },
|
|
26
|
+
async ({ origin, uploadId, bundle, fresh }) => {
|
|
27
|
+
let planGrant = await fresh('plan'), refused = null, preview;
|
|
28
|
+
try { preview = await door(planGrant, { uploadId, catchup: true }, lease.signal); }
|
|
29
|
+
catch (error) {
|
|
30
|
+
const reason = planGrant.catchup === 'bounded' && /^catchup_requires_proposal:([a-z0-9_]+)$/.exec(error.doorCode ?? '')?.[1];
|
|
31
|
+
if (!reason) throw error;
|
|
32
|
+
refused = Object.hasOwn(beyond, reason) ? beyond[reason] : 'it is more than that approval covers';
|
|
33
|
+
planGrant = await fresh('plan', { review: true });
|
|
34
|
+
preview = await door(planGrant, { uploadId, catchup: true }, lease.signal);
|
|
35
|
+
}
|
|
36
|
+
const { records, created, updated, unchanged, gone, rejected } = checkedPreview(preview, bundle);
|
|
37
|
+
const planned = `Catch-up planned in ${origin}: ${plural(records, 'source record')}; ${created} new, ${updated} changed, ${unchanged} unchanged, ${gone} gone, ${rejected} rejected.`;
|
|
38
|
+
return { outputs: { upload_id: uploadId, plan_id: preview.planId, bundle_sha256: bundle.sha256 },
|
|
39
|
+
said: planGrant.catchup === 'bounded' ? `${planned} It is within the owner's standing catch-up approval, so Business applies it and checks the result.`
|
|
40
|
+
: `${planned} ${refused ? `It needs the owner's own approval (${refused}): nothing` : 'Nothing'} changes in the app until the owner approves this catch-up in the browser: ${ownerPage}` };
|
|
41
|
+
});
|
|
42
|
+
}
|