@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,38 @@
|
|
|
1
|
+
import { createServer } from 'node:net';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { inspectionContext, portListener, uncheckedInspection } from './process-diagnostics.mjs';
|
|
4
|
+
|
|
5
|
+
async function bind(host, port) {
|
|
6
|
+
const socket = createServer();
|
|
7
|
+
try {
|
|
8
|
+
await new Promise((resolve, reject) => { socket.once('error', reject); socket.listen({ host, port, exclusive: true }, resolve); });
|
|
9
|
+
return { available: true };
|
|
10
|
+
} catch (error) {
|
|
11
|
+
// IPv6 can be disabled on the host; it must not prevent an IPv4 launch.
|
|
12
|
+
return { available: host === '::1' && ['EADDRNOTAVAIL', 'EAFNOSUPPORT'].includes(error.code), code: error.code };
|
|
13
|
+
} finally { if (socket.listening) await new Promise(resolve => socket.close(resolve)); }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// A failed diagnostic is unknown, never evidence of a foreign owner. A real
|
|
17
|
+
// bind can still prove availability. If a bind loses a race but inspection
|
|
18
|
+
// finds no listener, retry the bind within the same inspection deadline.
|
|
19
|
+
export async function probePort(host, port, { context = inspectionContext({ port }), hosts = [host], anyAddress = false } = {}) {
|
|
20
|
+
const bindings = async () => {
|
|
21
|
+
for (const address of hosts) { const result = await bind(address, port); if (!result.available) return result; }
|
|
22
|
+
return { available: true };
|
|
23
|
+
};
|
|
24
|
+
let bound = await bindings(), listener, unchecked;
|
|
25
|
+
if (!bound.available && bound.code !== 'EADDRINUSE') return bound;
|
|
26
|
+
try { listener = await portListener(port, anyAddress ? undefined : host, context); }
|
|
27
|
+
catch (error) { if (!uncheckedInspection(error)) throw error; unchecked = error; }
|
|
28
|
+
if (listener) return { available: false, listener };
|
|
29
|
+
// Inspecting sockets may have taken seconds. Bind again against the current
|
|
30
|
+
// state, including when the inspection consumed the rest of the budget.
|
|
31
|
+
do {
|
|
32
|
+
bound = await bindings();
|
|
33
|
+
if (bound.available || bound.code !== 'EADDRINUSE') return bound;
|
|
34
|
+
const remaining = context.deadline - performance.now();
|
|
35
|
+
if (remaining <= 0) return { ...bound, unchecked };
|
|
36
|
+
await delay(Math.min(100, remaining));
|
|
37
|
+
} while (true);
|
|
38
|
+
}
|
|
@@ -4,13 +4,15 @@ import {lstat,realpath,readFile,readdir,readlink} from 'node:fs/promises';
|
|
|
4
4
|
import {basename,join} from 'node:path';
|
|
5
5
|
import {homedir} from 'node:os';
|
|
6
6
|
import {isIP} from 'node:net';
|
|
7
|
-
import {
|
|
7
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
8
|
+
import {commandFailure,approvedFailure} from './failures.mjs';
|
|
8
9
|
const exec=promisify(execFile);
|
|
9
10
|
// macOS supplies lsof in /usr/sbin, which a command PATH may omit.
|
|
10
11
|
// Diagnose sockets with the system utility even when that PATH is constrained.
|
|
11
12
|
const lsof=process.platform==='darwin'?'/usr/sbin/lsof':'lsof';
|
|
12
13
|
// One monotonic budget covers every command in an ownership decision.
|
|
13
|
-
export const inspectionContext=()=>({deadline:performance.now()+15000});
|
|
14
|
+
export const inspectionContext=(details={})=>({deadline:performance.now()+15000,...details});
|
|
15
|
+
export const uncheckedInspection=error=>approvedFailure(error)?.ownershipUnchecked===true;
|
|
14
16
|
const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,noMatch=false}={})=>{
|
|
15
17
|
const invocation=[command,...args].join(' ').replaceAll(homedir(),'~');
|
|
16
18
|
let failure;
|
|
@@ -27,7 +29,9 @@ const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,no
|
|
|
27
29
|
failure=error.killed ? `timed out after ${timeout} ms` : `failed (${error.code??error.signal??'unknown error'}${typeof error.stderr==='string'&&error.stderr.trim()?'; diagnostic output':''}; attempt bound ${timeout} ms)`;
|
|
28
30
|
}
|
|
29
31
|
}
|
|
30
|
-
|
|
32
|
+
const subject=context.port?`who uses port ${context.port}`:'local process ownership';
|
|
33
|
+
const cause=failure?.startsWith('timed out')||performance.now()>=context.deadline?'in time (system busy)':'because the system process check failed';
|
|
34
|
+
throw commandFailure(`Could not check ${subject} ${cause}. Run rer ${context.verb??'dev'} again. No other owner was identified.\nOwnership check: ${invocation} ${failure??'total inspection deadline exhausted'} (at most 2 attempts; shared total bound 15000 ms).`,{ownershipUnchecked:true});
|
|
31
35
|
};
|
|
32
36
|
|
|
33
37
|
export async function processName(pid,context=inspectionContext()){
|
|
@@ -126,12 +130,17 @@ function matchingListener(rows,port,host){
|
|
|
126
130
|
const row=rows.find(row=>row.sockets.some(socket=>serves(socket,port,host)===true));
|
|
127
131
|
if(row)return row;
|
|
128
132
|
if(rows.some(row=>row.sockets.some(socket=>serves(socket,port,host)===undefined))){
|
|
129
|
-
throw commandFailure(`
|
|
133
|
+
throw commandFailure(`Could not check who uses port ${port}: a wildcard socket's address family does not prove it serves ${host}. No other owner was identified. Bind the application to the health address explicitly, then run rer dev again.`,{ownershipUnchecked:true});
|
|
130
134
|
}
|
|
131
135
|
}
|
|
132
136
|
export async function portListener(port,host,context=inspectionContext()){
|
|
137
|
+
context.port=port;
|
|
133
138
|
const row=matchingListener(await listeners(undefined,context,port),port,host);
|
|
134
|
-
|
|
139
|
+
if(!row)return;
|
|
140
|
+
// Labels improve the instruction, but a slow optional label cannot erase a
|
|
141
|
+
// positive PID/socket observation or turn it into an unchecked accusation.
|
|
142
|
+
const optional=async action=>{try{return await action();}catch(error){if(!uncheckedInspection(error))throw error;}};
|
|
143
|
+
return {pid:row.pid,command:await optional(()=>processName(row.pid,context))??'process',cwd:await optional(()=>processCwd(row.pid,context))};
|
|
135
144
|
}
|
|
136
145
|
async function descendants(pid,context){
|
|
137
146
|
const rows=(await run('/bin/ps',['-axo','pid=,ppid='],context)).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number));
|
|
@@ -146,6 +155,8 @@ export async function listenerPorts(pid,context=inspectionContext()){
|
|
|
146
155
|
// reach either loopback family, so it also needs a completed inspection with
|
|
147
156
|
// no foreign listener on either address before owner/sign-in can proceed.
|
|
148
157
|
export async function listenerOwnership(pid,port,host,context=inspectionContext()){
|
|
158
|
+
context.port=port;
|
|
159
|
+
do {
|
|
149
160
|
const owned=await descendants(pid,context);
|
|
150
161
|
const ownRows=await listeners([...owned],context);
|
|
151
162
|
const own=ownRows.find(row=>owned.has(row.pid)&&row.sockets.some(socket=>serves(socket,port,host)===true));
|
|
@@ -157,7 +168,12 @@ export async function listenerOwnership(pid,port,host,context=inspectionContext(
|
|
|
157
168
|
if(foreign)return {status:'other',pid:foreign.pid};
|
|
158
169
|
}
|
|
159
170
|
const row=matchingListener(rows,port,host);
|
|
160
|
-
return
|
|
171
|
+
if(row)return {status:owned.has(row.pid)?'owned':'other',pid:row.pid};
|
|
172
|
+
const remaining=context.deadline-performance.now();
|
|
173
|
+
if(remaining<=0)return {status:'none'};
|
|
174
|
+
await delay(Math.min(100,remaining));
|
|
175
|
+
}while(performance.now()<context.deadline);
|
|
176
|
+
return {status:'none'};
|
|
161
177
|
}
|
|
162
178
|
// The caller and the chain that launched it (an installer server running setup,
|
|
163
179
|
// pnpm, a shell) act for this command, never against it.
|
|
@@ -168,7 +184,20 @@ async function callerLineage(context){
|
|
|
168
184
|
return lineage;
|
|
169
185
|
}
|
|
170
186
|
export async function localProcessConflict(root,savedOrigin,context=inspectionContext()){
|
|
171
|
-
root=await realpath(root);const
|
|
187
|
+
root=await realpath(root);const lineage=await callerLineage(context);
|
|
188
|
+
// Inspect canonical state before optional socket diagnostics spend the shared
|
|
189
|
+
// budget. This is file custody, not a claim that another process owns a port.
|
|
190
|
+
const state=join(root,'.wrangler/state');
|
|
191
|
+
let hasState=true;try{await lstat(state);}catch(error){if(error.code==='ENOENT')hasState=false;else throw error;}
|
|
192
|
+
let held;
|
|
193
|
+
if(hasState){
|
|
194
|
+
if(process.platform==='linux'){for(const pid of await linuxPids())if(!lineage.has(pid)&&(await descriptors(pid)).some(path=>path.startsWith(state+'/'))){held={pid};break;}}
|
|
195
|
+
else held=records(await run(lsof,['-nP','-b','-w','-Fpn'],context,{maxBuffer:16*1024*1024})).find(row=>!lineage.has(row.pid)&&row.names.some(path=>path.startsWith(state+'/')));
|
|
196
|
+
if(held)return {pid:held.pid,command:await processName(held.pid,context),reason:'the canonical local state'};
|
|
197
|
+
}
|
|
198
|
+
let all;
|
|
199
|
+
try{all=await listeners(undefined,context);}
|
|
200
|
+
catch(error){if(!uncheckedInspection(error)||context.verb==='reset')throw error;return;}
|
|
172
201
|
const cwdRecords=process.platform!=='linux'&&all.length?records(await run(lsof,['-nP','-b','-w','-a','-p',all.map(row=>row.pid).join(','),'-d','cwd','-Fpn'],context)):[];
|
|
173
202
|
let port;try{const url=new URL(savedOrigin);port=Number(url.port||80);}catch{}
|
|
174
203
|
for(const row of all){
|
|
@@ -181,17 +210,4 @@ export async function localProcessConflict(root,savedOrigin,context=inspectionCo
|
|
|
181
210
|
if(onSavedPort&&places.length&&!places.some(place=>place===root||place.startsWith(root+'/')))continue;
|
|
182
211
|
if(onSavedPort||inCheckout)return {pid:row.pid,command:await processName(row.pid,context),reason:onSavedPort?`saved local port ${port}`:'this checkout'};
|
|
183
212
|
}
|
|
184
|
-
// A process may hold the canonical database without listening. Inspect only
|
|
185
|
-
// actual state files, never broad checkout contents or a process environment.
|
|
186
|
-
const state=join(root,'.wrangler/state');
|
|
187
|
-
try{await lstat(state);}catch(error){if(error.code==='ENOENT')return;throw error;}
|
|
188
|
-
let held;
|
|
189
|
-
if(process.platform==='linux'){for(const pid of await linuxPids())if(!lineage.has(pid)&&(await descriptors(pid)).some(path=>path.startsWith(state+'/'))){held={pid};break;}}
|
|
190
|
-
else {
|
|
191
|
-
// +D requires blocking pathname metadata even for a narrow directory. Read
|
|
192
|
-
// kernel-provided open paths instead, then match only canonical state files.
|
|
193
|
-
// This preflight protects data held by processes outside the app's tree.
|
|
194
|
-
held=records(await run(lsof,['-nP','-b','-w','-Fpn'],context,{maxBuffer:16*1024*1024})).find(row=>!lineage.has(row.pid)&&row.names.some(path=>path.startsWith(state+'/')));
|
|
195
|
-
}
|
|
196
|
-
if(held)return {pid:held.pid,command:await processName(held.pid,context),reason:'the canonical local state'};
|
|
197
213
|
}
|
package/onboarding/server.mjs
CHANGED
|
@@ -98,7 +98,7 @@ export async function startInstaller(root,{seed,port=0,answers,secretInput,noPre
|
|
|
98
98
|
if(req.method==='GET'&&path==='/api/open-app'){
|
|
99
99
|
const key=store.state.phase==='complete'&&store.state.devOpen?/^RER_DEV_KEY=([A-Za-z0-9_-]{43,256})$/m.exec(await readFile(join(root,'.rer/local/dev-key.env'),'utf8').catch(()=>''))?.[1]:undefined;
|
|
100
100
|
if(!key)return json(404,{error:'No dev key for this installation.'});
|
|
101
|
-
const app=new URL(store.state.appUrl);return json(200,{url:`${app.origin}/__dev/key#${new URLSearchParams({'rer-dev':key,next:'/
|
|
101
|
+
const app=new URL(store.state.appUrl);return json(200,{url:`${app.origin}/__dev/key#${new URLSearchParams({'rer-dev':key,as:'owner',next:'/auth/dev/enter?as=owner&returnTo='+encodeURIComponent(app.pathname+app.search)})}`});
|
|
102
102
|
}
|
|
103
103
|
if(req.method==='GET'&&path==='/api/agent-handoff')return json(200,(seed.handoff||agentHandoff)(root,origin,store.state.sessionId,seed));
|
|
104
104
|
if(req.method==='GET'&&path==='/api/state'){await workspaceArt?.refresh();store.state.known.secretReadiness=vault.readiness(store.state.draft);return json(200,store.state);}
|
package/onboarding/ui/app.js
CHANGED
|
@@ -327,7 +327,7 @@ function applyState(next) {
|
|
|
327
327
|
else if (next.phase === 'failed') error(failureHeadline(next.error, failure.step));
|
|
328
328
|
else error();
|
|
329
329
|
if (next.phase === 'complete' && next.appUrl) { try { const url = new URL(next.appUrl); if (['http:', 'https:'].includes(url.protocol)) { $('#open').href = url.href; $('#open').hidden = false; } } catch { error('The application address is invalid. Check the installer terminal.'); } }
|
|
330
|
-
//
|
|
330
|
+
// One-click development entry uses a key exchange; the key stays out of saved state.
|
|
331
331
|
if (next.phase === 'complete' && next.devOpen && !$('#open').dataset.devOpen) { $('#open').dataset.devOpen = 'pending'; request('/api/open-app').then(({ url }) => { if (new URL(url).origin === new URL(next.appUrl).origin) { $('#open').href = url; $('#open').dataset.devOpen = 'ready'; } }).catch(() => { delete $('#open').dataset.devOpen; }); }
|
|
332
332
|
}
|
|
333
333
|
function failureHeadline(message, step) {
|
package/operations/README.md
CHANGED
|
@@ -15,6 +15,9 @@ adapter; it does not return the operations manifest itself or test environment
|
|
|
15
15
|
values.
|
|
16
16
|
|
|
17
17
|
`check` validates declared command input files and required enabled loops.
|
|
18
|
+
It also validates surface and setup declarations in the standard delivery
|
|
19
|
+
packaging policies and committed integration spec, including unique
|
|
20
|
+
`originVariable` values across surfaces.
|
|
18
21
|
The first-party profile also enforces the manifest's `seedContract` marker,
|
|
19
22
|
adapter hooks and flags, command targets, package aliases, tool pins, complete
|
|
20
23
|
portable source inventory and copied source hashes. An explicit
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runeditrun/rer",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.21",
|
|
4
4
|
"description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -76,8 +76,10 @@
|
|
|
76
76
|
"./modules/operator-auth/accounts/native": "./modules/operator-auth/accounts/native.mjs",
|
|
77
77
|
"./modules/operator-auth/dev": "./modules/operator-auth/dev/index.mjs",
|
|
78
78
|
"./modules/operator-auth/dev-admission": "./modules/operator-auth/dev-admission.mjs",
|
|
79
|
-
"./modules/operator-auth/dev/badge": "./modules/operator-auth/dev/badge.mjs",
|
|
80
79
|
"./modules/operator-auth/identity/email-link": "./modules/operator-auth/identity/email-link/index.mjs",
|
|
80
|
+
"./modules/demo": "./modules/demo/index.mjs",
|
|
81
|
+
"./modules/demo/label": "./modules/demo/label.mjs",
|
|
82
|
+
"./modules/demo/vite": "./modules/demo/vite.mjs",
|
|
81
83
|
"./modules/owner-claim": "./modules/owner-claim/index.mjs",
|
|
82
84
|
"./modules/dependencies": "./modules/dependencies/index.mjs",
|
|
83
85
|
"./internal/*": "./*",
|
|
@@ -11,7 +11,8 @@ from trust_bundle import anchor_values
|
|
|
11
11
|
from png_text import text_chunks
|
|
12
12
|
from media import sample_spans
|
|
13
13
|
from c2pa import certificate_spans
|
|
14
|
-
URI_AUTHORITY = re.compile(r'''(?
|
|
14
|
+
URI_AUTHORITY = re.compile(r'''//(?P<authority>[^/?#\s<>"']+)''')
|
|
15
|
+
SCHEME_CHARACTERS = frozenset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-')
|
|
15
16
|
# Match raw, complete commit trailer lines; decoded or embedded prose cannot
|
|
16
17
|
# acquire trailer privileges. Only the address span is omitted from email checks.
|
|
17
18
|
COAUTHOR = re.compile(
|
|
@@ -37,19 +38,39 @@ def without_public_coauthor_addresses(data):
|
|
|
37
38
|
return bytes(result)
|
|
38
39
|
|
|
39
40
|
|
|
40
|
-
def
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
41
|
+
def without_transport_hosts(text):
|
|
42
|
+
pieces, offset = [], 0
|
|
43
|
+
for match in URI_AUTHORITY.finditer(text):
|
|
44
|
+
start = match.start()
|
|
45
|
+
colon = start - 1
|
|
46
|
+
if colon >= offset and text[colon] == ':':
|
|
47
|
+
# The optional scheme regex retried every suffix of a long run.
|
|
48
|
+
# Walk this gap once, stopping at the previous authority's end so
|
|
49
|
+
# matches keep the original substitution's non-overlapping bounds.
|
|
50
|
+
scheme = colon
|
|
51
|
+
while scheme > offset and text[scheme - 1] in SCHEME_CHARACTERS:
|
|
52
|
+
scheme -= 1
|
|
53
|
+
while scheme < colon and not text[scheme].isalpha():
|
|
54
|
+
scheme += 1
|
|
55
|
+
if scheme < colon:
|
|
56
|
+
start = scheme
|
|
57
|
+
userinfo, _, host = match['authority'].rpartition('@')
|
|
58
|
+
# Without a scheme, arbitrary //text can also be a source comment.
|
|
59
|
+
if start == match.start() and host.lower().split(':', 1)[0] not in REPOSITORY_HOSTS:
|
|
60
|
+
pieces.append(text[offset:match.end()])
|
|
61
|
+
else:
|
|
62
|
+
pieces.append(text[offset:start])
|
|
63
|
+
# Keep actual email-valued userinfo, including a decoded %40,
|
|
64
|
+
# while excluding an ordinary transport username@host delimiter.
|
|
65
|
+
pieces.append(userinfo)
|
|
66
|
+
offset = match.end()
|
|
67
|
+
pieces.append(text[offset:])
|
|
68
|
+
return ''.join(pieces)
|
|
48
69
|
|
|
49
70
|
|
|
50
71
|
def private_emails(text, config):
|
|
51
72
|
# URL paths, queries and fragments remain visible to email inspection.
|
|
52
|
-
email_text =
|
|
73
|
+
email_text = without_transport_hosts(without_required_notices(text))
|
|
53
74
|
email_text = re.sub(r'(?i)\b(?a:git@github\.com:)(?=[A-Za-z0-9]|\$\{[A-Za-z_$][A-Za-z0-9_.$]*\})', '', email_text)
|
|
54
75
|
# A package manager's patch filename joins the name and version with an at sign.
|
|
55
76
|
version = r'(?:v?[0-9]+(?:\.[0-9]+)*(?:-[A-Za-z0-9-]+)?|[a-f0-9]{40})(?:\.patch)?(?![A-Za-z0-9_.-])'
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
export const style = `*{box-sizing:border-box}body{margin:0;background:#f5f7fa;color:#17212e;font:16px/1.6 system-ui,sans-serif}main{max-width:52rem;margin:0 auto;padding:24px 16px}h1{font-size:1.75rem;line-height:1.2}article{margin:20px 0;padding:20px;background:white;border:1px solid #cad2dc;border-radius:12px}h2{font-size:1.2rem}h1,h2,p,a,pre{overflow-wrap:anywhere;word-break:normal}pre{white-space:pre-wrap;font:inherit}a{color:#174fb5}a.open{display:block;padding:16px;margin:20px 0;border-radius:8px;background:#174fb5;color:white;font-weight:700;text-align:center;text-decoration:none;min-height:56px}a.nav{display:inline-block;padding:4px 0}small{color:#465569}`;
|
|
2
|
-
|
|
3
|
-
// Added only when the seed declares a theme: its linked rer-theme.css supplies the
|
|
4
|
-
// --rer-* tokens. Each falls back to the plain sheet's value, and the focus ring is
|
|
5
|
-
// always drawn, so a theme that fails to load leaves a readable, usable page.
|
|
6
|
-
export const themedStyle = `.rer-themed body{background:var(--rer-page,#f5f7fa);color:var(--rer-text,#17212e);font-family:var(--rer-font-body,system-ui,sans-serif)}.rer-themed h1,.rer-themed h2{font-family:var(--rer-font-heading,var(--rer-font-body,system-ui,sans-serif))}.rer-themed article{background:var(--rer-surface,#fff);border-color:var(--rer-border,#cad2dc);border-radius:var(--rer-radius,12px)}.rer-themed p,.rer-themed small{color:var(--rer-muted,#465569)}.rer-themed h2,.rer-themed pre{color:var(--rer-text,#17212e)}.rer-themed a{color:var(--rer-link,#174fb5)}.rer-themed a.open{background:var(--rer-accent,#174fb5);color:var(--rer-accent-text,#fff);border-radius:var(--rer-radius,8px)}.rer-themed :focus-visible{outline:3px solid var(--rer-focus,#17212e);outline-offset:3px}`;
|
|
7
|
-
|
|
8
|
-
export function escape(value) {
|
|
9
|
-
return String(value).replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]);
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
// Read link candidates as data only. Never parse or mount mail HTML in the page.
|
|
13
|
-
export function firstLink(message) {
|
|
14
|
-
for (const body of [message.text, message.html]) {
|
|
15
|
-
if (typeof body !== 'string') continue;
|
|
16
|
-
for (const match of body.matchAll(/https?:\/\/[^\s<>"']+/gi)) {
|
|
17
|
-
try {
|
|
18
|
-
const candidate = match[0].replace(/&/g, '&').replace(/[.,;!?]+$/, '');
|
|
19
|
-
const url = new URL(candidate);
|
|
20
|
-
if (['http:', 'https:'].includes(url.protocol) && url.hostname && !url.username && !url.password) return url.href;
|
|
21
|
-
} catch { /* Malformed candidates are ordinary message text. */ }
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
return null;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function metadata(row) {
|
|
28
|
-
return `<h2>${escape(row.message.subject || '(No subject)')}</h2><p>To: ${escape(row.message.to.join(', '))}</p><p>Received: <time datetime="${escape(new Date(row.createdAt).toISOString())}">${escape(new Date(row.createdAt).toUTCString())}</time></p>`;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function document(body, theme) {
|
|
32
|
-
return `<!doctype html><html lang="en"${theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex, nofollow"><title>Development outbox</title>${theme ? `<link rel="stylesheet" href="${escape(theme)}">` : ''}<style>${theme ? style + themedStyle : style}</style></head><body><main><h1>Development outbox</h1><p>Messages captured on this computer. No email was sent.</p>${body}</main></body></html>`;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function listing(rows, path) {
|
|
36
|
-
return rows.length ? rows.map(row => `<article>${metadata(row)}<p><a href="${escape(`${path}?message=${encodeURIComponent(row.id)}`)}" class="nav">Read message</a></p></article>`).join('') : '<p>No messages yet.</p>';
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function detail(row, path) {
|
|
40
|
-
const link = firstLink(row.message);
|
|
41
|
-
return `<p><a href="${escape(path)}" class="nav">All messages</a></p><article>${metadata(row)}${link ? `<a class="open" href="${escape(link)}" rel="noreferrer noopener">Open this link</a>` : ''}<h2>Message text</h2><pre>${escape(row.message.text || row.message.html || '')}</pre>${row.message.attachments?.length ? `<p>${row.message.attachments.length} attachment(s) stored with this message.</p>` : ''}</article>`;
|
|
42
|
-
}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { detail, document, listing, style, themedStyle } from './viewer-html.mjs';
|
|
2
|
-
|
|
3
|
-
// The mail module runs as its own module root (in workerd too), so it cannot
|
|
4
|
-
// import operator-auth's shared predicate (modules/operator-auth/loopback.mjs);
|
|
5
|
-
// this is the same rule: the loopback hosts, 127/8, or a name under .localhost
|
|
6
|
-
// (the front door's http://NAME.localhost:PORT).
|
|
7
|
-
const localhostName = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+localhost$/;
|
|
8
|
-
const isLoopbackHost = hostname => hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || (hostname.length <= 253 && localhostName.test(hostname));
|
|
9
|
-
|
|
10
|
-
function localOrigin(origin) {
|
|
11
|
-
if (typeof origin !== 'string') return null;
|
|
12
|
-
try {
|
|
13
|
-
const url = new URL(origin);
|
|
14
|
-
const ipv4 = url.hostname.split('.');
|
|
15
|
-
const loopback = isLoopbackHost(url.hostname) ||
|
|
16
|
-
(ipv4.length === 4 && ipv4[0] === '127' && ipv4.every(part => /^(0|[1-9]\d{0,2})$/.test(part) && Number(part) <= 255));
|
|
17
|
-
return loopback && ['http:', 'https:'].includes(url.protocol) && url.origin === origin ? url : null;
|
|
18
|
-
} catch { return null; }
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function routePath(path) {
|
|
22
|
-
return typeof path === 'string' && /^\/(?:[A-Za-z0-9_-]+\/?)+$/.test(path) && !path.includes('//');
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
// The seed's own served stylesheet, in the grammar operator-auth branding accepts.
|
|
26
|
-
function themePath(theme) {
|
|
27
|
-
return typeof theme === 'string' && /^\/(?!\/)[A-Za-z0-9._~/-]{1,200}\.css$/.test(theme) && !theme.includes('//') && !theme.includes('/.');
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** Opt-in local route. Rejected requests return null without touching the outbox. */
|
|
31
|
-
export function createDevelopmentOutboxHandler({ local, origin, outbox, path = '/__dev/outbox', theme } = {}) {
|
|
32
|
-
if (theme !== undefined && !themePath(theme)) throw new TypeError('Declare the outbox theme as a same-origin path to the seed\'s served .css file');
|
|
33
|
-
const configured = local === true ? localOrigin(origin) : null;
|
|
34
|
-
if (!configured || !routePath(path)) return async () => null;
|
|
35
|
-
if (!outbox || typeof outbox.list !== 'function' || typeof outbox.get !== 'function') throw new TypeError('Invalid development outbox reader');
|
|
36
|
-
const sheet = theme ? style + themedStyle : style;
|
|
37
|
-
const styles = hash => theme ? `style-src 'self' 'sha256-${hash}'; font-src 'self'; img-src 'self'` : `style-src 'sha256-${hash}'`;
|
|
38
|
-
let hash;
|
|
39
|
-
async function response(body, status = 200, head = false) {
|
|
40
|
-
hash ??= crypto.subtle.digest('SHA-256', new TextEncoder().encode(sheet)).then(bytes => btoa(String.fromCharCode(...new Uint8Array(bytes))));
|
|
41
|
-
return new Response(head ? null : document(body, theme), { status, headers: {
|
|
42
|
-
'Content-Type': 'text/html; charset=utf-8',
|
|
43
|
-
'Cache-Control': 'no-store',
|
|
44
|
-
'X-Robots-Tag': 'noindex, nofollow',
|
|
45
|
-
'X-Content-Type-Options': 'nosniff',
|
|
46
|
-
'Referrer-Policy': 'no-referrer',
|
|
47
|
-
'Content-Security-Policy': `default-src 'none'; script-src 'none'; ${styles(await hash)}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'`,
|
|
48
|
-
...(status === 405 ? { Allow: 'GET, HEAD' } : {}),
|
|
49
|
-
} });
|
|
50
|
-
}
|
|
51
|
-
return async function handle(request) {
|
|
52
|
-
let url;
|
|
53
|
-
try { url = new URL(request.url); } catch { return null; }
|
|
54
|
-
if (url.origin !== configured.origin || url.username || url.password || request.headers.get('host') !== configured.host || url.pathname !== path) return null;
|
|
55
|
-
const requestOrigin = request.headers.get('origin');
|
|
56
|
-
if ((requestOrigin !== null && requestOrigin !== configured.origin) || request.headers.get('sec-fetch-site') === 'cross-site') return null;
|
|
57
|
-
const head = request.method === 'HEAD';
|
|
58
|
-
if (request.method !== 'GET' && !head) return response('<p>Use GET to read messages.</p>', 405);
|
|
59
|
-
if ([...url.searchParams.keys()].some(key => key !== 'message') || url.searchParams.getAll('message').length > 1) return response('<p>Invalid message request.</p>', 400, head);
|
|
60
|
-
try {
|
|
61
|
-
if (url.searchParams.has('message')) {
|
|
62
|
-
const id = url.searchParams.get('message');
|
|
63
|
-
if (!id || id.length > 128) return response('<p>Invalid message request.</p>', 400, head);
|
|
64
|
-
const row = await outbox.get(id);
|
|
65
|
-
return response(row ? detail(row, path) : '<p>Message not found or expired.</p>', row ? 200 : 404, head);
|
|
66
|
-
}
|
|
67
|
-
return response(listing(await outbox.list(), path), 200, head);
|
|
68
|
-
} catch {
|
|
69
|
-
return response('<p>The development outbox is unavailable.</p>', 503, head);
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { EXCHANGE_SCRIPT, exchangeHashes } from '../dev-gate.mjs';
|
|
2
|
-
import { escapeHtml } from '../http.mjs';
|
|
3
|
-
import { allow, sha256 } from '../csp.mjs';
|
|
4
|
-
|
|
5
|
-
// A slim bar at the top of the document, in normal flow so the page below it
|
|
6
|
-
// starts after it and nothing is ever covered. A grid body (the frames that
|
|
7
|
-
// centre their card) gives the bar its own auto row and keeps the card centred
|
|
8
|
-
// in the rest.
|
|
9
|
-
const STYLE = 'body:has(>#rer-dev-badge){grid-template-rows:auto 1fr}#rer-dev-badge{grid-column:1/-1;justify-self:stretch;align-self:start;position:relative;z-index:2147483647;box-sizing:border-box;width:100%;margin:0 0 12px;padding:6px 12px;border-radius:8px;background:#111827;color:#f9fafb;font:13px/1.5 system-ui,sans-serif;text-align:left}#rer-dev-badge summary{min-width:24px;min-height:24px;cursor:pointer;overflow-wrap:anywhere}#rer-dev-badge ul{margin:6px 0 0;padding:0;list-style:none;display:flex;flex-wrap:wrap;gap:4px 16px}#rer-dev-badge li{margin:0}#rer-dev-badge a{display:inline-block;min-width:24px;min-height:24px;color:#bfdbfe;text-decoration:underline}#rer-dev-badge a[aria-current]{color:#fff;font-weight:700}#rer-dev-badge a:focus-visible,#rer-dev-badge summary:focus-visible{outline:2px solid #fff;outline-offset:2px}';
|
|
10
|
-
let styleHash;
|
|
11
|
-
|
|
12
|
-
function badgeHtml({ session, choices }) {
|
|
13
|
-
const current = session ? choices.find(choice => choice.email === session.operator.email)?.as : 'signed-out';
|
|
14
|
-
const label = session ? `Dev: ${escapeHtml(session.operator.email)} (${escapeHtml(session.operator.role)})` : 'Dev: signed out';
|
|
15
|
-
const links = [...choices.map(choice => choice.as), 'signed-out'].map(as => `<li><a href="/auth/dev/enter?as=${encodeURIComponent(as)}"${as === current ? ' aria-current="true"' : ''}>${as === 'signed-out' ? 'Sign out' : `Switch to ${escapeHtml(as)}`}</a></li>`).join('');
|
|
16
|
-
return `<style>${STYLE}</style><aside id="rer-dev-badge" aria-label="Local development identity"><details><summary>${label}</summary><ul>${links}</ul></details></aside>`;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** Adds the fragment key exchange (root only) and the badge to an HTML document. */
|
|
20
|
-
export async function decorate(response, { exchange, badge }) {
|
|
21
|
-
// The Lobby is deliberately script-free. RER_OPEN uses /__dev/key, whose
|
|
22
|
-
// dedicated document exchanges the fragment under its own exact-hash CSP.
|
|
23
|
-
if (response.headers.get('x-rer-document') === 'lobby') exchange = false;
|
|
24
|
-
if ((!exchange && !badge) || !response.headers.get('content-type')?.toLowerCase().startsWith('text/html') || !response.body) return response;
|
|
25
|
-
let bar = '', scripts = '';
|
|
26
|
-
const headers = new Headers(response.headers);
|
|
27
|
-
let policy = headers.get('content-security-policy');
|
|
28
|
-
if (badge) {
|
|
29
|
-
bar = badgeHtml(badge);
|
|
30
|
-
if (policy) policy = allow(policy, 'style-src', styleHash ??= await sha256(STYLE));
|
|
31
|
-
}
|
|
32
|
-
if (exchange) {
|
|
33
|
-
scripts = `<script>${EXCHANGE_SCRIPT}</script>`;
|
|
34
|
-
if (policy) policy = allow(allow(policy, 'script-src', (await exchangeHashes()).script), 'connect-src', "'self'");
|
|
35
|
-
}
|
|
36
|
-
if (policy) headers.set('content-security-policy', policy);
|
|
37
|
-
headers.delete('content-length');
|
|
38
|
-
// The bar opens the body; the key exchange script stays at its end.
|
|
39
|
-
let html = await response.text();
|
|
40
|
-
const open = /<body\b[^>]*>/i.exec(html), at = open ? open.index + open[0].length : 0, end = html.lastIndexOf('</body>');
|
|
41
|
-
if (end >= at) html = html.slice(0, end) + scripts + html.slice(end); else html += scripts;
|
|
42
|
-
html = html.slice(0, at) + bar + html.slice(at);
|
|
43
|
-
return new Response(html, { status: response.status, statusText: response.statusText, headers });
|
|
44
|
-
}
|