@runeditrun/rer 0.2.16 → 0.2.18

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.
Files changed (46) hide show
  1. package/cli/demo-host.mjs +2 -0
  2. package/cli/deploy-claim-request.mjs +32 -0
  3. package/cli/deploy-command.mjs +22 -8
  4. package/cli/deploy-hook.mjs +11 -3
  5. package/cli/deploy-observation.mjs +7 -4
  6. package/cli/deploy-owner.mjs +5 -4
  7. package/cli/deploy.mjs +4 -4
  8. package/cli/door.mjs +4 -3
  9. package/cli/local.mjs +5 -3
  10. package/cli/output.mjs +7 -3
  11. package/cli/pnpm-probe.mjs +19 -10
  12. package/cli/port.mjs +17 -10
  13. package/cli/project-pnpm.mjs +4 -2
  14. package/cli/site-diagnostics.mjs +35 -0
  15. package/cli/site-render.mjs +4 -1
  16. package/cli/site.mjs +5 -0
  17. package/cli/stdio.mjs +12 -0
  18. package/global/CHANGELOG.md +12 -0
  19. package/global/output.mjs +1 -12
  20. package/modules/container/boundary.mjs +70 -34
  21. package/modules/container/build.mjs +20 -3
  22. package/modules/container/import-graph.mjs +233 -0
  23. package/modules/demo-host/README.md +25 -6
  24. package/modules/demo-host/capacity.mjs +27 -6
  25. package/modules/demo-host/container.mjs +37 -9
  26. package/modules/demo-host/entrypoint.sh +9 -0
  27. package/modules/demo-host/image.mjs +18 -0
  28. package/modules/demo-host/pages.mjs +7 -7
  29. package/modules/demo-host/plan.mjs +1 -1
  30. package/modules/demo-host/prepare.mjs +28 -0
  31. package/modules/demo-host/start-script.mjs +11 -4
  32. package/modules/demo-host/startup.mjs +25 -0
  33. package/modules/demo-host/template.mjs +71 -0
  34. package/modules/demo-host/worker.mjs +74 -31
  35. package/modules/deploy-kit/deploy.mjs +8 -3
  36. package/modules/deploy-kit/health-request.mjs +14 -11
  37. package/modules/deploy-kit/health.mjs +16 -6
  38. package/modules/deploy-kit/owner-cli.mjs +24 -4
  39. package/modules/deploy-kit/owner.mjs +6 -3
  40. package/modules/deploy-kit/provider.mjs +6 -2
  41. package/modules/deploy-kit/readiness-window.mjs +32 -0
  42. package/modules/deploy-kit/uploaded-worker.mjs +22 -0
  43. package/modules/deploy-kit/worker.mjs +1 -1
  44. package/onboarding/adapter.mjs +13 -4
  45. package/onboarding/process-diagnostics.mjs +142 -36
  46. package/package.json +1 -1
@@ -37,7 +37,7 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
37
37
  assert(typeof token === 'string' && token.trim() && !/[\r\n]/.test(token), 'invalid-cloudflare-api-token');
38
38
  let requests = 0;
39
39
  // `zone` scope: the zone-level API (/zones/...), for a run site's zone lookup and redirect rule.
