@flowshape/agent 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/LICENSE +61 -0
- package/README.md +210 -2
- package/SECURITY.md +34 -0
- package/agent.mjs +843 -0
- package/package.json +49 -4
- package/samples/azure-graph.json +1895 -0
- package/samples/kubernetes-shop.json +2642 -0
- package/samples/nmap-office.xml +334 -0
- package/samples/terraform-aws-show.json +1359 -0
package/agent.mjs
ADDED
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* FlowShape agent: runs read-only collectors in your own environment, on a schedule, and
|
|
4
|
+
* keeps their output in memory. FlowShape, open in a browser on this machine, fetches it with
|
|
5
|
+
* the agent's key and draws the diagram. It never contacts FlowShape or any third party: the
|
|
6
|
+
* only outgoing connections are the tools you enable and, with --grafana, your own Grafana.
|
|
7
|
+
*
|
|
8
|
+
* node agent.mjs --azure --kubernetes --terraform ./infra --nmap 10.0.1.0/24 --every 15m
|
|
9
|
+
* node agent.mjs --demo (sample environments, no tools needed)
|
|
10
|
+
*
|
|
11
|
+
* No dependencies: Node 20+ only. The collectors are the vendors' own tools (az, terraform,
|
|
12
|
+
* kubectl, nmap), run without a shell, with the rights of whoever runs the agent: give it a
|
|
13
|
+
* read-only identity (Azure "Reader", a read-only kubeconfig).
|
|
14
|
+
*
|
|
15
|
+
* Required Notice: Copyright 2026 FlowShape (https://flowshape.io). PolyForm Strict 1.0.0
|
|
16
|
+
* (LICENSE): noncommercial use; with FlowShape, under FlowShape's Terms.
|
|
17
|
+
*/
|
|
18
|
+
import { execFile } from "node:child_process";
|
|
19
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
20
|
+
import { realpathSync } from "node:fs";
|
|
21
|
+
import { readFile } from "node:fs/promises";
|
|
22
|
+
import { createServer } from "node:http";
|
|
23
|
+
import { hostname } from "node:os";
|
|
24
|
+
import path from "node:path";
|
|
25
|
+
import { fileURLToPath } from "node:url";
|
|
26
|
+
|
|
27
|
+
export const VERSION = "0.1.0";
|
|
28
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
29
|
+
const MAX_OUTPUT = 64 * 1024 * 1024;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Where FlowShape runs; the agent answers only pages from these origins (and still needs its
|
|
33
|
+
* key). Another FlowShape address is added with --origin (FlowShape's setup writes it).
|
|
34
|
+
*/
|
|
35
|
+
export const DEFAULT_ORIGINS = ["https://app.flowshape.io"];
|
|
36
|
+
/** Keys shorter than this are refused: the key is the agent's only lock. */
|
|
37
|
+
export const MIN_KEY = 16;
|
|
38
|
+
|
|
39
|
+
const AZURE_QUERY =
|
|
40
|
+
"Resources | project id, name, type, resourceGroup, subscriptionId, location, sku, kind, properties";
|
|
41
|
+
// Secrets are asked for separately (Kubernetes' read-only "view" role can't list them).
|
|
42
|
+
const K8S_KINDS = "deploy,sts,ds,svc,ing,cm,pvc,cronjob,job,pod";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The collectors: what each runs. `type` tells FlowShape which reader to use.
|
|
46
|
+
* @typedef {{ id: string, type: "azure"|"terraform"|"kubernetes"|"nmap"|"file", label: string,
|
|
47
|
+
* run: () => Promise<{ text: string, contentType: string }> }} Collector
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/** Run a program without a shell; its output, or an error that says what to install. */
|
|
51
|
+
export function run(cmd, args, opts = {}) {
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
execFile(
|
|
54
|
+
cmd,
|
|
55
|
+
args,
|
|
56
|
+
{ maxBuffer: MAX_OUTPUT, timeout: opts.timeout ?? 180_000, cwd: opts.cwd, windowsHide: true },
|
|
57
|
+
(err, stdout, stderr) => {
|
|
58
|
+
if (err) {
|
|
59
|
+
if (err.code === "ENOENT" || err.code === "EINVAL") {
|
|
60
|
+
// Windows' az is a batch file (az.cmd), which can't run without a shell.
|
|
61
|
+
if (process.platform === "win32" && cmd === "az")
|
|
62
|
+
return reject(
|
|
63
|
+
new Error(
|
|
64
|
+
"On Windows the agent can't run az itself. Run the query yourself (see the docs, Azure on Windows) and start the agent with --file azure.json.",
|
|
65
|
+
),
|
|
66
|
+
);
|
|
67
|
+
return reject(new Error(`"${cmd}" isn't installed on this machine (or not on PATH).`));
|
|
68
|
+
}
|
|
69
|
+
return reject(new Error((stderr || err.message).toString().trim().slice(0, 600)));
|
|
70
|
+
}
|
|
71
|
+
resolve(stdout.toString());
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Secrets keep their name and type; their values never leave kubectl's output. The cluster's
|
|
79
|
+
* context name goes on top (kubectl's list doesn't say which cluster it is).
|
|
80
|
+
*/
|
|
81
|
+
export function stripSecrets(json, context) {
|
|
82
|
+
const doc = JSON.parse(json);
|
|
83
|
+
if (context) doc.context = context;
|
|
84
|
+
const items = Array.isArray(doc.items) ? doc.items : [doc];
|
|
85
|
+
for (const it of items) {
|
|
86
|
+
if (it && it.kind === "Secret") {
|
|
87
|
+
delete it.data;
|
|
88
|
+
delete it.stringData;
|
|
89
|
+
if (it.metadata?.annotations)
|
|
90
|
+
delete it.metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return JSON.stringify(doc);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Values Terraform marks sensitive (passwords, tokens) are dropped here, before anything
|
|
98
|
+
* leaves the agent: `terraform show -json` prints them in plain text and marks them in a
|
|
99
|
+
* parallel tree (`sensitive_values`: true = sensitive, an object or array = look inside).
|
|
100
|
+
* Sensitive outputs lose their value too.
|
|
101
|
+
*/
|
|
102
|
+
export function stripTerraformSensitive(json) {
|
|
103
|
+
const doc = JSON.parse(json);
|
|
104
|
+
const strip = (values, mask) => {
|
|
105
|
+
if (!values || typeof values !== "object" || !mask || typeof mask !== "object") return;
|
|
106
|
+
for (const [k, flag] of Object.entries(mask)) {
|
|
107
|
+
if (flag === true) delete values[k];
|
|
108
|
+
else strip(values[k], flag);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
const walk = (mod) => {
|
|
112
|
+
for (const r of mod?.resources ?? []) {
|
|
113
|
+
if (r?.sensitive_values) strip(r.values, r.sensitive_values);
|
|
114
|
+
}
|
|
115
|
+
for (const child of mod?.child_modules ?? []) walk(child);
|
|
116
|
+
};
|
|
117
|
+
for (const values of [doc.values, doc.planned_values, doc.prior_state?.values]) {
|
|
118
|
+
if (!values) continue;
|
|
119
|
+
walk(values.root_module);
|
|
120
|
+
for (const out of Object.values(values.outputs ?? {})) if (out?.sensitive) delete out.value;
|
|
121
|
+
}
|
|
122
|
+
// A plan (terraform show -json plan.out): each change's before and after, and the outputs'.
|
|
123
|
+
for (const rc of doc.resource_changes ?? []) {
|
|
124
|
+
const c = rc?.change;
|
|
125
|
+
if (!c) continue;
|
|
126
|
+
if (c.before_sensitive === true) delete c.before;
|
|
127
|
+
else strip(c.before, c.before_sensitive);
|
|
128
|
+
if (c.after_sensitive === true) delete c.after;
|
|
129
|
+
else strip(c.after, c.after_sensitive);
|
|
130
|
+
}
|
|
131
|
+
for (const oc of Object.values(doc.output_changes ?? {})) {
|
|
132
|
+
if (oc?.before_sensitive) delete oc.before;
|
|
133
|
+
if (oc?.after_sensitive) delete oc.after;
|
|
134
|
+
}
|
|
135
|
+
// Input variables declared sensitive.
|
|
136
|
+
const declared = doc.configuration?.root_module?.variables ?? {};
|
|
137
|
+
for (const [name, v] of Object.entries(doc.variables ?? {}))
|
|
138
|
+
if (declared[name]?.sensitive && v) delete v.value;
|
|
139
|
+
return JSON.stringify(doc);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A file given with --file, its secrets dropped like a collector's: kubectl's JSON (Secrets'
|
|
144
|
+
* values) and Terraform's (sensitive values); anything else (nmap XML, Azure Resource Graph)
|
|
145
|
+
* as is.
|
|
146
|
+
*/
|
|
147
|
+
export function stripFile(text) {
|
|
148
|
+
let doc;
|
|
149
|
+
try {
|
|
150
|
+
doc = JSON.parse(text);
|
|
151
|
+
} catch {
|
|
152
|
+
return text;
|
|
153
|
+
}
|
|
154
|
+
if (!doc || typeof doc !== "object") return text;
|
|
155
|
+
if ("format_version" in doc || "terraform_version" in doc) return stripTerraformSensitive(text);
|
|
156
|
+
if (doc.kind === "List" || doc.kind === "Secret" || Array.isArray(doc.items))
|
|
157
|
+
return stripSecrets(text, doc.context);
|
|
158
|
+
return text;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function collectors(opts) {
|
|
162
|
+
/** @type {Collector[]} */
|
|
163
|
+
const out = [];
|
|
164
|
+
const json = "application/json";
|
|
165
|
+
if (opts.azure) {
|
|
166
|
+
const args = ["graph", "query", "-q", AZURE_QUERY, "--first", "1000", "-o", "json"];
|
|
167
|
+
if (opts.subscription) args.push("--subscriptions", opts.subscription);
|
|
168
|
+
out.push({
|
|
169
|
+
id: "azure",
|
|
170
|
+
type: "azure",
|
|
171
|
+
label: opts.subscription ? `Azure · ${opts.subscription}` : "Azure",
|
|
172
|
+
run: async () => ({ text: await run("az", args), contentType: json }),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
for (const dir of opts.terraform ?? []) {
|
|
176
|
+
out.push({
|
|
177
|
+
id: `terraform-${out.length}`,
|
|
178
|
+
type: "terraform",
|
|
179
|
+
label: `Terraform · ${path.basename(path.resolve(dir))}`,
|
|
180
|
+
run: async () => ({
|
|
181
|
+
text: stripTerraformSensitive(
|
|
182
|
+
await run("terraform", ["show", "-json"], { cwd: path.resolve(dir) }),
|
|
183
|
+
),
|
|
184
|
+
contentType: json,
|
|
185
|
+
}),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
if (opts.kubernetes) {
|
|
189
|
+
const args = ["get", K8S_KINDS, "-A", "-o", "json"];
|
|
190
|
+
if (opts.context) args.push("--context", opts.context);
|
|
191
|
+
out.push({
|
|
192
|
+
id: "kubernetes",
|
|
193
|
+
type: "kubernetes",
|
|
194
|
+
label: opts.context ? `Kubernetes · ${opts.context}` : "Kubernetes",
|
|
195
|
+
run: async () => {
|
|
196
|
+
const context =
|
|
197
|
+
opts.context ??
|
|
198
|
+
(await run("kubectl", ["config", "current-context"]).then(
|
|
199
|
+
(s) => s.trim(),
|
|
200
|
+
() => undefined,
|
|
201
|
+
));
|
|
202
|
+
const doc = JSON.parse(await run("kubectl", args));
|
|
203
|
+
// Secrets: optional (the "view" role can't list them). Only their names and types are
|
|
204
|
+
// kept: their values are dropped here, before anything leaves the agent.
|
|
205
|
+
const secretArgs = ["get", "secrets", "-A", "-o", "json"];
|
|
206
|
+
if (opts.context) secretArgs.push("--context", opts.context);
|
|
207
|
+
try {
|
|
208
|
+
const secrets = JSON.parse(await run("kubectl", secretArgs));
|
|
209
|
+
doc.items = [...(doc.items ?? []), ...(secrets.items ?? [])];
|
|
210
|
+
} catch {
|
|
211
|
+
// Not allowed to list Secrets: the diagram shows the workloads without them.
|
|
212
|
+
}
|
|
213
|
+
return { text: stripSecrets(JSON.stringify(doc), context), contentType: json };
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
for (const range of opts.nmap ?? []) {
|
|
218
|
+
out.push({
|
|
219
|
+
id: `nmap-${out.length}`,
|
|
220
|
+
type: "nmap",
|
|
221
|
+
label: `Network · ${range}`,
|
|
222
|
+
// -sV: what runs on open ports; --traceroute: the hops (needs root for raw sockets).
|
|
223
|
+
run: async () => ({
|
|
224
|
+
text: await run("nmap", ["-sV", "--traceroute", "-oX", "-", range], { timeout: 900_000 }),
|
|
225
|
+
contentType: "application/xml",
|
|
226
|
+
}),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
for (const file of opts.files ?? []) {
|
|
230
|
+
const p = path.resolve(file);
|
|
231
|
+
const type = /\.xml$/i.test(p) ? "nmap" : "file";
|
|
232
|
+
out.push({
|
|
233
|
+
id: `file-${out.length}`,
|
|
234
|
+
type,
|
|
235
|
+
label: path.basename(p),
|
|
236
|
+
run: async () => ({
|
|
237
|
+
text: stripFile(await readFile(p, "utf8")),
|
|
238
|
+
contentType: /\.xml$/i.test(p) ? "application/xml" : json,
|
|
239
|
+
}),
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
if (opts.demo) {
|
|
243
|
+
for (const [id, type, label, file] of [
|
|
244
|
+
["demo-azure", "azure", "Azure · sub-prod (sample)", "azure-graph.json"],
|
|
245
|
+
[
|
|
246
|
+
"demo-terraform",
|
|
247
|
+
"terraform",
|
|
248
|
+
"Terraform · shop-infra on AWS (sample)",
|
|
249
|
+
"terraform-aws-show.json",
|
|
250
|
+
],
|
|
251
|
+
["demo-kubernetes", "kubernetes", "Kubernetes · prod-eu (sample)", "kubernetes-shop.json"],
|
|
252
|
+
["demo-nmap", "nmap", "Network · office 10.0.1.0/24 (sample)", "nmap-office.xml"],
|
|
253
|
+
])
|
|
254
|
+
out.push({
|
|
255
|
+
id,
|
|
256
|
+
type,
|
|
257
|
+
label,
|
|
258
|
+
run: async () => {
|
|
259
|
+
// The single-file build (build.mjs) carries the samples inside it.
|
|
260
|
+
const text =
|
|
261
|
+
globalThis.__FLOWSHAPE_SAMPLES__?.[file] ??
|
|
262
|
+
(await readFile(path.join(HERE, "samples", file), "utf8"));
|
|
263
|
+
return {
|
|
264
|
+
// Like a real run: the sample's (made-up) secrets don't leave either.
|
|
265
|
+
text:
|
|
266
|
+
type === "terraform"
|
|
267
|
+
? stripTerraformSensitive(text)
|
|
268
|
+
: type === "kubernetes"
|
|
269
|
+
? stripSecrets(text, "prod-eu")
|
|
270
|
+
: text,
|
|
271
|
+
contentType: file.endsWith(".xml") ? "application/xml" : json,
|
|
272
|
+
};
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/* ---------------------------------------------------------------- monitoring (Grafana) */
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Live status, logs and traces from the customer's Grafana (its Prometheus, Loki and Tempo),
|
|
283
|
+
* asked from here, inside their network, with a read-only (Viewer) service-account token.
|
|
284
|
+
* The token never leaves this machine; FlowShape gets only the answers. Items are matched by
|
|
285
|
+
* name: a diagram's "api" is the series whose `label` (default `service`) is "api".
|
|
286
|
+
*/
|
|
287
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
|
|
288
|
+
/** Names in a PromQL regex: dots escaped (a backslash, doubled inside a PromQL string). */
|
|
289
|
+
const promAlternatives = (names) => names.map((n) => n.replace(/\./g, "\\\\.")).join("|");
|
|
290
|
+
|
|
291
|
+
/** The queries for the usual metric names; a JSON file (--grafana-queries) can replace any. */
|
|
292
|
+
export const DEFAULT_QUERIES = {
|
|
293
|
+
status:
|
|
294
|
+
'max by ($label) (service_up{$label=~"$names"}) or max by ($label) (up{$label=~"$names"})',
|
|
295
|
+
errors:
|
|
296
|
+
'sum by ($label) (rate(http_requests_total{$label=~"$names",status=~"5.."}[5m])) / sum by ($label) (rate(http_requests_total{$label=~"$names"}[5m]))',
|
|
297
|
+
latency:
|
|
298
|
+
'histogram_quantile(0.95, sum by ($label, le) (rate(http_request_duration_seconds_bucket{$label=~"$names"}[5m])))',
|
|
299
|
+
rate: 'sum by ($label) (rate(http_requests_total{$label=~"$names"}[5m])) * 60',
|
|
300
|
+
logs: '{$label="$name"}',
|
|
301
|
+
traceTag: "service.name",
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const fill = (q, vars) => q.replace(/\$(label|names|name)\b/g, (_, k) => vars[k] ?? "");
|
|
305
|
+
|
|
306
|
+
/** The last value of each series in a data-source query answer, by the series' label. */
|
|
307
|
+
function lastByLabel(answer, refId, label) {
|
|
308
|
+
const out = {};
|
|
309
|
+
for (const fr of answer?.results?.[refId]?.frames ?? []) {
|
|
310
|
+
const fields = fr.schema?.fields ?? [];
|
|
311
|
+
const values = fr.data?.values ?? [];
|
|
312
|
+
fields.forEach((f, i) => {
|
|
313
|
+
if (f.type !== "number") return;
|
|
314
|
+
const name = f.labels?.[label];
|
|
315
|
+
const v = (values[i] ?? []).at(-1);
|
|
316
|
+
if (name && typeof v === "number" && Number.isFinite(v)) out[name] = v;
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* @param {{ url: string, token: string, label?: string, queries?: Partial<typeof DEFAULT_QUERIES>,
|
|
324
|
+
* fetch?: typeof fetch, now?: () => number }} o
|
|
325
|
+
*/
|
|
326
|
+
/** An address without a user name or password in it. */
|
|
327
|
+
const withoutCredentials = (u) => {
|
|
328
|
+
try {
|
|
329
|
+
const url = new URL(u);
|
|
330
|
+
url.username = "";
|
|
331
|
+
url.password = "";
|
|
332
|
+
return url.href.replace(/\/$/, "");
|
|
333
|
+
} catch {
|
|
334
|
+
return u;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
export function createMonitor(o) {
|
|
339
|
+
const base = o.url.replace(/\/+$/, "");
|
|
340
|
+
const label = o.label ?? "service";
|
|
341
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(label))
|
|
342
|
+
throw new Error("--grafana-label must be a label name");
|
|
343
|
+
const q = { ...DEFAULT_QUERIES, ...(o.queries ?? {}) };
|
|
344
|
+
const get = o.fetch ?? fetch;
|
|
345
|
+
const now = o.now ?? Date.now;
|
|
346
|
+
const call = async (path, body) => {
|
|
347
|
+
const res = await get(`${base}${path}`, {
|
|
348
|
+
method: body ? "POST" : "GET",
|
|
349
|
+
headers: {
|
|
350
|
+
authorization: `Bearer ${o.token}`,
|
|
351
|
+
accept: "application/json",
|
|
352
|
+
...(body ? { "content-type": "application/json" } : {}),
|
|
353
|
+
},
|
|
354
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
355
|
+
});
|
|
356
|
+
if (res.status === 401 || res.status === 403)
|
|
357
|
+
throw new Error("Grafana refused the token (it needs the Viewer role)");
|
|
358
|
+
if (!res.ok) throw new Error(`Grafana answered ${res.status}`);
|
|
359
|
+
return res.json();
|
|
360
|
+
};
|
|
361
|
+
let sources = null;
|
|
362
|
+
/** Grafana's Prometheus, Loki and Tempo (the first of each kind, or as configured). */
|
|
363
|
+
const ds = async () => {
|
|
364
|
+
sources ??= call("/api/datasources").then((list) => {
|
|
365
|
+
const of = (type) => (o.uids?.[type] ?? list.find((d) => d.type === type)?.uid) || null;
|
|
366
|
+
return { prometheus: of("prometheus"), loki: of("loki"), tempo: of("tempo") };
|
|
367
|
+
});
|
|
368
|
+
return sources.catch((err) => {
|
|
369
|
+
sources = null;
|
|
370
|
+
throw err;
|
|
371
|
+
});
|
|
372
|
+
};
|
|
373
|
+
const cache = new Map();
|
|
374
|
+
|
|
375
|
+
return {
|
|
376
|
+
label,
|
|
377
|
+
/** Grafana's address, for links into it (the customer's own, seen only by their browser). */
|
|
378
|
+
url: withoutCredentials(base),
|
|
379
|
+
async kinds() {
|
|
380
|
+
const d = await ds();
|
|
381
|
+
// The data sources' ids too: the browser links into the customer's Grafana with them.
|
|
382
|
+
return { metrics: !!d.prometheus, logs: !!d.loki, traces: !!d.tempo, uids: d };
|
|
383
|
+
},
|
|
384
|
+
/** Per name: up (true, false or unknown), the 5xx share and the slowest 5% (seconds). */
|
|
385
|
+
async status(names) {
|
|
386
|
+
const key = names.join(",");
|
|
387
|
+
const hit = cache.get(key);
|
|
388
|
+
if (hit && now() - hit.at < 10_000) return hit.value;
|
|
389
|
+
const d = await ds();
|
|
390
|
+
if (!d.prometheus) throw new Error("Grafana has no Prometheus data source");
|
|
391
|
+
const vars = { label, names: promAlternatives(names) };
|
|
392
|
+
const answer = await call("/api/ds/query", {
|
|
393
|
+
from: "now-5m",
|
|
394
|
+
to: "now",
|
|
395
|
+
queries: ["status", "errors", "latency", "rate"].map((refId) => ({
|
|
396
|
+
refId,
|
|
397
|
+
datasource: { uid: d.prometheus },
|
|
398
|
+
expr: fill(q[refId], vars),
|
|
399
|
+
instant: true,
|
|
400
|
+
})),
|
|
401
|
+
});
|
|
402
|
+
const up = lastByLabel(answer, "status", label);
|
|
403
|
+
const errors = lastByLabel(answer, "errors", label);
|
|
404
|
+
const latency = lastByLabel(answer, "latency", label);
|
|
405
|
+
const rate = lastByLabel(answer, "rate", label);
|
|
406
|
+
const items = {};
|
|
407
|
+
for (const n of names)
|
|
408
|
+
items[n] = {
|
|
409
|
+
up: n in up ? up[n] > 0 : null,
|
|
410
|
+
errorRate: n in errors ? errors[n] : null,
|
|
411
|
+
p95: n in latency ? latency[n] : null,
|
|
412
|
+
rpm: n in rate ? rate[n] : null,
|
|
413
|
+
};
|
|
414
|
+
const value = { at: now(), items };
|
|
415
|
+
cache.set(key, { at: now(), value });
|
|
416
|
+
if (cache.size > 200) cache.clear();
|
|
417
|
+
return value;
|
|
418
|
+
},
|
|
419
|
+
/** The latest log lines of one item, newest first. */
|
|
420
|
+
async logs(name, limit = 50) {
|
|
421
|
+
const d = await ds();
|
|
422
|
+
if (!d.loki) throw new Error("Grafana has no Loki data source");
|
|
423
|
+
const answer = await call("/api/ds/query", {
|
|
424
|
+
from: "now-1h",
|
|
425
|
+
to: "now",
|
|
426
|
+
queries: [
|
|
427
|
+
{
|
|
428
|
+
refId: "logs",
|
|
429
|
+
datasource: { uid: d.loki },
|
|
430
|
+
expr: fill(q.logs, { label, name }),
|
|
431
|
+
queryType: "range",
|
|
432
|
+
maxLines: limit,
|
|
433
|
+
},
|
|
434
|
+
],
|
|
435
|
+
});
|
|
436
|
+
const lines = [];
|
|
437
|
+
for (const fr of answer?.results?.logs?.frames ?? []) {
|
|
438
|
+
const fields = fr.schema?.fields ?? [];
|
|
439
|
+
const col = (n) => fr.data?.values?.[fields.findIndex((f) => f.name === n)] ?? [];
|
|
440
|
+
const times = col("Time");
|
|
441
|
+
const text = col("Line");
|
|
442
|
+
const labels = col("labels");
|
|
443
|
+
times.forEach((t, i) =>
|
|
444
|
+
lines.push({
|
|
445
|
+
at: Number(t),
|
|
446
|
+
line: String(text[i] ?? ""),
|
|
447
|
+
...(labels[i]?.level ? { level: String(labels[i].level) } : {}),
|
|
448
|
+
}),
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
return { lines: lines.sort((a, b) => b.at - a.at).slice(0, limit) };
|
|
452
|
+
},
|
|
453
|
+
/** Recent traces that pass through one item, with a link into Grafana for each. */
|
|
454
|
+
async traces(name, limit = 10) {
|
|
455
|
+
const d = await ds();
|
|
456
|
+
if (!d.tempo) throw new Error("Grafana has no Tempo data source");
|
|
457
|
+
const end = Math.floor(now() / 1000);
|
|
458
|
+
const found = await call(
|
|
459
|
+
`/api/datasources/proxy/uid/${encodeURIComponent(d.tempo)}/api/search?tags=${encodeURIComponent(`${q.traceTag}=${name}`)}&limit=${limit}&start=${end - 3600}&end=${end}`,
|
|
460
|
+
);
|
|
461
|
+
const link = (id) =>
|
|
462
|
+
`${base}/explore?schemaVersion=1&panes=${encodeURIComponent(
|
|
463
|
+
JSON.stringify({
|
|
464
|
+
t: {
|
|
465
|
+
datasource: d.tempo,
|
|
466
|
+
queries: [
|
|
467
|
+
{ refId: "A", datasource: { uid: d.tempo }, queryType: "traceql", query: id },
|
|
468
|
+
],
|
|
469
|
+
range: { from: "now-1h", to: "now" },
|
|
470
|
+
},
|
|
471
|
+
}),
|
|
472
|
+
)}`;
|
|
473
|
+
return {
|
|
474
|
+
traces: (found?.traces ?? []).map((t) => ({
|
|
475
|
+
id: String(t.traceID),
|
|
476
|
+
root: String(t.rootServiceName ?? ""),
|
|
477
|
+
name: String(t.rootTraceName ?? ""),
|
|
478
|
+
start: Math.round(Number(t.startTimeUnixNano ?? 0) / 1e6),
|
|
479
|
+
ms: Number(t.durationMs ?? 0),
|
|
480
|
+
url: link(String(t.traceID)),
|
|
481
|
+
})),
|
|
482
|
+
};
|
|
483
|
+
},
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* The agent: collect now and every `everyMs`, and answer FlowShape's requests.
|
|
489
|
+
* @param {{ collectors: Collector[], key: string, origins?: string[], everyMs?: number,
|
|
490
|
+
* name?: string, log?: (s: string) => void, monitor?: ReturnType<typeof createMonitor> }} o
|
|
491
|
+
*/
|
|
492
|
+
export function createAgent(o) {
|
|
493
|
+
const origins = new Set(o.origins ?? DEFAULT_ORIGINS);
|
|
494
|
+
const log = o.log ?? (() => {});
|
|
495
|
+
/** @type {Map<string, { text?: string, contentType?: string, collectedAt?: number, error?: string, running?: Promise<void> }>} */
|
|
496
|
+
const results = new Map(o.collectors.map((c) => [c.id, {}]));
|
|
497
|
+
|
|
498
|
+
const collectOne = (c) => {
|
|
499
|
+
const r = results.get(c.id);
|
|
500
|
+
if (r.running) return r.running;
|
|
501
|
+
r.running = c
|
|
502
|
+
.run()
|
|
503
|
+
.then((res) => {
|
|
504
|
+
Object.assign(r, {
|
|
505
|
+
text: res.text,
|
|
506
|
+
contentType: res.contentType,
|
|
507
|
+
collectedAt: Date.now(),
|
|
508
|
+
error: undefined,
|
|
509
|
+
});
|
|
510
|
+
log(`collected ${c.label} (${Math.round(res.text.length / 1024)} KB)`);
|
|
511
|
+
})
|
|
512
|
+
.catch((err) => {
|
|
513
|
+
r.error = String(err.message ?? err);
|
|
514
|
+
log(`couldn't collect ${c.label}: ${r.error}`);
|
|
515
|
+
})
|
|
516
|
+
.finally(() => {
|
|
517
|
+
r.running = undefined;
|
|
518
|
+
});
|
|
519
|
+
return r.running;
|
|
520
|
+
};
|
|
521
|
+
const collectAll = () => Promise.all(o.collectors.map(collectOne));
|
|
522
|
+
const timer = o.everyMs ? setInterval(() => void collectAll(), o.everyMs) : null;
|
|
523
|
+
|
|
524
|
+
if (typeof o.key !== "string" || o.key.length < MIN_KEY)
|
|
525
|
+
throw new Error(`the agent's key must be at least ${MIN_KEY} characters`);
|
|
526
|
+
const key = Buffer.from(o.key);
|
|
527
|
+
const authorised = (req) => {
|
|
528
|
+
const h = req.headers.authorization ?? "";
|
|
529
|
+
const given = Buffer.from(h.startsWith("Bearer ") ? h.slice(7) : "");
|
|
530
|
+
return key.length > 0 && given.length === key.length && timingSafeEqual(given, key);
|
|
531
|
+
};
|
|
532
|
+
// Bound to this computer: answer to its own names only, so a rebound DNS name can't reach it.
|
|
533
|
+
const loopbackOnly = !o.host || ["127.0.0.1", "localhost", "::1"].includes(o.host);
|
|
534
|
+
const LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
|
|
535
|
+
const info = () => ({
|
|
536
|
+
agent: "flowshape-agent",
|
|
537
|
+
version: VERSION,
|
|
538
|
+
name: o.name ?? hostname(),
|
|
539
|
+
everyMs: o.everyMs ?? null,
|
|
540
|
+
...(o.monitor
|
|
541
|
+
? { monitoring: { grafana: true, label: o.monitor.label, url: o.monitor.url } }
|
|
542
|
+
: {}),
|
|
543
|
+
sources: o.collectors.map((c) => {
|
|
544
|
+
const r = results.get(c.id);
|
|
545
|
+
return {
|
|
546
|
+
id: c.id,
|
|
547
|
+
type: c.type,
|
|
548
|
+
label: c.label,
|
|
549
|
+
collectedAt: r.collectedAt ?? null,
|
|
550
|
+
ok: !!r.text,
|
|
551
|
+
running: !!r.running,
|
|
552
|
+
...(r.error ? { error: r.error } : {}),
|
|
553
|
+
};
|
|
554
|
+
}),
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
// Said once each in the terminal, so whoever runs the agent sees whether the page got through.
|
|
558
|
+
const noted = new Set();
|
|
559
|
+
const note = (what, text) => {
|
|
560
|
+
if (noted.has(what)) return;
|
|
561
|
+
if (noted.size > 100) noted.clear();
|
|
562
|
+
noted.add(what);
|
|
563
|
+
log(text);
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
const server = createServer(async (req, res) => {
|
|
567
|
+
const origin = req.headers.origin;
|
|
568
|
+
const allowed = !!origin && origins.has(origin);
|
|
569
|
+
if (allowed) {
|
|
570
|
+
res.setHeader("access-control-allow-origin", origin);
|
|
571
|
+
res.setHeader("vary", "origin");
|
|
572
|
+
res.setHeader("access-control-allow-headers", "authorization");
|
|
573
|
+
res.setHeader("access-control-allow-methods", "GET, POST");
|
|
574
|
+
// Older Chrome's private network access preflight (today's Chrome asks the person
|
|
575
|
+
// instead: its local network permission).
|
|
576
|
+
res.setHeader("access-control-allow-private-network", "true");
|
|
577
|
+
res.setHeader("access-control-max-age", "600");
|
|
578
|
+
}
|
|
579
|
+
res.setHeader("cache-control", "no-store");
|
|
580
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
581
|
+
const send = (status, body, type = "application/json") => {
|
|
582
|
+
res.writeHead(status, { "content-type": type });
|
|
583
|
+
res.end(typeof body === "string" ? body : JSON.stringify(body));
|
|
584
|
+
};
|
|
585
|
+
if (loopbackOnly && !LOOPBACK_HOST.test(req.headers.host ?? "")) {
|
|
586
|
+
note(
|
|
587
|
+
`host ${req.headers.host}`,
|
|
588
|
+
`Refused a request for ${req.headers.host}: not this computer's address.`,
|
|
589
|
+
);
|
|
590
|
+
return send(421, { error: "this agent answers on this computer's own address only" });
|
|
591
|
+
}
|
|
592
|
+
// Browsers send an Origin; other pages than FlowShape's get nothing.
|
|
593
|
+
if (origin && !allowed) {
|
|
594
|
+
note(`origin ${origin}`, `Refused a page at ${origin}: it isn't FlowShape.`);
|
|
595
|
+
return send(403, { error: "this page may not use the agent" });
|
|
596
|
+
}
|
|
597
|
+
if (req.method === "OPTIONS") return send(204, "");
|
|
598
|
+
if (!authorised(req)) {
|
|
599
|
+
if (origin)
|
|
600
|
+
note(
|
|
601
|
+
"key",
|
|
602
|
+
"A FlowShape page asked with a different key: it is set up for another agent. Run the command it shows now.",
|
|
603
|
+
);
|
|
604
|
+
else note("key-other", "Refused a request without the agent's key.");
|
|
605
|
+
return send(401, { error: "the agent's key is missing or wrong" });
|
|
606
|
+
}
|
|
607
|
+
if (origin) note(`connected ${origin}`, `FlowShape connected (${origin}).`);
|
|
608
|
+
const url = new URL(req.url ?? "/", "http://agent");
|
|
609
|
+
if (req.method === "GET" && url.pathname === "/v1/info") return send(200, info());
|
|
610
|
+
if (req.method === "POST" && url.pathname === "/v1/collect") {
|
|
611
|
+
await collectAll();
|
|
612
|
+
return send(200, info());
|
|
613
|
+
}
|
|
614
|
+
if (req.method === "GET" && url.pathname.startsWith("/v1/monitoring")) {
|
|
615
|
+
if (!o.monitor) return send(404, { error: "this agent isn't connected to Grafana" });
|
|
616
|
+
try {
|
|
617
|
+
if (url.pathname === "/v1/monitoring")
|
|
618
|
+
return send(200, {
|
|
619
|
+
label: o.monitor.label,
|
|
620
|
+
url: o.monitor.url,
|
|
621
|
+
...(await o.monitor.kinds()),
|
|
622
|
+
});
|
|
623
|
+
if (url.pathname === "/v1/monitoring/status") {
|
|
624
|
+
const names = [
|
|
625
|
+
...new Set((url.searchParams.get("names") ?? "").split(",").filter(Boolean)),
|
|
626
|
+
];
|
|
627
|
+
if (!names.length || names.length > 300 || !names.every((n) => NAME.test(n)))
|
|
628
|
+
return send(400, { error: "names: up to 300 item names" });
|
|
629
|
+
return send(200, await o.monitor.status(names));
|
|
630
|
+
}
|
|
631
|
+
const name = url.searchParams.get("name") ?? "";
|
|
632
|
+
if (!NAME.test(name)) return send(400, { error: "name: one item name" });
|
|
633
|
+
if (url.pathname === "/v1/monitoring/logs") return send(200, await o.monitor.logs(name));
|
|
634
|
+
if (url.pathname === "/v1/monitoring/traces")
|
|
635
|
+
return send(200, await o.monitor.traces(name));
|
|
636
|
+
} catch (err) {
|
|
637
|
+
return send(502, { error: String(err.message ?? err) });
|
|
638
|
+
}
|
|
639
|
+
return send(404, { error: "no such route" });
|
|
640
|
+
}
|
|
641
|
+
const m = /^\/v1\/sources\/([\w-]+)$/.exec(url.pathname);
|
|
642
|
+
if (req.method === "GET" && m) {
|
|
643
|
+
const r = results.get(m[1]);
|
|
644
|
+
if (!r) return send(404, { error: "no such source" });
|
|
645
|
+
if (r.running && !r.text) await r.running;
|
|
646
|
+
if (!r.text) return send(503, { error: r.error ?? "not collected yet" });
|
|
647
|
+
res.setHeader("x-collected-at", String(r.collectedAt));
|
|
648
|
+
return send(200, r.text, r.contentType);
|
|
649
|
+
}
|
|
650
|
+
return send(404, { error: "no such route" });
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
return {
|
|
654
|
+
server,
|
|
655
|
+
collectAll,
|
|
656
|
+
info,
|
|
657
|
+
close() {
|
|
658
|
+
if (timer) clearInterval(timer);
|
|
659
|
+
return new Promise((r) => server.close(() => r()));
|
|
660
|
+
},
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/* ---------------------------------------------------------------- command line */
|
|
665
|
+
|
|
666
|
+
const DURATION = /^(\d+)(s|m|h)$/;
|
|
667
|
+
export function parseArgs(argv) {
|
|
668
|
+
const o = { terraform: [], nmap: [], files: [], origins: [], port: 7777, host: "127.0.0.1" };
|
|
669
|
+
for (let i = 0; i < argv.length; i++) {
|
|
670
|
+
const a = argv[i];
|
|
671
|
+
const next = () => {
|
|
672
|
+
const v = argv[++i];
|
|
673
|
+
if (v === undefined || v.startsWith("--")) throw new Error(`${a} needs a value`);
|
|
674
|
+
return v;
|
|
675
|
+
};
|
|
676
|
+
if (a === "--azure") o.azure = true;
|
|
677
|
+
else if (a === "--subscription") o.subscription = next();
|
|
678
|
+
else if (a === "--terraform") o.terraform.push(next());
|
|
679
|
+
else if (a === "--kubernetes") o.kubernetes = true;
|
|
680
|
+
else if (a === "--context") o.context = next();
|
|
681
|
+
else if (a === "--nmap") o.nmap.push(next());
|
|
682
|
+
else if (a === "--file") o.files.push(next());
|
|
683
|
+
else if (a === "--demo") o.demo = true;
|
|
684
|
+
else if (a === "--grafana") o.grafana = next();
|
|
685
|
+
else if (a === "--grafana-token-file") o.grafanaTokenFile = next();
|
|
686
|
+
else if (a === "--grafana-label") o.grafanaLabel = next();
|
|
687
|
+
else if (a === "--grafana-queries") o.grafanaQueries = next();
|
|
688
|
+
else if (a === "--port") {
|
|
689
|
+
const port = Number(next());
|
|
690
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
691
|
+
throw new Error("--port takes a number from 1 to 65535");
|
|
692
|
+
o.port = port;
|
|
693
|
+
} else if (a === "--host") o.host = next();
|
|
694
|
+
else if (a === "--origin") o.origins.push(next());
|
|
695
|
+
// Any value: a generated key may itself start with "--".
|
|
696
|
+
else if (a === "--key") {
|
|
697
|
+
if (argv[i + 1] === undefined) throw new Error("--key needs a value");
|
|
698
|
+
o.key = argv[++i];
|
|
699
|
+
} else if (a === "--key-file") o.keyFile = next();
|
|
700
|
+
else if (a === "--every") {
|
|
701
|
+
const m = DURATION.exec(next());
|
|
702
|
+
if (!m) throw new Error("--every takes e.g. 15m, 1h or 90s");
|
|
703
|
+
o.everyMs = Number(m[1]) * { s: 1000, m: 60_000, h: 3_600_000 }[m[2]];
|
|
704
|
+
} else if (a === "--help" || a === "-h") o.help = true;
|
|
705
|
+
else throw new Error(`unknown option ${a}`);
|
|
706
|
+
}
|
|
707
|
+
return o;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const HELP = `FlowShape agent ${VERSION}
|
|
711
|
+
|
|
712
|
+
Collects what is running, with your vendors' own tools, and lets FlowShape in your browser
|
|
713
|
+
draw it. It never contacts FlowShape or any third party: FlowShape's page fetches the results
|
|
714
|
+
from this machine. Docs: https://docs.flowshape.io/agent/
|
|
715
|
+
|
|
716
|
+
--azure [--subscription <id>] Azure Resource Graph (az login first; Reader is enough)
|
|
717
|
+
--terraform <dir> terraform show -json in that folder (repeatable)
|
|
718
|
+
--kubernetes [--context <name>] kubectl get … -o json (secret values are removed)
|
|
719
|
+
--nmap <range> nmap -sV --traceroute (only networks you may scan)
|
|
720
|
+
--file <path> serve a file you collected yourself (repeatable)
|
|
721
|
+
--demo sample environments, to try FlowShape without tools
|
|
722
|
+
--grafana <url> live status, logs and traces on diagrams, from your Grafana
|
|
723
|
+
--grafana-token-file <path> a Viewer service-account token (or FLOWSHAPE_GRAFANA_TOKEN)
|
|
724
|
+
--grafana-label <service> the label that names an item in metrics and logs
|
|
725
|
+
--grafana-queries <file.json> your own PromQL / LogQL for status, errors, latency, logs
|
|
726
|
+
--every <15m|1h|90s> collect again on a schedule (default: once, then on request)
|
|
727
|
+
--key <key> the key FlowShape uses (16+ characters; or FLOWSHAPE_AGENT_KEY,
|
|
728
|
+
--key-file <path> or a file); a random one is made when none is given
|
|
729
|
+
--port <7777> --host <127.0.0.1> --origin <url> (another FlowShape address)
|
|
730
|
+
`;
|
|
731
|
+
|
|
732
|
+
async function main() {
|
|
733
|
+
let o;
|
|
734
|
+
try {
|
|
735
|
+
o = parseArgs(process.argv.slice(2));
|
|
736
|
+
} catch (err) {
|
|
737
|
+
console.error(String(err.message), "\n\n" + HELP);
|
|
738
|
+
process.exit(2);
|
|
739
|
+
}
|
|
740
|
+
const fail = (text) => {
|
|
741
|
+
console.error(text);
|
|
742
|
+
process.exit(2);
|
|
743
|
+
};
|
|
744
|
+
/** A file the agent needs to start (a token, a key, queries), or a clear message. */
|
|
745
|
+
const readNeeded = async (p, what) => {
|
|
746
|
+
try {
|
|
747
|
+
return await readFile(p, "utf8");
|
|
748
|
+
} catch (err) {
|
|
749
|
+
return fail(`Couldn't read ${what} (${p}): ${err.code ?? err.message}`);
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
const list = collectors(o);
|
|
753
|
+
let monitor;
|
|
754
|
+
if (o.grafana) {
|
|
755
|
+
const token = o.grafanaTokenFile
|
|
756
|
+
? (await readNeeded(o.grafanaTokenFile, "the Grafana token")).trim()
|
|
757
|
+
: process.env.FLOWSHAPE_GRAFANA_TOKEN;
|
|
758
|
+
if (!token) {
|
|
759
|
+
console.error(
|
|
760
|
+
"--grafana needs a token: --grafana-token-file <path> or FLOWSHAPE_GRAFANA_TOKEN",
|
|
761
|
+
);
|
|
762
|
+
process.exit(2);
|
|
763
|
+
}
|
|
764
|
+
monitor = createMonitor({
|
|
765
|
+
url: o.grafana,
|
|
766
|
+
token,
|
|
767
|
+
label: o.grafanaLabel,
|
|
768
|
+
queries: o.grafanaQueries
|
|
769
|
+
? await readNeeded(o.grafanaQueries, "the Grafana queries").then((t) => {
|
|
770
|
+
try {
|
|
771
|
+
return JSON.parse(t);
|
|
772
|
+
} catch {
|
|
773
|
+
return fail(`${o.grafanaQueries} isn't valid JSON`);
|
|
774
|
+
}
|
|
775
|
+
})
|
|
776
|
+
: undefined,
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
if (o.help || (!list.length && !monitor)) {
|
|
780
|
+
console.log(HELP);
|
|
781
|
+
process.exit(o.help ? 0 : 2);
|
|
782
|
+
}
|
|
783
|
+
if (o.nmap.length)
|
|
784
|
+
console.warn(
|
|
785
|
+
"Scan only networks you own or are allowed to test: scanning others can be illegal.",
|
|
786
|
+
);
|
|
787
|
+
// The key: given (an option, the environment or a file: the last two stay out of shell
|
|
788
|
+
// history and process lists), or a new random one.
|
|
789
|
+
const given =
|
|
790
|
+
o.key ??
|
|
791
|
+
(o.keyFile ? (await readNeeded(o.keyFile, "the key")).trim() : undefined) ??
|
|
792
|
+
process.env.FLOWSHAPE_AGENT_KEY;
|
|
793
|
+
if (given !== undefined && given.length < MIN_KEY)
|
|
794
|
+
fail(
|
|
795
|
+
`The key is too short (${given.length} characters; at least ${MIN_KEY}). Leave it out to get a random one.`,
|
|
796
|
+
);
|
|
797
|
+
const key = given ?? randomBytes(24).toString("base64url");
|
|
798
|
+
const agent = createAgent({
|
|
799
|
+
collectors: list,
|
|
800
|
+
key,
|
|
801
|
+
host: o.host,
|
|
802
|
+
origins: [...DEFAULT_ORIGINS, ...o.origins],
|
|
803
|
+
everyMs: o.everyMs,
|
|
804
|
+
monitor,
|
|
805
|
+
log: (s) => console.log(`${new Date().toISOString().slice(11, 19)} ${s}`),
|
|
806
|
+
});
|
|
807
|
+
if (!["127.0.0.1", "localhost", "::1"].includes(o.host))
|
|
808
|
+
console.warn(
|
|
809
|
+
`Listening on ${o.host}: other machines can reach the agent (plain HTTP, its key the only lock). FlowShape reaches an agent on your own computer only; for one on another machine, forward its port instead: ssh -N -L ${o.port}:127.0.0.1:${o.port} you@that-machine`,
|
|
810
|
+
);
|
|
811
|
+
agent.server.on("error", (err) =>
|
|
812
|
+
fail(
|
|
813
|
+
err.code === "EADDRINUSE"
|
|
814
|
+
? `Port ${o.port} is in use: another agent may be running. Stop it, or start this one with --port <another>.`
|
|
815
|
+
: `Couldn't listen on ${o.host}:${o.port}: ${err.code ?? err.message}`,
|
|
816
|
+
),
|
|
817
|
+
);
|
|
818
|
+
agent.server.listen(o.port, o.host, () => {
|
|
819
|
+
const shown = o.host === "0.0.0.0" || o.host === "::" ? "127.0.0.1" : o.host;
|
|
820
|
+
const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${o.port}`;
|
|
821
|
+
console.log(`\nFlowShape agent ${VERSION} on ${url}`);
|
|
822
|
+
console.log(
|
|
823
|
+
[
|
|
824
|
+
'FlowShape finds it by itself; this window says "FlowShape connected" when it does.',
|
|
825
|
+
"If your browser asks to let FlowShape reach devices on your local network (or apps on",
|
|
826
|
+
"this device), choose Allow: that is how the page talks to this agent, directly.",
|
|
827
|
+
`Or paste this address in FlowShape:\n\n ${url}#key=${key}\n`,
|
|
828
|
+
].join("\n"),
|
|
829
|
+
);
|
|
830
|
+
});
|
|
831
|
+
await agent.collectAll();
|
|
832
|
+
process.on("SIGINT", () => void agent.close().then(() => process.exit(0)));
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** Started as a program (also through a symlink, as npm installs a bin), not imported. */
|
|
836
|
+
const isMain = () => {
|
|
837
|
+
try {
|
|
838
|
+
return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
839
|
+
} catch {
|
|
840
|
+
return false;
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
if (process.argv[1] && isMain()) void main();
|