@celljs/ta-secops 4.35.0 → 4.36.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.
Files changed (2) hide show
  1. package/host/index.mjs +665 -62
  2. package/package.json +4 -4
package/host/index.mjs CHANGED
@@ -1,10 +1,441 @@
1
1
  // web-src/host.ts
2
- import { readFile as readFile6 } from "node:fs/promises";
3
- import { join as join5 } from "node:path";
2
+ import { readFile as readFile5 } from "node:fs/promises";
3
+ import { join as join6 } from "node:path";
4
4
 
5
5
  // web-src/secops-desk.ts
6
- import { appendFile as appendFile3, mkdir as mkdir4, readFile as readFile5, stat as stat2 } from "node:fs/promises";
7
- import { join as join4 } from "node:path";
6
+ import { mkdir as mkdir5 } from "node:fs/promises";
7
+ import { join as join5 } from "node:path";
8
+
9
+ // ../../packages/core/esm/common/utils/error-util.js
10
+ class ErrorUtil {
11
+ static fixProto(target, prototype) {
12
+ const setPrototypeOf = Object.setPrototypeOf;
13
+ if (setPrototypeOf) {
14
+ setPrototypeOf(target, prototype);
15
+ } else {
16
+ target.__proto__ = prototype;
17
+ }
18
+ }
19
+ static fixStack(target, fn = target.constructor) {
20
+ const captureStackTrace = Error.captureStackTrace;
21
+ if (captureStackTrace) {
22
+ captureStackTrace(target, fn);
23
+ }
24
+ }
25
+ static describe(error) {
26
+ let text = ErrorUtil.describeOne(error);
27
+ let cause = ErrorUtil.causeOf(error);
28
+ for (let depth = 0;cause !== undefined && depth < 5; depth++) {
29
+ text += `
30
+ Caused by: ${ErrorUtil.describeOne(cause)}`;
31
+ cause = ErrorUtil.causeOf(cause);
32
+ }
33
+ return text;
34
+ }
35
+ static causeOf(error) {
36
+ return error instanceof Error ? error.cause : undefined;
37
+ }
38
+ static describeOne(error) {
39
+ var _a;
40
+ if (error instanceof Error) {
41
+ return (_a = error.stack) !== null && _a !== undefined ? _a : `${error.name}: ${error.message}`;
42
+ }
43
+ return String(error);
44
+ }
45
+ }
46
+
47
+ // ../../packages/core/esm/common/utils/event.js
48
+ var Event;
49
+ (function(Event2) {
50
+ const _disposable = { dispose() {} };
51
+ Event2.None = Object.assign(function() {
52
+ return _disposable;
53
+ }, {
54
+ get maxListeners() {
55
+ return 0;
56
+ },
57
+ set maxListeners(maxListeners) {}
58
+ });
59
+ function map(event, mapFunc) {
60
+ return Object.assign((listener, thisArgs, disposables) => event((i) => listener.call(thisArgs, mapFunc(i)), undefined, disposables), {
61
+ maxListeners: 0
62
+ });
63
+ }
64
+ Event2.map = map;
65
+ })(Event || (Event = {}));
66
+
67
+ class CallbackList {
68
+ get length() {
69
+ return this._callbacks && this._callbacks.length || 0;
70
+ }
71
+ add(callback, context = undefined, bucket) {
72
+ if (!this._callbacks) {
73
+ this._callbacks = [];
74
+ this._contexts = [];
75
+ }
76
+ this._callbacks.push(callback);
77
+ this._contexts.push(context);
78
+ if (Array.isArray(bucket)) {
79
+ bucket.push({ dispose: () => this.remove(callback, context) });
80
+ }
81
+ }
82
+ remove(callback, context = undefined) {
83
+ if (!this._callbacks) {
84
+ return;
85
+ }
86
+ let foundCallbackWithDifferentContext = false;
87
+ for (let i = 0;i < this._callbacks.length; i++) {
88
+ if (this._callbacks[i] === callback) {
89
+ if (this._contexts[i] === context) {
90
+ this._callbacks.splice(i, 1);
91
+ this._contexts.splice(i, 1);
92
+ return;
93
+ } else {
94
+ foundCallbackWithDifferentContext = true;
95
+ }
96
+ }
97
+ }
98
+ if (foundCallbackWithDifferentContext) {
99
+ throw new Error("When adding a listener with a context, you should remove it with the same context");
100
+ }
101
+ }
102
+ *[Symbol.iterator]() {
103
+ if (!this._callbacks) {
104
+ return;
105
+ }
106
+ const callbacks = this._callbacks.slice(0);
107
+ const contexts = this._contexts.slice(0);
108
+ for (let i = 0;i < callbacks.length; i++) {
109
+ const callback = callbacks[i];
110
+ const context = contexts[i];
111
+ yield (...args) => callback.apply(context, args);
112
+ }
113
+ }
114
+ invoke(...args) {
115
+ if (!this._callbacks) {
116
+ return [];
117
+ }
118
+ const callbacks = this._callbacks.slice(0);
119
+ const contexts = this._contexts.slice(0);
120
+ const ret = [];
121
+ for (let i = 0;i < callbacks.length; i++) {
122
+ try {
123
+ ret.push(callbacks[i].apply(contexts[i], args));
124
+ } catch (e) {
125
+ console.error(e);
126
+ }
127
+ }
128
+ return ret;
129
+ }
130
+ isEmpty() {
131
+ return !this._callbacks || this._callbacks.length === 0;
132
+ }
133
+ dispose() {
134
+ this._callbacks = undefined;
135
+ this._contexts = undefined;
136
+ }
137
+ }
138
+
139
+ // ../../packages/core/esm/common/utils/emitter.js
140
+ class Emitter {
141
+ constructor(_options) {
142
+ this._options = _options;
143
+ this._disposed = false;
144
+ this._leakWarnCountdown = 0;
145
+ }
146
+ get event() {
147
+ if (!this._event) {
148
+ this._event = Object.assign((listener, thisArgs, disposables) => {
149
+ if (!this._callbacks) {
150
+ this._callbacks = new CallbackList;
151
+ }
152
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
153
+ this._options.onFirstListenerAdd(this);
154
+ }
155
+ this._callbacks.add(listener, thisArgs);
156
+ const removeMaxListenersCheck = this.checkMaxListeners(this._event.maxListeners);
157
+ const result = {
158
+ dispose: () => {
159
+ if (removeMaxListenersCheck) {
160
+ removeMaxListenersCheck();
161
+ }
162
+ result.dispose = Emitter._noop;
163
+ if (!this._disposed) {
164
+ this._callbacks.remove(listener, thisArgs);
165
+ result.dispose = Emitter._noop;
166
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
167
+ this._options.onLastListenerRemove(this);
168
+ }
169
+ }
170
+ }
171
+ };
172
+ if (Array.isArray(disposables)) {
173
+ disposables.push(result);
174
+ }
175
+ return result;
176
+ }, {
177
+ maxListeners: Emitter.LEAK_WARNING_THRESHHOLD
178
+ });
179
+ }
180
+ return this._event;
181
+ }
182
+ checkMaxListeners(maxListeners) {
183
+ if (maxListeners === 0 || !this._callbacks) {
184
+ return;
185
+ }
186
+ const listenerCount = this._callbacks.length;
187
+ if (listenerCount <= maxListeners) {
188
+ return;
189
+ }
190
+ const popStack = this.pushLeakingStack();
191
+ this._leakWarnCountdown -= 1;
192
+ if (this._leakWarnCountdown <= 0) {
193
+ this._leakWarnCountdown = maxListeners * 0.5;
194
+ let topStack;
195
+ let topCount = 0;
196
+ this._leakingStacks.forEach((stackCount, stack) => {
197
+ if (!topStack || topCount < stackCount) {
198
+ topStack = stack;
199
+ topCount = stackCount;
200
+ }
201
+ });
202
+ console.warn(`Possible Emitter memory leak detected. ${listenerCount} listeners added. Use event.maxListeners to increase the limit (${maxListeners}). MOST frequent listener (${topCount}):`);
203
+ console.warn(topStack);
204
+ }
205
+ return popStack;
206
+ }
207
+ pushLeakingStack() {
208
+ if (!this._leakingStacks) {
209
+ this._leakingStacks = new Map;
210
+ }
211
+ const stack = new Error().stack.split(`
212
+ `).slice(3).join(`
213
+ `);
214
+ const count = this._leakingStacks.get(stack) || 0;
215
+ this._leakingStacks.set(stack, count + 1);
216
+ return () => this.popLeakingStack(stack);
217
+ }
218
+ popLeakingStack(stack) {
219
+ if (!this._leakingStacks) {
220
+ return;
221
+ }
222
+ const count = this._leakingStacks.get(stack) || 0;
223
+ this._leakingStacks.set(stack, count - 1);
224
+ }
225
+ get hasListeners() {
226
+ return !!this._callbacks && !this._callbacks.isEmpty();
227
+ }
228
+ fire(event) {
229
+ if (this._callbacks) {
230
+ this._callbacks.invoke(event);
231
+ }
232
+ }
233
+ async sequence(processor) {
234
+ if (this._callbacks) {
235
+ for (const listener of this._callbacks) {
236
+ if (!await processor(listener)) {
237
+ break;
238
+ }
239
+ }
240
+ }
241
+ }
242
+ dispose() {
243
+ if (this._leakingStacks) {
244
+ this._leakingStacks.clear();
245
+ this._leakingStacks = undefined;
246
+ }
247
+ if (this._callbacks) {
248
+ this._callbacks.dispose();
249
+ this._callbacks = undefined;
250
+ }
251
+ this._disposed = true;
252
+ }
253
+ }
254
+ Emitter.LEAK_WARNING_THRESHHOLD = 175;
255
+ Emitter._noop = function() {};
256
+ var WaitUntilEvent;
257
+ (function(WaitUntilEvent2) {
258
+ async function fire(emitter, event, timeout = undefined) {
259
+ const waitables = [];
260
+ const asyncEvent = Object.assign(event, {
261
+ waitUntil: (thenable) => {
262
+ if (Object.isFrozen(waitables)) {
263
+ throw new Error("waitUntil cannot be called asynchronously.");
264
+ }
265
+ waitables.push(thenable);
266
+ }
267
+ });
268
+ try {
269
+ emitter.fire(asyncEvent);
270
+ Object.freeze(waitables);
271
+ } finally {
272
+ delete asyncEvent.waitUntil;
273
+ }
274
+ if (!waitables.length) {
275
+ return;
276
+ }
277
+ if (timeout !== undefined) {
278
+ await Promise.race([Promise.all(waitables), new Promise((resolve) => setTimeout(resolve, timeout))]);
279
+ } else {
280
+ await Promise.all(waitables);
281
+ }
282
+ }
283
+ WaitUntilEvent2.fire = fire;
284
+ })(WaitUntilEvent || (WaitUntilEvent = {}));
285
+
286
+ // ../../packages/core/esm/common/logger/logger-protocol.js
287
+ var LOGGER_CONFIG = "logger";
288
+ var LOGGER_LEVEL = `${LOGGER_CONFIG}.level`;
289
+ var Logger = Symbol("Logger");
290
+ var TraceIdProvider = Symbol("TraceIdProvider");
291
+ var LoggerService = Symbol("LoggerService");
292
+ var LOG_LEVELS = ["verbose", "debug", "info", "warn", "error"];
293
+ var onLogEmitter = new Emitter;
294
+
295
+ // ../../packages/core/esm/common/logger/console-logger.js
296
+ var RANK = Object.fromEntries(LOG_LEVELS.map((level, index) => [level, index]));
297
+ var write = {
298
+ error: (text) => console.error(text),
299
+ warn: (text) => console.warn(text),
300
+ info: (text) => console.info(text),
301
+ debug: (text) => console.debug(text)
302
+ };
303
+ var LEVEL = Symbol.for("@celljs/core/logger/level");
304
+ var Loggers;
305
+ (function(Loggers2) {
306
+ function get(context) {
307
+ return new ConsoleLogger(context);
308
+ }
309
+ Loggers2.get = get;
310
+ function level() {
311
+ var _a;
312
+ const set = globalThis[LEVEL];
313
+ if (set) {
314
+ return set;
315
+ }
316
+ const env = typeof process === "undefined" ? undefined : (_a = process.env) === null || _a === undefined ? undefined : _a.CELL_LOGGER__LEVEL;
317
+ return env && env in RANK ? env : "info";
318
+ }
319
+ Loggers2.level = level;
320
+ function setLevel(level2) {
321
+ globalThis[LEVEL] = level2 && level2 in RANK ? level2 : undefined;
322
+ }
323
+ Loggers2.setLevel = setLevel;
324
+ })(Loggers || (Loggers = {}));
325
+
326
+ class ConsoleLogger {
327
+ constructor(context) {
328
+ this.context = context;
329
+ }
330
+ setContext(context) {
331
+ this.context = context;
332
+ }
333
+ isEnabled(level) {
334
+ var _a, _b;
335
+ return RANK[level] >= ((_b = RANK[(_a = this.level) !== null && _a !== undefined ? _a : Loggers.level()]) !== null && _b !== undefined ? _b : RANK.info);
336
+ }
337
+ error(message, context) {
338
+ this.log(message, context, write.error, "error");
339
+ }
340
+ warn(message, context) {
341
+ if (this.isEnabled("warn")) {
342
+ this.log(message, context, write.warn, "warn");
343
+ }
344
+ }
345
+ info(message, context) {
346
+ if (this.isEnabled("info")) {
347
+ this.log(message, context, write.info, "info");
348
+ }
349
+ }
350
+ debug(message, context) {
351
+ if (this.isEnabled("debug")) {
352
+ this.log(message, context, write.debug, "debug");
353
+ }
354
+ }
355
+ time(label) {
356
+ var _a;
357
+ ((_a = this.timeRecords) !== null && _a !== undefined ? _a : this.timeRecords = new Map).set(label, Date.now());
358
+ }
359
+ timeEnd(label, context) {
360
+ var _a;
361
+ const start = (_a = this.timeRecords) === null || _a === undefined ? undefined : _a.get(label);
362
+ if (start !== undefined) {
363
+ const duration = Date.now() - start;
364
+ this.timeRecords.delete(label);
365
+ this.log(`${label} [${duration}ms]`, context);
366
+ return duration;
367
+ } else {
368
+ this.log(`No such label: ${label} for timeEnd`, context);
369
+ return;
370
+ }
371
+ }
372
+ resolveContextString(context) {
373
+ if (this.context) {
374
+ return context ? `[${this.context}] [${context}] ` : `[${this.context}] `;
375
+ }
376
+ return context ? `[${context}] ` : "";
377
+ }
378
+ resolvePrefix(level) {
379
+ const time = new Date().toISOString();
380
+ return `${time} [${level}]`;
381
+ }
382
+ log(message, context, logFn = write.info, level = "info") {
383
+ var _a;
384
+ const traceId = (_a = this.traceIdProvider) === null || _a === undefined ? undefined : _a.provide();
385
+ const contextStr = this.resolveContextString(context);
386
+ const text = message instanceof Error ? ErrorUtil.describe(message) : message;
387
+ let head = this.resolvePrefix(level);
388
+ if (traceId) {
389
+ head = head ? `${head} [trace: ${traceId}]` : `[trace: ${traceId}]`;
390
+ }
391
+ logFn(`${head ? `${head} ` : ""}${contextStr}${text}`);
392
+ if (onLogEmitter.hasListeners) {
393
+ onLogEmitter.fire({
394
+ level,
395
+ traceId,
396
+ rootContext: this.context,
397
+ context,
398
+ message
399
+ });
400
+ }
401
+ }
402
+ }
403
+
404
+ // ../../packages/core/esm/node/fs/file-retention.js
405
+ import { appendFileSync, chmodSync as chmodSync2, existsSync, mkdirSync as mkdirSync2, renameSync as renameSync2, rmSync as rmSync2, statSync } from "node:fs";
406
+ import { appendFile, chmod as chmod2, mkdir as mkdir2, readdir, rename as rename2, rm as rm2, stat } from "node:fs/promises";
407
+ import { dirname as dirname2, join as join2 } from "node:path";
408
+
409
+ // ../../packages/core/esm/common/utils/retention-util.js
410
+ var RetentionUtil;
411
+ (function(RetentionUtil2) {
412
+ RetentionUtil2.DAY_MS = 24 * 60 * 60 * 1000;
413
+ function select(items, limits, now = Date.now()) {
414
+ var _a;
415
+ const sorted = [...items].sort((a, b) => a.at - b.at);
416
+ const newest = limits.keepNewest === false ? undefined : sorted[sorted.length - 1];
417
+ let total = ((_a = limits.otherBytes) !== null && _a !== undefined ? _a : 0) + sorted.reduce((sum, one) => sum + one.bytes, 0);
418
+ const removed = [];
419
+ for (const one of sorted) {
420
+ if (one.pinned || one === newest) {
421
+ continue;
422
+ }
423
+ const old = limits.maxAgeMs !== undefined && now - one.at > limits.maxAgeMs;
424
+ const over = limits.maxBytes !== undefined && total > limits.maxBytes;
425
+ if (old || over) {
426
+ removed.push(one.key);
427
+ total -= one.bytes;
428
+ }
429
+ }
430
+ return removed;
431
+ }
432
+ RetentionUtil2.select = select;
433
+ function megabytes(value, fallback, max = 1024 * 1024) {
434
+ const mb = Number(value);
435
+ return Math.round((Number.isFinite(mb) && mb > 0 ? Math.min(max, Math.max(1, mb)) : fallback) * 1024 * 1024);
436
+ }
437
+ RetentionUtil2.megabytes = megabytes;
438
+ })(RetentionUtil || (RetentionUtil = {}));
8
439
 
