@remoteshell/device 0.0.0-stage → 0.1.0-beta.10
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/LICENSE +26 -0
- package/NOTICE +20 -0
- package/bin/dev-agent-client.mjs +228 -0
- package/bin/dev-agent-runner.mjs +60 -0
- package/bin/dev-api-client.mjs +31 -0
- package/bin/dev-auto-worker.mjs +25 -0
- package/bin/dev-browser-open.mjs +12 -0
- package/bin/dev-dogfood-read.mjs +3 -0
- package/bin/dev-heartbeat-service.mjs +77 -0
- package/bin/dev-pairing-client.mjs +63 -0
- package/bin/dev-secrets.mjs +33 -0
- package/bin/dev-setup-recovery.mjs +34 -0
- package/bin/dev-signer-pin.mjs +22 -0
- package/bin/device.mjs +384 -0
- package/bin/direct-npx-runtime.mjs +150 -0
- package/bin/enrollment-client.mjs +105 -0
- package/bin/install-acquire.mjs +89 -0
- package/bin/install-integrity.mjs +74 -0
- package/bin/install-plan.mjs +43 -0
- package/bin/lifecycle.mjs +172 -0
- package/bin/native-path-contract.mjs +23 -0
- package/bin/remoteshell-device-install.cmd +17 -0
- package/bin/remoteshell-device-install.ps1 +17 -0
- package/bin/remoteshell-device-install.sh +15 -0
- package/bin/remoteshell-device-preflight.cmd +10 -0
- package/bin/remoteshell-device-preflight.ps1 +10 -0
- package/bin/remoteshell-easy-diagnose.ps1 +32 -0
- package/bin/remoteshell-easy-install.ps1 +292 -0
- package/bin/remoteshell-easy-install.sh +71 -0
- package/bin/remoteshell-easy-uninstall.ps1 +128 -0
- package/bin/windows-acl-wmi-client.mjs +50 -0
- package/bin/windows-acl-wmi.js +43 -0
- package/bin/windows-credential-boundary.mjs +113 -0
- package/bin/windows-direct-autostart-runner.mjs +50 -0
- package/bin/windows-direct-autostart.mjs +110 -0
- package/bin/windows-install-layout.mjs +28 -0
- package/bin/windows-native-installer.mjs +91 -0
- package/bin/windows-private-store.mjs +176 -0
- package/bin/windows-user-lifecycle.mjs +34 -0
- package/npm-shrinkwrap.json +8591 -0
- package/package.json +27 -4
- package/shared/lib/bounded-search-contract.mjs +5 -0
- package/shared/lib/bounded-search-policy.mjs +24 -0
- package/shared/lib/config.mjs +14 -0
- package/shared/lib/contracts.mjs +26 -0
- package/shared/lib/dc-generic-policy.mjs +102 -0
- package/shared/lib/dc-relay-contract.mjs +42 -0
- package/shared/lib/dc-tool-catalog.mjs +67 -0
- package/shared/lib/dev-dc-relay-contract.mjs +20 -0
- package/shared/lib/dev-paged-output.mjs +32 -0
- package/shared/lib/dev-root-exclusions.mjs +56 -0
- package/shared/lib/errors.mjs +9 -0
- package/shared/lib/events.mjs +5 -0
- package/shared/lib/execution-policy.mjs +41 -0
- package/shared/lib/isolated-read-boundary.mjs +50 -0
- package/shared/lib/isolated-read-policy.mjs +29 -0
- package/shared/lib/lifecycle-events.mjs +13 -0
- package/shared/lib/runtime-timing.mjs +9 -0
- package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
- package/shared/lib/synthetic-write-policy.mjs +52 -0
- package/shared/lib/tool-registry.mjs +58 -0
- package/src/config/l2-dev-oci-credential.mjs +39 -0
- package/src/config/p2-private-credential.mjs +15 -0
- package/src/connection/dev-dogfood-processes.mjs +25 -0
- package/src/connection/dev-dogfood-read.mjs +64 -0
- package/src/connection/dev-dogfood-task.mjs +113 -0
- package/src/connection/dev-dogfood-write.mjs +62 -0
- package/src/connection/dev-file-task.mjs +119 -0
- package/src/connection/dev-r4-file-task.mjs +56 -0
- package/src/connection/dev-read-tools.mjs +134 -0
- package/src/connection/dev-root-scopes.mjs +82 -0
- package/src/core/c1-dc-transport.mjs +26 -0
- package/src/core/c1-startup.mjs +22 -0
- package/src/core/c1-supervisor.mjs +111 -0
- package/src/core/c1-worker.mjs +88 -0
- package/src/core/fixture.txt +2 -0
- package/src/dc/dc-access-readiness.mjs +31 -0
- package/src/dc/dev-dc-relay.mjs +47 -0
- package/src/device-agent/main.mjs +1 -0
- package/src/gateway-keepalive.mjs +73 -0
- package/src/main.mjs +436 -0
- package/src/policy/bounded-search-adapter.mjs +115 -0
- package/src/policy/isolated-read-adapter.mjs +50 -0
- package/src/policy/isolated-read-mount.mjs +27 -0
- package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
- package/src/policy/synthetic-file-adapter.mjs +26 -0
- package/src/policy/synthetic-file-transaction.mjs +87 -0
- package/src/policy/synthetic-write-adapter.mjs +151 -0
- package/src/policy/synthetic-write-mount.mjs +23 -0
- package/src/policy/verified-bounded-search.mjs +12 -0
- package/src/policy/verified-isolated-read.mjs +15 -0
- package/src/policy/verified-synthetic-write.mjs +14 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
RemoteShell Proprietary Software License (Beta)
|
|
2
|
+
Copyright (c) 2026 Individual owner of RemoteShell (GitHub: lkhkhk). All rights reserved.
|
|
3
|
+
|
|
4
|
+
RemoteShell is proprietary software. The source repository is not licensed
|
|
5
|
+
under an open-source license. Redistribution or publishing the source code
|
|
6
|
+
or a modified RemoteShell distribution requires separate written permission
|
|
7
|
+
from the applicable copyright holder.
|
|
8
|
+
|
|
9
|
+
Users may download, install, and execute unmodified official RemoteShell
|
|
10
|
+
device-agent distributions solely for connecting their own authorized devices
|
|
11
|
+
to the RemoteShell service, subject to applicable service terms. No right to
|
|
12
|
+
resell, sublicense, or distribute modified copies is granted by this notice.
|
|
13
|
+
|
|
14
|
+
This license applies only to original RemoteShell code. Open-source and other
|
|
15
|
+
third-party components included as dependencies remain subject to their own
|
|
16
|
+
licenses. Their copyright notices and license texts are not superseded by
|
|
17
|
+
this document. See NOTICE and the licenses accompanying installed dependencies.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
20
|
+
KIND, TO THE EXTENT PERMITTED BY APPLICABLE LAW. THIS NOTICE DOES NOT LIMIT
|
|
21
|
+
NON-WAIVABLE STATUTORY CONSUMER OR OTHER RIGHTS.
|
|
22
|
+
|
|
23
|
+
The RemoteShell project owner has declared that the original RemoteShell
|
|
24
|
+
code is personally owned and will remain proprietary. This assertion does
|
|
25
|
+
not establish ownership of independently contributed or third-party code;
|
|
26
|
+
their licenses and copyright notices remain applicable.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
RemoteShell device agent — Third-party software notices
|
|
2
|
+
|
|
3
|
+
The RemoteShell-owned portions are proprietary; see LICENSE.
|
|
4
|
+
Third-party dependencies keep their own licenses and notices. In particular:
|
|
5
|
+
|
|
6
|
+
* @wonderwhy-er/desktop-commander 0.3.1 — MIT License
|
|
7
|
+
Copyright (c) 2024-2025 Eduard Ruzga and Desktop Commander Contributors
|
|
8
|
+
License is shipped by the installed npm dependency.
|
|
9
|
+
* @modelcontextprotocol/sdk 1.32.1 — MIT License
|
|
10
|
+
Copyright (c) 2024 Anthropic, PBC
|
|
11
|
+
License is shipped by the installed npm dependency.
|
|
12
|
+
|
|
13
|
+
The exact dependency versions are fixed in npm-shrinkwrap.json. Transitive
|
|
14
|
+
packages have independent copyright holders and license conditions. This
|
|
15
|
+
summary is not a replacement for their full license files, which must remain
|
|
16
|
+
available with the installed dependencies. Check the complete dependency
|
|
17
|
+
license inventory and review unknown licenses before public release.
|
|
18
|
+
|
|
19
|
+
No license to the Desktop Commander trademark or to third-party code beyond
|
|
20
|
+
their respective third-party terms is granted by RemoteShell.
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// OCI DEV-only Agent consumer. No browser sessions or Control Plane authority.
|
|
2
|
+
import {createPrivateKey,createPublicKey,generateKeyPairSync,randomBytes,sign} from 'node:crypto';
|
|
3
|
+
import {existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync,renameSync,rmSync} from 'node:fs';
|
|
4
|
+
import {join,resolve,win32} from 'node:path';
|
|
5
|
+
import {homedir} from 'node:os';
|
|
6
|
+
import {inspectWindowsCredentialAcl} from './windows-credential-boundary.mjs';
|
|
7
|
+
import {ensureWindowsPrivateStore,readWindowsPrivate,atomicWindowsPrivate,readWindowsPrivateForUpdate} from './windows-private-store.mjs';
|
|
8
|
+
import {hostname as osHostname} from 'node:os';
|
|
9
|
+
import {readDevCapabilityFromStdin} from './dev-secrets.mjs';
|
|
10
|
+
const FAIL='DEVICE_DEV_AGENT_DENIED';
|
|
11
|
+
const deny=()=>{throw Error(FAIL);};
|
|
12
|
+
const idPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
|
+
const b64=buf=>Buffer.from(buf).toString('base64url');
|
|
14
|
+
const validHostname=x=>typeof x==='string'&&x.length>0&&x.length<=120&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(x);
|
|
15
|
+
const hostReports=new Map();
|
|
16
|
+
const HOST_RETRY_MS=60000;
|
|
17
|
+
export function detectDevHostname({hostnameImpl=osHostname}={}){
|
|
18
|
+
try{const name=hostnameImpl();return validHostname(name)?name:null;}catch{return null;}
|
|
19
|
+
}
|
|
20
|
+
function urlBase(input,{allowLocal=false}={}){
|
|
21
|
+
let u;
|
|
22
|
+
try{u=new URL(input);}catch{deny();}
|
|
23
|
+
if(!u||u.username||u.password||u.hash||u.search||u.pathname!=='/dev/'||
|
|
24
|
+
!(u.protocol==='https:'||(allowLocal&&u.protocol==='http:'&&['localhost','127.0.0.1'].includes(u.hostname))))deny();
|
|
25
|
+
return u;
|
|
26
|
+
}
|
|
27
|
+
function privateDir(path){
|
|
28
|
+
if(process.platform==='win32')return ensureWindowsPrivateStore(path);
|
|
29
|
+
if(typeof path!=='string'||!path.startsWith('/')||resolve(path)==='/')deny();
|
|
30
|
+
if(!existsSync(path))mkdirSync(path,{recursive:true,mode:0o700});
|
|
31
|
+
const s=lstatSync(path);
|
|
32
|
+
if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&0o777)!==0o700||s.uid!==process.getuid?.())deny();
|
|
33
|
+
}
|
|
34
|
+
function readPrivate(path){
|
|
35
|
+
if(process.platform==='win32')return readWindowsPrivate(path);
|
|
36
|
+
try{
|
|
37
|
+
const s=lstatSync(path);
|
|
38
|
+
if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o777)!==0o600||s.size>16384)deny();
|
|
39
|
+
return readFileSync(path,'utf8');
|
|
40
|
+
}catch{deny();}
|
|
41
|
+
}
|
|
42
|
+
function atomic(path,value,{replace=false}={}){
|
|
43
|
+
if(process.platform==='win32')return atomicWindowsPrivate(path,value,{replace});
|
|
44
|
+
if(!replace&&existsSync(path))deny();
|
|
45
|
+
const temp=path+'.tmp-'+b64(randomBytes(12));
|
|
46
|
+
try{
|
|
47
|
+
writeFileSync(temp,value,{mode:0o600,flag:'wx'});
|
|
48
|
+
if(!replace&&existsSync(path))deny();
|
|
49
|
+
renameSync(temp,path);
|
|
50
|
+
}finally{rmSync(temp,{force:true});}
|
|
51
|
+
}
|
|
52
|
+
async function request({base,path,body,bearer,fetchImpl=fetch,timeoutMs=10000,allowLocal=false}){
|
|
53
|
+
const u=urlBase(base,{allowLocal});
|
|
54
|
+
if(!['api/agent/enrollments/challenge','api/agent/enrollments/exchange','api/agent/heartbeat','api/agent/hostname'].includes(path))deny();
|
|
55
|
+
let res;
|
|
56
|
+
try{
|
|
57
|
+
res=await fetchImpl(new URL(path,u).href,{
|
|
58
|
+
method:'POST',redirect:'manual',signal:AbortSignal.timeout(timeoutMs),
|
|
59
|
+
headers:{'content-type':'application/json',accept:'application/json',...(bearer?{authorization:'Bearer '+bearer}:{})},
|
|
60
|
+
body:JSON.stringify(body)
|
|
61
|
+
});
|
|
62
|
+
if(['api/agent/heartbeat','api/agent/hostname'].includes(path)&&[401,403].includes(res.status))
|
|
63
|
+
throw Error('DEVICE_DEV_CREDENTIAL_REVOKED');
|
|
64
|
+
if(res.status!==200||!String(res.headers.get('content-type')||'').includes('application/json'))deny();
|
|
65
|
+
const raw=await res.text();
|
|
66
|
+
if(raw.length>16384)deny();
|
|
67
|
+
return JSON.parse(raw);
|
|
68
|
+
}catch(e){if(e?.message==='DEVICE_DEV_CREDENTIAL_REVOKED')throw e;deny();}
|
|
69
|
+
}
|
|
70
|
+
function loadKey(store){
|
|
71
|
+
privateDir(store);
|
|
72
|
+
const file=join(store,'device-key.pem');
|
|
73
|
+
if(!existsSync(file)){
|
|
74
|
+
const pair=generateKeyPairSync('ed25519');
|
|
75
|
+
atomic(file,pair.privateKey.export({type:'pkcs8',format:'pem'}));
|
|
76
|
+
}
|
|
77
|
+
const key=createPrivateKey(readPrivate(file));
|
|
78
|
+
if(key.asymmetricKeyType!=='ed25519')deny();
|
|
79
|
+
return key;
|
|
80
|
+
}
|
|
81
|
+
function checkResponse(res){
|
|
82
|
+
if(!res||!idPattern.test(res.device_id||'')||
|
|
83
|
+
typeof res.device_credential!=='string'||res.device_credential.length<24||res.device_credential.length>2048||
|
|
84
|
+
res.connection_state!=='offline'||!Number.isSafeInteger(res.heartbeat_ttl_ms)||
|
|
85
|
+
res.heartbeat_ttl_ms<1000||res.heartbeat_ttl_ms>300000)deny();
|
|
86
|
+
}
|
|
87
|
+
export async function devEnroll({base,enrollmentId,storageDir,capability,fetchImpl=fetch,allowLocal=false,replaceRevoked=false,previousDeviceId}={}){
|
|
88
|
+
if(!idPattern.test(enrollmentId||'')||typeof capability!=='string'||capability.length<24||
|
|
89
|
+
capability.length>2048||!/^[A-Za-z0-9._~-]+$/.test(capability))deny();
|
|
90
|
+
privateDir(storageDir);
|
|
91
|
+
if(replaceRevoked){
|
|
92
|
+
const previous=readState(storageDir,{allowLocal});
|
|
93
|
+
if(previous.state.device_id!==previousDeviceId)deny();
|
|
94
|
+
}else if(existsSync(join(storageDir,'device.json')))deny();
|
|
95
|
+
const challenge=await request({base,path:'api/agent/enrollments/challenge',
|
|
96
|
+
body:{enrollment_id:enrollmentId,capability},fetchImpl,allowLocal});
|
|
97
|
+
if(challenge?.proof_version!=='dev-ed25519-v1'||typeof challenge.challenge!=='string'||
|
|
98
|
+
challenge.challenge.length<24||challenge.challenge.length>4096||
|
|
99
|
+
typeof challenge.nonce!=='string'||challenge.nonce.length<16||
|
|
100
|
+
!Number.isSafeInteger(challenge.expires_at)||challenge.expires_at<=Date.now())deny();
|
|
101
|
+
const privateKey=loadKey(storageDir);
|
|
102
|
+
const payload={
|
|
103
|
+
enrollment_id:enrollmentId,consumer:'remoteshell-device.v0.1',
|
|
104
|
+
proof_version:'dev-ed25519-v1',challenge:challenge.challenge,
|
|
105
|
+
public_key:createPublicKey(privateKey).export({type:'spki',format:'pem'})
|
|
106
|
+
};
|
|
107
|
+
const signature=b64(sign(null,Buffer.from(JSON.stringify(payload)),privateKey));
|
|
108
|
+
const response=await request({base,path:'api/agent/enrollments/exchange',
|
|
109
|
+
body:{enrollment_id:enrollmentId,capability,proof:{payload,signature}},fetchImpl,allowLocal});
|
|
110
|
+
checkResponse(response);
|
|
111
|
+
if(replaceRevoked&&response.device_id===previousDeviceId)deny();
|
|
112
|
+
// The old credential remains intact until the new owner-approved exchange succeeds.
|
|
113
|
+
if(replaceRevoked&&readState(storageDir,{allowLocal}).state.device_id!==previousDeviceId)deny();
|
|
114
|
+
atomic(join(storageDir,'device.json'),JSON.stringify({
|
|
115
|
+
version:1,base:urlBase(base,{allowLocal}).href,device_id:response.device_id,
|
|
116
|
+
device_credential:response.device_credential,sequence:0
|
|
117
|
+
})+'\n',{replace:replaceRevoked});
|
|
118
|
+
return {registered:true,connected:false,device_id:response.device_id,
|
|
119
|
+
heartbeat_ttl_ms:response.heartbeat_ttl_ms,credentialReturned:false,provider:'oci-dev-agent'};
|
|
120
|
+
}
|
|
121
|
+
function readState(store,{allowLocal=false,os=process.platform,home=homedir(),
|
|
122
|
+
inspectWindows=inspectWindowsCredentialAcl,read=readFileSync}={}){
|
|
123
|
+
let state,path,commit;
|
|
124
|
+
try{
|
|
125
|
+
if(os==='win32'){
|
|
126
|
+
path=win32.join(store,'device.json');
|
|
127
|
+
if(inspectWindows===inspectWindowsCredentialAcl&&read===readFileSync){
|
|
128
|
+
// Bind a single-use update to this independently verified native ACL
|
|
129
|
+
// read. This removes redundant Windows PowerShell startups.
|
|
130
|
+
const verified=readWindowsPrivateForUpdate(path,{home});
|
|
131
|
+
state=JSON.parse(verified.content);
|
|
132
|
+
commit=verified.replace;
|
|
133
|
+
}else{
|
|
134
|
+
if(inspectWindows({file:path,home,os})?.restrictedAcl!==true)deny();
|
|
135
|
+
state=JSON.parse(read(path,'utf8'));
|
|
136
|
+
}
|
|
137
|
+
}else{
|
|
138
|
+
privateDir(store);
|
|
139
|
+
path=join(store,'device.json');
|
|
140
|
+
state=JSON.parse(readPrivate(path));
|
|
141
|
+
}
|
|
142
|
+
}catch{deny();}
|
|
143
|
+
if(state?.version!==1||!idPattern.test(state.device_id||'')||
|
|
144
|
+
typeof state.device_credential!=='string'||state.device_credential.length<24||
|
|
145
|
+
!Number.isSafeInteger(state.sequence)||state.sequence<0)deny();
|
|
146
|
+
urlBase(state.base,{allowLocal});
|
|
147
|
+
return {path,state,commit};
|
|
148
|
+
}
|
|
149
|
+
async function sendVerifiedHostname({storageDir,state,fetchImpl,allowLocal,hostnameImpl,now}){
|
|
150
|
+
// Use the same verified credential state as the heartbeat for display-only
|
|
151
|
+
// hostname reporting; no extra Windows ACL subprocess is needed.
|
|
152
|
+
const name=detectDevHostname({hostnameImpl});
|
|
153
|
+
if(!name)return {hostnameSent:false,reason:'INVALID_OS_HOSTNAME'};
|
|
154
|
+
const key=resolve(storageDir);
|
|
155
|
+
const old=hostReports.get(key);
|
|
156
|
+
if(old?.deviceId===state.device_id&&old?.hostname===name&&
|
|
157
|
+
(old.success||now()-old.at<HOST_RETRY_MS))
|
|
158
|
+
return {hostnameSent:false,reason:old.success?'UNCHANGED':'RETRY_BACKOFF'};
|
|
159
|
+
// Throttle even when the endpoint is unreachable; keep credential and heartbeat intact.
|
|
160
|
+
hostReports.set(key,{deviceId:state.device_id,hostname:name,at:now(),success:false});
|
|
161
|
+
try{
|
|
162
|
+
const result=await request({base:state.base,path:'api/agent/hostname',
|
|
163
|
+
bearer:state.device_credential,body:{device_id:state.device_id,hostname:name},
|
|
164
|
+
fetchImpl,allowLocal,timeoutMs:2500});
|
|
165
|
+
if(result?.device_id!==state.device_id||result?.hostname!==name)throw Error('INVALID_HOSTNAME_RESPONSE');
|
|
166
|
+
hostReports.set(key,{deviceId:state.device_id,hostname:name,at:now(),success:true});
|
|
167
|
+
return {hostnameSent:true,hostname:name};
|
|
168
|
+
}catch(e){
|
|
169
|
+
return {hostnameSent:false,reason:e?.message==='DEVICE_DEV_CREDENTIAL_REVOKED'?'CREDENTIAL_DENIED':'DELIVERY_FAILED'};
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
export async function devHostnameOnce({storageDir,fetchImpl=fetch,allowLocal=false,hostnameImpl=osHostname,now=Date.now}={}){
|
|
173
|
+
const {state}=readState(storageDir,{allowLocal});
|
|
174
|
+
return sendVerifiedHostname({storageDir,state,fetchImpl,allowLocal,hostnameImpl,now});
|
|
175
|
+
}
|
|
176
|
+
export async function devHeartbeatOnce({storageDir,fetchImpl=fetch,allowLocal=false,hostnameImpl=osHostname,now=Date.now}={}){
|
|
177
|
+
const {path,state,commit}=readState(storageDir,{allowLocal});
|
|
178
|
+
const nonce=b64(randomBytes(24));
|
|
179
|
+
// Reserve the next monotonic heartbeat sequence durably BEFORE sending.
|
|
180
|
+
// The CP may accept this request even when the reply is lost or the Agent
|
|
181
|
+
// terminates. Persisting only after success would replay an accepted
|
|
182
|
+
// sequence forever on restart (HEARTBEAT_REPLAY).
|
|
183
|
+
if(!Number.isSafeInteger(state.sequence+1))deny();
|
|
184
|
+
// Both platforms reserve the next sequence using a verified private,
|
|
185
|
+
// atomic replacement before sending the heartbeat.
|
|
186
|
+
const next=JSON.stringify({...state,sequence:state.sequence+1})+'\n';
|
|
187
|
+
if(commit)commit(next);else atomic(path,next,{replace:true});
|
|
188
|
+
const result=await request({base:state.base,path:'api/agent/heartbeat',
|
|
189
|
+
bearer:state.device_credential,body:{device_id:state.device_id,sequence:state.sequence,session_nonce:nonce},
|
|
190
|
+
fetchImpl,allowLocal});
|
|
191
|
+
if(result?.connection_state!=='connected')deny();
|
|
192
|
+
// Hostname is display metadata; it must never make a valid heartbeat fail.
|
|
193
|
+
await sendVerifiedHostname({storageDir,state,fetchImpl,allowLocal,hostnameImpl,now});
|
|
194
|
+
return {connected:true,device_id:state.device_id,provider:'oci-dev-agent'};
|
|
195
|
+
}
|
|
196
|
+
export async function devHeartbeatForeground({storageDir,fetchImpl=fetch,allowLocal=false,intervalMs=15000,signal}={}){
|
|
197
|
+
if(!Number.isInteger(intervalMs)||intervalMs<1000||intervalMs>30000)deny();
|
|
198
|
+
let count=0;
|
|
199
|
+
while(!signal?.aborted){
|
|
200
|
+
await devHeartbeatOnce({storageDir,fetchImpl,allowLocal});
|
|
201
|
+
count++;
|
|
202
|
+
await new Promise(done=>{
|
|
203
|
+
if(signal?.aborted){done();return;}
|
|
204
|
+
const timer=setTimeout(finish,intervalMs);
|
|
205
|
+
function finish(){clearTimeout(timer);signal?.removeEventListener('abort',finish);done();}
|
|
206
|
+
signal?.addEventListener('abort',finish,{once:true});
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
return {stopped:true,heartbeatCount:count};
|
|
210
|
+
}
|
|
211
|
+
export {readDevCapabilityFromStdin};
|
|
212
|
+
|
|
213
|
+
export function devLocalStatus({storageDir,allowLocal=false}={}){
|
|
214
|
+
if(!storageDir||!existsSync(join(storageDir,'device.json')))
|
|
215
|
+
return {devRegistered:false,devConnectionState:'unknown'};
|
|
216
|
+
const {state}=readState(storageDir,{allowLocal});
|
|
217
|
+
return {devRegistered:true,devDeviceId:state.device_id,devConnectionState:'unverified'};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// This method intentionally returns public owner-pairing metadata only.
|
|
221
|
+
export function devOfficialRegistration({storageDir,os=process.platform,home=homedir(),
|
|
222
|
+
inspectWindows=inspectWindowsCredentialAcl,read=readFileSync,exists=existsSync}={}){
|
|
223
|
+
const file=os==='win32'?win32.join(storageDir||'','device.json'):join(storageDir||'','device.json');
|
|
224
|
+
if(!storageDir||!exists(file))return null;
|
|
225
|
+
const {state}=readState(storageDir,{os,home,inspectWindows,read});
|
|
226
|
+
return state.base==='https://ailab-remoteshell.duckdns.org/dev/'?
|
|
227
|
+
Object.freeze({deviceId:state.device_id}):null;
|
|
228
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Foreground runner for the existing, owner-paired DEV Agent credential.
|
|
2
|
+
// rootId/path configure the local mapping only; every dispatched task still
|
|
3
|
+
// needs the Gateway's fresh CP authorization.
|
|
4
|
+
import {lstatSync,realpathSync} from 'node:fs';
|
|
5
|
+
import {dirname,resolve,win32} from 'node:path';
|
|
6
|
+
import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
|
|
7
|
+
import {inspectWindowsCredentialAcl} from './windows-credential-boundary.mjs';
|
|
8
|
+
import {spawn} from 'node:child_process';
|
|
9
|
+
const DENY=()=>{throw Error('DEVICE_DEV_AGENT_RUN_DENIED');};
|
|
10
|
+
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
11
|
+
export function devAgentWorkerEnv({gatewayUrl,credentialFile,rootId,rootPath,mainFile,home},baseEnv=process.env,{
|
|
12
|
+
os=process.platform,lstat=lstatSync,realpath=realpathSync,inspectWindows=inspectWindowsCredentialAcl
|
|
13
|
+
}={}){
|
|
14
|
+
let gateway;try{gateway=new URL(gatewayUrl);}catch{DENY();}
|
|
15
|
+
const loopback=['127.0.0.1','localhost','[::1]'].includes(gateway?.hostname);
|
|
16
|
+
const publicDevGateway=gateway?.protocol==='https:'&&gateway?.hostname==='ailab-remoteshell.duckdns.org'&&
|
|
17
|
+
gateway?.pathname==='/gateway/v1/';
|
|
18
|
+
if(!gateway||gateway.username||gateway.password||gateway.search||gateway.hash||
|
|
19
|
+
(gateway.pathname!=='/'&&!publicDevGateway)||
|
|
20
|
+
!(gateway.protocol==='https:'||gateway.protocol==='http:'&&loopback)||
|
|
21
|
+
!UUID.test(rootId||''))DENY();
|
|
22
|
+
if(os==='win32'){
|
|
23
|
+
try{
|
|
24
|
+
for(const p of [home,rootPath,credentialFile,mainFile])canonicalWindowsLocalFile(p);
|
|
25
|
+
if(rootPath.toLowerCase()!==home.toLowerCase())DENY();
|
|
26
|
+
isWindowsChildPath(credentialFile,home);
|
|
27
|
+
isWindowsChildPath(mainFile,home);
|
|
28
|
+
const root=lstat(rootPath),entry=lstat(mainFile);
|
|
29
|
+
if(!root.isDirectory()||root.isSymbolicLink()||
|
|
30
|
+
!entry.isFile()||entry.isSymbolicLink()||
|
|
31
|
+
win32.normalize(realpath(rootPath)).toLowerCase()!==rootPath.toLowerCase()||
|
|
32
|
+
win32.normalize(realpath(mainFile)).toLowerCase()!==mainFile.toLowerCase()||
|
|
33
|
+
inspectWindows({file:credentialFile,home,os})?.restrictedAcl!==true)DENY();
|
|
34
|
+
}catch{DENY();}
|
|
35
|
+
}else if(os==='linux'||os==='darwin'){
|
|
36
|
+
if(typeof rootPath!=='string'||!rootPath.startsWith('/')||resolve(rootPath)!==rootPath||
|
|
37
|
+
typeof credentialFile!=='string'||!credentialFile.startsWith('/')||resolve(credentialFile)!==credentialFile||
|
|
38
|
+
typeof mainFile!=='string'||!mainFile.startsWith('/')||resolve(mainFile)!==mainFile||
|
|
39
|
+
typeof home!=='string'||!home.startsWith('/')||resolve(home)!==home)DENY();
|
|
40
|
+
try{
|
|
41
|
+
const root=lstat(rootPath),cred=lstat(credentialFile),parent=lstat(dirname(credentialFile)),entry=lstat(mainFile);
|
|
42
|
+
if(root.isSymbolicLink()||!root.isDirectory()||root.uid!==process.getuid?.()||realpath(rootPath)!==rootPath||
|
|
43
|
+
cred.isSymbolicLink()||!cred.isFile()||cred.uid!==process.getuid?.()||(cred.mode&0o777)!==0o600||
|
|
44
|
+
parent.isSymbolicLink()||!parent.isDirectory()||parent.uid!==process.getuid?.()||(parent.mode&0o777)!==0o700||
|
|
45
|
+
entry.isSymbolicLink()||!entry.isFile())DENY();
|
|
46
|
+
}catch{DENY();}
|
|
47
|
+
}else DENY();
|
|
48
|
+
return Object.freeze({PATH:baseEnv.PATH||baseEnv.Path||(os==='win32'?'':'/usr/bin:/bin'),HOME:home,
|
|
49
|
+
...(os==='win32'?{SystemRoot:baseEnv.SystemRoot||'C:\\Windows'}:{}),RS_P2_MODE:'true',
|
|
50
|
+
RS_55A_TEST_MODE:'true',RS_55A_ROOT:'.',RS_55B_TEST_MODE:'false',RS_55C1_TEST_MODE:'false',
|
|
51
|
+
RS_L2_DEV_AGENT:'true',RS_L2_DEV_CREDENTIAL_FILE:credentialFile,RS_GATEWAY_URL:gateway.href,
|
|
52
|
+
...(gateway.protocol==='https:'?{RS_ENABLE_REMOTE:'true'}:{}),
|
|
53
|
+
RS_L2_D1_ROOT_ID:rootId,RS_L2_D1_ROOT:rootPath});
|
|
54
|
+
}
|
|
55
|
+
export function runDevAgentWorker(options,{spawnImpl=spawn,baseEnv=process.env,nodeBin=process.execPath}={}){
|
|
56
|
+
const env=devAgentWorkerEnv(options,baseEnv),child=spawnImpl(nodeBin,[options.mainFile],{
|
|
57
|
+
cwd:dirname(options.mainFile),env,stdio:'inherit',shell:false,
|
|
58
|
+
});
|
|
59
|
+
return child;
|
|
60
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// DEV-only public reachability check. No browser cookie, CP credential, or owner ID accepted.
|
|
2
|
+
const DENY='DEVICE_DEV_PROBE_DENIED';
|
|
3
|
+
function target(input){
|
|
4
|
+
let u;
|
|
5
|
+
try{u=new URL(input);}catch{throw Error(DENY);}
|
|
6
|
+
const local=u.hostname==='127.0.0.1'||u.hostname==='localhost';
|
|
7
|
+
if((u.protocol!=='https:'&&!(local&&u.protocol==='http:'))||
|
|
8
|
+
u.username||u.password||u.search||u.hash||u.pathname!=='/dev/')throw Error(DENY);
|
|
9
|
+
return u;
|
|
10
|
+
}
|
|
11
|
+
export async function probeDev({url,fetchImpl=fetch,timeoutMs=8000}={}){
|
|
12
|
+
const base=target(url);
|
|
13
|
+
if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>10000)throw Error(DENY);
|
|
14
|
+
try{
|
|
15
|
+
const opts={method:'GET',redirect:'manual',signal:AbortSignal.timeout(timeoutMs),
|
|
16
|
+
headers:{accept:'text/html','cache-control':'no-store'}};
|
|
17
|
+
const page=await fetchImpl(base.href,opts);
|
|
18
|
+
// GET /dev/ is public; avoid following redirects to login/other hosts.
|
|
19
|
+
// Current DEV entrance redirects only to the fixed, same-origin account page.
|
|
20
|
+
// Inspect Location without following redirects or forwarding credentials.
|
|
21
|
+
const account=new URL('account',base);
|
|
22
|
+
const location=page.headers.get('location');
|
|
23
|
+
const accountRedirect=page.status===302&&location===account.pathname;
|
|
24
|
+
const htmlPage=page.status===200&&String(page.headers.get('content-type')||'').includes('text/html');
|
|
25
|
+
if(!htmlPage&&!accountRedirect)throw Error(DENY);
|
|
26
|
+
const me=await fetchImpl(new URL('me',base).href,{...opts,headers:{accept:'application/json','cache-control':'no-store'}});
|
|
27
|
+
if(![401,403].includes(me.status))throw Error(DENY);
|
|
28
|
+
return Object.freeze({devReachable:true,sessionAuthenticated:false,registered:false,
|
|
29
|
+
connected:false,agentEnrollmentReady:false,provider:'oci-dev-web',next:'agent-api-not-ready'});
|
|
30
|
+
}catch{throw Error(DENY);}
|
|
31
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// #289: one owner-paired Agent session owns both CP heartbeat and original DC worker.
|
|
2
|
+
// Never mint a new device credential or grant a CP Root. The DC/OS retain access decisions.
|
|
3
|
+
import {join} from 'node:path';
|
|
4
|
+
import {devOfficialRegistration} from './dev-agent-client.mjs';
|
|
5
|
+
import {runDevAgentWorker} from './dev-agent-runner.mjs';
|
|
6
|
+
export const OFFICIAL_DEV_GATEWAY='https://ailab-remoteshell.duckdns.org/gateway/v1/';
|
|
7
|
+
export function officialWorkerOptions({home,install,storageDir}={}){
|
|
8
|
+
const registration=devOfficialRegistration({storageDir});
|
|
9
|
+
if(!registration)return null;
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
gatewayUrl:OFFICIAL_DEV_GATEWAY,credentialFile:join(storageDir,'device.json'),
|
|
12
|
+
rootId:registration.deviceId,rootPath:home,home,
|
|
13
|
+
mainFile:join(install,'node_modules/@remoteshell/device/src/device-agent/main.mjs')
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export function startOfficialWorker(options,{runWorker=runDevAgentWorker}={}){
|
|
17
|
+
const config=officialWorkerOptions(options);
|
|
18
|
+
if(!config)return null;
|
|
19
|
+
const child=runWorker(config);
|
|
20
|
+
child.once('error',()=>{process.exitCode=1;});
|
|
21
|
+
child.once('exit',(code,signal)=>{process.exitCode=signal?1:(code??1);});
|
|
22
|
+
process.once('SIGINT',()=>child.kill('SIGINT'));
|
|
23
|
+
process.once('SIGTERM',()=>child.kill('SIGTERM'));
|
|
24
|
+
return child;
|
|
25
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Open same-origin approval URL in desktop browser. Never pass secrets or shell.
|
|
2
|
+
import {spawn} from 'node:child_process';
|
|
3
|
+
export function openDevApproval(url,{base,spawnImpl=spawn}={}){
|
|
4
|
+
let target,origin;
|
|
5
|
+
try{target=new URL(url);origin=new URL(base);}catch{return false;}
|
|
6
|
+
if(target.protocol!==origin.protocol||target.origin!==origin.origin||
|
|
7
|
+
!target.pathname.startsWith('/dev/')||target.username||target.password||
|
|
8
|
+
target.search||target.hash||origin.pathname!=='/dev/')return false;
|
|
9
|
+
// No shell, detached: the device setup continues polling for browser consent.
|
|
10
|
+
try{const child=spawnImpl('xdg-open',[target.href],{detached:true,stdio:'ignore',shell:false});
|
|
11
|
+
child.on?.('error',()=>{});child.unref?.();return true;}catch{return false;}
|
|
12
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Separate permanent device registration from local heartbeat process and autostart.
|
|
2
|
+
// User-only systemd; no implicit enable/linger/sudo or CP authorization changes.
|
|
3
|
+
import {existsSync,lstatSync,mkdirSync,writeFileSync,rmSync} from 'node:fs';
|
|
4
|
+
import {homedir,userInfo} from 'node:os';
|
|
5
|
+
import {join,resolve} from 'node:path';
|
|
6
|
+
import {spawnSync} from 'node:child_process';
|
|
7
|
+
const UNIT='remoteshell-device-dev-heartbeat.service';
|
|
8
|
+
const FAIL=()=>{throw Error('DEVICE_DEV_SERVICE_DENIED');};
|
|
9
|
+
const MODES=new Set(['foreground','manual','login','boot']);
|
|
10
|
+
function secure(path,kind,mode=null){
|
|
11
|
+
const s=lstatSync(path);
|
|
12
|
+
if(s.isSymbolicLink()||s.uid!==process.getuid?.()||(kind==='file'?!s.isFile():!s.isDirectory())||
|
|
13
|
+
(mode!==null&&(s.mode&0o777)!==mode))FAIL();
|
|
14
|
+
}
|
|
15
|
+
function shellless(run,program,args){const r=run(program,args,{encoding:'utf8',timeout:6000,maxBuffer:4096,stdio:'pipe'});
|
|
16
|
+
if(r.error||r.signal||r.status!==0)FAIL();return String(r.stdout||'');}
|
|
17
|
+
function call(run,...args){return shellless(run,'systemctl',['--user',...args]);}
|
|
18
|
+
function status(run,command){const r=run('systemctl',['--user',command,UNIT],{encoding:'utf8',timeout:4000,maxBuffer:4096,stdio:'pipe'});
|
|
19
|
+
if(r.error||r.signal)FAIL();return r.status===0;}
|
|
20
|
+
function target(home){if(typeof home!=='string'||!home.startsWith('/')||resolve(home)==='/')FAIL();secure(home,'directory');return join(home,'.config/systemd/user',UNIT);}
|
|
21
|
+
function requireDevice(home){
|
|
22
|
+
const base=join(home,'.local/share/remoteshell-device');secure(base,'directory',0o700);
|
|
23
|
+
const install=join(base,'install');secure(install,'directory',0o700);
|
|
24
|
+
const script=join(install,'node_modules/@remoteshell/device/bin/device.mjs');secure(script,'file');
|
|
25
|
+
const cred=join(base,'dev-credentials');secure(cred,'directory',0o700);secure(join(cred,'device.json'),'file',0o600);
|
|
26
|
+
return {install,script};
|
|
27
|
+
}
|
|
28
|
+
function ensureUnitDirs(home){let p=home;for(const seg of ['.config','systemd','user']){p=join(p,seg);if(!existsSync(p))mkdirSync(p,{mode:0o700});secure(p,'directory');}}
|
|
29
|
+
function unitFile(script,install,nodeBin){for(const v of [script,install,nodeBin])if(!/^\/[A-Za-z0-9._/@+-]+$/.test(v))FAIL();
|
|
30
|
+
return ['[Unit]','Description=RemoteShell DEV Agent heartbeat (user)','After=network-online.target','Wants=network-online.target','','[Service]','Type=simple','ExecStart='+nodeBin+' '+script+' dev-heartbeat','WorkingDirectory='+install,'Restart=on-failure','RestartSec=5','UMask=0077','NoNewPrivileges=yes','PrivateTmp=yes','','[Install]','WantedBy=default.target',''].join('\n');}
|
|
31
|
+
function userLinger(run,username){const v=shellless(run,'loginctl',['show-user',username,'--property=Linger','--value']).trim();if(!['yes','no'].includes(v))FAIL();return v==='yes';}
|
|
32
|
+
export function configureDevHeartbeatService({home=homedir(),nodeBin=process.execPath,mode='manual',confirmLinger=false,run=spawnSync,username=userInfo().username}={}){
|
|
33
|
+
if(!MODES.has(mode)||typeof nodeBin!=='string'||!nodeBin.startsWith('/')||typeof username!=='string'||!/^[a-z_][a-z0-9_-]*$/.test(username))FAIL();
|
|
34
|
+
const file=target(home);
|
|
35
|
+
if(mode==='foreground')return Object.freeze({mode:'foreground',unitInstalled:existsSync(file),started:false,enabled:false,registeredPreserved:true});
|
|
36
|
+
const {install,script}=requireDevice(home);ensureUnitDirs(home);
|
|
37
|
+
const wasPresent=existsSync(file);
|
|
38
|
+
if(wasPresent)secure(file,'file',0o600);
|
|
39
|
+
else writeFileSync(file,unitFile(script,install,nodeBin),{flag:'wx',mode:0o600});
|
|
40
|
+
try{
|
|
41
|
+
call(run,'daemon-reload');
|
|
42
|
+
if(mode==='boot'){
|
|
43
|
+
if(!confirmLinger)FAIL();
|
|
44
|
+
if(!userLinger(run,username)){
|
|
45
|
+
shellless(run,'loginctl',['enable-linger',username]);
|
|
46
|
+
if(!userLinger(run,username))FAIL();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if(mode==='manual'){call(run,'disable',UNIT);call(run,'start',UNIT);}
|
|
50
|
+
else call(run,'enable','--now',UNIT);
|
|
51
|
+
return Object.freeze({mode,unitInstalled:true,started:true,enabled:mode!=='manual',
|
|
52
|
+
bootAfterLogout:mode==='boot',connected:false,registeredPreserved:true});
|
|
53
|
+
}catch{
|
|
54
|
+
// Fail without tampering with another pre-existing unit. A fresh unit only
|
|
55
|
+
// is stopped and removed; credential is always preserved.
|
|
56
|
+
if(!wasPresent){try{call(run,'disable','--now',UNIT);}catch{}rmSync(file,{force:true});try{call(run,'daemon-reload');}catch{}}
|
|
57
|
+
FAIL();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// Backward-compatible opt-in helper: never enable by default.
|
|
61
|
+
export function installDevHeartbeatService(options={}){return configureDevHeartbeatService({...options,mode:options.mode??'manual'});}
|
|
62
|
+
export function controlDevHeartbeatService({home=homedir(),action,run=spawnSync}={}){
|
|
63
|
+
const file=target(home);
|
|
64
|
+
if(!['start','stop','status','autostart-enable','autostart-disable'].includes(action))FAIL();
|
|
65
|
+
if(!existsSync(file)){if(action==='status')return Object.freeze({unitInstalled:false,running:false,autostartEnabled:false,registeredPreserved:true});FAIL();}
|
|
66
|
+
secure(file,'file',0o600);
|
|
67
|
+
if(action==='status')return Object.freeze({unitInstalled:true,running:status(run,'is-active'),autostartEnabled:status(run,'is-enabled'),registeredPreserved:true});
|
|
68
|
+
if(action==='start'){requireDevice(home);call(run,'start',UNIT);return Object.freeze({running:true,registeredPreserved:true});}
|
|
69
|
+
if(action==='stop'){call(run,'stop',UNIT);return Object.freeze({running:false,registeredPreserved:true});}
|
|
70
|
+
if(action==='autostart-enable'){requireDevice(home);call(run,'enable',UNIT);return Object.freeze({autostartEnabled:true,runningUnchanged:true});}
|
|
71
|
+
call(run,'disable',UNIT);return Object.freeze({autostartEnabled:false,runningUnchanged:true});
|
|
72
|
+
}
|
|
73
|
+
export function uninstallDevHeartbeatService({home=homedir(),run=spawnSync}={}){
|
|
74
|
+
const file=target(home);if(!existsSync(file))return Object.freeze({unitRemoved:false});secure(file,'file',0o600);
|
|
75
|
+
call(run,'disable','--now',UNIT);if(status(run,'is-active'))FAIL();
|
|
76
|
+
rmSync(file);call(run,'daemon-reload');return Object.freeze({unitRemoved:true,credentialPreserved:true});
|
|
77
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// DEV pairing client: device starts, browser owner approves, Agent enrolls.
|
|
2
|
+
// Provider proposal only until OCI BFF implements the signed pairing endpoints.
|
|
3
|
+
// Never prints or accepts a capability or enrollment_id from the user.
|
|
4
|
+
import {randomBytes,createHash} from 'node:crypto';
|
|
5
|
+
import {devEnroll,devHeartbeatOnce} from './dev-agent-client.mjs';
|
|
6
|
+
const DENY=()=>{throw Error('DEVICE_PAIRING_DENIED');};
|
|
7
|
+
const uuid=x=>typeof x==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(x);
|
|
8
|
+
const validToken=x=>typeof x==='string'&&/^[A-Za-z0-9._~-]{24,2048}$/.test(x);
|
|
9
|
+
function origin(input){let u;try{u=new URL(input);}catch{DENY();}
|
|
10
|
+
if(u.username||u.password||u.search||u.hash||u.pathname!=='/dev/'||
|
|
11
|
+
!(u.protocol==='https:'||(u.protocol==='http:'&&['127.0.0.1','localhost'].includes(u.hostname))))DENY();
|
|
12
|
+
return u;
|
|
13
|
+
}
|
|
14
|
+
async function request(u,route,body,{fetchImpl,timeoutMs}){
|
|
15
|
+
try{
|
|
16
|
+
const response=await fetchImpl(new URL(route,u),{method:'POST',redirect:'manual',
|
|
17
|
+
headers:{'content-type':'application/json',accept:'application/json'},
|
|
18
|
+
body:JSON.stringify(body),signal:AbortSignal.timeout(timeoutMs)});
|
|
19
|
+
if(response.status!==200||!String(response.headers.get('content-type')||'').includes('application/json'))DENY();
|
|
20
|
+
const raw=await response.text();if(raw.length>4096)DENY();
|
|
21
|
+
const obj=JSON.parse(raw);if(!obj||typeof obj!=='object'||Array.isArray(obj))DENY();
|
|
22
|
+
return obj;
|
|
23
|
+
}catch{DENY();}
|
|
24
|
+
}
|
|
25
|
+
export async function devPairDevice({base,storageDir,fetchImpl=fetch,now=Date.now,
|
|
26
|
+
sleep=ms=>new Promise(done=>setTimeout(done,ms)),onApprove=()=>{},
|
|
27
|
+
timeoutMs=5000,signal,replaceRevoked=false,previousDeviceId}={}){
|
|
28
|
+
const u=origin(base);
|
|
29
|
+
if(typeof storageDir!=='string'||typeof fetchImpl!=='function'||typeof now!=='function'||
|
|
30
|
+
typeof sleep!=='function'||typeof onApprove!=='function'||timeoutMs<100||timeoutMs>10000)DENY();
|
|
31
|
+
const nonce=randomBytes(32).toString('base64url');
|
|
32
|
+
const start=await request(u,'api/agent/pairings/start',{
|
|
33
|
+
contract_version:'dev-device-pair-v1',nonce_hash:createHash('sha256').update(nonce).digest('hex')},{fetchImpl,timeoutMs});
|
|
34
|
+
if(start.contract_version!=='dev-device-pair-v1'||!uuid(start.pairing_id)||
|
|
35
|
+
!validToken(start.poll_token)||!Number.isSafeInteger(start.expires_at)||
|
|
36
|
+
start.expires_at<=now()||start.expires_at>now()+300000||
|
|
37
|
+
!Number.isSafeInteger(start.interval_ms)||start.interval_ms<1000||start.interval_ms>10000)DENY();
|
|
38
|
+
let approvalUrl;try{approvalUrl=new URL(start.approval_url);}catch{DENY();}
|
|
39
|
+
if(approvalUrl.origin!==u.origin||!approvalUrl.pathname.startsWith('/dev/')||
|
|
40
|
+
approvalUrl.search||approvalUrl.hash||approvalUrl.username||approvalUrl.password)DENY();
|
|
41
|
+
// Only a non-secret same-origin link is exposed to the browser.
|
|
42
|
+
onApprove(approvalUrl.href);
|
|
43
|
+
while(now()<start.expires_at){
|
|
44
|
+
if(signal?.aborted)DENY();
|
|
45
|
+
await sleep(start.interval_ms);
|
|
46
|
+
if(signal?.aborted||now()>=start.expires_at)DENY();
|
|
47
|
+
const row=await request(u,'api/agent/pairings/poll',{
|
|
48
|
+
contract_version:'dev-device-pair-v1',pairing_id:start.pairing_id,poll_token:start.poll_token,nonce
|
|
49
|
+
},{fetchImpl,timeoutMs});
|
|
50
|
+
if(row.contract_version!=='dev-device-pair-v1'||row.pairing_id!==start.pairing_id)DENY();
|
|
51
|
+
if(row.state==='pending')continue;
|
|
52
|
+
if(row.state!=='approved'||!uuid(row.enrollment_id)||!validToken(row.capability))DENY();
|
|
53
|
+
// Approved, one-time capability is consumed in-memory only. The existing
|
|
54
|
+
// Ed25519 possession challenge still controls central credential issuance.
|
|
55
|
+
const result=await devEnroll({base,storageDir,enrollmentId:row.enrollment_id,
|
|
56
|
+
capability:row.capability,fetchImpl,allowLocal:u.protocol==='http:',
|
|
57
|
+
replaceRevoked,previousDeviceId});
|
|
58
|
+
const online=await devHeartbeatOnce({storageDir,fetchImpl,allowLocal:u.protocol==='http:'});
|
|
59
|
+
return Object.freeze({registered:result.registered,connected:online.connected,
|
|
60
|
+
device_id:result.device_id,provider:'oci-dev-agent',approval:'browser-owner'});
|
|
61
|
+
}
|
|
62
|
+
DENY();
|
|
63
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// DEV Agent enrollment local inputs. No network or issuer implementation.
|
|
2
|
+
// A one-time capability must enter through stdin, never argv or an env var.
|
|
3
|
+
import {readSync,fstatSync} from 'node:fs';
|
|
4
|
+
|
|
5
|
+
const FAIL='DEVICE_DEV_ENROLLMENT_INPUT_DENIED';
|
|
6
|
+
const deny=()=>{throw Error(FAIL);};
|
|
7
|
+
const MAX_BYTES=4096;
|
|
8
|
+
export function readDevCapabilityFromStdin({fd=0,read=readSync,stat=fstatSync}={}){
|
|
9
|
+
try{
|
|
10
|
+
if(!Number.isInteger(fd)||fd<0)deny();
|
|
11
|
+
// A redirected regular file may contain secrets, but is not a TTY prompt.
|
|
12
|
+
// Explicitly reject interactive terminals so the caller can use a masked
|
|
13
|
+
// prompt in a future CLI instead of silently echoing a bearer secret.
|
|
14
|
+
if(fd===0&&process.stdin.isTTY)deny();
|
|
15
|
+
const descriptor=stat(fd);
|
|
16
|
+
if(!descriptor.isFile()&&!descriptor.isFIFO()&&!descriptor.isSocket()&&!descriptor.isCharacterDevice())deny();
|
|
17
|
+
const chunks=[];
|
|
18
|
+
let total=0;
|
|
19
|
+
const buffer=Buffer.alloc(512);
|
|
20
|
+
while(total<=MAX_BYTES){
|
|
21
|
+
const count=read(fd===0?0:fd,buffer,0,Math.min(buffer.length,MAX_BYTES+1-total),null);
|
|
22
|
+
if(!Number.isInteger(count)||count<0||count>buffer.length)deny();
|
|
23
|
+
if(count===0)break;
|
|
24
|
+
chunks.push(Buffer.from(buffer.subarray(0,count)));
|
|
25
|
+
total+=count;
|
|
26
|
+
}
|
|
27
|
+
if(total>MAX_BYTES)deny();
|
|
28
|
+
const value=Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/,'');
|
|
29
|
+
// Reject multi-line or control characters and avoid returning user input in errors.
|
|
30
|
+
if(value.length<24||value.length>2048||!/^[A-Za-z0-9._~-]+$/.test(value))deny();
|
|
31
|
+
return value;
|
|
32
|
+
}catch{deny();}
|
|
33
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Existing DEV registration survives a temporary heartbeat outage.
|
|
2
|
+
// Never report connected until the authoritative provider confirms it.
|
|
3
|
+
export async function resumeRegisteredDevice({localStatus,heartbeatOnce}={}){
|
|
4
|
+
if(localStatus?.devRegistered!==true||typeof localStatus.devDeviceId!=='string'||
|
|
5
|
+
typeof heartbeatOnce!=='function')throw Error('DEVICE_DEV_AGENT_DENIED');
|
|
6
|
+
let connected=false;
|
|
7
|
+
try{
|
|
8
|
+
const result=await heartbeatOnce();
|
|
9
|
+
connected=result?.connected===true&&result?.device_id===localStatus.devDeviceId;
|
|
10
|
+
}catch(e){
|
|
11
|
+
if(e?.message==='DEVICE_DEV_CREDENTIAL_REVOKED')throw e;
|
|
12
|
+
// Network interruption is not a reason to discard the persisted registration.
|
|
13
|
+
// The selected user-systemd service/foreground run will retry its own heartbeat.
|
|
14
|
+
}
|
|
15
|
+
return Object.freeze({
|
|
16
|
+
registered:true,connected,device_id:localStatus.devDeviceId,
|
|
17
|
+
provider:'oci-dev-agent',approval:'already-completed',
|
|
18
|
+
connectionRetry:connected?'not-needed':'service-start-required'
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Re-registration must be a separate, explicit owner decision. The pairing
|
|
23
|
+
// consumer persists nothing until the provider approves and exchanges a NEW id.
|
|
24
|
+
export async function recoverRevokedDevice({localStatus,confirmReplacement,pairDevice}={}){
|
|
25
|
+
if(localStatus?.devRegistered!==true||typeof localStatus.devDeviceId!=='string'||
|
|
26
|
+
typeof confirmReplacement!=='function'||typeof pairDevice!=='function')
|
|
27
|
+
throw Error('DEVICE_DEV_AGENT_DENIED');
|
|
28
|
+
const approved=await confirmReplacement();
|
|
29
|
+
if(approved!==true)throw Error('DEVICE_REREGISTRATION_CANCELLED');
|
|
30
|
+
const result=await pairDevice({replaceRevoked:true,previousDeviceId:localStatus.devDeviceId});
|
|
31
|
+
if(result?.registered!==true||typeof result.device_id!=='string'||
|
|
32
|
+
result.device_id===localStatus.devDeviceId)throw Error('DEVICE_PAIRING_DENIED');
|
|
33
|
+
return result;
|
|
34
|
+
}
|