@trillboards/edge-sdk 0.2.191 → 0.2.194

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 (51) hide show
  1. package/deploy/detector/pyproject.toml +1 -1
  2. package/deploy/detector/tests/test_detection_colors_wire.py +134 -0
  3. package/deploy/detector/trillboards_detector/_version.py +2 -2
  4. package/deploy/detector/trillboards_detector/colors.py +85 -0
  5. package/deploy/detector/trillboards_detector/server.py +27 -0
  6. package/deploy/macos/apply-update.sh +254 -104
  7. package/deploy/macos/ci/connector-stand-in.js +42 -0
  8. package/deploy/macos/ci/helper-stand-in.sh +23 -0
  9. package/deploy/macos/ci/launchd-matrix.js +39 -0
  10. package/deploy/macos/ci/lib.sh +339 -0
  11. package/deploy/macos/ci/test-field-self-update.sh +153 -0
  12. package/deploy/macos/ci/test-update-launchd-boundary.sh +260 -0
  13. package/dist/DetectionColors.d.ts +44 -0
  14. package/dist/DetectionColors.d.ts.map +1 -0
  15. package/dist/DetectionColors.js +51 -0
  16. package/dist/DetectionColors.js.map +1 -0
  17. package/dist/DetectorFields.d.ts +213 -0
  18. package/dist/DetectorFields.d.ts.map +1 -0
  19. package/dist/DetectorFields.js +205 -0
  20. package/dist/DetectorFields.js.map +1 -0
  21. package/dist/EdgeAgent.js +1 -1
  22. package/dist/LocalDetectorClient.d.ts +4 -1
  23. package/dist/LocalDetectorClient.d.ts.map +1 -1
  24. package/dist/LocalDetectorClient.js +24 -1
  25. package/dist/LocalDetectorClient.js.map +1 -1
  26. package/dist/RetainedFieldContract.d.ts +1 -1
  27. package/dist/RetainedFieldContract.d.ts.map +1 -1
  28. package/dist/RetainedFieldContract.js +8 -1
  29. package/dist/RetainedFieldContract.js.map +1 -1
  30. package/dist/ReviewModelUse.d.ts.map +1 -1
  31. package/dist/ReviewModelUse.js +4 -0
  32. package/dist/ReviewModelUse.js.map +1 -1
  33. package/dist/ScopedVlmReview.d.ts +41 -0
  34. package/dist/ScopedVlmReview.d.ts.map +1 -1
  35. package/dist/ScopedVlmReview.js +160 -8
  36. package/dist/ScopedVlmReview.js.map +1 -1
  37. package/dist/SensingProfileClient.d.ts +3 -0
  38. package/dist/SensingProfileClient.d.ts.map +1 -1
  39. package/dist/SensingProfileClient.js +2 -0
  40. package/dist/SensingProfileClient.js.map +1 -1
  41. package/dist/connectorUpdate.d.ts.map +1 -1
  42. package/dist/connectorUpdate.js +19 -0
  43. package/dist/connectorUpdate.js.map +1 -1
  44. package/dist/diagnose.d.ts +1 -1
  45. package/dist/diagnose.js +1 -1
  46. package/dist/localSensing.d.ts +8 -0
  47. package/dist/localSensing.d.ts.map +1 -1
  48. package/dist/localSensing.js +86 -4
  49. package/dist/localSensing.js.map +1 -1
  50. package/package.json +1 -1
  51. package/retained/ProfileAuthorityClient.cjs +2 -1
@@ -1,9 +1,33 @@
1
1
  #!/bin/bash
2
2
  #
3
- # Stage and apply the signed, notarized macOS connector update package.
4
- # The running connector chooses the safe point; this detached helper owns the
5
- # download, macOS trust checks, LaunchAgent handoff, swap, smoke test, and
6
- # `.previous` rollback.
3
+ # apply-update.sh — stage and apply the signed, notarized macOS connector
4
+ # update package. The running connector chooses the safe point; this helper
5
+ # owns the download, the macOS trust checks, the LaunchAgent hand-off, the
6
+ # swap, the smoke test and the `.previous` rollback.
7
+ #
8
+ # The connector starts each phase detached (its own session and process
9
+ # group, connectorUpdateApplyMac.ts). launchd kills only the job's process
10
+ # group when the connector exits, so the helper outlives the connector it
11
+ # replaces and its own bootout of com.trillboards.edge — measured on a
12
+ # GitHub-hosted Mac (macOS 26.7, run 41934489152): a child in the connector's
13
+ # group got SIGTERM at its exit, the detached one ran on through both.
14
+ #
15
+ # EVERY EXIT AFTER THE ARGUMENTS PARSE LEAVES A RECORD in outcome.json, which
16
+ # the connector reports as connector_update_{result,detail,attempted_at}.
17
+ # Through 0.2.193 a failed stage exited silently — and staging failed on every
18
+ # Mac: verification ran `xcrun stapler validate` on `connector-update.pkg.download`.
19
+ # A Mac without developer tools has no stapler (xcrun only offers to install
20
+ # them), and with Xcode installed stapler refused the name: "Stapler is
21
+ # incapable of working with Safari download files." (run 41938418215). The
22
+ # published 0.2.140 under its real LaunchAgent, run 41934336173: "package has no
23
+ # valid notarization staple", with and without Xcode. No Mac ever staged an
24
+ # update, and none ever said so.
25
+ #
26
+ # TRUST, WITH TOOLS EVERY MAC HAS: pkgutil (a Developer ID Installer signature
27
+ # whose leaf is pinned to Team ID 78JQ7882U9, and Apple's notarization verdict)
28
+ # and spctl (Gatekeeper's install assessment). Nothing from Xcode.
29
+ #
30
+ # Compatible with the /bin/bash 3.2 that ships with macOS.
7
31
 