40
- async function envelope(path, { method = 'GET', body, assetToken, zone = false } = {}) {
40
+ async function envelope(path, { method = 'GET', body, assetToken, zone = false, signal: callerSignal } = {}) {
41
41
  assert(typeof path === 'string' && (isR2ObjectDelete(path, method) || /^\/[a-z0-9/_?=&.,%-]+$/i.test(path) && !path.includes('..') && !path.split('?')[0].includes('%')), 'invalid-provider-path');
42
42
  assert(!zone || /^\/zones(?:[/?]|$)/.test(path), 'invalid-provider-path');
43
43
  assert(++requests <= maxRequests, 'provider-request-budget');
@@ -46,13 +46,17 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
46
46
  // Preserve complete text for the CLI's remaining redaction before truncation.
47
47
  const redactAuth = text => /\/r2\/buckets\/[^/]+\/objects(?:[/?]|$)/.test(path) ? '[R2 object details omitted]' : /\/d1\/database\/[^/]+\/import$/.test(path) ? '[D1 import details omitted]' : [accountId,token,assetToken].filter(Boolean).flatMap(value=>[value,encodeURIComponent(value),JSON.stringify(value).slice(1,-1)]).sort((a,b)=>b.length-a.length).reduce((value,secret)=>value.split(secret).join('[REDACTED]'),text);
48
48
  const transportFailure = cause => recordDeployFailure(new Error('provider-transport-failed'),{output:redactAuth(transportOutput(cause))});
49
- const signal = AbortSignal.timeout(timeoutMs);
49
+ const timeout = AbortSignal.timeout(timeoutMs);
50
+ const signal = callerSignal ? AbortSignal.any([callerSignal,timeout]) : timeout;
50
51
  let response;
51
52
  try { response = isR2ObjectDelete(path, method) ? await objectDelete(`/client/v4/accounts/${accountId}${path}`, {headers:{Authorization:`Bearer ${token}`},signal}) : await request(zone ? `https://api.cloudflare.com/client/v4${path}` : `https://api.cloudflare.com/client/v4/accounts/${accountId}${path}`, {
52
53
  method, redirect: 'error', signal, headers: { Authorization: `Bearer ${assetToken ?? token}`, ...(body && !(body instanceof FormData) ? { 'Content-Type':'application/json' } : {}) },
53
54
  ...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }),
54
55
  }); } catch (cause) { throw transportFailure(cause); }
55
56
  const output = response.body ? await boundedText(response,undefined,transportFailure) : '';
57
+ // A successful DELETE may have no response body (including HTTP 200).
58
+ // Nonempty replies and all other methods still require the API envelope.
59
+ if (method === 'DELETE' && response.ok && output === '') return { success: true, result: null };
56
60
  let payload;
57
61
  try { payload = JSON.parse(output); } catch { if (response.ok) throw new Error('malformed-response'); }
