@passioncode-ai/fabric-agent-adapter 0.77.0 → 0.79.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/README.md +31 -11
  3. package/SECURITY.md +17 -3
  4. package/package.json +1 -1
  5. package/plugins/fabric-agent-adapter/.claude-plugin/plugin.json +2 -2
  6. package/plugins/fabric-agent-adapter/hooks/hooks.json +1 -1
  7. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/SKILL.md +15 -5
  8. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/references/dashboard-links.md +37 -5
  9. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/references/operator-channel-and-repository.md +13 -3
  10. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/references/provider-entry.md +2 -2
  11. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/references/when-to-use.md +5 -0
  12. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/scripts/fabric_provider.py +14 -7
  13. package/plugins/fabric-agent-adapter/skills/building-fabric-services/SKILL.md +27 -39
  14. package/plugins/fabric-agent-adapter/skills/building-fabric-services/assets/dashboard-kit/fabric-button.js +6 -3
  15. package/plugins/fabric-agent-adapter/skills/building-fabric-services/assets/dashboard-kit/fabric-dashboard.css +1 -1
  16. package/plugins/fabric-agent-adapter/skills/building-fabric-services/assets/dashboard-kit/fabric-dashboard.js +34 -8
  17. package/plugins/fabric-agent-adapter/skills/building-fabric-services/assets/dashboard-kit/kit.json +9 -4
  18. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/board.md +8 -5
  19. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/connectors.md +2 -2
  20. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/dashboard-kit.md +1 -1
  21. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/dashboard-links.md +37 -5
  22. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/delegation.md +4 -1
  23. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/kit-modules.md +2 -1
  24. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/lifecycle.md +74 -3
  25. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/protocol.md +8 -3
  26. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/remote-placement.md +5 -0
  27. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/surfaces-and-auth.md +43 -1
  28. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/when-to-use.md +5 -0
  29. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/check_service.py +3 -2
  30. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-base.mjs +5 -0
  31. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-board-link.mjs +2 -0
  32. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-board-session.mjs +12 -6
  33. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-board-slots.mjs +2 -2
  34. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-delegation.mjs +30 -2
  35. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-descriptor.mjs +7 -2
  36. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-lock.mjs +54 -20
  37. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-openrouter.mjs +4 -0
  38. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-peer-owner.mjs +3 -1
  39. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-secrets.mjs +4 -1
  40. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-service.mjs +6 -0
  41. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-supervisors.mjs +339 -26
  42. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-tailnet.mjs +198 -0
  43. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_base.py +6 -0
  44. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_board_link.py +3 -0
  45. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_board_session.py +13 -5
  46. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_board_slots.py +2 -2
  47. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_delegation.py +22 -4
  48. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_descriptor.py +14 -1
  49. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_lock.py +41 -1
  50. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_openrouter.py +6 -0
  51. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_service.py +6 -0
  52. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_supervisors.py +367 -27
  53. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_tailnet.py +208 -0
  54. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/kit.json +323 -25
  55. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/SKILL.md +19 -6
  56. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/references/dashboard-links.md +37 -5
  57. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/references/models-and-providers.md +6 -3
  58. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/references/operator-channel-and-repository.md +13 -3
  59. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/references/resilience-and-autonomy.md +6 -3
  60. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/references/when-to-use.md +5 -0
  61. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/references/where-agents-run.md +4 -0
  62. package/plugins/fabric-agent-adapter/skills/observing-products/SKILL.md +179 -0
  63. package/plugins/fabric-agent-adapter/skills/observing-products/references/channels.md +129 -0
  64. package/plugins/fabric-agent-adapter/skills/observing-products/references/cycle.md +129 -0
  65. package/plugins/fabric-agent-adapter/skills/observing-products/references/when-to-use.md +5 -0
  66. package/plugins/fabric-agent-adapter/skills/observing-products/scripts/observer_inventory.py +259 -0
  67. package/plugins/fabric-agent-adapter/skills/working-with-fabric/SKILL.md +30 -39
  68. package/plugins/fabric-agent-adapter/skills/working-with-fabric/references/native-host-hooks.md +2 -0
  69. package/plugins/fabric-agent-adapter/skills/working-with-fabric/references/on-demand-session.md +57 -37
  70. package/plugins/fabric-agent-adapter/skills/working-with-fabric/references/project-board.md +50 -25
  71. package/plugins/fabric-agent-adapter/skills/working-with-fabric/references/session-hooks.md +1 -1
  72. package/plugins/fabric-agent-adapter/skills/working-with-fabric/references/when-to-use.md +5 -0
  73. package/plugins/fabric-agent-adapter/skills/working-with-fabric/scripts/fabric_session_cli.py +26 -10
  74. package/plugins/fabric-agent-adapter/skills/working-with-fabric/scripts/fabric_session_env.py +11 -5
@@ -9,8 +9,10 @@ import { DRAIN_SECONDS, SUPERVISOR_ENV, ServiceError, TASK, UNIT } from './fabri
9
9
  import { atomicWrite, instanceDirs } from './fabric-paths.mjs';