8
32
  set -u
9
33
 
@@ -17,6 +41,12 @@ CURRENT_VERSION=''
17
41
  EXPECTED_SHA256=''
18
42
  EXPECTED_SIZE=''
19
43
  WAIT_PID=''
44
+ # How long the connector may take to stop after it hands over. Its shutdown
45
+ # closes cameras and settles in-flight work; on expiry the helper restarts it
46
+ # on the current version rather than leaving a half-stopped connector.
47
+ CONNECTOR_EXIT_DEADLINE_S="${TRILLBOARDS_UPDATE_EXIT_DEADLINE_S:-300}"
48
+ # A lock older than any phase can run is stale even if its PID was reused.
49
+ LOCK_STALE_S=10800
20
50
 
21
51
  while [ "$#" -gt 0 ]; do
22
52
  case "$1" in
@@ -32,9 +62,13 @@ while [ "$#" -gt 0 ]; do
32
62
  esac
33
63
  done
34
64
 
65
+ HELPER_LOG=''
35
66
  log() {
36
67
  /usr/bin/logger -t com.trillboards.edge "apply-update: $*" 2>/dev/null || true
37
68
  printf '[apply-update] %s\n' "$*"
69
+ if [ -n "$HELPER_LOG" ]; then
70
+ printf '%s [%s %s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" "${MODE#--}" "$*" >> "$HELPER_LOG" 2>/dev/null || true
71
+ fi
38
72
  }
39
73
 
40
74
  case "$EXPECTED_VERSION" in
@@ -49,39 +83,111 @@ if [ "$INSTALL_DIR" != "$EXPECTED_INSTALL_DIR" ]; then
49
83
  log "refusing unexpected install root: $INSTALL_DIR"
50
84
  exit 2
51
85
  fi
86
+ if [ "$MODE" != '--stage' ] && [ "$MODE" != '--commit' ]; then
87
+ log 'exactly one of --stage or --commit is required'
88
+ exit 2
89
+ fi
52
90
 
53
91
  PARENT_DIR="$(dirname "$INSTALL_DIR")"
54
92
  UPDATE_DIR="$PARENT_DIR/.edge-auto-update"
55
93
  ARCHIVE="$UPDATE_DIR/connector-update.pkg"
94
+ # The download keeps a .pkg extension: Gatekeeper and pkgutil identify an
95
+ # installer package by its name as well as its bytes.
96
+ INCOMING="$UPDATE_DIR/incoming.pkg"
56
97
  MARKER="$UPDATE_DIR/staged.json"
57
98
  OUTCOME="$UPDATE_DIR/outcome.json"
58
99
  LOCK_DIR="$UPDATE_DIR/lock"
59
100
  PREVIOUS="$PARENT_DIR/edge.previous"
60
101
  PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
102
+ SERVICE="gui/$(id -u)/$LABEL"
61
103
 
62
104
  mkdir -p "$UPDATE_DIR" || exit 1
63
- if ! mkdir "$LOCK_DIR" 2>/dev/null; then
64
- log 'another update transaction is already running'
65
- exit 0
105
+ HELPER_LOG="$UPDATE_DIR/apply-update.log"
106
+ # Bounded: keep the last ~200 KB once the log passes 1 MB.
107
+ if [ -f "$HELPER_LOG" ] && [ "$(/usr/bin/wc -c < "$HELPER_LOG" | tr -d ' ')" -gt 1048576 ]; then
108
+ /usr/bin/tail -c 204800 "$HELPER_LOG" > "$HELPER_LOG.tmp.$$" 2>/dev/null && mv -f "$HELPER_LOG.tmp.$$" "$HELPER_LOG"
66
109
  fi
67
- trap 'rmdir "$LOCK_DIR" 2>/dev/null || true' EXIT
110
+ log "start: $MODE $CURRENT_VERSION -> $EXPECTED_VERSION (uid $(id -u), pid $$, started from ${XPC_SERVICE_NAME:-a shell})"
68
111
 
69
112
  json_escape() {
70
- printf '%s' "$1" | /usr/bin/sed 's/\\/\\\\/g; s/"/\\"/g'
113
+ printf '%s' "$1" | /usr/bin/tr '\n\r\t' ' ' | /usr/bin/sed 's/\\/\\\\/g; s/"/\\"/g'
71
114
  }
72
115
 
