@tapflowio/ios-agent 0.19.0 → 0.20.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 (24) hide show
  1. package/bin/TapflowNetFilter.app/Contents/CodeResources +0 -0
  2. package/bin/TapflowNetFilter.app/Contents/Info.plist +48 -0
  3. package/bin/TapflowNetFilter.app/Contents/Library/SystemExtensions/dev.tapflow.netfilter.ext.systemextension/Contents/Info.plist +58 -0
  4. package/bin/TapflowNetFilter.app/Contents/Library/SystemExtensions/dev.tapflow.netfilter.ext.systemextension/Contents/MacOS/dev.tapflow.netfilter.ext +0 -0
  5. package/bin/TapflowNetFilter.app/Contents/Library/SystemExtensions/dev.tapflow.netfilter.ext.systemextension/Contents/_CodeSignature/CodeResources +123 -0
  6. package/bin/TapflowNetFilter.app/Contents/Library/SystemExtensions/dev.tapflow.netfilter.ext.systemextension/Contents/embedded.provisionprofile +0 -0
  7. package/bin/TapflowNetFilter.app/Contents/MacOS/TapflowNetFilter +0 -0
  8. package/bin/TapflowNetFilter.app/Contents/PkgInfo +1 -0
  9. package/bin/TapflowNetFilter.app/Contents/_CodeSignature/CodeResources +151 -0
  10. package/bin/TapflowNetFilter.app/Contents/embedded.provisionprofile +0 -0
  11. package/bin/libtapflow-nethook.dylib +0 -0
  12. package/dist/IOSAgent.d.ts +131 -3
  13. package/dist/IOSAgent.d.ts.map +1 -1
  14. package/dist/IOSAgent.js +312 -20
  15. package/dist/IOSAgent.js.map +1 -1
  16. package/dist/SimctlWrapper.d.ts +24 -0
  17. package/dist/SimctlWrapper.d.ts.map +1 -1
  18. package/dist/SimctlWrapper.js +32 -0
  19. package/dist/SimctlWrapper.js.map +1 -1
  20. package/dist/SimulatorNetwork.d.ts +369 -0
  21. package/dist/SimulatorNetwork.d.ts.map +1 -0
  22. package/dist/SimulatorNetwork.js +899 -0
  23. package/dist/SimulatorNetwork.js.map +1 -0
  24. package/package.json +9 -7