9
440
  // ../../packages/core/esm/node/fs/file-util.js
10
441
  import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -22,7 +453,7 @@ var FileUtil;
22
453
  return new RegExp(`\\.${process.pid}\\.\\d+\\.tmp$`).test(name);
23
454
  }
24
455
  FileUtil2.ownTemporary = ownTemporary;
25
- function write(file, data, options = {}) {
456
+ function write2(file, data, options = {}) {
26
457
  if (options.mkdir !== false) {
27
458
  mkdirSync(dirname(file), { recursive: true });
28
459
  }
@@ -38,7 +469,7 @@ var FileUtil;
38
469
  throw error;
39
470
  }
40
471
  }
41
- FileUtil2.write = write;
472
+ FileUtil2.write = write2;
42
473
  async function writeAsync(file, data, options = {}) {
43
474
  if (options.mkdir !== false) {
44
475
  await mkdir(dirname(file), { recursive: true });
@@ -57,7 +488,7 @@ var FileUtil;
57
488
  }
58
489
  FileUtil2.writeAsync = writeAsync;
59
490
  function writeJson(file, value, options = {}) {
60
- write(file, json(value, options.pretty), options);
491
+ write2(file, json(value, options.pretty), options);
61
492
  }
62
493
  FileUtil2.writeJson = writeJson;
63
494
  function writeJsonAsync(file, value, options = {}) {
@@ -69,6 +500,184 @@ var FileUtil;
69
500
  ` : JSON.stringify(value);
70
501
  }
71
502
  })(FileUtil || (FileUtil = {}));
503
+
504
+ // ../../packages/core/esm/node/fs/file-retention.js
505
+ var STALE_MS = 60 * 60 * 1000;
506
+ var FileRetention;
507
+ (function(FileRetention2) {
508
+ async function prune(dir, options = {}) {
509
+ var _a;
510
+ var _b, _c, _d;
511
+ const now = (_b = options.now) !== null && _b !== undefined ? _b : Date.now();
512
+ const all = await list(dir, (_c = options.each) !== null && _c !== undefined ? _c : "file");
513
+ const stale = all.filter((one) => isStaleTemporary(one.key, one.at, now));
514
+ const kept = all.filter((one) => !stale.includes(one));
515
+ const items = [];
516
+ let otherBytes = 0;
517
+ for (const one of kept) {
518
+ if (options.match && !options.match(one.key)) {
519
+ otherBytes += one.bytes;
520
+ } else {
521
+ items.push({ ...one, pinned: (_a = options.pinned) === null || _a === undefined ? undefined : _a.call(options, one.key) });
522
+ }
523
+ }
524
+ const limits = {
525
+ maxAgeMs: options.keepDays === undefined ? undefined : options.keepDays * RetentionUtil.DAY_MS,
526
+ maxBytes: options.maxBytes,
527
+ otherBytes,
528
+ keepNewest: options.keepNewest
529
+ };
530
+ const removed = [...stale.map((one) => one.key), ...RetentionUtil.select(items, limits, now)];
531
+ const sizes = new Map(all.map((one) => [one.key, one.bytes]));
532
+ let freedBytes = 0;
533
+ for (const path of removed) {
534
+ await rm2(join2(dir, path), { recursive: true, force: true });
535
+ freedBytes += (_d = sizes.get(path)) !== null && _d !== undefined ? _d : 0;
536
+ }
537
+ const bytes = all.reduce((sum, one) => sum + one.bytes, 0) - freedBytes;
538
+ return { removed, freedBytes, bytes };
539
+ }
540
+ FileRetention2.prune = prune;
541
+ async function usage(dir, options = {}) {
542
+ const files = (await list(dir, "file")).filter((one) => !options.match || options.match(one.key));
543
+ return { files: files.length, bytes: files.reduce((sum, one) => sum + one.bytes, 0) };
544
+ }
545
+ FileRetention2.usage = usage;
546
+ async function clear(dir, options = {}) {
547
+ const entries = (await list(dir, "entry")).filter((one) => !options.match || options.match(one.key));
548
+ for (const one of entries) {
549
+ await rm2(join2(dir, one.key), { recursive: true, force: true });
550
+ }
551
+ return { files: entries.length, bytes: entries.reduce((sum, one) => sum + one.bytes, 0) };
552
+ }
553
+ FileRetention2.clear = clear;
554
+ function rotate(file, options) {
555
+ var _a;
556
+ let size;
557
+ try {
558
+ size = statSync(file).size;
559
+ } catch (_b) {
560
+ return false;
561
+ }
562
+ if (size <= options.maxBytes) {
563
+ return false;
564
+ }
565
+ const keep = Math.max(0, (_a = options.keep) !== null && _a !== undefined ? _a : 1);
566
+ if (keep === 0) {
567
+ rmSync2(file, { force: true });
568
+ return true;
569
+ }
570
+ rmSync2(`${file}.${keep}`, { force: true });
571
+ for (let n = keep - 1;n >= 1; n--) {
572
+ if (existsSync(`${file}.${n}`)) {
573
+ renameSync2(`${file}.${n}`, `${file}.${n + 1}`);
574
+ }
575
+ }
576
+ renameSync2(file, `${file}.1`);
577
+ return true;
578
+ }
579
+ FileRetention2.rotate = rotate;
580
+ function append(file, text, options) {
581
+ mkdirSync2(dirname2(file), { recursive: true });
582
+ rotate(file, options);
583
+ appendFileSync(file, text, options.mode === undefined ? undefined : { mode: options.mode });
584
+ if (options.mode !== undefined) {
585
+ chmodSync2(file, options.mode);
586
+ }
587
+ }
588
+ FileRetention2.append = append;
589
+ async function rotateAsync(file, options) {
590
+ var _a;
591
+ var _b;
592
+ const size = (_a = await stat(file).catch(() => {
593
+ return;
594
+ })) === null || _a === undefined ? undefined : _a.size;
595
+ if (size === undefined || size <= options.maxBytes) {
596
+ return false;
597
+ }
598
+ const keep = Math.max(0, (_b = options.keep) !== null && _b !== undefined ? _b : 1);
599
+ if (keep === 0) {
600
+ await rm2(file, { force: true });
601
+ return true;
602
+ }
603
+ await rm2(`${file}.${keep}`, { force: true });
604
+ for (let n = keep - 1;n >= 1; n--) {
605
+ await rename2(`${file}.${n}`, `${file}.${n + 1}`).catch(() => {
606
+ return;
607
+ });
608
+ }
609
+ await rename2(file, `${file}.1`);
610
+ return true;
611
+ }
612
+ FileRetention2.rotateAsync = rotateAsync;
613
+ async function appendAsync(file, text, options) {
614
+ await mkdir2(dirname2(file), { recursive: true });
615
+ await rotateAsync(file, options);
616
+ await appendFile(file, text, options.mode === undefined ? undefined : { mode: options.mode });
617
+ if (options.mode !== undefined) {
618
+ await chmod2(file, options.mode);
619
+ }
620
+ }
621
+ FileRetention2.appendAsync = appendAsync;
622
+ async function list(dir, each) {
623
+ var _a;
624
+ var _b;
625
+ const found = [];
626
+ const walk = async (path, into) => {
627
+ const entries = await readdir(join2(dir, path), { withFileTypes: true }).catch(() => []);
628
+ for (const entry of entries) {
629
+ const below = path ? join2(path, entry.name) : entry.name;
630
+ if (entry.isDirectory()) {
631
+ await walk(below, into);
632
+ } else {
633
+ const info = await stat(join2(dir, below)).catch(() => {
634
+ return;
635
+ });
636
+ if (info) {
637
+ into(info.mtimeMs, info.size);
638
+ if (each === "file") {
639
+ found.push({ key: below, at: info.mtimeMs, bytes: info.size });
640
+ }
641
+ }
642
+ }
643
+ }
644
+ };
645
+ if (each === "file") {
646
+ await walk("", () => {
647
+ return;
648
+ });
649
+ return found;
650
+ }
651
+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
652
+ if (entry.isDirectory()) {
653
+ const one = { key: entry.name, at: 0, bytes: 0 };
654
+ await walk(entry.name, (at, bytes) => {
655
+ one.at = Math.max(one.at, at);
656
+ one.bytes += bytes;
657
+ });
658
+ if (!one.at) {
659
+ one.at = (_b = (_a = await stat(join2(dir, entry.name)).catch(() => {
660
+ return;
661
+ })) === null || _a === undefined ? undefined : _a.mtimeMs) !== null && _b !== undefined ? _b : 0;
662
+ }
663
+ found.push(one);
664
+ } else {
665
+ const info = await stat(join2(dir, entry.name)).catch(() => {
666
+ return;
667
+ });
668
+ if (info) {
669
+ found.push({ key: entry.name, at: info.mtimeMs, bytes: info.size });
670
+ }
671
+ }
672
+ }
673
+ return found;
674
+ }
675
+ function isStaleTemporary(path, at, now) {
676
+ var _a;
677
+ const name = (_a = path.split(/[\\/]/).pop()) !== null && _a !== undefined ? _a : "";
678
+ return name.endsWith(".tmp") && /\.\d+\.\d+\.tmp$/.test(name) && !FileUtil.ownTemporary(name) && now - at > STALE_MS;
679
+ }
680
+ })(FileRetention || (FileRetention = {}));
72
681
  // ../ta-protocol/esm/common/message-protocol.js
73
682
  var TaMessageContext;
74
683
  (function(TaMessageContext2) {
@@ -299,7 +908,7 @@ var TaTaskNote;
299
908
  (function(TaTaskNote2) {
300
909
  const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
301
910
  const ATTRIBUTE = /(\w+)="([^"]*)"/g;
302
- function write(note) {
911
+ function write2(note) {
303
912
  const attributes = [`id="${quote(note.id)}"`];
304
913
  if (note.was !== undefined) {
305
914
  attributes.push(`was="${quote(note.was)}"`);
@@ -312,7 +921,7 @@ var TaTaskNote;
312
921
  ${note.body}
313
922
  </task_${note.kind}>`;
314
923
  }
315
- TaTaskNote2.write = write;
924
+ TaTaskNote2.write = write2;
316
925
  function parse(text) {
317
926
  const match = NOTE.exec(text.trim());
318
927
  if (!match) {
@@ -1048,12 +1657,12 @@ class SecopsCases {
1048
1657
  }
1049
1658
 
1050
1659
  // web-src/secops-learning.ts
1051
- import { appendFile, mkdir as mkdir2, readFile as readFile2 } from "node:fs/promises";
1052
- import { join as join2 } from "node:path";
1660
+ import { appendFile as appendFile2, mkdir as mkdir3, readFile as readFile2 } from "node:fs/promises";
1661
+ import { join as join3 } from "node:path";
1053
1662
 
1054
1663
  // web-src/secops-sources.ts
1055
1664
  import { createHash } from "node:crypto";
1056
- import { readFile, stat } from "node:fs/promises";
1665
+ import { readFile, stat as stat2 } from "node:fs/promises";
1057
1666
  class SecopsSources {
1058
1667
  sources;
1059
1668
  files = new Map;
@@ -1094,7 +1703,7 @@ class SecopsSources {
1094
1703
  if (source.type !== "jsonl" || !source.path) {
1095
1704
  throw new Error(`${source.name} is no file of records.`);
1096
1705
  }
1097
- const mtime = (await stat(source.path)).mtimeMs;
1706
+ const mtime = (await stat2(source.path)).mtimeMs;
1098
1707
  const kept = this.files.get(source.path);
1099
1708
  if (kept?.mtime === mtime) {
1100
1709
  return kept.records;
@@ -1218,7 +1827,7 @@ class SecopsLearning {
1218
1827
  }
1219
1828
  async labels(field, chainField) {
1220
1829
  const learned = new Map;
1221
- const text = await readFile2(join2(this.context.rules().dir, "labels.jsonl"), "utf8").catch(() => "");
1830
+ const text = await readFile2(join3(this.context.rules().dir, "labels.jsonl"), "utf8").catch(() => "");
1222
1831
  for (const line of text.split(`
1223
1832
  `)) {
1224
1833
  try {
@@ -1253,8 +1862,8 @@ class SecopsLearning {
1253
1862
  return;
1254
1863
  }
1255
1864
  const lines = ids.map((id) => JSON.stringify({ id: String(id), label, case: found.id, at: this.context.now() }));
1256
- await mkdir2(this.context.rules().dir, { recursive: true });
1257
- await appendFile(join2(this.context.rules().dir, "labels.jsonl"), `${lines.join(`
1865
+ await mkdir3(this.context.rules().dir, { recursive: true });
1866
+ await appendFile2(join3(this.context.rules().dir, "labels.jsonl"), `${lines.join(`
1258
1867
  `)}
1259
1868
  `, "utf8");
1260
1869
  }
@@ -1276,8 +1885,8 @@ class SecopsLearning {
1276
1885
 
1277
1886
  // web-src/secops-ledger.ts
1278
1887
  import { createHash as createHash2 } from "node:crypto";
1279
- import { appendFile as appendFile2, mkdir as mkdir3, readFile as readFile3 } from "node:fs/promises";
1280
- import { dirname as dirname2 } from "node:path";
1888
+ import { appendFile as appendFile3, mkdir as mkdir4, readFile as readFile3 } from "node:fs/promises";
1889
+ import { dirname as dirname3 } from "node:path";
1281
1890
 
1282
1891
  class SecopsLedger {
1283
1892
  file;
@@ -1301,8 +1910,8 @@ class SecopsLedger {
1301
1910
  prev: last.hash
1302
1911
  };
1303
1912
  const line = { ...body, hash: SecopsLedger.hash(body) };
1304
- await mkdir3(dirname2(this.file), { recursive: true });
1305
- await appendFile2(this.file, `${JSON.stringify(line)}
1913
+ await mkdir4(dirname3(this.file), { recursive: true });
1914
+ await appendFile3(this.file, `${JSON.stringify(line)}
1306
1915
  `, "utf8");
1307
1916
  this.last = { seq: line.seq, hash: line.hash };
1308
1917
  return line;
@@ -1807,50 +2416,52 @@ ${TaMessageSource.line(NAME)}`;
1807
2416
 
1808
2417
  // web-src/secops-rules.ts
1809
2418
  import { execFile } from "node:child_process";
1810
- import { existsSync } from "node:fs";
1811
- import { readdir, readFile as readFile4, rm as rm2 } from "node:fs/promises";
1812
- import { join as join3 } from "node:path";
2419
+ import { existsSync as existsSync2 } from "node:fs";
2420
+ import { readdir as readdir2, readFile as readFile4, rm as rm3 } from "node:fs/promises";
2421
+ import { join as join4 } from "node:path";
2422
+ var logger = Loggers.get("ta-secops");
2423
+
1813
2424
  class SecopsRules {
1814
2425
  dir;
1815
2426
  constructor(dir) {
1816
2427
  this.dir = dir;
1817
2428
  }
1818
2429
  get ledgerFile() {
1819
- return join3(this.dir, "ledger.jsonl");
2430
+ return join4(this.dir, "ledger.jsonl");
1820
2431
  }
1821
2432
  async load() {
1822
- const rulesDir = join3(this.dir, "rules");
1823
- const names = (await readdir(rulesDir).catch(() => [])).filter((name) => name.endsWith(".json")).sort();
2433
+ const rulesDir = join4(this.dir, "rules");
2434
+ const names = (await readdir2(rulesDir).catch(() => [])).filter((name) => name.endsWith(".json")).sort();
1824
2435
  const rules = [];
1825
2436
  for (const name of names) {
1826
- const rule = await this.json(join3(rulesDir, name));
2437
+ const rule = await this.json(join4(rulesDir, name));
1827
2438
  if (rule && !SecopsReplay.check(rule)) {
1828
2439
  rules.push(rule);
1829
2440
  }
1830
2441
  }
1831
- const scoring = { ...DEFAULT_SCORING, ...await this.json(join3(this.dir, "scoring.json")) ?? {} };
1832
- const version = (await this.json(join3(this.dir, "version.json")))?.version ?? 0;
2442
+ const scoring = { ...DEFAULT_SCORING, ...await this.json(join4(this.dir, "scoring.json")) ?? {} };
2443
+ const version = (await this.json(join4(this.dir, "version.json")))?.version ?? 0;
1833
2444
  return { rules, scoring, version };
1834
2445
  }
1835
2446
  async propose(id, body) {
1836
- const file = join3(this.dir, "proposed", `${id}.json`);
2447
+ const file = join4(this.dir, "proposed", `${id}.json`);
1837
2448
  await this.write(file, body);
1838
2449
  return file;
1839
2450
  }
1840
2451
  async release(change, note) {
1841
2452
  const current = await this.load();
1842
2453
  if (change.rule) {
1843
- await this.write(join3(this.dir, "rules", `${change.rule.id}.json`), change.rule);
2454
+ await this.write(join4(this.dir, "rules", `${change.rule.id}.json`), change.rule);
1844
2455
  }
1845
2456
  if (change.remove) {
1846
- await rm2(join3(this.dir, "rules", `${change.remove}.json`), { force: true });
2457
+ await rm3(join4(this.dir, "rules", `${change.remove}.json`), { force: true });
1847
2458
  }
1848
2459
  if (change.scoring) {
1849
- await this.write(join3(this.dir, "scoring.json"), { ...current.scoring, ...change.scoring });
2460
+ await this.write(join4(this.dir, "scoring.json"), { ...current.scoring, ...change.scoring });
1850
2461
  }
1851
2462
  const version = current.version + 1;
1852
- await this.write(join3(this.dir, "version.json"), { version, at: new Date().toISOString(), proposal: note.proposal, ledger: note.ledger, by: note.by });
1853
- await rm2(join3(this.dir, "proposed", `${note.proposal}.json`), { force: true });
2463
+ await this.write(join4(this.dir, "version.json"), { version, at: new Date().toISOString(), proposal: note.proposal, ledger: note.ledger, by: note.by });
2464
+ await rm3(join4(this.dir, "proposed", `${note.proposal}.json`), { force: true });
1854
2465
  await this.commit(`secops: release v${version}: ${change.why.slice(0, 72)}`, [
1855
2466
  `Proposal: ${note.proposal}`,
1856
2467
  `Approved-by: ${note.by}`,
@@ -1859,12 +2470,12 @@ class SecopsRules {
1859
2470
  return version;
1860
2471
  }
1861
2472
  async playbook() {
1862
- const text = await readFile4(join3(this.dir, "playbook.md"), "utf8").catch(() => "");
2473
+ const text = await readFile4(join4(this.dir, "playbook.md"), "utf8").catch(() => "");
1863
2474
  return text.split(`
1864
2475
  `).filter((line) => line.startsWith("- ")).map((line) => line.slice(2).replace(/\s*<!--.*?-->\s*$/, "").trim()).filter(Boolean);
1865
2476
  }
1866
2477
  async addLesson(id, text, note) {
1867
- const file = join3(this.dir, "playbook.md");
2478
+ const file = join4(this.dir, "playbook.md");
1868
2479
  const before = await readFile4(file, "utf8").catch(() => `# Playbook
1869
2480
 
1870
2481
  What investigations follow, as people approved it after reviews.
@@ -1875,14 +2486,14 @@ What investigations follow, as people approved it after reviews.
1875
2486
  await this.commit(`secops: lesson ${id}`, [`Approved-by: ${note.by}`, `Ledger: ${note.ledger}`]);
1876
2487
  }
1877
2488
  async reject(proposal) {
1878
- await rm2(join3(this.dir, "proposed", `${proposal}.json`), { force: true });
2489
+ await rm3(join4(this.dir, "proposed", `${proposal}.json`), { force: true });
1879
2490
  }
1880
2491
  async commit(subject, trailers) {
1881
- if (!existsSync(join3(this.dir, ".git"))) {
2492
+ if (!existsSync2(join4(this.dir, ".git"))) {
1882
2493
  return;
1883
2494
  }
1884
2495
  const git = (...args) => new Promise((resolve, reject) => execFile("git", args, { cwd: this.dir }, (error, stdout) => error ? reject(error) : resolve(String(stdout))));
1885
- const paths = ["rules", "scoring.json", "version.json", "ledger.jsonl", "labels.jsonl", "playbook.md"].filter((path) => existsSync(join3(this.dir, path)));
2496
+ const paths = ["rules", "scoring.json", "version.json", "ledger.jsonl", "labels.jsonl", "playbook.md"].filter((path) => existsSync2(join4(this.dir, path)));
1886
2497
  const known = (await git("config", "user.email").catch(() => "")).trim();
1887
2498
  const author = known ? [] : ["-c", "user.name=Ta", "-c", "user.email=ta-secops@localhost"];
1888
2499
  try {
@@ -1890,7 +2501,7 @@ What investigations follow, as people approved it after reviews.
1890
2501
  await git(...author, "commit", "-q", "-m", subject, "-m", trailers.join(`
1891
2502
  `));
1892
2503
  } catch (error) {
1893
- console.error(`ta-secops: ${String(error)}`);
2504
+ logger.error(String(error));
1894
2505
  }
1895
2506
  }
1896
2507
  async json(file) {
@@ -1907,6 +2518,7 @@ What investigations follow, as people approved it after reviews.
1907
2518
  }
1908
2519
 
1909
2520
  // web-src/secops-desk.ts
2521
+ var logger2 = Loggers.get("ta-secops");
1910
2522
  var OUTBOX_MAX = 5 * 1024 * 1024;
1911
2523
  var HOUR = 3600000;
1912
2524
  var STATUSES = ["queued", "investigating", "decided", "overflow", "failed"];
@@ -1931,10 +2543,10 @@ class SecopsDesk {
1931
2543
  this.options = options;
1932
2544
  }
1933
2545
  get dir() {
1934
- return join4(this.host.agentDir, "secops");
2546
+ return join5(this.host.agentDir, "secops");
1935
2547
  }
1936
2548
  get rules() {
1937
- return new SecopsRules(this.settings.rulesDir ?? join4(this.dir, "rules"));
2549
+ return new SecopsRules(this.settings.rulesDir ?? join5(this.dir, "rules"));
1938
2550
  }
1939
2551
  get ledger() {
1940
2552
  return new SecopsLedger(this.rules.ledgerFile);
@@ -1962,10 +2574,10 @@ class SecopsDesk {
1962
2574
  this.secret = SecopsInput.secret();
1963
2575
  await this.host.setExtensionData(NAME, Keys.HOOK, this.secret);
1964
2576
  }
1965
- await mkdir4(this.dir, { recursive: true });
1966
- this.stopEvents = this.host.onSessionEvent((event) => void this.serial(() => this.heard(event)).catch((error) => console.error(`${NAME}: ${String(error)}`)));
2577
+ await mkdir5(this.dir, { recursive: true });
2578
+ this.stopEvents = this.host.onSessionEvent((event) => void this.serial(() => this.heard(event)).catch((error) => logger2.error(String(error))));
1967
2579
  await this.serial(() => this.pump());
1968
- this.timer = setInterval(() => void this.due().catch((error) => console.error(`${NAME}: ${String(error)}`)), HOUR);
2580
+ this.timer = setInterval(() => void this.due().catch((error) => logger2.error(String(error))), HOUR);
1969
2581
  this.timer.unref?.();
1970
2582
  }
1971
2583
  dispose() {
@@ -2335,20 +2947,11 @@ ${TaMessageSource.line(NAME)}`;
2335
2947
  }
2336
2948
  async out(record) {
2337
2949
  const line = { at: new Date(this.options.now()).toISOString(), ...record };
2338
- const file = join4(this.dir, "outbox.jsonl");
2339
- await mkdir4(this.dir, { recursive: true });
2340
- if (((await stat2(file).catch(() => {
2341
- return;
2342
- }))?.size ?? 0) > OUTBOX_MAX) {
2343
- const kept = (await readFile5(file, "utf8")).split(`
2344
- `);
2345
- await FileUtil.writeAsync(file, kept.slice(Math.floor(kept.length / 2)).join(`
2346
- `), { mkdir: false });
2347
- }
2348
- await appendFile3(file, `${JSON.stringify(line)}
2349
- `, "utf8");
2950
+ const file = join5(this.dir, "outbox.jsonl");
2951
+ await FileRetention.appendAsync(file, `${JSON.stringify(line)}
2952
+ `, { maxBytes: OUTBOX_MAX, keep: 1 });
2350
2953
  if (this.settings.outUrl && this.options.post) {
2351
- await this.options.post(this.settings.outUrl, line).catch((error) => console.error(`${NAME}: ${String(error)}`));
2954
+ await this.options.post(this.settings.outUrl, line).catch((error) => logger2.error(String(error)));
2352
2955
  }
2353
2956
  }
2354
2957
  async due() {
@@ -2365,8 +2968,8 @@ ${TaMessageSource.line(NAME)}`;
2365
2968
  return kept?.day === day ? { day, count: kept.count ?? 0 } : { day, count: 0 };
2366
2969
  }
2367
2970
  async cwd() {
2368
- const cwd = this.settings.cwd ?? join4(this.dir, "work");
2369
- await mkdir4(cwd, { recursive: true }).catch(() => {
2971
+ const cwd = this.settings.cwd ?? join5(this.dir, "work");
2972
+ await mkdir5(cwd, { recursive: true }).catch(() => {
2370
2973
  return;
2371
2974
  });
2372
2975
  return cwd;
@@ -2399,7 +3002,7 @@ async function activate(host) {
2399
3002
  const desk = new SecopsDesk(host, {
2400
3003
  now: () => Date.now(),
2401
3004
  serverUrl: async () => {
2402
- const info = await readFile6(join5(host.agentDir, "serve.json"), "utf8").catch(() => {
3005
+ const info = await readFile5(join6(host.agentDir, "serve.json"), "utf8").catch(() => {
2403
3006
  return;
2404
3007
  });
2405
3008
  const url = info && JSON.parse(info).url;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-secops",
3
- "version": "4.35.0",
3
+ "version": "4.36.0",
4
4
  "description": "A pi package for Ta: security operations on the events of a stream of detections, each investigated with evidence it cites, actions and changes of the rules approved by a person, every step in a hash-chained ledger",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -28,9 +28,9 @@
28
28
  "watch": "tsc -b -w --preserveWatchOutput"
29
29
  },
30
30
  "devDependencies": {
31
- "@celljs/core": "4.35.0",
32
- "@celljs/ta-protocol": "4.35.0",
33
- "@celljs/ta-web": "4.35.0",
31
+ "@celljs/core": "4.36.0",
32
+ "@celljs/ta-protocol": "4.36.0",
33
+ "@celljs/ta-web": "4.36.0",
34
34
  "@types/react": "^19.3.0"
35
35
  },
36
36
  "publishConfig": {