73
116
  write_outcome() {
74
- local result="$1" detail="$2" tmp="$OUTCOME.tmp.$$"
117
+ local result="$1" detail tmp="$OUTCOME.tmp.$$"
118
+ detail="$(printf '%s' "$2" | /usr/bin/cut -c1-450)"
75
119
  printf '{"attemptedAt":"%s","result":"%s","detail":"%s"}\n' \
76
120
  "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$result" "$(json_escape "$detail")" > "$tmp" \
77
121
  && mv -f "$tmp" "$OUTCOME"
122
+ log "outcome $result: $detail"
78
123
  }
79
124
 
80
- fail_stage() {
81
- log "$1"
82
- rm -f "$ARCHIVE.download" "$MARKER.tmp.$$"
83
- exit 1
125
+ # ---- one transaction at a time ---------------------------------------------
126
+ # A helper that was killed (power loss, SIGKILL, a reboot mid-download) never
127
+ # runs its EXIT trap, so a bare `mkdir` lock would refuse every later update
128
+ # for ever — silently, since that refusal is not a failure. The holder's PID
129
+ # and the lock's age decide instead. Builds through 0.2.193 wrote no PID file;
130
+ # their connector cannot be running once this helper is the one installed.
131
+ LOCK_HELD=0
132
+ lock_age_s() {
133
+ echo $(( $(date +%s) - $(/usr/bin/stat -f %m "$LOCK_DIR" 2>/dev/null || date +%s) ))
134
+ }
135
+ acquire_lock() {
136
+ local holder
137
+ if ! mkdir "$LOCK_DIR" 2>/dev/null; then
138
+ holder="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
139
+ if [ -n "$holder" ] && kill -0 "$holder" 2>/dev/null && [ "$(lock_age_s)" -lt "$LOCK_STALE_S" ]; then
140
+ return 1
141
+ fi
142
+ log "clearing a stale update lock (holder ${holder:-unrecorded}, age $(lock_age_s)s)"
143
+ rm -rf "$LOCK_DIR"
144
+ mkdir "$LOCK_DIR" 2>/dev/null || return 1
145
+ fi
146
+ printf '%s\n' "$$" > "$LOCK_DIR/pid"
147
+ LOCK_HELD=1
148
+ }
149
+
150
+ # ---- the LaunchAgent ---------------------------------------------------------
151
+ restart_agent() {
152
+ [ -f "$PLIST" ] || { log "no LaunchAgent plist at $PLIST"; return 1; }
153
+ /bin/launchctl bootout "$SERVICE" >/dev/null 2>&1 || true
154
+ local attempt=1
155
+ while [ "$attempt" -le 10 ]; do
156
+ /bin/launchctl bootstrap "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 || true
157
+ if /bin/launchctl print "$SERVICE" >/dev/null 2>&1; then
158
+ /bin/launchctl kickstart -k "$SERVICE" >/dev/null 2>&1 || true
159
+ return 0
160
+ fi
161
+ sleep 1
162
+ attempt=$((attempt + 1))
163
+ done
164
+ return 1
165
+ }
166
+
167
+ # The connector exits 0 once it has handed over, and its LaunchAgent restarts
168
+ # only an UNSUCCESSFUL exit (KeepAlive.SuccessfulExit=false). So after a
169
+ # --commit hand-off nothing restarts it unless this helper does — on every
170
+ # path, including the ones that refuse the update.
171
+ AGENT_PENDING=0
172
+ ensure_agent_running() {
173
+ if /bin/launchctl print "$SERVICE" 2>/dev/null | /usr/bin/grep -q 'state = running'; then
174
+ return 0
175
+ fi
176
+ if /bin/launchctl print "$SERVICE" >/dev/null 2>&1; then
177
+ /bin/launchctl kickstart "$SERVICE" >/dev/null 2>&1 && return 0
178
+ fi
179
+ restart_agent
180
+ }
181
+
182
+ on_exit() {
183
+ local rc=$?
184
+ if [ "$AGENT_PENDING" -eq 1 ]; then
185
+ if ensure_agent_running; then log 'connector restarted on the current version'; else log 'could not restart the connector'; fi
186
+ fi
187
+ [ "$LOCK_HELD" -eq 1 ] && rm -rf "$LOCK_DIR"
188
+ log "exit $rc"
84
189
  }
190
+ trap on_exit EXIT
85
191
 
86
192
  configure_proxy() {
87
193
  if [ -n "${HTTPS_PROXY:-}" ] || [ -n "${https_proxy:-}" ] || [ -n "${ALL_PROXY:-}" ]; then
@@ -98,128 +204,172 @@ configure_proxy() {
98
204
  export HTTPS_PROXY HTTP_PROXY="$HTTPS_PROXY"
99
205
  }
100
206
 
207
+ first_line() { printf '%s\n' "$1" | /usr/bin/sed -n '/[^[:space:]]/{p;q;}' | /usr/bin/cut -c1-200; }
208
+
209
+ # Sets VERIFY_FAILURE on refusal. Size and hash first (integrity: is this the
210
+ # package the manifest named?), then the signature and notarization
211
+ # (authenticity: did Aethercorp ship it, and did Apple notarize it?). A hash
212
+ # from the manifest is not authorization; the package signature is.
213
+ VERIFY_FAILURE=''
101
214
  verify_pkg() {
102
- local pkg="$1" sha="$2" size="$3" actual_size actual_sha sig_out
103
- [ -f "$pkg" ] || return 1
104
- case "$size" in *[!0-9]*|'') return 1 ;; esac
105
- printf '%s' "$sha" | /usr/bin/grep -Eq '^[0-9a-f]{64}$' || return 1
215
+ local pkg="$1" sha="$2" size="$3" actual_size actual_sha sig gk notarized=0
216
+ VERIFY_FAILURE=''
217
+ [ -f "$pkg" ] || { VERIFY_FAILURE='the downloaded package is missing'; return 1; }
218
+ case "$size" in *[!0-9]*|'') VERIFY_FAILURE='the manifest size is not a number'; return 1 ;; esac
219
+ printf '%s' "$sha" | /usr/bin/grep -Eq '^[0-9a-f]{64}$' || { VERIFY_FAILURE='the manifest SHA-256 is malformed'; return 1; }
106
220
 
107
221
  actual_size="$(/usr/bin/wc -c < "$pkg" | tr -d ' ')"
108
- [ "$actual_size" = "$size" ] || { log "payload size mismatch: expected $size, got $actual_size"; return 1; }
222
+ [ "$actual_size" = "$size" ] || { VERIFY_FAILURE="payload size mismatch: expected $size, got $actual_size"; return 1; }
109
223
  actual_sha="$(/usr/bin/shasum -a 256 "$pkg" | /usr/bin/awk '{print $1}')"
110
- [ "$actual_sha" = "$sha" ] || { log 'payload SHA-256 mismatch'; return 1; }
224
+ [ "$actual_sha" = "$sha" ] || { VERIFY_FAILURE="payload SHA-256 mismatch: got $actual_sha"; return 1; }
111
225
 
112
- sig_out="$UPDATE_DIR/signature.txt"
113
- /usr/sbin/pkgutil --check-signature "$pkg" > "$sig_out" 2>&1 || { log 'package signature is invalid'; return 1; }
114
- /usr/bin/grep -Fq "$EXPECTED_SIGNER" "$sig_out" || { log 'package signer is not Aethercorp'; return 1; }
115
- /usr/bin/xcrun stapler validate "$pkg" >/dev/null 2>&1 || { log 'package has no valid notarization staple'; return 1; }
116
- /usr/sbin/spctl -a -vv --type install "$pkg" >/dev/null 2>&1 || { log 'Gatekeeper rejected the update package'; return 1; }
226
+ sig="$(/usr/sbin/pkgutil --check-signature "$pkg" 2>&1)" \
227
+ || { VERIFY_FAILURE="pkgutil rejected the package signature: $(first_line "$sig")"; return 1; }
228
+ printf '%s\n' "$sig" > "$UPDATE_DIR/signature.txt"
229
+ printf '%s\n' "$sig" | /usr/bin/grep -Fq 'Status: signed by a developer certificate issued by Apple for distribution' \
230
+ || { VERIFY_FAILURE="the package is not signed with a Developer ID certificate: $(first_line "$(printf '%s\n' "$sig" | /usr/bin/grep -F 'Status:')")"; return 1; }
231
+ # The LEAF certificate (chain entry 1) must be ours; appearing anywhere in the
232
+ # output is not enough.
233
+ printf '%s\n' "$sig" | /usr/bin/grep -Eq "^[[:space:]]*1\\. Developer ID Installer: Aethercorp Inc \\(78JQ7882U9\\)[[:space:]]*\$" \
234
+ || { VERIFY_FAILURE="the package is not signed by $EXPECTED_SIGNER"; return 1; }
235
+ printf '%s\n' "$sig" | /usr/bin/grep -Fq 'Notarization: trusted by the Apple notary service' && notarized=1
236
+
237
+ # Gatekeeper's verdict on installing it. With assessments disabled on the
238
+ # machine spctl accepts without naming a source; notarization is then proven
239
+ # by pkgutil above.
240
+ gk="$(/usr/sbin/spctl --assess --type install -vv "$pkg" 2>&1)" \
241
+ || { VERIFY_FAILURE="Gatekeeper rejected the package: $(first_line "$gk")"; return 1; }
242
+ printf '%s\n' "$gk" >> "$UPDATE_DIR/signature.txt"
243
+ if printf '%s\n' "$gk" | /usr/bin/grep -q '^source='; then
244
+ printf '%s\n' "$gk" | /usr/bin/grep -Fqx 'source=Notarized Developer ID' \
245
+ || { VERIFY_FAILURE="Gatekeeper did not see a notarized Developer ID package: $(printf '%s\n' "$gk" | /usr/bin/grep '^source=')"; return 1; }
246
+ printf '%s\n' "$gk" | /usr/bin/grep -Fqx "origin=$EXPECTED_SIGNER" \
247
+ || { VERIFY_FAILURE="Gatekeeper saw a different signer: $(printf '%s\n' "$gk" | /usr/bin/grep '^origin=')"; return 1; }
248
+ notarized=1
249
+ fi
250
+ [ "$notarized" -eq 1 ] || { VERIFY_FAILURE='Apple has not notarized the package'; return 1; }
117
251
  return 0
118
252
  }