@@ -0,0 +1,899 @@
1
+ import { execFile } from 'child_process';
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { promisify } from 'util';
5
+ const execFileAsync = promisify(execFile);
6
+ const NETHOOK_DYLIB = join(import.meta.dirname, '..', 'bin', 'libtapflow-nethook.dylib');
7
+ /**
8
+ * A regular file, not merely a path that resolves.
9
+ *
10
+ * `existsSync` answers true for a directory, and dyld cannot inject one — so the check that exists to
11
+ * say "the library is not here" would have passed and let `state()` fall through to the verdict,
12
+ * reporting `awaiting-app` about an install that can never work. `statSync` follows symlinks, which is
13
+ * right: a link to a real dylib is one.
14
+ */
15
+ function isFile(p) {
16
+ try {
17
+ return statSync(p).isFile();
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ const DEFAULT_HOST_BINARY = '/Applications/TapflowNetFilter.app/Contents/MacOS/TapflowNetFilter';
24
+ /** How long the filter host gets. It activates a system extension, which is a few hundred ms when
25
+ * nothing is wrong and unbounded when a user is being asked to approve something. */
26
+ const FILTER_HOST_TIMEOUT_MS = 15_000;
27
+ /**
28
+ * How long a confirmation gets. **This is the mechanism, not a backstop.**
29
+ *
30
+ * A confirmation made while the provider is dead does not fail — it *blocks*. Measured 3/3: the call
31
+ * ran to the caller's own deadline with neither the invalidation nor the interruption handler firing,
32
+ * because launchd holds the mach name while the process is away. So this number is what decides
33
+ * `filter-unavailable` in the commonest failure there is, and the window it has to decide inside is
34
+ * not rare: a provider killed and restarted by launchd is gone for about 5.8 seconds (measured; one
35
+ * run in five took 21.3).
36
+ *
37
+ * One second: about thirty times the measured worst case of a healthy round trip (host binary launch
38
+ * 34ms, XPC 0.26–0.74ms, propagation under 55ms), and an eighth of the dashboard's 8s request
39
+ * deadline, so a refusal arrives as a refusal rather than as a request that timed out.
40
+ *
41
+ * It is also how long the operation queue is held when things go wrong, which is the cost side: a
42
+ * second device's toggle waits behind it. That is accepted rather than overlooked, and the
43
+ * alternative was tried and reviewed out — confirming outside the queue lets the write and its
44
+ * confirmation belong to different rules, which produced two ways of applying layers 2 and 3 over a
45
+ * kernel that was not enforcing. `serialize` has the sequences.
46
+ */
47
+ const FILTER_CONFIRM_TIMEOUT_MS = 1_000;
48
+ /** Where the provider writes what it is enforcing. Both are tried: the first is where it lands on a
49
+ * healthy Mac, the second is the fallback it uses when that directory cannot be written. */
50
+ const FILTER_STATE_FILES = [
51
+ '/Library/Application Support/tapflow/tapflow-netfilter-state.json',
52
+ '/tmp/tapflow-netfilter-state.json',
53
+ ];
54
+ /** How often liveness is checked while anything is offline. Matches the provider's fast pulse — it
55
+ * writes every second while its rule is non-empty — so a stopped heartbeat is noticed in about the
56
+ * time it takes for three of them to go missing. */
57
+ const LIVENESS_INTERVAL_MS = 1_000;
58
+ /**
59
+ * How long after a launch an absent verdict is still ordinary (#629).
60
+ *
61
+ * **Derived from the dylib rather than picked.** Its verdict is written from a
62
+ * `__attribute__((constructor))`, which reads as "milliseconds" and is wrong: the constructor runs
63
+ * `tf_self_check()` first, and that waits on a semaphore for up to **3 seconds** for a path update
64
+ * (`network-hook.m`). So a perfectly healthy install produces no verdict for three seconds after the
65
+ * process starts, plus whatever the launch itself took.
66
+ *
67
+ * 10s is that plus room for a loaded Mac starting a large app. Generous on purpose: past this the
68
+ * answer changes from "waiting" to "this cannot work", and being early would put that verdict on an
69
+ * install that was about to succeed. The cost of being late is that a tester sees `awaiting-app` for a
70
+ * few seconds longer — which is the true answer for those seconds.
71
+ */
72
+ export const LAUNCH_VERDICT_DEADLINE_MS = 10_000;
73
+ /** What the provider pulses at **while it is enforcing something** (`Provider.swift`, `pulseSeconds`).
74
+ * Held here as well because a file written before the rule changed declares the *idle* rate, so the
75
+ * rate to expect next cannot always be read out of the file. Change one and change the other. */
76
+ const ENFORCING_PULSE_SECONDS = 1;
77
+ /**
78
+ * The non-negative counts in an untrusted object, entry by entry.
79
+ *
80
+ * Anything else is dropped rather than failing the whole read — see `droppedByDevice`. This file is
81
+ * written by a root-owned process on the other side of a version boundary, so a value that is not a
82
+ * count is a thing to discard, not a reason to disbelieve the rest.
83
+ *
84
+ * **`Number.isInteger`, because these are flows** and `dropped 0.5 flow(s)` is a sentence no reader
85
+ * should be handed. **The array guard and the `>= 0` do not change today's output** — an array index
86
+ * cannot be a udid, and a negative would fail the `> 0` test at the only place this is consumed. They
87
+ * are here for the second consumer, and that is stated rather than left to look load-bearing.
88
+ */
89
+ function numbersIn(raw) {
90
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
91
+ return {};
92
+ const out = {};
93
+ for (const [k, v] of Object.entries(raw)) {
94
+ if (typeof v === 'number' && Number.isInteger(v) && v >= 0)
95
+ out[k] = v;
96
+ }
97
+ return out;
98
+ }
99
+ export class SimulatorNetwork {
100
+ simctl;
101
+ hostBinary;
102
+ conditionDir;
103
+ verdictDir;
104
+ dylib;
105
+ /** Every simulator currently offline. The filter takes the whole set on each call — it has no
106
+ * add/remove — so this is the authority for what the rule should say, not a cache of it. */
107
+ offline = new Set();
108
+ /** Devices whose injection is actually in place. Separates "nothing was delivered" from "delivered,
109
+ * no app has run under it yet" — two states with different remedies, and a reason each. */
110
+ armed = new Set();
111
+ /** Serialises **whole operations**, not just the host run. See `serialize`. */
112
+ filterQueue = Promise.resolve();
113
+ /** Set while a liveness check is queued, so a slow toggle does not let ticks pile up behind it. */
114
+ livenessQueued = false;
115
+ /** What layer 1 was last found doing, per device. See `FilterVerdict` for why it is remembered. */
116
+ filterVerdict = new Map();
117
+ /** When each device's offline rule was confirmed, in whole seconds. Read by `checkLiveness` to tell
118
+ * a file that disagrees from one that is simply older than the write. */
119
+ offlineSince = new Map();
120
+ /**
121
+ * The drop count last reported for each offline device (#654).
122
+ *
123
+ * **Two things need it.** The liveness check runs every second, so a device with any drops at all
124
+ * would otherwise repeat the same line 600 times in a ten-minute session — into the stream where
125
+ * the enforcement-lost report a person is actually looking for arrives. And the provider's count is
126
+ * per episode but the *file* is a snapshot: only an increase since the last read is news.
127
+ *
128
+ * Cleared wherever `offlineSince` is, so a device that goes offline again starts from nothing —
129
+ * an absent entry reads as zero, and the provider prunes its own counts per episode too, so both
130
+ * ends forget together.
131
+ */
132
+ dropsReported = new Map();
133
+ /**
134
+ * When a launch was last issued for each device (#629).
135
+ *
136
+ * A timestamp rather than a timer: `state()` is synchronous and called from several paths, and there
137
+ * is nothing to cancel — a second launch overwrites this, and a verdict arriving makes it
138
+ * irrelevant. A timer would have to be cancelled on both.
139
+ */
140
+ launchedAt = new Map();
141
+ /** The pid of the last launch that actually started a process, per device. See `markLaunched`. */
142
+ launchedPid = new Map();
143
+ /** Runs only while something is offline. See `updateLiveness`. */
144
+ liveness;
145
+ /** Set by `dispose`. Without it, work that was already in flight puts the interval back: both
146
+ * `setOffline` and `checkLiveness` call `updateLiveness()` *after* their awaits, so a dispose
147
+ * landing in between was undone by whichever of them resumed next.
148
+ *
149
+ * **No test reaches this flag, and one that appeared to was deleted rather than kept.** The
150
+ * scenario it needs — a dispose landing mid-operation, then a state file that makes the watcher
151
+ * report on its next tick — did not report even with the flag removed *and* `clearInterval` taken
152
+ * out of `dispose`, so the assertion was green against every mutation of the thing it named.
153
+ * Observing the watcher stop needs a seam this class does not have (#664). The flag stays because
154
+ * it is correct and costs one comparison; what it does not have is coverage, and saying so here is
155
+ * cheaper than a test that says otherwise. */
156
+ disposed = false;
157
+ stateFiles;
158
+ enforcementLost;
159
+ livenessIntervalMs;
160
+ constructor(simctl, opts = {}) {
161
+ this.simctl = simctl;
162
+ this.hostBinary = opts.filterHostBinary ?? DEFAULT_HOST_BINARY;
163
+ this.conditionDir = opts.conditionDir ?? '/tmp';
164
+ this.verdictDir = opts.verdictDir ?? '/tmp';
165
+ this.dylib = opts.nethookDylib ?? NETHOOK_DYLIB;
166
+ this.stateFiles = opts.filterStateFiles ?? FILTER_STATE_FILES;
167
+ this.enforcementLost = opts.onEnforcementLost ?? (() => { });
168
+ this.livenessIntervalMs = opts.livenessIntervalMs ?? LIVENESS_INTERVAL_MS;
169
+ }
170
+ /**
171
+ * Put the injection in place for a device that has just booted.
172
+ *
173
+ * **Clearing comes first, and it is not tidiness.** The condition file and the verdict both outlive
174
+ * the simulator that wrote them — they are on the host, keyed only by udid — so a device that boots
175
+ * into a leftover condition file is offline before anyone asked, and a leftover verdict answers for
176
+ * hooks that belong to a process which no longer exists.
177
+ *
178
+ * The library is armed here and the target app is not, because the target is not known yet. Until
179
+ * `target()` names one the dylib loads into every process in the simulator and hooks none of them,
180
+ * which is its designed default.
181
+ */
182
+ async arm(udid) {
183
+ return this.serialize(() => this.armLocked(udid));
184
+ }
185
+ async armLocked(udid) {
186
+ this.offline.delete(udid);
187
+ this.armed.delete(udid);
188
+ // **Layer 1's remembered judgment goes too, and leaving it out was a defect two reviewers found
189
+ // independently.** `state()` reads it before every other piece of evidence, and nothing else ever
190
+ // clears it: a `'lost'` set by `checkLiveness` survives the provider coming back, because the
191
+ // device has left `this.offline` and liveness never looks at it again. So a simulator whose
192
+ // enforcement was lost, then rebooted, answered `enforcement-lost` from `device:ready` and from
193
+ // every re-join afterwards — and the dashboard interrupts on that reason rather than re-colouring,
194
+ // so a new tester was told to re-check work belonging to a session that had already ended.
195
+ //
196
+ // This block's own doc says a leftover verdict answers for a process that no longer exists. That
197
+ // was true of the dylib's file and not of this, which is exactly how it was missed.
198
+ this.filterVerdict.delete(udid);
199
+ this.offlineSince.delete(udid);
200
+ this.dropsReported.delete(udid);
201
+ // **With the verdict it belongs to.** A boot is a new process for every app, so a launch recorded
202
+ // before it describes one that no longer exists — and leaving it behind means a freshly booted
203
+ // device reads as `hooks-not-installed` from its first `state()` call, on the strength of an app
204
+ // that ran in the previous session.
205
+ this.launchedAt.delete(udid);
206
+ this.launchedPid.delete(udid);
207
+ this.setCondition(udid, false);
208
+ rmSync(this.verdictPath(udid), { force: true });
209
+ // **The rule is rewritten, not merely forgotten.** Clearing the in-memory set and the condition
210
+ // file used to be the whole of this, which left the one layer that actually stops traffic still
211
+ // naming the device: a simulator toggled offline, shut down and booted again came up with its
212
+ // traffic dead while this class reported it online and steerable, and nothing recovered it short
213
+ // of toggling twice.
214
+ //
215
+ // **Names this udid and only this udid.** The rule is the host's and the set is this process's
216
+ // memory, so a rule left behind by the process before it still has to be cleared — but clearing
217
+ // it by writing this agent's whole set is what erased every other agent's devices. Naming the one
218
+ // that just booted does the same job for the device that is actually being armed.
219
+ await this.runFilterHost({ remove: [udid] });
220
+ // Arm can empty the offline set, and the watcher has to stop with it or tick forever on nothing.
221
+ this.updateLiveness();
222
+ // Recorded only after the call returns. A device whose environment could not be set has had
223
+ // nothing delivered, and saying otherwise would report it as merely waiting for an app — a state
224
+ // whose remedy is to launch one, which would never help.
225
+ await this.simctl.setSimulatorEnv(udid, 'DYLD_INSERT_LIBRARIES', this.dylib);
226
+ this.armed.add(udid);
227
+ }
228
+ /**
229
+ * Name the app the hooks may touch.
230
+ *
231
+ * **Must be called before the app is launched.** dyld reads the environment when a process starts,
232
+ * so naming the target afterwards arms the *next* launch and leaves the running one unhooked —
233
+ * reporting `available: true` for an app that would never see a path update.
234
+ *
235
+ * **The previous app's verdict goes with it.** A verdict is one process's report that its own hooks
236
+ * took, and that process has exited by the time a second app is launched. Leaving the file behind
237
+ * answered for the new app on the old one's evidence: `available: true` before the new process had
238
+ * written anything, and — if its hooks fail — for as long as it runs. The gap where `state()`
239
+ * answers `awaiting-app` for a launch already in flight is the correct reading of that moment;
240
+ * inheriting a stale `ok` is not.
241
+ */
242
+ async target(udid, bundleId) {
243
+ rmSync(this.verdictPath(udid), { force: true });
244
+ await this.simctl.setSimulatorEnv(udid, 'TAPFLOW_TARGET_BUNDLE', bundleId);
245
+ }
246
+ /**
247
+ * A process started, so a verdict is now owed — `markLaunched` opens the window `state()` measures.
248
+ *
249
+ * **Called after the launch, not before it, and that is a correction.** The mark was first set at
250
+ * the top of `target()`, which put `simctl spawn … launchctl setenv`, `simctl launch` and the app's
251
+ * whole dyld load *inside* the budget — none of it measured — and left the mark standing when the
252
+ * launch failed outright, so a launch that never happened reported the hooks as broken ten seconds
253
+ * later.
254
+ *
255
+ * **Only for a pid that is new.** `simctl launch` is issued without `--terminate-running-process`,
256
+ * so launching a bundle that is already running returns the existing pid and starts nothing. The
257
+ * verdict is written from a dyld constructor — once per process — so nothing will rewrite the file
258
+ * `target()` just deleted, and starting a deadline there would report a permanently dead control
259
+ * over an app whose hooks are live and watching. That case stays what it was before this change,
260
+ * which is wrong but harmless; #692 has the decision it needs.
261
+ */
262
+ markLaunched(udid, pid) {
263
+ if (pid === null || this.launchedPid.get(udid) === pid)
264
+ return;
265
+ this.launchedPid.set(udid, pid);
266
+ this.launchedAt.set(udid, Date.now());
267
+ }
268
+ /**
269
+ * **Layer 1 leads in both directions, and the order is measured rather than chosen.**
270
+ *
271
+ * Going offline, the dylib cuts the app's open sockets the moment the flag file appears. If the
272
+ * filter were not already dropping new flows at that instant, the app would simply reconnect —
273
+ * reproduced exactly that way while stepping the layers separately, and the reconnected socket then
274
+ * survived the rest of the session.
275
+ *
276
+ * Coming back, the filter has to stop dropping before the app is told the path is satisfied, or the
277
+ * first thing it does with the good news is fail.
278
+ *
279
+ * The status bar goes last either way: it reports, so it should not claim a state before the state
280
+ * is true.
281
+ */
282
+ async setOffline(udid, offline) {
283
+ return this.serialize(() => this.setOfflineLocked(udid, offline));
284
+ }
285
+ /** The body of `setOffline`, running with the queue held. Calls `runFilterHost` directly: going
286
+ * through `serialize` again from in here would wait on a slot this call already owns. */
287
+ async setOfflineLocked(udid, offline) {
288
+ const was = this.offline.has(udid);
289
+ if (offline)
290
+ this.offline.add(udid);
291
+ else
292
+ this.offline.delete(udid);
293
+ const enforced = await this.applyAndConfirm(udid, offline);
294
+ if (!enforced) {
295
+ // **Layer 1 is not enforcing, so layers 2 and 3 do not get applied.** Two of the three work
296
+ // without it and neither blocks traffic: the app would be told its path is unsatisfied and its
297
+ // sockets would be cut, while every request it makes afterwards succeeds. That is a tester
298
+ // signing off offline behaviour they never saw — the exact failure this feature exists to
299
+ // prevent, produced by the feature itself.
300
+ //
301
+ // **Both directions, including coming back online.** A draft carried the online request out
302
+ // anyway, reasoning that a device nothing is enforcing is reachable already and refusing would
303
+ // strand an app believing it is offline. That reasoning was wrong and a test caught it: not
304
+ // being able to *change* the rule is not the same as nothing enforcing it. The provider is a
305
+ // separate process holding the rule it was last given, so a container app that cannot run
306
+ // leaves a device exactly as offline as it was — and taking layers 2 and 3 down there would tell
307
+ // the app it is online while the kernel goes on dropping its traffic.
308
+ //
309
+ // Enforcement that has genuinely stopped is a different signal with a different remedy, and it
310
+ // has one: `checkLiveness` takes the layers down and reports `enforcement-lost`.
311
+ //
312
+ // The device is wherever it already was — **which is not necessarily online.** This used to
313
+ // delete unconditionally and answer `offline: false`, so a device that was already offline came
314
+ // back as online here and from every later `state()` call, with the rule and the condition file
315
+ // still saying otherwise. Reporting the request back as if it had taken is how a tester ends up
316
+ // filing bugs against an app that was never offline; reporting it as online when it is offline
317
+ // sends them to file against one that cannot reach anything.
318
+ if (was)
319
+ this.offline.add(udid);
320
+ else
321
+ this.offline.delete(udid);
322
+ // **And the restored set is written back**, because the run that failed was not necessarily the
323
+ // only writer. The host reads `this.offline` when it *runs*, not when it was queued — correct,
324
+ // since the set is the authority — so with two toggles in flight an earlier run can already have
325
+ // committed a later one's set. Restoring in memory alone then leaves this device named offline
326
+ // here and absent from the kernel rule: traffic alive, and this class saying it is not, which is
327
+ // the direction the paragraph above calls filing bugs against an app that was never offline.
328
+ //
329
+ // Best-effort by definition — the write that just failed may fail again — and that is still
330
+ // strictly better than not trying, because the alternative is a divergence nothing revisits
331
+ // until the device is rebooted.
332
+ await this.runFilterHost(was ? { add: [udid] } : { remove: [udid] });
333
+ this.filterVerdict.set(udid, 'unavailable');
334
+ this.updateLiveness();
335
+ return { offline: was, available: false, reason: 'filter-unavailable' };
336
+ }
337
+ this.filterVerdict.delete(udid);
338
+ if (offline) {
339
+ this.offlineSince.set(udid, Math.floor(Date.now() / 1000));
340
+ // **Seeded from whatever the file already says, and this is the episode boundary.**
341
+ //
342
+ // The provider prunes its own counts when a device leaves the rule, but only while rendering —
343
+ // and its `ruleWatch` only advances when a flow arrives. So a device toggled off, on, and off
344
+ // again with no flow and no pulse in between leaves the provider having never seen the empty
345
+ // rule, and it republishes the previous episode's count as if it belonged to this one.
346
+ //
347
+ // **The provider cannot fix that, because it cannot see an episode.** It knows a rule, not that
348
+ // a tester toggled a control. This class does. Taking the current count as the baseline makes a
349
+ // stale number harmless whatever the provider does: only drops *above* it are evidence for this
350
+ // episode, and if there were none the answer is silence, which is what zero has always meant
351
+ // here.
352
+ this.dropsReported.set(udid, this.readFilterState()?.droppedByDevice[udid] ?? 0);
353
+ }
354
+ else {
355
+ this.offlineSince.delete(udid);
356
+ this.dropsReported.delete(udid);
357
+ }
358
+ this.setCondition(udid, offline);
359
+ // **Layer 3 only reports, so its failure is not a reason and must not undo the two that do.**
360
+ // Unswallowed, one `status_bar` failure threw out of here with layers 1 and 2 already applied: the
361
+ // device really was offline and the caller was told the request failed, which is the direction
362
+ // that sends a tester to file against an app that was never online.
363
+ //
364
+ // Swallowed in both directions, and they fail differently. Going offline it errs *quietly* — the
365
+ // device is offline and the status bar has not caught up. Coming back it errs the other way: every
366
+ // layer is restored and the bar still shows no service, on a device whose requests now succeed.
367
+ // Neither is worth failing the call for. What puts the second one right is a later toggle writing
368
+ // the bar again — **a full cycle, not one press**, since the first press writes the value the bar
369
+ // is already stuck on. And it is not guaranteed: if layer 1 becomes unavailable in between, every
370
+ // later call returns above this line and the bar stays wrong until the device is retired. That
371
+ // gap, and the fact that swallowing also removes the `network:error` this used to raise, are
372
+ // recorded rather than solved here.
373
+ await this.simctl.setStatusBarOffline(udid, offline).catch((e) => {
374
+ console.warn(`[network] status bar for ${udid} could not be set: ${e.message}`);
375
+ });
376
+ this.updateLiveness();
377
+ return this.state(udid);
378
+ }
379
+ /**
380
+ * Write the rule and **ask the provider whether it is holding it.**
381
+ *
382
+ * The write's exit code cannot answer that. The container app exits when the framework accepts the
383
+ * save — 27ms for the whole run — and the running provider is handed the configuration afterwards
384
+ * with nothing coming back. Measured propagation is under 55ms and a probe measured the ask itself
385
+ * at 0.26–0.74ms, which is what makes asking cheaper than the six-second wait an earlier draft
386
+ * proposed in place of it.
387
+ *
388
+ * **The predicate is per-device membership, not set equality.** The filter is host-wide and this
389
+ * agent is not guaranteed to be its only writer; comparing whole sets would report every device as
390
+ * unenforced the moment somebody else's device appeared in the rule.
391
+ *
392
+ * **`wanted` is the value the caller asked for, and it is a parameter for that reason.** Reading it
393
+ * back off `this.offline` here compares the provider's answer against whatever the set says *now*,
394
+ * which is not necessarily what this call wrote — so a second toggle landing in between made a
395
+ * confirmation agree with a rule its own request had not asked for, and the success path then
396
+ * applied layers 2 and 3 for the wrong direction.
397
+ *
398
+ * A mismatch is logged **with what was actually read**. Two agents writing the same rule cannot be
399
+ * told apart afterwards from a log that only records what each one expected — each is internally
400
+ * consistent and one of them is stale.
401
+ */
402
+ async applyAndConfirm(udid, wanted) {
403
+ if (!await this.runFilterHost(wanted ? { add: [udid] } : { remove: [udid] }))
404
+ return false;
405
+ const seen = await this.confirmEnforcement();
406
+ if (!seen)
407
+ return false;
408
+ if (!seen.enforcing)
409
+ return false;
410
+ if (seen.rule.includes(udid) !== wanted) {
411
+ console.warn(`[network] filter rule disagrees for ${udid}: wanted ${wanted ? 'offline' : 'online'}, ` +
412
+ `provider ${seen.pid} holds [${seen.rule.join(',')}]`);
413
+ return false;
414
+ }
415
+ return true;
416
+ }
417
+ /** Ask the running provider what it is enforcing. `undefined` for every way of not finding out —
418
+ * the remedy is the same whether the filter is absent, disabled, or restarting. */
419
+ async confirmEnforcement() {
420
+ if (!existsSync(this.hostBinary))
421
+ return undefined;
422
+ try {
423
+ const { stdout } = await execFileAsync(this.hostBinary, ['--confirm'], {
424
+ timeout: FILTER_CONFIRM_TIMEOUT_MS,
425
+ });
426
+ const parsed = JSON.parse(stdout);
427
+ if (typeof parsed.enforcing !== 'boolean' || !Array.isArray(parsed.rule))
428
+ return undefined;
429
+ return {
430
+ enforcing: parsed.enforcing,
431
+ rule: parsed.rule.filter((r) => typeof r === 'string'),
432
+ pid: typeof parsed.pid === 'number' ? parsed.pid : -1,
433
+ };
434
+ }
435
+ catch {
436
+ // A timeout lands here as well as a refusal, and they are the same answer: not confirmed.
437
+ return undefined;
438
+ }
439
+ }
440
+ /** Layers 2 and 3, taken down together. Layer 3 is swallowed for the reason `forget` gives: it only
441
+ * reports, and failing it would abandon the cleanup that matters. */
442
+ async takeDownLayers(udid) {
443
+ this.setCondition(udid, false);
444
+ await this.simctl.setStatusBarOffline(udid, false).catch(() => { });
445
+ }
446
+ /**
447
+ * What the device is doing and whether tapflow can still steer it.
448
+ *
449
+ * `offline` describes the **device**, not the last request: a simulator taken offline and then left
450
+ * unsteerable is still offline, and saying otherwise would draw "online" over an app that can reach
451
+ * nothing.
452
+ */
453
+ state(udid) {
454
+ const offline = this.offline.has(udid);
455
+ // **Layer 1 is answered first, and from memory.** This method is synchronous — `device:ready`, a
456
+ // viewer's re-join and the capability's `networkState()` all arrive here — so it cannot ask
457
+ // anything. Deriving layer 1's health from the dylib's verdict instead would repaint a Mac that
458
+ // cannot take devices offline as a healthy one on the next re-join, and the tester's toast would
459
+ // be the only evidence it ever said otherwise.
460
+ const filter = this.filterVerdict.get(udid);
461
+ if (filter === 'lost')
462
+ return { offline, available: false, reason: 'enforcement-lost' };
463
+ if (filter === 'unavailable')
464
+ return { offline, available: false, reason: 'filter-unavailable' };
465
+ // **Layer 2 cannot work at all if the library is not on disk**, and that is the quietest failure
466
+ // in the feature: `DYLD_INSERT_LIBRARIES` naming a path that does not exist is ignored by dyld
467
+ // without a word, so the app launches unhooked and no verdict is ever written. `arm()` records
468
+ // the device as armed whatever the file's state — it sets the environment and does not read the
469
+ // path it sets — so the branch below fell to `awaiting-app`: "launch an app through tapflow", to
470
+ // a tester who has already launched one, for the life of the session. (`not-armed` and its
471
+ // reboot only appear when this process restarted, since `armed` is its memory.)
472
+ //
473
+ // Read rather than remembered, unlike layer 1 above. Layer 1 is a question this synchronous
474
+ // method cannot put to the provider; this one is a `stat`, and a `node_modules` emptied under a
475
+ // running agent is an ordinary thing to happen.
476
+ if (!isFile(this.dylib))
477
+ return { offline, available: false, reason: 'hooks-not-installed' };
478
+ const verdict = this.readVerdict(udid);
479
+ // The three answers differ by what the tester has to do, which is what the reason set is for.
480
+ // An absent verdict means two different things and they were reported as one: nothing was
481
+ // delivered (reboot), or it was delivered and no app has exercised it yet (launch one). The
482
+ // second is what every iOS session looks like before its app starts, so folding it into
483
+ // `not-armed` put the wrong remedy on the common case.
484
+ if (verdict === 'missing') {
485
+ if (!this.armed.has(udid))
486
+ return { offline, available: false, reason: 'not-armed' };
487
+ // **A launch that produced no verdict is not a device waiting for one** (#629), and this is the
488
+ // second form of the failure the `isFile` guard above exists for. That one covers a path dyld
489
+ // ignores because nothing is there; this covers a library that is there and still does not load
490
+ // — a wrong architecture, a runtime change, a signature. dyld says nothing in either case.
491
+ //
492
+ // Without it, `awaiting-app` says "launch an app through tapflow" to a tester who has already
493
+ // launched one, for the life of the session: word for word the sentence the comment above calls
494
+ // the quietest failure in the feature.
495
+ //
496
+ // The window before the deadline is genuinely `awaiting-app` — the dylib may still be inside its
497
+ // own three-second self-check — which is why this is a deadline and not a flag.
498
+ const launched = this.launchedAt.get(udid);
499
+ if (launched !== undefined && Date.now() - launched > LAUNCH_VERDICT_DEADLINE_MS) {
500
+ return { offline, available: false, reason: 'hooks-not-installed' };
501
+ }
502
+ return { offline, available: false, reason: 'awaiting-app' };
503
+ }
504
+ if (verdict === 'failed')
505
+ return { offline, available: false, reason: 'hooks-not-installed' };
506
+ // **`state-unconfirmed`, because that is what happened: a read that could not be confirmed.**
507
+ //
508
+ // Two members it is deliberately not. Not `awaiting-app`: resolving this against `armed` would
509
+ // land there almost every time — the library writes the file *because* an app is running, so
510
+ // `armed` is true — and `awaiting-app` is the one member drawn with a healthy control and "launch
511
+ // an app", which hands a normal-looking toggle to a device nobody can vouch for. And not
512
+ // `not-armed`, whose sentence is "restart the device". Rebooting a simulator mid-session destroys
513
+ // the app state under test, and none of the causes left here is fixed by it — a verdict from an
514
+ // older dylib is replaced by the app's next launch, and a shape this reader cannot parse is not a
515
+ // property of the boot. `state-unconfirmed` says "could not confirm — try again", and looking again is
516
+ // exactly the remedy.
517
+ if (verdict === 'unreadable')
518
+ return { offline, available: false, reason: 'state-unconfirmed' };
519
+ return { offline, available: true };
520
+ }
521
+ /** Called when a device goes away, so a shutdown simulator does not keep a rule alive that names
522
+ * it — the filter would carry the udid for the rest of the host's uptime. */
523
+ async forget(udid) {
524
+ return this.serialize(() => this.forgetLocked(udid));
525
+ }
526
+ async forgetLocked(udid) {
527
+ this.armed.delete(udid);
528
+ // The judgment was about a device that is going away. Keeping it would answer for whatever is
529
+ // booted into the same udid next.
530
+ this.filterVerdict.delete(udid);
531
+ this.offlineSince.delete(udid);
532
+ this.dropsReported.delete(udid);
533
+ this.launchedAt.delete(udid);
534
+ this.launchedPid.delete(udid);
535
+ // Unconditional, for the reason `arm()` gives at length: the set is this process's memory and the
536
+ // rule is the host's. An agent that restarted knows of no offline device, so `delete` answers
537
+ // false and the write was skipped — leaving the udid named in the rule for the rest of the Mac's
538
+ // uptime, which is the exact outcome this method's doc block says it exists to prevent.
539
+ this.offline.delete(udid);
540
+ await this.runFilterHost({ remove: [udid] });
541
+ this.setCondition(udid, false);
542
+ // **The status bar is part of what has to come back.** It was set by `setOffline` and had no
543
+ // other caller, so a device retired while offline kept showing no service for as long as it
544
+ // stayed booted — a relay disconnect was enough. That is the pixels-only false result this class
545
+ // exists to prevent, pointed the other way.
546
+ //
547
+ // Swallowed, and only here: a device being retired is often already gone, and `status_bar clear`
548
+ // against a shut-down simulator fails. Failing this call would abandon the rest of the cleanup
549
+ // for a layer that only reports.
550
+ await this.simctl.setStatusBarOffline(udid, false).catch(() => { });
551
+ this.updateLiveness();
552
+ }
553
+ /**
554
+ * Point the report somewhere after construction.
555
+ *
556
+ * **The constructor option alone left this untestable, which a review found by mutating the wiring
557
+ * away and watching the whole suite stay green.** `IOSAgent` builds its own `SimulatorNetwork` only
558
+ * when one was not injected, and every test injects one — so the handler was attached on exactly the
559
+ * path no test takes. The one channel that tells a tester their finished check was invalidated had
560
+ * no coverage at all, while the refusal path beside it had five tests.
561
+ */
562
+ setEnforcementLostHandler(fn) {
563
+ this.enforcementLost = fn;
564
+ }
565
+ /**
566
+ * Stop watching. **Nothing else clears the interval**, so an agent that shuts down while a device
567
+ * is offline would otherwise keep a timer alive for the life of the process — which is what
568
+ * happened, because for a while this had no caller outside the tests at all. `IOSAgent.disconnect`
569
+ * owns it, beside the resources timer and the tree reader it already stops.
570
+ */
571
+ dispose() {
572
+ this.disposed = true;
573
+ if (this.liveness)
574
+ clearInterval(this.liveness);
575
+ this.liveness = undefined;
576
+ }
577
+ /**
578
+ * Undo `dispose`, because an agent that disconnected can connect again on the same instance.
579
+ *
580
+ * **A one-way disposed flag is a bug with the shape of the one it fixes**, and this codebase has
581
+ * already shipped it once: the provider's `Heartbeat.stopped` was set by a stop and cleared by
582
+ * nothing, so the first `stopFilter` in a process killed the state file for good while the filter
583
+ * went on filtering. Here it would be quieter and worse — `connect()` is public and reuses the
584
+ * network, so a reconnect after a disconnect would leave the watcher off, and the one report that
585
+ * tells a tester their check was invalidated would simply never come.
586
+ */
587
+ resume() {
588
+ this.disposed = false;
589
+ this.updateLiveness();
590
+ }
591
+ // ── liveness: enforcement that stops after the fact ────────────────────────
592
+ /**
593
+ * Watch only while something is offline, because that is the only time there is anything to lose.
594
+ *
595
+ * The interval is `unref`'d: this must not be the reason a process stays alive.
596
+ */
597
+ updateLiveness() {
598
+ const wanted = !this.disposed && this.offline.size > 0;
599
+ if (wanted && !this.liveness) {
600
+ this.liveness = setInterval(() => { void this.checkLiveness(); }, this.livenessIntervalMs);
601
+ this.liveness.unref?.();
602
+ }
603
+ else if (!wanted && this.liveness) {
604
+ clearInterval(this.liveness);
605
+ this.liveness = undefined;
606
+ }
607
+ }
608
+ /**
609
+ * Notice that a device stopped being enforced, and say so.
610
+ *
611
+ * **Why this exists at all, given the confirmation on the write.** The confirmation answers the
612
+ * moment of the request; enforcement can stop at any point afterwards, and when it does the tester
613
+ * is looking at a control that still says offline. Measured on the reference Mac: killing the
614
+ * provider leaves the kernel passing that simulator's traffic for about 5.8 seconds before launchd
615
+ * has it back, and 23 to 27 requests got through each time. The tester's sign-off covers requests
616
+ * that succeeded.
617
+ *
618
+ * **The threshold comes out of the file.** Three pulses, at whatever rate the provider says it is
619
+ * pulsing — 1s while it is enforcing, so about three seconds. Hard-coding fifteen (three of the old
620
+ * five-second pulses) is what made the outage above arithmetically invisible: the gap closes before
621
+ * the threshold expires and nothing is ever reported.
622
+ *
623
+ * **A timestamp in the future is not freshness, it is a file that cannot be trusted.** Clocks move
624
+ * backwards — NTP corrections, a sleeping Mac — and treating `at > now` as "very fresh" would make
625
+ * a stale file look perfect for as long as the skew lasted.
626
+ */
627
+ async checkLiveness() {
628
+ // Queued like every other mutation. It edits `this.offline`, rewrites the rule and takes layers
629
+ // down, so running it beside a toggle is the race described on `serialize` — and the tick is the
630
+ // half that used to run outside the boundary.
631
+ if (this.livenessQueued)
632
+ return;
633
+ this.livenessQueued = true;
634
+ try {
635
+ await this.serialize(() => this.checkLivenessLocked());
636
+ }
637
+ finally {
638
+ this.livenessQueued = false;
639
+ }
640
+ }
641
+ /**
642
+ * **Three questions per device, and each one is a different piece of evidence.** A single "is the
643
+ * file stale" test read against the whole set could not answer them, and the gap it left is
644
+ * measured: the provider publishes its pulse rate *as of the rule it held when it wrote*, so the
645
+ * last write before a device went offline says `pulseSeconds: 5`. A provider dying in the second
646
+ * after a toggle therefore leaves a file that is not stale by its own declared rate for fifteen
647
+ * seconds, and does not name the device either — both predicates false, nothing reported, and the
648
+ * kernel passing that simulator's traffic for the whole of it.
649
+ */
650
+ async checkLivenessLocked() {
651
+ if (this.offline.size === 0)
652
+ return;
653
+ const file = this.readFilterState();
654
+ const now = Math.floor(Date.now() / 1000);
655
+ const lost = [...this.offline].filter((udid) => {
656
+ // No file at all, or a timestamp from the future — a clock that moved backwards must not read
657
+ // as very fresh, or a frozen file looks perfect for as long as the skew lasts.
658
+ if (!file || file.at > now)
659
+ return true;
660
+ const since = this.offlineSince.get(udid) ?? now;
661
+ // Named in the rule: only the file going stale can lose it, at whatever rate the file declares.
662
+ // Per device rather than by set equality — the filter is host-wide, and somebody else's device
663
+ // appearing in the rule must not make this one look unenforced.
664
+ if (file.rule.includes(udid))
665
+ return now - file.at > 3 * Math.max(file.pulseSeconds, 1);
666
+ // Not named, and the file was written before this device's rule was confirmed: the provider has
667
+ // simply not published since. That is the ordinary state for about a second after every toggle,
668
+ // and reading it as a disagreement fires on every one of them. It stops being ordinary once the
669
+ // provider has had three of its enforcing pulses to say something.
670
+ if (file.at <= since)
671
+ return now - since > 3 * ENFORCING_PULSE_SECONDS;
672
+ // Not named, and published *after* the confirmation. The provider has spoken and this device is
673
+ // not in what it said.
674
+ return true;
675
+ });
676
+ // **Q1, resolved: the evidence goes in the log and not on the wire.** Adding a drop count to
677
+ // `NetworkStatePayload` would be a protocol change for a number a tester cannot act on, and the
678
+ // one-directional reading below is not something a control can render honestly — "0 drops" looks
679
+ // like a failure and is not. A person diagnosing reads this line; nothing else changes.
680
+ //
681
+ // Deliberately outside the `lost` branch: it is worth saying that a device is *proven* enforcing,
682
+ // not only that one stopped being.
683
+ if (file) {
684
+ // **Over `this.offline`, never over the file's own keys.** The state file is host-wide: another
685
+ // agent's devices and rule entries this instance never wrote can be in it, and claiming evidence
686
+ // about those is the same mistake the loop above refuses to make — "somebody else's device
687
+ // appearing in the rule must not make this one look unenforced", pointed the other way.
688
+ for (const udid of this.offline) {
689
+ // **Not for a device this tick just declared lost.** The file that froze is where both
690
+ // readings come from, so without this the log says "enforcement observed" and then reports
691
+ // that enforcement stopped, one line apart, about the same device — a flat contradiction
692
+ // handed to the person the line exists for.
693
+ if (lost.includes(udid))
694
+ continue;
695
+ const drops = file.droppedByDevice[udid] ?? 0;
696
+ // **Only an increase is news.** This runs once a second, so a device with any drops at all
697
+ // would repeat the same line for as long as it stays offline — 600 of them in a ten-minute
698
+ // session, in the stream where the enforcement-lost report actually matters. A count that
699
+ // went *down* is a provider that restarted; it re-reports from there rather than staying
700
+ // silent until it passes the old high-water mark.
701
+ const reported = this.dropsReported.get(udid) ?? 0;
702
+ if (drops > reported) {
703
+ console.log(`[network] filter has dropped ${drops} flow(s) for ${udid} — enforcement observed, not just delivered`);
704
+ }
705
+ if (drops !== reported)
706
+ this.dropsReported.set(udid, drops);
707
+ }
708
+ }
709
+ if (lost.length === 0)
710
+ return;
711
+ for (const udid of lost) {
712
+ this.offline.delete(udid);
713
+ this.offlineSince.delete(udid);
714
+ this.dropsReported.delete(udid);
715
+ this.filterVerdict.set(udid, 'lost');
716
+ }
717
+ // **`remove: lost` is the whole point of this write, and naming only `add` was a regression.**
718
+ //
719
+ // The divergence being repaired is caused by the devices just deleted from `this.offline`. The
720
+ // whole-set write this replaced removed them by writing a set they were no longer in; a delta has
721
+ // to say so. Without it they stay in the host's rule, launchd brings the provider back in about
722
+ // six seconds, it re-reads the persisted configuration, and the kernel drops that simulator's
723
+ // traffic again — while layers 2 and 3 are down, `state()` answers `offline: false`, and the
724
+ // watcher has stopped because the set is empty. Traffic dead and reported online, which is the
725
+ // one direction this class exists to prevent.
726
+ //
727
+ // `add` stays, and not as symmetry: a device can be in this set with the rule not naming it, when
728
+ // `setOffline`'s failure path restored it in memory and its best-effort rewrite failed too.
729
+ await this.runFilterHost({ add: [...this.offline], remove: lost });
730
+ for (const udid of lost) {
731
+ // **Telling the tester is the remedy; taking the layers down is the tidying up.** The device is
732
+ // already reachable — that is what was detected — so leaving the app believing otherwise would
733
+ // add a second false state on top of the one being reported.
734
+ await this.takeDownLayers(udid);
735
+ this.enforcementLost(udid);
736
+ }
737
+ this.updateLiveness();
738
+ }
739
+ /** The first candidate that parses wins. A file that is present but unreadable is not evidence of
740
+ * anything, so it is treated as absent rather than as a reason to stop looking. */
741
+ readFilterState() {
742
+ for (const path of this.stateFiles) {
743
+ if (!existsSync(path))
744
+ continue;
745
+ try {
746
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
747
+ if (typeof raw.at !== 'number' || !Array.isArray(raw.rule))
748
+ continue;
749
+ return {
750
+ at: raw.at,
751
+ pulseSeconds: typeof raw.pulseSeconds === 'number' ? raw.pulseSeconds : 5,
752
+ rule: raw.rule.filter((r) => typeof r === 'string'),
753
+ // **Its absence is not a parse failure**, and that is the load-bearing part. The provider is
754
+ // installed by hand and replaced only on reboot, so a Mac running a provider older than
755
+ // #654 is the ordinary case during rollout — treating a missing field as a bad file would
756
+ // report "not enforcing" for a filter doing its job, which is the exact failure the rest of
757
+ // this file exists to prevent. A malformed one is discarded the same way, entry by entry.
758
+ droppedByDevice: numbersIn(raw.droppedByDevice),
759
+ };
760
+ }
761
+ catch {
762
+ continue;
763
+ }
764
+ }
765
+ return undefined;
766
+ }
767
+ // ── layer 1 ────────────────────────────────────────────────────────────────
768
+ /**
769
+ * **Serialised, and bounded in time.**
770
+ *
771
+ * The host takes the whole offline set on each run and the last writer wins, so two of these in
772
+ * flight at once decide the rule by which subprocess happens to finish last rather than by which
773
+ * request came last. Two devices toggled in the same second is enough — and the set each one reads
774
+ * is correct, which is what makes the wrong outcome hard to see afterwards: both runs are internally
775
+ * consistent and one of them is stale.
776
+ *
777
+ * **What is serialised is the whole operation, and an earlier version serialised only the host
778
+ * run.** That version released the queue the moment the rule was written, so the confirmation that
779
+ * follows ran outside it — and a review found two ways that breaks. A liveness tick landing between
780
+ * a device joining the offline set and its confirmation declared that device's enforcement lost,
781
+ * rewrote the rule without it, took layers 2 and 3 down, and told every session; the confirmation
782
+ * then came back, compared against a set the tick had already edited, agreed with itself, and put
783
+ * layers 2 and 3 **back on** over a kernel rule that no longer named the device. Two toggles of the
784
+ * same device overlapping produced the mirror image: a fully healthy-looking offline control with
785
+ * layer 2 taken down under it. Both end in the state this class exists to prevent — the app told it
786
+ * is offline while its requests succeed — so the boundary has to contain the confirmation, and
787
+ * every reader and writer of `offline` has to be inside it.
788
+ *
789
+ * The timeout covers a host that never returns. It waits on `OSSystemExtensionRequest`, and one of
790
+ * its outcomes is a System Settings dialog nobody is standing in front of; the binary now exits
791
+ * itself on that path, but a timeout here is what keeps a wedge from taking the queue with it —
792
+ * everything after it is waiting on this chain.
793
+ */
794
+ serialize(work) {
795
+ const run = this.filterQueue.then(work);
796
+ // Keep the chain alive whatever this run did: a rejection left on it would fail every later call.
797
+ this.filterQueue = run.then(() => undefined, () => undefined);
798
+ return run;
799
+ }
800
+ /**
801
+ * The container app writes the rule and exits.
802
+ *
803
+ * **Its exit is not the confirmation.** Zero means the container app launched and the framework
804
+ * accepted the save — the whole run is 27ms, measured — and the running provider is handed the new
805
+ * configuration afterwards, with nothing coming back to say it has it. So this answers "nothing
806
+ * refused"; whether the device is actually offline is answered by `state()`, from evidence the
807
+ * dylib wrote inside the simulator.
808
+ */
809
+ /**
810
+ * **Names the devices it is changing, and nothing else.**
811
+ *
812
+ * This used to write `[...this.offline]` — the whole set — and the host replaced the rule with it.
813
+ * The rule is host-wide, so that made every run an assertion about devices this agent had never
814
+ * heard of: a second agent starting knows of no offline device, and `arm()` runs on every device
815
+ * boot, so **starting one put every device the other had taken offline back online**, silently,
816
+ * while its tester watched an offline control over working traffic.
817
+ *
818
+ * A delta cannot say anything about a device it does not name. The cleanup the whole-set write used
819
+ * to provide is not lost, only made precise: `armLocked` names the udid that just booted in
820
+ * `remove`, and a rule left behind by a dead process is cleared the next time that device comes up
821
+ * rather than by wiping the host's.
822
+ */
823
+ async runFilterHost(delta) {
824
+ if (!existsSync(this.hostBinary))
825
+ return false;
826
+ const args = [];
827
+ if (delta.add?.length)
828
+ args.push('--add', delta.add.join(','));
829
+ if (delta.remove?.length)
830
+ args.push('--remove', delta.remove.join(','));
831
+ // **Nothing to say means do not run it, and that is load-bearing rather than an optimisation.**
832
+ // The host reads the absence of both flags as "clear the rule" — deliberately, because a person
833
+ // whose agent died holding a rule has no other way to empty it. So an agent that ran it with an
834
+ // empty delta would wipe the host's rule while believing it had done nothing.
835
+ if (args.length === 0)
836
+ return true;
837
+ try {
838
+ await execFileAsync(this.hostBinary, args, { timeout: FILTER_HOST_TIMEOUT_MS });
839
+ return true;
840
+ }
841
+ catch {
842
+ return false;
843
+ }
844
+ }
845
+ // ── layer 2 ────────────────────────────────────────────────────────────────
846
+ conditionPath(udid) {
847
+ return `${this.conditionDir}/tapflow-offline-${udid}`;
848
+ }
849
+ setCondition(udid, offline) {
850
+ const path = this.conditionPath(udid);
851
+ if (!offline) {
852
+ rmSync(path, { force: true });
853
+ return;
854
+ }
855
+ mkdirSync(this.conditionDir, { recursive: true });
856
+ writeFileSync(path, '');
857
+ }
858
+ /**
859
+ * `missing`, `failed` and `unreadable` are three different answers and a tester needs all of them.
860
+ *
861
+ * Missing is not by itself an answer — it is the same file being absent whether the injection was
862
+ * never delivered or is simply waiting for its first app, which is why `state` reads it against
863
+ * `armed` rather than reporting it directly. Failed means the dylib ran and proved by trying that
864
+ * its hooks did not take, which no amount of relaunching will change.
865
+ *
866
+ * Unreadable is neither, and folding it into `failed` was this reader claiming evidence it does not
867
+ * have: a file this reader cannot parse says nothing about whether the hooks took. **The library
868
+ * now writes it with `rename` and no longer produces torn ones (#653)**, which removes the cause
869
+ * that was reachable on a healthy session — not the member. A simulator still running an app that
870
+ * was launched by an older dylib writes the old way, and a file whose shape this reader does not
871
+ * recognise is unreadable however it got there. Unlike the other two it is **not** resolved against
872
+ * `armed` — see `state` for why that would be worse than the problem.
873
+ */
874
+ verdictPath(udid) {
875
+ return `${this.verdictDir}/tapflow-nethook-${udid}.json`;
876
+ }
877
+ readVerdict(udid) {
878
+ const path = this.verdictPath(udid);
879
+ if (!existsSync(path))
880
+ return 'missing';
881
+ try {
882
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
883
+ if (raw.installed === true)
884
+ return 'ok';
885
+ // **`failed` is the library's own signal and nothing else.** Testing for `!== true` swept up
886
+ // every shape that is not it — `{}`, `[]`, a bare number, a bare string — and answered
887
+ // "the library ran and proved its hooks did not take" about a file that shows no such thing.
888
+ // That is the same overclaim this branch was split out to remove, one case over.
889
+ return raw.installed === false ? 'failed' : 'unreadable';
890
+ }
891
+ catch {
892
+ // A file whose shape says nothing, or one written by a dylib from before the write became
893
+ // atomic (#653). Says nothing about the hooks either way, which is the whole reason it is not
894
+ // `failed`.
895
+ return 'unreadable';
896
+ }
897
+ }
898
+ }
899
+ //# sourceMappingURL=SimulatorNetwork.js.map