GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — perch/package-release.py at main · mossfinch/perch

Expand file tree

/

package-release.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
449 lines (377 loc) · 21.4 KB
/

package-release.py

Copy path

File metadata and controls

449 lines (377 loc) · 21.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#!/usr/bin/env python3
"""Package a built Perch.app into the release zip, and prove the zip is exactly that bundle.
This is separate from installation because the zip is the released artifact.
A bundle-only audit cannot detect extra siblings added during packaging.
So the input here is one `.app` path, never a directory to sweep. Anything that
is not inside that bundle is structurally unable to end up in the archive.
The archive is written here rather than delegated to a generic packer because
standard archive formats can preserve build-machine metadata:
tar -czf ustar header writes the owner's account name
zip -r 0x7875 extra carries the numeric uid; the DOS
timestamp is local wall time, and subtracting it
from a release's public UTC publish time yields
the packer's timezone
ditto -c -k __MACOSX/._* sidecars, carrying the xattrs whole
ditto with every "clean" flag it has, under TZ=UTC
still writes an 0x5855 extra into each local
header carrying the packer's uid and gid
hdiutil (dmg) all of the above
The script therefore owns the archive bytes instead of chasing packer-specific
fields. A gate tied to one packer's metadata field does not protect output from
another packer. Naming known-bad fields cannot terminate. Declaring the whole
archive can, so every entry below is written with its extra and comment
explicitly empty, and the audit refuses anything it did not declare.
The audit parses the archive's raw bytes instead of reading it through
zipfile. `ZipInfo.extra` exposes only the central directory copy of an entry's
extra field; the uid above lives only in the local header, where that view
cannot reach it. That is the same shape as the bundle-versus-archive mistake
this file exists to prevent.
Run it:
python3 package-release.py /path/to/Perch.app # writes ./Perch-<ver>.zip
"""
from __future__ import annotations
import argparse
import hashlib
import os
import struct
import subprocess
import tempfile
import zipfile
from pathlib import Path
from typing import NamedTuple
# A fixed stamp, so the archive says nothing about when it was built, not even
# the hour of the day. It has to be >= 1980: the zip format's DOS
# timestamp cannot represent anything earlier, and out-of-range values get
# silently clamped rather than rejected.
EPOCH_DOS = (2026, 1, 1, 0, 0, 0)
EXEC_SUBPATH = "Contents/MacOS/Perch"
# Path components that have no business shipping at all. The manifest already
# excludes the ones that live *beside* the bundle; this catches the day a build
# starts leaving them *inside* it, which is the only way they could get in now.
BANNED_COMPONENT_SUFFIX = (".dSYM", ".swiftmodule", ".swiftsourceinfo",
".swiftdoc", ".swiftinterface", ".build")
SIDECAR_PREFIX = "._"
SIDECAR_DIR = "__MACOSX"
# An opaque compressed payload cannot be read as text, so its bytes would ship
# unscanned. Nothing in the bundle should be one; if a future build adds one,
# stop rather than wave it through.
ARCHIVE_MAGIC = (b"PK\x03\x04", b"\x1f\x8b", b"BZh", b"\xfd7zXZ")
BUILD_PATH_ROOT = "/Users/"
# Zip's fixed-size records. Named here because the audit reads them by hand.
LOCAL_SIG, CENTRAL_SIG, EOCD_SIG = b"PK\x03\x04", b"PK\x01\x02", b"PK\x05\x06"
LOCAL_HEADER_LEN, CENTRAL_HEADER_LEN, EOCD_LEN = 30, 46, 22
# Bit 11 says "the filename is UTF-8". It is the only general-purpose flag an
# archive written here may carry; every other bit means encryption, a data
# descriptor, or a compression option none of which this packer emits.
FLAG_UTF8_NAME = 0x800
class Entry(NamedTuple):
"""One declared member of the archive. `digest` is "" for directories."""
is_dir: bool
mode: int
digest: str
def needles() -> list[tuple[bytes, str]]:
"""The build-path root in every encoding a Mach-O or a plist might use.
A raw `find(b"/Users/")` reads only the ASCII case. UTF-16 is not exotic
here (plists and some resource formats use it), and UTF-32 sails past a
search written for the other two.
Lowercased, because the buffer is lowercased before searching: `bytes.lower`
touches only ASCII A-Z, so in every encoding here the padding bytes are left
alone and one pass covers both casings.
"""
return [(BUILD_PATH_ROOT.lower().encode(enc), enc)
for enc in ("utf-8", "utf-16-le", "utf-16-be", "utf-32-le", "utf-32-be")]
def run(cmd: list[str], **kwargs) -> None:
print("+", " ".join(cmd))
subprocess.run(cmd, check=True, **kwargs)
def manifest(app: Path) -> dict[str, Entry]:
"""Declare exactly what the archive must contain, read off the real bundle.
The audit downstream compares the archive against this and refuses any
difference in either direction, so a field, an entry or a byte that nothing
here declared cannot ship.
"""
want: dict[str, Entry] = {}
def add(p: Path) -> None:
rel = p.relative_to(app.parent).as_posix()
if p.is_symlink():
raise SystemExit(
f"{rel}: symlink inside the bundle. This packer writes plain files only, "
"so it would silently ship the link's target instead — refusing rather than guessing.")
for part in rel.split("/"):
if part == SIDECAR_DIR or part.startswith(SIDECAR_PREFIX):
raise SystemExit(f"{rel}: resource-fork sidecar, refusing to ship it")
if part.endswith(BANNED_COMPONENT_SUFFIX):
raise SystemExit(
f"{rel}: build by-product (debug symbols or Swift module) inside the bundle, "
"refusing to ship it — these carry the builder's absolute source paths")
# The full st_mode, file-type bits included, not just the permissions.
# ditto reads an entry whose mode lacks S_IFREG/S_IFDIR as not-Unix and
# falls back to 0644, which costs the executable its execute bit and the
# app its ability to launch. `unzip` honours the permissions either way,
# so it cannot be the tool this is verified with (see prove_extractable).
mode = p.lstat().st_mode & 0xFFFF
if p.is_dir():
want[rel + "/"] = Entry(True, mode, "")
else:
want[rel] = Entry(False, mode, hashlib.sha256(p.read_bytes()).hexdigest())
add(app)
for p in sorted(app.rglob("*")):
add(p)
if f"{app.name}/{EXEC_SUBPATH}" not in want:
raise SystemExit(
f"{app.name} has no {EXEC_SUBPATH} — refusing to call an archive clean "
"when it may hold nothing that runs")
return want
def pack(app: Path, out: Path, want: dict[str, Entry]) -> None:
"""Write the archive entry by entry, so nothing gets stamped on it unasked.
Every field a packer would fill in from the machine is set here instead:
the timestamp is fixed, the extra and comment fields stay empty, and the
permission bits are the bundle's own rather than the umask's.
"""
if out.exists():
out.unlink()
with zipfile.ZipFile(out, "w") as z:
for name, e in want.items():
info = zipfile.ZipInfo(name, date_time=EPOCH_DOS)
# Unix, or the mode below is ignored on extraction and the
# executable comes out without its execute bit.
info.create_system = 3
info.external_attr = (e.mode & 0xFFFF) << 16
if e.is_dir:
info.external_attr |= 0x10 # MS-DOS directory flag
info.compress_type = zipfile.ZIP_STORED
z.writestr(info, b"")
else:
info.compress_type = zipfile.ZIP_DEFLATED
z.writestr(info, (app.parent / name).read_bytes())
def _u16(buf: bytes, at: int) -> int:
return struct.unpack_from("<H", buf, at)[0]
def _u32(buf: bytes, at: int) -> int:
return struct.unpack_from("<I", buf, at)[0]
def dos_datetime(date: int, time: int) -> tuple[int, int, int, int, int, int]:
"""Decode zip's packed DOS date and time into the tuple EPOCH_DOS is written in."""
return ((date >> 9) + 1980, (date >> 5) & 0xF, date & 0x1F,
time >> 11, (time >> 5) & 0x3F, (time & 0x1F) * 2)
def read_structure(raw: bytes) -> list[dict]:
"""Account for every byte of the archive, from 0 to EOF.
Read by hand because `zipfile` shows only the central directory's copy of
each entry's extra field, and a packer's identity can live in the local
headers alone.
Byte accounting instead of boundary checks, because checking boundaries is
the same losing game as naming bad fields: a zip has spans no boundary
touches (between the last file's data and the central directory, for one),
and anything can sit there while every boundary holds. Every span has to be
claimed by a record, or the claim is not worth making: the cursor below
starts at 0, is handed from one record to the next, and must land exactly
on EOF.
"""
eocd = len(raw) - EOCD_LEN
if eocd < 0 or raw[eocd:eocd + 4] != EOCD_SIG:
raise SystemExit("archive does not end with its end-of-central-directory record — "
"there are trailing bytes, or an archive comment, and both carry content")
if _u16(raw, eocd + 20) != 0:
raise SystemExit("archive claims a comment; refusing to ship a field nothing declared")
if _u16(raw, eocd + 4) or _u16(raw, eocd + 6):
raise SystemExit("archive claims to be one volume of a multi-part set — "
"the other parts are not here and nothing accounts for them")
if _u16(raw, eocd + 8) != _u16(raw, eocd + 10):
raise SystemExit("end record disagrees with itself about how many entries there are")
count = _u16(raw, eocd + 10)
cd_size, cd_at = _u32(raw, eocd + 12), _u32(raw, eocd + 16)
if cd_at + cd_size != eocd:
raise SystemExit("central directory does not run up to the end record — "
"there is unaccounted space inside the archive")
# Pass 1: the central directory, consumed header by header up to the end record.
entries, at = [], cd_at
for _ in range(count):
if raw[at:at + 4] != CENTRAL_SIG:
raise SystemExit("central directory is shorter than its own entry count")
n_len, e_len, c_len = _u16(raw, at + 28), _u16(raw, at + 30), _u16(raw, at + 32)
name = raw[at + 46:at + 46 + n_len].decode("utf-8", "replace")
if e_len or c_len:
raise SystemExit(f"{name}: central directory entry carries an extra field or comment. "
"Those are exactly where a packer writes its uid — refusing.")
if _u16(raw, at + 34):
raise SystemExit(f"{name}: entry claims to start on another volume")
flags = _u16(raw, at + 8)
if flags & ~FLAG_UTF8_NAME:
raise SystemExit(f"{name}: unexpected general-purpose flags {flags:#06x} "
"(encryption, data descriptor or a compression option this packer never emits)")
entries.append({
"name": name,
"mode": (_u32(raw, at + 38) >> 16) & 0xFFFF,
"when": dos_datetime(_u16(raw, at + 14), _u16(raw, at + 12)),
"local_at": _u32(raw, at + 42),
"central_at": at,
"csize": _u32(raw, at + 20),
})
at += CENTRAL_HEADER_LEN + n_len + e_len + c_len
if at != eocd:
raise SystemExit("central directory ends before the end record — the gap between them ships too")
# Pass 2: the local headers and their payloads, in file order, with no gaps.
cursor = 0
for e in sorted(entries, key=lambda e: e["local_at"]):
name, local_at = e["name"], e["local_at"]
if local_at != cursor:
span = local_at - cursor
raise SystemExit(
f"{name}: {span} byte(s) before this entry belong to no record. "
"Unclaimed bytes ship with the archive and no reader accounts for them." if span > 0 else
f"{name}: entry overlaps the one before it")
if raw[local_at:local_at + 4] != LOCAL_SIG:
raise SystemExit(f"{name}: central directory points at something that is not a local header")
ln_len, le_len = _u16(raw, local_at + 26), _u16(raw, local_at + 28)
if le_len:
raise SystemExit(
f"{name}: local header carries an extra field ({le_len} bytes). This is where "
"ditto writes the packer's uid and gid, and where the central directory copy "
"cannot show it — refusing.")
local_name = raw[local_at + 30:local_at + 30 + ln_len].decode("utf-8", "replace")
if local_name != name:
raise SystemExit(f"{name}: local header names it {local_name!r} instead. "
"A reader that trusts one of the two sees a different archive than the other.")
# The two copies must agree; a reader that trusts one otherwise sees a
# different archive than a reader that trusts the other.
for field, off_c, off_l, width in (("flags", 8, 6, _u16), ("method", 10, 8, _u16),
("time", 12, 10, _u16), ("date", 14, 12, _u16),
("crc", 16, 14, _u32), ("csize", 20, 18, _u32),
("usize", 24, 22, _u32)):
if width(raw, e["central_at"] + off_c) != width(raw, local_at + off_l):
raise SystemExit(f"{name}: {field} differs between local header and central directory")
cursor = local_at + LOCAL_HEADER_LEN + ln_len + le_len + e["csize"]
if cursor > cd_at:
raise SystemExit(f"{name}: its data runs past the start of the central directory")
if cursor != cd_at:
raise SystemExit(f"{cd_at - cursor} byte(s) between the last entry's data and the central "
"directory belong to no record. Unclaimed bytes ship with the archive.")
return entries
def audit(zip_path: Path, want: dict[str, Entry]) -> None:
"""The archive must be exactly `want`: no extra entry, field, or byte.
Kept separate from packing so it can be pointed at a finished archive
without trusting whatever produced it.
"""
entries = read_structure(zip_path.read_bytes())
names = [e["name"] for e in entries]
if len(names) != len(set(names)):
dupes = sorted({n for n in names if names.count(n) > 1})
raise SystemExit(f"archive lists the same entry twice: {', '.join(dupes)}. "
"Which one a reader gets depends on the reader.")
for name in names:
if name.startswith("/") or ".." in name.split("/") or "\\" in name:
raise SystemExit(f"{name}: entry name escapes the extraction directory")
missing = sorted(set(want) - set(names))
surplus = sorted(set(names) - set(want))
if missing or surplus:
raise SystemExit(
"archive does not match the bundle it claims to be:\n"
+ "".join(f" missing: {n}\n" for n in missing)
+ "".join(f" not declared anywhere: {n}\n" for n in surplus))
for e in entries:
declared = want[e["name"]]
# A value that is declared but never checked is a hole: pack() writes a
# fixed stamp so the archive says nothing about when, or in which
# timezone, it was built, and this confirms that it did.
if e["when"] != EPOCH_DOS:
raise SystemExit(f"{e['name']}: stamped {e['when']}, not the fixed {EPOCH_DOS}. "
"A real clock here leaks the packer's timezone.")
if e["mode"] != declared.mode:
raise SystemExit(f"{e['name']}: mode {e['mode']:o} in the archive, "
f"{declared.mode:o} in the bundle")
with zipfile.ZipFile(zip_path) as z:
for e in entries:
declared = want[e["name"]]
if declared.is_dir:
continue
buf = z.read(e["name"])
got = hashlib.sha256(buf).hexdigest()
if got != declared.digest:
raise SystemExit(f"{e['name']}: content differs from the bundle "
f"(declared {declared.digest[:12]}…, archive holds {got[:12]}…)")
if buf[:6].startswith(ARCHIVE_MAGIC):
raise SystemExit(
f"{e['name']}: a compressed archive inside the archive. Its bytes cannot "
"be scanned as text, so it is refused rather than trusted.")
hay = buf.lower()
for needle, enc in needles():
at = hay.find(needle)
if at != -1:
sample = buf[at:at + 120].decode(enc, "replace").split("\x00")[0]
raise SystemExit(
f"{e['name']}: carries a build-machine path ({enc}), refusing to ship it:\n"
f" {sample}")
exe = next((e for e in entries if e["name"].endswith("/" + EXEC_SUBPATH)), None)
if exe is None:
raise SystemExit(f"archive contains no {EXEC_SUBPATH} — refusing to call it clean "
"when it may hold nothing that runs")
if not exe["mode"] & 0o111:
raise SystemExit(f"{exe['name']}: no execute bit survived packing; the app would not launch")
# Success text must match audited coverage because callers act on the claim.
print(f"Audited {zip_path.name}: {len(entries)} entries. Every byte from 0 to EOF belongs "
"to a record; every entry matches the bundle's own name, mode, timestamp and sha256; "
"no extra field, no comment, no entry the bundle does not have.\n"
" This proves the archive IS the bundle it was packed from. It does not prove the\n"
" bundle is clean — that is the installer's check at build time. The path scan below\n"
" is a second pair of eyes, not a proof: searched " + ", ".join(e for _, e in needles())
+ f" for {BUILD_PATH_ROOT!r}, found none.")
def prove_extractable(zip_path: Path, app_name: str) -> None:
"""Unpack it and check the app still runs and still verifies.
Writing the archive by hand puts the permission bits and the byte-for-byte
content under this file's control, and both are things the signature and the
launch depend on. Neither is assumed.
Unpacked with ditto specifically, because that is what expands the zip
when someone double-clicks the download. `unzip` applies an entry's
permissions where ditto refuses them, so verifying with `unzip` reports a
launchable app for an archive that produces an unlaunchable one.
"""
with tempfile.TemporaryDirectory() as tmp:
run(["ditto", "-x", "-k", str(zip_path), tmp])
app = Path(tmp) / app_name
if not os.access(app / EXEC_SUBPATH, os.X_OK):
raise SystemExit(f"{app_name} unpacks without an executable bit — it would not launch")
run(["codesign", "--verify", "--deep", "--strict", str(app)])
refuse_team_signature(app)
def refuse_team_signature(app: Path) -> None:
"""Refuse an archive whose signature names a development team.
Every build is ad-hoc, the local install included (`sign_adhoc` in
install-island-app.py), but a copy signed with a team, such as an install
made before 2.4, can still sit in /Applications.
A team signature may never leave the machine. A Team ID is registered to a named
person, so a released binary carrying one links a pseudonymous repository
to whoever pays for the developer account, and `codesign -dv` reads it out
of the download in one command.
The build path does not sign with a team (the project sets
`CODE_SIGNING_ALLOWED = NO`, and `sign_adhoc` is the only signing step),
but that is a habit, not a guard: pointing this script at an older
team-signed copy would package the team signature with everything else and
report success.
"""
out = subprocess.run(["codesign", "-dv", str(app)],
capture_output=True, text=True).stderr
for line in out.splitlines():
key, _, value = line.partition("=")
if key.strip() != "TeamIdentifier":
continue
if value.strip() and value.strip() != "not set":
raise SystemExit(
f"{app.name} is signed by a development team, which names a real person.\n"
"A release build must be ad-hoc signed. Build without Config.xcconfig, "
"or point this script at a build that was.")
return
raise SystemExit("codesign said nothing about a TeamIdentifier — this check read nothing "
"and its silence proves nothing.")
def main() -> None:
parser = argparse.ArgumentParser(description="Package a built Perch.app for release, and audit the result.")
parser.add_argument("app", type=Path, help="Path to the built Perch.app")
parser.add_argument("-o", "--out", type=Path, help="Output zip (default: ./<AppName>.zip beside this script)")
opts = parser.parse_args()
app = opts.app.resolve()
if app.suffix != ".app" or not app.is_dir():
raise SystemExit(f"{app} is not an .app bundle")
out = (opts.out or Path.cwd() / f"{app.stem}.zip").resolve()
want = manifest(app)
pack(app, out, want)
audit(out, want)
prove_extractable(out, app.name)
print(f"\n{out} ({out.stat().st_size // 1024} KB)")
print("Upload this file and nothing else: no .dSYM, no .swiftmodule, no build directory.")
if __name__ == "__main__":
main()
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.