119
253
 
120
- if [ "$MODE" = '--stage' ]; then
121
- case "$UPDATE_URL" in https://*) ;; *) fail_stage 'update URL must use HTTPS' ;; esac
254
+ # ---- stage: download and verify while the connector keeps sensing ----------
255
+ fail_stage() { # result detail
256
+ rm -f "$INCOMING" "$MARKER.tmp.$$"
257
+ write_outcome "$1" "staging $EXPECTED_VERSION: $2"
258
+ exit 1
259
+ }
260
+
261
+ stage() {
262
+ case "$UPDATE_URL" in https://*) ;; *) fail_stage rejected 'the update URL is not HTTPS' ;; esac
263
+ acquire_lock || { log 'another update transaction is running'; exit 0; }
122
264
  configure_proxy
123
265
  log "downloading connector $EXPECTED_VERSION while sensing stays online"
124
- /usr/bin/curl --fail --location --silent --show-error --proto '=https' --tlsv1.2 \
125
- --connect-timeout 30 --max-time 3600 --output "$ARCHIVE.download" "$UPDATE_URL" \
126
- || fail_stage 'update download failed'
127
- verify_pkg "$ARCHIVE.download" "$EXPECTED_SHA256" "$EXPECTED_SIZE" \
128
- || fail_stage 'update package verification failed'
129
- mv -f "$ARCHIVE.download" "$ARCHIVE" || fail_stage 'could not retain verified package'
130
- marker_tmp="$MARKER.tmp.$$"
266
+ rm -f "$INCOMING"
267
+ local curl_err
268
+ curl_err="$(/usr/bin/curl --fail --location --silent --show-error --proto '=https' --tlsv1.2 \
269
+ --connect-timeout 30 --max-time 3600 --output "$INCOMING" "$UPDATE_URL" 2>&1)" \
270
+ || fail_stage failed "the download failed: $(first_line "$curl_err")"
271
+ verify_pkg "$INCOMING" "$EXPECTED_SHA256" "$EXPECTED_SIZE" || fail_stage rejected "$VERIFY_FAILURE"
272
+ mv -f "$INCOMING" "$ARCHIVE" || fail_stage failed 'could not keep the verified package'
273
+ local marker_tmp="$MARKER.tmp.$$"
131
274
  printf '{"version":"%s","currentVersion":"%s","sha256":"%s","sizeBytes":%s}\n' \