10
10
  import { SUPERVISOR_ARG, markerArguments } from './fabric-lock.mjs';
11
11
  import { URI } from './fabric-backups.mjs';
12
- import { CheckedAgent, ListenerRefused, TABLE_RESTRICTED } from './fabric-peer-owner.mjs';
12
+ import { CheckedAgent, LSOF, ListenerRefused, PS, SERVER_NOT_OWN, TABLE_RESTRICTED, UNKNOWN, parseLsofListeners, parsePsUid,
13
+ runProgram, serverEnd } from './fabric-peer-owner.mjs';
13
14
  import http from 'node:http';
15
+ import net from 'node:net';
14
16
 
15
17
  export const DEFAULT_EXIT_TIMEOUT = 15;
16
18
 
@@ -263,13 +265,15 @@ function plistValue(value, depth) {
263
265
  * FABRIC_SERVICE_SUPERVISOR=launchd tells the lock to back off instead of exiting into a respawn loop (DEC-0057).
264
266
  * No secret is written: an environment name ending TOKEN/SECRET/PASSWORD/KEY (a `*_FILE` path is fine), a value or an
265
267
  * argument shaped like a credential is refused. Returns the XML text, the same bytes Python's plistlib writes.
268
+ * `userName` writes UserName, the account a LaunchDaemon (launchd's system domain, FAA-278) runs as: a macOS short name.
266
269
  */
267
- export function launchdPlist(label, programArguments, { workingDirectory, stdoutPath, environment = {}, exitTimeout = DEFAULT_EXIT_TIMEOUT } = {}) {
270
+ export function launchdPlist(label, programArguments, { workingDirectory, stdoutPath, environment = {}, exitTimeout = DEFAULT_EXIT_TIMEOUT, userName = null } = {}) {
268
271
  launchdLabel(label);
269
272
  const argv = programArguments.map(String);
270
273
  if (!argv.length) throw new ServiceError('A launchd job starts a program; ProgramArguments is empty.');
271
274
  if (!(exitTimeout > DRAIN_SECONDS)) throw new ServiceError(`ExitTimeOut must outlast the ${DRAIN_SECONDS} s drain.`);
272
275
  if (workingDirectory === undefined || stdoutPath === undefined) throw new ServiceError('A launchd job names its working directory and its log file.');
276
+ if (userName !== null && userName !== undefined && !USER_NAME.test(String(userName))) throw new ServiceError(`UserName must be a macOS short name matching ${USER_NAME.source}`);
273
277
  const env = { ...environment };
274
278
  for (const [name, value] of Object.entries(env)) {
275
279
  if (/(TOKEN|SECRET|PASSWORD|KEY)$/.test(name) && !name.endsWith('_FILE')) throw new ServiceError(`Environment variable ${name} looks like a secret; pass a *_FILE path instead.`);
@@ -295,25 +299,168 @@ export function launchdPlist(label, programArguments, { workingDirectory, stdout
295
299
  StandardErrorPath: String(stdoutPath),
296
300
  EnvironmentVariables: env,
297
301
  };
302
+ if (userName !== null && userName !== undefined) job.UserName = String(userName); // a LaunchDaemon's account (FAA-278)
298
303
  return '<?xml version="1.0" encoding="UTF-8"?>\n'
299
304
  + '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
300
305
  + `<plist version="1.0">\n${plistValue(job, 0)}</plist>\n`;
301
306
  }
302
307
 
303
- function launchdDomain(platform, uid) {
308
+ function guiDomain(platform, uid) {
304
309
  // DEC-0032: launchd is macOS's supervisor; Linux has systemd and Windows Task Scheduler.
305
310
  if (platform !== 'darwin') throw new ServiceError('launchd is the supervisor on macOS only; use systemdInstall on Linux and taskInstall on Windows.');
306
311
  return `gui/${uid ?? process.getuid()}`;
307
312
  }
308
313
 
309
- /** True when launchd has the job loaded (`launchctl print gui/<uid>/<label>` answers). */
310
- export function launchdLoaded(label, { run = defaultRun, platform = process.platform, uid } = {}) {
311
- return run(['launchctl', 'print', `${launchdDomain(platform, uid)}/${launchdLabel(label)}`])?.status === 0;
314
+ /** Where a LaunchDaemon's plist lives: a job in launchd's system domain, started at boot with no GUI login (FAA-278). */
315
+ export const SYSTEM_DAEMONS = '/Library/LaunchDaemons';
316
+ const USER_NAME = /^[a-z_][a-z0-9_.-]{0,31}$/;
317
+
318
+ /**
319
+ * The launchd domain a job lives in: `system` for a LaunchDaemon (`domain: 'system'`, or a plist in
320
+ * /Library/LaunchDaemons), else this user's `gui/<uid>` (FAA-278). A LaunchDaemon starts at boot, before any login, so it
321
+ * is the form for a headless Mac that a FileVault restart leaves with no GUI session.
322
+ */
323
+ export function launchdDomain(plistPath = null, { domain = null, platform = process.platform, uid } = {}) {
324
+ if (![null, undefined, 'gui', 'system'].includes(domain)) throw new ServiceError('domain must be gui or system');
325
+ let which = domain;
326
+ if ((which === null || which === undefined) && plistPath !== null && plistPath !== undefined) {
327
+ const paths = platform === 'darwin' ? path.posix : path; // a macOS path, whatever host reads it
328
+ which = paths.dirname(paths.resolve(String(plistPath))).toLowerCase() === SYSTEM_DAEMONS.toLowerCase() ? 'system' : 'gui'; // APFS ignores case
329
+ }
330
+ if (which === 'system') {
331
+ if (platform !== 'darwin') throw new ServiceError('launchd is the supervisor on macOS only; use systemdInstall on Linux and taskInstall on Windows.');
332
+ return 'system';
333
+ }
334
+ return guiDomain(platform, uid);
335
+ }
336
+
337
+ // A system-domain job is installed and removed by root: refuse before anything is written (FAA-278).
338
+ function needRoot(domain, label, plistPath, install, euid) {
339
+ if (domain !== 'system' || euid === 0) return;
340
+ if (install) {
341
+ throw new ServiceError(`A LaunchDaemon (launchd's system domain) is installed by root, and this process is not root: run launchdInstall as root (the release, descriptor and token stay its UserName's, lifecycle reference, The system domain), or as root write ${plistPath} and run \`launchctl bootstrap system ${plistPath}\`. Status and pid read without root.`);
342
+ }
343
+ throw new ServiceError(`A LaunchDaemon (launchd's system domain) is removed by root, and this process is not root: run launchdUninstall as root, or as root run \`launchctl bootout system/${label}\`, remove ${plistPath} and run \`launchctl enable system/${label}\` (so a later install is not kept off). Status and pid read without root.`);
344
+ }
345
+
346
+ // The top-level string values of an XML plist's dict, read as CoreFoundation does: comments, the prolog and DOCTYPE
347
+ // skipped, entities, character references and CDATA decoded in keys and values, a repeated key's last value kept, a key
348
+ // nested deeper (an EnvironmentVariables entry named UserName) never read. null when the text cannot be read so.
349
+ const XML_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
350
+ function decodeXml(text) {
351
+ return text.replace(/&(?:(amp|lt|gt|quot|apos)|#([0-9]+)|#x([0-9a-fA-F]+));/g, (_, e, d, h) => {
352
+ if (e) return XML_ENTITIES[e];
353
+ const code = d ? Number(d) : parseInt(h, 16);
354
+ // XML 1.0's Char, as expat (Python's plistlib) reads it: a reference outside it makes the file unreadable.
355
+ const xmlChar = code === 0x9 || code === 0xa || code === 0xd || (code >= 0x20 && code <= 0xd7ff)
356
+ || (code >= 0xe000 && code <= 0xfffd) || (code >= 0x10000 && code <= 0x10ffff);
357
+ if (!xmlChar) throw new RangeError('character reference outside XML 1.0');
358
+ return String.fromCodePoint(code);
359
+ });
360
+ }
361
+ function topStrings(text) {
362
+ const token = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([A-Za-z][\w.:-]*)\s*[^>]*?(\/?)>|([^<]+)/g;
363
+ const values = Object.create(null);
364
+ let depth = 0;
365
+ let key = null;
366
+ let capture = null;
367
+ let buffer = '';
368
+ try {
369
+ for (let m = token.exec(String(text ?? '')); m; m = token.exec(String(text ?? ''))) {
370
+ const [, cdata, closing, name, selfClosing, chars] = m;
371
+ if (cdata !== undefined || chars !== undefined) {
372
+ if (capture) buffer += cdata !== undefined ? cdata : decodeXml(chars);
373
+ } else if (name === 'dict' || name === 'array') {
374
+ if (selfClosing) {
375
+ if (depth === 1 && key !== null) { delete values[key]; key = null; }
376
+ } else if (closing) {
377
+ depth -= 1;
378
+ } else {
379
+ if (depth === 1 && key !== null) { delete values[key]; key = null; } // a container is this key's value
380
+ depth += 1;
381
+ }
382
+ } else if (name && depth === 1) {
383
+ if (selfClosing) {
384
+ if (key !== null) {
385
+ if (name === 'string') values[key] = '';
386
+ else delete values[key]; // <true/>, <false/>: the last value is not a string
387
+ }
388
+ key = name === 'key' ? '' : null;
389
+ } else if (!closing && (name === 'key' || name === 'string')) {
390
+ capture = name;
391
+ buffer = '';
392
+ } else if (closing && name === capture) {
393
+ if (capture === 'key') key = buffer;
394
+ else if (key !== null) { values[key] = buffer; key = null; }
395
+ capture = null;
396
+ } else if (closing) {
397
+ if (key !== null) delete values[key]; // another value (integer, date, data, real) replaces the earlier string
398
+ key = null;
399
+ }
400
+ }
401
+ }
402
+ } catch {
403
+ return null;
404
+ }
405
+ return values;
406
+ }
407
+
408
+ function topKey(text, key) {
409
+ const values = topStrings(text);
410
+ return values && Object.hasOwn(values, key) ? values[key] : null;
312
411
  }
313
412
 
314
- // The running pid of this account's launchd job `label`, or null (not running, or not readable).
315
- export function launchdPid(label, { run = defaultRun, platform = process.platform, uid } = {}) {
316
- const result = run(['launchctl', 'print', `${launchdDomain(platform, uid)}/${launchdLabel(label)}`]);
413
+ const topUserName = (text) => topKey(text, 'UserName');
414
+
415
+ // A plist file's text as XML, a binary plist converted with plutil; null when it cannot be read.
416
+ function plistXml(file, run) {
417
+ let text;
418
+ try { text = fs.readFileSync(file, 'latin1'); } catch { return null; }
419
+ if (!text.startsWith('bplist')) return Buffer.from(text, 'latin1').toString('utf8');
420
+ const converted = run(['plutil', '-convert', 'xml1', '-o', '-', String(file)]);
421
+ return converted?.status === 0 ? String(converted.stdout ?? '') : null;
422
+ }
423
+
424
+ // Other plists that hold launchd label `label` in the system domain (FAA-278): the plist launchd loaded the job from,
425
+ // when it is not `plistPath`, and any plist of that label beside `plistPath`. Reading needs no root.
426
+ function labelHolders(label, plistPath, run) {
427
+ const real = (p) => { try { return fs.realpathSync.native(p); } catch { return path.resolve(p); } }; // the case on disk
428
+ const own = real(String(plistPath));
429
+ const found = [];
430
+ const loaded = run(['launchctl', 'print', `system/${label}`]);
431
+ if (loaded?.status === 0) {
432
+ const hit = /^\s*path\s*=\s*(.+?)\s*$/m.exec(String(loaded.stdout ?? ''));
433
+ if (hit) found.push(hit[1]);
434
+ }
435
+ const folder = path.dirname(String(plistPath));
436
+ let names = [];
437
+ try { names = fs.readdirSync(folder).filter((name) => name.endsWith('.plist')).sort(); } catch { names = []; }
438
+ for (const name of names) {
439
+ const file = path.join(folder, name);
440
+ if (topKey(plistXml(file, run), 'Label') === label) found.push(file);
441
+ }
442
+ return [...new Set(found)].filter((file) => real(file) !== own);
443
+ }
444
+
445
+ function refuseHeldLabel(label, plistPath, run) {
446
+ const holders = labelHolders(label, plistPath, run);
447
+ if (holders.length) {
448
+ const owner = topUserName(plistXml(holders[0], run));
449
+ throw new ServiceError(`Label ${label} is already held by ${holders[0]}${owner ? ` (${owner}'s)` : ''}: the system domain is shared by every account of this Mac, so a label is the machine's and one plist holds it. Choose a label of your own (for example with the account in it), or remove that LaunchDaemon as root first.`);
450
+ }
451
+ }
452
+
453
+ const ownEuid = () => (typeof process.geteuid === 'function' ? process.geteuid() : null);
454
+
455
+ /** True when launchd has the job loaded (`launchctl print gui/<uid>/<label>`, or `system/<label>` with domain 'system'). */
456
+ export function launchdLoaded(label, { run = defaultRun, platform = process.platform, uid, domain = null } = {}) {
457
+ return run(['launchctl', 'print', `${launchdDomain(null, { domain, platform, uid })}/${launchdLabel(label)}`])?.status === 0;
458
+ }
459
+
460
+ // The running pid of this account's launchd job `label` (with domain 'system', of the LaunchDaemon), or null (not
461
+ // running, or not readable). Reading needs no root.
462
+ export function launchdPid(label, { run = defaultRun, platform = process.platform, uid, domain = null } = {}) {
463
+ const result = run(['launchctl', 'print', `${launchdDomain(null, { domain, platform, uid })}/${launchdLabel(label)}`]);
317
464
  if (result?.status !== 0) return null;
318
465
  const hit = /^\s*pid\s*=\s*([0-9]+)\s*$/m.exec(String(result.stdout ?? ''));
319
466
  return hit ? Number(hit[1]) : null;
@@ -325,8 +472,8 @@ const OVERRIDE_ROW = /^\s*"([^"]+)"\s*=>\s*(\S+)\s*$/;
325
472
  * The operator's launchd override for `label`: 'disabled', 'enabled', null when none is recorded (a first install), or
326
473
  * 'unknown' when the table cannot be read. macOS 14+ prints `=> disabled|enabled`, older releases `=> true|false`.
327
474
  */
328
- export function launchdOverride(label, { run = defaultRun, platform = process.platform, uid } = {}) {
329
- const result = run(['launchctl', 'print-disabled', launchdDomain(platform, uid)]);
475
+ export function launchdOverride(label, { run = defaultRun, platform = process.platform, uid, domain = null } = {}) {
476
+ const result = run(['launchctl', 'print-disabled', launchdDomain(null, { domain, platform, uid })]);
330
477
  if (result?.status !== 0) return 'unknown';
331
478
  for (const line of String(result.stdout ?? '').split('\n')) {
332
479
  const match = OVERRIDE_ROW.exec(line);
@@ -343,8 +490,20 @@ export class ForeignUserAnswer {
343
490
  // The well-known answer at a loopback origin, read only on a connection whose server end is this OS account's process
344
491
  // (DEC-0154 HA-2): null when nothing answers or the answer is not JSON, a ForeignUserAnswer when the listener is another
345
492
  // account's or its owner cannot be told.
346
- export async function wellKnownOf(origin, { vouchPid = null } = {}) {
347
- const m = /^http:\/\/127\.0\.0\.1:([0-9]{1,5})$/.exec(origin);
493
+ // Every loopback spelling (127.0.0.1, another 127/8 address, localhost, [::1]) goes on a checked connection, never the
494
+ // unchecked way (FAA-257): the host, without brackets, and the port, or null.
495
+ function loopbackOrigin(origin) {
496
+ let url;
497
+ try { url = new URL(String(origin)); } catch { return null; }
498
+ const host = url.hostname.replace(/^\[|\]$/g, '');
499
+ const loop = host === 'localhost' || host === '::1' || (net.isIPv4(host) && host.startsWith('127.'));
500
+ if (url.protocol !== 'http:' || !loop) return null;
501
+ // new URL drops a default port: http://127.0.0.1:80 has port '', read as 80 as Python's urlsplit reads it (0.79.0 seam)
502
+ return { host, port: Number(url.port || 80) };
503
+ }
504
+
505
+ export async function wellKnownOf(origin, { vouchPid = null, ask = undefined } = {}) {
506
+ const m = loopbackOrigin(origin);
348
507
  if (!m) {
349
508
  try {
350
509
  const response = await fetch(`${origin}/.well-known/fabric-service`, { signal: AbortSignal.timeout(2000) });
@@ -355,9 +514,14 @@ export async function wellKnownOf(origin, { vouchPid = null } = {}) {
355
514
  }
356
515
  // A CheckedAgent without keep-alive: the request goes on the very socket it checked, and the socket closes after the
357
516
  // answer, so a poll leaves no connection open behind it.
358
- const agent = new CheckedAgent({ keepAlive: false, vouchPid });
517
+ return loopbackWellKnown(m.port, new CheckedAgent({ keepAlive: false, vouchPid, ...(ask ? { ask } : {}) }), m.host);
518
+ }
519
+
520
+ // The well-known answer at 127.0.0.1:<port> over `agent`, whose connections check their server end: null when nothing
521
+ // answers or the answer is not JSON, a ForeignUserAnswer when the agent refused the listener.
522
+ function loopbackWellKnown(port, agent, host = '127.0.0.1') {
359
523
  return new Promise((resolve) => {
360
- const req = http.request({ host: '127.0.0.1', port: Number(m[1]), path: '/.well-known/fabric-service', agent,
524
+ const req = http.request({ host, port, path: '/.well-known/fabric-service', agent,
361
525
  timeout: 2000 }, (res) => {
362
526
  const chunks = [];
363
527
  res.on('data', (c) => chunks.push(c));
@@ -374,6 +538,95 @@ export async function wellKnownOf(origin, { vouchPid = null } = {}) {
374
538
  }).finally(() => agent.destroy());
375
539
  }
376
540
 
541
+ // Whether launchd's job `pid` listens on exactly 127.0.0.1:<port>, never the wildcard, asked of the process itself (`lsof -p`),
542
+ // which a restricted socket table does not hide. Only for a LaunchDaemon root bootstrapped, whose pid launchd named.
543
+ async function jobListens(pid, port, run = runProgram) {
544
+ if (process.platform !== 'darwin' || !Number.isInteger(pid) || pid <= 1) return false;
545
+ try {
546
+ const out = await run(LSOF, ['-nP', '-a', '-p', String(pid), '-i4TCP', '-sTCP:LISTEN', '-Fn']);
547
+ return parseLsofListeners(out).some(([host, p]) => host === '127.0.0.1' && p === port); // exact bind, as RT-3
548
+ } catch {
549
+ return false;
550
+ }
551
+ }
552
+
553
+ // The uid account `name` has on this machine (`id -u`), or null when it has none.
554
+ function accountUid(name, run) {
555
+ if (!USER_NAME.test(String(name))) return null; // `id -u 501` answers a uid, but launchd looks UserName up by name
556
+ const result = run(['id', '-u', String(name)]);
557
+ const uid = result?.status === 0 ? String(result.stdout ?? '').trim() : '';
558
+ return /^[0-9]+$/.test(uid) ? Number(uid) : null;
559
+ }
560
+
561
+ // An http.Agent whose connections must be accepted by launchd's job `jobPid`, running as `jobUid`, its UserName's uid: a
562
+ // LaunchDaemon runs as its UserName, so the installer, root, reads it as another account's, and the job's own pid and
563
+ // uid are the proof (FAA-278; contract DEC-0161, proposed: RT-3 extended to launchd's system domain).
564
+ class JobAgent extends http.Agent {
565
+ constructor({ jobPid, jobUid, ask = {}, ...options } = {}) {
566
+ if (!Number.isInteger(jobPid) || jobPid <= 1) throw new ServiceError("A LaunchDaemon's answer is read only on its job's pid, a positive number.");
567
+ if (!Number.isInteger(jobUid) || jobUid < 0) throw new ServiceError("A LaunchDaemon's answer is read only from its UserName's uid, a number.");
568
+ super(options);
569
+ this.jobPid = jobPid;
570
+ this.jobUid = jobUid;
571
+ this.ask = ask;
572
+ }
573
+
574
+ createConnection(options, callback) {
575
+ const port = Number(options.port);
576
+ const socket = net.connect({ host: '127.0.0.1', port, noDelay: true });
577
+ const timer = setTimeout(() => socket.destroy(Object.assign(new Error('connect timeout'), { code: 'ETIMEDOUT' })), options.timeout ?? 10000);
578
+ socket.once('error', (err) => { clearTimeout(timer); callback(err); });
579
+ socket.once('connect', async () => {
580
+ clearTimeout(timer);
581
+ socket.pause();
582
+ let who;
583
+ try {
584
+ who = await serverEnd(socket, this.ask);
585
+ } catch (err) {
586
+ who = { kind: UNKNOWN, uid: null, pid: null, reason: `check: ${err?.name ?? 'Error'}` };
587
+ }
588
+ if (who.pid === this.jobPid && !await jobListens(this.jobPid, port, this.ask.run)) {
589
+ socket.destroy();
590
+ // The job's pid, but lsof did not show it bound to exactly 127.0.0.1:<port>: a wildcard is never vouched for.
591
+ callback(new ListenerRefused(SERVER_NOT_OWN, `the LaunchDaemon's pid ${this.jobPid} is not shown listening on exactly 127.0.0.1:${port} by lsof (a wildcard is never vouched for); nothing was sent`));
592
+ return;
593
+ }
594
+ const proved = who.pid === this.jobPid || (who.kind === UNKNOWN && String(who.reason ?? '').startsWith(TABLE_RESTRICTED)
595
+ && await jobListens(this.jobPid, port, this.ask.run));
596
+ if (!proved) {
597
+ socket.destroy();
598
+ callback(new ListenerRefused(SERVER_NOT_OWN, `the server on port ${port} is not the LaunchDaemon's pid ${this.jobPid} (${who.reason ?? who.kind}): another process holds the port, or the job's program starts the server as a child (start it with exec); nothing was sent`, who));
599
+ return;
600
+ }
601
+ let runsAs = null;
602
+ try { runsAs = parsePsUid(await (this.ask.run ?? runProgram)(PS, ['-o', 'uid=', '-p', String(this.jobPid)])); } catch { runsAs = null; }
603
+ if (runsAs !== this.jobUid) {
604
+ socket.destroy();
605
+ // Not the restricted owner: the pid was proved, only its uid is wrong, and the error says so.
606
+ callback(new ListenerRefused(SERVER_NOT_OWN, `the LaunchDaemon's pid ${this.jobPid} runs as uid ${runsAs}, not its UserName's uid ${this.jobUid}; nothing was sent`));
607
+ return;
608
+ }
609
+ socket.removeAllListeners('error');
610
+ socket.resume();
611
+ callback(null, socket);
612
+ });
613
+ }
614
+ }
615
+
616
+ // The port of exactly http://127.0.0.1:<port> (1 to 65535, no leading zero), else null.
617
+ function loopbackPort(origin) {
618
+ const m = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(String(origin));
619
+ return m && Number(m[1]) <= 65535 ? Number(m[1]) : null;
620
+ }
621
+
622
+ // As wellKnownOf, for a LaunchDaemon: a loopback origin is read only when launchd's job `jobPid`, running as `jobUid`,
623
+ // accepted the connection.
624
+ export async function jobWellKnownOf(origin, { jobPid, jobUid } = {}) {
625
+ const port = loopbackPort(origin);
626
+ if (port === null) throw new ServiceError(`A LaunchDaemon's answer is read only at http://127.0.0.1:<port>, where its job's pid and uid prove it; ${origin} is not.`);
627
+ return loopbackWellKnown(port, new JobAgent({ keepAlive: false, jobPid, jobUid }));
628
+ }
629
+
377
630
  /**
378
631
  * Write and lint the plist, bootout and WAIT for the unload, bootstrap (retrying launchd's EIO 5 times), then poll the
379
632
  * well-known document until it answers with this identity; resolves to that document.
@@ -382,17 +635,52 @@ export async function wellKnownOf(origin, { vouchPid = null } = {}) {
382
635
  * operator disabled stays disabled and unloaded — the plist is still rewritten, so the new release is what starts once
383
636
  * they turn it back on — and the answer is {disabled: true, label, plist, loaded}. `forceEnable` is for an operator
384
637
  * who asked for the service to be switched on.
638
+ *
639
+ * A plist in /Library/LaunchDaemons (or `domain: 'system'`) is a LaunchDaemon in launchd's system domain, started at boot
640
+ * with no login (FAA-278): only root installs it, refused before anything is written otherwise, and the answer counts
641
+ * only when launchd's own job accepted the connection. A gui/<uid> bootstrap with no GUI session says so.
385
642
  */
386
643
  export async function launchdInstall(label, plistPath, plistText, { origin, serviceId, instance = 'default', timeout = 40, forceEnable = false,
387
- run = defaultRun, platform = process.platform, uid, fetchWellKnown = wellKnownOf, sleep = pause } = {}) {
388
- const domain = launchdDomain(platform, uid);
644
+ run = defaultRun, platform = process.platform, uid, domain = null, euid = ownEuid(), fetchWellKnown = wellKnownOf,
645
+ fetchJobWellKnown = jobWellKnownOf, sleep = pause } = {}) {
646
+ const dom = launchdDomain(plistPath, { domain, platform, uid });
389
647
  launchdLabel(label);
390
648
  if (!origin || !serviceId) throw new ServiceError('launchdInstall needs the origin and the service id it waits to see answer.');
391
- const opts = { run, platform, uid };
649
+ needRoot(dom, label, plistPath, true, euid);
650
+ if (dom === 'system' && loopbackPort(origin) === null) {
651
+ throw new ServiceError(`A LaunchDaemon's origin is http://127.0.0.1:<port>: only there is its answer proved by the job's pid and uid (FAA-278); ${origin} is not.`);
652
+ }
653
+ const named = dom === 'system' ? topUserName(plistText) : null;
654
+ if (dom === 'system' && named) {
655
+ refuseHeldLabel(label, plistPath, run);
656
+ const installedText = plistXml(plistPath, run);
657
+ const installedLabel = topKey(installedText, 'Label');
658
+ if (installedLabel !== null && installedLabel !== label) {
659
+ throw new ServiceError(`${plistPath} holds launchd label ${installedLabel}, not ${label}: writing over it would leave that job loaded from a plist that no longer describes it. Uninstall it as root first, or write this one at /Library/LaunchDaemons/${label}.plist.`);
660
+ }
661
+ const installed = topUserName(installedText);
662
+ if (installed && installed !== named) {
663
+ throw new ServiceError(`${plistPath} is ${installed}'s LaunchDaemon: the system domain is shared by every account of this Mac, so a label is the machine's. Choose a label of your own (for example with the account in it), or uninstall that one as root first.`);
664
+ }
665
+ }
666
+ if (dom === 'system' && named && !USER_NAME.test(named)) {
667
+ throw new ServiceError(`UserName ${named} is not a macOS short name (${USER_NAME.source}): launchd takes the account's short name.`);
668
+ }
669
+ const jobUid = named ? accountUid(named, run) : null;
670
+ if (dom === 'system' && named && jobUid === null) {
671
+ throw new ServiceError(`UserName ${named} is no account of this Mac: launchd would not start the job. Name the account whose Fabric and agents call the service.`);
672
+ }
673
+ if (dom === 'system' && jobUid === 0) {
674
+ throw new ServiceError(`UserName ${named} is root: the job would run as root, keep its data in root's home, and every client refuses root's listener (DEC-0154 HA-2). Name the account whose Fabric and agents call the service.`);
675
+ }
676
+ if (dom === 'system' && !named) {
677
+ throw new ServiceError("A LaunchDaemon needs UserName: without it the job runs as root, keeps its data in root's home, and every client refuses root's listener (DEC-0154 HA-2). Write the plist with launchdPlist(..., { userName: <the account whose Fabric and agents call it> }).");
678
+ }
679
+ const opts = { run, platform, uid, domain: dom === 'system' ? 'system' : null };
392
680
  atomicWrite(plistPath, plistText, 0o644);
393
681
  const lint = run(['plutil', '-lint', String(plistPath)]);
394
682
  if (lint?.status !== 0) throw new ServiceError(`plist failed plutil -lint: ${String(lint?.stdout || lint?.stderr || '').trim().slice(0, 200)}`);
395
- const target = `${domain}/${label}`;
683
+ const target = `${dom}/${label}`;
396
684
  const override = launchdOverride(label, opts);
397
685
  if (forceEnable || override === null) run(['launchctl', 'enable', target]);
398
686
  else if (override === 'disabled') return { disabled: true, label, plist: String(plistPath), loaded: launchdLoaded(label, opts) };
@@ -401,13 +689,33 @@ export async function launchdInstall(label, plistPath, plistText, { origin, serv
401
689
  while (launchdLoaded(label, opts) && Date.now() < unloaded) await sleep(250);
402
690
  let last = '';
403
691
  for (let attempt = 0; ; attempt += 1) {
404
- const result = run(['launchctl', 'bootstrap', domain, String(plistPath)]);
692
+ const result = run(['launchctl', 'bootstrap', dom, String(plistPath)]);
405
693
  if (result?.status === 0) break;
406
694
  last = String(result?.stderr || result?.stdout || '').trim();
407
- if (attempt === 4) throw new ServiceError(`launchctl bootstrap failed: ${last.slice(0, 200)}`);
695
+ if (attempt === 4) {
696
+ if (dom !== 'system' && /:\s*125:|Domain does not support|Could not find domain/.test(last)) {
697
+ throw new ServiceError(`launchctl bootstrap failed: ${last.slice(0, 200)}. This user has no GUI login session (an SSH session, or a headless Mac after a FileVault restart), so ${dom} does not run jobs: remove the LaunchAgent this attempt wrote (launchdUninstall), then install it as a LaunchDaemon in the system domain (a plist in ${SYSTEM_DAEMONS} with UserName, as root; FAA-278).`);
698
+ }
699
+ throw new ServiceError(`launchctl bootstrap failed: ${last.slice(0, 200)}`);
700
+ }
408
701
  await sleep(1000);
409
702
  }
410
703
  const deadline = Date.now() + timeout * 1000;
704
+ if (dom === 'system') {
705
+ let refused = null;
706
+ while (Date.now() < deadline) {
707
+ const jobPid = launchdPid(label, opts);
708
+ const doc = jobPid ? await fetchJobWellKnown(origin, { jobPid, jobUid }) : null;
709
+ const now = doc instanceof ForeignUserAnswer ? doc.reason : null;
710
+ refused = now ?? refused; // the last refusal stays the reason, but only this round's answer decides
711
+ if (!now && doc?.service?.id === serviceId && doc?.service?.instance === instance) return doc;
712
+ await sleep(500);
713
+ }
714
+ const loaded = `; the job stays loaded and its plist starts it again at boot: as root, \`launchctl bootout system/${label}\` and removing ${plistPath} (or launchdUninstall) take it away`;
715
+ if (refused?.startsWith(TABLE_RESTRICTED)) throw new ServiceError(`${origin} could not be proved this LaunchDaemon's: ${refused}; the job's pid did not show the listener: start the server with exec (no wrapper child), or read the job's log${loaded}.`);
716
+ if (refused) throw new ServiceError(`${origin} is not this LaunchDaemon's: ${refused}${loaded}.`);
717
+ throw new ServiceError(`${origin} did not answer as ${serviceId}.${instance} within ${timeout} s; read its log${loaded}.`);
718
+ }
411
719
  let foreign = null;
412
720
  let vouchPid = null;
413
721
  while (Date.now() < deadline) {
@@ -432,15 +740,20 @@ export async function launchdInstall(label, plistPath, plistText, { origin, serv
432
740
  * override to enabled — launchctl has no verb that deletes an override, and a leftover `disabled` would keep a later
433
741
  * fresh install off. Data stays unless `purge` (then `serviceId` names whose data, logs and cache go, and `instance` which
434
742
  * instance's, so one context's purge never reaches another's, FAA-125). A job still
435
- * loaded at `timeout` seconds throws, leaving the plist and the data in place.
743
+ * loaded at `timeout` seconds throws, leaving the plist and the data in place. A LaunchDaemon (a plist in
744
+ * /Library/LaunchDaemons, or `domain: 'system'`) is removed only by root, and its data belongs to its UserName, so
745
+ * `purge` is refused for it (FAA-278).
436
746
  */
437
- export async function launchdUninstall(label, plistPath, { timeout = 30, purge = false, serviceId, instance = 'default', run = defaultRun, platform = process.platform, uid, sleep = pause } = {}) {
438
- const domain = launchdDomain(platform, uid);
747
+ export async function launchdUninstall(label, plistPath, { timeout = 30, purge = false, serviceId, instance = 'default', run = defaultRun, platform = process.platform, uid, domain = null, euid = ownEuid(), sleep = pause } = {}) {
748
+ const dom = launchdDomain(plistPath, { domain, platform, uid });
439
749
  launchdLabel(label);
440
750
  if (purge && !serviceId) throw new ServiceError('purge needs the service id whose data, logs and cache to remove.');
751
+ needRoot(dom, label, plistPath, false, euid);
752
+ if (purge && dom === 'system') throw new ServiceError("A LaunchDaemon's data belongs to its UserName, not to root: uninstall without purge, then remove the data as that user.");
753
+ if (dom === 'system') refuseHeldLabel(label, plistPath, run); // a bootout would stop another plist's job (FAA-278)
441
754
  const dirs = purge ? instanceDirs(serviceId, instance, platform) : {}; // one instance's folders only (FAA-125)
442
- const opts = { run, platform, uid };
443
- const target = `${domain}/${label}`;
755
+ const opts = { run, platform, uid, domain: dom === 'system' ? 'system' : null };
756
+ const target = `${dom}/${label}`;
444
757
  run(['launchctl', 'bootout', target]);
445
758
  const deadline = Date.now() + timeout * 1000;
446
759
  while (launchdLoaded(label, opts)) {