@uuaid/pillar 2.6.1 → 2.7.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/README.md +201 -5
- package/bin/carrier.mjs +21 -0
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +280 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +504 -255
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +308 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +308 -92
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +725 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +195 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +549 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +296 -0
- package/src/vnext/jsonl-mailbox.mjs +1066 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +86 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +251 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
package/src/notify.mjs
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* notify.mjs — "you have new mail" notices for a Pillar home (2.7.0).
|
|
3
|
+
* Pure helpers; file custody lives in notify-store.mjs, the hook runner in
|
|
4
|
+
* notify-runner.mjs, and the CLI in bin/pillar.mjs.
|
|
5
|
+
*
|
|
6
|
+
* Main path: a resident `pillar recv --notify` (print a unit with
|
|
7
|
+
* `pillar notify --print-unit launchd|systemd`). The hook comes from
|
|
8
|
+
* config.json `notify.hook` only; nothing here takes command text.
|
|
9
|
+
* Fallback: one-shot `pillar notify` for hosts that cannot keep a process.
|
|
10
|
+
* It never pulls or stores mail.
|
|
11
|
+
*
|
|
12
|
+
* Every surface is metadata only (RedTeam notify C+N1, Q3): records, stdout,
|
|
13
|
+
* logs and overflow carry id, from, kind, at and a verified inReplyTo, never
|
|
14
|
+
* payload text. There is no includeText option.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const NOTIFY_KINDS = Object.freeze(["message", "reply", "request"]);
|
|
18
|
+
const RECORD_KINDS = Object.freeze([...NOTIFY_KINDS, "ack"]);
|
|
19
|
+
|
|
20
|
+
// Protocol checks for the record fields. ASCII patterns, so length = bytes.
|
|
21
|
+
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
22
|
+
const UUAID_RE = /^uuaid:[a-z0-9-]{1,32}:[a-z0-9-]{1,32}:[a-z0-9][a-z0-9-]{0,127}$/i; // link-offer.mjs shape, bounded
|
|
23
|
+
const AT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; // local receipt time, toISOString()
|
|
24
|
+
|
|
25
|
+
export const isSafeId = (v) => typeof v === "string" && ID_RE.test(v);
|
|
26
|
+
export const isSafeUuaid = (v) => typeof v === "string" && UUAID_RE.test(v);
|
|
27
|
+
|
|
28
|
+
/** Wake budget defaults (RedTeam Q1 starting points; each is config). */
|
|
29
|
+
export const DEFAULT_BUDGET = Object.freeze({
|
|
30
|
+
minIntervalS: 30, // between hook starts
|
|
31
|
+
unknownPerHour: 6, // wakes triggered by senders outside the address book
|
|
32
|
+
perPrincipalS: 600, // one wake per sender per 10 min
|
|
33
|
+
totalPerHour: 60, // every wake
|
|
34
|
+
priorityReserve: 12, // of totalPerHour, only notify.priority senders may use
|
|
35
|
+
});
|
|
36
|
+
const BUDGET_BOUNDS = { minIntervalS: [0, 86400], unknownPerHour: [0, 3600], perPrincipalS: [0, 86400], totalPerHour: [0, 3600], priorityReserve: [0, 3600] };
|
|
37
|
+
/** notify.maxWakesPerDay: wakes in any rolling 24 h, every class; null = off (the owner has not set one). */
|
|
38
|
+
export const MAX_WAKES_PER_DAY_BOUNDS = [0, 10000];
|
|
39
|
+
export const HOOK_TIMEOUT_S = 10;
|
|
40
|
+
export const HOOK_MAX_RECORDS = 32;
|
|
41
|
+
export const HOOK_MAX_BYTES = 16 * 1024;
|
|
42
|
+
|
|
43
|
+
/** The `notify` block a fresh `pillar init` writes into config.json. No hook. */
|
|
44
|
+
export function defaultNotifyConfig({ enabled = true } = {}) {
|
|
45
|
+
return {
|
|
46
|
+
enabled,
|
|
47
|
+
kinds: [...NOTIFY_KINDS],
|
|
48
|
+
watchedUuaids: [], // [] = any verified sender whose message passed delivery
|
|
49
|
+
priority: [], // contact and sensor senders with reserved wake capacity
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function intIn(v, [lo, hi], dflt) {
|
|
54
|
+
return Number.isInteger(v) && v >= lo && v <= hi ? v : dflt;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The effective notify config from a home's config.json object. `present` is
|
|
59
|
+
* false for a home without a `notify` block (made before 2.7.0, or kept by
|
|
60
|
+
* `init --refresh`): its readers write no eligibility events.
|
|
61
|
+
*/
|
|
62
|
+
export function notifyConfigFrom(cfgFile = {}) {
|
|
63
|
+
const raw = cfgFile && typeof cfgFile.notify === "object" && cfgFile.notify !== null && !Array.isArray(cfgFile.notify) ? cfgFile.notify : null;
|
|
64
|
+
const n = raw ?? {};
|
|
65
|
+
const b = n.budget && typeof n.budget === "object" ? n.budget : {};
|
|
66
|
+
const budget = {};
|
|
67
|
+
// A limit that is set but not a whole number in range is reported, not
|
|
68
|
+
// silently replaced: the wake paths refuse to start with it (invalid).
|
|
69
|
+
const invalid = [];
|
|
70
|
+
const bad = (v, [lo, hi]) => v !== undefined && v !== null && !(Number.isInteger(v) && v >= lo && v <= hi);
|
|
71
|
+
for (const k of Object.keys(DEFAULT_BUDGET)) {
|
|
72
|
+
if (bad(b[k], BUDGET_BOUNDS[k])) invalid.push(`notify.budget.${k} must be a whole number ${BUDGET_BOUNDS[k][0]}-${BUDGET_BOUNDS[k][1]}`);
|
|
73
|
+
budget[k] = intIn(b[k], BUDGET_BOUNDS[k], DEFAULT_BUDGET[k]);
|
|
74
|
+
}
|
|
75
|
+
if (bad(n.maxWakesPerDay, MAX_WAKES_PER_DAY_BOUNDS)) invalid.push(`notify.maxWakesPerDay must be null (off) or a whole number ${MAX_WAKES_PER_DAY_BOUNDS[0]}-${MAX_WAKES_PER_DAY_BOUNDS[1]}`);
|
|
76
|
+
if (bad(n.timeoutS, [1, HOOK_TIMEOUT_S])) invalid.push(`notify.timeoutS must be a whole number 1-${HOOK_TIMEOUT_S}`);
|
|
77
|
+
if (n.budget !== undefined && (typeof n.budget !== "object" || n.budget === null || Array.isArray(n.budget))) invalid.push("notify.budget must be an object");
|
|
78
|
+
const uuaids = (v) => (Array.isArray(v) ? v.filter(isSafeUuaid) : []);
|
|
79
|
+
return {
|
|
80
|
+
present: raw !== null,
|
|
81
|
+
enabled: n.enabled !== false,
|
|
82
|
+
kinds: Array.isArray(n.kinds) ? n.kinds.filter((k) => NOTIFY_KINDS.includes(k)) : [...NOTIFY_KINDS],
|
|
83
|
+
watchedUuaids: uuaids(n.watchedUuaids),
|
|
84
|
+
priority: uuaids(n.priority),
|
|
85
|
+
acks: n.acks === "outbox" ? "outbox" : "off", // @rule notify.acks-default-off
|
|
86
|
+
budget,
|
|
87
|
+
maxWakesPerDay: intIn(n.maxWakesPerDay, MAX_WAKES_PER_DAY_BOUNDS, null),
|
|
88
|
+
timeoutS: intIn(n.timeoutS, [1, HOOK_TIMEOUT_S], HOOK_TIMEOUT_S),
|
|
89
|
+
hook: n.hook ?? null, // checked by notify-runner.mjs checkHook()
|
|
90
|
+
invalid,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const senderOf = (view) => view?.sender ?? view?.from ?? null;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Would this decrypted view count as new mail? Used for counts only (the
|
|
98
|
+
* carrier peek); notices come from eligibility events. Acks never count.
|
|
99
|
+
*/
|
|
100
|
+
export function qualifies(view, cfg = notifyConfigFrom({})) {
|
|
101
|
+
if (!cfg || cfg.enabled === false) return false;
|
|
102
|
+
const from = senderOf(view);
|
|
103
|
+
if (typeof from !== "string" || !view?.id || view.erased) return false;
|
|
104
|
+
if (view.kind === "ack") return false; // @rule notify.ack-no-record
|
|
105
|
+
if (!(cfg.kinds ?? NOTIFY_KINDS).includes(view.kind)) return false; // @rule notify.kind-filter
|
|
106
|
+
if (cfg.watchedUuaids?.length && !cfg.watchedUuaids.includes(from)) return false; // @rule notify.watched-filter
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The stdin/log record for one eligibility event, or null when any field
|
|
112
|
+
* fails its protocol check (the event then counts in `more`).
|
|
113
|
+
* Fields: id, from, kind, at (local receipt), and inReplyTo only when the
|
|
114
|
+
* event recorded a verified own-outbox match. Never fromPublicKey or text.
|
|
115
|
+
*/
|
|
116
|
+
export function safeRecord(e) {
|
|
117
|
+
if (!isSafeId(e?.id) || !isSafeUuaid(e?.from)) return null; // @rule notify.record-protocol-check
|
|
118
|
+
if (!RECORD_KINDS.includes(e.kind)) return null;
|
|
119
|
+
if (typeof e.at !== "string" || !AT_RE.test(e.at)) return null;
|
|
120
|
+
const r = { id: e.id, from: e.from, kind: e.kind, at: e.at };
|
|
121
|
+
if (e.inReplyToVerified === true && isSafeId(e.inReplyTo)) r.inReplyTo = e.inReplyTo; // @rule notify.inreplyto-verified-only
|
|
122
|
+
return r;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Closed JSON for the hook's stdin and the log: at most 32 records and 16 KiB.
|
|
127
|
+
* { v, uuaid, new, records, more }: `new` counts every event in the batch
|
|
128
|
+
* (plus `dropped`, events lost to a full queue), `more` the ones not listed
|
|
129
|
+
* (over a cap, unsafe metadata, or dropped).
|
|
130
|
+
*/
|
|
131
|
+
export function buildBatch(uuaid, events, { maxRecords = HOOK_MAX_RECORDS, maxBytes = HOOK_MAX_BYTES, dropped = 0 } = {}) {
|
|
132
|
+
const head = { v: "pillar-notify/1", uuaid: isSafeUuaid(uuaid) ? uuaid : null, new: events.length + dropped };
|
|
133
|
+
const records = [];
|
|
134
|
+
const size = (recs) => Buffer.byteLength(JSON.stringify({ ...head, records: recs, more: head.new })) + 1;
|
|
135
|
+
for (const e of events) {
|
|
136
|
+
if (records.length >= maxRecords) break; // @rule notify.stdin-record-cap
|
|
137
|
+
const r = safeRecord(e);
|
|
138
|
+
if (!r) continue;
|
|
139
|
+
if (size([...records, r]) > maxBytes) break; // @rule notify.stdin-byte-cap
|
|
140
|
+
records.push(r);
|
|
141
|
+
}
|
|
142
|
+
const input = { ...head, records, more: head.new - records.length };
|
|
143
|
+
return { input, json: `${JSON.stringify(input)}\n` };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ── wake budget (RedTeam Q1, brief S2-B) ─────────────────────────────────────
|
|
147
|
+
|
|
148
|
+
const HOUR = 3600_000;
|
|
149
|
+
const DAY = 24 * HOUR;
|
|
150
|
+
export const PRINCIPALS_CAP = 1024;
|
|
151
|
+
const STAMPS_CAP = 4096;
|
|
152
|
+
|
|
153
|
+
/** "priority" (notify.priority), "contact" (known at receipt), or "unknown". */
|
|
154
|
+
export function classOf(event, cfg) {
|
|
155
|
+
if (cfg.priority?.includes(event.from)) return "priority";
|
|
156
|
+
return event.known ? "contact" : "unknown";
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Drop stamps past their window (1 h; 24 h for the daily cap) and principals past theirs; bound all. */
|
|
160
|
+
export function pruneBudget(b, now, cfg) {
|
|
161
|
+
const dayCap = cfg.maxWakesPerDay ?? 0; // off or 0: no stamps needed; else only the newest `dayCap` matter
|
|
162
|
+
b.day = dayCap ? (Array.isArray(b.day) ? b.day : []).filter((t) => Number.isFinite(t) && now - t < DAY).slice(-dayCap) : [];
|
|
163
|
+
b.starts = (Array.isArray(b.starts) ? b.starts : []).filter((t) => Number.isFinite(t) && now - t < HOUR).slice(-STAMPS_CAP);
|
|
164
|
+
b.unknown = (Array.isArray(b.unknown) ? b.unknown : []).filter((t) => Number.isFinite(t) && now - t < HOUR).slice(-STAMPS_CAP);
|
|
165
|
+
const win = cfg.budget.perPrincipalS * 1000;
|
|
166
|
+
let keep = Object.entries(b.principals && typeof b.principals === "object" ? b.principals : {})
|
|
167
|
+
.filter(([, t]) => Number.isFinite(t) && now - t < win)
|
|
168
|
+
.sort((x, y) => x[1] - y[1]);
|
|
169
|
+
keep = keep.slice(-PRINCIPALS_CAP); // @rule notify.budget-principals-bounded
|
|
170
|
+
b.principals = Object.fromEntries(keep);
|
|
171
|
+
return b;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* May a hook start now for these pending events? Picks the trigger
|
|
176
|
+
* (priority, then contact, then unknown; oldest first) or returns the reason
|
|
177
|
+
* and the earliest time a start becomes possible. Mutates only by pruning.
|
|
178
|
+
*/
|
|
179
|
+
export function planWake(b, pending, now, cfg) {
|
|
180
|
+
pruneBudget(b, now, cfg);
|
|
181
|
+
const B = cfg.budget;
|
|
182
|
+
const last = b.starts.at(-1);
|
|
183
|
+
const intervalAt = last === undefined ? 0 : last + B.minIntervalS * 1000;
|
|
184
|
+
if (last !== undefined && now < intervalAt) return { ok: false, reason: "interval", nextAt: intervalAt }; // @rule notify.budget-min-interval
|
|
185
|
+
const dayCap = cfg.maxWakesPerDay;
|
|
186
|
+
const dayAt = dayCap ? b.day[b.day.length - dayCap] + DAY : Infinity;
|
|
187
|
+
if (dayCap !== null && dayCap !== undefined && b.day.length >= dayCap) return { ok: false, reason: "day", nextAt: dayAt }; // @rule notify.budget-day-cap
|
|
188
|
+
const rank = { priority: 0, contact: 1, unknown: 2 };
|
|
189
|
+
const cands = pending.map((e) => ({ e, cls: classOf(e, cfg) })).sort((x, y) => rank[x.cls] - rank[y.cls] || x.e.seq - y.e.seq);
|
|
190
|
+
let reason = null;
|
|
191
|
+
let nextAt = Infinity;
|
|
192
|
+
const blocked = (why, at) => { if (reason === null || at < nextAt) { reason = why; nextAt = at; } };
|
|
193
|
+
for (const { e, cls } of cands) {
|
|
194
|
+
const pt = b.principals[e.from];
|
|
195
|
+
if (pt !== undefined && now - pt < B.perPrincipalS * 1000) { blocked("principal", pt + B.perPrincipalS * 1000); continue; } // @rule notify.budget-per-principal
|
|
196
|
+
const unknownAt = B.unknownPerHour > 0 ? b.unknown[b.unknown.length - B.unknownPerHour] + HOUR : Infinity;
|
|
197
|
+
if (cls === "unknown" && b.unknown.length >= B.unknownPerHour) { blocked("unknown", unknownAt); continue; } // @rule notify.budget-unknown-hour
|
|
198
|
+
let cap = B.totalPerHour;
|
|
199
|
+
if (cls !== "priority") cap = Math.max(0, B.totalPerHour - B.priorityReserve); // @rule notify.budget-priority-reserve
|
|
200
|
+
const capAt = cap > 0 ? b.starts[b.starts.length - cap] + HOUR : Infinity;
|
|
201
|
+
if (b.starts.length >= cap) { blocked(cls === "priority" ? "total" : "reserve", capAt); continue; } // @rule notify.budget-total-hour
|
|
202
|
+
return { ok: true, trigger: e, cls };
|
|
203
|
+
}
|
|
204
|
+
return { ok: false, reason: reason ?? "none", nextAt };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Charge one start to the budget. */
|
|
208
|
+
export function recordStart(b, trigger, cls, now, cfg = null) {
|
|
209
|
+
if (cfg?.maxWakesPerDay) b.day = [...(b.day ?? []), now]; // @rule notify.budget-day-record
|
|
210
|
+
b.starts.push(now);
|
|
211
|
+
b.principals[trigger.from] = now;
|
|
212
|
+
if (cls === "unknown") b.unknown.push(now);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── wake paths per home (V1 F2, F2b) ─────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
export const NOTIFY_BRIDGE_REFUSAL = "--notify cannot run with the Zestro bridge: two wake paths";
|
|
218
|
+
export const BRIDGE_TWICE_REFUSAL = "the Zestro bridge cannot run twice on one home: two wake paths";
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* The wake path a `pillar recv` is, by the kind it takes notify/wake.lock as:
|
|
222
|
+
* "bridge" (the Zestro bridge forwards each message as an agent command),
|
|
223
|
+
* "resident" (--notify), or null: a plain recv is not a wake path and takes
|
|
224
|
+
* no lock (F2b-3). --notify together with the bridge is refused before this.
|
|
225
|
+
*/
|
|
226
|
+
export function recvWakeKind({ notify = false, bridge = false } = {}) {
|
|
227
|
+
let kind = notify ? "resident" : null;
|
|
228
|
+
if (bridge) kind = "bridge"; // @rule notify.bridge-takes-wake-lock
|
|
229
|
+
return kind;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** The notify mode of the Pillar a recv opens: a bridged recv writes no eligibility events (F2b-2). */
|
|
233
|
+
export function recvNotifyMode({ bridge = false } = {}) {
|
|
234
|
+
let mode = "auto";
|
|
235
|
+
if (bridge) mode = "off"; // @rule notify.bridge-no-events
|
|
236
|
+
return mode;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* `mine` could not take wake.lock because `held` holds it. Returns
|
|
241
|
+
* { code, message }; message null = the caller's usual "one wake path per
|
|
242
|
+
* home" refusal (resident exit 2, fallback exit 0). The bridge against any
|
|
243
|
+
* other wake path is exit 64 with the bridge message, whichever came first.
|
|
244
|
+
*/
|
|
245
|
+
export const BRIDGE_INBOX_REFUSAL = "the Zestro bridge cannot start while `pillar inbox --notify` runs its hook: two wake paths";
|
|
246
|
+
export const RESPONDER_REFUSAL = "pillar-responder --command cannot run beside another wake path on this home: two wake paths";
|
|
247
|
+
|
|
248
|
+
export function wakeRefusal(mine, held) {
|
|
249
|
+
let r = { code: mine === "fallback" ? 0 : 2, message: null };
|
|
250
|
+
const bridgeInvolved = mine === "bridge" || held === "bridge";
|
|
251
|
+
if (bridgeInvolved) r = { code: 64, message: mine === "bridge" && held === "bridge" ? BRIDGE_TWICE_REFUSAL : NOTIFY_BRIDGE_REFUSAL }; // @rule notify.bridge-refusal
|
|
252
|
+
if (mine === "bridge" && held === "inbox") r = { code: 64, message: BRIDGE_INBOX_REFUSAL };
|
|
253
|
+
// Lead T6: a responder with a command hook is a wake path too, and any
|
|
254
|
+
// pairing with it is refused (exit 64), whichever starts second.
|
|
255
|
+
if (mine === "responder" || held === "responder") r = { code: 64, message: RESPONDER_REFUSAL }; // @rule notify.responder-refusal
|
|
256
|
+
return r;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ── printed service units (nothing is installed) ─────────────────────────────
|
|
260
|
+
|
|
261
|
+
export const UNIT_KINDS = Object.freeze(["launchd", "systemd", "cron"]);
|
|
262
|
+
const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
263
|
+
// eslint-disable-next-line no-control-regex
|
|
264
|
+
const CONTROL_RE = /[\u0000-\u001f\u007f]/;
|
|
265
|
+
|
|
266
|
+
function xmlEscape(s) {
|
|
267
|
+
return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// systemd ExecStart word: quote when needed; "%" -> "%%" and "$" -> "$$".
|
|
271
|
+
function systemdWord(s) {
|
|
272
|
+
const v = String(s).replace(/%/g, "%%").replace(/\$/g, "$$$$");
|
|
273
|
+
if (/^[A-Za-z0-9_@+=:,./-]+$/.test(v)) return v;
|
|
274
|
+
return `"${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// crontab word: POSIX single quotes; "%" is a newline to cron, so escape it.
|
|
278
|
+
function cronWord(s) {
|
|
279
|
+
return `'${String(s).replace(/'/g, "'\\''")}'`.replace(/%/g, "\\%");
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Text of a service unit for the owner to review and install.
|
|
284
|
+
* "launchd" | "systemd": resident `pillar recv --home H --notify`
|
|
285
|
+
* (KeepAlive / Restart=always; no timer). It carries no command text:
|
|
286
|
+
* the hook comes from config.json notify.hook.
|
|
287
|
+
* "cron": the one-shot fallback on a timer, labelled as such.
|
|
288
|
+
*/
|
|
289
|
+
export function renderUnit(kind, { node, pillarBin, home, label = null, everyMinutes = 5 }) {
|
|
290
|
+
if (!UNIT_KINDS.includes(kind)) throw new Error(`--print-unit takes ${UNIT_KINDS.join("|")}`);
|
|
291
|
+
for (const [k, v] of Object.entries({ node, pillarBin, home })) {
|
|
292
|
+
if (typeof v !== "string" || !v || CONTROL_RE.test(v)) throw new Error(`print-unit: ${k} is not a usable path`);
|
|
293
|
+
}
|
|
294
|
+
if (kind === "cron") {
|
|
295
|
+
const m = Number(everyMinutes);
|
|
296
|
+
if (!Number.isInteger(m) || m < 1 || m > 59) throw new Error("print-unit: --every takes whole minutes 1-59");
|
|
297
|
+
return [
|
|
298
|
+
"# Pillar notify FALLBACK: one-shot `pillar notify` on a timer, for hosts that cannot keep a process.",
|
|
299
|
+
"# Fallback; do not install with the resident unit (pillar notify --print-unit launchd|systemd).",
|
|
300
|
+
`*/${m} * * * * ${[node, pillarBin, "notify", "--home", home].map(cronWord).join(" ")} >/dev/null 2>&1`,
|
|
301
|
+
"",
|
|
302
|
+
].join("\n");
|
|
303
|
+
}
|
|
304
|
+
const lbl = label ?? "org.uuaid.pillar.recv-notify";
|
|
305
|
+
if (!LABEL_RE.test(lbl)) throw new Error("print-unit: --label takes 1-128 letters, digits, '.', '_' or '-'");
|
|
306
|
+
const argv = [node, pillarBin, "recv", "--home", home, "--notify"]; // no command text: the hook is config
|
|
307
|
+
if (kind === "launchd") {
|
|
308
|
+
return [
|
|
309
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
310
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
311
|
+
"<!-- Pillar resident notifier (printed, not installed). The hook comes from notify.hook in config.json; status goes to notify/status.json in the home. Review this, save it under ~/Library/LaunchAgents/, and load it with launchctl bootstrap. -->",
|
|
312
|
+
'<plist version="1.0">',
|
|
313
|
+
"<dict>",
|
|
314
|
+
` <key>Label</key><string>${xmlEscape(lbl)}</string>`,
|
|
315
|
+
" <key>ProgramArguments</key>",
|
|
316
|
+
" <array>",
|
|
317
|
+
...argv.map((a) => ` <string>${xmlEscape(a)}</string>`),
|
|
318
|
+
" </array>",
|
|
319
|
+
" <key>RunAtLoad</key><true/>",
|
|
320
|
+
" <key>KeepAlive</key><true/>",
|
|
321
|
+
" <key>ThrottleInterval</key><integer>10</integer>", // >= 10 s between restarts (Lead L4); a refused (64) start retries at that pace
|
|
322
|
+
" <key>StandardOutPath</key><string>/dev/null</string>",
|
|
323
|
+
" <key>StandardErrorPath</key><string>/dev/null</string>",
|
|
324
|
+
"</dict>",
|
|
325
|
+
"</plist>",
|
|
326
|
+
"",
|
|
327
|
+
].join("\n");
|
|
328
|
+
}
|
|
329
|
+
return [
|
|
330
|
+
"# Pillar resident notifier (printed, not installed). The hook comes from notify.hook in config.json; status goes to notify/status.json in the home.",
|
|
331
|
+
`# Review it, save it as ~/.config/systemd/user/${lbl}.service, then: systemctl --user daemon-reload && systemctl --user enable --now ${lbl}.service`,
|
|
332
|
+
"[Unit]",
|
|
333
|
+
`Description=Pillar recv with new-message notify (${home.replace(/%/g, "%%")})`,
|
|
334
|
+
"Wants=network-online.target",
|
|
335
|
+
"After=network-online.target",
|
|
336
|
+
"",
|
|
337
|
+
"[Service]",
|
|
338
|
+
"Type=simple",
|
|
339
|
+
`ExecStart=${argv.map(systemdWord).join(" ")}`,
|
|
340
|
+
"Restart=always",
|
|
341
|
+
"RestartSec=10",
|
|
342
|
+
"RestartPreventExitStatus=64", // @rule notify.unit-no-restart-on-refusal
|
|
343
|
+
"StandardOutput=null",
|
|
344
|
+
"StandardError=null",
|
|
345
|
+
"",
|
|
346
|
+
"[Install]",
|
|
347
|
+
"WantedBy=default.target",
|
|
348
|
+
"",
|
|
349
|
+
].join("\n");
|
|
350
|
+
}
|