132
275
  "$EXPECTED_VERSION" "$CURRENT_VERSION" "$EXPECTED_SHA256" "$EXPECTED_SIZE" > "$marker_tmp" \
133
- || fail_stage 'could not write staged marker'
134
- mv -f "$marker_tmp" "$MARKER" || fail_stage 'could not publish staged marker'
135
- log "connector $EXPECTED_VERSION is staged, signed, notarized, and verified"
276
+ || fail_stage failed 'could not write the staged marker'
277
+ mv -f "$marker_tmp" "$MARKER" || fail_stage failed 'could not publish the staged marker'
278
+ log "connector $EXPECTED_VERSION is staged: size, SHA-256, Developer ID signature and notarization verified"
136
279
  exit 0
137
- fi
138
-
139
- if [ "$MODE" != '--commit' ]; then
140
- log 'exactly one of --stage or --commit is required'
141
- exit 2
142
- fi
143
-
144
- marker_version="$(/usr/bin/plutil -extract version raw "$MARKER" 2>/dev/null || true)"
145
- marker_sha="$(/usr/bin/plutil -extract sha256 raw "$MARKER" 2>/dev/null || true)"
146
- marker_size="$(/usr/bin/plutil -extract sizeBytes raw "$MARKER" 2>/dev/null || true)"
147
- if [ "$marker_version" != "$EXPECTED_VERSION" ]; then
148
- write_outcome 'rejected' 'staged version did not match the requested version'
149
- log 'staged version mismatch; refusing update'
150
- exit 1
151
- fi
152
- verify_pkg "$ARCHIVE" "$marker_sha" "$marker_size" || {
153
- write_outcome 'rejected' 'staged package failed commit-time verification'
154
- rm -f "$MARKER" "$ARCHIVE"
155
- exit 1
156
280
  }
157
281
 
158
- # The connector launches us and then exits cleanly. Do not touch its mapped
159
- # binaries until that PID is gone; a timeout leaves the current install intact.
160
- if [ -n "$WAIT_PID" ]; then
161
- waited=0
162
- while kill -0 "$WAIT_PID" 2>/dev/null && [ "$waited" -lt 120 ]; do
163
- sleep 1
164
- waited=$((waited + 1))
165
- done
166
- if kill -0 "$WAIT_PID" 2>/dev/null; then
167
- write_outcome 'failed' 'connector did not exit before the update deadline'
168
- log 'connector did not exit; leaving current install untouched'
169
- exit 1
282
+ # ---- commit: the connector has stopped at a safe point ----------------------
283
+ INSTALLER_DETAIL=''
284
+ installer_failure_detail() { # setup-log line count before the install
285
+ local setup_log="$HOME/Library/Logs/Trillboards/litertlm-setup.log" why=''
286
+ if [ -f "$setup_log" ]; then
287
+ why="$(/usr/bin/tail -n "+$(( $1 + 1 ))" "$setup_log" 2>/dev/null | /usr/bin/grep 'ERROR' | /usr/bin/tail -n 1 \
288
+ | /usr/bin/sed 's/^.*ERROR: *//')"
170
289
  fi
