@finogeeks2026/finshield-kilo 0.0.0-stage → 0.11.1-debug.1

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.
@@ -0,0 +1,296 @@
1
+ // Fixed native owners decide installation, authorization and process identity.
2
+ // Startup keeps or wraps. Running Restart replaces Main through the same updater.
3
+ export function createUpdater({ports,startup}) {
4
+ const clients=new Map(),sessions=new Map(),tasks=new Map(),operations=new Set(),requests=new Set();
5
+ let sequence=0,draining=false,startupReleased=false,mainRetained=false,finish;
6
+ const closed=new Promise(resolve=>{finish=resolve;});
7
+ const wait=ports.wait??(()=>new Promise(done=>setTimeout(done,2000)));
8
+ const resource=b=>JSON.stringify([b.installationResource??b.installation,b.configurationResource??b.configuration,b.profile]);
9
+ const taskKey=b=>JSON.stringify([resource(b),b.requestedRelease]);
10
+ const failure=error=>error.result??{phase:error.authority==='uac_cancelled'?'cancelled':'failed',error:error.message};
11
+ const pending=s=>s?.phase!=='ready'||(Number.isInteger(s.exit_code)&&s.exit_code!==0);
12
+ const active=s=>s?.authorization_in_progress===true;
13
+ const readyAuth=s=>s?.prepared===true&&!pending(s)&&!active(s);
14
+ function tracked(binding,operation) {
15
+ const work={binding};operations.add(work);
16
+ work.promise=Promise.resolve().then(operation).finally(()=>operations.delete(work));
17
+ work.promise.catch(()=>{});return work.promise;
18
+ }
19
+ function status(value) {
20
+ const session=value.session,task=session.task??value.task;
21
+ const state=task?.satisfied&&value.binding.protected?{phase:'protected'}:session.attempt?.state??task?.state;
22
+ const result=value.result??state??{phase:session.startupError?'failed':'starting'};
23
+ const error=[result.error,session.startupError].filter(Boolean).join('; ');
24
+ return {...result,...(error?{error}:{}),
25
+ currentProtected:value.binding.protected===true,currentRelease:session.currentRelease,requestedRelease:task?.binding.requestedRelease??value.binding.requestedRelease,
26
+ reminderDismissed:task?.dismissed===true,reminderId:task?.id,
27
+ restartPolicy:session.attempt||state?.phase!=='ready'||task?.satisfied?'never':task?.restartPolicy??'confirm'};
28
+ }
29
+ function sessionFor(binding) {
30
+ let session=sessions.get(binding.mainKey)??[...sessions.values()].find(current=>current.wrapping);
31
+ if(!session) {
32
+ session={mainKey:binding.mainKey,binding,mainBinding:binding,bindings:new Set(),items:new Map(),closed:false,wrapping:false};
33
+ sessions.set(binding.mainKey,session);
34
+ }
35
+ session.binding=binding;
36
+ if(session.attempt&&!session.attempt.transition&&session.attempt.state.phase==='completed')session.attempt=undefined;
37
+ return session;
38
+ }
39
+ async function observe(task,binding,initial,{update=false}={}) {
40
+ let state=initial;
41
+ while(active(state)) {
42
+ task.state={...state,phase:update?'waiting-authorization':'authorizing'};
43
+ await wait();
44
+ state=await ports.preparation(binding);
45
+ }
46
+ return state;
47
+ }
48
+ async function wrapRestart(session,target,onStopped) {
49
+ session.wrapping=true;
50
+ try {
51
+ await ports.wrap(target,mainKey=>{
52
+ // retain_replacement updates this target's native Binding. Host rebinds
53
+ // create independent native owners and must not replace lifecycle ownership.
54
+ session.mainBinding=target;
55
+ if(mainKey&&mainKey!==session.mainKey) {
56
+ sessions.delete(session.mainKey);
57
+ session.mainKey=mainKey;sessions.set(mainKey,session);
58
+ for(const value of clients.values())if(value.session===session&&value.binding.mainKey!==mainKey)value.released=true;
59
+ }
60
+ },onStopped);
61
+ mainRetained=true;
62
+ } finally {session.wrapping=false;}
63
+ await ports.watchMain?.(session.mainBinding);
64
+ }
65
+ function restart(session) {
66
+ const task=session.task,target=task?.target;
67
+ const attempt={state:{phase:'restarting'},transition:true};session.attempt=attempt;
68
+ attempt.promise=tracked(session.binding,async()=>{
69
+ let mainStopped=false;
70
+ try {
71
+ await wrapRestart(session,target,()=>{mainStopped=true;});
72
+ session.currentRelease=target.requestedRelease;
73
+ if(task){task.satisfied=true;task.restartPolicy='never';}
74
+ attempt.state={phase:'completed'};
75
+ } catch(error){
76
+ attempt.state=failure(error);ports.report?.(error,target,'restart');
77
+ if(mainStopped)stop();
78
+ }
79
+ finally{attempt.transition=false;}
80
+ });
81
+ return {accepted:true};
82
+ }
83
+ async function assess(task,session,value) {
84
+ try {
85
+ const b=session.binding,release=b.requestedRelease;
86
+ if(!/^\d+\.\d+\.\d+$/.test(release))throw Error('A requested stable native release is required');
87
+ task.target=await ports.select(b,release);
88
+ const current=await ports.installation(b);
89
+ session.currentRelease=current?.version;
90
+ task.update=Boolean(current&&current.version!==release);
91
+ const alreadyProtected=b.protected&&current?.version===release&&resource(task.target)===resource(b);
92
+ if(alreadyProtected) {
93
+ task.state={phase:'protected'};task.satisfied=true;task.restartPolicy='never';return;
94
+ }
95
+ const installed=await ports.installation(task.target);
96
+ const needsSetup=!installed||installed.version!==release;
97
+ if(needsSetup) {
98
+ task.state={phase:'downloading'};
99
+ task.download=new AbortController();
100
+ task.staged=await ports.stage(task.target,release,task.download.signal);task.download=undefined;
101
+ if(draining||session.closed||!await ports.mainAlive(b))return;
102
+ // Observe existing authorization before a conflicting native mutation.
103
+ if(task.update)await observe(task,b,await ports.preparation(b),{update:true});
104
+ if(draining||session.closed||!await ports.mainAlive(b))return;
105
+ task.state={phase:'installing'};
106
+ const setup=await ports.install(task.target,release,task.staged);
107
+ if(setup.phase!=='completed'){task.state=setup;return;}
108
+ await ports.selected?.(b,task.target);
109
+ }
110
+ if(draining||session.closed||!await ports.mainAlive(b))return;
111
+ const acknowledgment=await ports.prepare(task.target);
112
+ if(acknowledgment.completion) {
113
+ task.owner=tracked(task.target,()=>acknowledgment.completion);
114
+ }
115
+ if(task.previous&&!pending(acknowledgment)&&acknowledgment.accepted!==true) {
116
+ task.id=task.previous.id;task.dismissed=task.previous.dismissed;
117
+ }
118
+ task.state=pending(acknowledgment)?{...acknowledgment}:{phase:'starting',progress:acknowledgment.progress};delete task.state.completion;
119
+ let state=acknowledgment;
120
+ if(active(state)) {
121
+ if(acknowledgment.accepted&&task.owner) {
122
+ let terminal,terminalError;
123
+ task.owner.then(result=>{terminal=result;},error=>{terminalError=error;});
124
+ while(active(state)&&!terminal&&!terminalError) {
125
+ await Promise.race([wait(), task.owner]);
126
+ if(terminal||terminalError)break;
127
+ state=await ports.preparation(task.target);
128
+ if(!active(state))break;
129
+ task.state=pending(state)?state:{phase:'authorizing',progress:state.progress};
130
+ }
131
+ if(terminalError)throw terminalError;
132
+ if(terminal)state=terminal;
133
+ } else state=await observe(task,task.target,state);
134
+ }
135
+ if(task.owner)await task.owner;
136
+ if(draining||session.closed){task.state=state;return;}
137
+ if(!readyAuth(state)){task.state=state;return;}
138
+ const selected=await ports.installation(task.target);
139
+ if(selected?.version!==release)throw Error('Selected target installation is unavailable at the requested release');
140
+ task.restartPolicy='confirm';
141
+ task.state={...state,phase:'ready',reason:task.update?'update':needsSetup?'install':'authorization'};
142
+ } catch(error){task.state=failure(error);ports.report?.(error,task.target??session.binding,'prepare');}
143
+ finally{task.done=true;}
144
+ }
145
+ function stop() {
146
+ draining=true;
147
+ for(const session of new Set(sessions.values()))session.closed=true;
148
+ for(const task of tasks.values())task.download?.abort();
149
+ finish();
150
+ }
151
+ async function drain() {
152
+ stop();
153
+ for(;;) {
154
+ const work=[...requests,...operations].map(item=>item.promise??item);
155
+ if(!work.length)break;
156
+ await Promise.allSettled(work);
157
+ }
158
+ for(const session of new Set(sessions.values()))for(const binding of session.bindings) {
159
+ await ports.detach(binding);
160
+ }
161
+ if(startup&&!startupReleased){startupReleased=true;await ports.detach(startup);}
162
+ }
163
+ async function beginAssessment(value) {
164
+ const {binding,session}=value;
165
+ if(value.task||session.attempt)return {accepted:true};
166
+ const key=taskKey(binding),retained=session.items.get(key);
167
+ if(retained){value.task=retained;session.task=retained;return {accepted:true};}
168
+ let task=tasks.get(taskKey(binding));
169
+ if(!task||task.done) {
170
+ const ownInstall=binding.installationResource??binding.installation;
171
+ const ownConfig=binding.configurationResource??binding.configuration;
172
+ if([...tasks.values()].some(t=>!t.done&&((t.binding.installationResource??t.binding.installation)===ownInstall
173
+ ||(t.binding.configurationResource??t.binding.configuration)===ownConfig)&&resource(t.binding)!==resource(binding)))
174
+ throw Error('Selected installation/configuration conflict with active native work');
175
+ const previous=session.task?.done&&session.task.state.phase==='ready'
176
+ &&session.task.binding.requestedRelease===binding.requestedRelease?session.task:undefined;
177
+ task={id:String(++sequence),previous,binding,state:{phase:'starting'},restartPolicy:'never',done:false};
178
+ tasks.set(taskKey(binding),task);
179
+ task.promise=tracked(binding,()=>assess(task,session,value));
180
+ }
181
+ value.task=task;session.task=task;session.items.set(key,task);return {accepted:true};
182
+ }
183
+ return {
184
+ closed,
185
+ running:()=>mainRetained||[...sessions.values()].some(session=>session.keep),
186
+ async admit(binding) {
187
+ if(mainRetained) {
188
+ if(!sessions.has(binding.mainKey))throw Error('Updater already owns another DSH Main');
189
+ return {period:'running'};
190
+ }
191
+ const session=sessionFor(binding);
192
+ if(session.keep)return {period:'running'};
193
+ if(!/^\d+\.\d+\.\d+$/.test(binding.requestedRelease))throw Error('A requested stable native release is required');
194
+ let target,shouldWrap=false;
195
+ try {
196
+ if(!binding.protected) {
197
+ target=await ports.select(binding,binding.requestedRelease);
198
+ const installed=await ports.installation(target);
199
+ shouldWrap=installed?.version===binding.requestedRelease&&readyAuth(await ports.preparation(target));
200
+ }
201
+ } catch(error) {
202
+ session.startupError=error.message;
203
+ ports.report?.(error,target??binding,'startup_readiness');
204
+ }
205
+ if(shouldWrap) {
206
+ let decision,rejectAdmission;
207
+ const admission=new Promise((resolve,reject)=>{decision=resolve;rejectAdmission=reject;});
208
+ void tracked(binding,async()=>{
209
+ try {await wrapRestart(session,target,()=>decision({period:'wrap'}));}
210
+ catch(error) {
211
+ ports.report?.(error,target,'wrap');
212
+ session.wrapping=false;
213
+ if(await ports.mainAlive(startup??binding)) {
214
+ session.keep=true;session.startupError=error.message;
215
+ decision({period:'keep',error:error.message});
216
+ } else {decision({period:'wrap'});stop();}
217
+ }
218
+ }).catch(rejectAdmission);
219
+ return admission;
220
+ }
221
+ session.keep=true;
222
+ return {period:'keep',...(session.startupError?{error:session.startupError}:{})};
223
+ },
224
+ async keep(binding) {
225
+ const session=sessions.get(binding.mainKey);
226
+ if(!session?.keep||binding.protected)throw Error('No ordinary Keep decision for this Main');
227
+ return {kept:true};
228
+ },
229
+ async bind(peer) {
230
+ const binding=await ports.bind(peer),id=String(++sequence);
231
+ const session=sessionFor(binding);
232
+ session.bindings.add(binding);session.binding=binding;
233
+ clients.set(id,{binding,session,released:false});return id;
234
+ },
235
+ request(id,operation,fields={}) {
236
+ const request=(async()=>{
237
+ if(Object.keys(fields).length)throw Error('Unknown operation fields');
238
+ if(!['status','ensure','restart','later','restore','release','uninstall'].includes(operation))throw Error('Unknown operation');
239
+ const value=clients.get(id);
240
+ if(!value||value.released)throw Error('Unknown client binding');
241
+ const {binding,session}=value;
242
+ if(operation==='status')return status(value);
243
+ if(operation==='restart')return restart(session);
244
+ if(operation==='restore'||operation==='release') {
245
+ if(operation==='release')value.released=true;
246
+ const pendingWork=[session.attempt?.transition&&session.attempt.promise,
247
+ session.task&&!session.task.done&&session.task.promise].filter(Boolean);
248
+ if(pendingWork.length&&operation==='release') {
249
+ void tracked(binding,async()=>{await Promise.allSettled(pendingWork);await ports.restore(binding);}).catch(error=>ports.report?.(error));
250
+ return {released:true,cleanupPending:true};
251
+ }
252
+ await tracked(binding,async()=>{await Promise.allSettled(pendingWork);await ports.restore(binding);});
253
+ return operation==='release'?{released:true}:{restored:true};
254
+ }
255
+ if(draining||session.closed)throw Error('Updater is draining');
256
+ if(!await ports.alive(binding))throw Error('Bound DSH process departed');
257
+ if(operation==='ensure') {
258
+ value.ensureIntent=true;
259
+ return beginAssessment(value);
260
+ }
261
+ if(operation==='later') {
262
+ const task=session.task??value.task;
263
+ if(!task||status(value).phase!=='ready')throw Error('No current restart reminder');
264
+ task.dismissed=true;return {dismissed:true};
265
+ }
266
+ if(operation==='uninstall') {
267
+ if(binding.protected)throw Error('Native uninstall requires an ordinary session');
268
+ if([...operations].some(work=>resource(work.binding)===resource(binding)))throw Error('Native operation conflict');
269
+ try {await ports.restore(binding);}
270
+ catch(error){ports.report?.(error,binding,'uninstall_cleanup');}
271
+ void tracked(binding,async()=>{try{const result=await ports.uninstall(binding);
272
+ value.result={phase:result?.code?'failed':'completed',nativeUninstall:result};}
273
+ catch(error){value.result=failure(error);}});
274
+ return {accepted:true};
275
+ }
276
+ })();
277
+ if(operation==='status')return request;
278
+ requests.add(request);return request.finally(()=>requests.delete(request));
279
+ },
280
+ async observeMainExits() {
281
+ if(draining)return true;
282
+ const current=[...new Set(sessions.values())];
283
+ if(!current.length){if(startup&&!await ports.mainAlive(startup)){stop();return true;}return false;}
284
+ for(const session of current) {
285
+ if(session.wrapping)continue;
286
+ if(!await ports.mainAlive(session.mainBinding))session.closed=true;
287
+ }
288
+ if(current.every(session=>session.closed||session.wrapping)) {
289
+ if(current.every(session=>session.wrapping))return false;
290
+ stop();return true;
291
+ }
292
+ return false;
293
+ },
294
+ stop,drain,
295
+ };
296
+ }
@@ -0,0 +1,89 @@
1
+ import {cpSync, existsSync, mkdirSync, mkdtempSync, renameSync, readFileSync} from 'node:fs';
2
+ import {join, dirname} from 'node:path';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {createRequire} from 'node:module';
5
+ import {nativeAdapter} from './native.js';
6
+ import {requestBytes} from './protocol.js';
7
+ import {windowsNative} from '../src/native.mjs';
8
+ import {replacementArgs} from '../src/arguments.mjs';
9
+ import {release, pluginVersion} from '../src/lifecycle-settings.mjs';
10
+
11
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));
12
+ export function stageUpdater(settings) {
13
+ const stage = join(settings.runtimeRoot, pluginVersion);
14
+ if (!existsSync(stage)) {
15
+ mkdirSync(settings.runtimeRoot, {recursive: true});
16
+ const temporary = mkdtempSync(join(settings.runtimeRoot, '.stage-'));
17
+ for (const name of ['src', 'updater', 'install', 'policy', 'bin', 'package.json'])
18
+ cpSync(join(packageRoot, name), join(temporary, name), {recursive: true, dereference: true});
19
+ const require = createRequire(join(packageRoot, 'package.json'));
20
+ for (const name of ['koffi', `@koromix/koffi-${process.platform}-${process.arch}`])
21
+ cpSync(dirname(require.resolve(name)), join(temporary, 'node_modules', name), {recursive: true, dereference: true});
22
+ try {renameSync(temporary, stage);} catch (error) {if (!existsSync(stage)) throw error;}
23
+ }
24
+ return stage;
25
+ }
26
+
27
+ export function copyClientSupport(settings) {
28
+ if (!settings.clientSupportDirectory) throw Error('Kilo did not provide its writable state directory');
29
+ const support = join(settings.clientSupportDirectory, pluginVersion);
30
+ mkdirSync(join(support, 'bin'), {recursive: true});
31
+ const dll = join(support, 'bin', 'finshield_kilo_native.dll');
32
+ if (!existsSync(dll)) cpSync(join(packageRoot, 'bin', 'finshield_kilo_native.dll'), dll);
33
+ return support;
34
+ }
35
+ export async function hostConnections(settings, dependencies = {}) {
36
+ const native = dependencies.native ?? windowsNative(), identity = native.currentIdentity();
37
+ let support;
38
+ if (identity.appContainer) {
39
+ support = (dependencies.copyClientSupport ?? copyClientSupport)(settings);
40
+ } else support = (dependencies.stageUpdater ?? stageUpdater)(settings);
41
+ const stage = support, call = dependencies.call ?? nativeAdapter(support, {require: createRequire(join(packageRoot, 'package.json'))});
42
+ const context = {desktop: process.execPath, home: settings.stateDirectory,
43
+ installation: settings.installation, configuration: settings.configuration, requestedRelease: release,
44
+ nativeVersionRoot: settings.nativeVersionRoot, configurationVersionRoot: settings.configurationVersionRoot,
45
+ pluginRoot: packageRoot, cliRoot: dirname(process.execPath), cwd: process.cwd(), args: replacementArgs(process.argv.slice(2), process.cwd())};
46
+ let client;
47
+ const request = async (operation, fields = {}, options = {}) => {
48
+ const message = {protocol: 1, operation, ...fields};requestBytes(message);
49
+ const response = await call({action: 'request', request: message, ...options});
50
+ if (!response.ok) throw Error(response.error);
51
+ if (operation === 'bind') client = response.value.client;
52
+ return response.value;
53
+ };
54
+ const connection = {request, context};
55
+ const admit = async deadline => {
56
+ await request('hello', {}, {deadline});
57
+ const decision = await request('admit', {context}, {deadline});
58
+ connection.period = decision.period;connection.admitted = true;connection.startupError = decision.error;
59
+ };
60
+ return {async existing() {await request('hello');return connection;},
61
+ async uninstall() {if (!client) throw Error('FinShield is not bound');return request('uninstall', {client});},
62
+ async obtain() {
63
+ mkdirSync(settings.stateDirectory, {recursive: true});
64
+ const old = await call({action: 'open_updater_job'});
65
+ if (old.job) {
66
+ try {await admit(Date.now() + 10000);await call({action: 'close_updater_job', job: old.job});return connection;}
67
+ catch {await call({action: 'recover_updater_job', job: old.job});}
68
+ }
69
+ {
70
+ const attempt = mkdtempSync(join(settings.stateDirectory, 'startup-'));
71
+ const deadline = Date.now() + 10000;
72
+ const handoff = JSON.stringify({settings, context, original: identity, deadline, logs: attempt});
73
+ const child = native.launch({executable: process.execPath,
74
+ args: [join(stage, 'updater', 'server.mjs'), handoff], cwd: process.cwd(),
75
+ env: {...process.env, BUN_BE_BUN: '1', KILO_CLI_INSTALL_ROOT: context.cliRoot,
76
+ KILO_PLUGIN_INSTALL_ROOT: context.pluginRoot, KILO_PLUGIN_RUNTIME_ROOT: settings.runtimeRoot}}, {visible: settings.visible});
77
+ try {await admit(deadline);}
78
+ catch (error) {
79
+ await child.stop();let detail = error.message;
80
+ const report = join(attempt, 'startup-error.json');
81
+ if (existsSync(report)) {try {detail = JSON.parse(readFileSync(report, 'utf8')).error ?? detail;} catch { /* Keep the actual connection error if diagnostics are unreadable. */ }}
82
+ throw Error(`${detail}\nLogs: ${attempt}`);
83
+ }
84
+ finally {child.close();}
85
+ }
86
+ return connection;
87
+ },
88
+ };
89
+ }
@@ -0,0 +1,28 @@
1
+ import {createRequire} from 'node:module';
2
+ import {join} from 'node:path';
3
+ import {randomUUID} from 'node:crypto';
4
+
5
+ export function nativeAdapter(root, {require = createRequire(join(root, 'package.json'))} = {}) {
6
+ const koffi = require('koffi');
7
+ const library = koffi.load(join(root, 'bin', 'finshield_kilo_native.dll'));
8
+ const invoke = library.func('void* finshield_kilo_call(str input)');
9
+ const free = library.func('void finshield_kilo_free(void* value)');
10
+ const callbackType = koffi.proto(`void FinShieldKiloExit_${randomUUID().replaceAll('-', '')}(void)`);
11
+ const decode = pointer => {try {const result = JSON.parse(koffi.decode(pointer, 'char', -1));
12
+ if (!result.ok) throw Error(result.error);return result.value;} finally {free(pointer);}};
13
+ const call = request => new Promise((resolve, reject) => {
14
+ const input = JSON.stringify(request);
15
+ if (Buffer.byteLength(input) > 16384) return reject(Error('Native request exceeds 16 KiB'));
16
+ invoke.async(input, (error, pointer) => {if (error) return reject(error);
17
+ try {resolve(decode(pointer));} catch (error) {reject(error);}});
18
+ });
19
+ call.watchMain = (request, onExit) => {
20
+ const callback = koffi.register(onExit, koffi.pointer(callbackType));
21
+ const watch = library.func('void* finshield_kilo_watch_main(str input, void* callback)');
22
+ let observer;
23
+ try {observer = decode(watch(JSON.stringify(request), callback)).observer;}
24
+ catch (error) {koffi.unregister(callback);throw error;}
25
+ return async () => {await call({action: 'unwatch_main', observer});koffi.unregister(callback);};
26
+ };
27
+ return call;
28
+ }
@@ -0,0 +1,40 @@
1
+ export const protocol=1;
2
+ export const operations=['hello','bind','admit','keep','status','ensure','restart','later','restore','release','uninstall'];
3
+ // Full per-path diagnostics stay with native owners, outside bounded IPC frames.
4
+ export function projectState(value) {
5
+ if(typeof value?.phase!=='string'||value.phase.length>64) throw Error('Invalid native phase');
6
+ const result={phase:value.phase,restartPolicy:value.restartPolicy};
7
+ for(const name of ['currentProtected','authorizationPending','reminderDismissed'])if(typeof value[name]==='boolean')result[name]=value[name];
8
+ for(const name of ['currentRelease','requestedRelease','reason','reminderId'])if(typeof value[name]==='string')result[name]=value[name];
9
+ if(value.error) result.error=String(value.error).slice(0,2048);
10
+ if(value.authorization) {
11
+ result.authorization={};
12
+ for(const name of ['phase','prepared','authorization_in_progress','exit_code'])
13
+ if(value.authorization[name]!==undefined)result.authorization[name]=value.authorization[name];
14
+ if(value.authorization.error)result.authorization.error=String(value.authorization.error).slice(0,2048);
15
+ }
16
+ if(value.progress) {
17
+ const percent=value.progress.overall_percent??null;
18
+ if(percent!==null&&(typeof percent!=='number'||!Number.isFinite(percent))) throw Error('Invalid native percentage');
19
+ result.progress={overall_percent:percent};
20
+ }
21
+ for(const name of ['prepared','authorization_in_progress']) if(typeof value[name]==='boolean') result[name]=value[name];
22
+ if(value.nativeSetup) result.nativeSetup={code:value.nativeSetup.code,phase:value.nativeSetup.phase};
23
+ if(value.nativeUninstall) result.nativeUninstall={code:value.nativeUninstall.code};
24
+ return result;
25
+ }
26
+ export function validateRequest(value) {
27
+ if(!value||typeof value!=='object'||Array.isArray(value)) throw Error('Invalid updater request');
28
+ if(value.protocol!==undefined&&!Number.isSafeInteger(value.protocol)) throw Error('Invalid updater framing label');
29
+ if(!operations.includes(value.operation)) throw Error('Unknown updater operation');
30
+ const allowed=['hello','bind','admit','keep'].includes(value.operation)?(value.operation==='hello'?['protocol','operation']:['protocol','operation','context']):['protocol','operation','client'];
31
+ if(Object.keys(value).some(key=>!allowed.includes(key))) throw Error('Unknown updater request fields');
32
+ if(!['hello','bind','admit','keep'].includes(value.operation)&&typeof value.client!=='string') throw Error('Missing updater client binding');
33
+ return value;
34
+ }
35
+ export function requestBytes(value) {
36
+ validateRequest(value);
37
+ const bytes=Buffer.from(JSON.stringify(value)+'\n');
38
+ if(bytes.length>16384) throw Error('Updater frame exceeds 16 KiB');
39
+ return bytes;
40
+ }
@@ -0,0 +1,143 @@
1
+ import {readFileSync, appendFileSync, writeFileSync} from 'node:fs';
2
+ import {join} from 'node:path';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {createUpdater} from './coordinator.js';
6
+ import {nativeAdapter} from './native.js';
7
+ import {validateRequest, projectState} from './protocol.js';
8
+ import {windowsNative} from '../src/native.mjs';
9
+ import {buildLaunch} from '../src/handoff.mjs';
10
+ import {createPreparationObserver, prepareRuntime} from '../src/preparation.js';
11
+ import {nativeDesktopChild, submitDesktopAuthorization} from '../src/connector.js';
12
+ import {stageRuntime, installRuntime} from '../install/runtime.js';
13
+
14
+ // The creator's Windows command line carries bootstrap inputs; no writable plan file.
15
+ const bootstrap = JSON.parse(process.argv[2]), logs = bootstrap.logs;
16
+ const root = fileURLToPath(new URL('../', import.meta.url)), call = nativeAdapter(root), native = windowsNative();
17
+ const version = JSON.parse(readFileSync(join(root, 'package.json'))).version;
18
+ const record = event => {try {appendFileSync(join(logs, 'events.jsonl'), JSON.stringify({at: Date.now(), ...event}) + '\n');}
19
+ catch (error) {process.stderr.write(`FinShield diagnostic: ${error.message}\n`);}};
20
+ let startup;
21
+ try {startup = await call({action: 'initialize_session_job', ...bootstrap.original, deadline: bootstrap.deadline});}
22
+ catch (error) {writeFileSync(join(logs, 'startup-error.json'), JSON.stringify({error: error.message}));throw error;}
23
+ record({phase: 'coordinator', ...native.currentIdentity()});
24
+ const observations = createPreparationObserver(), clients = new Map(), roots = new Map();
25
+ let updater, unwatch, exiting = false, replacement, protectedListener;
26
+ const bound = (b, action, fields = {}) => {
27
+ const previous = b.queue.pending ?? Promise.resolve();
28
+ const current = previous.catch(() => {}).then(() => call({action, native: b.native, ...fields}));
29
+ b.queue.pending = current;return current;
30
+ };
31
+ const report = (error, _binding, operation = 'lifecycle') => {record({phase: 'failed', operation, error: error.message});process.stderr.write(`FinShield ${operation}: ${error.message}\n`);};
32
+ const settingsFor = c => ({installation: c.installation, configuration: c.configuration,
33
+ executable: join(c.installation, 'finsafe.exe'), yamlPath: join(c.configuration, 'effective.yaml'),
34
+ stateDirectory: bootstrap.settings.stateDirectory, downloads: bootstrap.settings.downloadRoot, localAppData: bootstrap.settings.localAppData});
35
+ const ports = {
36
+ bind: async b => b,
37
+ alive: b => bound(b, 'alive'),
38
+ mainAlive: b => b.native ? bound(b, 'main_alive') : call({action: 'startup_main_alive', startup: b.startup}),
39
+ installation: b => bound(b, 'installation', {selected: b.selected === true}),
40
+ async select(b, release) {const target = await bound(b, 'select_target', {release, ...b.roots, downloads: bootstrap.settings.downloadRoot});
41
+ return {...b, ...target, selected: true, settings: {...b.settings, ...target}};},
42
+ stage: (b, release, signal) => stageRuntime(b.settings.downloads, release, {signal}),
43
+ async install(b, release, staged) {
44
+ const candidate = await bound(b, 'stage_configuration'), previous = await bound(b, 'setup_inputs');
45
+ const setup = await installRuntime(b.settings.downloads, release, {...b.settings, ...candidate, ...previous, staged,
46
+ execute: request => call({action: 'run_setup', request})});
47
+ b.retainedWorker = setup.retainedWorker;
48
+ return {phase: setup.rebootRequired ? 'reboot-required' : 'completed', nativeSetup: {code: setup.exitCode}};
49
+ },
50
+ async selected(_b, target) {
51
+ observations.invalidate(target.settings);
52
+ if ((await bound(target, 'target_identity')).changed) throw Error('Changing the FinSAFE security domain is unsupported');
53
+ writeFileSync(join(bootstrap.settings.stateDirectory, 'selected.json'), JSON.stringify({installation: target.installation, configuration: target.configuration}));
54
+ },
55
+ async prepare(b) {
56
+ const acknowledgment = await prepareRuntime({...b.settings, retainedWorker: b.retainedWorker}, {
57
+ run: (executable, args, options) => submitDesktopAuthorization(executable, args, {...options,
58
+ spawnChild: () => nativeDesktopChild({start: () => bound(b, 'authorization_start', {retainedWorker: b.retainedWorker}),
59
+ read: owner => call({action: 'authorization_read', owner})})})});
60
+ b.retainedWorker = undefined;observations.publish(b.settings, acknowledgment);
61
+ acknowledgment.completion?.then(value => observations.publish(b.settings, value)).catch(() => {});
62
+ return acknowledgment;
63
+ },
64
+ preparation: b => observations.read(b.settings),
65
+ ready: async () => {}, restore: b => bound(b, 'restore'),
66
+ async detach(b) {await b.queue?.pending?.catch(() => {});await call(b.native ? {action: 'detach', native: b.native} : {action: 'detach_startup_main', startup: b.startup});},
67
+ async watchMain(b) {
68
+ await unwatch?.();
69
+ unwatch = call.watchMain(b.native ? {native: b.native} : {startup: b.startup}, () => {
70
+ if (!exiting) void updater.observeMainExits().catch(error => {report(error);finish(1);});
71
+ });
72
+ },
73
+ async wrap(b, observeReplacement, onStopped) {
74
+ if (replacement) throw Error('Kilo replacement is already active');
75
+ await (protectedListener ??= listen(true));
76
+ let resolveReplacement;
77
+ const connected = new Promise(resolve => {resolveReplacement = resolve;});
78
+ replacement = {binding: b, connected: resolveReplacement};
79
+ try {
80
+ const launch = buildLaunch({original: bootstrap.original, kilo: b.context.desktop, args: b.context.args,
81
+ cwd: b.context.cwd, finsafe: b.settings.executable, yamlPath: b.settings.yamlPath}, process.env);
82
+ await bound(b, 'stop_main');onStopped?.();record({phase: 'original-exited'});
83
+ record({phase: 'self-confine-launch', executable: launch.executable, cwd: launch.cwd});
84
+ const supervisor = native.launch(launch, {inheritConsole: true, breakaway: true});
85
+ record({phase: 'supervisor-started', pid: supervisor.pid, created: supervisor.created});
86
+ const completion = supervisor.wait().finally(() => supervisor.close());completion.catch(() => {});
87
+ const peer = await Promise.race([connected, completion.then(code => {throw Error(`FinSAFE exited before protected Kilo bound (${code})`);})]);
88
+ const retained = await bound(b, 'adopt_replacement', {replacement: peer.native, supervisor: supervisor.pid});
89
+ observeReplacement(retained.mainKey);record({phase: 'protected-bound', mainKey: retained.mainKey});
90
+ // The coordinator follows the exact retained Kilo handle. The supervisor owns confinement.
91
+ completion.then(code => {record({phase: 'supervisor-exited', exitCode: code});if (code) report(Error(`FinSAFE exited (${code})`));}).catch(report);
92
+ } catch (error) {
93
+ report(error, b, 'restart');native.showError(`${error.message}\nLogs: ${logs}`);throw error;
94
+ } finally {replacement = undefined;}
95
+ },
96
+ report,
97
+ uninstall: b => bound(b, 'run_uninstall'),
98
+ };
99
+ updater = createUpdater({ports, startup});
100
+ await ports.watchMain(startup);
101
+ updater.closed.then(() => finish(0));
102
+ async function finish(code) {
103
+ if (exiting) return;exiting = true;
104
+ await unwatch?.();await updater.drain();record({phase: 'coordinator-exited', exitCode: code});
105
+ writeFileSync(join(logs, 'result.json'), JSON.stringify({exitCode: code}));process.exit(code);
106
+ }
107
+ async function materialize(message, context) {
108
+ const value = await call({action: 'bind', connection: message.connection, context});
109
+ const c = value.context;
110
+ if (!value.protected) roots.set(value.profile, {nativeVersionRoot: c.nativeVersionRoot, configurationVersionRoot: c.configurationVersionRoot});
111
+ const trusted = roots.get(value.profile);if (!trusted) throw Error('No ordinary-bound version roots for this profile');
112
+ return {...value, ...c, context: c, settings: settingsFor(c), roots: trusted, queue: {}};
113
+ }
114
+ async function dispatch(message) {
115
+ const request = validateRequest(message.request);
116
+ if (request.operation === 'hello') return {version, protocol: 1};
117
+ if (['admit', 'keep', 'bind'].includes(request.operation)) {
118
+ const b = await materialize(message, request.context);
119
+ if (request.operation === 'admit') return updater.admit(b);
120
+ if (request.operation === 'keep') return updater.keep(b);
121
+ if (b.protected && replacement) replacement.connected(b);
122
+ const id = await updater.bind(b), client = randomUUID();clients.set(client, {id, peer: message.peer});return {client};
123
+ }
124
+ const client = clients.get(request.client);
125
+ if (!client || client.peer !== message.peer) throw Error('Kilo client binding differs');
126
+ try {const value = await updater.request(client.id, request.operation);return request.operation === 'status' ? projectState(value) : value;}
127
+ finally {if (request.operation === 'release') clients.delete(request.client);}
128
+ }
129
+ async function listen(container) {
130
+ const server = await call({action: 'server', container});
131
+ void (async () => {for (;;) {
132
+ let message;
133
+ try {message = await call({action: 'receive', server: server.server});}
134
+ catch (error) {report(error);if (error.message.includes('updater listener')) {await finish(1);return;}continue;}
135
+ if (!message) continue;
136
+ void (async () => {
137
+ let response;try {response = {ok: true, value: await dispatch(message)};}
138
+ catch (error) {response = {ok: false, error: error.message.slice(0, 2048)};}
139
+ try {await call({action: 'reply', connection: message.connection, response});} catch (error) {report(error);}
140
+ })();
141
+ }})().catch(error => {report(error);void finish(1);});
142
+ }
143
+ await listen(false);