@tnunamak/dalan 0.6.2 → 0.8.0
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/CHANGELOG.md +53 -0
- package/CONTRIBUTING.md +4 -0
- package/PROTOCOL.md +2 -0
- package/README.md +81 -84
- package/bin/dalan.mjs +9 -0
- package/bin/dot-worker.mjs +29 -4
- package/contracts/adapter-qualification.schema.json +170 -0
- package/docs/chatgpt-worker-onboarding.md +10 -14
- package/docs/claude-worker-onboarding.md +9 -8
- package/docs/codex-to-muse.md +21 -35
- package/docs/connect-chatgpt.md +10 -16
- package/docs/dalan-upgrade.md +4 -2
- package/docs/local-agent-mcp.md +24 -4
- package/docs/local-agent-requester.md +46 -0
- package/docs/manual-setup.md +2 -2
- package/docs/operations.md +12 -13
- package/docs/pull-workers.md +1 -2
- package/docs/service-setup.md +110 -163
- package/docs/setup-reference.md +6 -6
- package/docs/t3-question-relationship.md +43 -0
- package/docs/t3-reverse-control.md +12 -8
- package/docs/t3-wake-fence-r4.md +42 -0
- package/docs/test-suite-isolation.md +204 -0
- package/docs/worker-clients.md +6 -4
- package/package.json +5 -3
- package/qualification/README.md +13 -0
- package/qualification/mcp.json +121 -0
- package/qualification/protocol-v0.json +127 -0
- package/scripts/dalan-try-selfcheck.mjs +8 -7
- package/scripts/worker-bridge-setup.mjs +91 -81
- package/src/admin-socket.mjs +2 -1
- package/src/answer-journal.mjs +200 -0
- package/src/as-store.mjs +5 -3
- package/src/as.mjs +35 -26
- package/src/auth-check.mjs +59 -0
- package/src/cli-help.mjs +16 -16
- package/src/client-approval.mjs +57 -0
- package/src/client-convenience.mjs +166 -0
- package/src/client-conveniences.json +106 -0
- package/src/client-conveniences.schema.json +97 -0
- package/src/connect-cli.mjs +5 -5
- package/src/default-home.mjs +36 -0
- package/src/destinations/index.mjs +6 -0
- package/src/destinations/none.mjs +3 -0
- package/src/destinations/t3.mjs +63 -6
- package/src/execution.mjs +20 -2
- package/src/follow-current.mjs +27 -0
- package/src/gozar-routes.mjs +315 -0
- package/src/host-budget.mjs +17 -11
- package/src/host-execution-policy.mjs +2 -2
- package/src/host-stop-reverify.mjs +6 -4
- package/src/integrator.mjs +3 -1
- package/src/redirect-policy.mjs +61 -0
- package/src/route-setting.mjs +71 -12
- package/src/server.mjs +64 -12
- package/src/service-auto-update.mjs +8 -1
- package/src/service-launchd.mjs +186 -0
- package/src/service-migrate-workers.mjs +12 -2
- package/src/service-update-runtime.mjs +40 -6
- package/src/service-update.mjs +20 -14
- package/src/service.mjs +211 -63
- package/src/setup.mjs +55 -44
- package/src/store.mjs +77 -14
- package/src/submission-policy.mjs +8 -4
- package/src/t3.mjs +21 -2
- package/src/tool-registry.mjs +54 -8
- package/src/try-exposure.mjs +7 -657
- package/src/try-hosted.mjs +71 -101
- package/src/try-selfcheck.mjs +15 -8
- package/src/try.mjs +9 -13
- package/src/workers.mjs +4 -3
- package/src/workspace.mjs +94 -15
- package/scripts/lib/expose-tailscale.mjs +0 -408
- package/src/try-hosted-clients.mjs +0 -46
package/src/workspace.mjs
CHANGED
|
@@ -96,13 +96,15 @@ function safePath(dir,p,existing=false) { p=relative(p); let cursor=dir; for(con
|
|
|
96
96
|
// alias (docs/PRIVATE-NOTE.TXT, a decomposed "é") that a case-insensitive or normalizing filesystem (macOS APFS) opens as
|
|
97
97
|
// the excluded file is excluded too. On case-sensitive Linux this over-excludes a differently-cased sibling: that fails closed.
|
|
98
98
|
export const canonicalPath=p=>p.split('/').map(part=>part.normalize('NFC').toLowerCase()).join('/');
|
|
99
|
-
export const isExcludedPath=(p,excluded)=>excluded.has(
|
|
99
|
+
export const isExcludedPath=(p,excluded)=>{const parts=canonicalPath(p).split('/');return parts.some((_,i)=>excluded.has(parts.slice(0,i+1).join('/')));};
|
|
100
100
|
function scopeOf(assignment) {
|
|
101
101
|
const raw=assignment.scope_paths, excluded=new Set((assignment.scope_excluded||[]).map(d=>canonicalPath(d.path)));
|
|
102
102
|
const scope=Array.isArray(raw)&&raw.length?raw.map(p=>String(p).replace(/^\.\//,'').replace(/\/$/,'')):[];
|
|
103
103
|
const paths=!scope.length||scope.includes('.')?null:scope;
|
|
104
104
|
const outputs=outputsOf(assignment);
|
|
105
|
-
|
|
105
|
+
const sensitive=assignment.execution_scope==='implementation'&&!paths&&excluded.size?sensitivePolicyPaths():null;
|
|
106
|
+
if(sensitive?.error) throw new Error('sensitive_policy_unavailable');
|
|
107
|
+
return paths||excluded.size||outputs.size?{paths,excluded,outputs,sensitive}:null;
|
|
106
108
|
}
|
|
107
109
|
// output_paths: new files the job may create. They are readable and writable once they exist, and are the only writable
|
|
108
110
|
// files of a read-only assignment. Submit proved they are absent at the pinned revision and not sensitive.
|
|
@@ -115,7 +117,7 @@ function existsAtHead(dir,file) {
|
|
|
115
117
|
if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
|
|
116
118
|
return r.stdout.length>0;
|
|
117
119
|
}
|
|
118
|
-
const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded);
|
|
120
|
+
const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||!isSensitiveRepoPath(p,scope.sensitive.paths));
|
|
119
121
|
// A directory that holds a scope entry may be listed so the walk can reach it.
|
|
120
122
|
const leadsToScope=(p,scope)=>!scope||!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`));
|
|
121
123
|
function outputDirectoryHint(file,outputs) {
|
|
@@ -219,8 +221,9 @@ const GENERATED_EXCLUDES=[...GENERATED_DIRS].map(name=>`:(exclude,glob)**/${name
|
|
|
219
221
|
// environment, so symlinks are stored as links and never followed, and a path behind a symlinked directory is not read. New objects go to
|
|
220
222
|
// `scratch`, a throw-away directory, never into the mirror. Returns the tree id, or null with a reason when git could not read everything
|
|
221
223
|
// (an unreadable tracked file, an unreadable untracked directory, a timeout, a skip-worktree or assume-unchanged index entry, a missing
|
|
222
|
-
// index): then the receipt says the observation is unavailable instead of hashing a placeholder.
|
|
223
|
-
|
|
224
|
+
// index): then the receipt says the observation is unavailable instead of hashing a placeholder. Explicitly withheld, absent
|
|
225
|
+
// skip-worktree entries are omitted from the private digest index. The whole call has a 120 s deadline.
|
|
226
|
+
export async function treeDigest(dir,scratch,withheldPaths=[]) {
|
|
224
227
|
const own=!scratch;if(own) fs.mkdirSync(path.join(root,'run'),{recursive:true,mode:0o700});scratch??=fs.mkdtempSync(path.join(root,'run','digest-'));
|
|
225
228
|
try {
|
|
226
229
|
const base=gitEnv(),deadline=Date.now()+DIGEST_DEADLINE_MS,left=()=>Math.max(1000,deadline-Date.now());
|
|
@@ -239,7 +242,18 @@ export async function treeDigest(dir,scratch) {
|
|
|
239
242
|
// Index flags that tell git not to look at the worktree (skip-worktree, assume-unchanged) would hide changes from `add -u`.
|
|
240
243
|
const flags=await gitAsync2(dir,['ls-files','-v','-z'],env,left());
|
|
241
244
|
if(flags.status!==0) return {sha256:null,reason:flags.status===null?'git_timeout_or_error':`git_could_not_read_a_file: ${flags.stderr.split('\n')[0].slice(0,160)}`};
|
|
242
|
-
|
|
245
|
+
const withheld=new Set(withheldPaths),omitted=[];
|
|
246
|
+
for(const record of flags.stdout.split('\0').filter(Boolean)) {
|
|
247
|
+
const file=record.slice(2);
|
|
248
|
+
if(record[0]==='S'&&withheld.has(file)&&!pathExistsOrThrow(absBytes(dir,file))) omitted.push(file);
|
|
249
|
+
else if(record[0]==='S'||/[a-z]/.test(record[0])) return {sha256:null,reason:'index_flags_present'};
|
|
250
|
+
}
|
|
251
|
+
// Only this private index drops verified absent exclusions. The workspace
|
|
252
|
+
// index retains its flags so physical withholding is never a worker patch.
|
|
253
|
+
if(omitted.length) {
|
|
254
|
+
const removed=await gitAsyncInput(dir,['update-index','--force-remove','-z','--stdin'],env,Buffer.from(omitted.join('\0')+'\0'));
|
|
255
|
+
if(removed.status!==0) return {sha256:null,reason:'withheld_index_removal_failed'};
|
|
256
|
+
}
|
|
243
257
|
const deleted=await gitAsync2(dir,['ls-files','--deleted','-z'],env,left());
|
|
244
258
|
if(deleted.status!==0) return {sha256:null,reason:deleted.status===null?'git_timeout_or_error':`git_could_not_read_a_file: ${deleted.stderr.split('\n')[0].slice(0,160)}`};
|
|
245
259
|
for(const file of deleted.stdout.split('\0').filter(Boolean)) {
|
|
@@ -358,6 +372,63 @@ export function sensitiveMasks(dir,repo,copyDir) {
|
|
|
358
372
|
if(maskedPaths.length>MASK_LIMIT) throw new Error(`sensitive_mask_limit: ${maskedPaths.length} sensitive files in the checkout (limit ${MASK_LIMIT}); a check cannot be confined around that many`);
|
|
359
373
|
return {paths:maskedPaths,sourceExemptions,policyError:policy.error};
|
|
360
374
|
}
|
|
375
|
+
// Excluded implementation files never enter the runner's source tree. Skip-worktree
|
|
376
|
+
// keeps these deliberate omissions out of the worker's patch without reading blobs.
|
|
377
|
+
function withholdExcludedPaths(dir,assignment) {
|
|
378
|
+
if(assignment.execution_scope!=='implementation'||!assignment.scope_paths?.includes('.')||!assignment.scope_excluded?.length) return;
|
|
379
|
+
const excluded=assignment.scope_excluded.map(entry=>relative(entry.path));
|
|
380
|
+
for(const file of excluded) {
|
|
381
|
+
const parent=path.posix.dirname(file);
|
|
382
|
+
if(parent!=='.') safePath(dir,parent);
|
|
383
|
+
fs.rmSync(path.join(dir,file),{force:true});
|
|
384
|
+
// Prune empty ancestors too: a sensitive directory name must not remain in
|
|
385
|
+
// the execution checkout after its last withheld file is removed.
|
|
386
|
+
for(let ancestor=parent;ancestor!=='.';ancestor=path.posix.dirname(ancestor)) {
|
|
387
|
+
try { fs.rmdirSync(path.join(dir,ancestor)); }
|
|
388
|
+
catch(error) { if(error.code==='ENOTEMPTY'||error.code==='EEXIST') break;if(error.code!=='ENOENT') throw error; }
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const tracked=new Set(git(['-C',dir,'ls-files','-z']).split('\0').filter(Boolean));
|
|
392
|
+
const omitted=excluded.filter(file=>tracked.has(file));
|
|
393
|
+
if(omitted.length) git(['-C',dir,'update-index','--skip-worktree','--',...omitted]);
|
|
394
|
+
}
|
|
395
|
+
function excludedPathsAbsent(dir,assignment) {
|
|
396
|
+
if(!assignment.scope_excluded?.length) return false;
|
|
397
|
+
if(!dir) return false;
|
|
398
|
+
const policy=sensitivePolicyPaths();
|
|
399
|
+
if(policy.error) return false;
|
|
400
|
+
for(const entry of assignment.scope_excluded) {
|
|
401
|
+
const file=relative(entry.path),parent=path.posix.dirname(file);
|
|
402
|
+
if(parent!=='.') safePath(dir,parent);
|
|
403
|
+
try { fs.lstatSync(path.join(dir,file));return false; } catch(error) { if(error.code!=='ENOENT') return false; }
|
|
404
|
+
}
|
|
405
|
+
// Check the current policy too, including ignored and generated files. A new
|
|
406
|
+
// sensitive file or policy change invalidates the proof rather than unmasking it.
|
|
407
|
+
const walk=base=>fs.readdirSync(path.join(dir,base),{withFileTypes:true}).every(entry=>{
|
|
408
|
+
if(entry.name==='.git') return true;
|
|
409
|
+
const file=base?`${base}/${entry.name}`:entry.name;
|
|
410
|
+
if(isSensitiveRepoPath(file,policy.paths)) return false;
|
|
411
|
+
return !entry.isDirectory()||walk(file);
|
|
412
|
+
});
|
|
413
|
+
return walk('');
|
|
414
|
+
}
|
|
415
|
+
// The same proof as excludedPathsAbsent, made from the pinned tree for callers with no checkout. Withholding removes exactly the paths in
|
|
416
|
+
// scope_excluded, so the proof holds when no other path in the tree (or any directory above it) is sensitive under the current policy.
|
|
417
|
+
// A sensitive file the record does not list, a malformed record, an unreadable tree or an unreadable policy all give false.
|
|
418
|
+
function excludedPathsAccountedAtBase(mirror,assignment) {
|
|
419
|
+
if(!assignment.scope_excluded?.length) return false;
|
|
420
|
+
const policy=sensitivePolicyPaths();
|
|
421
|
+
if(policy.error) return false;
|
|
422
|
+
const listed=spawnSync('git',['-C',mirror,'ls-tree','-r','-z','--name-only','--full-tree',assignmentInput(assignment).base_sha],{encoding:'utf8',timeout:10000,maxBuffer:64*1024*1024,env:gitEnv()});
|
|
423
|
+
if(listed.error||listed.status!==0) return false;
|
|
424
|
+
let excluded;
|
|
425
|
+
// A malformed persisted entry is not proof; refuse instead of throwing from claim or get.
|
|
426
|
+
try { excluded=new Set(assignment.scope_excluded.map(entry=>relative(entry.path))); } catch { return false; }
|
|
427
|
+
return listed.stdout.split('\0').filter(file=>file&&!excluded.has(file)).every(file=>{
|
|
428
|
+
const parts=file.split('/');
|
|
429
|
+
return parts.every((_,i)=>!isSensitiveRepoPath(parts.slice(0,i+1).join('/'),policy.paths));
|
|
430
|
+
});
|
|
431
|
+
}
|
|
361
432
|
// A list shown in the receipt: the first `shown` names, the true total, and a flag when the preview is shorter than the total.
|
|
362
433
|
const preview=(list,shown)=>list===null?null:({preview:list.slice(0,shown),total:list.length,truncated:list.length>shown});
|
|
363
434
|
// The lists go to one bounded artifact; null when every list is empty. The cap counts the serialized JSON, envelope and separators
|
|
@@ -454,10 +525,11 @@ export class Workspace {
|
|
|
454
525
|
row=this.store.db.prepare('SELECT * FROM workspaces WHERE request_id=?').get(requestId);
|
|
455
526
|
}
|
|
456
527
|
if(row.claim_id!==claimId||row.base_sha!==ctx.input.base_sha||row.path!==dir||git(['-C',dir,'rev-parse','HEAD']).trim()!==checkoutSha) throw new Error('workspace binding mismatch');
|
|
528
|
+
withholdExcludedPaths(dir,ctx.a.assignment);
|
|
457
529
|
if(!row.initial_patch_applied) {
|
|
458
530
|
if(ctx.input.input_patch) {
|
|
459
531
|
const reverse=spawnSync('git',['-C',dir,'apply','--reverse','--check','-'],{input:ctx.input.input_patch,encoding:'utf8',timeout:10000,env:gitEnv()});
|
|
460
|
-
if(reverse.status!==0) applyPatchToTree(dir,ctx.input.input_patch);
|
|
532
|
+
if(reverse.status!==0) applyPatchToTree(dir,ctx.input.input_patch,scopeOf(ctx.a.assignment));
|
|
461
533
|
}
|
|
462
534
|
this.store.db.prepare('UPDATE workspaces SET initial_patch_applied=1 WHERE request_id=?').run(requestId);
|
|
463
535
|
}
|
|
@@ -704,8 +776,11 @@ export class Workspace {
|
|
|
704
776
|
.run(id,requestId,claimId,kind,file,bytes.length,sha(bytes),1,new Date().toISOString(),this.retention(requestId),claimId,requestId);
|
|
705
777
|
return {artifact_id:id,size:bytes.length,sha256:sha(bytes),kind};
|
|
706
778
|
}
|
|
779
|
+
mirrorFor(input,worker='dot') {
|
|
780
|
+
return fs.existsSync(mirrorPath(input.github_repo,{worker}))?mirrorPath(input.github_repo,{worker}):prepareGithubRepo(input,{worker});
|
|
781
|
+
}
|
|
707
782
|
availableChecksFor(assignment,worker='dot') {
|
|
708
|
-
const input=assignmentInput(assignment),mirror=
|
|
783
|
+
const input=assignmentInput(assignment),mirror=this.mirrorFor(input,worker);
|
|
709
784
|
return withCheckMetadata(mirror,input.base_sha,dir=>availableChecks(input.github_repo,dir));
|
|
710
785
|
}
|
|
711
786
|
// Catalog data is response enrichment; keep it from discarding a committed claim or finish snapshot.
|
|
@@ -715,9 +790,12 @@ export class Workspace {
|
|
|
715
790
|
const repo=assignment.inputs[0].github_repo;
|
|
716
791
|
const declared=dir?availableChecks(repo,dir):this.availableChecksFor(assignment,worker);
|
|
717
792
|
if(execution!=='host') return {available_checks:declared};
|
|
718
|
-
|
|
793
|
+
// Without a checkout (claim, get) the persisted exclusion record is checked against the pinned tree. A check still
|
|
794
|
+
// proves physical absence in its own checkout before it launches.
|
|
795
|
+
const absent=dir?excludedPathsAbsent(dir,assignment):excludedPathsAccountedAtBase(this.mirrorFor(assignmentInput(assignment),worker),assignment);
|
|
796
|
+
const baseRefusal=hostCheckRefusal(assignment,null,null,null,absent);
|
|
719
797
|
const readiness=hostReadiness();
|
|
720
|
-
const candidates=baseRefusal||!readiness.ready?[]:declared.filter(id=>!hostCheckRefusal(assignment,repo,id));
|
|
798
|
+
const candidates=baseRefusal||!readiness.ready?[]:declared.filter(id=>!hostCheckRefusal(assignment,repo,id,null,absent));
|
|
721
799
|
const reason=baseRefusal||(!readiness.ready?readiness.reason:null)||(!candidates.length?'host_check_not_allowlisted: no permitted owner-configured check is runnable':null);
|
|
722
800
|
return {available_checks:candidates,host_execution_available:candidates.length>0,host_execution_unavailable_reason:reason};
|
|
723
801
|
} catch(error) {
|
|
@@ -727,7 +805,7 @@ export class Workspace {
|
|
|
727
805
|
}
|
|
728
806
|
}
|
|
729
807
|
checkMetadataFor(assignment,worker='dot') {
|
|
730
|
-
const input=assignmentInput(assignment),mirror=
|
|
808
|
+
const input=assignmentInput(assignment),mirror=this.mirrorFor(input,worker);
|
|
731
809
|
return checkSpecsAt(input.github_repo,mirror,input.base_sha);
|
|
732
810
|
}
|
|
733
811
|
// What the bridge itself observed about one host check, and nothing more. The receipt identifies the candidate source: git's view of
|
|
@@ -787,7 +865,8 @@ export class Workspace {
|
|
|
787
865
|
if(execution!=='host') return refuse();
|
|
788
866
|
// Refuse before resolving worker-controlled check metadata or launching either phase.
|
|
789
867
|
const inputForPolicy=assignmentInput(context.a.assignment);
|
|
790
|
-
const
|
|
868
|
+
const prepared=context.a.assignment.scope_excluded?.length?this.ensure(requestId,claimId,subject,true,worker):null;
|
|
869
|
+
const refusal=hostCheckRefusal(context.a.assignment,inputForPolicy.github_repo,checkId,null,excludedPathsAbsent(prepared?.dir,context.a.assignment));
|
|
791
870
|
if(refusal) return refuse(refusal);
|
|
792
871
|
const readiness=hostReadiness();
|
|
793
872
|
if(!readiness.ready) return refuse(`host_execution (${readiness.reason})`);
|
|
@@ -846,13 +925,13 @@ export class Workspace {
|
|
|
846
925
|
const backend=hostBackend();let evidenceMs=0;
|
|
847
926
|
const timed=async fn=>{const t=Date.now();try{return await fn();}finally{evidenceMs+=Date.now()-t;}};
|
|
848
927
|
fs.mkdirSync(path.join(root,'run'),{recursive:true,mode:0o700});scratch=fs.mkdtempSync(path.join(root,'run','digest-'));
|
|
849
|
-
const firstSnap=await timed(()=>treeDigest(dir,scratch));
|
|
928
|
+
const firstSnap=await timed(()=>treeDigest(dir,scratch,a.assignment.scope_excluded?.map(entry=>entry.path)));
|
|
850
929
|
const sourceCopyDir=path.join(scratch,'source-exemptions');fs.mkdirSync(sourceCopyDir,{mode:0o700});
|
|
851
930
|
const masked=sensitiveMasks(dir,input.github_repo,sourceCopyDir);
|
|
852
931
|
// One service reservation and one cumulative envelope cover preparation,
|
|
853
932
|
// install and check. Mutations stay in the private tmpfs execution copy.
|
|
854
933
|
assertCurrentAuthority();
|
|
855
|
-
const launchRefusal=hostCheckRefusal(this.store.get(requestId).assignment,input.github_repo,checkId,spec);
|
|
934
|
+
const launchRefusal=hostCheckRefusal(this.store.get(requestId).assignment,input.github_repo,checkId,spec,excludedPathsAbsent(dir,this.store.get(requestId).assignment));
|
|
856
935
|
if(launchRefusal) throw new Error(launchRefusal);
|
|
857
936
|
const hosted=await this.runConfined(requestId,dir,spec.argv,{...spec,host_budget:jobBudget,maskPaths:masked.paths,sourceExemptions:masked.sourceExemptions},{checkRunId,repo:input.github_repo,checkId,expectedSpec:spec,cancelled:()=>{
|
|
858
937
|
try { assertCurrentAuthority(); return false; } catch { return true; }
|
|
@@ -939,7 +1018,7 @@ export class Workspace {
|
|
|
939
1018
|
async runConfined(requestId,dir,command,spec,{cancelled,checkRunId,repo=null,checkId=null,expectedSpec=null}={}) {
|
|
940
1019
|
// Policy is rechecked at the only launch boundary; repository metadata
|
|
941
1020
|
// cannot opt the operator in or bypass the whole-repository read grant.
|
|
942
|
-
const refusal=hostCheckRefusal(this.store.get(requestId).assignment,repo,checkId,expectedSpec);
|
|
1021
|
+
const refusal=hostCheckRefusal(this.store.get(requestId).assignment,repo,checkId,expectedSpec,excludedPathsAbsent(dir,this.store.get(requestId).assignment));
|
|
943
1022
|
if(refusal) throw new Error(refusal);
|
|
944
1023
|
const budgets=parseHostBudget(spec.host_budget);
|
|
945
1024
|
budgets.wall_ms=Math.min(budgets.wall_ms,spec.timeout_ms??budgets.wall_ms);
|
|
@@ -1,408 +0,0 @@
|
|
|
1
|
-
// Public exposure for a worker bridge: Tailscale Funnel (preflight, port choice, the funnel rule, public verification,
|
|
2
|
-
// removal) and the ngrok fallback (config file and printed commands only; this code never runs ngrok).
|
|
3
|
-
// Used by scripts/worker-bridge-setup.mjs --expose tailscale|ngrok. Nothing here changes a serve or funnel rule that already
|
|
4
|
-
// exists. The only Tailscale mutation is our own rule on our own port.
|
|
5
|
-
import fs from 'node:fs';
|
|
6
|
-
import https from 'node:https';
|
|
7
|
-
import path from 'node:path';
|
|
8
|
-
import { randomBytes } from 'node:crypto';
|
|
9
|
-
import { spawnSync } from 'node:child_process';
|
|
10
|
-
import { Resolver } from 'node:dns/promises';
|
|
11
|
-
|
|
12
|
-
// Public ports Tailscale Funnel accepts, in the order we prefer them.
|
|
13
|
-
// Source: https://tailscale.com/kb/1223/funnel ("443, 8443, and 10000").
|
|
14
|
-
export const FUNNEL_PORTS = [443, 8443, 10000];
|
|
15
|
-
// Admin pages. Host verified this session: https://tailscale.com/kb/1223/funnel and https://tailscale.com/kb/1153/enabling-https
|
|
16
|
-
// both name console.tailscale.com. Brief: "use whichever host the docs currently give".
|
|
17
|
-
export const ADMIN_DNS_URL = 'https://console.tailscale.com/admin/dns';
|
|
18
|
-
export const ADMIN_ACL_URL = 'https://console.tailscale.com/admin/acls';
|
|
19
|
-
export const INSTALL_URL = 'https://tailscale.com/download';
|
|
20
|
-
export const HTTPS_DOC_URL = 'https://tailscale.com/kb/1153/enabling-https';
|
|
21
|
-
export const FUNNEL_DOC_URL = 'https://tailscale.com/kb/1223/funnel';
|
|
22
|
-
export const MACOS_VARIANTS_DOC_URL = 'https://tailscale.com/docs/concepts/macos-variants';
|
|
23
|
-
const DEFAULT_TIMEOUT_MS = 20_000;
|
|
24
|
-
const refuseOverwrite = message => { throw Object.assign(new Error(message), { name: 'SetupRefusal', code: 'SETUP_REFUSED' }); };
|
|
25
|
-
|
|
26
|
-
// Public DNS: up to 10 minutes is normal (first Funnel certificate). Progress every 30 s.
|
|
27
|
-
export const DNS_WAIT_MS = 600_000;
|
|
28
|
-
export const DNS_PROGRESS_MS = 30_000;
|
|
29
|
-
|
|
30
|
-
// ngrok: free-plan limits from https://ngrok.com/docs/pricing-limits/free-plan-limits (20,000 HTTP requests/month, 1 GB egress/month).
|
|
31
|
-
export const NGROK_FREE_PLAN_URL = 'https://ngrok.com/docs/pricing-limits/free-plan-limits';
|
|
32
|
-
export const NGROK_QUOTA_WARNING = `ngrok free plan quota (${NGROK_FREE_PLAN_URL}): 20,000 HTTP requests per month and 1 GB egress per month. `
|
|
33
|
-
+ 'A 60 s wake hook alone makes about 43,000 requests per month. Set the hook poll interval to 300 s or more with ngrok. '
|
|
34
|
-
+ 'Rejecting fast polls on the bridge would still count them against the quota, so the interval has to be set in the hook.';
|
|
35
|
-
export const WAKE_POLL_SECONDS = 60;
|
|
36
|
-
export const WAKE_POLL_SECONDS_NGROK = 300;
|
|
37
|
-
|
|
38
|
-
const MACOS_APP = '/Applications/Tailscale.app';
|
|
39
|
-
|
|
40
|
-
// The wake-hook poll interval for this home: 300 s when any recorded exposure is ngrok, else 60 s.
|
|
41
|
-
export function pollIntervalSeconds(records) {
|
|
42
|
-
return records.some(r => r.mode === 'ngrok') ? WAKE_POLL_SECONDS_NGROK : WAKE_POLL_SECONDS;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// Reads every dot-bridge-<worker>.exposure.json in a bridge home. Missing home or no records gives [].
|
|
46
|
-
export function readExposureRecords(home, { readdir = fs.readdirSync, read = fs.readFileSync } = {}) {
|
|
47
|
-
let names;
|
|
48
|
-
try { names = readdir(home); } catch { return []; }
|
|
49
|
-
return names.filter(n => /^dot-bridge-.+\.exposure\.json$/.test(n))
|
|
50
|
-
.map(n => JSON.parse(read(path.join(home, n), 'utf8')));
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export function enableMagicDnsMessage() {
|
|
54
|
-
return `MagicDNS is off for this tailnet. Turn it on at ${ADMIN_DNS_URL} (the DNS page, MagicDNS), then retry. Doc: ${HTTPS_DOC_URL} (step 2).`;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// The doc says enabling HTTPS publishes machine names and the tailnet DNS name on a public ledger. Say so before the owner clicks.
|
|
58
|
-
export function enableHttpsMessage() {
|
|
59
|
-
return `HTTPS certificates are off for this tailnet. Turn them on at ${ADMIN_DNS_URL} (HTTPS Certificates: Enable HTTPS). `
|
|
60
|
-
+ `Tailscale publishes your machine names and tailnet DNS name on a public ledger when you do; accept that or do not enable Funnel. Then retry. Doc: ${HTTPS_DOC_URL}.`;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export function enableFunnelMessage() {
|
|
64
|
-
return `Funnel is not allowed for this tailnet. Add the funnel node attribute at ${ADMIN_ACL_URL} (Access controls, Funnel section, "Add Funnel to policy"), then retry. Doc: ${FUNNEL_DOC_URL}.`;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export function macConflictMessage(label) {
|
|
68
|
-
return `macOS: the Tailscale ${label} is installed and its CLI is the \`tailscale\` on PATH. Funnel is not supported by the App Store app or the Standalone app; only the open-source tailscaled supports it (${MACOS_VARIANTS_DOC_URL}). The app and the open-source daemon conflict. Nothing was changed.\n`
|
|
69
|
-
+ 'Either:\n'
|
|
70
|
-
+ ' 1. Quit Tailscale from the menu bar, then uninstall the app (Standalone: move /Applications/Tailscale.app to the Trash; App Store: delete it from Launchpad). Then run:\n'
|
|
71
|
-
+ ' brew install tailscale && sudo brew services start tailscale && sudo tailscale up\n'
|
|
72
|
-
+ ' and retry this command.\n'
|
|
73
|
-
+ ' 2. Or use the ngrok fallback instead: --expose ngrok --ngrok-domain <assigned-domain>';
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const notInstalled = () => new Error(`Tailscale is not installed. Install it from ${INSTALL_URL}, then run \`tailscale up\` and retry.`);
|
|
77
|
-
const notRunning = () => new Error('Tailscale is not running or not logged in. Run `tailscale up` and retry.');
|
|
78
|
-
|
|
79
|
-
// Injected by tests through PATH only; the real binary is never named here except as the PATH lookup.
|
|
80
|
-
export function defaultTailscale(args) {
|
|
81
|
-
return spawnSync('tailscale', args, { encoding: 'utf8', timeout: DEFAULT_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// First executable named `name` on PATH, or null.
|
|
85
|
-
export function whichOnPath(name, env = process.env) {
|
|
86
|
-
for (const dir of (env.PATH ?? '').split(path.delimiter)) {
|
|
87
|
-
if (!dir) continue;
|
|
88
|
-
const candidate = path.join(dir, name);
|
|
89
|
-
try { fs.accessSync(candidate, fs.constants.X_OK); return candidate; } catch { /* keep looking */ }
|
|
90
|
-
}
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// macOS variant check (darwin only). Detects the App Store or Standalone app at /Applications/Tailscale.app.
|
|
95
|
-
// It is in use when the `tailscale` on PATH resolves into that bundle. The open-source tailscaled (Homebrew) on PATH is fine.
|
|
96
|
-
// Everything is injected so tests can use fake paths. Returns null off macOS or when the app is not installed.
|
|
97
|
-
// The App Store label relies on the _MASReceipt directory (the usual App Store receipt location). Assumed, not doc-verified.
|
|
98
|
-
export function macVariantCheck({
|
|
99
|
-
platform = process.platform, exists = fs.existsSync, realpath = fs.realpathSync, which = name => whichOnPath(name),
|
|
100
|
-
} = {}) {
|
|
101
|
-
if (platform !== 'darwin' || !exists(MACOS_APP)) return null;
|
|
102
|
-
const label = exists(path.join(MACOS_APP, 'Contents/_MASReceipt/receipt')) ? 'App Store app' : 'Standalone app';
|
|
103
|
-
const cli = which('tailscale');
|
|
104
|
-
let real = null;
|
|
105
|
-
if (cli) { try { real = realpath(cli); } catch { real = cli; } }
|
|
106
|
-
if (real && real.startsWith(`${MACOS_APP}/`)) return { label, inUse: true, cli: real };
|
|
107
|
-
return { label, inUse: false, cli: real, warning: `the Tailscale ${label} is installed, but the \`tailscale\` on PATH is not its CLI (${real ?? 'not found'}); continuing with that one. If the app's daemon is also running, the two will conflict: ${MACOS_VARIANTS_DOC_URL}` };
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function parseJsonOutput(result, label) {
|
|
111
|
-
const text = (result.stdout ?? '').trim();
|
|
112
|
-
if (!text.startsWith('{')) {
|
|
113
|
-
if (result.status === 0 && text === '') return {};
|
|
114
|
-
throw new Error(`could not read \`${label}\` output as JSON`);
|
|
115
|
-
}
|
|
116
|
-
try { return JSON.parse(text); }
|
|
117
|
-
catch { throw new Error(`could not parse \`${label}\` output as JSON`); }
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function runOrThrow(tailscale, args, label) {
|
|
121
|
-
const r = tailscale(args);
|
|
122
|
-
if (r.error?.code === 'ENOENT') throw notInstalled();
|
|
123
|
-
if (r.error) throw new Error(`\`tailscale ${label}\` failed to start (${r.error.code ?? r.error.message})`);
|
|
124
|
-
if (r.status !== 0) throw new Error(`\`tailscale ${label}\` exited ${r.status ?? r.signal}: ${String(r.stderr ?? '').trim().split('\n').at(-1) ?? ''}`.trimEnd());
|
|
125
|
-
return r;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// Ports the cap allows: the query of https://tailscale.com/cap/funnel-ports?ports=443,8443,10000 in Self.CapMap.
|
|
129
|
-
export function allowedFunnelPorts(capMap = {}) {
|
|
130
|
-
const ports = new Set();
|
|
131
|
-
for (const key of Object.keys(capMap)) {
|
|
132
|
-
if (!key.startsWith('https://tailscale.com/cap/funnel-ports')) continue;
|
|
133
|
-
for (const p of new URL(key).searchParams.get('ports')?.split(',') ?? []) {
|
|
134
|
-
const n = Number(p);
|
|
135
|
-
if (Number.isInteger(n)) ports.add(n);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
return [...ports].sort((a, b) => a - b);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Ports that serve status already uses: TCP listeners and Web handlers keyed by "name:port".
|
|
142
|
-
export function occupiedPorts(serve) {
|
|
143
|
-
const occupied = new Map();
|
|
144
|
-
for (const k of Object.keys(serve.TCP ?? {})) occupied.set(Number(k), `TCP listener on ${k}`);
|
|
145
|
-
for (const k of Object.keys(serve.Web ?? {})) occupied.set(Number(k.split(':').at(-1)), `web rule ${k}`);
|
|
146
|
-
return occupied;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Read-only. Throws with the exact next step for each refusal, in this order: macOS variant, status, MagicDNS, HTTPS, funnel.
|
|
150
|
-
// MagicDNS is CurrentTailnet.MagicDNSEnabled (field name observed in `tailscale status --json` on this host).
|
|
151
|
-
// HTTPS is the `https` key in Self.CapMap (observed on this host; the HTTPS doc names no field, so this is assumed to track it).
|
|
152
|
-
// Funnel is the `funnel` key in Self.CapMap plus the funnel-ports cap (observed on this host).
|
|
153
|
-
export function preflight({ tailscale = defaultTailscale, platform = process.platform, mac = {} } = {}) {
|
|
154
|
-
const variant = macVariantCheck({ platform, ...mac });
|
|
155
|
-
if (variant?.inUse) throw new Error(macConflictMessage(variant.label));
|
|
156
|
-
const status = runOrThrow(tailscale, ['status', '--json'], 'status --json');
|
|
157
|
-
const s = parseJsonOutput(status, 'tailscale status --json');
|
|
158
|
-
if (s.BackendState !== 'Running') throw notRunning();
|
|
159
|
-
const dnsName = String(s.Self?.DNSName ?? '').replace(/\.$/, '');
|
|
160
|
-
if (!dnsName) throw new Error('`tailscale status --json` has no Self.DNSName; the node is not fully set up');
|
|
161
|
-
if (s.CurrentTailnet?.MagicDNSEnabled !== true) throw new Error(enableMagicDnsMessage());
|
|
162
|
-
const capMap = s.Self?.CapMap ?? {};
|
|
163
|
-
if (!('https' in capMap)) throw new Error(enableHttpsMessage());
|
|
164
|
-
const allowed = allowedFunnelPorts(capMap);
|
|
165
|
-
if (!('funnel' in capMap) || allowed.length === 0) throw new Error(enableFunnelMessage());
|
|
166
|
-
const serve = parseJsonOutput(runOrThrow(tailscale, ['serve', 'status', '--json'], 'serve status --json'), 'tailscale serve status --json');
|
|
167
|
-
return { dnsName, allowed, occupied: occupiedPorts(serve), warnings: variant?.warning ? [variant.warning] : [] };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// --funnel-port must be allowed and free. Without it, the first free allowed port of 443, 8443, 10000.
|
|
171
|
-
export function choosePort({ requested, allowed, occupied }) {
|
|
172
|
-
if (requested !== undefined) {
|
|
173
|
-
if (!allowed.includes(requested)) throw new Error(`--funnel-port ${requested} is not allowed for this tailnet (allowed: ${allowed.join(', ')})`);
|
|
174
|
-
if (occupied.has(requested)) throw new Error(`--funnel-port ${requested} is already used (${occupied.get(requested)}). Pick another port; existing rules are never replaced.`);
|
|
175
|
-
return requested;
|
|
176
|
-
}
|
|
177
|
-
const free = FUNNEL_PORTS.find(p => allowed.includes(p) && !occupied.has(p));
|
|
178
|
-
if (free !== undefined) return free;
|
|
179
|
-
const lines = FUNNEL_PORTS.map(p => {
|
|
180
|
-
if (!allowed.includes(p)) return ` ${p}: not allowed by this tailnet`;
|
|
181
|
-
return ` ${p}: ${occupied.get(p) ?? 'free'}`;
|
|
182
|
-
});
|
|
183
|
-
throw new Error(`no free Funnel port (443, 8443, 10000). What occupies each port:\n${lines.join('\n')}\nRemove one of those rules yourself, or pass --funnel-port with a free allowed port.`);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export function publicUrl(dnsName, port) {
|
|
187
|
-
return `https://${dnsName}${port === 443 ? '' : `:${port}`}`;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
export const funnelOnArgs = (port, localPort) => ['funnel', '--bg', `--https=${port}`, `http://127.0.0.1:${localPort}`];
|
|
191
|
-
export const funnelOffArgs = port => ['funnel', `--https=${port}`, 'off'];
|
|
192
|
-
export const funnelStatusArgs = () => ['funnel', 'status', '--json'];
|
|
193
|
-
|
|
194
|
-
// True when the funnel status maps exactly our port to our local bridge port, and nothing else on that port.
|
|
195
|
-
export function funnelRuleMatches(status, dnsName, port, localPort) {
|
|
196
|
-
const key = `${dnsName}:${port}`;
|
|
197
|
-
const handlers = status.Web?.[key]?.Handlers ?? {};
|
|
198
|
-
return Object.keys(handlers).join(',') === '/'
|
|
199
|
-
&& handlers['/'].Proxy === `http://127.0.0.1:${localPort}`
|
|
200
|
-
&& status.AllowFunnel?.[key] === true;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
export function funnelRulePresent(status, dnsName, port) {
|
|
204
|
-
return Object.hasOwn(status.Web ?? {}, `${dnsName}:${port}`);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// Public DNS through three resolvers in parallel (one resolver can keep a negative-cached NXDOMAIN for a new name for >10 min).
|
|
208
|
-
// Returns the first IPv4 found as { address, server }, or null when none of them has an answer.
|
|
209
|
-
export const PUBLIC_DNS_SERVERS = ['1.1.1.1', '8.8.8.8', '9.9.9.9'];
|
|
210
|
-
|
|
211
|
-
export function makePublicResolver(resolvers = defaultResolvers()) {
|
|
212
|
-
return name => new Promise(resolve => {
|
|
213
|
-
let pending = resolvers.length;
|
|
214
|
-
const settle = () => { if (--pending === 0) resolve(null); };
|
|
215
|
-
for (const { server, resolver } of resolvers) {
|
|
216
|
-
resolver.resolve4(name).then(
|
|
217
|
-
addresses => (addresses[0] ? resolve({ address: addresses[0], server }) : settle()),
|
|
218
|
-
settle,
|
|
219
|
-
);
|
|
220
|
-
}
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function defaultResolvers() {
|
|
225
|
-
return PUBLIC_DNS_SERVERS.map(server => {
|
|
226
|
-
const resolver = new Resolver({ timeout: 3000, tries: 1 });
|
|
227
|
-
resolver.setServers([server]);
|
|
228
|
-
return { server, resolver };
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
// GET /admin pinned to the address that DNS returned. Expects 404 from the bridge (its unauthenticated path).
|
|
233
|
-
export function fetchPinned(url, address, { timeoutMs = 15_000 } = {}) {
|
|
234
|
-
const u = new URL(url);
|
|
235
|
-
return new Promise((resolve, reject) => {
|
|
236
|
-
const req = https.request({
|
|
237
|
-
hostname: u.hostname, port: u.port || 443, path: '/admin', method: 'GET', timeout: timeoutMs,
|
|
238
|
-
// Keep the hostname for SNI and the Host header; only the address is pinned.
|
|
239
|
-
lookup: (_host, options, cb) => (options?.all ? cb(null, [{ address, family: 4 }]) : cb(null, address, 4)),
|
|
240
|
-
}, res => { res.resume(); resolve(res.statusCode); });
|
|
241
|
-
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
242
|
-
req.on('error', reject);
|
|
243
|
-
req.end();
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
// Retries DNS for up to timeoutMs (10 minutes is normal), logging progress every progressMs, then retries GET /admin for up to 120 s until it returns 404.
|
|
248
|
-
const HTTPS_WAIT_MS = 120_000;
|
|
249
|
-
|
|
250
|
-
export async function verifyPublic({
|
|
251
|
-
url, dnsName, resolve4, request = fetchPinned, sleep = ms => new Promise(r => setTimeout(r, ms)), now = Date.now,
|
|
252
|
-
timeoutMs = DNS_WAIT_MS, intervalMs = 5_000, progressMs = DNS_PROGRESS_MS, log = console.log,
|
|
253
|
-
}) {
|
|
254
|
-
const secs = ms => Math.round(ms / 1000);
|
|
255
|
-
const start = now();
|
|
256
|
-
const end = start + timeoutMs;
|
|
257
|
-
let nextProgress = progressMs;
|
|
258
|
-
let found = null;
|
|
259
|
-
while (!found) {
|
|
260
|
-
found = await resolve4(dnsName);
|
|
261
|
-
if (found) break;
|
|
262
|
-
const elapsed = now() - start;
|
|
263
|
-
if (elapsed >= nextProgress && elapsed < timeoutMs) {
|
|
264
|
-
log(`waiting for public DNS of ${dnsName} … ${secs(elapsed)} s / ${secs(timeoutMs)} s`);
|
|
265
|
-
nextProgress += progressMs;
|
|
266
|
-
}
|
|
267
|
-
if (now() >= end) break;
|
|
268
|
-
await sleep(intervalMs);
|
|
269
|
-
}
|
|
270
|
-
if (!found) {
|
|
271
|
-
log(`FAIL public DNS: no A record for ${dnsName} from 1.1.1.1, 8.8.8.8 or 9.9.9.9 after ${secs(timeoutMs)} s. Likely cause: the Funnel rule or its certificate is not ready, or the name is not published yet. Next: run \`dig @8.8.8.8 ${dnsName} A\` (also try @1.1.1.1 and @9.9.9.9) and \`tailscale funnel status\`, then retry.`);
|
|
272
|
-
return false;
|
|
273
|
-
}
|
|
274
|
-
const { address, server } = found;
|
|
275
|
-
log(`PASS public DNS: ${dnsName} -> ${address} (via ${server})`);
|
|
276
|
-
// Funnel needs a while after the rule exists: the first requests can fail the TLS handshake or hit a 5xx.
|
|
277
|
-
// Retry every non-404 outcome until the window ends, then fail with the last error or status.
|
|
278
|
-
const httpsEnd = now() + HTTPS_WAIT_MS;
|
|
279
|
-
let nextHttpsProgress = now() + progressMs;
|
|
280
|
-
let last;
|
|
281
|
-
for (;;) {
|
|
282
|
-
try {
|
|
283
|
-
const code = await request(url, address);
|
|
284
|
-
if (code === 404) break;
|
|
285
|
-
last = `GET /admin returned ${code}, expected 404 from the bridge`;
|
|
286
|
-
} catch (e) { last = e.message; }
|
|
287
|
-
if (now() >= httpsEnd) {
|
|
288
|
-
log(`FAIL public HTTPS: ${last} (still failing after ${secs(HTTPS_WAIT_MS)} s). Likely cause: the Funnel certificate is still being issued, the rule is not active, or a different service answers on this port. Next: \`tailscale funnel status\` and check the local port, then retry.`);
|
|
289
|
-
return false;
|
|
290
|
-
}
|
|
291
|
-
if (now() >= nextHttpsProgress) {
|
|
292
|
-
log(`waiting for public HTTPS of ${dnsName} … last result: ${last}`);
|
|
293
|
-
nextHttpsProgress += progressMs;
|
|
294
|
-
}
|
|
295
|
-
await sleep(intervalMs);
|
|
296
|
-
}
|
|
297
|
-
log('PASS public HTTPS: GET /admin returned 404 from the bridge');
|
|
298
|
-
return true;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
export function recordPath(unitDir, worker) {
|
|
302
|
-
return path.join(unitDir, `dot-bridge-${worker}.exposure.json`);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
function writeRecord(file, value) {
|
|
306
|
-
try { fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); }
|
|
307
|
-
catch (error) {
|
|
308
|
-
if (error.code === 'EEXIST') refuseOverwrite(`${file} already exists; refusing to overwrite an exposure record`);
|
|
309
|
-
throw error;
|
|
310
|
-
}
|
|
311
|
-
fs.chmodSync(file, 0o600);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
function readOwnedRecord(file) {
|
|
315
|
-
const stat = fs.lstatSync(file);
|
|
316
|
-
if (!stat.isFile() || stat.isSymbolicLink() || (typeof process.getuid === 'function' && stat.uid !== process.getuid())) {
|
|
317
|
-
throw new Error(`exposure record ${file} is not a regular file owned by the current user; refusing to use it`);
|
|
318
|
-
}
|
|
319
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// Step 3 of the brief: run our funnel rule, then prove it maps exactly our port.
|
|
323
|
-
export function applyFunnel({ tailscale = defaultTailscale, dnsName, port, localPort }) {
|
|
324
|
-
runOrThrow(tailscale, funnelOnArgs(port, localPort), `funnel --bg --https=${port}`);
|
|
325
|
-
const status = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
|
|
326
|
-
if (!funnelRuleMatches(status, dnsName, port, localPort)) {
|
|
327
|
-
throw new Error(`funnel status does not show ${dnsName}:${port} mapped to http://127.0.0.1:${localPort}. Run \`tailscale funnel status\` and fix it by hand; nothing else was changed.`);
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
export const ngrokStopCommands = worker => [
|
|
332
|
-
`ngrok service stop`,
|
|
333
|
-
`ngrok service uninstall`,
|
|
334
|
-
].map(c => ` ${c} # worker ${worker}`);
|
|
335
|
-
|
|
336
|
-
// --remove: a tailscale record turns off exactly its rule and verifies it is gone; an ngrok record only drops the record
|
|
337
|
-
// and prints the ngrok commands (ngrok is never run here). Units and home are left alone.
|
|
338
|
-
export function removeExposure({ tailscale = defaultTailscale, file, log = console.log }) {
|
|
339
|
-
if (!fs.existsSync(file)) throw new Error(`no exposure record at ${file}; nothing to remove`);
|
|
340
|
-
const rec = readOwnedRecord(file);
|
|
341
|
-
if (rec.mode === 'ngrok') {
|
|
342
|
-
if (!rec.domain || !rec.ngrok_config) throw new Error(`exposure record ${file} is not a valid ngrok record`);
|
|
343
|
-
fs.rmSync(file);
|
|
344
|
-
log(`Removed the ngrok exposure record for ${rec.domain} (was -> http://127.0.0.1:${rec.local_port}). ngrok itself was NOT stopped by this script. To stop it and remove its service, run:`);
|
|
345
|
-
for (const line of ngrokStopCommands(rec.worker)) log(line);
|
|
346
|
-
log(`The ngrok config ${rec.ngrok_config} is left in place; delete it yourself if you do not need it.`);
|
|
347
|
-
return;
|
|
348
|
-
}
|
|
349
|
-
if (rec.mode !== 'tailscale' || !Number.isInteger(rec.public_port) || !rec.dns_name) throw new Error(`exposure record ${file} is not a tailscale record`);
|
|
350
|
-
const before = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
|
|
351
|
-
if (funnelRulePresent(before, rec.dns_name, rec.public_port)) {
|
|
352
|
-
if (!funnelRuleMatches(before, rec.dns_name, rec.public_port, rec.local_port)) {
|
|
353
|
-
throw Object.assign(new Error(`funnel rule ${rec.dns_name}:${rec.public_port} no longer matches this setup; refusing to change it. Inspect tailscale funnel status and remove the owned rule by hand if appropriate.`), { code: 'FUNNEL_RULE_MISMATCH' });
|
|
354
|
-
}
|
|
355
|
-
runOrThrow(tailscale, funnelOffArgs(rec.public_port), `funnel --https=${rec.public_port} off`);
|
|
356
|
-
const after = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
|
|
357
|
-
if (funnelRulePresent(after, rec.dns_name, rec.public_port)) throw new Error(`funnel rule ${rec.dns_name}:${rec.public_port} is still present after off`);
|
|
358
|
-
}
|
|
359
|
-
fs.rmSync(file);
|
|
360
|
-
log(`Removed Funnel rule ${rec.dns_name}:${rec.public_port} (was -> http://127.0.0.1:${rec.local_port}) and its record`);
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// Publish intent before changing Funnel so --remove can recover an interrupted mutation.
|
|
364
|
-
export function writeExposureRecord({ file, worker, dnsName, port, localPort, url, state = 'pending' }) {
|
|
365
|
-
writeRecord(file, { mode: 'tailscale', state, worker, dns_name: dnsName, public_url: url, public_port: port, local_port: localPort, created_at: new Date().toISOString() });
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
export function updateExposureState(file, state) {
|
|
369
|
-
const info = fs.lstatSync(file);
|
|
370
|
-
if (!info.isFile() || info.isSymbolicLink() || (typeof process.getuid === 'function' && info.uid !== process.getuid())) {
|
|
371
|
-
throw new Error('exposure record is not a regular file owned by the current user; refusing to update it');
|
|
372
|
-
}
|
|
373
|
-
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
374
|
-
const temporary = `${file}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
|
|
375
|
-
fs.writeFileSync(temporary, `${JSON.stringify({ ...value, state }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
376
|
-
fs.renameSync(temporary, file);
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// ngrok v3 agent config (https://ngrok.com/docs/agent/config/v3: version 3, endpoints[].name, url, upstream.url).
|
|
380
|
-
// The authtoken is deliberately absent: `ngrok config add-authtoken` keeps it in ngrok's own config.
|
|
381
|
-
export function ngrokConfigText({ worker, domain, localPort }) {
|
|
382
|
-
return `version: 3\n\nendpoints:\n - name: dot-bridge-${worker}\n url: ${domain}\n upstream:\n url: http://127.0.0.1:${localPort}\n`;
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
export function ngrokConfigPath(home, worker) {
|
|
386
|
-
return path.join(home, `ngrok-${worker}.yml`);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// Writes the config (0600, never overwritten) and the record (0600). The record is what signal-token and --remove read.
|
|
390
|
-
export function writeNgrokExposure({ home, worker, domain, localPort, file }) {
|
|
391
|
-
const configFile = ngrokConfigPath(home, worker);
|
|
392
|
-
try { fs.writeFileSync(configFile, ngrokConfigText({ worker, domain, localPort }), { mode: 0o600, flag: 'wx' }); }
|
|
393
|
-
catch (error) {
|
|
394
|
-
if (error.code === 'EEXIST') refuseOverwrite(`${configFile} already exists; refusing to overwrite the ngrok config`);
|
|
395
|
-
throw error;
|
|
396
|
-
}
|
|
397
|
-
fs.chmodSync(configFile, 0o600);
|
|
398
|
-
writeRecord(file, { mode: 'ngrok', state: 'unverified', worker, domain, public_url: `https://${domain}`, public_port: null, local_port: localPort, ngrok_config: configFile, created_at: new Date().toISOString() });
|
|
399
|
-
return configFile;
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
export function ngrokCommands(configFile) {
|
|
403
|
-
return [
|
|
404
|
-
'ngrok config add-authtoken <TOKEN> # placeholder: paste your token from the ngrok dashboard; this script never stores it',
|
|
405
|
-
`ngrok service install --config ${configFile}`,
|
|
406
|
-
'ngrok service start',
|
|
407
|
-
];
|
|
408
|
-
}
|