171
- fi
172
-
173
- restart_agent() {
174
- [ -f "$PLIST" ] || return 1
175
- /bin/launchctl bootout "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
176
- local attempt=1
177
- while [ "$attempt" -le 10 ]; do
178
- /bin/launchctl bootstrap "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 || true
179
- if /bin/launchctl print "gui/$(id -u)/$LABEL" >/dev/null 2>&1; then
180
- /bin/launchctl kickstart -k "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
181
- return 0
182
- fi
183
- sleep 1
184
- attempt=$((attempt + 1))
185
- done
186
- return 1
290
+ [ -n "$why" ] || why="$(/usr/bin/grep -iE 'error|fail' "$UPDATE_DIR/installer.log" 2>/dev/null | /usr/bin/tail -n 1)"
291
+ INSTALLER_DETAIL="$(printf '%s' "$why" | /usr/bin/cut -c1-200)"
187
292
  }
188
293
 
189
294
  rollback() {
190
295
  local detail="$1"
191
- /bin/launchctl bootout "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
296
+ /bin/launchctl bootout "$SERVICE" >/dev/null 2>&1 || true
192
297
  rm -rf "$INSTALL_DIR"
193
298
  if [ -d "$PREVIOUS" ]; then
194
299
  mv "$PREVIOUS" "$INSTALL_DIR" || true
195
300
  fi
196
301
  if restart_agent; then
197
- write_outcome 'failed' "$detail; previous version restored"
302
+ AGENT_PENDING=0
303
+ write_outcome 'failed' "$detail; previous version $CURRENT_VERSION restored"
198
304
  else
199
305
  write_outcome 'failed' "$detail; previous files restored but the agent did not restart"
200
306
  fi
201
307
  rm -f "$MARKER" "$ARCHIVE"
202
- log "$detail; rolled back"
203
308
  exit 1
204
309
  }
205
310
 
206
- log "applying connector $EXPECTED_VERSION"
207
- /bin/launchctl bootout "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
208
- rm -rf "$PREVIOUS"
209
- mv "$INSTALL_DIR" "$PREVIOUS" || {
210
- write_outcome 'failed' 'could not preserve the current install for rollback'
211
- exit 1
212
- }
311
+ commit() {
312
+ AGENT_PENDING=1
313
+ # Wait for the connector FIRST. It exits right after starting this helper
314
+ # whatever happens next, so every decision below is made with it stopped,
315
+ # and every refusal can restart it cleanly.
316
+ if [ -n "$WAIT_PID" ]; then
317
+ local waited=0
318
+ while kill -0 "$WAIT_PID" 2>/dev/null && [ "$waited" -lt "$CONNECTOR_EXIT_DEADLINE_S" ]; do
319
+ sleep 1
320
+ waited=$((waited + 1))
321
+ done
322
+ if kill -0 "$WAIT_PID" 2>/dev/null; then
323
+ /bin/launchctl kickstart -k "$SERVICE" >/dev/null 2>&1 || true
324
+ AGENT_PENDING=0
325
+ write_outcome 'failed' "the connector did not stop within ${CONNECTOR_EXIT_DEADLINE_S}s; restarted on $CURRENT_VERSION"
326
+ exit 1
327
+ fi
328
+ log "connector pid $WAIT_PID stopped after ${waited}s"
329
+ fi
330
+ acquire_lock || { write_outcome 'failed' 'another update transaction was running'; exit 1; }
213
331
 
214
- /usr/sbin/installer -pkg "$ARCHIVE" -target CurrentUserHomeDirectory >/dev/null 2>&1 \
215
- || rollback 'macOS Installer rejected the update'
332
+ local marker_version marker_sha marker_size
333
+ marker_version="$(/usr/bin/plutil -extract version raw "$MARKER" 2>/dev/null || true)"
334
+ marker_sha="$(/usr/bin/plutil -extract sha256 raw "$MARKER" 2>/dev/null || true)"
335
+ marker_size="$(/usr/bin/plutil -extract sizeBytes raw "$MARKER" 2>/dev/null || true)"
336
+ if [ "$marker_version" != "$EXPECTED_VERSION" ]; then
337
+ write_outcome 'rejected' "the staged version (${marker_version:-none}) is not the requested $EXPECTED_VERSION"
338
+ exit 1
339
+ fi
340
+ if ! verify_pkg "$ARCHIVE" "$marker_sha" "$marker_size"; then
341
+ write_outcome 'rejected' "the staged package failed commit-time verification: $VERIFY_FAILURE"
342
+ rm -f "$MARKER" "$ARCHIVE"
343
+ exit 1
344
+ fi
345
+
346
+ log "applying connector $EXPECTED_VERSION"
347
+ /bin/launchctl bootout "$SERVICE" >/dev/null 2>&1 || true
348
+ rm -rf "$PREVIOUS"
349
+ mv "$INSTALL_DIR" "$PREVIOUS" || {
350
+ write_outcome 'failed' 'could not preserve the current install for rollback'
351
+ exit 1
352
+ }
353
+
354
+ local setup_lines=0
355
+ [ -f "$HOME/Library/Logs/Trillboards/litertlm-setup.log" ] \
356
+ && setup_lines="$(/usr/bin/wc -l < "$HOME/Library/Logs/Trillboards/litertlm-setup.log" | tr -d ' ')"
357
+ if ! /usr/sbin/installer -pkg "$ARCHIVE" -target CurrentUserHomeDirectory -verboseR > "$UPDATE_DIR/installer.log" 2>&1; then
358
+ installer_failure_detail "$setup_lines"
359
+ rollback "macOS Installer rejected the update${INSTALLER_DETAIL:+: $INSTALLER_DETAIL}"
360
+ fi
216
361
 
217
- installed_version="$($INSTALL_DIR/bin/trillboards-edge version 2>/dev/null || true)"
218
- printf '%s' "$installed_version" | /usr/bin/grep -Fq "edge-sdk v$EXPECTED_VERSION" \
219
- || rollback 'updated connector failed its version smoke test'
362
+ local installed_version
363
+ installed_version="$("$INSTALL_DIR/bin/trillboards-edge" version 2>/dev/null || true)"
364
+ printf '%s' "$installed_version" | /usr/bin/grep -Fq "edge-sdk v$EXPECTED_VERSION" \
365
+ || rollback "the updated connector failed its version smoke test ($(first_line "$installed_version"))"
366
+
367
+ restart_agent || rollback 'the updated connector installed but its LaunchAgent did not restart'
368
+ AGENT_PENDING=0
369
+ write_outcome 'success' "updated from $CURRENT_VERSION to $EXPECTED_VERSION"
370
+ rm -f "$MARKER" "$ARCHIVE"
371
+ log "connector $EXPECTED_VERSION installed and relaunched"
372
+ exit 0
373
+ }
220
374
 
