@tnunamak/dalan 0.6.1 → 0.6.2
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 +9 -0
- package/README.md +4 -0
- package/docs/service-setup.md +30 -0
- package/package.json +1 -1
- package/src/cli-help.mjs +8 -2
- package/src/server.mjs +36 -2
- package/src/service-auto-update.mjs +61 -0
- package/src/service-update-gate.mjs +20 -0
- package/src/service-update-lock.mjs +22 -0
- package/src/service-update-runtime.mjs +256 -0
- package/src/service-update.mjs +393 -0
- package/src/service.mjs +82 -11
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
This file lists user-visible changes, newest first. Check the section for your target release before you upgrade.
|
|
4
4
|
|
|
5
|
+
## 0.6.2
|
|
6
|
+
|
|
7
|
+
- Add `dalan service update`, `--check`, automatic-update on/off and update status for Linux systemd services. New installs enable daily checks with jitter. Releases install side by side with npm integrity checks, local self-checks and a complete tool-catalog comparison for each configured worker. Changed descriptors stage until an explicit `--yes`; refresh hosted connectors after that switch. Failed switches attempt to restore the previous package and saved persistent state, and report rollback failures. See [service updates](docs/service-setup.md#service-updates) for limits and enrollment of older services.
|
|
8
|
+
- A candidate release is now checked with synthetic keys made for the check. It never receives the service keys.
|
|
9
|
+
- An interrupted update is recovered when the service starts (`dalan service recover` runs before the server), not only at the next update. It does nothing while an update is running.
|
|
10
|
+
- While an update switches, the restarted bridge refuses worker calls, OAuth requests and owner commands with a retryable 503 and runs no background writer until the update commits or rolls back. A rollback can no longer lose a change that was acknowledged.
|
|
11
|
+
- A release that was rolled back is skipped by the daily timer until a newer release or a different package appears. `dalan service update --retry` tries it again. `dalan service status` shows the failed release.
|
|
12
|
+
- The first `dalan service update` adopts a service installed by 0.6.0 or 0.6.1 and keeps the node binary its unit uses.
|
|
13
|
+
|
|
5
14
|
## 0.6.1
|
|
6
15
|
|
|
7
16
|
- `dalan service install` now uses the Gozar that ships with Dalan. A `gozar` command on `PATH` is no longer required. An explicit `--gozar-bin` still wins; otherwise Dalan uses the bundled copy, then `GOZAR_BIN`, then `PATH`. If none is found, the command stops before it creates any unit.
|
package/README.md
CHANGED
|
@@ -86,6 +86,10 @@ npm install -g @tnunamak/dalan
|
|
|
86
86
|
|
|
87
87
|
For a bridge that runs in the background on Linux, follow [Run Dalan as a service](docs/service-setup.md). `dalan service install` installs a systemd user service and registers an existing HTTPS origin with Gozar. It does not configure your reverse proxy. One bridge can serve several workers with built-in sign-in and a stable tool catalog.
|
|
88
88
|
|
|
89
|
+
New service installs enable daily update checks with up to one hour of jitter. `dalan service update --check --home DIR` reports the newest npm release without installing it. An update installs a separate version, checks every worker's tool catalog, restarts the bridge, and checks its health. A failed switch attempts to restore the previous version and saved state; a failed rollback is reported. Restarts interrupt client connections; these checks do not prove that every change in tool behavior is compatible.
|
|
90
|
+
|
|
91
|
+
If any tool descriptor changes, Dalan stages the release and records `connector_refresh_required` without switching. Run `dalan service update --yes --home DIR` to authorize that switch, then refresh the Dalan connector in each hosted client. The daily timer never passes `--yes`. Use `dalan service status --home DIR` for the last result, or `dalan service auto-update off --home DIR` to disable future scheduled checks. Pass `--no-auto-update` during installation to opt out. Existing service preferences are preserved. See [update and recovery details](docs/service-setup.md#service-updates). These commands support Linux systemd services; they do not add launchd support.
|
|
92
|
+
|
|
89
93
|
For an existing bridge, migrate worker settings into a new home before you install the service. Repeat `--source` for each old workers file. Use `--workspace-worker` for each worker that needs workspace access:
|
|
90
94
|
|
|
91
95
|
```sh
|
package/docs/service-setup.md
CHANGED
|
@@ -206,6 +206,36 @@ From a source checkout, use `node scripts/worker-bridge-setup.mjs` with the same
|
|
|
206
206
|
|
|
207
207
|
It should mark the existing exposure verified. A 404 from unauthenticated `/admin` proves the expected public route answers, not that OAuth pairing or a worker job works, so complete both separately.
|
|
208
208
|
|
|
209
|
+
## Service updates
|
|
210
|
+
|
|
211
|
+
For the Linux service made by `dalan service install`, new installs enable a systemd user timer that runs once daily with up to one hour of random delay. A missed run can run after the user manager next starts. Installation with `--no-auto-update` disables the timer; `--auto-update` explicitly enables it. Reinstalling preserves the saved choice unless you pass one of those flags. The timer needs your systemd user manager to run; it does not configure login lingering.
|
|
212
|
+
|
|
213
|
+
```sh
|
|
214
|
+
dalan service update --check --home HOME_PATH
|
|
215
|
+
dalan service update --home HOME_PATH
|
|
216
|
+
dalan service status --home HOME_PATH --json
|
|
217
|
+
dalan service auto-update off --home HOME_PATH
|
|
218
|
+
dalan service auto-update on --home HOME_PATH
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The home defaults to `~/.local/share/dalan-service`; pass the home used for installation if it differs. `service status` shows the selected version, saved automatic-update preference and last update result. Use `systemctl --user list-timers` to inspect the actual timer schedule. Turning updates off prevents future starts; it does not cancel an update already running. Preference changes refuse while an update holds the home lock. A release that was rolled back is recorded and skipped on later runs, including the timer; `dalan service update --retry` tries it again, and a newer or republished release is attempted normally. `service status` shows it as `failed_release`.
|
|
222
|
+
|
|
223
|
+
`--check` queries the public npm registry for the latest stable `@tnunamak/dalan` version and reports availability without installation or restart. A normal update installs the exact release under `HOME_PATH/versions/<version>`, with npm integrity checks and install scripts disabled. The registry's integrity value binds the downloaded bytes to its metadata; it is not an independent publisher signature. The original package must remain available until the first successful update. Later starts use the selected package through `HOME_PATH/current`.
|
|
224
|
+
|
|
225
|
+
Before switching, Dalan starts the candidate on a scratch loopback port against a private copy of the worker configuration, fresh mutable state, and synthetic keys made for that check. It never receives the service's signing, cookie, storage or operator keys. It checks initialization, ping and complete tool descriptors for every configured worker, then compares them with the running bridge. An unreachable worker, failed check or incomplete catalog stops the update. This local check does not test the public HTTPS route or hosted-client OAuth sign-in.
|
|
226
|
+
|
|
227
|
+
If a descriptor changes, the candidate stays staged and the last result is `connector_refresh_required`. To authorize switching to that release, run:
|
|
228
|
+
|
|
229
|
+
```sh
|
|
230
|
+
dalan service update --yes --home HOME_PATH
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Refresh the Dalan connector in each hosted client after that switch. `--yes` allows the catalog change; it does not skip integrity, scratch checks or post-restart health checks. The timer never supplies it. Equal catalogs permit an automatic switch, but they cannot prove equal tool behavior or authorization semantics. Restarting interrupts connections and can interrupt in-progress requests.
|
|
234
|
+
|
|
235
|
+
While a switch is in progress, the restarted candidate refuses every worker call, OAuth request and owner command with a retryable 503 (`service_updating`, with `Retry-After`) and starts no background writer, until the update commits or rolls back. A rollback restores the saved state, so no change that Dalan acknowledged can be lost. Hosted clients retry after the window. For a switch, Dalan stops the bridge, saves its persistent configuration and data, selects the candidate, restarts the unit and checks local health and catalogs. On failure it attempts to stop the candidate, restore the previous selection and saved state, then restart and check the old version. A failed rollback is reported separately. An interrupted switch leaves a transaction record for recovery. Recovery runs when the service starts (an `ExecStartPre` step, `dalan service recover`) and again on the next update attempt; it does nothing while another update is running. Retention keeps three staged versions, including the active and previous versions. This is update recovery, not a replacement for your own backups.
|
|
236
|
+
|
|
237
|
+
A service installed by 0.6.0 or 0.6.1 is adopted by its first `dalan service update` with no other step: Dalan reads the package path and node binary from the service unit, keeps that node binary, and leaves the original package in place until a later update succeeds. To turn on the daily timer for such a service, run `dalan service auto-update on`, or enroll it the long way: install the current Dalan package, then repeat its original `dalan service install` command with the same home, origin, port and target. Enrollment preserves keys and worker grants, changes the unit's package path and restarts it. Its timer stays off unless you pass `--auto-update` or run `service auto-update on`. A modified unit is refused for inspection. These update commands cover the service made by `dalan service install`; the older `worker-bridge-setup.mjs` Linux/macOS units are not enrolled automatically. `service install` has no launchd support.
|
|
238
|
+
|
|
209
239
|
## Remove a generated service
|
|
210
240
|
|
|
211
241
|
Use the same worker and home that created it. The full list of things an uninstall must remove (service, homes, trial home, client entries, lock file) is in [operations](operations.md#remove-an-installation).
|
package/package.json
CHANGED
package/src/cli-help.mjs
CHANGED
|
@@ -18,9 +18,15 @@ export const COMMANDS = [
|
|
|
18
18
|
{ name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
|
|
19
19
|
detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
|
|
20
20
|
'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
|
|
21
|
-
{ name: 'service', group: 'operator', summary: 'Install or
|
|
21
|
+
{ name: 'service', group: 'operator', summary: 'Install, update or inspect a long-running bridge service', usage: 'dalan service install|migrate-workers|update|auto-update|status [options]',
|
|
22
22
|
detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
|
|
23
|
-
'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]',
|
|
23
|
+
'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]',
|
|
24
|
+
'New installs enable a daily update timer with up to one hour of jitter. Existing preferences are preserved.',
|
|
25
|
+
'Update: dalan service update [--check|--yes] [--retry] [--home DIR] [--json]. --check only reports availability. --retry tries a release again after a rollback.',
|
|
26
|
+
'Updates install side by side, check every worker catalog, then restart and health-check the bridge. Failures attempt to restore the previous install and saved state; a failed rollback is reported.',
|
|
27
|
+
'Changed tool descriptors stage without switching. Refresh the hosted connectors when you explicitly switch with --yes. The timer never supplies --yes.',
|
|
28
|
+
'Automatic updates: dalan service auto-update on|off [--home DIR]. Status: dalan service status [--home DIR] [--json] shows the last result.',
|
|
29
|
+
'Service installation and update timers require Linux systemd; launchd is not supported by this command.',
|
|
24
30
|
'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
|
|
25
31
|
'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
|
|
26
32
|
'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
|
package/src/server.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs';
|
|
1
2
|
import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
2
3
|
import {inspect} from 'node:util';
|
|
3
4
|
import { loopbackRequestAllowed } from './loopback.mjs';
|
|
@@ -211,7 +212,8 @@ const protocolServices=catalogProfile==='protocol-v0'?createProtocolServices(sto
|
|
|
211
212
|
const iconBytes=fs.readFileSync(new URL('../docs/t3-connector-icon.png',import.meta.url));
|
|
212
213
|
const iconSource=`data:image/png;base64,${iconBytes.toString('base64')}`;
|
|
213
214
|
if(Buffer.byteLength(iconSource)>10000) throw new Error('server icon exceeds 10 KB');
|
|
214
|
-
const
|
|
215
|
+
const packageVersion=JSON.parse(fs.readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
216
|
+
const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':packageVersion,icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
|
|
215
217
|
// A quiet-delivery job in profile mode has no T3 thread; its response must not carry the T3 fields. Legacy profile keeps them.
|
|
216
218
|
const withoutT3=response=>{ if(legacyProfile||response.delivery_mode!=='none') return response; const {t3_muted,thread_id,...rest}=response; return rest; };
|
|
217
219
|
function mayPrepareCheckMetadata(response,worker,subject=null) {
|
|
@@ -422,6 +424,17 @@ const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'da
|
|
|
422
424
|
// Same name mapping as the protected-resource metadata and the 401 challenge, so all three surfaces agree.
|
|
423
425
|
const advertisedScope=name=>wireScope(scopeFor(name),legacyScopeNames(oauth));
|
|
424
426
|
if(oauth) for(const item of tools) item.securitySchemes=[{type:'oauth2',scopes:[advertisedScope(item.name)]}];
|
|
427
|
+
// During an update, refuse a changed catalog before either listener can expose it.
|
|
428
|
+
const catalogGuardFile=path.join(configDir,'service-catalog.json');
|
|
429
|
+
if(fs.existsSync(catalogGuardFile)) {
|
|
430
|
+
const info=fs.lstatSync(catalogGuardFile);
|
|
431
|
+
if(!info.isFile()||info.isSymbolicLink()||(info.mode&0o777)!==0o600)throw new Error('service catalog guard mismatch');
|
|
432
|
+
const guard=JSON.parse(fs.readFileSync(catalogGuardFile,'utf8'));
|
|
433
|
+
const normalize=value=>Array.isArray(value)?value.map(normalize):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,normalize(value[key])])):value;
|
|
434
|
+
const ordered=catalogs=>Object.fromEntries(Object.keys(catalogs).sort().map(worker=>[worker,[...catalogs[worker]].sort((a,b)=>a.name.localeCompare(b.name))]));
|
|
435
|
+
const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):tools]));
|
|
436
|
+
if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
|
|
437
|
+
}
|
|
425
438
|
// A refusal that must stay tells the worker the next call and what to change; workers often do not retry a bare "invalid X".
|
|
426
439
|
const argumentFixes={
|
|
427
440
|
finish:{
|
|
@@ -950,6 +963,8 @@ const verifyService=builtinMode&&readEnv('DALAN_GOZAR_SERVICE')==='1'?createServ
|
|
|
950
963
|
const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)=>{
|
|
951
964
|
const outcome=req.url===publicPath?beginMcpOutcome(req,res,log,toolNames,!!oauth):null;
|
|
952
965
|
try {
|
|
966
|
+
// Updater window: no entry may acknowledge a write the rollback snapshot would erase. Clients retry after the commit.
|
|
967
|
+
if(updateWindowOpen()) return refuseDuringUpdate(res);
|
|
953
968
|
if(loopback && !loopbackRequestAllowed(req, `http://127.0.0.1:${port}`)) { log({kind:'mcp_inbound',status:403,route:'loopback',ua:uaToken(req)}); res.writeHead(403); res.end(); return; }
|
|
954
969
|
// Both authentication modes serve only the configured public Host, including discovery and verifier routes.
|
|
955
970
|
if(as ? !as.hostOk(req) : oauth&&req.headers.host!==new URL(oauth.OAUTH_AUDIENCE).host) { log({kind:'mcp_inbound',status:421,route:'host',ua:uaToken(req)}); res.writeHead(421); res.end(); return; }
|
|
@@ -991,10 +1006,23 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
991
1006
|
let rejected=null, dryRequested=false;
|
|
992
1007
|
try {
|
|
993
1008
|
const raw=req.method==='POST'?await readBody(req):'',body=raw?JSON.parse(raw):{},url=new URL(req.url,'http://localhost');
|
|
1009
|
+
if(updateWindowOpen()&&!(req.method==='GET'&&url.pathname==='/service-check')) return refuseDuringUpdate(res);
|
|
994
1010
|
if(url.pathname.startsWith('/protocol/service/')) {
|
|
995
1011
|
if(!protocolServices||req.method!=='POST')return json(res,404,{error:'not found'});
|
|
996
1012
|
return json(res,200,await protocolServices.invoke(url.pathname.slice('/protocol/service/'.length),req.headers['x-protocol-service-capability'],body));
|
|
997
1013
|
}
|
|
1014
|
+
if(url.pathname==='/service-check'&&req.method==='GET') {
|
|
1015
|
+
adminOperator(req);
|
|
1016
|
+
const catalogs={};
|
|
1017
|
+
for(const worker of workers.workers.keys()) {
|
|
1018
|
+
const principal={worker,subject:'service-self-check',local:true};
|
|
1019
|
+
const initialized=await dispatch({method:'initialize',params:{protocolVersion:'2025-11-25'}},principal);
|
|
1020
|
+
if(!initialized.capabilities?.tools)throw new Error('service self-check: initialize failed');
|
|
1021
|
+
await dispatch({method:'ping'},principal);
|
|
1022
|
+
catalogs[worker]=(await dispatch({method:'tools/list'},principal)).tools;
|
|
1023
|
+
}
|
|
1024
|
+
return json(res,200,{version:packageVersion,catalogs,port:publicServer.address()?.port,self_check:true,update_protocol:1});
|
|
1025
|
+
}
|
|
998
1026
|
dryRequested=url.pathname==='/submit-preview';
|
|
999
1027
|
log({kind:'admin_call',route:url.pathname,method:req.method});
|
|
1000
1028
|
if(url.pathname==='/submit'&&(url.searchParams.get('dry_run')==='1'||body.dry_run===true)) throw new Error('dry run requires POST /submit-preview; /submit always submits');
|
|
@@ -1430,12 +1458,15 @@ function maintain() {
|
|
|
1430
1458
|
} catch(error) { log({kind:'maintenance_error',reason:error.message}); }
|
|
1431
1459
|
}
|
|
1432
1460
|
const runDrain=createDrainRunner(drain,log);
|
|
1433
|
-
store.recoverSends();
|
|
1434
1461
|
try { fs.unlinkSync(socket); } catch(e) { if(e.code!=='ENOENT') throw e; }
|
|
1435
1462
|
const adminListening=new Promise(resolve=>adminServer.listen(socket,()=>{fs.chmodSync(socket,0o600);console.log(`admin socket ${socket}`);resolve();}));
|
|
1436
1463
|
// Built-in mode sits behind a tunnel on this computer: only loopback may reach the listener.
|
|
1437
1464
|
const bindHost=readEnv('DALAN_BIND_HOST')||(as||loopbackOnly||loopback?'127.0.0.1':'0.0.0.0');
|
|
1438
1465
|
const publicListening=new Promise(resolve=>publicServer.listen(port,bindHost,()=>{console.log(`MCP listening on ${bindHost}:${publicServer.address().port}`);resolve();}));
|
|
1466
|
+
// Every background writer starts only when no update window is open, so a candidate restarted inside the window changes no state
|
|
1467
|
+
// the rollback snapshot would discard. Outside a window this runs at once, in the same order as before.
|
|
1468
|
+
function startBackground() {
|
|
1469
|
+
store.recoverSends();
|
|
1439
1470
|
// Cleanup removes worktrees and dependency caches; it starts only after both servers listen, and
|
|
1440
1471
|
// cleanupExpired is async and single-flight, so neither startup nor the hourly tick blocks requests.
|
|
1441
1472
|
if(workspace) {
|
|
@@ -1453,6 +1484,9 @@ const staleDays=(d=>Number.isFinite(d)&&d>0?d:7)(Number(readEnv('DALAN_DECISION_
|
|
|
1453
1484
|
const sweepStale=()=>{try{const ids=store.sweepStaleDecisions(staleDays);if(ids.length)log({kind:'decisions_stale',count:ids.length,request_ids:ids.slice(0,20)});}catch(error){log({kind:'decisions_stale_error',reason:error.message});}};
|
|
1454
1485
|
sweepStale(); setInterval(sweepStale,3600000).unref();
|
|
1455
1486
|
setInterval(()=>checkAlerts(store,log).catch(e=>log({kind:'alert_error',reason:e.message})),60000).unref();
|
|
1487
|
+
}
|
|
1488
|
+
const startWhenWindowCloses=()=>{ if(updateWindowOpen()) setTimeout(startWhenWindowCloses,250).unref(); else startBackground(); };
|
|
1489
|
+
startWhenWindowCloses();
|
|
1456
1490
|
|
|
1457
1491
|
}
|
|
1458
1492
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { defaultPath } from './paths.mjs';
|
|
5
|
+
import { acquireUpdateLock } from './service-update-lock.mjs';
|
|
6
|
+
import { writeAtomic } from './as-files.mjs';
|
|
7
|
+
|
|
8
|
+
const safePath = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
9
|
+
|
|
10
|
+
export function autoUpdateUnits({ home, unit, node }) {
|
|
11
|
+
const name = unit.replace(/\.service$/, '');
|
|
12
|
+
if (!/^dalan-[a-z0-9-]+$/.test(name)) throw new Error('invalid Dalan service unit');
|
|
13
|
+
if (![home, node].every(value => path.isAbsolute(value) && safePath.test(value))) throw new Error('update units require absolute systemd-safe paths');
|
|
14
|
+
const timer = `${name}-update.timer`;
|
|
15
|
+
return { timer, files: {
|
|
16
|
+
[`${name}-update.service`]: [
|
|
17
|
+
'[Unit]', 'Description=Check and update the Dalan bridge', 'After=network-online.target', '',
|
|
18
|
+
'[Service]', 'Type=oneshot',
|
|
19
|
+
`ExecStart=${node} ${home}/current/bin/dalan.mjs service update --home ${home} --json`,
|
|
20
|
+
`Environment=PATH=${[path.dirname(node), '/usr/local/bin', '/usr/bin', '/bin'].join(':')}`,
|
|
21
|
+
'UMask=0077', 'TimeoutStartSec=20min', 'Nice=19', 'IOSchedulingClass=idle', '',
|
|
22
|
+
].join('\n'),
|
|
23
|
+
[timer]: [
|
|
24
|
+
'[Unit]', 'Description=Daily Dalan update check', '', '[Timer]', 'OnCalendar=daily',
|
|
25
|
+
'RandomizedDelaySec=1h', 'Persistent=true', '', '[Install]', 'WantedBy=timers.target', '',
|
|
26
|
+
].join('\n'),
|
|
27
|
+
} };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function setAutoUpdate({ home, enabled }, seams = {}) {
|
|
31
|
+
if ((seams.platform ?? process.platform) !== 'linux') throw new Error('automatic service updates currently require Linux with a systemd user manager');
|
|
32
|
+
if (typeof enabled !== 'boolean') throw new Error('auto-update requires on or off');
|
|
33
|
+
home = path.resolve(home);
|
|
34
|
+
if (fs.realpathSync(home) !== home) throw new Error('service home must not use a symlink');
|
|
35
|
+
const releaseLock = acquireUpdateLock(home);
|
|
36
|
+
try {
|
|
37
|
+
const config = defaultPath(home, '.config/dot-bridge');
|
|
38
|
+
const receiptFile = path.join(config, 'service-install.json');
|
|
39
|
+
const info = fs.lstatSync(receiptFile);
|
|
40
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service receipt must be a private regular file');
|
|
41
|
+
const receipt = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
|
|
42
|
+
if (receipt.home !== home || !receipt.unit_dir || !receipt.node) throw new Error('reinstall this service with the current Dalan release before enabling automatic updates');
|
|
43
|
+
if (!safePath.test(receipt.unit_dir) || !path.isAbsolute(receipt.unit_dir) || fs.realpathSync(receipt.unit_dir) !== receipt.unit_dir) throw new Error('service unit directory must be a real absolute directory');
|
|
44
|
+
const spawn = seams.spawn ?? spawnSync;
|
|
45
|
+
const run = args => {
|
|
46
|
+
const result = spawn('systemctl', ['--user', ...args], { encoding: 'utf8', env: seams.env ?? process.env, timeout: 30000, maxBuffer: 1024 * 1024 });
|
|
47
|
+
if (result.error || result.status !== 0) throw new Error(`systemctl ${args.join(' ')} failed: ${result.error?.message ?? result.stderr ?? result.status}`);
|
|
48
|
+
};
|
|
49
|
+
const { files, timer } = autoUpdateUnits(receipt);
|
|
50
|
+
// Refuse collisions before replacing either generated unit.
|
|
51
|
+
for (const [name, text] of Object.entries(files)) {
|
|
52
|
+
const file = path.join(receipt.unit_dir, name);
|
|
53
|
+
if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) throw new Error(`${file} has different contents; refusing to replace it`);
|
|
54
|
+
}
|
|
55
|
+
for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(receipt.unit_dir, name), text, { mode: 0o644 });
|
|
56
|
+
run(['daemon-reload']);
|
|
57
|
+
run([enabled ? 'enable' : 'disable', '--now', timer]);
|
|
58
|
+
writeAtomic(receiptFile, `${JSON.stringify({ ...receipt, auto_update: enabled }, null, 2)}\n`);
|
|
59
|
+
return { home, auto_update: enabled, timer };
|
|
60
|
+
} finally { releaseLock(); }
|
|
61
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// An update window is open from the moment the updater records phase 'switched' (service stopped, snapshot complete) until it
|
|
6
|
+
// records 'committed' or finishes a rollback and removes the journal. Rollback restores the snapshot, so any mutation the
|
|
7
|
+
// candidate acknowledged inside the window would be lost. The server therefore refuses every mutating entry while it is open.
|
|
8
|
+
// Unreadable journal: fail closed. The updater writes it atomically, so only damage reaches this branch.
|
|
9
|
+
export function updateWindowOpen(home = os.homedir()) {
|
|
10
|
+
let text;
|
|
11
|
+
try { text = fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8'); }
|
|
12
|
+
catch (error) { return error.code === 'ENOENT' || error.code === 'ENOTDIR' ? false : true; }
|
|
13
|
+
try { return JSON.parse(text)?.phase === 'switched'; } catch { return true; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const UPDATE_RETRY_SECONDS = 15;
|
|
17
|
+
export function refuseDuringUpdate(res) {
|
|
18
|
+
res.writeHead(503, { 'content-type': 'application/json', 'retry-after': String(UPDATE_RETRY_SECONDS) });
|
|
19
|
+
res.end(JSON.stringify({ error: 'service_updating', retryable: true }));
|
|
20
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
|
|
5
|
+
// Keep the inode: deleting a lock file would let a new caller lock a different file.
|
|
6
|
+
// SQLite's exclusive lock is released by the kernel even if the updater is killed.
|
|
7
|
+
export function acquireUpdateLock(home) {
|
|
8
|
+
const file = path.join(home, 'update-lock.sqlite');
|
|
9
|
+
const fd = fs.openSync(file, 'a', 0o600);
|
|
10
|
+
fs.closeSync(fd);
|
|
11
|
+
const info = fs.lstatSync(file);
|
|
12
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service update lock must be a private regular file');
|
|
13
|
+
const db = new DatabaseSync(file);
|
|
14
|
+
try { db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE'); }
|
|
15
|
+
catch (error) { db.close(); if (error.errcode === 5 || error.errcode === 6) throw new Error('another service update is already running'); throw error; }
|
|
16
|
+
let held = true;
|
|
17
|
+
return () => {
|
|
18
|
+
if (!held) return;
|
|
19
|
+
held = false;
|
|
20
|
+
try { db.exec('ROLLBACK'); } finally { db.close(); }
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import https from 'node:https';
|
|
6
|
+
import net from 'node:net';
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { randomBytes } from 'node:crypto';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { defaultPath } from './paths.mjs';
|
|
11
|
+
import { initAsFiles } from './as-files.mjs';
|
|
12
|
+
|
|
13
|
+
const PACKAGE = '@tnunamak/dalan';
|
|
14
|
+
const PUBLIC_REGISTRY = 'https://registry.npmjs.org';
|
|
15
|
+
const REPO = fileURLToPath(new URL('..', import.meta.url));
|
|
16
|
+
const TIMEOUT = 30_000;
|
|
17
|
+
const fail = message => { throw new Error(message); };
|
|
18
|
+
|
|
19
|
+
function validRelease(value, { allowLocalTarball = false } = {}) {
|
|
20
|
+
const localTarball = typeof value?.dist?.tarball === 'string' && (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?\//.test(value.dist.tarball) || /^file:\/\//.test(value.dist.tarball));
|
|
21
|
+
let productionTarball = false;
|
|
22
|
+
try { const url = new URL(value?.dist?.tarball); productionTarball = url.protocol === 'https:' && url.hostname === 'registry.npmjs.org'; } catch { /* checked below */ }
|
|
23
|
+
if (!value || value.name !== PACKAGE || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value.version ?? '') ||
|
|
24
|
+
!value.dist || typeof value.dist.tarball !== 'string' || (!productionTarball && !(allowLocalTarball && localTarball)) ||
|
|
25
|
+
typeof value.dist.integrity !== 'string' || !/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(value.dist.integrity)) {
|
|
26
|
+
fail('npm registry returned invalid Dalan release metadata');
|
|
27
|
+
}
|
|
28
|
+
return { name: value.name, version: value.version, dist: { tarball: value.dist.tarball, integrity: value.dist.integrity } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function requestJson(url, { timeout = TIMEOUT, socketPath, headers = {}, allowHttp = false } = {}) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
let absoluteTimer, settled = false;
|
|
34
|
+
const finish = (fn, value) => {
|
|
35
|
+
if (settled) return;
|
|
36
|
+
settled = true;
|
|
37
|
+
clearTimeout(absoluteTimer);
|
|
38
|
+
fn(value);
|
|
39
|
+
};
|
|
40
|
+
const target = new URL(url);
|
|
41
|
+
const transport = target.protocol === 'https:' ? https : http;
|
|
42
|
+
if (target.protocol !== 'https:' && !socketPath && !(allowHttp && target.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(target.hostname))) return finish(reject, new Error('HTTPS required'));
|
|
43
|
+
const req = transport.request({ ...(socketPath ? { socketPath, path: url } : { hostname: target.hostname, port: target.port || undefined, path: target.pathname + target.search }), method: 'GET', headers, timeout }, res => {
|
|
44
|
+
const chunks = []; let size = 0;
|
|
45
|
+
res.on('data', chunk => { size += chunk.length; if (size > 2 * 1024 * 1024) req.destroy(new Error('response too large')); else chunks.push(chunk); });
|
|
46
|
+
res.on('aborted', () => finish(reject, new Error('response ended before completion')));
|
|
47
|
+
res.on('error', error => finish(reject, error));
|
|
48
|
+
res.on('end', () => {
|
|
49
|
+
if (res.statusCode !== 200) return finish(reject, new Error(`request failed (${res.statusCode})`));
|
|
50
|
+
try { finish(resolve, JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { finish(reject, new Error('invalid JSON response')); }
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
req.on('timeout', () => req.destroy(new Error('request timed out')));
|
|
54
|
+
req.on('error', error => finish(reject, error));
|
|
55
|
+
absoluteTimer = setTimeout(() => req.destroy(new Error('request timed out')), timeout);
|
|
56
|
+
req.end();
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function run(command, args, { cwd, env, timeout = TIMEOUT } = {}) {
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
const child = spawn(command, args, { cwd, env, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
63
|
+
let stderr = '', done = false;
|
|
64
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), timeout);
|
|
65
|
+
child.stderr.on('data', chunk => { if (stderr.length < 8192) stderr += chunk.toString().slice(0, 8192 - stderr.length); });
|
|
66
|
+
child.on('error', error => { if (done) return; done = true; clearTimeout(timer); reject(error); });
|
|
67
|
+
child.on('close', (code, signal) => { if (done) return; done = true; clearTimeout(timer); code === 0 ? resolve() : reject(new Error(`${path.basename(command)} failed (${signal || code})${stderr.trim() ? `: ${stderr.trim().slice(0, 1000)}` : ''}`)); });
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function latestRelease(_receipt, { registry = PUBLIC_REGISTRY } = {}) {
|
|
72
|
+
const localTestRegistry = /^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(registry);
|
|
73
|
+
if (!/^https:\/\//.test(registry) && !localTestRegistry) fail('npm registry must use HTTPS');
|
|
74
|
+
const metadata = await requestJson(`${registry.replace(/\/$/, '')}/@tnunamak%2fdalan/latest`, { allowHttp: localTestRegistry });
|
|
75
|
+
return validRelease(metadata, { allowLocalTarball: localTestRegistry });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function packageAt(home, version) { return path.join(home, 'versions', version, 'node_modules', '@tnunamak', 'dalan'); }
|
|
79
|
+
function installEnv(dir) {
|
|
80
|
+
const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: dir, npm_config_userconfig: path.join(dir, '.npmrc'), npm_config_cache: path.join(dir, '.cache') };
|
|
81
|
+
if (process.platform === 'win32') env.SystemRoot = process.env.SystemRoot;
|
|
82
|
+
return env;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function installRelease(home, input, options = {}) {
|
|
86
|
+
const localTestRegistry = /^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(options.registry ?? '');
|
|
87
|
+
const release = validRelease(input, { allowLocalTarball: localTestRegistry }), versions = path.join(home, 'versions'), destination = packageAt(home, release.version);
|
|
88
|
+
fs.mkdirSync(versions, { recursive: true, mode: 0o700 });
|
|
89
|
+
const marker = path.join(path.dirname(path.dirname(path.dirname(destination))), '.dalan-release.json');
|
|
90
|
+
if (fs.existsSync(destination)) {
|
|
91
|
+
let existing;
|
|
92
|
+
try { existing = JSON.parse(fs.readFileSync(marker, 'utf8')); } catch { fail(`installed version ${release.version} has no valid integrity receipt`); }
|
|
93
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(destination, 'package.json'), 'utf8'));
|
|
94
|
+
if (existing.integrity !== release.dist.integrity || pkg.name !== PACKAGE || pkg.version !== release.version) fail(`installed version ${release.version} does not match registry integrity`);
|
|
95
|
+
return destination;
|
|
96
|
+
}
|
|
97
|
+
const staging = path.join(versions, `.stage-${release.version}-${process.pid}-${randomBytes(5).toString('hex')}`);
|
|
98
|
+
fs.mkdirSync(staging, { recursive: true, mode: 0o700 });
|
|
99
|
+
const registry = options.registry ?? PUBLIC_REGISTRY;
|
|
100
|
+
if (!/^https:\/\//.test(registry) && !/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(registry)) fail('npm registry must use HTTPS');
|
|
101
|
+
try {
|
|
102
|
+
const pkg = { private: true, name: 'dalan-release-stage', version: '1.0.0', dependencies: { [PACKAGE]: release.dist.tarball } };
|
|
103
|
+
fs.writeFileSync(path.join(staging, 'package.json'), JSON.stringify(pkg), { mode: 0o600 });
|
|
104
|
+
const env = installEnv(staging), npm = options.npm ?? 'npm';
|
|
105
|
+
const base = ['--ignore-scripts', '--no-audit', '--no-fund', '--registry', registry];
|
|
106
|
+
await (options.run ?? run)(npm, ['install', '--package-lock-only', ...base], { cwd: staging, env, timeout: options.timeout ?? TIMEOUT });
|
|
107
|
+
const lock = JSON.parse(fs.readFileSync(path.join(staging, 'package-lock.json'), 'utf8'));
|
|
108
|
+
if (lock.packages?.[`node_modules/${PACKAGE}`]?.integrity !== release.dist.integrity) fail('npm lock integrity does not match registry metadata');
|
|
109
|
+
await (options.run ?? run)(npm, ['ci', ...base, '--omit=dev'], { cwd: staging, env, timeout: options.timeout ?? TIMEOUT });
|
|
110
|
+
const installed = JSON.parse(fs.readFileSync(path.join(staging, 'node_modules', PACKAGE, 'package.json'), 'utf8'));
|
|
111
|
+
if (installed.name !== PACKAGE || installed.version !== release.version) fail('installed package identity does not match registry metadata');
|
|
112
|
+
fs.writeFileSync(path.join(staging, '.dalan-release.json'), JSON.stringify({ name: PACKAGE, version: release.version, integrity: release.dist.integrity }), { mode: 0o600 });
|
|
113
|
+
fs.rmSync(path.join(staging, '.cache'), { recursive: true, force: true });
|
|
114
|
+
fs.rmSync(path.join(staging, '.npmrc'), { force: true });
|
|
115
|
+
fs.renameSync(staging, path.join(versions, release.version));
|
|
116
|
+
return destination;
|
|
117
|
+
} catch (error) { fs.rmSync(staging, { recursive: true, force: true }); throw error; }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function validateProbe(value, { expectedWorkers, expectedVersion } = {}) {
|
|
121
|
+
if (!value || typeof value !== 'object' || typeof value.version !== 'string' || value.update_protocol !== 1 || !Number.isInteger(value.port) || value.port < 1 || value.port > 65535 || value.self_check !== true ||
|
|
122
|
+
!value.catalogs || typeof value.catalogs !== 'object' || Array.isArray(value.catalogs) || !Object.keys(value.catalogs).length) fail('service self-check response is incomplete');
|
|
123
|
+
for (const [worker, tools] of Object.entries(value.catalogs)) {
|
|
124
|
+
const names = new Set();
|
|
125
|
+
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(worker) || !Array.isArray(tools) || !tools.length || tools.some(tool => {
|
|
126
|
+
if (!tool || typeof tool.name !== 'string' || !tool.name || names.has(tool.name) || typeof tool.description !== 'string' || !tool.inputSchema || typeof tool.inputSchema !== 'object') return true;
|
|
127
|
+
names.add(tool.name); return false;
|
|
128
|
+
})) fail('service self-check returned an invalid worker catalog');
|
|
129
|
+
}
|
|
130
|
+
if (expectedWorkers && JSON.stringify(Object.keys(value.catalogs).sort()) !== JSON.stringify([...expectedWorkers].sort())) fail('service self-check worker set does not match configuration');
|
|
131
|
+
if (expectedVersion && value.version !== expectedVersion) fail('service self-check version does not match selected package');
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function expectedProbe(home, receipt, repo) {
|
|
136
|
+
const workers = JSON.parse(fs.readFileSync(defaultPath(home, '.config/dot-bridge', 'workers.json'), 'utf8'))?.workers;
|
|
137
|
+
if (!workers || typeof workers !== 'object' || Array.isArray(workers)) fail('worker configuration is invalid for service self-check');
|
|
138
|
+
const packageDir = repo ?? receipt?.repo ?? path.join(home, 'current');
|
|
139
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
|
|
140
|
+
return { expectedWorkers: Object.keys(workers), expectedVersion: manifest.version };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function probeService(home, _receipt, options = {}) {
|
|
144
|
+
const socketPath = defaultPath(home, '.local/share/dot-bridge', 'admin.sock');
|
|
145
|
+
const operator = fs.readFileSync(defaultPath(home, '.config/dot-bridge', 'operator.key'), 'utf8').trim();
|
|
146
|
+
if (!operator || operator.length > 1024) fail('service operator key is invalid');
|
|
147
|
+
const timeout = options.timeout ?? TIMEOUT;
|
|
148
|
+
if (!Number.isFinite(timeout) || timeout <= 0) fail('service probe timeout must be positive');
|
|
149
|
+
const deadline = performance.now() + timeout;
|
|
150
|
+
const value = validateProbe(await requestJson('http://localhost/service-check', { socketPath, headers: { 'x-operator-key': operator }, timeout }), expectedProbe(home, _receipt));
|
|
151
|
+
const remaining = deadline - performance.now();
|
|
152
|
+
if (remaining <= 0) fail('service probe timed out');
|
|
153
|
+
await checkLoopback(value.port, remaining);
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function checkLoopback(port, timeout = 1500) {
|
|
158
|
+
return new Promise((resolve, reject) => {
|
|
159
|
+
const socket = net.connect({ host: '127.0.0.1', port });
|
|
160
|
+
const timer = setTimeout(() => socket.destroy(new Error('service listener check timed out')), timeout);
|
|
161
|
+
socket.once('connect', () => { clearTimeout(timer); socket.end(); resolve(); });
|
|
162
|
+
socket.once('error', error => { clearTimeout(timer); reject(new Error(`reported loopback listener is unavailable: ${error.message}`)); });
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// The candidate runs before promotion and may be incompatible or hostile. It receives configuration shape (workers, public origin)
|
|
167
|
+
// but never a live secret: signing keys, cookie keys, the storage key and the operator key are generated fresh for each probe.
|
|
168
|
+
function prepareProbeConfig(from, to) {
|
|
169
|
+
const source = defaultPath(from, '.config/dot-bridge'), target = defaultPath(to, '.config/dot-bridge');
|
|
170
|
+
fs.mkdirSync(target, { recursive: true, mode: 0o700 });
|
|
171
|
+
for (const name of ['workers.json', 'workers-repos.json']) {
|
|
172
|
+
const a = path.join(source, name); if (!fs.existsSync(a)) continue;
|
|
173
|
+
const stat = fs.lstatSync(a); if (!stat.isFile() || stat.isSymbolicLink()) continue;
|
|
174
|
+
fs.copyFileSync(a, path.join(target, name), fs.constants.COPYFILE_EXCL); fs.chmodSync(path.join(target, name), stat.mode & 0o777);
|
|
175
|
+
}
|
|
176
|
+
const origin = JSON.parse(fs.readFileSync(path.join(source, 'as.json'), 'utf8'));
|
|
177
|
+
initAsFiles(target, { publicUrl: origin.public_url });
|
|
178
|
+
fs.writeFileSync(path.join(target, 'as.json'), JSON.stringify({ ...origin, public_url: origin.public_url }), { mode: 0o600 });
|
|
179
|
+
fs.writeFileSync(path.join(target, 'operator.key'), `${randomBytes(32).toString('hex')}\n`, { mode: 0o600 });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function stopChild(child) {
|
|
183
|
+
if (!child || child.exitCode !== null || child.signalCode !== null || child.spawned === false) return;
|
|
184
|
+
if (!child.pid) return;
|
|
185
|
+
child.kill('SIGTERM');
|
|
186
|
+
let timer;
|
|
187
|
+
await Promise.race([new Promise(resolve => child.once('close', resolve)), new Promise(resolve => { timer = setTimeout(resolve, 3000); })]);
|
|
188
|
+
clearTimeout(timer);
|
|
189
|
+
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
|
190
|
+
if (child.exitCode === null && child.signalCode === null && child.spawned !== false) await new Promise(resolve => child.once('close', resolve));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function requireCatalogGuard(repo, env, receipt, options) {
|
|
194
|
+
const child = (options.spawn ?? spawn)(receipt.node ?? process.execPath, [path.join(repo, 'src/server.mjs')], { cwd: repo, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
195
|
+
let stdout = '', stderr = '';
|
|
196
|
+
let spawnError = null, closed = false;
|
|
197
|
+
child.on('error', error => { spawnError = error; });
|
|
198
|
+
child.once('close', () => { closed = true; });
|
|
199
|
+
child.stdout?.on('data', chunk => { if (stdout.length < 8192) stdout += chunk.toString().slice(0, 8192 - stdout.length); });
|
|
200
|
+
child.stderr?.on('data', chunk => { if (stderr.length < 8192) stderr += chunk.toString().slice(0, 8192 - stderr.length); });
|
|
201
|
+
try {
|
|
202
|
+
const deadline = Date.now() + (options.guardTimeoutMs ?? 10_000);
|
|
203
|
+
while (Date.now() < deadline) {
|
|
204
|
+
if (spawnError) fail(`candidate service could not start: ${spawnError.message}`);
|
|
205
|
+
if (/MCP listening|admin socket/.test(stdout)) fail('candidate started despite mismatched service catalog pin');
|
|
206
|
+
if (closed) break;
|
|
207
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
208
|
+
}
|
|
209
|
+
if (!closed) fail('candidate did not enforce the service catalog pin before timeout');
|
|
210
|
+
if (/MCP listening|admin socket/.test(stdout)) fail('candidate announced a listener before enforcing the service catalog pin');
|
|
211
|
+
if (child.exitCode === 0 || !stderr.includes('service catalog guard mismatch')) fail('candidate did not reject the mismatched service catalog pin');
|
|
212
|
+
} finally { await stopChild(child); }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function probeCandidate(home, receipt, repo, options = {}) {
|
|
216
|
+
const scratchBase = path.join(os.homedir(), '.tmp');
|
|
217
|
+
fs.mkdirSync(scratchBase, { recursive: true, mode: 0o700 });
|
|
218
|
+
const scratch = fs.mkdtempSync(path.join(scratchBase, 'dalan-candidate-'));
|
|
219
|
+
fs.chmodSync(scratch, 0o700);
|
|
220
|
+
let child;
|
|
221
|
+
try {
|
|
222
|
+
prepareProbeConfig(home, scratch);
|
|
223
|
+
const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: scratch, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_PORT: '0', DALAN_CATALOG_PROFILE: 'stable', DALAN_ENABLE_WORKSPACE: receipt.enable_workspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: receipt.enable_t3 ? '1' : '0' };
|
|
224
|
+
const configDir = defaultPath(scratch, '.config/dot-bridge');
|
|
225
|
+
const pinFile = path.join(configDir, 'service-catalog.json');
|
|
226
|
+
const version = JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version;
|
|
227
|
+
fs.writeFileSync(pinFile, JSON.stringify({ version, catalogs: {} }), { mode: 0o600, flag: 'wx' });
|
|
228
|
+
try { await requireCatalogGuard(repo, env, receipt, options); }
|
|
229
|
+
finally { fs.rmSync(pinFile, { force: true }); }
|
|
230
|
+
child = (options.spawn ?? spawn)(receipt.node ?? process.execPath, [path.join(repo, 'src/server.mjs')], { cwd: repo, env, stdio: ['ignore', 'ignore', 'ignore'] });
|
|
231
|
+
let spawnError = null, closed = false;
|
|
232
|
+
child.on('error', error => { spawnError = error; });
|
|
233
|
+
child.once('close', () => { closed = true; });
|
|
234
|
+
const deadline = Date.now() + (options.startupTimeoutMs ?? 20_000);
|
|
235
|
+
let result;
|
|
236
|
+
while (Date.now() < deadline) {
|
|
237
|
+
if (spawnError) fail(`candidate service could not start: ${spawnError.message}`);
|
|
238
|
+
if (closed) fail('candidate service exited before self-check');
|
|
239
|
+
if (child.exitCode !== null || child.signalCode !== null) fail('candidate service exited before self-check');
|
|
240
|
+
try { result = await probeService(scratch, { ...receipt, repo }); break; } catch { await new Promise(resolve => setTimeout(resolve, 150)); }
|
|
241
|
+
}
|
|
242
|
+
if (!result) fail('candidate service did not pass its self-check before timeout');
|
|
243
|
+
return result;
|
|
244
|
+
} finally {
|
|
245
|
+
await stopChild(child);
|
|
246
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export async function controlService(receipt, action, options = {}) {
|
|
251
|
+
if (!['stop', 'restart', 'daemon-reload'].includes(action)) fail('unsupported service action');
|
|
252
|
+
const unit = String(receipt.unit ?? '');
|
|
253
|
+
if (!/^[A-Za-z0-9_.@-]+$/.test(unit)) fail('invalid systemd unit name');
|
|
254
|
+
const name = unit.endsWith('.service') ? unit : `${unit}.service`;
|
|
255
|
+
await (options.run ?? run)('systemctl', ['--user', action, ...(action === 'daemon-reload' ? [] : [name])], { timeout: TIMEOUT });
|
|
256
|
+
}
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
5
|
+
import { defaultPath } from './paths.mjs';
|
|
6
|
+
import { acquireUpdateLock } from './service-update-lock.mjs';
|
|
7
|
+
import { writeAtomic } from './as-files.mjs';
|
|
8
|
+
import { latestRelease as defaultLatest, installRelease as defaultInstall, probeService as defaultProbe, probeCandidate as defaultCandidate, controlService as defaultControl } from './service-update-runtime.mjs';
|
|
9
|
+
|
|
10
|
+
const PACKAGE = '@tnunamak/dalan';
|
|
11
|
+
const HEALTH_TIMEOUT_MS = 30_000;
|
|
12
|
+
const fail = message => { throw new Error(message); };
|
|
13
|
+
const privateDir = dir => fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
14
|
+
function readReceipt(home) {
|
|
15
|
+
const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
|
|
16
|
+
let st, value;
|
|
17
|
+
try { st = fs.lstatSync(file); value = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
18
|
+
catch { fail(`service receipt is missing or invalid: ${file}`); }
|
|
19
|
+
if (!st.isFile() || st.isSymbolicLink() || (st.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
|
|
20
|
+
if (!value || value.schema_version !== 1 || value.home !== home || !value.unit) fail(`${file} has an unsupported service receipt`);
|
|
21
|
+
return { file, value };
|
|
22
|
+
}
|
|
23
|
+
function canonical(x) {
|
|
24
|
+
if (Array.isArray(x)) return `[${x.map(canonical).join(',')}]`;
|
|
25
|
+
if (x && typeof x === 'object') return `{${Object.keys(x).sort().map(k => `${JSON.stringify(k)}:${canonical(x[k])}`).join(',')}}`;
|
|
26
|
+
return JSON.stringify(x);
|
|
27
|
+
}
|
|
28
|
+
function canonicalCatalogs(catalogs) {
|
|
29
|
+
return canonical(Object.fromEntries(Object.keys(catalogs ?? {}).sort().map(worker => [worker,
|
|
30
|
+
[...(catalogs[worker] ?? [])].sort((a, b) => String(a?.name).localeCompare(String(b?.name)))])));
|
|
31
|
+
}
|
|
32
|
+
function configurationDigest(home, receipt) {
|
|
33
|
+
const root = defaultPath(home, '.config/dot-bridge');
|
|
34
|
+
const hash = createHash('sha256');
|
|
35
|
+
hash.update(canonical({ enable_workspace: !!receipt.enable_workspace, enable_t3: !!receipt.enable_t3 }));
|
|
36
|
+
for (const name of ['workers.json', 'workers-repos.json', 'as.json', 'as-jwks.json', 'as-cookie-keys.json', 'as-storage.key', 'operator.key', 'env']) {
|
|
37
|
+
const file = path.join(root, name);
|
|
38
|
+
let st;
|
|
39
|
+
try { st = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') { hash.update(`missing:${name}`); continue; } throw error; }
|
|
40
|
+
if (!st.isFile() || st.isSymbolicLink()) fail(`configuration input must be a regular file: ${file}`);
|
|
41
|
+
hash.update(`file:${name}:${st.mode & 0o777}:`); hash.update(fs.readFileSync(file));
|
|
42
|
+
}
|
|
43
|
+
return hash.digest('hex');
|
|
44
|
+
}
|
|
45
|
+
function completeCatalogs(a, b, workers) {
|
|
46
|
+
if (!a?.catalogs || !b?.catalogs) return false;
|
|
47
|
+
const keysA = Object.keys(a.catalogs).sort(), keysB = Object.keys(b.catalogs).sort();
|
|
48
|
+
if (canonical(keysA) !== canonical(keysB) || canonical(keysA) !== canonical([...workers].sort())) return false;
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
function catalogsEqual(a, b, workers) {
|
|
52
|
+
return completeCatalogs(a, b, workers) && canonicalCatalogs(a.catalogs) === canonicalCatalogs(b.catalogs);
|
|
53
|
+
}
|
|
54
|
+
function releaseVersion(r, current) {
|
|
55
|
+
if (!r || r.name !== PACKAGE || typeof r.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(r.version) || typeof r.dist?.integrity !== 'string' || !r.dist.integrity.startsWith('sha512-')) fail('registry returned invalid stable release metadata');
|
|
56
|
+
const parts = s => s.split('.').map(Number), a = parts(r.version), b = parts(current);
|
|
57
|
+
if (!/^\d+\.\d+\.\d+$/.test(current) || a.some(n => !Number.isSafeInteger(n))) fail('installed service version is not a stable semantic version');
|
|
58
|
+
return a[0] > b[0] || a[0] === b[0] && (a[1] > b[1] || a[1] === b[1] && a[2] > b[2]);
|
|
59
|
+
}
|
|
60
|
+
function atomic(file, text) {
|
|
61
|
+
privateDir(path.dirname(file)); writeAtomic(file, text);
|
|
62
|
+
}
|
|
63
|
+
const failedFile = home => path.join(home, 'update-failed.json');
|
|
64
|
+
function readFailed(home) {
|
|
65
|
+
try {
|
|
66
|
+
const v = JSON.parse(fs.readFileSync(failedFile(home), 'utf8'));
|
|
67
|
+
return typeof v?.version === 'string' && typeof v.integrity === 'string' ? v : null;
|
|
68
|
+
} catch { return null; }
|
|
69
|
+
}
|
|
70
|
+
function copyTree(src, dst) {
|
|
71
|
+
const st = fs.lstatSync(src);
|
|
72
|
+
if (st.isSymbolicLink()) { fs.symlinkSync(fs.readlinkSync(src), dst); return; }
|
|
73
|
+
if (!st.isDirectory() && !st.isFile()) return;
|
|
74
|
+
if (st.isDirectory()) {
|
|
75
|
+
fs.mkdirSync(dst, { recursive: true, mode: st.mode & 0o777 });
|
|
76
|
+
for (const name of fs.readdirSync(src)) copyTree(path.join(src, name), path.join(dst, name));
|
|
77
|
+
fs.chmodSync(dst, st.mode & 0o777);
|
|
78
|
+
} else { fs.copyFileSync(src, dst); fs.chmodSync(dst, st.mode & 0o777); }
|
|
79
|
+
}
|
|
80
|
+
function replaceTree(src, dst) {
|
|
81
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
82
|
+
if (fs.existsSync(src)) copyTree(src, dst);
|
|
83
|
+
}
|
|
84
|
+
function snapshot(home, txn) {
|
|
85
|
+
const target = path.join(txn, 'snapshot.pending'); fs.rmSync(target, { recursive: true, force: true }); privateDir(target);
|
|
86
|
+
const roots = {};
|
|
87
|
+
for (const item of ['.config', '.local']) {
|
|
88
|
+
const src = path.join(home, item);
|
|
89
|
+
if (fs.existsSync(src)) {
|
|
90
|
+
const st = fs.lstatSync(src);
|
|
91
|
+
if (!st.isDirectory() || st.isSymbolicLink()) fail(`cannot snapshot non-directory service state: ${src}`);
|
|
92
|
+
roots[item] = true; copyTree(src, path.join(target, item));
|
|
93
|
+
} else roots[item] = false;
|
|
94
|
+
}
|
|
95
|
+
atomic(path.join(target, '.snapshot-complete.json'), JSON.stringify({ complete: true, roots }));
|
|
96
|
+
const ready = path.join(txn, 'snapshot'); fs.rmSync(ready, { recursive: true, force: true }); fs.renameSync(target, ready); return ready;
|
|
97
|
+
}
|
|
98
|
+
function validateSnapshot(tx) {
|
|
99
|
+
const root = tx.snapshot;
|
|
100
|
+
let marker;
|
|
101
|
+
try {
|
|
102
|
+
const st = fs.lstatSync(root);
|
|
103
|
+
if (!st.isDirectory() || st.isSymbolicLink()) fail('transaction snapshot is not a real directory');
|
|
104
|
+
marker = JSON.parse(fs.readFileSync(path.join(root, '.snapshot-complete.json'), 'utf8'));
|
|
105
|
+
} catch { fail('transaction snapshot is missing or incomplete; refusing to restore service state'); }
|
|
106
|
+
if (marker.complete !== true || !marker.roots || typeof marker.roots['.config'] !== 'boolean' || typeof marker.roots['.local'] !== 'boolean') fail('transaction snapshot completion marker is invalid');
|
|
107
|
+
for (const item of ['.config', '.local']) {
|
|
108
|
+
const file = path.join(root, item), exists = fs.existsSync(file);
|
|
109
|
+
if (exists !== marker.roots[item]) fail(`transaction snapshot is incomplete for ${item}; refusing to restore service state`);
|
|
110
|
+
if (exists) { const st = fs.lstatSync(file); if (!st.isDirectory() || st.isSymbolicLink()) fail(`transaction snapshot is invalid for ${item}`); }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function unitPath(receipt, home) {
|
|
114
|
+
if (!/^[A-Za-z0-9_.@-]+$/.test(String(receipt.unit ?? ''))) fail('invalid service unit name in receipt');
|
|
115
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
116
|
+
const dir = receipt.unit_dir || path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config'), 'systemd/user');
|
|
117
|
+
if (!path.isAbsolute(dir) || dir.includes('\n')) fail('invalid service unit directory in receipt');
|
|
118
|
+
const name = String(receipt.unit).endsWith('.service') ? String(receipt.unit) : `${receipt.unit}.service`;
|
|
119
|
+
return path.join(dir, name);
|
|
120
|
+
}
|
|
121
|
+
// A 0.6.0 or 0.6.1 receipt names no package, node binary or unit directory. Read them from the unit that runs the service,
|
|
122
|
+
// so the first update adopts the install with no hand step and keeps the node binary the service already uses.
|
|
123
|
+
function adoptInstall(receipt, home) {
|
|
124
|
+
if (receipt.repo && receipt.node && receipt.unit_dir) return receipt;
|
|
125
|
+
const file = unitPath(receipt, home);
|
|
126
|
+
let text;
|
|
127
|
+
try { const st = fs.lstatSync(file); if (!st.isFile() || st.isSymbolicLink()) fail('not a regular file'); text = fs.readFileSync(file, 'utf8'); }
|
|
128
|
+
catch { fail(`cannot read the service unit to adopt this install: ${file}`); }
|
|
129
|
+
const repo = text.match(/^WorkingDirectory=(.+)$/m)?.[1], exec = text.match(/^ExecStart=(\S+) (\S+)$/m);
|
|
130
|
+
if (!repo || !exec || exec[2] !== `${repo}/src/server.mjs` || !path.isAbsolute(repo) || !path.isAbsolute(exec[1])) fail(`service unit does not contain a supported Dalan command: ${file}`);
|
|
131
|
+
return { ...receipt, repo: receipt.repo ?? repo, node: receipt.node ?? exec[1], unit_dir: receipt.unit_dir ?? path.dirname(file) };
|
|
132
|
+
}
|
|
133
|
+
function rewriteUnit(file, current, home) {
|
|
134
|
+
if (!fs.existsSync(file)) fail(`service unit is missing: ${file}`);
|
|
135
|
+
const st = fs.lstatSync(file);
|
|
136
|
+
if (!st.isFile() || st.isSymbolicLink()) fail(`service unit must be a regular file: ${file}`);
|
|
137
|
+
const before = fs.readFileSync(file, 'utf8');
|
|
138
|
+
const oldRepo = before.match(/^WorkingDirectory=(.+)$/m)?.[1];
|
|
139
|
+
const exec = before.match(/^ExecStart=(.+)$/m)?.[1];
|
|
140
|
+
if (!oldRepo || !exec || !exec.endsWith('/src/server.mjs')) fail(`service unit does not contain a supported Dalan command: ${file}`);
|
|
141
|
+
const after = before.split('\n').map(line => /^WorkingDirectory=/.test(line) ? `WorkingDirectory=${current}` : /^ExecStart=/.test(line) ? line.replace(/\/src\/server\.mjs(?:\s.*)?$/, `${path.sep}src${path.sep}server.mjs`) : line).join('\n');
|
|
142
|
+
// Preserve the selected package in ExecStart, including its node executable prefix.
|
|
143
|
+
const fixed = after.replaceAll(`${oldRepo}/src/server.mjs`, `${current}/src/server.mjs`);
|
|
144
|
+
const lines = fixed.split('\n').filter(l => !/^ExecStartPre=.*\sservice recover\s/.test(l));
|
|
145
|
+
const i = lines.findIndex(l => /^ExecStart=/.test(l));
|
|
146
|
+
const execLine = lines[i].slice('ExecStart='.length), nodeBin = execLine.slice(0, execLine.indexOf(' '));
|
|
147
|
+
lines.splice(i + 1, 0, `ExecStartPre=${nodeBin} ${current}/bin/dalan.mjs service recover --home ${home} --quiet`);
|
|
148
|
+
atomic(file, lines.join('\n')); fs.chmodSync(file, st.mode & 0o777); return before;
|
|
149
|
+
}
|
|
150
|
+
function select(home, repo) {
|
|
151
|
+
const current = path.join(home, 'current'), tmp = path.join(home, `.current-${randomUUID()}`);
|
|
152
|
+
fs.symlinkSync(path.relative(home, repo), tmp); fs.renameSync(tmp, current);
|
|
153
|
+
}
|
|
154
|
+
function prune(home, active, previous) {
|
|
155
|
+
const root = path.join(home, 'versions'); if (!fs.existsSync(root)) return;
|
|
156
|
+
const dirs = fs.readdirSync(root, { withFileTypes: true }).filter(d => d.isDirectory() && !d.isSymbolicLink()).map(d => d.name).sort((a,b) => b.localeCompare(a, undefined, { numeric: true }));
|
|
157
|
+
const keep = new Set([active, previous]);
|
|
158
|
+
for (const name of dirs) { if (keep.size >= 3) break; keep.add(name); }
|
|
159
|
+
for (const name of dirs) if (!keep.has(name)) fs.rmSync(path.join(root, name), { recursive: true, force: true });
|
|
160
|
+
}
|
|
161
|
+
async function probeReady(probe, home, receipt, healthTimeoutMs = HEALTH_TIMEOUT_MS) {
|
|
162
|
+
const deadline = performance.now() + healthTimeoutMs;
|
|
163
|
+
let error;
|
|
164
|
+
while (performance.now() < deadline) {
|
|
165
|
+
const remaining = deadline - performance.now();
|
|
166
|
+
try { return await probe(home, receipt, { timeout: Math.max(1, Math.min(remaining, 1000)) }); }
|
|
167
|
+
catch (e) {
|
|
168
|
+
error = e;
|
|
169
|
+
const delay = Math.min(150, Math.max(0, deadline - performance.now()));
|
|
170
|
+
if (delay) await new Promise(resolve => setTimeout(resolve, delay));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
throw new Error(`service health check timed out after ${healthTimeoutMs}ms${error ? `: ${error.message}` : ''}`);
|
|
174
|
+
}
|
|
175
|
+
function readJournal(home) {
|
|
176
|
+
const file = path.join(home, 'update-transaction.json');
|
|
177
|
+
let txStat;
|
|
178
|
+
try { txStat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
179
|
+
if (!txStat.isFile() || txStat.isSymbolicLink() || (txStat.mode & 0o777) !== 0o600) fail('update transaction must be a private regular file');
|
|
180
|
+
let tx;
|
|
181
|
+
try { tx = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail('update transaction is invalid JSON'); }
|
|
182
|
+
const oldReceipt = tx?.oldReceipt;
|
|
183
|
+
if (tx.home !== home || !oldReceipt || oldReceipt.home !== home || oldReceipt.schema_version !== 1 || !oldReceipt.unit ||
|
|
184
|
+
!tx.oldRepo || !tx.oldVersion || !tx.snapshot || !['prepared', 'switched', 'committed'].includes(tx.phase)) fail('invalid interrupted update transaction');
|
|
185
|
+
if (tx.unitFile !== (oldReceipt.unit ? unitPath(oldReceipt, home) : null) || !tx.oldCatalogs || typeof tx.oldCatalogs !== 'object') fail('update transaction control data is invalid');
|
|
186
|
+
if (path.resolve(tx.snapshot) !== path.join(home, 'update-backup', 'snapshot')) fail('update transaction snapshot path is invalid');
|
|
187
|
+
return { file, tx };
|
|
188
|
+
}
|
|
189
|
+
// Put the old package, unit and saved state back on disk. Touches no service and probes nothing.
|
|
190
|
+
function restoreFiles(home, tx) {
|
|
191
|
+
validateSnapshot(tx);
|
|
192
|
+
select(home, tx.oldRepo);
|
|
193
|
+
if (tx.unitFile && tx.oldUnit != null) atomic(tx.unitFile, tx.oldUnit);
|
|
194
|
+
for (const item of ['.config', '.local']) replaceTree(path.join(tx.snapshot, item), path.join(home, item));
|
|
195
|
+
}
|
|
196
|
+
function discardJournal(home, tx) {
|
|
197
|
+
fs.rmSync(path.join(home, 'update-transaction.json'), { force: true });
|
|
198
|
+
fs.rmSync(path.dirname(tx.snapshot), { recursive: true, force: true });
|
|
199
|
+
}
|
|
200
|
+
function restoreFromJournal(home, tx) {
|
|
201
|
+
if (tx.phase === 'committed') {
|
|
202
|
+
fs.rmSync(path.join(home, 'update-transaction.json'), { force: true });
|
|
203
|
+
try { fs.rmSync(path.dirname(tx.snapshot), { recursive: true, force: true }); } catch { /* committed service stays selected */ }
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (tx.phase === 'switched') restoreFiles(home, tx);
|
|
207
|
+
discardJournal(home, tx);
|
|
208
|
+
}
|
|
209
|
+
// Run at service start (ExecStartPre): finish filesystem recovery without touching systemd.
|
|
210
|
+
export function recoverService({ home }) {
|
|
211
|
+
home = path.resolve(home ?? fail('home is required'));
|
|
212
|
+
if (!fs.existsSync(path.join(home, 'update-transaction.json'))) return { outcome: 'nothing_pending' };
|
|
213
|
+
let release;
|
|
214
|
+
try { release = acquireUpdateLock(home); }
|
|
215
|
+
catch (error) { if (/already running/.test(error.message)) return { outcome: 'update_running' }; throw error; }
|
|
216
|
+
try {
|
|
217
|
+
const journal = readJournal(home);
|
|
218
|
+
if (!journal) return { outcome: 'nothing_pending' };
|
|
219
|
+
restoreFromJournal(home, journal.tx);
|
|
220
|
+
return { outcome: 'recovered' };
|
|
221
|
+
} finally { release(); }
|
|
222
|
+
}
|
|
223
|
+
async function recover(home, control, probe, healthTimeoutMs) {
|
|
224
|
+
const journal = readJournal(home);
|
|
225
|
+
if (!journal) return;
|
|
226
|
+
const { tx } = journal, oldReceipt = tx.oldReceipt;
|
|
227
|
+
if (tx.phase === 'committed') return restoreFromJournal(home, tx);
|
|
228
|
+
if (tx.phase === 'prepared') {
|
|
229
|
+
await control(oldReceipt, 'restart');
|
|
230
|
+
const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
|
|
231
|
+
if (live.version !== tx.oldVersion || tx.oldCatalogs && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs))) fail('interrupted update recovery could not verify old service');
|
|
232
|
+
} else {
|
|
233
|
+
validateSnapshot(tx);
|
|
234
|
+
await control(oldReceipt, 'stop'); restoreFiles(home, tx);
|
|
235
|
+
await control(oldReceipt, 'daemon-reload'); await control(oldReceipt, 'restart');
|
|
236
|
+
const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
|
|
237
|
+
if (tx.oldCatalogs && (live.version !== tx.oldVersion || !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs)))) fail('interrupted update recovery restored selection but old service health failed');
|
|
238
|
+
}
|
|
239
|
+
discardJournal(home, tx);
|
|
240
|
+
}
|
|
241
|
+
function actualWorkers(home) {
|
|
242
|
+
const file = path.join(defaultPath(home, '.config/dot-bridge'), 'workers.json');
|
|
243
|
+
let value;
|
|
244
|
+
try { value = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail(`cannot read configured workers: ${file}`); }
|
|
245
|
+
const workers = Object.keys(value?.workers ?? {}).sort();
|
|
246
|
+
if (!workers.length) fail('configured worker set is empty');
|
|
247
|
+
return workers;
|
|
248
|
+
}
|
|
249
|
+
export async function updateService({ home, check = false, yes = false, retry = false }, seams = {}) {
|
|
250
|
+
if (check && retry) fail('--retry cannot be used with --check');
|
|
251
|
+
home = path.resolve(home ?? fail('home is required'));
|
|
252
|
+
const latest = seams.latestRelease ?? defaultLatest, install = seams.installRelease ?? defaultInstall;
|
|
253
|
+
const probe = seams.probeService ?? defaultProbe, candidateProbe = seams.probeCandidate ?? defaultCandidate;
|
|
254
|
+
const control = seams.controlService ?? defaultControl, pruneVersions = seams.pruneVersions ?? prune;
|
|
255
|
+
const healthTimeoutMs = seams.healthTimeoutMs ?? HEALTH_TIMEOUT_MS;
|
|
256
|
+
if (!Number.isFinite(healthTimeoutMs) || healthTimeoutMs <= 0) fail('healthTimeoutMs must be a positive finite duration');
|
|
257
|
+
if (check) {
|
|
258
|
+
const receipt = adoptInstall(readReceipt(home).value, home), active = fs.existsSync(path.join(home, 'current')) ? fs.realpathSync(path.join(home, 'current')) : receipt.repo;
|
|
259
|
+
if (!active) fail('current service repository is missing');
|
|
260
|
+
const current = JSON.parse(fs.readFileSync(path.join(active, 'package.json'), 'utf8')).version;
|
|
261
|
+
const r = await latest(receipt); const forward = releaseVersion(r, current);
|
|
262
|
+
const result = { outcome: forward ? 'update_available' : 'up_to_date', current_version: current, latest_version: r.version };
|
|
263
|
+
if (!forward) result.outcome = 'up_to_date';
|
|
264
|
+
atomic(path.join(home, 'update-result.json'), JSON.stringify({ ...result, timestamp: new Date().toISOString() })); return result;
|
|
265
|
+
}
|
|
266
|
+
privateDir(home);
|
|
267
|
+
const releaseLock = acquireUpdateLock(home);
|
|
268
|
+
const resultFile = path.join(home, 'update-result.json');
|
|
269
|
+
let result, attempted;
|
|
270
|
+
try {
|
|
271
|
+
await recover(home, control, probe, healthTimeoutMs);
|
|
272
|
+
const { value: storedReceipt, file: receiptFile } = readReceipt(home);
|
|
273
|
+
const receipt = adoptInstall(storedReceipt, home);
|
|
274
|
+
let current = path.join(home, 'current');
|
|
275
|
+
let oldRepo = fs.existsSync(current) ? fs.realpathSync(current) : receipt.repo;
|
|
276
|
+
if (!oldRepo || !fs.existsSync(oldRepo)) fail('current service repository is missing');
|
|
277
|
+
const oldVersion = JSON.parse(fs.readFileSync(path.join(oldRepo, 'package.json'), 'utf8')).version;
|
|
278
|
+
const workers = actualWorkers(home);
|
|
279
|
+
const r = await latest(receipt), forward = releaseVersion(r, oldVersion);
|
|
280
|
+
if (!forward) { result = { outcome: 'up_to_date', current_version: oldVersion, latest_version: r.version }; return result; }
|
|
281
|
+
const failed = readFailed(home);
|
|
282
|
+
if (!retry && failed && failed.version === r.version && failed.integrity === r.dist.integrity) {
|
|
283
|
+
result = { outcome: 'skipped_failed_release', current_version: oldVersion, latest_version: r.version, failed_version: failed.version, message: `Release ${r.version} was rolled back earlier; not retrying automatically. Run dalan service update --retry to try it again.` };
|
|
284
|
+
return result;
|
|
285
|
+
}
|
|
286
|
+
attempted = r;
|
|
287
|
+
const installed = await install(home, r);
|
|
288
|
+
const candidate = path.resolve(installed), versions = path.resolve(home, 'versions');
|
|
289
|
+
if (candidate !== path.join(versions, r.version, 'node_modules', '@tnunamak', 'dalan') || !candidate.startsWith(`${versions}${path.sep}`) || fs.realpathSync(candidate) !== candidate) fail('candidate repository does not match exact package version path');
|
|
290
|
+
const packageInfo = JSON.parse(fs.readFileSync(path.join(candidate, 'package.json'), 'utf8'));
|
|
291
|
+
if (packageInfo.name !== PACKAGE || packageInfo.version !== r.version) fail('installed candidate package identity does not match registry release');
|
|
292
|
+
const base = await probe(home, receipt);
|
|
293
|
+
const configBeforeCandidate = configurationDigest(home, receipt);
|
|
294
|
+
const tested = await candidateProbe(home, receipt, candidate);
|
|
295
|
+
if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed during candidate self-check; retry update');
|
|
296
|
+
if (base.version !== oldVersion || tested.version !== r.version) fail('service probe returned an unexpected package version');
|
|
297
|
+
if (!completeCatalogs(base, tested, workers)) fail('candidate self-check failed or worker catalogs are incomplete');
|
|
298
|
+
const changedCatalog = !catalogsEqual(base, tested, workers);
|
|
299
|
+
if (changedCatalog && !yes) {
|
|
300
|
+
result = { outcome: 'connector_refresh_required', current_version: oldVersion, candidate_version: r.version, connector_refresh_required: true, message: 'Worker tool catalogs changed. Run dalan service update --yes with the same --home to switch, then refresh hosted connectors.' };
|
|
301
|
+
prune(home, oldVersion, r.version);
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
// A catalog difference requires explicit consent; exact parity may proceed without it.
|
|
305
|
+
const digestBeforeRecheck = configurationDigest(home, receipt);
|
|
306
|
+
const liveAgain = await probe(home, receipt);
|
|
307
|
+
if (liveAgain.version !== oldVersion || !catalogsEqual(base, liveAgain, workers)) fail('live worker catalog changed during update; retry after connector refresh');
|
|
308
|
+
if (configurationDigest(home, receipt) !== digestBeforeRecheck || digestBeforeRecheck !== configBeforeCandidate) fail('service configuration changed during update; retry after connector refresh');
|
|
309
|
+
const unitFile = receipt.unit ? unitPath(receipt, home) : null;
|
|
310
|
+
const txDir = path.join(home, 'update-backup'); privateDir(txDir);
|
|
311
|
+
const tx = { home, oldRepo, candidate, snapshot: path.join(txDir, 'snapshot'), unitFile, oldUnit: unitFile && fs.existsSync(unitFile) ? fs.readFileSync(unitFile, 'utf8') : null, oldCatalogs: base.catalogs, oldVersion, oldReceipt: { ...receipt }, phase: 'prepared' };
|
|
312
|
+
if (unitFile && tx.oldUnit == null) fail(`service unit is missing: ${unitFile}`);
|
|
313
|
+
atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
|
|
314
|
+
try {
|
|
315
|
+
await control(receipt, 'stop');
|
|
316
|
+
if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed while stopping; update cancelled');
|
|
317
|
+
snapshot(home, txDir);
|
|
318
|
+
if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed while preparing switch; update cancelled');
|
|
319
|
+
tx.phase = 'switched'; atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
|
|
320
|
+
atomic(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), JSON.stringify({ version: r.version, catalogs: tested.catalogs }));
|
|
321
|
+
select(home, candidate);
|
|
322
|
+
if (unitFile) rewriteUnit(unitFile, current, home);
|
|
323
|
+
await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
|
|
324
|
+
const live = await probeReady(probe, home, { ...receipt, repo: candidate }, healthTimeoutMs);
|
|
325
|
+
if (live.version !== r.version || !completeCatalogs(tested, live, workers) || !catalogsEqual(tested, live, workers)) fail('updated service health or worker catalogs failed');
|
|
326
|
+
receipt.repo = candidate; receipt.version = r.version;
|
|
327
|
+
atomic(receiptFile, JSON.stringify(receipt));
|
|
328
|
+
fs.rmSync(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), { force: true });
|
|
329
|
+
const committedTx = { ...tx, phase: 'committed' };
|
|
330
|
+
try { atomic(path.join(home, 'update-transaction.json'), JSON.stringify(committedTx)); }
|
|
331
|
+
catch (error) {
|
|
332
|
+
let journal;
|
|
333
|
+
try { journal = JSON.parse(fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8')); }
|
|
334
|
+
catch { error.preserveCandidate = true; throw error; }
|
|
335
|
+
if (journal.phase === 'committed' && journal.home === home) {
|
|
336
|
+
tx.phase = 'committed';
|
|
337
|
+
try { fs.rmSync(failedFile(home), { force: true }); } catch { /* see above */ }
|
|
338
|
+
result = { outcome: 'updated', previous_version: oldVersion, version: r.version, cleanup_warning: `committed journal is visible but its durability check failed: ${error.message}; recovery data was preserved` };
|
|
339
|
+
return result;
|
|
340
|
+
}
|
|
341
|
+
if (journal.phase !== 'switched') { error.preserveCandidate = true; throw error; }
|
|
342
|
+
throw error;
|
|
343
|
+
}
|
|
344
|
+
tx.phase = 'committed';
|
|
345
|
+
result = { outcome: 'updated', previous_version: oldVersion, version: r.version };
|
|
346
|
+
try { fs.rmSync(failedFile(home), { force: true }); } catch { /* stale record only skips the same release */ }
|
|
347
|
+
const cleanupWarnings = [];
|
|
348
|
+
try { fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); } catch (error) { cleanupWarnings.push(`transaction marker cleanup failed: ${error.message}`); }
|
|
349
|
+
try { fs.rmSync(txDir, { recursive: true, force: true }); } catch (error) { cleanupWarnings.push(`backup cleanup failed: ${error.message}`); }
|
|
350
|
+
try { pruneVersions(home, r.version, oldVersion); } catch (error) { cleanupWarnings.push(`version pruning failed: ${error.message}`); }
|
|
351
|
+
if (cleanupWarnings.length) result.cleanup_warning = cleanupWarnings.join('; ');
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (error.preserveCandidate) {
|
|
354
|
+
const uncertain = new Error(`update commit state is uncertain; candidate and recovery data were preserved: ${error.message}`);
|
|
355
|
+
uncertain.updateOutcome = 'rollback_failed';
|
|
356
|
+
throw uncertain;
|
|
357
|
+
}
|
|
358
|
+
let rollbackError;
|
|
359
|
+
try {
|
|
360
|
+
if (tx.phase === 'switched') validateSnapshot(tx);
|
|
361
|
+
await control(receipt, 'stop'); select(home, oldRepo); if (unitFile && tx.oldUnit != null) atomic(unitFile, tx.oldUnit);
|
|
362
|
+
if (tx.phase === 'switched') for (const item of ['.config', '.local']) replaceTree(path.join(txDir, 'snapshot', item), path.join(home, item));
|
|
363
|
+
await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
|
|
364
|
+
const restored = await probeReady(probe, home, { ...receipt, repo: oldRepo }, healthTimeoutMs);
|
|
365
|
+
if (restored.version !== oldVersion || !catalogsEqual(base, restored, workers)) fail('old service health verification failed');
|
|
366
|
+
fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); fs.rmSync(txDir, { recursive: true, force: true });
|
|
367
|
+
} catch (e) { rollbackError = e; }
|
|
368
|
+
if (rollbackError) { const e = new Error(`update failed: ${error.message}; rollback failed: ${rollbackError.message}`); e.updateOutcome = 'rollback_failed'; throw e; }
|
|
369
|
+
error.updateOutcome = 'rolled_back';
|
|
370
|
+
throw error;
|
|
371
|
+
}
|
|
372
|
+
return result;
|
|
373
|
+
} catch (error) {
|
|
374
|
+
result = { outcome: error.updateOutcome ?? 'failed', error: error.message };
|
|
375
|
+
if (attempted && (result.outcome === 'rolled_back' || result.outcome === 'rollback_failed')) {
|
|
376
|
+
try { atomic(failedFile(home), JSON.stringify({ version: attempted.version, integrity: attempted.dist.integrity, outcome: result.outcome, timestamp: new Date().toISOString() })); } catch { /* best effort */ }
|
|
377
|
+
}
|
|
378
|
+
throw error;
|
|
379
|
+
} finally {
|
|
380
|
+
try { if (result) atomic(resultFile, JSON.stringify({ ...result, timestamp: new Date().toISOString() })); }
|
|
381
|
+
finally { releaseLock(); }
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export function serviceStatus({ home }) {
|
|
386
|
+
home = path.resolve(home ?? fail('home is required'));
|
|
387
|
+
const { value: receipt } = readReceipt(home), current = path.join(home, 'current');
|
|
388
|
+
let version = receipt.version;
|
|
389
|
+
if (fs.existsSync(current)) version = JSON.parse(fs.readFileSync(path.join(fs.realpathSync(current), 'package.json'), 'utf8')).version;
|
|
390
|
+
let last_result = null;
|
|
391
|
+
try { last_result = JSON.parse(fs.readFileSync(path.join(home, 'update-result.json'), 'utf8')); } catch { /* no update attempt */ }
|
|
392
|
+
return { version, auto_update: receipt.auto_update ?? false, last_result, failed_release: readFailed(home)?.version ?? null };
|
|
393
|
+
}
|
package/src/service.mjs
CHANGED
|
@@ -7,10 +7,11 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
8
8
|
import { isIP } from 'node:net';
|
|
9
9
|
import { defaultPath } from './paths.mjs';
|
|
10
|
-
import { initAsFiles } from './as-files.mjs';
|
|
10
|
+
import { initAsFiles, writeAtomic } from './as-files.mjs';
|
|
11
11
|
import { parseWorkers } from './workers.mjs';
|
|
12
12
|
import { parseArgs } from '../scripts/live-trial/common.mjs';
|
|
13
13
|
import { resolveGozarCommand } from './try-exposure.mjs';
|
|
14
|
+
import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
|
|
14
15
|
|
|
15
16
|
const REPO = fileURLToPath(new URL('..', import.meta.url));
|
|
16
17
|
const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
@@ -49,10 +50,11 @@ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
|
|
|
49
50
|
function parseOptions(argv, env) {
|
|
50
51
|
const parsed = parseArgs(argv, {
|
|
51
52
|
values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
|
|
52
|
-
flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--json', '--help'],
|
|
53
|
+
flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--json', '--help'],
|
|
53
54
|
});
|
|
54
55
|
if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
|
|
55
56
|
if (parsed['--help']) return { help: true };
|
|
57
|
+
if (parsed['--auto-update'] && parsed['--no-auto-update']) fail('choose --auto-update or --no-auto-update');
|
|
56
58
|
const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
|
|
57
59
|
if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
|
|
58
60
|
const origin = parseOrigin(parsed['--public-url']);
|
|
@@ -74,7 +76,8 @@ function parseOptions(argv, env) {
|
|
|
74
76
|
const gozarBin = parsed['--gozar-bin'];
|
|
75
77
|
if (gozarBin !== undefined && (!gozarBin || gozarBin.startsWith('-'))) fail('--gozar-bin must name a command');
|
|
76
78
|
return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
|
|
77
|
-
gozarBin,
|
|
79
|
+
gozarBin, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
|
|
80
|
+
writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
|
|
78
81
|
}
|
|
79
82
|
|
|
80
83
|
function assertRealDirectoryPath(target, { owner = false } = {}) {
|
|
@@ -105,7 +108,7 @@ function nodePath(execPath) {
|
|
|
105
108
|
|
|
106
109
|
function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
|
|
107
110
|
|
|
108
|
-
function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null } = {}) {
|
|
111
|
+
function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null, recover = true } = {}) {
|
|
109
112
|
const name = unitName(home);
|
|
110
113
|
for (const [label, value] of [['home', home], ['repo', repo], ['node', node]]) {
|
|
111
114
|
if (!SAFE_PATH.test(value)) fail(`${label} contains characters that cannot be written safely in a systemd unit`);
|
|
@@ -114,6 +117,7 @@ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), pr
|
|
|
114
117
|
[`${name}.service`]: [
|
|
115
118
|
'[Unit]', 'Description=Dalan worker bridge', 'After=network-online.target', '', '[Service]',
|
|
116
119
|
`WorkingDirectory=${repo}`, `ExecStart=${node} ${path.join(repo, 'src/server.mjs')}`,
|
|
120
|
+
...(recover ? [`ExecStartPre=${node} ${path.join(repo, 'bin/dalan.mjs')} service recover --home ${home} --quiet`] : []),
|
|
117
121
|
`Environment=HOME=${home}`, 'Environment=NODE_ENV=production', 'Environment=DALAN_AUTH_MODE=builtin',
|
|
118
122
|
'Environment=DALAN_BIND_HOST=127.0.0.1', 'Environment=DALAN_GOZAR_SERVICE=1', 'Environment=DALAN_CATALOG_PROFILE=stable',
|
|
119
123
|
`Environment=DALAN_ENABLE_WORKSPACE=${o.enableWorkspace ? '1' : '0'}`, `Environment=DALAN_ENABLE_T3_TOOLS=${o.enableT3 ? '1' : '0'}`,
|
|
@@ -204,7 +208,7 @@ function checkHomeScope(home, configDir, o, workers) {
|
|
|
204
208
|
if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
|
|
205
209
|
const rootEntries = fs.readdirSync(home);
|
|
206
210
|
if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
|
|
207
|
-
const rootAllowed = ['.config', '.local', '.tmp', 'resource-url'];
|
|
211
|
+
const rootAllowed = ['.config', '.local', '.tmp', 'resource-url', 'current', 'versions', 'update-result.json', 'update-failed.json', 'update-transaction.json', 'update-backup', 'update-lock.sqlite', 'update-lock.sqlite-journal'];
|
|
208
212
|
if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
|
|
209
213
|
if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
|
|
210
214
|
const configRoot = path.join(home, '.config');
|
|
@@ -221,6 +225,7 @@ function checkHomeScope(home, configDir, o, workers) {
|
|
|
221
225
|
const receiptFile = path.join(configDir, 'service-install.json');
|
|
222
226
|
const entries = fs.readdirSync(configDir);
|
|
223
227
|
const hasReceipt = entries.includes('service-install.json');
|
|
228
|
+
if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url'].includes(name))) fail(`${home} contains update data without a service receipt`);
|
|
224
229
|
if (hasReceipt) {
|
|
225
230
|
const info = fs.lstatSync(receiptFile);
|
|
226
231
|
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
|
|
@@ -351,13 +356,33 @@ export async function installService(o, seams = {}) {
|
|
|
351
356
|
const configDir = path.dirname(profile.file);
|
|
352
357
|
const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
|
|
353
358
|
const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
|
|
354
|
-
const
|
|
359
|
+
const repo = seams.repo ?? REPO, node = seams.node ?? nodePath(process.execPath);
|
|
360
|
+
const receiptFile = homeScope.receiptFile;
|
|
361
|
+
const previous = homeScope.hasReceipt ? JSON.parse(fs.readFileSync(receiptFile, 'utf8')) : null;
|
|
362
|
+
const autoUpdate = o.autoUpdate ?? previous?.auto_update ?? !homeScope.hasReceipt;
|
|
363
|
+
const current = path.join(o.home, 'current');
|
|
364
|
+
const hasCurrent = fs.existsSync(current) || (() => { try { fs.lstatSync(current); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } })();
|
|
365
|
+
if (hasCurrent && !fs.lstatSync(current).isSymbolicLink()) fail(`${current} must be the service package symlink`);
|
|
366
|
+
const { files, enable, name } = unitFiles(o, { home: o.home, repo: current, node, proxy });
|
|
367
|
+
const updateUnits = autoUpdateUnits({ home: o.home, unit: name, node });
|
|
368
|
+
Object.assign(files, updateUnits.files);
|
|
369
|
+
let replaceLegacyUnit = false;
|
|
355
370
|
// Check every collision before creating the bridge home or the first unit file.
|
|
356
371
|
for (const [filename, text] of Object.entries(files)) {
|
|
357
372
|
const file = path.join(unitDir, filename);
|
|
358
|
-
if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text))
|
|
373
|
+
if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) {
|
|
374
|
+
const actual = fs.lstatSync(file).isFile() ? fs.readFileSync(file, 'utf8') : '';
|
|
375
|
+
const oldRepo = actual.match(/^WorkingDirectory=(.+)$/m)?.[1];
|
|
376
|
+
const oldNode = actual.match(/^ExecStart=(\S+) /m)?.[1];
|
|
377
|
+
const expected = filename === `${name}.service` && previous && oldRepo && oldNode && SAFE_PATH.test(oldRepo) && SAFE_PATH.test(oldNode)
|
|
378
|
+
? unitFiles(o, { home: o.home, repo: oldRepo, node: oldNode, proxy, recover: false }).files[filename] : null;
|
|
379
|
+
// Only the exact former generated unit can be enrolled or retried after interruption.
|
|
380
|
+
if (expected && actual === expected) replaceLegacyUnit = true;
|
|
381
|
+
else fail(`${file} already exists with different contents; refusing to overwrite it`);
|
|
382
|
+
}
|
|
359
383
|
}
|
|
360
384
|
if (o.writeUnitsOnly) {
|
|
385
|
+
if (replaceLegacyUnit) fail('rerun without --write-units-only to enroll an existing service for updates');
|
|
361
386
|
writeUnits(unitDir, files);
|
|
362
387
|
return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
|
|
363
388
|
}
|
|
@@ -366,14 +391,25 @@ export async function installService(o, seams = {}) {
|
|
|
366
391
|
: resolveGozarCommand({ env, resolveBundled: seams.resolveBundled, which: seams.which });
|
|
367
392
|
if (!gozar.binary) fail('Gozar is unavailable; reinstall @tnunamak/dalan with its dependencies, or install gozar on PATH or set GOZAR_BIN to an executable path, then retry service install.');
|
|
368
393
|
assertGozarStatePath(env);
|
|
394
|
+
const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
|
|
369
395
|
const spawn = seams.spawn ?? spawnSync;
|
|
370
396
|
runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
|
|
371
397
|
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
372
|
-
if (!homeScope.hasReceipt) writePrivate(
|
|
398
|
+
if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate }, null, 2)}\n`);
|
|
399
|
+
if (!hasCurrent) fs.symlinkSync(repo, current);
|
|
373
400
|
const homeFiles = prepareHome(o, profile);
|
|
401
|
+
if (needsEnrollmentRestart) {
|
|
402
|
+
writeAtomic(receiptFile, `${JSON.stringify({ ...previous, repo: previous.repo ?? repo, node, unit_dir: unitDir, auto_update: autoUpdate, enrollment_pending: true }, null, 2)}\n`);
|
|
403
|
+
}
|
|
404
|
+
if (replaceLegacyUnit) {
|
|
405
|
+
const file = path.join(unitDir, `${name}.service`), mode = fs.statSync(file).mode & 0o777;
|
|
406
|
+
writeAtomic(file, files[`${name}.service`]);
|
|
407
|
+
fs.chmodSync(file, mode);
|
|
408
|
+
}
|
|
374
409
|
writeUnits(unitDir, files);
|
|
375
410
|
runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
|
|
376
411
|
runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
|
|
412
|
+
if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
|
|
377
413
|
const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
|
|
378
414
|
const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
|
|
379
415
|
if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
|
|
@@ -389,9 +425,15 @@ export async function installService(o, seams = {}) {
|
|
|
389
425
|
if (routeReply.route.verification?.status !== 'verified') {
|
|
390
426
|
fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
|
|
391
427
|
}
|
|
428
|
+
await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn });
|
|
429
|
+
if (needsEnrollmentRestart) {
|
|
430
|
+
const enrolled = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
|
|
431
|
+
delete enrolled.enrollment_pending;
|
|
432
|
+
writeAtomic(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
|
|
433
|
+
}
|
|
392
434
|
return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
|
|
393
435
|
workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
|
|
394
|
-
target: o.target.value, started: true, route: routeReply.route };
|
|
436
|
+
target: o.target.value, started: true, route: routeReply.route, auto_update: autoUpdate };
|
|
395
437
|
}
|
|
396
438
|
|
|
397
439
|
export async function serviceMain(argv, seams = {}) {
|
|
@@ -400,11 +442,40 @@ export async function serviceMain(argv, seams = {}) {
|
|
|
400
442
|
const { migrationMain } = await import('./service-migrate-workers.mjs');
|
|
401
443
|
return migrationMain(args);
|
|
402
444
|
}
|
|
445
|
+
if (action === 'recover') {
|
|
446
|
+
const parsed = parseArgs(args, { values: ['--home'], flags: ['--quiet', '--help'] });
|
|
447
|
+
if (parsed['--help']) return serviceMain(['help'], seams);
|
|
448
|
+
if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
|
|
449
|
+
const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
|
|
450
|
+
const { recoverService } = await import('./service-update.mjs');
|
|
451
|
+
const result = recoverService({ home });
|
|
452
|
+
if (!parsed['--quiet']) (seams.out ?? console.log)(JSON.stringify(result));
|
|
453
|
+
return result;
|
|
454
|
+
}
|
|
455
|
+
if (['update', 'status', 'auto-update'].includes(action)) {
|
|
456
|
+
const parsed = parseArgs(args, { values: ['--home'], flags: ['--check', '--yes', '--retry', '--json', '--help'] });
|
|
457
|
+
if (parsed['--help']) return serviceMain(['help'], seams);
|
|
458
|
+
const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
|
|
459
|
+
let result;
|
|
460
|
+
if (action === 'auto-update') {
|
|
461
|
+
if (parsed._.length !== 1 || !['on', 'off'].includes(parsed._[0]) || parsed['--check'] || parsed['--yes'] || parsed['--retry']) fail('use dalan service auto-update on|off [--home DIR]');
|
|
462
|
+
result = await setAutoUpdate({ home, enabled: parsed._[0] === 'on' }, seams);
|
|
463
|
+
} else {
|
|
464
|
+
if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
|
|
465
|
+
if (parsed['--check'] && parsed['--retry']) fail('--check cannot be used with --retry');
|
|
466
|
+
if (parsed['--check'] && parsed['--yes']) fail('--check cannot be used with --yes');
|
|
467
|
+
if (action === 'status' && (parsed['--check'] || parsed['--yes'] || parsed['--retry'])) fail('service status does not accept --check, --yes or --retry');
|
|
468
|
+
const updater = await import('./service-update.mjs');
|
|
469
|
+
result = await updater[action === 'status' ? 'serviceStatus' : 'updateService']({ home, check: !!parsed['--check'], yes: !!parsed['--yes'], retry: !!parsed['--retry'] }, seams);
|
|
470
|
+
}
|
|
471
|
+
(seams.out ?? console.log)(parsed['--json'] ? JSON.stringify(result) : JSON.stringify(result, null, 2));
|
|
472
|
+
return result;
|
|
473
|
+
}
|
|
403
474
|
if (action === 'help' || action === '--help' || !action) {
|
|
404
|
-
(seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]');
|
|
475
|
+
(seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]\n dalan service update [--check|--yes] [--retry] [--home DIR] [--json]\n dalan service auto-update on|off [--home DIR]\n dalan service status [--home DIR] [--json]\n dalan service recover --home DIR [--quiet]\nNew installs check daily with jitter. Catalog changes stage until --yes authorizes a connector refresh. --check reports availability without installing. Linux systemd only.');
|
|
405
476
|
return null;
|
|
406
477
|
}
|
|
407
|
-
if (action !== 'install') fail('use dalan service install
|
|
478
|
+
if (action !== 'install') fail('use dalan service install, update, auto-update, status, recover or migrate-workers');
|
|
408
479
|
const o = parseOptions(args, seams.env ?? process.env);
|
|
409
480
|
if (o.help) return serviceMain(['help'], seams);
|
|
410
481
|
const result = await installService(o, seams);
|