@intflow/gateflowctl 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/gateflowctl.js +4 -0
- package/catalog.json +242 -0
- package/package.json +31 -4
- package/src/cli.js +178 -0
- package/updater/errors.js +10 -0
- package/updater/files.js +134 -0
- package/updater/runtime-store.js +206 -0
- package/updater/runtime.js +353 -0
- package/updater/updates.js +99 -0
- package/README.md +0 -3
package/catalog.json
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"group": "gateway",
|
|
4
|
+
"name": "summary",
|
|
5
|
+
"summary": "Show the gateway summary.",
|
|
6
|
+
"role": "admin",
|
|
7
|
+
"mutates": false,
|
|
8
|
+
"args": [],
|
|
9
|
+
"options": [],
|
|
10
|
+
"route": "/api/summary"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
"group": "gateway",
|
|
14
|
+
"name": "health",
|
|
15
|
+
"summary": "Check gateway dependencies and health.",
|
|
16
|
+
"role": "admin",
|
|
17
|
+
"mutates": false,
|
|
18
|
+
"args": [],
|
|
19
|
+
"options": [],
|
|
20
|
+
"route": "/api/health"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"group": "gateway",
|
|
24
|
+
"name": "activity",
|
|
25
|
+
"summary": "List recent console activity.",
|
|
26
|
+
"role": "admin",
|
|
27
|
+
"mutates": false,
|
|
28
|
+
"args": [],
|
|
29
|
+
"options": [],
|
|
30
|
+
"route": "/api/dashboard-activity"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"group": "services",
|
|
34
|
+
"name": "list",
|
|
35
|
+
"summary": "List registered services.",
|
|
36
|
+
"role": "admin",
|
|
37
|
+
"mutates": false,
|
|
38
|
+
"args": [],
|
|
39
|
+
"options": [],
|
|
40
|
+
"route": "/api/services"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"group": "nodes",
|
|
44
|
+
"name": "list",
|
|
45
|
+
"summary": "List registered nodes.",
|
|
46
|
+
"role": "admin",
|
|
47
|
+
"mutates": false,
|
|
48
|
+
"args": [],
|
|
49
|
+
"options": [],
|
|
50
|
+
"route": "/api/nodes"
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"group": "policies",
|
|
54
|
+
"name": "list",
|
|
55
|
+
"summary": "List runtime policies and allowlist groups.",
|
|
56
|
+
"role": "admin",
|
|
57
|
+
"mutates": false,
|
|
58
|
+
"args": [],
|
|
59
|
+
"options": [],
|
|
60
|
+
"route": "/api/runtime/policies"
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
"group": "dns",
|
|
64
|
+
"name": "namespaces",
|
|
65
|
+
"summary": "Inspect DNS coverage and namespaces.",
|
|
66
|
+
"role": "admin",
|
|
67
|
+
"mutates": false,
|
|
68
|
+
"args": [],
|
|
69
|
+
"options": [],
|
|
70
|
+
"route": "/api/runtime/dns-namespaces"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"group": "certificates",
|
|
74
|
+
"name": "list",
|
|
75
|
+
"summary": "List certificate metadata.",
|
|
76
|
+
"role": "admin",
|
|
77
|
+
"mutates": false,
|
|
78
|
+
"args": [],
|
|
79
|
+
"options": [],
|
|
80
|
+
"route": "/api/certificates"
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"group": "traffic",
|
|
84
|
+
"name": "summary",
|
|
85
|
+
"summary": "Read aggregated traffic.",
|
|
86
|
+
"role": "admin",
|
|
87
|
+
"mutates": false,
|
|
88
|
+
"args": [],
|
|
89
|
+
"options": [],
|
|
90
|
+
"route": "/api/traffic"
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
"group": "traffic",
|
|
94
|
+
"name": "quotas",
|
|
95
|
+
"summary": "Read traffic quota decisions.",
|
|
96
|
+
"role": "admin",
|
|
97
|
+
"mutates": false,
|
|
98
|
+
"args": [],
|
|
99
|
+
"options": [],
|
|
100
|
+
"route": "/api/traffic/quotas"
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
"group": "registry",
|
|
104
|
+
"name": "generated",
|
|
105
|
+
"summary": "Inspect generated routing configuration.",
|
|
106
|
+
"role": "admin",
|
|
107
|
+
"mutates": false,
|
|
108
|
+
"args": [],
|
|
109
|
+
"options": [],
|
|
110
|
+
"route": "/api/generated"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"group": "changes",
|
|
114
|
+
"name": "history",
|
|
115
|
+
"summary": "Read gateway apply history.",
|
|
116
|
+
"role": "admin",
|
|
117
|
+
"mutates": false,
|
|
118
|
+
"args": [],
|
|
119
|
+
"options": [],
|
|
120
|
+
"route": "/api/apply-history"
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
"group": "changes",
|
|
124
|
+
"name": "readiness",
|
|
125
|
+
"summary": "Check apply readiness.",
|
|
126
|
+
"role": "admin",
|
|
127
|
+
"mutates": false,
|
|
128
|
+
"args": [],
|
|
129
|
+
"options": [],
|
|
130
|
+
"route": "/api/apply-readiness"
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
"group": "gateway",
|
|
134
|
+
"name": "evidence",
|
|
135
|
+
"summary": "List operational evidence.",
|
|
136
|
+
"role": "admin",
|
|
137
|
+
"mutates": false,
|
|
138
|
+
"args": [],
|
|
139
|
+
"options": [],
|
|
140
|
+
"route": "/api/evidence"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"group": "services",
|
|
144
|
+
"name": "get",
|
|
145
|
+
"summary": "Show a service and its routing.",
|
|
146
|
+
"role": "admin",
|
|
147
|
+
"mutates": false,
|
|
148
|
+
"args": [
|
|
149
|
+
"service_id"
|
|
150
|
+
],
|
|
151
|
+
"options": []
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
"group": "nodes",
|
|
155
|
+
"name": "get",
|
|
156
|
+
"summary": "Show a node and its services.",
|
|
157
|
+
"role": "admin",
|
|
158
|
+
"mutates": false,
|
|
159
|
+
"args": [
|
|
160
|
+
"node_id"
|
|
161
|
+
],
|
|
162
|
+
"options": []
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
"group": "nodes",
|
|
166
|
+
"name": "history",
|
|
167
|
+
"summary": "Read node status history.",
|
|
168
|
+
"role": "admin",
|
|
169
|
+
"mutates": false,
|
|
170
|
+
"args": [
|
|
171
|
+
"node_id"
|
|
172
|
+
],
|
|
173
|
+
"options": []
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
"group": "changes",
|
|
177
|
+
"name": "revision",
|
|
178
|
+
"summary": "Read a redacted revision record.",
|
|
179
|
+
"role": "admin",
|
|
180
|
+
"mutates": false,
|
|
181
|
+
"args": [
|
|
182
|
+
"revision_id"
|
|
183
|
+
],
|
|
184
|
+
"options": []
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
"group": "changes",
|
|
188
|
+
"name": "preview",
|
|
189
|
+
"summary": "Preview a runtime proposal and return a signed ten-minute receipt.",
|
|
190
|
+
"role": "admin",
|
|
191
|
+
"mutates": false,
|
|
192
|
+
"args": [
|
|
193
|
+
"proposal"
|
|
194
|
+
],
|
|
195
|
+
"options": []
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
"group": "changes",
|
|
199
|
+
"name": "apply",
|
|
200
|
+
"summary": "Submit the exact reviewed proposal once. Use APPLY followed by its request ID.",
|
|
201
|
+
"role": "admin",
|
|
202
|
+
"mutates": true,
|
|
203
|
+
"args": [
|
|
204
|
+
"proposal",
|
|
205
|
+
"receipt",
|
|
206
|
+
"confirmation"
|
|
207
|
+
],
|
|
208
|
+
"options": []
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
"group": "changes",
|
|
212
|
+
"name": "status",
|
|
213
|
+
"summary": "Read the status of an operation owned by this administrator.",
|
|
214
|
+
"role": "admin",
|
|
215
|
+
"mutates": false,
|
|
216
|
+
"args": [
|
|
217
|
+
"operation_id"
|
|
218
|
+
],
|
|
219
|
+
"options": []
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
"group": "nodes",
|
|
223
|
+
"name": "rotate",
|
|
224
|
+
"summary": "Request browser-confirmed pull-token recovery for a node.",
|
|
225
|
+
"role": "admin",
|
|
226
|
+
"mutates": true,
|
|
227
|
+
"args": [
|
|
228
|
+
"node_id",
|
|
229
|
+
"request_id"
|
|
230
|
+
],
|
|
231
|
+
"options": []
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
"group": "",
|
|
235
|
+
"name": "whoami",
|
|
236
|
+
"summary": "Show the calling operator and access level.",
|
|
237
|
+
"role": "admin",
|
|
238
|
+
"mutates": false,
|
|
239
|
+
"args": [],
|
|
240
|
+
"options": []
|
|
241
|
+
}
|
|
242
|
+
]
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intflow/gateflowctl",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "GateFlow operator CLI",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"bin": {
|
|
8
|
+
"gateflowctl": "bin/gateflowctl.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"updater",
|
|
14
|
+
"catalog.json"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=22"
|
|
18
|
+
},
|
|
19
|
+
"intflow": {
|
|
20
|
+
"cliUpdateProtocol": 1
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"test": "node --test test/*.test.js"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/yeon3724/gateflow.git",
|
|
28
|
+
"directory": "console/operator_cli"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { readFile, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { privateDirectory, readPrivate, writePrivate } from "../updater/files.js";
|
|
7
|
+
import { VERSION } from "../updater/updates.js";
|
|
8
|
+
|
|
9
|
+
const catalog = JSON.parse(await readFile(new URL("../catalog.json", import.meta.url), "utf8"));
|
|
10
|
+
const defaultOrigin = "https://console.gateflow.intflow.dev";
|
|
11
|
+
const usage = "gateflowctl <group> <command> [--argument value] [-o table|json]\n" +
|
|
12
|
+
"gateflowctl login | logout | whoami | access create|list|revoke | commands | update\n" +
|
|
13
|
+
"Supply --proposal as JSON or @filename. Run commands for the complete catalog.";
|
|
14
|
+
|
|
15
|
+
class Failure extends Error {
|
|
16
|
+
constructor(status, code, message, hint = "") {
|
|
17
|
+
super(message);
|
|
18
|
+
this.payload = { status, code, message, hint };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function invalid(message) { throw new Failure(400, "usage", message); }
|
|
23
|
+
|
|
24
|
+
function origin() {
|
|
25
|
+
const url = new URL(process.env.GATEFLOW_URL || defaultOrigin);
|
|
26
|
+
if (url.username || url.password || url.href !== url.origin + "/" ||
|
|
27
|
+
!(url.protocol === "https:" || (url.protocol === "http:" && ["127.0.0.1","[::1]","localhost"].includes(url.hostname)))) {
|
|
28
|
+
invalid("GATEFLOW_URL must be an HTTPS origin or a loopback HTTP origin.");
|
|
29
|
+
}
|
|
30
|
+
return url.origin;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const configDir = join(process.env.APPDATA || process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "gateflowctl");
|
|
34
|
+
const credentialFile = join(configDir, "credentials.json");
|
|
35
|
+
|
|
36
|
+
async function savedToken(base) {
|
|
37
|
+
const raw = await readPrivate(credentialFile);
|
|
38
|
+
if (!raw) return "";
|
|
39
|
+
const saved = JSON.parse(raw);
|
|
40
|
+
return saved.origin === base ? saved.token : "";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function request(base, path, token, body) {
|
|
44
|
+
if (!token) throw new Failure(401, "sign_in_required", "Run gateflowctl login or set GATEFLOW_TOKEN.");
|
|
45
|
+
const response = await fetch(base + path, {
|
|
46
|
+
method:"POST", redirect:"error", signal:AbortSignal.timeout(35000),
|
|
47
|
+
headers:{"Authorization":"Bearer " + token,"Content-Type":"application/json","X-GateFlow-CLI-Version":VERSION},
|
|
48
|
+
body:JSON.stringify(body),
|
|
49
|
+
});
|
|
50
|
+
const data = await response.json();
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
const error = data.error || {};
|
|
53
|
+
throw new Failure(response.status, error.code || "request_failed", error.message || "Request failed.", error.hint || "");
|
|
54
|
+
}
|
|
55
|
+
return data;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function login(base) {
|
|
59
|
+
const token = "gatecli_" + randomBytes(32).toString("base64url");
|
|
60
|
+
const challenge = createHash("sha256").update(token).digest("hex");
|
|
61
|
+
const response = await fetch(base + "/api/operator/login", {
|
|
62
|
+
method:"POST",redirect:"error",signal:AbortSignal.timeout(10000),
|
|
63
|
+
headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge}),
|
|
64
|
+
});
|
|
65
|
+
if (!response.ok) throw new Failure(response.status,"login_failed","Could not start sign-in.");
|
|
66
|
+
const {expires,code,proof} = await response.json();
|
|
67
|
+
process.stderr.write("Sign in to GateFlow, then open " + base + "/operator#login/" + expires + "/" + challenge + "/" + proof +
|
|
68
|
+
"\nEnter the code shown here: " + code + "\n");
|
|
69
|
+
while (Date.now() < expires * 1000) {
|
|
70
|
+
try {
|
|
71
|
+
await request(base, "/api/operator/call", token, {name:"gateflow_whoami",arguments:{}});
|
|
72
|
+
await privateDirectory(configDir);
|
|
73
|
+
const temp = join(configDir, ".credentials-" + randomUUID());
|
|
74
|
+
try {
|
|
75
|
+
await writePrivate(temp, JSON.stringify({origin:base,token}));
|
|
76
|
+
await rename(temp, credentialFile);
|
|
77
|
+
} finally {
|
|
78
|
+
await unlink(temp).catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
79
|
+
}
|
|
80
|
+
return {signed_in:true};
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.payload?.status !== 401) throw error;
|
|
83
|
+
}
|
|
84
|
+
await delay(2500);
|
|
85
|
+
}
|
|
86
|
+
throw new Failure(401, "approval_expired", "Sign-in approval expired.");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function parse(argv) {
|
|
90
|
+
const words = [], opts = {};
|
|
91
|
+
let output = "table";
|
|
92
|
+
for (let i = 0; i < argv.length; i++) {
|
|
93
|
+
const arg = argv[i];
|
|
94
|
+
if (arg === "--json") output = "json";
|
|
95
|
+
else if (arg === "-o" || arg === "--output") output = argv[++i];
|
|
96
|
+
else if (arg.startsWith("--")) {
|
|
97
|
+
const key = arg.slice(2).replaceAll("-", "_");
|
|
98
|
+
if (Object.hasOwn(opts, key) || i + 1 >= argv.length) invalid("Invalid option: " + arg);
|
|
99
|
+
Object.defineProperty(opts,key,{value:argv[++i],enumerable:true});
|
|
100
|
+
} else words.push(arg);
|
|
101
|
+
}
|
|
102
|
+
if (!["json","table"].includes(output)) invalid("Expected -o table or -o json.");
|
|
103
|
+
return {words,opts,output};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function exactFields(opts, names) {
|
|
107
|
+
if (Object.keys(opts).length !== names.length || !names.every(name => Object.hasOwn(opts,name))) {
|
|
108
|
+
invalid("Expected options: " + names.map(name => "--" + name.replaceAll("_","-")).join(" "));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function command(words, opts) {
|
|
113
|
+
const name = words.join(" ");
|
|
114
|
+
if (name === "commands") { exactFields(opts,[]); return catalog; }
|
|
115
|
+
const base = origin();
|
|
116
|
+
if (name === "login") { exactFields(opts,[]); return login(base); }
|
|
117
|
+
const token = process.env.GATEFLOW_TOKEN || await savedToken(base);
|
|
118
|
+
if (name === "logout") {
|
|
119
|
+
exactFields(opts,[]);
|
|
120
|
+
const saved = await savedToken(base);
|
|
121
|
+
if (saved) {
|
|
122
|
+
const me = await request(base,"/api/operator/call",saved,{name:"gateflow_whoami",arguments:{}}).catch(error => {
|
|
123
|
+
if (error.payload?.status !== 401) throw error;
|
|
124
|
+
});
|
|
125
|
+
if (me) await request(base,"/api/operator/access",saved,{action:"revoke",id:me.key_id});
|
|
126
|
+
await unlink(credentialFile);
|
|
127
|
+
}
|
|
128
|
+
return {signed_out:true};
|
|
129
|
+
}
|
|
130
|
+
if (words[0] === "access") {
|
|
131
|
+
const actions = {"access create":["issue",["name","access"]],"access list":["list",[]],"access revoke":["revoke",["id"]]};
|
|
132
|
+
const action = actions[name];
|
|
133
|
+
if (!action) invalid("Unknown access command.");
|
|
134
|
+
exactFields(opts,action[1]);
|
|
135
|
+
return request(base,"/api/operator/access",token,{...opts,action:action[0]});
|
|
136
|
+
}
|
|
137
|
+
const item = catalog.find(row => [row.group,row.name].filter(Boolean).join(" ") === name);
|
|
138
|
+
if (!item) invalid("Unknown command. Run gateflowctl commands.");
|
|
139
|
+
exactFields(opts,item.args);
|
|
140
|
+
const args = {...opts};
|
|
141
|
+
if (item.args.includes("proposal")) {
|
|
142
|
+
const text = opts.proposal.startsWith("@") ? await readFile(opts.proposal.slice(1),"utf8") : opts.proposal;
|
|
143
|
+
try { args.proposal = JSON.parse(text); } catch { invalid("Expected valid proposal JSON."); }
|
|
144
|
+
}
|
|
145
|
+
return request(base,"/api/operator/call",token,{name:["gateflow",item.group,item.name].filter(Boolean).join("_"),arguments:args});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function commandHelp(argv) {
|
|
149
|
+
const topic = argv.filter(arg => !["help","--help","-h"].includes(arg)).join(" ");
|
|
150
|
+
const entries = catalog.filter(row => {
|
|
151
|
+
const name = [row.group,row.name].filter(Boolean).join(" ");
|
|
152
|
+
return !topic || topic === row.group || topic === name;
|
|
153
|
+
});
|
|
154
|
+
const lines = entries.map(row => {
|
|
155
|
+
const args = row.args.map(key => "--" + key.replaceAll("_","-") + " <" + key + ">");
|
|
156
|
+
return " " + [row.group,row.name,...args].filter(Boolean).join(" ") + "\n " + row.summary;
|
|
157
|
+
});
|
|
158
|
+
return [usage,...lines].join("\n");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export async function main(argv) {
|
|
162
|
+
try {
|
|
163
|
+
if (argv.includes("--version") || argv.includes("-V")) { process.stdout.write(VERSION + "\n"); return 0; }
|
|
164
|
+
if (!argv.length || argv.includes("--help") || argv.includes("-h") || argv[0] === "help") {
|
|
165
|
+
process.stdout.write(commandHelp(argv) + "\n"); return 0;
|
|
166
|
+
}
|
|
167
|
+
const {words,opts,output} = parse(argv);
|
|
168
|
+
const data = await command(words,opts);
|
|
169
|
+
if (output === "json") process.stdout.write(JSON.stringify(data) + "\n");
|
|
170
|
+
else console.table(data);
|
|
171
|
+
return 0;
|
|
172
|
+
} catch (error) {
|
|
173
|
+
const detail = error.payload || {status:500,code:"client_error",message:"The request or local credential operation failed.",hint:"Check the URL, server and local file permissions."};
|
|
174
|
+
process.stderr.write(JSON.stringify({error:detail}) + "\n");
|
|
175
|
+
if (detail.code === "usage") return 2;
|
|
176
|
+
return [401,403,426].includes(detail.status) ? 3 : 1;
|
|
177
|
+
}
|
|
178
|
+
}
|
package/updater/files.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { lstat, mkdir, open } from "node:fs/promises";
|
|
3
|
+
import { dirname, parse, resolve, sep } from "node:path";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { UpdateError } from "./errors.js";
|
|
7
|
+
const run = promisify(execFile);
|
|
8
|
+
export function installerEnvironment() {
|
|
9
|
+
const allowed = /^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|HOME|USERPROFILE|LOCALAPPDATA|APPDATA|TEMP|TMP|TMPDIR|LANG|LC_ALL)$/i;
|
|
10
|
+
return {
|
|
11
|
+
...Object.fromEntries(Object.entries(process.env).filter(([key])=>allowed.test(key))),
|
|
12
|
+
INTFLOW_CLI_RUNTIME_ACTIVE: "1",
|
|
13
|
+
INTFLOW_CLI_AUTO_UPDATE: "0"
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function isMissing(error) {
|
|
17
|
+
return error?.code === "ENOENT";
|
|
18
|
+
}
|
|
19
|
+
export async function checkPath(path) {
|
|
20
|
+
const absolute = resolve(path);
|
|
21
|
+
let current = parse(absolute).root;
|
|
22
|
+
for (const part of absolute.slice(current.length).split(sep).filter(Boolean)){
|
|
23
|
+
if (process.platform === "win32" && (part.includes(":") || /[. ]$/.test(part))) throw new UpdateError("UNSAFE_PATH");
|
|
24
|
+
current = resolve(current, part);
|
|
25
|
+
try {
|
|
26
|
+
if ((await lstat(current)).isSymbolicLink()) throw new UpdateError("UNSAFE_PATH");
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (!isMissing(error)) throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export async function windowsAcl(path, protect = false, directory = false, runner = run) {
|
|
33
|
+
const rights = directory ? "(OI)(CI)(F)" : "(F)";
|
|
34
|
+
const change = protect ? `$tool=Join-Path $env:SYSTEMROOT 'System32\\icacls.exe'; & $tool $p /setowner ('*'+$s.Value) /q | Out-Null; if ($LASTEXITCODE -ne 0) {throw 'owner'}; & $tool $p /reset /q | Out-Null; if ($LASTEXITCODE -ne 0) {throw 'reset'}; & $tool $p /inheritance:r /grant:r ('*'+$s.Value+':${rights}') /q | Out-Null; if ($LASTEXITCODE -ne 0) {throw 'access'};` : "";
|
|
35
|
+
const script = `$ErrorActionPreference='Stop'; $p=$env:INTFLOW_CLI_ACL_PATH; $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $i=Get-Item -LiteralPath $p -Force; if (($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {throw 'path'}; ${change} $a=Get-Acl -LiteralPath $p; if ($a.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $s.Value -or -not $a.AreAccessRulesProtected) {throw 'owner'}; $r=$a.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]); if ($r.Count -eq 0) {throw 'empty'}; foreach($v in $r) {if ($v.IdentityReference.Value -ne $s.Value -or $v.AccessControlType -ne 'Allow') {throw 'access'}}`;
|
|
36
|
+
try {
|
|
37
|
+
await runner("powershell.exe", [
|
|
38
|
+
"-NoProfile",
|
|
39
|
+
"-NonInteractive",
|
|
40
|
+
"-WindowStyle",
|
|
41
|
+
"Hidden",
|
|
42
|
+
"-EncodedCommand",
|
|
43
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
44
|
+
], {
|
|
45
|
+
windowsHide: true,
|
|
46
|
+
timeout: 10000,
|
|
47
|
+
maxBuffer: 4096,
|
|
48
|
+
env: {
|
|
49
|
+
...installerEnvironment(),
|
|
50
|
+
INTFLOW_CLI_ACL_PATH: path
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
} catch {
|
|
54
|
+
throw new UpdateError("UNSAFE_ACL");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export const access = {
|
|
58
|
+
windowsAcl
|
|
59
|
+
};
|
|
60
|
+
export async function verifyDirectory(path, created = false) {
|
|
61
|
+
await checkPath(path);
|
|
62
|
+
const value = await lstat(path);
|
|
63
|
+
if (!value.isDirectory() || value.isSymbolicLink()) throw new UpdateError("UNSAFE_PATH");
|
|
64
|
+
if (process.platform === "win32") await access.windowsAcl(path, created, true);
|
|
65
|
+
else if ((value.mode & 0o077) !== 0 || value.uid !== process.getuid?.()) throw new UpdateError("UNSAFE_PATH");
|
|
66
|
+
}
|
|
67
|
+
export async function privateDirectory(path) {
|
|
68
|
+
path = resolve(path);
|
|
69
|
+
await checkPath(path);
|
|
70
|
+
const missing = [];
|
|
71
|
+
let current = path;
|
|
72
|
+
for(;;){
|
|
73
|
+
try {
|
|
74
|
+
await lstat(current);
|
|
75
|
+
break;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (!isMissing(error)) throw error;
|
|
78
|
+
}
|
|
79
|
+
missing.push(current);
|
|
80
|
+
current = dirname(current);
|
|
81
|
+
}
|
|
82
|
+
for (const item of missing.reverse()){
|
|
83
|
+
let created = false;
|
|
84
|
+
try {
|
|
85
|
+
await mkdir(item, {
|
|
86
|
+
mode: 0o700
|
|
87
|
+
});
|
|
88
|
+
created = true;
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (error.code !== "EEXIST") throw error;
|
|
91
|
+
}
|
|
92
|
+
await verifyDirectory(item, created);
|
|
93
|
+
}
|
|
94
|
+
if (!missing.length) await verifyDirectory(path);
|
|
95
|
+
}
|
|
96
|
+
export async function readPrivate(path, maximum = 8192) {
|
|
97
|
+
await checkPath(path);
|
|
98
|
+
try {
|
|
99
|
+
const info = await lstat(path);
|
|
100
|
+
if (!info.isFile() || info.nlink > 1) throw new UpdateError("INVALID_RECORD");
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (isMissing(error)) return;
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
let handle;
|
|
106
|
+
try {
|
|
107
|
+
handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (isMissing(error)) return;
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const value = await handle.stat();
|
|
114
|
+
if (!value.isFile() || value.nlink > 1 || value.size > maximum) throw new UpdateError("INVALID_RECORD");
|
|
115
|
+
if (process.platform === "win32") await access.windowsAcl(path);
|
|
116
|
+
else if ((value.mode & 0o077) !== 0 || value.uid !== process.getuid?.()) throw new UpdateError("UNSAFE_PATH");
|
|
117
|
+
const text = await handle.readFile("utf8");
|
|
118
|
+
if (Buffer.byteLength(text) > maximum) throw new UpdateError("INVALID_RECORD");
|
|
119
|
+
return text;
|
|
120
|
+
} finally{
|
|
121
|
+
await handle.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export async function writePrivate(path, value) {
|
|
125
|
+
await checkPath(path);
|
|
126
|
+
const handle = await open(path, "wx", 0o600);
|
|
127
|
+
try {
|
|
128
|
+
if (process.platform === "win32") await access.windowsAcl(path, true);
|
|
129
|
+
await handle.writeFile(value, "utf8");
|
|
130
|
+
await handle.sync();
|
|
131
|
+
} finally{
|
|
132
|
+
await handle.close();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstat, readFile, readdir, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { checkPath, privateDirectory, readPrivate, verifyDirectory, writePrivate } from "./files.js";
|
|
6
|
+
import { engineCompatible, packageName, parts, VERSION } from "./updates.js";
|
|
7
|
+
import { UpdateError } from "./errors.js";
|
|
8
|
+
export { packageName } from "./updates.js";
|
|
9
|
+
export const root = join(process.env.LOCALAPPDATA ?? process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "intflow-cli", packageName, `npm-${process.platform}-${process.arch}-${process.versions.node.split(".")[0]}`);
|
|
10
|
+
export async function record(folder, name) {
|
|
11
|
+
const text = await readPrivate(join(folder, name));
|
|
12
|
+
if (text === undefined) return;
|
|
13
|
+
const value = JSON.parse(text);
|
|
14
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new UpdateError("INVALID_RECORD");
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export async function save(folder, name, value) {
|
|
18
|
+
await privateDirectory(folder);
|
|
19
|
+
await readPrivate(join(folder, name));
|
|
20
|
+
const temporary = join(folder, ".record-" + randomUUID());
|
|
21
|
+
try {
|
|
22
|
+
await writePrivate(temporary, JSON.stringify(value));
|
|
23
|
+
await rename(temporary, join(folder, name));
|
|
24
|
+
} finally{
|
|
25
|
+
await unlink(temporary).catch((error)=>{
|
|
26
|
+
if (error.code !== "ENOENT") throw error;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function validPolicy(value) {
|
|
31
|
+
if (value === undefined) return {
|
|
32
|
+
schema: 1,
|
|
33
|
+
automatic: true,
|
|
34
|
+
pin: null
|
|
35
|
+
};
|
|
36
|
+
if (!value || typeof value !== "object") throw new UpdateError("INVALID_POLICY");
|
|
37
|
+
const data = value;
|
|
38
|
+
if (data.schema !== 1 || typeof data.automatic !== "boolean" || !(data.pin === null || typeof data.pin === "string")) throw new UpdateError("INVALID_POLICY");
|
|
39
|
+
if (data.pin !== null) parts(data.pin);
|
|
40
|
+
return data;
|
|
41
|
+
}
|
|
42
|
+
async function transaction(folder) {
|
|
43
|
+
const value = await record(folder, "transaction.json");
|
|
44
|
+
if (!value) return;
|
|
45
|
+
if (value.schema !== 1 || !value.before || typeof value.before !== "object") throw new UpdateError("INVALID_RECORD");
|
|
46
|
+
const before = value.before;
|
|
47
|
+
validPolicy(before.policy);
|
|
48
|
+
return before;
|
|
49
|
+
}
|
|
50
|
+
export async function policy(folder = root) {
|
|
51
|
+
return validPolicy((await transaction(folder))?.policy ?? await record(folder, "policy.json"));
|
|
52
|
+
}
|
|
53
|
+
async function pointerRecord(folder, name) {
|
|
54
|
+
try {
|
|
55
|
+
return await record(folder, name);
|
|
56
|
+
} catch {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export async function values(folder = root) {
|
|
61
|
+
const before = await transaction(folder);
|
|
62
|
+
if (before) return before;
|
|
63
|
+
return {
|
|
64
|
+
active: await pointerRecord(folder, "active.json"),
|
|
65
|
+
previous: await pointerRecord(folder, "previous.json")
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export async function fingerprint(folder) {
|
|
69
|
+
const hash = createHash("sha256");
|
|
70
|
+
const pending = [
|
|
71
|
+
""
|
|
72
|
+
];
|
|
73
|
+
let count = 0, bytes = 0;
|
|
74
|
+
while(pending.length){
|
|
75
|
+
const relative = pending.shift();
|
|
76
|
+
const entries = await readdir(join(folder, relative), {
|
|
77
|
+
withFileTypes: true
|
|
78
|
+
});
|
|
79
|
+
entries.sort((a, b)=>a.name.localeCompare(b.name));
|
|
80
|
+
for (const item of entries){
|
|
81
|
+
if (!relative && item.name === ".bin" && item.isDirectory()) continue;
|
|
82
|
+
const name = join(relative, item.name), path = join(folder, name);
|
|
83
|
+
await checkPath(path);
|
|
84
|
+
if (++count > 8192 || item.isSymbolicLink()) throw new UpdateError("INVALID_RELEASE");
|
|
85
|
+
const info = await lstat(path);
|
|
86
|
+
if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) throw new UpdateError("UNSAFE_PATH");
|
|
87
|
+
if (item.isDirectory()) {
|
|
88
|
+
pending.push(name);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (!info.isFile() || info.nlink !== 1 || (bytes += info.size) > 67108864) throw new UpdateError("INVALID_RELEASE");
|
|
92
|
+
hash.update(name).update("\0").update(createHash("sha256").update(await readFile(path)).digest());
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return hash.digest("hex");
|
|
96
|
+
}
|
|
97
|
+
export async function selection(value, folder = root) {
|
|
98
|
+
try {
|
|
99
|
+
if (!value || typeof value !== "object") return;
|
|
100
|
+
const pointer = value;
|
|
101
|
+
parts(pointer.version);
|
|
102
|
+
if (!/^release-[a-f0-9-]{36}$/.test(pointer.release) || !/^[a-f0-9]{64}$/.test(pointer.digest)) return;
|
|
103
|
+
await verifyDirectory(folder);
|
|
104
|
+
const release = join(folder, pointer.release);
|
|
105
|
+
await verifyDirectory(release);
|
|
106
|
+
const receipt = await record(release, "release.json");
|
|
107
|
+
if (receipt?.package !== packageName || receipt.version !== pointer.version || receipt.protocol !== 1 || receipt.digest !== pointer.digest) return;
|
|
108
|
+
const modules = join(release, "node_modules");
|
|
109
|
+
const path = join(modules, "@intflow/gateflowctl");
|
|
110
|
+
await checkPath(path);
|
|
111
|
+
const metadata = JSON.parse(await readFile(join(path, "package.json"), "utf8"));
|
|
112
|
+
if (metadata.name !== packageName || metadata.version !== pointer.version || metadata.intflow?.cliUpdateProtocol !== 1 || !engineCompatible(metadata.engines?.node)) return;
|
|
113
|
+
if (await fingerprint(modules) !== pointer.digest) return;
|
|
114
|
+
const entry = join(path, "src", "cli.js");
|
|
115
|
+
if (!(await lstat(entry)).isFile()) return;
|
|
116
|
+
return {
|
|
117
|
+
...pointer,
|
|
118
|
+
entry
|
|
119
|
+
};
|
|
120
|
+
} catch {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export async function candidates(folder = root) {
|
|
125
|
+
const state = await values(folder);
|
|
126
|
+
const found = await Promise.all([
|
|
127
|
+
selection(state.active, folder),
|
|
128
|
+
selection(state.previous, folder)
|
|
129
|
+
]);
|
|
130
|
+
return found.filter((value)=>value !== undefined);
|
|
131
|
+
}
|
|
132
|
+
export async function active(folder = root) {
|
|
133
|
+
const settings = await policy(folder);
|
|
134
|
+
if (settings.pin === VERSION) return;
|
|
135
|
+
const state = await values(folder);
|
|
136
|
+
const base = state.active;
|
|
137
|
+
if (!settings.pin && base?.version === VERSION && base.release === null) return;
|
|
138
|
+
const found = await candidates(folder);
|
|
139
|
+
if (!settings.pin) return found[0];
|
|
140
|
+
const selected = found.find((item)=>item.version === settings.pin);
|
|
141
|
+
if (!selected) throw new UpdateError("PIN_UNAVAILABLE");
|
|
142
|
+
return selected;
|
|
143
|
+
}
|
|
144
|
+
async function restore(folder, name, value) {
|
|
145
|
+
if (value !== undefined) await save(folder, name, value);
|
|
146
|
+
else {
|
|
147
|
+
await readPrivate(join(folder, name));
|
|
148
|
+
await unlink(join(folder, name)).catch((error)=>{
|
|
149
|
+
if (error.code !== "ENOENT") throw error;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export async function recover(folder = root) {
|
|
154
|
+
const before = await transaction(folder);
|
|
155
|
+
if (!before) return;
|
|
156
|
+
await restore(folder, "active.json", before.active);
|
|
157
|
+
await restore(folder, "previous.json", before.previous);
|
|
158
|
+
await save(folder, "policy.json", before.policy);
|
|
159
|
+
await unlink(join(folder, "transaction.json"));
|
|
160
|
+
}
|
|
161
|
+
export async function commit(folder, settings, selected, previous, writer = save) {
|
|
162
|
+
const before = {
|
|
163
|
+
policy: await policy(folder),
|
|
164
|
+
...await values(folder)
|
|
165
|
+
};
|
|
166
|
+
await writer(folder, "transaction.json", {
|
|
167
|
+
schema: 1,
|
|
168
|
+
before
|
|
169
|
+
});
|
|
170
|
+
await restore(folder, "previous.json", previous);
|
|
171
|
+
await writer(folder, "active.json", selected);
|
|
172
|
+
await writer(folder, "policy.json", settings);
|
|
173
|
+
await unlink(join(folder, "transaction.json"));
|
|
174
|
+
}
|
|
175
|
+
async function recoverLock(folder, path) {
|
|
176
|
+
const value = await record(folder, "update.lock");
|
|
177
|
+
if (!value || typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid < 1) return;
|
|
178
|
+
try {
|
|
179
|
+
process.kill(value.pid, 0);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (error.code === "ESRCH" && JSON.stringify(await record(folder, "update.lock")) === JSON.stringify(value)) await unlink(path);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
export async function locked(folder, operation, timeout = 250) {
|
|
185
|
+
await privateDirectory(folder);
|
|
186
|
+
const path = join(folder, "update.lock"), nonce = randomUUID(), deadline = Date.now() + timeout;
|
|
187
|
+
for(;;){
|
|
188
|
+
try {
|
|
189
|
+
await writePrivate(path, JSON.stringify({
|
|
190
|
+
pid: process.pid,
|
|
191
|
+
nonce
|
|
192
|
+
}));
|
|
193
|
+
break;
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error.code !== "EEXIST") throw error;
|
|
196
|
+
await recoverLock(folder, path);
|
|
197
|
+
if (Date.now() >= deadline) throw new UpdateError("LOCK_BUSY");
|
|
198
|
+
await new Promise((resolve)=>setTimeout(resolve, 25));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
return await operation();
|
|
203
|
+
} finally{
|
|
204
|
+
if ((await record(folder, "update.lock"))?.nonce === nonce) await unlink(path);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { lstat, readFile, rm } from "node:fs/promises";
|
|
2
|
+
import { join, dirname, resolve } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { check, engineCompatible, newer, packageName, parts, VERSION } from "./updates.js";
|
|
8
|
+
import { active, candidates, commit, fingerprint, locked, policy, record, recover, root, save, values } from "./runtime-store.js";
|
|
9
|
+
import { checkPath, installerEnvironment, isMissing, privateDirectory, writePrivate } from "./files.js";
|
|
10
|
+
import { UpdateError } from "./errors.js";
|
|
11
|
+
export { active, root, save, installerEnvironment };
|
|
12
|
+
const run = promisify(execFile);
|
|
13
|
+
export const probe = {
|
|
14
|
+
protocol: 1,
|
|
15
|
+
package: packageName,
|
|
16
|
+
version: VERSION,
|
|
17
|
+
runtime: "node"
|
|
18
|
+
};
|
|
19
|
+
export function installArgs(folder, version) {
|
|
20
|
+
parts(version);
|
|
21
|
+
return [
|
|
22
|
+
"install",
|
|
23
|
+
"--prefix",
|
|
24
|
+
folder,
|
|
25
|
+
"--ignore-scripts",
|
|
26
|
+
"--no-audit",
|
|
27
|
+
"--no-fund",
|
|
28
|
+
"--engine-strict",
|
|
29
|
+
"--umask=077",
|
|
30
|
+
"--package-lock=false",
|
|
31
|
+
"--prefer-online",
|
|
32
|
+
"--cache=" + join(folder, ".npm-cache"),
|
|
33
|
+
"--userconfig=" + join(folder, ".npmrc-user"),
|
|
34
|
+
"--globalconfig=" + join(folder, ".npmrc-global"),
|
|
35
|
+
"--registry=https://registry.npmjs.org",
|
|
36
|
+
packageName + "@" + version
|
|
37
|
+
];
|
|
38
|
+
}
|
|
39
|
+
export async function stage(version, folder = root, runner = run) {
|
|
40
|
+
parts(version);
|
|
41
|
+
await privateDirectory(folder);
|
|
42
|
+
const release = "release-" + randomUUID(), directory = join(folder, release);
|
|
43
|
+
await privateDirectory(directory);
|
|
44
|
+
const deadline = Date.now() + 180000;
|
|
45
|
+
try {
|
|
46
|
+
await writePrivate(join(directory, ".npmrc-user"), "");
|
|
47
|
+
await writePrivate(join(directory, ".npmrc-global"), "");
|
|
48
|
+
const npm = process.platform === "win32" ? join(dirname(process.execPath), "node_modules/npm/bin/npm-cli.js") : null;
|
|
49
|
+
await runner(npm ? process.execPath : "npm", npm ? [
|
|
50
|
+
npm,
|
|
51
|
+
...installArgs(directory, version)
|
|
52
|
+
] : installArgs(directory, version), {
|
|
53
|
+
cwd: directory,
|
|
54
|
+
windowsHide: true,
|
|
55
|
+
timeout: Math.max(1, deadline - Date.now()),
|
|
56
|
+
maxBuffer: 1048576,
|
|
57
|
+
env: installerEnvironment()
|
|
58
|
+
});
|
|
59
|
+
const packageRoot = join(directory, "node_modules", packageName);
|
|
60
|
+
const metadata = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
|
|
61
|
+
if (metadata.name !== packageName || metadata.version !== version || metadata.intflow?.cliUpdateProtocol !== 1 || !engineCompatible(metadata.engines?.node)) throw new UpdateError("UNSUPPORTED_PROTOCOL");
|
|
62
|
+
const binary = join(packageRoot, "bin", "gateflowctl.js");
|
|
63
|
+
for (const argument of [
|
|
64
|
+
"--runtime-probe",
|
|
65
|
+
"--version"
|
|
66
|
+
]){
|
|
67
|
+
if (Date.now() >= deadline) throw new UpdateError("INSTALL_TIMEOUT");
|
|
68
|
+
const result = await runner(process.execPath, [
|
|
69
|
+
binary,
|
|
70
|
+
argument
|
|
71
|
+
], {
|
|
72
|
+
windowsHide: true,
|
|
73
|
+
timeout: Math.min(10000, deadline - Date.now()),
|
|
74
|
+
maxBuffer: 4096,
|
|
75
|
+
env: installerEnvironment()
|
|
76
|
+
});
|
|
77
|
+
if (argument === "--runtime-probe") {
|
|
78
|
+
const info = JSON.parse(result.stdout);
|
|
79
|
+
if (info.protocol !== 1 || info.package !== packageName || info.version !== version || info.runtime !== "node") throw new UpdateError("INVALID_PROBE");
|
|
80
|
+
} else if (!result.stdout.trim().split(/\s+/).includes(version)) throw new UpdateError("VERSION_MISMATCH");
|
|
81
|
+
}
|
|
82
|
+
const digest = await fingerprint(join(directory, "node_modules"));
|
|
83
|
+
if (Date.now() >= deadline) throw new UpdateError("INSTALL_TIMEOUT");
|
|
84
|
+
await save(directory, "release.json", {
|
|
85
|
+
package: packageName,
|
|
86
|
+
version,
|
|
87
|
+
protocol: 1,
|
|
88
|
+
digest
|
|
89
|
+
});
|
|
90
|
+
return {
|
|
91
|
+
version,
|
|
92
|
+
release,
|
|
93
|
+
digest
|
|
94
|
+
};
|
|
95
|
+
} catch (error) {
|
|
96
|
+
await checkPath(directory);
|
|
97
|
+
if (resolve(dirname(directory)) === resolve(folder)) await rm(directory, {
|
|
98
|
+
recursive: true,
|
|
99
|
+
force: true
|
|
100
|
+
});
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
export function automatic(settings) {
|
|
105
|
+
return settings.automatic && process.env.INTFLOW_CLI_AUTO_UPDATE !== "0";
|
|
106
|
+
}
|
|
107
|
+
function failure(error) {
|
|
108
|
+
return error instanceof UpdateError ? error.code : "UPDATE_FAILED";
|
|
109
|
+
}
|
|
110
|
+
export async function refresh(folder = root, lookup = check, installer = stage) {
|
|
111
|
+
await locked(folder, async ()=>{
|
|
112
|
+
await recover(folder);
|
|
113
|
+
const settings = await policy(folder);
|
|
114
|
+
if (!automatic(settings) || settings.pin !== null) return;
|
|
115
|
+
try {
|
|
116
|
+
const result = await lookup();
|
|
117
|
+
const selected = await active(folder);
|
|
118
|
+
if (result.latest && result.compatible && newer(result.latest, selected?.version ?? VERSION)) {
|
|
119
|
+
const prepared = await installer(result.latest, folder);
|
|
120
|
+
await commit(folder, settings, prepared, selected);
|
|
121
|
+
}
|
|
122
|
+
await save(folder, "state.json", {
|
|
123
|
+
last_check: new Date().toISOString(),
|
|
124
|
+
last_error: result.last_error
|
|
125
|
+
});
|
|
126
|
+
} catch (error) {
|
|
127
|
+
await save(folder, "state.json", {
|
|
128
|
+
last_check: new Date().toISOString(),
|
|
129
|
+
last_error: failure(error)
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
export async function status(folder = root) {
|
|
135
|
+
const settings = await policy(folder), state = await record(folder, "state.json"), stored = await values(folder);
|
|
136
|
+
let selected, unavailable = false;
|
|
137
|
+
try {
|
|
138
|
+
selected = await active(folder);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (!(error instanceof UpdateError) || error.code !== "PIN_UNAVAILABLE") throw error;
|
|
141
|
+
unavailable = true;
|
|
142
|
+
}
|
|
143
|
+
const previous = stored.previous;
|
|
144
|
+
const error = state?.last_error;
|
|
145
|
+
return {
|
|
146
|
+
current: selected?.version ?? (unavailable ? null : VERSION),
|
|
147
|
+
installed: VERSION,
|
|
148
|
+
active: selected?.version ?? null,
|
|
149
|
+
previous: typeof previous?.version === "string" ? previous.version : null,
|
|
150
|
+
automatic: automatic(settings),
|
|
151
|
+
pin: settings.pin,
|
|
152
|
+
protocol: 1,
|
|
153
|
+
last_check: state?.last_check ?? null,
|
|
154
|
+
last_error: unavailable ? "PIN_UNAVAILABLE" : typeof error === "string" && /^[A-Z0-9_]{1,64}$/.test(error) ? error : null
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
export function parseControl(arguments_) {
|
|
158
|
+
if (!arguments_.length) return {
|
|
159
|
+
check: true
|
|
160
|
+
};
|
|
161
|
+
const single = {
|
|
162
|
+
"--apply": {
|
|
163
|
+
apply: true
|
|
164
|
+
},
|
|
165
|
+
"--check": {
|
|
166
|
+
check: true
|
|
167
|
+
},
|
|
168
|
+
"--status": {
|
|
169
|
+
status: true
|
|
170
|
+
},
|
|
171
|
+
"--unpin": {
|
|
172
|
+
unpin: true
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
if (arguments_.length === 1 && single[arguments_[0]]) return single[arguments_[0]];
|
|
176
|
+
if (arguments_.length === 2 && arguments_[0] === "--pin") {
|
|
177
|
+
parts(arguments_[1]);
|
|
178
|
+
return {
|
|
179
|
+
pin: arguments_[1]
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
if (arguments_.length === 2 && arguments_[0] === "--auto" && [
|
|
183
|
+
"on",
|
|
184
|
+
"off"
|
|
185
|
+
].includes(arguments_[1])) return {
|
|
186
|
+
auto: arguments_[1]
|
|
187
|
+
};
|
|
188
|
+
throw new UpdateError("INVALID_UPDATE_ARGUMENTS");
|
|
189
|
+
}
|
|
190
|
+
async function exact(version, folder, settings, lookup, installer) {
|
|
191
|
+
parts(version);
|
|
192
|
+
const previous = (await candidates(folder)).find((item)=>item.version === settings.pin) ?? (await candidates(folder))[0];
|
|
193
|
+
if (version === VERSION) {
|
|
194
|
+
await commit(folder, {
|
|
195
|
+
...settings,
|
|
196
|
+
pin: version
|
|
197
|
+
}, {
|
|
198
|
+
version,
|
|
199
|
+
release: null
|
|
200
|
+
}, previous);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
let selected = (await candidates(folder)).find((item)=>item.version === version);
|
|
204
|
+
if (!selected) {
|
|
205
|
+
const candidate = await lookup(undefined, undefined, version);
|
|
206
|
+
if (!candidate.compatible || candidate.latest !== version) throw new UpdateError(candidate.last_error ?? "CANDIDATE_UNAVAILABLE");
|
|
207
|
+
selected = await installer(version, folder);
|
|
208
|
+
}
|
|
209
|
+
await commit(folder, {
|
|
210
|
+
...settings,
|
|
211
|
+
pin: version
|
|
212
|
+
}, selected, previous);
|
|
213
|
+
}
|
|
214
|
+
export async function manage(options, folder = root, lookup = check, installer = stage) {
|
|
215
|
+
if (Object.values(options).filter((value)=>value !== undefined && value !== false).length > 1) throw new UpdateError("INVALID_UPDATE_ARGUMENTS");
|
|
216
|
+
if (options.status) return status(folder);
|
|
217
|
+
if (!options.apply && options.auto === undefined && options.pin === undefined && !options.unpin) {
|
|
218
|
+
const settings = await policy(folder), found = await lookup(undefined, undefined, settings.pin ?? undefined);
|
|
219
|
+
return {
|
|
220
|
+
...await status(folder),
|
|
221
|
+
latest: found.latest ?? null,
|
|
222
|
+
compatible: found.compatible,
|
|
223
|
+
available: found.compatible && found.latest !== (await status(folder)).current,
|
|
224
|
+
last_error: found.last_error
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
await locked(folder, async ()=>{
|
|
228
|
+
await recover(folder);
|
|
229
|
+
const settings = await policy(folder);
|
|
230
|
+
if (options.auto !== undefined) {
|
|
231
|
+
if (![
|
|
232
|
+
"on",
|
|
233
|
+
"off"
|
|
234
|
+
].includes(options.auto)) throw new UpdateError("INVALID_UPDATE_ARGUMENTS");
|
|
235
|
+
await save(folder, "policy.json", {
|
|
236
|
+
...settings,
|
|
237
|
+
automatic: options.auto === "on"
|
|
238
|
+
});
|
|
239
|
+
} else if (options.unpin) await save(folder, "policy.json", {
|
|
240
|
+
...settings,
|
|
241
|
+
pin: null
|
|
242
|
+
});
|
|
243
|
+
else if (options.pin !== undefined) await exact(options.pin, folder, settings, lookup, installer);
|
|
244
|
+
else if (settings.pin) await exact(settings.pin, folder, settings, lookup, installer);
|
|
245
|
+
else {
|
|
246
|
+
const found = await lookup();
|
|
247
|
+
if (!found.compatible || !found.latest) throw new UpdateError(found.last_error ?? "CANDIDATE_UNAVAILABLE");
|
|
248
|
+
const previous = await active(folder);
|
|
249
|
+
if (newer(found.latest, previous?.version ?? VERSION)) await commit(folder, settings, await installer(found.latest, folder), previous);
|
|
250
|
+
}
|
|
251
|
+
}, 5000);
|
|
252
|
+
return status(folder);
|
|
253
|
+
}
|
|
254
|
+
export function controls(arguments_) {
|
|
255
|
+
let index = 0;
|
|
256
|
+
const flags = new Set([
|
|
257
|
+
"--json",
|
|
258
|
+
"--non-interactive",
|
|
259
|
+
"--token-stdin"
|
|
260
|
+
]);
|
|
261
|
+
const options = new Set([
|
|
262
|
+
"--output",
|
|
263
|
+
"-o",
|
|
264
|
+
"--format",
|
|
265
|
+
"--config",
|
|
266
|
+
"--credential-store"
|
|
267
|
+
]);
|
|
268
|
+
while(index < arguments_.length){
|
|
269
|
+
const argument = arguments_[index];
|
|
270
|
+
if (flags.has(argument)) index++;
|
|
271
|
+
else if (options.has(argument) && index + 1 < arguments_.length) index += 2;
|
|
272
|
+
else if (argument.includes("=") && options.has(argument.split("=")[0])) index++;
|
|
273
|
+
else break;
|
|
274
|
+
}
|
|
275
|
+
return arguments_[index] === "update" ? arguments_.slice(index + 1) : undefined;
|
|
276
|
+
}
|
|
277
|
+
async function base() {
|
|
278
|
+
return await import(new URL("../src/cli.js", import.meta.url).href);
|
|
279
|
+
}
|
|
280
|
+
async function verifyRoot(folder) {
|
|
281
|
+
try {
|
|
282
|
+
await lstat(folder);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
if (isMissing(error)) return;
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
await privateDirectory(folder);
|
|
288
|
+
}
|
|
289
|
+
export async function repair(folder) {
|
|
290
|
+
const selected = await active(folder);
|
|
291
|
+
if (!selected || (await policy(folder)).pin) return selected;
|
|
292
|
+
const snapshot = await values(folder);
|
|
293
|
+
if (snapshot.active?.release === selected.release) return selected;
|
|
294
|
+
await locked(folder, async ()=>{
|
|
295
|
+
await recover(folder);
|
|
296
|
+
if (JSON.stringify(await values(folder)) !== JSON.stringify(snapshot)) return;
|
|
297
|
+
await commit(folder, await policy(folder), selected);
|
|
298
|
+
}).catch(()=>{});
|
|
299
|
+
return selected;
|
|
300
|
+
}
|
|
301
|
+
export async function selectCore(folder, fallback = base) {
|
|
302
|
+
const settings = await policy(folder), selected = await repair(folder);
|
|
303
|
+
if (!selected) return fallback();
|
|
304
|
+
for (const candidate of [
|
|
305
|
+
selected,
|
|
306
|
+
...await candidates(folder)
|
|
307
|
+
]){
|
|
308
|
+
if (settings.pin && candidate.version !== settings.pin) continue;
|
|
309
|
+
try {
|
|
310
|
+
const module = await import(pathToFileURL(candidate.entry).href);
|
|
311
|
+
if (typeof module.main === "function") return module;
|
|
312
|
+
} catch {
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (settings.pin) throw new UpdateError("PIN_UNAVAILABLE");
|
|
317
|
+
return fallback();
|
|
318
|
+
}
|
|
319
|
+
export async function bootstrap(arguments_, folder = root, fallback = base) {
|
|
320
|
+
if (arguments_.includes("--runtime-probe") && arguments_.length !== 1) {
|
|
321
|
+
process.stderr.write("INVALID_UPDATE_ARGUMENTS\n");
|
|
322
|
+
return 2;
|
|
323
|
+
}
|
|
324
|
+
if (arguments_.length === 1 && arguments_[0] === "--runtime-probe") {
|
|
325
|
+
process.stdout.write(JSON.stringify(probe) + "\n");
|
|
326
|
+
return 0;
|
|
327
|
+
}
|
|
328
|
+
if (process.env.INTFLOW_CLI_RUNTIME_ACTIVE === "1") return (await fallback()).main(arguments_);
|
|
329
|
+
let module;
|
|
330
|
+
try {
|
|
331
|
+
await verifyRoot(folder);
|
|
332
|
+
const action = controls(arguments_);
|
|
333
|
+
if (action !== undefined) {
|
|
334
|
+
process.stdout.write(JSON.stringify(await manage(parseControl(action), folder)) + "\n");
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
const local = !arguments_.length || arguments_[0] === "help" || arguments_.some((value)=>[
|
|
338
|
+
"--help",
|
|
339
|
+
"-h",
|
|
340
|
+
"--version",
|
|
341
|
+
"-V"
|
|
342
|
+
].includes(value));
|
|
343
|
+
if (!local && automatic(await policy(folder))) await refresh(folder).catch(()=>{});
|
|
344
|
+
module = await selectCore(folder, fallback);
|
|
345
|
+
} catch (error) {
|
|
346
|
+
process.stderr.write(failure(error) + "\n");
|
|
347
|
+
return error instanceof UpdateError && [
|
|
348
|
+
"INVALID_VERSION",
|
|
349
|
+
"INVALID_UPDATE_ARGUMENTS"
|
|
350
|
+
].includes(error.code) ? 2 : 1;
|
|
351
|
+
}
|
|
352
|
+
return module.main(arguments_);
|
|
353
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { UpdateError } from "./errors.js";
|
|
3
|
+
export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
4
|
+
export const packageName = "@intflow/gateflowctl";
|
|
5
|
+
export function parts(value) {
|
|
6
|
+
if (typeof value !== "string" || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) throw new UpdateError("INVALID_VERSION");
|
|
7
|
+
const found = value.split(".").map(Number);
|
|
8
|
+
if (found.some((part)=>!Number.isSafeInteger(part))) throw new UpdateError("INVALID_VERSION");
|
|
9
|
+
return found;
|
|
10
|
+
}
|
|
11
|
+
export function newer(candidate, current) {
|
|
12
|
+
const a = parts(candidate), b = parts(current);
|
|
13
|
+
const index = a.findIndex((part, at)=>part !== b[at]);
|
|
14
|
+
return index >= 0 && a[index] > b[index];
|
|
15
|
+
}
|
|
16
|
+
export function engineCompatible(value, current = process.versions.node) {
|
|
17
|
+
if (typeof value !== "string") return false;
|
|
18
|
+
const match = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(value);
|
|
19
|
+
if (!match) return false;
|
|
20
|
+
const minimum = `${match[1]}.${match[2] ?? 0}.${match[3] ?? 0}`;
|
|
21
|
+
try {
|
|
22
|
+
return current === minimum || newer(current, minimum);
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async function document(fetcher, signal, target) {
|
|
28
|
+
const response = await fetcher(`https://registry.npmjs.org/@intflow%2Fgateflowctl/${target}`, {
|
|
29
|
+
redirect: "error",
|
|
30
|
+
signal,
|
|
31
|
+
headers: {
|
|
32
|
+
Accept: "application/json"
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
if (response.status === 404) {
|
|
36
|
+
await response.body?.cancel();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (!response.ok || !response.body) throw new UpdateError("REGISTRY_UNAVAILABLE");
|
|
40
|
+
const reader = response.body.getReader();
|
|
41
|
+
const chunks = [];
|
|
42
|
+
let size = 0;
|
|
43
|
+
try {
|
|
44
|
+
for(;;){
|
|
45
|
+
const value = await reader.read();
|
|
46
|
+
if (value.done) break;
|
|
47
|
+
if ((size += value.value.length) > 1048576) throw new UpdateError("INVALID_REGISTRY_RESPONSE");
|
|
48
|
+
chunks.push(value.value);
|
|
49
|
+
}
|
|
50
|
+
} finally{
|
|
51
|
+
await reader.cancel();
|
|
52
|
+
}
|
|
53
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
54
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new UpdateError("INVALID_REGISTRY_RESPONSE");
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
export async function check(fetcher = fetch, timeout = 3000, target) {
|
|
58
|
+
if (target !== undefined) parts(target);
|
|
59
|
+
const controller = new AbortController();
|
|
60
|
+
let timer;
|
|
61
|
+
try {
|
|
62
|
+
const deadline = new Promise((_resolve, reject)=>{
|
|
63
|
+
timer = setTimeout(()=>{
|
|
64
|
+
controller.abort();
|
|
65
|
+
reject(new UpdateError("REGISTRY_TIMEOUT"));
|
|
66
|
+
}, timeout);
|
|
67
|
+
});
|
|
68
|
+
const value = await Promise.race([
|
|
69
|
+
document(fetcher, controller.signal, target ?? "latest"),
|
|
70
|
+
deadline
|
|
71
|
+
]);
|
|
72
|
+
if (!value) return {
|
|
73
|
+
current: VERSION,
|
|
74
|
+
published: false,
|
|
75
|
+
available: false,
|
|
76
|
+
compatible: false,
|
|
77
|
+
last_error: null
|
|
78
|
+
};
|
|
79
|
+
parts(value.version);
|
|
80
|
+
if (value.name !== packageName || target !== undefined && value.version !== target) throw new UpdateError("INVALID_REGISTRY_RESPONSE");
|
|
81
|
+
const marker = value.intflow;
|
|
82
|
+
const engines = value.engines;
|
|
83
|
+
const compatible = marker?.cliUpdateProtocol === 1 && engineCompatible(engines?.node);
|
|
84
|
+
return {
|
|
85
|
+
current: VERSION,
|
|
86
|
+
latest: value.version,
|
|
87
|
+
published: true,
|
|
88
|
+
available: newer(value.version, VERSION),
|
|
89
|
+
compatible,
|
|
90
|
+
last_error: compatible ? null : marker?.cliUpdateProtocol !== 1 ? "UNSUPPORTED_PROTOCOL" : "INCOMPATIBLE_RUNTIME"
|
|
91
|
+
};
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (error instanceof UpdateError) throw error;
|
|
94
|
+
throw new UpdateError("REGISTRY_UNAVAILABLE");
|
|
95
|
+
} finally{
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
controller.abort();
|
|
98
|
+
}
|
|
99
|
+
}
|
package/README.md
DELETED