221
- restart_agent || rollback 'updated connector installed but its LaunchAgent did not restart'
222
- write_outcome 'success' "updated from $CURRENT_VERSION to $EXPECTED_VERSION"
223
- rm -f "$MARKER" "$ARCHIVE" "$UPDATE_DIR/signature.txt"
224
- log "connector $EXPECTED_VERSION installed and relaunched"
225
- exit 0
375
+ if [ "$MODE" = '--stage' ]; then stage; else commit; fi
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+ // Runs as the MAIN process of com.trillboards.edge and drives a compiled
3
+ // MacConnectorUpdateApplier exactly as connectorUpdate.ts does: stage, poll the
4
+ // staged marker, commit, then exit 0 the way requestExit() does. A relaunch of
5
+ // the LaunchAgent finds the marker file and records only that it came back.
6
+ //
7
+ // node connector-stand-in.js <dir> <applier.js> <installRoot> <phase> <version> <url> <sha256> <size> <current>
8
+ // phase: stage (stage, then stay up) | full (stage, then commit and exit)
9
+ // | commit-staged (commit what is already on disk, then exit)
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+
13
+ const [dir, applierJs, installRoot, phase, version, updateUrl, sha, size, currentVersion] = process.argv.slice(2);
14
+ const log = (m) => fs.appendFileSync(path.join(dir, 'connector.log'), `${new Date().toISOString()} pid=${process.pid} ${m}\n`);
15
+ const ran = path.join(dir, 'connector.ran');
16
+ if (fs.existsSync(ran)) {
17
+ log(`RELAUNCHED by launchd (first run pid ${fs.readFileSync(ran, 'utf8').trim()}) env XPC_SERVICE_NAME=${process.env.XPC_SERVICE_NAME}`);
18
+ setInterval(() => {}, 1 << 30);
19
+ return;
20
+ }
21
+ fs.writeFileSync(ran, String(process.pid));
22
+ log(`started env XPC_SERVICE_NAME=${process.env.XPC_SERVICE_NAME}`);
23
+ const { MacConnectorUpdateApplier } = require(applierJs);
24
+ const applier = new MacConnectorUpdateApplier({ installRoot, log: (m) => log(`applier: ${m}`) });
25
+ const manifest = { connectorVersion: version, updateUrl, updateSha256: sha, updateSizeBytes: Number(size) };
26
+ if (phase === 'commit-staged') {
27
+ log(`commit() -> ${applier.commit({ version, currentVersion })}; exiting 0 like requestExit`);
28
+ setTimeout(() => process.exit(0), 250);
29
+ return;
30
+ }
31
+ log(`stage() -> ${applier.stage({ manifest, currentVersion })}`);
32
+ let polls = 0;
33
+ const timer = setInterval(() => {
34
+ polls += 1;
35
+ const staged = applier.stagedVersion();
36
+ if (polls % 6 === 0) log(`poll ${polls}: staged=${staged} outcome=${JSON.stringify(applier.readOutcome())}`);
37
+ if (phase !== 'full' || staged !== version) return;
38
+ clearInterval(timer);
39
+ const ok = applier.commit({ version, currentVersion });
40
+ log(`staged ${staged}; commit() -> ${ok}; exiting 0 like requestExit`);
41
+ setTimeout(() => process.exit(0), 250);
42
+ }, 5000);
@@ -0,0 +1,23 @@
1
+ #!/bin/bash
2
+ # A stand-in for the update helper: records how it was started, then heartbeats
3
+ # so the rig can see whether launchd let it live. Optional third argument: a
4
+ # launchd service target this child boots out after 20 s, the way
5
+ # apply-update.sh --commit boots out com.trillboards.edge.
6
+ dir="$1"; tag="$2"; bootout_target="${3:-}"
7
+ hb="$dir/$tag.hb"
8
+ log="$dir/$tag.log"
9
+ printf '%s start pid=%s ps=[%s]\n' "$(date -u +%H:%M:%S)" "$$" "$(ps -o pid=,ppid=,pgid=,sess=,tpgid= -p $$ | tr -s ' ')" >> "$log"
10
+ for s in TERM HUP INT QUIT USR1 USR2; do
11
+ trap "printf '%s got SIG$s\n' \"\$(date -u +%H:%M:%S)\" >> '$log'; exit 0" "$s"
12
+ done
13
+ i=0
14
+ while [ "$i" -lt 420 ]; do
15
+ date -u +%H:%M:%S > "$hb"
16
+ if [ -n "$bootout_target" ] && [ "$i" -eq 20 ]; then
17
+ out="$(/bin/launchctl bootout "$bootout_target" 2>&1)"; rc=$?
18
+ printf '%s self-bootout of %s rc=%s %s\n' "$(date -u +%H:%M:%S)" "$bootout_target" "$rc" "$out" >> "$log"
19
+ fi
20
+ sleep 1
21
+ i=$((i + 1))
22
+ done
23
+ printf '%s finished normally\n' "$(date -u +%H:%M:%S)" >> "$log"
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ // Runs as the MAIN process of a LaunchAgent, like the connector (record arm of
3
+ // test-update-launchd-boundary.sh). Starts the
4
+ // stand-in helper several ways, then exits 0 the way requestExit() does.
5
+ const { spawn, spawnSync } = require('node:child_process');
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+
9
+ const [dir, childScript, uid, selfLabel, withSelfBootout] = process.argv.slice(2);
10
+ const log = (m) => fs.appendFileSync(path.join(dir, 'matrix.log'), `${new Date().toISOString()} ${m}\n`);
11
+ log(`main pid=${process.pid} ppid=${process.ppid} label=${selfLabel}`);
12
+
13
+ // 1. The released hand-off: connectorUpdateApplyMac.ts launch().
14
+ spawn('/bin/bash', [childScript, dir, 'detached-ignore'], { detached: true, stdio: 'ignore' }).unref();
15
+ // 2. A plain child in the connector's own process group.
16
+ spawn('/bin/bash', [childScript, dir, 'attached-ignore'], { stdio: 'ignore' }).unref();
17
+ // 3. nohup + detached.
18
+ spawn('/usr/bin/nohup', ['/bin/bash', childScript, dir, 'nohup-detached'], { detached: true, stdio: 'ignore' }).unref();
19
+ // 4. Its own launchd job, bootstrapped from a one-shot plist.
20
+ const helperLabel = `${selfLabel}.helper`;
21
+ const plist = path.join(dir, `${helperLabel}.plist`);
22
+ fs.writeFileSync(plist, `<?xml version="1.0" encoding="UTF-8"?>
23
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
24
+ <plist version="1.0"><dict>
25
+ <key>Label</key><string>${helperLabel}</string>
26
+ <key>ProgramArguments</key><array><string>/bin/bash</string><string>${childScript}</string><string>${dir}</string><string>own-launchd-job</string></array>
27
+ <key>RunAtLoad</key><true/>
28
+ <key>AbandonProcessGroup</key><true/>
29
+ <key>ProcessType</key><string>Background</string>
30
+ </dict></plist>
31
+ `);
32
+ const boot = spawnSync('/bin/launchctl', ['bootstrap', `gui/${uid}`, plist], { encoding: 'utf8' });
33
+ log(`bootstrap ${helperLabel}: status=${boot.status} ${String(boot.stderr || '').trim()}`);
34
+ // 5. The released hand-off again, but this child later boots out the job that
35
+ // started it, exactly as apply-update.sh --commit does.
36
+ if (withSelfBootout === '1') {
37
+ spawn('/bin/bash', [childScript, dir, 'detached-self-bootout', `gui/${uid}/${selfLabel}`], { detached: true, stdio: 'ignore' }).unref();
38
+ }
39
+ setTimeout(() => { log('main exiting 0 (requestExit)'); process.exit(0); }, 8000);