58
62
  if (!response.ok || payload?.success === false) {
@@ -0,0 +1,32 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { assert } from './validation.mjs';
3
+
4
+ // A single, in-memory deadline travels with this upload. It is deliberately not
5
+ // persisted: an old receipt is not evidence of a fresh propagation window.
6
+ export function readinessWindow({ totalMs = 90000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) } = {}) {
7
+ assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000, 'invalid-health-bound');
8
+ let start;
9
+ return {
10
+ clock, sleep,
11
+ get active() { return start !== undefined; },
12
+ start() { start ??= clock(); },
13
+ remaining() { return start === undefined ? totalMs : Math.max(0, totalMs - (clock() - start)); },
14
+ async pause() { const left = this.remaining(); if (left > 0) await sleep(Math.min(2000, left)); },
15
+ };
16
+ }
17
+
18
+ // Custom deploy hooks can claim before returning their result. Keep the proof
19
+ // inside their current observation scope, never in a process-global cache.
20
+ const observations = new AsyncLocalStorage();
21
+ export const observeReadiness = run => observations.getStore() ? run() : observations.run(new Map(), run);
22
+ export const rememberReadiness = deployed => observations.getStore()?.set(deployed.origin, deployed);
23
+ export const observedReadiness = origin => observations.getStore()?.get(origin);
24
+
25
+ export function readinessAPI(api, window, failure = 'deployment-readiness-timeout') {
26
+ return {...api, request(path, options = {}) {
27
+ const remaining = window.remaining();
28
+ assert(remaining > 0, failure);
29
+ const deadline = AbortSignal.timeout(Math.max(1, Math.ceil(remaining)));
30
+ return api.request(path, {...options, signal:options.signal ? AbortSignal.any([options.signal,deadline]) : deadline});
31
+ }};
32
+ }
@@ -0,0 +1,22 @@
1
+ import { readinessAPI } from './readiness-window.mjs';
2
+ import { activeWorker, deployedFingerprint } from './worker.mjs';
3
+ import { assert, uuid } from './validation.mjs';
4
+
5
+ // Poll only the missing fresh Worker or the exact pre-upload version. A new
6
+ // unrelated version is drift, even during propagation; provider errors fail.
7
+ export async function uploadedWorker({ api, worker, upload, previous, fingerprint, window }) {
8
+ const rawVersion = typeof upload?.deployment_id === 'string' ? upload.deployment_id.toLowerCase() : upload?.deployment_id;
9
+ // The legacy upload API also returns the UUID without separators (Wrangler
10
+ // normalizes this field before treating it as its uploaded version ID).
11
+ const versionId = typeof rawVersion === 'string' && /^[a-f0-9]{32}$/i.test(rawVersion) ? rawVersion.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5').toLowerCase() : rawVersion;
12
+ if (versionId !== undefined) assert(uuid(versionId), 'invalid-upload-version');
13
+ const bounded = readinessAPI(api, window, 'uploaded-worker-timeout');
14
+ while (window.remaining() > 0) {
15
+ const current = await activeWorker(bounded, worker);
16
+ if (current && (!versionId || current.versionId === versionId) && deployedFingerprint(current.settings) === fingerprint) return current;
17
+ const prior = previous && current?.versionId === previous.versionId && current.deploymentId === previous.deploymentId && current.etag === previous.etag;
18
+ assert(!current || prior || current.versionId === versionId, 'uploaded-worker-drift');
19
+ await window.pause();
20
+ }
21
+ throw new Error('uploaded-worker-timeout');
22
+ }
@@ -85,7 +85,7 @@ export async function uploadWorker(api, {plan,artifact,bindings,secrets,migratio
85
85
  if (artifact.assets.length) { metadata.assets = {jwt:await uploadAssets(api,plan.worker,artifact.assets),config:{run_worker_first:RUN_WORKER_FIRST}}; }
86
86
  data.set('metadata',new Blob([JSON.stringify(metadata)],{type:'application/json'}));
87
87
  for (const file of artifact.modules) data.set(file.path,new Blob([Buffer.from(file.base64,'base64')],{type:moduleType(file.path)}),file.path);
88
- await api.request(`/workers/scripts/${plan.worker}?bindings_inherit=strict`,{method:'PUT',body:data});
88
+ return api.request(`/workers/scripts/${plan.worker}?bindings_inherit=strict`,{method:'PUT',body:data});
89
89
  }
90
90
  /** The workers.dev origin, enabling it when allowed. With `workersDev: false` the route is kept
91
91
  * off (a Worker reached only through service bindings) and there is no origin. */
@@ -10,7 +10,7 @@ import { credentialValues } from './redaction.mjs';
10
10
  import { dependencyEnvironment } from './dependency-environment.mjs';
11
11
  import { labels } from './adapter-labels.mjs';
12
12
  import { chooseOrigin, prepareSettings, readSettings } from './adapter-settings.mjs';
13
- import {listenerPorts} from './process-diagnostics.mjs';
13
+ import {listenerPorts,listenerOwnership} from './process-diagnostics.mjs';
14
14
  import { appFetch } from './app-fetch.mjs';
15
15
  import { owner, signIn } from './adapter-auth.mjs';
16
16
  import { installerDevKey } from './dev-identity.mjs';
@@ -214,11 +214,15 @@ async function start(context, hooks) {
214
214
  const url = new URL(health, context.origin).href;
215
215
  const expectedPort=context.runtimePort??Number(new URL(context.origin).port||80);
216
216
  const readinessLabel=`${labels.start} (expected internal port ${expectedPort})`;
217
+ const ownedPorts=async()=>{
218
+ try{return await listenerPorts(child.pid);}
219
+ catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
220
+ };
217
221
  try {
218
222
  await store.waitForReady(readinessLabel, child, ready ? probeSignal => ready(url, probeSignal, context) : probeSignal => (hooks.health ?? defaultHealth)(url, probeSignal, context), { signal, timeoutMs: ['dev','preview'].includes(context.verb)?Math.min(timeoutMs??60000,120000):(timeoutMs??900000), ...(softAfterMs ? { softAfterMs } : {}), ...(intervalMs ? { intervalMs } : {}) });
219
223
  } catch (error) {
220
224
  if (signal?.aborted) throw error;
221
- const ports=await listenerPorts(child.pid);
225
+ const ports=await ownedPorts();
222
226
  if(ports.length){
223
227
  const message=store.redact(`Application listened on port ${ports.join(', ')}; readiness failed for expected internal port ${expectedPort}. Check application health and the runtime target's port binding.`);
224
228
  store.report(message);const prior=approvedFailure(error);error=commandFailure(`${prior?.message??readinessLabel}\n${message}`,prior??{});
@@ -228,8 +232,13 @@ async function start(context, hooks) {
228
232
  // Another app can take the loopback port between the port check and the bind;
229
233
  // its /health would pass. Claim and sign in only against the process this
230
234
  // setup started.
231
- if (!(await listenerPorts(child.pid)).includes(expectedPort)) {
232
- const message = store.redact?.(`Another process answered on port ${expectedPort}; the application did not bind it. Nothing was sent. Stop that process or choose another port, then run setup again.`) ?? `Another process answered on port ${expectedPort}; the application did not bind it.`;
235
+ let ownership;
236
+ try { ownership=await listenerOwnership(child.pid,expectedPort,context.runtimePort?'127.0.0.1':new URL(url).hostname); }
237
+ catch(error){throw installationFailure('command_failed',{step:'start',diagnostic:error});}
238
+ if (ownership.status !== 'owned') {
239
+ const message = (store.redact??(value=>value))(ownership.status==='other'
240
+ ? `Another process answered on port ${expectedPort}; the application did not bind it. Listener PID ${ownership.pid}. Nothing was sent. Stop that process or choose another port, then run setup again.`
241
+ : `The application did not bind expected internal port ${expectedPort}; completed inspection found no listener on the health address. Nothing was sent. Check the application binding, then run setup again.`);
233
242
  store.report?.(message);
234
243
  throw installationFailure('command_failed', { step: 'start', diagnostic: commandFailure(message, {}) });
235
244
  }
@@ -1,75 +1,175 @@
1
1
  import {execFile} from 'node:child_process';
2
2
  import {promisify} from 'node:util';
3
- import {realpath,readFile,readdir,readlink} from 'node:fs/promises';
3
+ import {lstat,realpath,readFile,readdir,readlink} from 'node:fs/promises';
4
4
  import {basename,join} from 'node:path';
5
+ import {homedir} from 'node:os';
6
+ import {isIP} from 'node:net';
7
+ import {commandFailure} from './failures.mjs';
5
8
  const exec=promisify(execFile);
6
9
  // macOS supplies lsof in /usr/sbin, which a command PATH may omit.
7
10
  // Diagnose sockets with the system utility even when that PATH is constrained.
8
11
  const lsof=process.platform==='darwin'?'/usr/sbin/lsof':'lsof';
9
- const run=async(command,args)=>{
10
- try{return (await exec(command,args,{timeout:3000,maxBuffer:1024*1024})).stdout;}
11
- catch(error){
12
- // lsof exits 1 when a selected PID has exited,
13
- // while still returning the live listeners of other selected PIDs.
14
- return command===lsof&&error.code===1&&typeof error.stdout==='string'?error.stdout:'';
12
+ // One monotonic budget covers every command in an ownership decision.
13
+ export const inspectionContext=()=>({deadline:performance.now()+15000});
14
+ const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,noMatch=false}={})=>{
15
+ const invocation=[command,...args].join(' ').replaceAll(homedir(),'~');
16
+ let failure;
17
+ for(let attempt=0;attempt<2;attempt++){
18
+ const remaining=Math.floor(context.deadline-performance.now());
19
+ if(remaining<=0)break;
20
+ const timeout=attempt===0?Math.min(3000,remaining):remaining;
21
+ try{return (await exec(command,args,{timeout,maxBuffer})).stdout;}
22
+ catch(error){
23
+ // A quiet lsof exit 1 means no match, including a selected PID exiting
24
+ // while other selected PIDs still return records. Diagnostic output instead
25
+ // means inspection failed, even if lsof also returned partial records.
26
+ if((command===lsof||noMatch)&&error.code===1&&!error.killed&&!error.signal&&typeof error.stdout==='string'&&typeof error.stderr==='string'&&!error.stderr.trim())return error.stdout;
27
+ 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
+ }
15
29
  }
30
+ throw commandFailure(`ownership-unchecked: Listener ownership could not be checked: ${invocation} ${failure??'total inspection deadline exhausted'} (at most 2 attempts; shared total bound 15000 ms). Launch refused; no ownership conclusion was made.`,{});
16
31
  };
17
- export async function processName(pid){
32
+
33
+ export async function processName(pid,context=inspectionContext()){
34
+ try{process.kill(pid,0);}catch(error){if(error.code==='ESRCH')return 'process';}
18
35
  if(process.platform==='linux'){const name=await readFile(`/proc/${pid}/comm`,'utf8').catch(()=>'');if(name)return name.trim().replace(/[^a-zA-Z0-9._-]/g,'').slice(0,80)||'process';}
19
- const text=await run('/bin/ps',['-p',String(pid),'-o','comm=']);
36
+ // A completed quiet ps exit 1 means the PID has exited. Its display label
37
+ // is optional; this does not prove listener ownership or process liveness.
38
+ const text=await run('/bin/ps',['-p',String(pid),'-o','comm='],context,{noMatch:true});
20
39
  return basename(text.trim()).replace(/[^a-zA-Z0-9._-]/g,'').slice(0,80)||'process';
21
40
  }
22
- function records(text){let record;const rows=[];for(const line of text.split('\n')){if(line[0]==='p'){record={pid:Number(line.slice(1)),names:[]};rows.push(record);}else if(line[0]==='n'&&record)record.names.push(line.slice(1));}return rows;}
23
- export async function listeners(pids){
41
+ function records(text,socketTypes=false){
42
+ let record,family;const rows=[];
43
+ for(const line of text.split('\n')){
44
+ if(line[0]==='p'){record={pid:Number(line.slice(1)),names:[],...(socketTypes?{sockets:[]}: {})};family=undefined;rows.push(record);}
45
+ else if(line[0]==='f')family=undefined;
46
+ else if(line[0]==='t')family=['IPv4','IPv6'].includes(line.slice(1))?line.slice(1):undefined;
47
+ else if(line[0]==='n'&&record){const name=line.slice(1);record.names.push(name);if(socketTypes)record.sockets.push({name,family});}
48
+ }
49
+ return rows;
50
+ }
51
+ export async function listeners(pids,context=inspectionContext(),port){
24
52
  // -a is essential: otherwise lsof ORs the PID and network selections and
25
53
  // still walks every process's sockets. Read only the owned tree on failure.
26
- if(process.platform!=='linux')return records(await run(lsof,['-nP',...(pids?['-a','-p',pids.join(',')]:[]),'-iTCP','-sTCP:LISTEN','-Fpn']));
54
+ if(!pids&&!port&&context.allListeners)return context.allListeners;
55
+ if(process.platform!=='linux'){
56
+ // lsof renders both IPv4 and IPv6 wildcards as '*'. Keep the type of
57
+ // each file descriptor: a process may hold sockets of both families.
58
+ // -b avoids unrelated mount stat/readlink calls that can block even a PID
59
+ // query on macOS. -w suppresses the expected warnings for skipped filesystem
60
+ // metadata; neither that metadata nor pathname selection is used here.
61
+ const rows=records(await run(lsof,['-nP','-b','-w',...(pids?['-a','-p',pids.join(',')]:[]),port?`-iTCP:${port}`:'-iTCP','-sTCP:LISTEN','-Fpftn'],context),true);
62
+ if(!pids&&!port)context.allListeners=rows;
63
+ return rows;
64
+ }
27
65
  const sockets=new Map();
28
66
  for(const file of ['tcp','tcp6'])for(const line of (await readFile('/proc/net/'+file,'utf8').catch(()=>'' )).trim().split('\n').slice(1)){
29
- const parts=line.trim().split(/\s+/);if(parts[3]==='0A')sockets.set(parts[9],parseInt(parts[1].split(':')[1],16));
67
+ const parts=line.trim().split(/\s+/);if(parts[3]==='0A'&&(!port||parseInt(parts[1].split(':')[1],16)===port))sockets.set(parts[9],{name:linuxAddress(parts[1]),family:file==='tcp'?'IPv4':'IPv6'});
30
68
  }
31
69
  const found=[];
32
70
  for(const pid of pids??await linuxPids()){
33
- const names=[];for(const target of await descriptors(pid)){const inode=/^socket:\[(\d+)\]$/.exec(target)?.[1];if(sockets.has(inode))names.push('127.0.0.1:'+sockets.get(inode));}
34
- if(names.length)found.push({pid,names});
35
- }return found;
71
+ const held=[];for(const target of await descriptors(pid)){const inode=/^socket:\[(\d+)\]$/.exec(target)?.[1];if(sockets.has(inode))held.push(sockets.get(inode));}
72
+ if(held.length)found.push({pid,names:held.map(socket=>socket.name),sockets:held});
73
+ }
74
+ if(!pids&&!port)context.allListeners=found;
75
+ return found;
76
+ }
77
+ // /proc encodes each 32-bit address word in host byte order.
78
+ function linuxAddress(local){
79
+ const [hex,port]=local.split(':');
80
+ const bytes=hex.match(/.{8}/g).map(word=>Buffer.from(word.match(/../g).reverse().join(''),'hex'));
81
+ const address=Buffer.concat(bytes);
82
+ const host=address.every(byte=>byte===0)?'*':hex.length===8?[...address].join('.'):
83
+ address.subarray(0,10).every(byte=>byte===0)&&address[10]===255&&address[11]===255?'::ffff:'+([...address.subarray(12)].join('.')):
84
+ [...Array(8)].map((_,i)=>address.readUInt16BE(i*2).toString(16)).join(':').replace(/(^|:)0(?::0)+(?=:|$)/,':').replace(/^:([^:])/, '::$1').replace(/([^:]):$/, '$1::');
85
+ return `${host.includes(':')?'['+host+']':host}:${parseInt(port,16)}`;
36
86
  }
37
87
  async function linuxPids(){return (await readdir('/proc')).filter(name=>/^\d+$/.test(name)).map(Number);}
38
88
  async function descriptors(pid){return Promise.all((await readdir(`/proc/${pid}/fd`).catch(()=>[])).map(fd=>readlink(`/proc/${pid}/fd/${fd}`).catch(()=>'')));}
39
89
 
40
90
  const portOf=name=>Number(/:(\d+)$/.exec(name)?.[1]);
41
- export async function processCwd(pid){
91
+ export async function processCwd(pid,context=inspectionContext()){
42
92
  if(process.platform==='linux')return readlink(`/proc/${pid}/cwd`).catch(()=>undefined);
43
- return records(await run(lsof,['-a','-p',String(pid),'-d','cwd','-Fpn'])).flatMap(row=>row.names)[0];
93
+ return records(await run(lsof,['-nP','-b','-w','-a','-p',String(pid),'-d','cwd','-Fpn'],context)).flatMap(row=>row.names)[0];
44
94
  }
45
95
  // Every TCP port some process listens on, on any address: a wildcard listener
46
96
  // does not stop a bind to 127.0.0.1, yet it still serves that port's traffic.
47
- export async function listeningPorts(){return new Set((await listeners()).flatMap(row=>row.names.map(portOf)).filter(Number.isInteger));}
97
+ export async function listeningPorts(context=inspectionContext()){return new Set((await listeners(undefined,context)).flatMap(row=>row.names.map(portOf)).filter(Number.isInteger));}
48
98
  // The process that listens on a port on the given host's address or on every
49
99
  // address, with its command and working directory.
50
- export async function portListener(port,host){
51
- const bare=host?.replace(/^\[|\]$/g,''),serves=name=>{const address=name.slice(0,name.lastIndexOf(':')).replace(/^\[|\]$/g,'');return portOf(name)===port&&(!host||address==='*'||address===bare);};
52
- const row=(await listeners()).find(item=>item.names.some(serves));
53
- return row&&{pid:row.pid,command:await processName(row.pid),cwd:await processCwd(row.pid)};
100
+ function normalizedAddress(address){
101
+ const bare=address.replace(/^\[|\]$/g,'');
102
+ if(bare.toLowerCase()==='localhost')return 'localhost';
103
+ if(isIP(bare)!==6)return bare;
104
+ const [ip,zone]=bare.split('%');
105
+ const normalized=new URL(`http://[${ip}]/`).hostname.slice(1,-1)+(zone?'%'+zone:'');
106
+ const mapped=/^::ffff:([\da-f]+):([\da-f]+)$/i.exec(normalized);
107
+ return mapped?mapped.slice(1).flatMap(word=>[parseInt(word,16)>>>8,parseInt(word,16)&255]).join('.'):normalized;
54
108
  }
55
-
56
- export async function listenerPorts(pid){
57
- // Include child processes: pnpm commonly delegates the actual Vite listener.
58
- const rows=(await run('/bin/ps',['-axo','pid=,ppid='])).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number));
109
+ // undefined means the inspection cannot prove whether this socket serves the
110
+ // address. In particular, an IPv6 wildcard does not reveal IPV6_V6ONLY.
111
+ function serves({name,family},port,host){
112
+ if(portOf(name)!==port)return false;
113
+ if(!host)return true;
114
+ const address=normalizedAddress(name.slice(0,name.lastIndexOf(':'))),target=normalizedAddress(host);
115
+ if(target==='localhost'){
116
+ const matches=['127.0.0.1','::1'].map(loopback=>serves({name,family},port,loopback));
117
+ return matches.includes(true)?true:matches.includes(undefined)?undefined:false;
118
+ }
119
+ if(address!=='*'&&address!=='0.0.0.0'&&address!=='::')return address===target;
120
+ const socketFamily=family??(address==='0.0.0.0'?'IPv4':address==='::'?'IPv6':undefined);
121
+ if(socketFamily==='IPv4')return isIP(target)===4;
122
+ if(socketFamily==='IPv6'&&isIP(target)===6)return true;
123
+ return undefined;
124
+ }
125
+ function matchingListener(rows,port,host){
126
+ const row=rows.find(row=>row.sockets.some(socket=>serves(socket,port,host)===true));
127
+ if(row)return row;
128
+ if(rows.some(row=>row.sockets.some(socket=>serves(socket,port,host)===undefined))){
129
+ throw commandFailure(`ownership-unchecked: Listener inspection found a wildcard socket on port ${port} whose address family does not prove it serves ${host}. No ownership conclusion was made. Bind the application to the health address explicitly, then retry.`,{});
130
+ }
131
+ }
132
+ export async function portListener(port,host,context=inspectionContext()){
133
+ const row=matchingListener(await listeners(undefined,context,port),port,host);
134
+ return row&&{pid:row.pid,command:await processName(row.pid,context),cwd:await processCwd(row.pid,context)};
135
+ }
136
+ async function descendants(pid,context){
137
+ const rows=(await run('/bin/ps',['-axo','pid=,ppid='],context)).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number));
59
138
  const owned=new Set([pid]);for(let changed=true;changed;){changed=false;for(const [child,parent]of rows)if(owned.has(parent)&&!owned.has(child)){owned.add(child);changed=true;}}
60
- return [...new Set((await listeners([...owned])).filter(row=>owned.has(row.pid)).flatMap(row=>row.names.map(name=>Number(/:(\d+)$/.exec(name)?.[1])).filter(port=>Number.isInteger(port)&&port>0&&port<=65535)))].sort((a,b)=>a-b);
139
+ return owned;
140
+ }
141
+ export async function listenerPorts(pid,context=inspectionContext()){
142
+ const owned=await descendants(pid,context);
143
+ return [...new Set((await listeners([...owned],context)).filter(row=>owned.has(row.pid)).flatMap(row=>row.names.map(portOf)).filter(port=>Number.isInteger(port)&&port>0&&port<=65535))].sort((a,b)=>a-b);
144
+ }
145
+ // An exact health address can use positive own-tree evidence. localhost can
146
+ // reach either loopback family, so it also needs a completed inspection with
147
+ // no foreign listener on either address before owner/sign-in can proceed.
148
+ export async function listenerOwnership(pid,port,host,context=inspectionContext()){
149
+ const owned=await descendants(pid,context);
150
+ const ownRows=await listeners([...owned],context);
151
+ const own=ownRows.find(row=>owned.has(row.pid)&&row.sockets.some(socket=>serves(socket,port,host)===true));
152
+ const localhost=host&&normalizedAddress(host)==='localhost';
153
+ if(own&&!localhost)return {status:'owned',pid:own.pid};
154
+ const rows=await listeners(undefined,context,port);
155
+ if(localhost){
156
+ const foreign=matchingListener(rows.filter(row=>!owned.has(row.pid)),port,host);
157
+ if(foreign)return {status:'other',pid:foreign.pid};
158
+ }
159
+ const row=matchingListener(rows,port,host);
160
+ return row?{status:owned.has(row.pid)?'owned':'other',pid:row.pid}:{status:'none'};
61
161
  }
62
162
  // The caller and the chain that launched it (an installer server running setup,
63
163
  // pnpm, a shell) act for this command, never against it.
64
- async function callerLineage(){
65
- const parents=new Map((await run('/bin/ps',['-axo','pid=,ppid='])).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number)));
164
+ async function callerLineage(context){
165
+ const parents=new Map((await run('/bin/ps',['-axo','pid=,ppid='],context)).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number)));
66
166
  const lineage=new Set([process.pid,process.ppid]);
67
167
  for(let pid=process.ppid;pid>1&&parents.has(pid);){pid=parents.get(pid);if(lineage.has(pid))break;lineage.add(pid);}
68
168
  return lineage;
69
169
  }
70
- export async function localProcessConflict(root,savedOrigin){
71
- root=await realpath(root);const all=await listeners(),lineage=await callerLineage();
72
- const cwdRecords=process.platform!=='linux'&&all.length?records(await run(lsof,['-a','-p',all.map(row=>row.pid).join(','),'-d','cwd','-Fpn'])):[];
170
+ export async function localProcessConflict(root,savedOrigin,context=inspectionContext()){
171
+ root=await realpath(root);const all=await listeners(undefined,context),lineage=await callerLineage(context);
172
+ 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)):[];
73
173
  let port;try{const url=new URL(savedOrigin);port=Number(url.port||80);}catch{}
74
174
  for(const row of all){
75
175
  if(lineage.has(row.pid))continue;
@@ -79,13 +179,19 @@ export async function localProcessConflict(root,savedOrigin){
79
179
  // A listener running somewhere else is another program's or another checkout's
80
180
  // server: it does not use this checkout's state, so it only blocks the port.
81
181
  if(onSavedPort&&places.length&&!places.some(place=>place===root||place.startsWith(root+'/')))continue;
82
- if(onSavedPort||inCheckout)return {pid:row.pid,command:await processName(row.pid),reason:onSavedPort?`saved local port ${port}`:'this checkout'};
182
+ if(onSavedPort||inCheckout)return {pid:row.pid,command:await processName(row.pid,context),reason:onSavedPort?`saved local port ${port}`:'this checkout'};
83
183
  }
84
184
  // A process may hold the canonical database without listening. Inspect only
85
185
  // actual state files, never broad checkout contents or a process environment.
86
186
  const state=join(root,'.wrangler/state');
187
+ try{await lstat(state);}catch(error){if(error.code==='ENOENT')return;throw error;}
87
188
  let held;
88
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;}}
89
- else held=records(await run(lsof,['-nP','+D',state,'-Fpn'])).find(row=>!lineage.has(row.pid));
90
- if(held)return {pid:held.pid,command:await processName(held.pid),reason:'the canonical local state'};
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'};
91
197
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.16",
3
+ "version": "0.2.18",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",