Package a self-contained macOS app and harden serving

- Add macos/build.mjs: stages a universal .app outside the checkout, bundles
  and checksums Node, installs production deps per architecture, compiles the
  launcher shim, signs ad-hoc or with a Developer ID, and writes a zip and dmg
  with an optional notarization path.
- Serve precompressed brotli/gzip assets and split admin panels and the public
  pages out of the main bundle.
- Support HTTP range requests, and fix upload and quota accounting, gallery
  download counts and unreadable-file handling.
- Add server HTTP integration tests, a Gitea CI workflow, a catalog backup
  script and a crash screen for the UI.
This commit is contained in:
2026-11-29 06:23:58 +00:00
parent d42727618e
commit b34d34dacb
24 changed files with 2598 additions and 93 deletions
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>Luminary</string>
<key>CFBundleDisplayName</key>
<string>Luminary</string>
<key>CFBundleIdentifier</key>
<string>__BUNDLE_ID__</string>
<key>CFBundleVersion</key>
<string>__VERSION__</string>
<key>CFBundleShortVersionString</key>
<string>__VERSION__</string>
<key>CFBundleExecutable</key>
<string>Luminary</string>
<key>CFBundleIconFile</key>
<string>Luminary</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>LSMinimumSystemVersion</key>
<string>__MIN_OS__</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.photography</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>MIT licensed. Copyright 2026 Brian Hursey.</string>
</dict>
</plist>
+63
View File
@@ -0,0 +1,63 @@
Luminary for macOS
==================
Install
1. Open the disk image (or unzip the archive).
2. Drag Luminary to the Applications folder.
3. Eject the disk image, then open Luminary from Applications.
First launch (unsigned build)
This build is not notarized by Apple, so macOS will say it cannot verify the
app. That is expected: it means nobody paid Apple's yearly fee, not that
anything is wrong with the file.
1. Double-click Luminary and dismiss the warning with Done.
2. Open System Settings > Privacy & Security.
3. Scroll to Security and click Open Anyway, then authenticate.
macOS remembers the choice, so this is a one-time step. The Open Anyway
button only appears for about an hour after the blocked attempt; if it is
missing, double-click the app again and go back.
What it needs
- macOS 11 Big Sur or newer (the build records its own minimum in
Info.plist; 11.0 for the Node 22 build, 13.5 for the Node 24 build).
- A browser with WebAssembly and WebGL2. Chrome or Edge is used for the app
window when installed; otherwise the default browser opens a normal tab.
- Nothing else. Node.js is inside the app, so no Homebrew, no npm install
and no administrator password are needed for day-to-day use.
Start, stop and status
Opening Luminary starts the local server and opens the editor. Opening it
again reuses the running copy instead of starting a second one.
- Stop Luminary.command (next to the app in the disk image) stops the server.
- The same commands are available from a terminal:
/Applications/Luminary.app/Contents/Resources/launcher.sh --status
/Applications/Luminary.app/Contents/Resources/launcher.sh --stop
(or run the app with --args --status: open -a Luminary --args --status)
Where your photos live
~/Library/Application Support/Luminary/data
That folder holds the SQLite catalog, the originals, previews and thumbnails.
Set LUMINARY_DATA before launching to keep it somewhere else, such as an
external drive. Back it up by copying the whole folder while Luminary is
stopped, including lumenroom.db, lumenroom.db-wal and lumenroom.db-shm.
Logs
~/Library/Application Support/Luminary/data/logs/server.out.log
~/Library/Application Support/Luminary/data/logs/server.err.log
Updating
Quit the server (Stop Luminary.command), drag the new Luminary.app over the
old one, and start it again. The data folder is outside the app and is not
touched. The catalog migrates itself on first start.
Notes
- The server listens on 127.0.0.1 only. For proofing galleries that other
devices should reach, run the server yourself with HOST=0.0.0.0.
- The app window is Chrome or Edge in app mode, using its own profile in the
data folder, so it does not mix with your normal browsing. Set
LUMINARY_WINDOW=browser to open a normal tab instead.
- This build is single-user desktop mode: it signs in as a local admin
without a password and is not meant for several people sharing one Mac
account.
- The bundle is ad-hoc signed. If you rebuild it yourself with a Developer ID
certificate and notarize it, the first-launch step above disappears.
+186
View File
@@ -0,0 +1,186 @@
# macOS app (optional)
An additive, self-contained way to produce a double-clickable macOS app of
Luminary. The server and Docker workflow stay the source of truth: this folder
only *packages* the existing `dist/` + `server/` output, and the build writes
its artifacts **outside the checkout**.
## Isolation guarantees
1. **The packaging tree is additive.** There is no `package.json` script for
this, and no change to `Dockerfile`, `docker-compose.yml` or
`scripts/deploy.mjs`. Invoke it directly: `node macos/build.mjs`. The app
uses the same desktop mode the Windows launcher uses (`LUMINARY_LOCAL=1`),
which is off unless a launcher sets it.
2. **Artifacts live outside the repo** (default: `~/Library/Caches/luminary-macos`).
The script refuses an `--out` inside the checkout, because
`scripts/deploy.mjs` rsyncs the worktree to production and `docker build`
would pull the bundle into its context.
3. **The worktree must be clean outside `macos/`** before and after a build
(the untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
4. **Nothing in the app changes at run time.** The bundle is the unchanged
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
It must run on macOS: the build needs `clang`, `codesign`, `ditto`, `hdiutil`,
`sips` and `iconutil`. The Windows bundle is the one that cross-builds from
Linux.
## Quick start
On a fresh checkout run `npm ci` once: the UI build uses `vite` and `tsc` from
the dev dependencies, and the script copies the production dependencies into
the app itself.
```sh
node macos/build.mjs # host arch, Node 24, ad-hoc signature, zip + dmg
node macos/build.mjs --arch universal # arm64 + x86_64, both sharp slices
node macos/build.mjs --node v22.23.5 # minimum macOS 11.0 instead of 13.5
node macos/build.mjs --skip-build --sign none
```
Outputs:
```
~/Library/Caches/luminary-macos/
stage/Luminary.app
Luminary-0.5.1-mac-arm64.zip
Luminary-0.5.1-mac-arm64.dmg
cache/ # downloaded node tarballs, icon work
```
`--publish` copies the zip and dmg into `macos/releases/` with a
`SHA256SUMS.txt`, for transfer to a Mac. `.gitignore` keeps those archives out
of git.
## Bundle layout
```
Luminary.app/Contents/
Info.plist, PkgInfo
MacOS/Luminary native shim (main.c) -> execs the launcher
Resources/
launcher.sh start/stop/status/verify (bash)
Luminary.icns
version.txt, README-macos.txt
runtime/node official Node for the built architecture
app/
server/ unchanged, minus data/ and *.test.*
dist/ unchanged, including .br/.gz variants
node_modules/ production deps only (sharp for each slice)
package.json, LICENSE, THIRD_PARTY_NOTICES.md, licenses/
```
The main executable is a **Mach-O shim**, not a shell script. Apple treats
scripts in `Contents/MacOS` as resources, and the notary service rejects a
bundle whose main executable is not signed native code; the shim is a few lines
of C that execs `bash launcher.sh`, so the launcher stays editable without a
rebuild and the bundle can still be signed and notarized.
## Node and the minimum macOS version
| Node | Bundled runtime minimum | `LSMinimumSystemVersion` |
| --- | --- | --- |
| v22.18+ | macOS 11.0 | 11.0 |
| v24+ | macOS 13.5 | 13.5 |
Node 24's official macOS binaries are built against 13.5, so they cannot start
on Big Sur or Monterey; a macOS 11 build must bundle Node 22. Both lines run
this server: `node:sqlite` is unflagged from 22.13, type stripping (used by
`server/denoise-worker.mjs` importing a `.ts` pipeline) from 22.18, and the
HTTP integration suite passes under 22.23.5.
`--node-bin` uses a local binary instead of downloading one; the build warns if
`otool -L` shows libraries outside `/usr/lib` and `/System` (a Homebrew node
would drag Homebrew's ICU along and fail on a stock Mac).
## Signing and notarization
Three modes:
| `--sign` | What it does | Users see |
| --- | --- | --- |
| `adhoc` (default) | `codesign --sign -` on every Mach-O, then the bundle | “Apple could not verify …”, one-time Open Anyway |
| `none` | no signature | the same, and arm64 Macs may refuse to launch it |
| `developer-id` | signs each nested Mach-O with the Developer ID, hardened runtime and JIT entitlements on executables, then the bundle | no warning |
Notarization needs a paid Apple Developer Program membership:
```sh
xcrun notarytool store-credentials luminary \
--apple-id you@example.com --team-id TEAMID --password APP_SPECIFIC_PASSWORD
node macos/build.mjs --arch universal \
--sign developer-id --identity "Developer ID Application: Brian Hursey (TEAMID)" \
--notarize luminary --publish
```
The build submits the zip, staples the `.app`, rebuilds the zip, then creates the
dmg and submits and staples that too. `entitlements.plist` contains
`allow-jit`, `allow-unsigned-executable-memory` and `disable-library-validation`
— Node needs the first two under the hardened runtime, and sharp loads libvips
as a dylib, which library validation would otherwise reject.
Without the certificate everything still works; the first-launch instructions in
`README-macos.txt` cover the Gatekeeper step. macOS 15 and 26 removed the
Control-click → Open bypass, so that text names the System Settings path.
## Launcher behaviour
Same rules as the Windows launcher (`windows/launcher/DESIGN.md`):
- **No mutex.** `runtime.json` in the data folder records pid/port, and
`/api/health` is the liveness test: a healthy recorded port is reused, a stale
one is replaced.
- **Ports** 8787–8887, loopback only. The chosen port is passed as `PORT`.
- **Data** defaults to `~/Library/Application Support/Luminary/data`; an
existing `LUMINARY_DATA` wins. Logs go to `<data>/logs/`.
- **Window**: Chrome or Edge in `--app` mode with its own profile in the data
folder; `--browser` or `LUMINARY_WINDOW=browser` opens a normal tab; neither
installed falls back to the default browser.
- **Server lifetime**: detached, so closing the browser does not stop it and
reopening the app reuses it. `--stop` (and `Stop Luminary.command` next to the
app in the dmg) terminates it; `--status` prints pid, port, health and paths;
`--verify` checks the three files a complete bundle needs.
## Test checklist (on the Tahoe machine)
1. `node macos/build.mjs --arch universal --dmg` → zip and dmg exist; summary
prints arch, Node version, target and hashes.
2. `codesign --verify --deep --strict --verbose=2 stage/Luminary.app` → valid.
3. Copy the app out of the dmg, open it → browser/app window opens on the
editor, no sign-in screen (desktop mode).
4. Launch again while it runs → same port is reused, no second node process;
`pgrep -fl 'Resources/runtime/node'` shows one.
5. `--stop` → process gone, `runtime.json` removed; `--stop` again says
"not running".
6. Occupy 8787 with another listener → the app starts on 8788 and opens that
URL.
7. Import a raw, apply a film look, export → proves libraw WASM, sharp (dylibs
load under the signature) and the export path.
8. Denoise a photo → proves the `.ts` worker under the bundled Node.
9. Quit the browser, reopen the app → the same catalog opens; the data folder
holds the SQLite files.
10. `--verify` with a renamed `runtime/node` → exit 3 and a dialog, not a silent
failure.
11. Path with spaces / non-ASCII in `LUMINARY_DATA` → starts and writes there.
12. Gatekeeper: download the zip through a browser (quarantine flag), then
follow README-macos.txt → one-time Open Anyway, then normal launches.
13. On an Intel Mac: the same bundle runs (universal, both sharp slices).
14. Optional: notarized build → double-click installs with no warning,
`spctl -a -vv -t exec Luminary.app` says `accepted`.
## Known limits
- **No Dock menu.** The launcher exits once the browser opens; stopping is
`--stop` / `Stop Luminary.command`, not a Quit menu item.
- **Ad-hoc signing is per-bundle.** Copying the app with an archiver that drops
extended attributes can make macOS call it damaged; the zip is made with
`ditto` for that reason.
- **Universal builds install sharp twice** (one `npm ci` per architecture) and
copy the second slice's `@img` packages across; this is tested for layout, not
for runtime, until both architectures are exercised.
- **Icon quality depends on the source.** `public/logo.png` is 147×160, so the
generated `.icns` is soft; pass `--icon` with a 1024×1024 PNG for a release.
- **No auto-update, no file associations, no login item.** Same phase-2 list as
Windows.
+854
View File
@@ -0,0 +1,854 @@
#!/usr/bin/env node
/**
* Build the optional self-contained macOS app for Luminary.
*
* Like windows/build.mjs this is deliberately additive: it only reads the
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
* the Dockerfile or the deploy script is modified, and no npm script is added.
* Run it directly, on macOS:
*
* node macos/build.mjs # host arch, Node 24, ad-hoc signed
* node macos/build.mjs --arch universal --dmg
* node macos/build.mjs --node v22.23.5 # minimum macOS 11.0
* node macos/build.mjs --skip-build --sign none
*
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
* the parent of `server/`), with a native shim as the app's main executable:
*
* Luminary.app/Contents/
* Info.plist, PkgInfo
* MacOS/Luminary native shim that execs the launcher script
* Resources/
* launcher.sh start/stop/status/verify logic (bash)
* Luminary.icns
* version.txt, README-macos.txt
* runtime/node official Node for this architecture
* app/ unchanged server/, dist/, production deps
*/
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
chmodSync,
cpSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const LAUNCHER_DIR = path.join(HERE, 'launcher');
const RELEASES_DIR = path.join(HERE, 'releases');
const DEFAULT_NODE = 'v24.22.2';
const DEFAULT_BUNDLE_ID = 'net.maple-street.luminary';
const INFO_PLIST = path.join(HERE, 'Info.plist');
const ENTITLEMENTS = path.join(HERE, 'entitlements.plist');
const HELP = `Luminary macOS app
Usage: node macos/build.mjs [options]
--out <dir> output directory (default: ~/Library/Caches/luminary-macos).
Must be outside this repository; the app is staged in
<out>/stage/Luminary.app and archived next to it.
--skip-build reuse the existing dist/ instead of running npm run build
--node <version> bundled Node version (default ${DEFAULT_NODE}).
v22.18+ gives a macOS 11.0 bundle; v24+ needs macOS 13.5.
--node-bin <path> bundle this node binary instead of downloading one
--arch <arch> host (default), arm64, x64 or universal
--target <ver> minimum macOS version (default: derived from Node;
e.g. 11.0 for Node 22, 13.5 for Node 24)
--sign <kind> adhoc (default), developer-id or none
--identity <name> Developer ID Application identity for --sign developer-id
--notarize <name> notarytool keychain profile; implies --sign developer-id
--dmg also write a disk image (default)
--no-dmg skip the disk image
--icon <png> icon source (default: macos/icon-1024.png)
--bundle-id <id> CFBundleIdentifier (default ${DEFAULT_BUNDLE_ID})
--allow-dirty skip the check that the checkout is clean outside macos/
--publish copy the finished zip and dmg to macos/releases
--help print this text
Requires macOS with the Xcode command line tools (clang, codesign, ditto,
hdiutil, sips, iconutil). Nothing is written into the repository except with
--publish.
`;
function fail(message) {
process.stderr.write(`macos: FAILED: ${message}\n`);
process.exit(1);
}
function log(step, message) {
process.stdout.write(`macos: ${step.padEnd(9)} ${message}\n`);
}
function warn(message) {
process.stderr.write(`macos: warning: ${message}\n`);
}
function capture(command, args, cwd) {
return spawnSync(command, args, { cwd, encoding: 'utf8' });
}
function run(command, args, cwd, extraEnv) {
log('run', [command, ...args].join(' '));
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
});
if (result.error) fail(`${command} could not start: ${result.error.message}`);
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
return result;
}
function defaultOutDir() {
return path.join(os.homedir(), 'Library', 'Caches', 'luminary-macos');
}
function parseArgs(argv) {
const options = {
out: defaultOutDir(),
node: DEFAULT_NODE,
nodeBin: '',
arch: 'host',
target: '',
sign: 'adhoc',
identity: '',
notarize: '',
dmg: true,
build: true,
icon: path.join(HERE, 'icon-1024.png'),
bundleId: DEFAULT_BUNDLE_ID,
allowDirty: false,
publish: false,
help: false,
};
const value = (index, flag) => {
const next = argv[index + 1];
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
return next;
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out') {
options.out = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--node') {
const version = value(i, arg);
options.node = version.startsWith('v') ? version : `v${version}`;
i += 1;
} else if (arg === '--node-bin') {
options.nodeBin = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--arch') {
options.arch = value(i, arg);
i += 1;
} else if (arg === '--target') {
options.target = value(i, arg);
i += 1;
} else if (arg === '--sign') {
options.sign = value(i, arg);
i += 1;
} else if (arg === '--identity') {
options.identity = value(i, arg);
i += 1;
} else if (arg === '--notarize') {
options.notarize = value(i, arg);
i += 1;
} else if (arg === '--icon') {
options.icon = path.resolve(value(i, arg));
i += 1;
} else if (arg === '--bundle-id') {
options.bundleId = value(i, arg);
i += 1;
} else if (arg === '--skip-build') {
options.build = false;
} else if (arg === '--dmg') {
options.dmg = true;
} else if (arg === '--no-dmg') {
options.dmg = false;
} else if (arg === '--allow-dirty') {
options.allowDirty = true;
} else if (arg === '--publish') {
options.publish = true;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
fail(`unknown option ${arg} (see --help)`);
}
}
if (!['host', 'arm64', 'x64', 'universal'].includes(options.arch)) {
fail(`--arch must be host, arm64, x64 or universal (got ${options.arch})`);
}
if (!['adhoc', 'developer-id', 'none'].includes(options.sign)) {
fail(`--sign must be adhoc, developer-id or none (got ${options.sign})`);
}
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
fail(`--node must look like v24.22.2 (got ${options.node})`);
}
if (options.notarize) options.sign = 'developer-id';
if (options.sign === 'developer-id' && !options.identity) {
fail('--sign developer-id needs --identity "Developer ID Application: ..."');
}
if (options.nodeBin && !existsSync(options.nodeBin)) {
fail(`--node-bin not found: ${options.nodeBin}`);
}
return options;
}
/**
* The staged app and its runtime must not land in the checkout: scripts/deploy
* rsyncs the worktree to production and docker build would pull it into the
* context.
*/
function assertOutsideRepo(outDir) {
const relative = path.relative(ROOT, outDir);
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
if (inside) {
fail(
`--out resolves inside the repository (${outDir}).\n` +
'Pick a directory outside the checkout, or omit --out to use the cache.',
);
}
}
function git(args, { trim = true } = {}) {
const result = capture('git', args, ROOT);
if (result.error || result.status !== 0) return null;
return trim ? result.stdout.trim() : result.stdout;
}
/** Only this folder and the long-standing untracked logo may be dirty. */
function checkRepoClean(options) {
const status = git(['status', '--porcelain'], { trim: false });
if (status === null) {
warn('git is unavailable here; skipping the worktree check');
return;
}
const unexpected = status
.split('\n')
.filter((line) => line.length > 3)
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
.filter((file) => file && !file.startsWith('macos/') && file !== 'logo.png');
if (!unexpected.length) return;
if (options.allowDirty) {
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
return;
}
fail(
`the checkout has changes outside macos/:\n ${unexpected.join('\n ')}\n` +
'Commit or stash them, or pass --allow-dirty to build anyway.',
);
}
function readPackage() {
const file = path.join(ROOT, 'package.json');
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
return JSON.parse(readFileSync(file, 'utf8'));
}
function sha256File(file) {
return createHash('sha256').update(readFileSync(file)).digest('hex');
}
async function download(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
return Buffer.from(await response.arrayBuffer());
}
function fileType(file) {
const result = capture('file', ['-b', file]);
return result.status === 0 ? result.stdout.trim() : '';
}
function nodeMajor(version) {
return Number(version.slice(1).split('.')[0]);
}
function minimumOS(version) {
const major = nodeMajor(version);
if (major === 22) return '11.0';
if (major >= 24) return '13.5';
return '11.0';
}
function resolveArchs(requested) {
if (requested === 'universal') return ['arm64', 'x64'];
if (requested === 'host') return [process.arch === 'arm64' ? 'arm64' : 'x64'];
return [requested];
}
function clangArch(arch) {
return arch === 'x64' ? 'x86_64' : 'arm64';
}
function ensureUi(options) {
const dist = path.join(ROOT, 'dist', 'index.html');
if (options.build) {
log('ui', 'npm run build (typecheck + vite build + compressed variants)');
run('npm', ['run', 'build'], ROOT);
} else {
log('ui', 'reusing the existing dist/ (--skip-build)');
}
if (!existsSync(dist)) fail('dist/index.html is missing; drop --skip-build or run "npm run build"');
}
function copyServer(appDir) {
cpSync(path.join(ROOT, 'server'), path.join(appDir, 'server'), {
recursive: true,
filter: (source) => {
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
if (relative === 'data' || relative.startsWith('data/')) return false;
if (/\.test\.(mjs|ts)$/.test(relative)) return false;
return true;
},
});
}
function copyLegal(appDir) {
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
const source = path.join(ROOT, name);
if (existsSync(source)) cpSync(source, path.join(appDir, name));
}
const licenses = path.join(ROOT, 'licenses');
if (existsSync(licenses)) cpSync(licenses, path.join(appDir, 'licenses'), { recursive: true });
}
function installDeps(appDir, archs, outDir) {
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
log('deps', `npm ci --omit=dev --os=darwin --cpu=${archs[0]} (sharp darwin-${archs[0]})`);
// sharp resolves its prebuilt binary through optionalDependencies, so npm can
// fetch the target architecture's package from any host.
run(
'npm',
['ci', '--omit=dev', '--os=darwin', `--cpu=${archs[0]}`, '--ignore-scripts', '--no-audit', '--no-fund'],
appDir,
);
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
// A universal app needs both sharp slices; npm's --cpu selects one at a time,
// so install the second architecture separately and copy its packages across.
for (const arch of archs.slice(1)) {
const side = path.join(outDir, `deps-${arch}`);
rmSync(side, { recursive: true, force: true });
mkdirSync(side, { recursive: true });
cpSync(path.join(ROOT, 'package.json'), path.join(side, 'package.json'));
cpSync(path.join(ROOT, 'package-lock.json'), path.join(side, 'package-lock.json'));
run(
'npm',
['ci', '--omit=dev', '--os=darwin', `--cpu=${arch}`, '--ignore-scripts', '--no-audit', '--no-fund'],
side,
);
for (const pkg of [`@img/sharp-darwin-${arch}`, `@img/sharp-libvips-darwin-${arch}`]) {
const from = path.join(side, 'node_modules', pkg);
if (!existsSync(from)) fail(`${pkg} was not installed for the ${arch} slice`);
rmSync(path.join(appDir, 'node_modules', pkg), { recursive: true, force: true });
cpSync(from, path.join(appDir, 'node_modules', pkg), { recursive: true });
log('deps', `added ${pkg}`);
}
rmSync(side, { recursive: true, force: true });
}
verifySharp(appDir, archs);
}
function verifySharp(appDir, archs) {
for (const arch of archs) {
const dir = path.join(appDir, 'node_modules', '@img', `sharp-darwin-${arch}`);
if (!existsSync(dir)) {
warn(`@img/sharp-darwin-${arch} is missing; the server will fall back to JPEG proxies`);
continue;
}
const binaries = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) walk(absolute);
else if (/\.(node|dylib)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
}
};
walk(dir);
const libvips = path.join(appDir, 'node_modules', '@img', `sharp-libvips-darwin-${arch}`);
log(
'deps',
binaries.some((file) => file.endsWith('.node'))
? `sharp darwin-${arch} ready (${binaries.length} native file(s)${existsSync(libvips) ? ', libvips included' : ''})`
: `sharp darwin-${arch} has no .node binary`,
);
}
}
async function ensureNode(options, outDir, archs) {
if (options.nodeBin) {
const kind = fileType(options.nodeBin);
if (!/Mach-O/.test(kind)) fail(`--node-bin is not a Mach-O binary (${kind || 'unknown'})`);
const binaryArch = /universal/.test(kind) ? 'universal' : /arm64/.test(kind) ? 'arm64' : 'x64';
if (binaryArch !== 'universal' && (archs.length > 1 || binaryArch !== archs[0])) {
fail(
`--node-bin is ${binaryArch} but --arch needs ${archs.join(' + ')}.\n` +
'Use the official nodejs.org tarball, or omit --node-bin to download both slices.',
);
}
log('node', `using ${options.nodeBin} (${binaryArch})`);
return { path: options.nodeBin, arch: binaryArch, version: options.node, hash: sha256File(options.nodeBin) };
}
const version = options.node;
const major = nodeMajor(version);
if (major === 23) fail('Node 23 is not an LTS line; use v22 (macOS 11) or v24 (macOS 13.5)');
if (major < 22) fail(`Node ${version} is too old: node:sqlite needs 22.13+ (type stripping 22.18+)`);
if (major === 22 && Number(version.split('.')[1]) < 18) {
fail(`${version} cannot strip types by default; server/denoise-worker.mjs needs v22.18+`);
}
const cache = path.join(outDir, 'cache', `node-${version}`);
mkdirSync(cache, { recursive: true });
const sumsFile = path.join(cache, 'SHASUMS256.txt');
if (!existsSync(sumsFile)) {
log('node', `downloading SHASUMS256.txt for ${version}`);
writeFileSync(sumsFile, await download(`https://nodejs.org/dist/${version}/SHASUMS256.txt`));
}
const sums = new Map(
readFileSync(sumsFile, 'utf8')
.split('\n')
.filter(Boolean)
.map((line) => {
const [hash, name] = line.trim().split(/\s+/);
return [name, hash];
}),
);
const binaries = [];
for (const arch of archs) {
const name = `node-${version}-darwin-${arch}.tar.gz`;
const tarball = path.join(cache, name);
if (!existsSync(tarball)) {
log('node', `downloading ${name}`);
try {
writeFileSync(tarball, await download(`https://nodejs.org/dist/${version}/${name}`));
} catch (error) {
fail(`could not download ${name}: ${error.message}`);
}
}
const hash = sha256File(tarball);
const expected = sums.get(name);
if (expected && expected !== hash) {
rmSync(tarball, { force: true });
fail(`${name} failed its SHA-256 check (${hash} != ${expected}); re-run to download again`);
}
if (!expected) warn(`${name} has no published checksum; using it unverified`);
const dir = path.join(cache, `node-${version}-darwin-${arch}`);
const binary = path.join(dir, 'bin', 'node');
if (!existsSync(binary)) {
mkdirSync(dir, { recursive: true });
run('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1']);
}
const kind = fileType(binary);
if (!/Mach-O/.test(kind)) fail(`extracted ${arch} node is not a Mach-O binary (${kind})`);
binaries.push(binary);
log('node', `${version} darwin-${arch} verified (sha256 ${hash.slice(0, 12)}…)`);
}
if (binaries.length === 1) {
return { path: binaries[0], arch: archs[0], version, hash: sha256File(binaries[0]) };
}
const universal = path.join(cache, `node-${version}-universal`);
rmSync(universal, { force: true });
run('lipo', ['-create', ...binaries, '-output', universal]);
const kind = fileType(universal);
if (!/universal binary/.test(kind)) fail(`lipo did not produce a universal binary (${kind})`);
chmodSync(universal, 0o755);
log('node', `${version} universal (arm64 + x86_64)`);
return { path: universal, arch: 'universal', version, hash: sha256File(universal) };
}
function checkNodePortability(binary) {
const result = capture('otool', ['-L', binary]);
if (result.status !== 0) return;
const foreign = result.stdout
.split('\n')
.slice(1)
.map((line) => line.trim().split(' ')[0])
.filter((lib) => lib && !lib.startsWith('/usr/lib/') && !lib.startsWith('/System/'));
if (foreign.length) {
warn(
`the bundled node links to libraries outside macOS: ${foreign.join(', ')}.\n` +
'Use the official nodejs.org tarball so the app runs on a Mac without Homebrew.',
);
}
}
function compileShim(app, archs, target) {
const found = capture('xcrun', ['--find', 'clang']);
const clang = found.status === 0 ? found.stdout.trim() : '';
if (!clang) {
fail(
'clang is missing. Install the Xcode command line tools:\n' +
' xcode-select --install\n' +
'and run the build again.',
);
}
const output = path.join(app, 'Contents', 'MacOS', 'Luminary');
const args = ['-O2', '-Wall', '-Wextra', `-mmacosx-version-min=${target}`];
for (const arch of archs) args.push('-arch', clangArch(arch));
args.push('-o', output, path.join(LAUNCHER_DIR, 'main.c'));
run(clang, args);
chmodSync(output, 0o755);
log('launcher', `native shim (${archs.join(' + ')}, macOS ${target}+)`);
}
function renderInfoPlist(app, { version, target, bundleId }) {
const text = readFileSync(INFO_PLIST, 'utf8')
.replaceAll('__VERSION__', version)
.replaceAll('__MIN_OS__', target)
.replaceAll('__BUNDLE_ID__', bundleId);
writeFileSync(path.join(app, 'Contents', 'Info.plist'), text);
writeFileSync(path.join(app, 'Contents', 'PkgInfo'), 'APPL????');
}
function buildIcon(app, source, outDir) {
if (!existsSync(source)) {
warn(`icon source not found: ${source}; the app will use the generic icon`);
return;
}
const sips = '/usr/bin/sips';
const iconutil = '/usr/bin/iconutil';
if (!existsSync(sips) || !existsSync(iconutil)) {
warn('sips/iconutil are missing; skipping the icon');
return;
}
const probe = capture(sips, ['-g', 'pixelWidth', '-g', 'pixelHeight', source]);
const width = Number((probe.stdout.match(/pixelWidth:\s*(\d+)/) ?? [])[1] ?? 0);
const height = Number((probe.stdout.match(/pixelHeight:\s*(\d+)/) ?? [])[1] ?? 0);
if (!width || !height) {
warn(`could not read the icon size of ${source}; skipping the icon`);
return;
}
const square = Math.max(width, height);
if (square < 512) {
warn(
`the icon source is ${width}x${height}; the .icns will look soft.\n` +
'Pass --icon with a 1024x1024 PNG for a crisp Dock icon.',
);
}
const work = path.join(outDir, 'cache', 'icon');
rmSync(work, { recursive: true, force: true });
mkdirSync(path.join(work, 'Luminary.iconset'), { recursive: true });
const padded = path.join(work, 'square.png');
if (width === height) {
cpSync(source, padded);
} else {
run(sips, ['-p', String(square), String(square), '--padColor', '0B0D10', source, '--out', padded]);
}
const iconset = path.join(work, 'Luminary.iconset');
for (const size of [16, 32, 128, 256, 512]) {
for (const scale of [1, 2]) {
const pixels = size * scale;
const name = scale === 1 ? `icon_${size}x${size}.png` : `icon_${size}x${size}@2x.png`;
run(sips, ['-z', String(pixels), String(pixels), padded, '--out', path.join(iconset, name)]);
}
}
run(iconutil, ['-c', 'icns', iconset, '-o', path.join(app, 'Contents', 'Resources', 'Luminary.icns')]);
log('icon', `Luminary.icns from ${path.relative(ROOT, source)} (${width}x${height})`);
}
function writeVersion(resources, info) {
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
const lines = [
`Luminary ${info.version}`,
`commit ${commit}`,
`built ${new Date().toISOString()}`,
`node ${info.nodeVersion} darwin-${info.nodeArch} sha256 ${info.nodeHash} size ${info.nodeSize}`,
`arch ${info.archs.join(' + ')}`,
`minimum macOS ${info.target}`,
'launcher native shim -> launcher.sh',
];
writeFileSync(path.join(resources, 'version.txt'), `${lines.join('\n')}\n`);
return commit;
}
function machOFiles(root) {
const found = [];
const walk = (current) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
walk(absolute);
continue;
}
if (!entry.isFile()) continue;
// `file` per file would be hundreds of subprocesses across node_modules;
// only native modules, dylibs and executables can be Mach-O here.
const stat = statSync(absolute);
const candidate =
/\.(node|dylib|so)$/i.test(entry.name) || (stat.mode & 0o111) !== 0;
if (candidate && /Mach-O/.test(fileType(absolute))) found.push(absolute);
}
};
walk(root);
return found;
}
function signApp(app, options) {
if (options.sign === 'none') {
warn(
'the app is unsigned: arm64 Macs refuse to launch it at all, and Intel\n' +
'Macs show the Gatekeeper warning. Ship adhoc or developer-id instead.',
);
return;
}
const nested = machOFiles(app).filter((file) => !file.endsWith('/Contents/MacOS/Luminary'));
for (const file of nested) {
if (options.sign === 'adhoc') {
run('codesign', ['--force', '--sign', '-', file]);
continue;
}
const kind = fileType(file);
const executable = /executable/.test(kind) && !/dylib|bundle/.test(kind);
const args = ['--force', '--timestamp', '--sign', options.identity];
if (executable) args.push('--options', 'runtime', '--entitlements', ENTITLEMENTS);
args.push(file);
run('codesign', args);
}
const finalArgs =
options.sign === 'adhoc'
? ['--force', '--sign', '-', app]
: [
'--force',
'--timestamp',
'--options',
'runtime',
'--entitlements',
ENTITLEMENTS,
'--sign',
options.identity,
app,
];
run('codesign', finalArgs);
const verify = capture('codesign', ['--verify', '--deep', '--strict', '--verbose=2', app]);
if (verify.status !== 0) fail(`codesign verification failed:\n${verify.stderr.trim()}`);
log('sign', options.sign === 'adhoc' ? 'ad-hoc signature verified' : `signed with ${options.identity}`);
}
function zipApp(app, zipPath) {
rmSync(zipPath, { force: true });
// ditto keeps symlinks, extended attributes and the code signature intact;
// `zip -r` corrupts bundles often enough to produce "app is damaged".
run('ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', app, zipPath]);
return statSync(zipPath).size;
}
function makeDmg(app, dmgPath, outDir) {
const root = path.join(outDir, 'dmg');
rmSync(root, { recursive: true, force: true });
mkdirSync(root, { recursive: true });
cpSync(app, path.join(root, 'Luminary.app'), { recursive: true, verbatimSymlinks: true });
symlinkSync('Applications', path.join(root, 'Applications'));
cpSync(path.join(HERE, 'README-macos.txt'), path.join(root, 'README-macos.txt'));
const stop = path.join(LAUNCHER_DIR, 'Stop Luminary.command');
if (existsSync(stop)) {
cpSync(stop, path.join(root, 'Stop Luminary.command'));
chmodSync(path.join(root, 'Stop Luminary.command'), 0o755);
}
rmSync(dmgPath, { force: true });
run('hdiutil', [
'create',
'-volname',
'Luminary',
'-srcfolder',
root,
'-ov',
'-format',
'UDZO',
dmgPath,
]);
rmSync(root, { recursive: true, force: true });
return statSync(dmgPath).size;
}
function notarize(artifact, profile) {
log('notarize', `submitting ${path.basename(artifact)}`);
run('xcrun', ['notarytool', 'submit', artifact, '--keychain-profile', profile, '--wait']);
}
function staple(artifact) {
run('xcrun', ['stapler', 'staple', artifact]);
run('xcrun', ['stapler', 'validate', artifact]);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(HELP);
return 0;
}
if (process.platform !== 'darwin') {
fail(
'the macOS app must be built on macOS: it needs clang, codesign, ditto and hdiutil.\n' +
'The Windows bundle is the one that cross-builds from Linux.',
);
}
assertOutsideRepo(options.out);
const pkg = readPackage();
const archs = resolveArchs(options.arch);
const target = options.target || minimumOS(options.node);
const [targetMajor, targetMinor = 0] = target.split('.').map(Number);
if (nodeMajor(options.node) >= 24 && (targetMajor < 13 || (targetMajor === 13 && targetMinor < 5))) {
fail(
`Node ${options.node} needs macOS 13.5 or newer, but --target is ${target}.\n` +
'Build with --node v22.23.5 for a macOS 11.0 bundle.',
);
}
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
log('out', options.out);
checkRepoClean(options);
ensureUi(options);
const stageRoot = path.join(options.out, 'stage');
const workRoot = path.join(options.out, 'stage.next');
const app = path.join(workRoot, 'Luminary.app');
const contents = path.join(app, 'Contents');
const resources = path.join(contents, 'Resources');
const appDir = path.join(resources, 'app');
rmSync(workRoot, { recursive: true, force: true });
for (const dir of [path.join(contents, 'MacOS'), resources, appDir, path.join(resources, 'runtime')]) {
mkdirSync(dir, { recursive: true });
}
log('stage', 'copying dist/ and server/ (the layout the server expects)');
cpSync(path.join(ROOT, 'dist'), path.join(appDir, 'dist'), { recursive: true });
copyServer(appDir);
copyLegal(appDir);
installDeps(appDir, archs, options.out);
const node = await ensureNode(options, options.out, archs);
checkNodePortability(node.path);
cpSync(node.path, path.join(resources, 'runtime', 'node'));
chmodSync(path.join(resources, 'runtime', 'node'), 0o755);
log('node', `bundled ${path.basename(node.path)} (${(statSync(node.path).size / 1024 / 1024).toFixed(1)} MB)`);
cpSync(path.join(LAUNCHER_DIR, 'launcher.sh'), path.join(resources, 'launcher.sh'));
chmodSync(path.join(resources, 'launcher.sh'), 0o755);
cpSync(path.join(HERE, 'README-macos.txt'), path.join(resources, 'README-macos.txt'));
renderInfoPlist(app, { version: pkg.version, target, bundleId: options.bundleId });
compileShim(app, archs, target);
buildIcon(app, options.icon, options.out);
const commit = writeVersion(resources, {
version: pkg.version,
nodeVersion: options.node,
nodeArch: node.arch,
nodeHash: node.hash,
nodeSize: statSync(node.path).size,
archs,
target,
});
signApp(app, options);
const label = archs.length > 1 ? 'universal' : archs[0];
const zipPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.zip`);
let zipBytes = zipApp(app, zipPath);
if (options.notarize) {
notarize(zipPath, options.notarize);
staple(app);
zipBytes = zipApp(app, zipPath);
} else {
const assessment = capture('spctl', ['-a', '-vv', '-t', 'exec', app]);
if (assessment.status !== 0) {
log('gatekeeper', 'not notarized: users must use Privacy & Security > Open Anyway');
}
}
let dmgPath = '';
let dmgBytes = 0;
if (options.dmg) {
dmgPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.dmg`);
dmgBytes = makeDmg(app, dmgPath, options.out);
if (options.notarize) {
notarize(dmgPath, options.notarize);
staple(dmgPath);
}
log('dmg', `${path.basename(dmgPath)} (${(dmgBytes / 1024 / 1024).toFixed(1)} MB)`);
}
// The isolation contract: nothing outside macos/ may have changed. Checked
// before --publish writes anything into the checkout.
if (!options.allowDirty) checkRepoClean(options);
rmSync(stageRoot, { recursive: true, force: true });
renameSync(workRoot, stageRoot);
let published = [];
if (options.publish) {
mkdirSync(RELEASES_DIR, { recursive: true });
const sums = [];
for (const artifact of [zipPath, ...(dmgPath ? [dmgPath] : [])]) {
const targetPath = path.join(RELEASES_DIR, path.basename(artifact));
cpSync(artifact, targetPath);
sums.push(`${sha256File(targetPath)} ${path.basename(targetPath)}`);
log('publish', path.relative(ROOT, targetPath));
}
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
published = sums;
}
process.stdout.write(
[
'',
'macos build PASSED',
` app ${path.join(stageRoot, 'Luminary.app')}`,
` zip ${zipPath}`,
` zip size ${(zipBytes / 1024 / 1024).toFixed(1)} MB`,
` zip sha256 ${sha256File(zipPath)}`,
...(dmgPath
? [
` dmg ${dmgPath}`,
` dmg size ${(dmgBytes / 1024 / 1024).toFixed(1)} MB`,
` dmg sha256 ${sha256File(dmgPath)}`,
]
: []),
` arch ${label}`,
` node ${options.node} darwin-${node.arch}`,
` target macOS ${target}+`,
` signature ${options.sign}${options.identity ? ` (${options.identity})` : ''}`,
` commit ${commit}`,
...(published.length ? ['', ...published.map((line) => ` publish ${line}`)] : []),
'',
options.notarize
? 'Notarized and stapled: users can open it with a normal double-click.'
: 'Not notarized: first launch needs Privacy & Security > Open Anyway (see README-macos.txt).',
'',
].join('\n'),
);
return 0;
}
main().then(
(code) => {
process.exitCode = code;
},
(error) => {
fail(error instanceof Error ? error.message : String(error));
},
);
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- V8 compiles JavaScript at run time; the hardened runtime blocks that
unless the process opts in. Node's own documentation names these two. -->
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<!-- sharp loads libvips as a dylib from its own package directory; library
validation would otherwise reject it when the signatures differ. -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

+35
View File
@@ -0,0 +1,35 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="tile" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#141b25"/>
<stop offset="1" stop-color="#07090c"/>
</linearGradient>
<radialGradient id="glow" cx="50%" cy="36%" r="64%">
<stop offset="0" stop-color="#2f6cb5" stop-opacity="0.5"/>
<stop offset="0.65" stop-color="#123055" stop-opacity="0.16"/>
<stop offset="1" stop-color="#0b0d10" stop-opacity="0"/>
</radialGradient>
<linearGradient id="bar" x1="0" y1="0" x2="0.35" y2="1">
<stop offset="0" stop-color="#a6d2ff"/>
<stop offset="0.18" stop-color="#6cb0fb"/>
<stop offset="0.38" stop-color="#3d8df0"/>
<stop offset="0.58" stop-color="#14509f"/>
<stop offset="0.78" stop-color="#0a3272"/>
<stop offset="1" stop-color="#021f4c"/>
</linearGradient>
<clipPath id="tileClip">
<rect x="100" y="100" width="824" height="824" rx="185"/>
</clipPath>
</defs>
<g clip-path="url(#tileClip)">
<rect x="100" y="100" width="824" height="824" fill="url(#tile)"/>
<rect x="100" y="100" width="824" height="824" fill="url(#glow)"/>
</g>
<rect x="100.5" y="100.5" width="823" height="823" rx="184.5" fill="none" stroke="#ffffff" stroke-opacity="0.10" stroke-width="1"/>
<g transform="translate(206 178) scale(4.2)">
<path d="M 0 127 Q 0 134 7 134 L 26 134 Q 33 134 33 127 L 33 112.5 A 16.5 16.5 0 0 0 0 112.5 Z" fill="url(#bar)"/>
<path d="M 37 127 Q 37 134 44 134 L 62 134 Q 69 134 69 127 L 69 79 A 16 16 0 0 0 37 79 Z" fill="url(#bar)"/>
<path d="M 74 126.5 Q 74 133.5 81 133.5 L 99 133.5 Q 106 133.5 106 126.5 L 106 41 A 16 16 0 0 0 74 41 Z" fill="url(#bar)"/>
<path d="M 110 126 Q 110 133 117 133 L 134 133 Q 141 133 141 126 L 141 93.5 A 15.5 15.5 0 0 0 110 93.5 Z" fill="url(#bar)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# Stop the Luminary server started by Luminary.app.
# Double-clicking a .command file opens Terminal for as long as this runs.
set -u
APP="/Applications/Luminary.app"
if [ ! -d "$APP" ]; then
APP="$(cd "$(dirname "$0")" && pwd)/Luminary.app"
fi
if [ ! -d "$APP" ]; then
echo "Luminary.app was not found in /Applications. Move it there and try again."
read -r -p "Press Return to close this window." _
exit 1
fi
"$APP/Contents/Resources/launcher.sh" --stop
read -r -p "Press Return to close this window." _
+248
View File
@@ -0,0 +1,248 @@
#!/bin/bash
# Luminary.app launcher.
#
# Called by the native shim in Contents/MacOS/Luminary. Keeps the same rules as
# the Windows launcher: pick a loopback port, start the bundled node exactly like
# `node server/index.mjs`, wait for /api/health, then open the browser. The
# server is detached and keeps running after the app exits, so launching again
# reuses it instead of starting a second copy.
#
# launcher.sh start (or reuse) and open the window
# launcher.sh --stop stop the server recorded in runtime.json
# launcher.sh --status print pid, port, health and data directory
# launcher.sh --verify check that this is a complete bundle (exit 3 if not)
# launcher.sh --browser open a normal browser tab instead of an app window
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
APP="$HERE/app"
NODE="$HERE/runtime/node"
DATA="${LUMINARY_DATA:-$HOME/Library/Application Support/Luminary/data}"
STATE="$DATA/runtime.json"
LOGS="$DATA/logs"
WINDOW="${LUMINARY_WINDOW:-app}"
say() { printf 'Luminary: %s\n' "$*"; }
err() { printf 'Luminary: %s\n' "$*" >&2; }
die() { err "$*"; exit 1; }
# A blocking dialog for launches from Finder, where stderr goes nowhere.
dialog() {
local message
message=$(printf '%s' "$1" | tr '"' "'" | tr '\n' ' ')
if command -v osascript >/dev/null 2>&1; then
osascript -e "display dialog \"$message\" with title \"Luminary\" buttons {\"OK\"} default button 1 with icon caution" >/dev/null 2>&1 || true
fi
}
version_line() {
if [ -f "$HERE/version.txt" ]; then head -1 "$HERE/version.txt"; else echo "Luminary (version unknown)"; fi
}
state_port() {
[ -f "$STATE" ] || return 0
sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1
}
state_pid() {
[ -f "$STATE" ] || return 0
sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1
}
healthy() {
curl -fs -m 2 "http://127.0.0.1:$1/api/health" >/dev/null 2>&1
}
# Ask node rather than nc: the bundle always has one, and nc's flags differ
# between the BSD tool macOS ships and builds found elsewhere.
port_in_use() {
"$NODE" -e 'const net=require("net");const s=net.connect(+process.argv[1],"127.0.0.1");s.on("connect",()=>{s.destroy();process.exit(0)});s.on("error",()=>process.exit(1))' "$1" >/dev/null 2>&1
}
tail_logs() {
[ -f "$LOGS/server.err.log" ] || return 0
err "last lines from $LOGS/server.err.log:"
tail -n 20 "$LOGS/server.err.log" >&2 || true
}
open_window() {
local url="$1"
if [ "$WINDOW" = "browser" ]; then
open "$url"
return
fi
if [ -d "/Applications/Google Chrome.app" ] || [ -d "$HOME/Applications/Google Chrome.app" ]; then
open -na "Google Chrome" --args \
--app="$url" \
--user-data-dir="$DATA/window-profile-chrome" \
--window-size=1500,950 --no-first-run --no-default-browser-check
elif [ -d "/Applications/Microsoft Edge.app" ] || [ -d "$HOME/Applications/Microsoft Edge.app" ]; then
open -na "Microsoft Edge" --args \
--app="$url" \
--user-data-dir="$DATA/window-profile-edge" \
--window-size=1500,950 --no-first-run --no-default-browser-check
else
open "$url"
fi
}
verify() {
local status=0 file size
for file in "$NODE" "$APP/server/index.mjs" "$APP/dist/index.html"; do
if [ ! -f "$file" ]; then
err "missing: ${file#"$HERE"/}"
status=3
elif [ ! -s "$file" ]; then
err "empty: ${file#"$HERE"/}"
status=3
else
size=$(wc -c <"$file" | tr -d ' ')
say "ok: ${file#"$HERE"/} ($size bytes)"
fi
done
say "bundle: $HERE"
say "version: $(version_line)"
return $status
}
start() {
[ -x "$NODE" ] || chmod +x "$NODE" 2>/dev/null || true
if [ -f "$STATE" ]; then
local existing
existing=$(state_port)
if [ -n "$existing" ] && healthy "$existing"; then
say "already running on port $existing"
open_window "http://127.0.0.1:$existing"
exit 0
fi
rm -f "$STATE"
fi
if ! verify >/dev/null 2>&1; then
verify >&2 || true
dialog "This copy of Luminary is incomplete. Copy Luminary.app out of the disk image or zip and try again. If it still fails, download the app again."
exit 3
fi
mkdir -p "$DATA" "$LOGS" 2>/dev/null || {
dialog "Luminary cannot write to $DATA. Set LUMINARY_DATA to a folder you can write to and try again."
exit 1
}
local port=""
local candidate
# Brace expansion instead of seq: macOS does not ship seq.
for candidate in {8787..8887}; do
if ! port_in_use "$candidate"; then
port="$candidate"
break
fi
done
[ -n "$port" ] || { dialog "No free port between 8787 and 8887. Quit the app using one and try again."; exit 1; }
LUMINARY_DATA="$DATA" \
LUMINARY_LOCAL=1 \
HOST=127.0.0.1 \
PORT="$port" \
NODE_ENV=production \
nohup "$NODE" --disable-warning=ExperimentalWarning "$APP/server/index.mjs" \
>>"$LOGS/server.out.log" 2>>"$LOGS/server.err.log" &
local pid=$!
printf '{\n "pid": %s,\n "port": %s,\n "url": "http://127.0.0.1:%s",\n "data": "%s",\n "started": "%s"\n}\n' \
"$pid" "$port" "$port" "$DATA" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$STATE"
local waited=0
while [ "$waited" -lt 240 ]; do
if healthy "$port"; then
open_window "http://127.0.0.1:$port"
exit 0
fi
if ! kill -0 "$pid" 2>/dev/null; then
rm -f "$STATE"
tail_logs
dialog "Luminary's server stopped while starting. Log: $LOGS/server.err.log"
exit 1
fi
sleep 0.5
waited=$((waited + 1))
done
kill "$pid" 2>/dev/null || true
rm -f "$STATE"
tail_logs
dialog "Luminary did not start within 120 seconds. Log: $LOGS/server.err.log"
exit 1
}
stop() {
if [ ! -f "$STATE" ]; then
say "not running"
return 0
fi
local pid
pid=$(state_pid)
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
kill -TERM "$pid" 2>/dev/null || true
local tick
for tick in {1..20}; do
kill -0 "$pid" 2>/dev/null || break
sleep 0.25
done
kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true
say "stopped (pid $pid)"
else
say "not running (removed a stale runtime.json)"
fi
rm -f "$STATE"
}
status() {
local port pid
port=$(state_port)
pid=$(state_pid)
say "version: $(version_line)"
say "bundle: $HERE"
say "data: $DATA"
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
say "pid: $pid"
elif [ -n "$pid" ]; then
say "pid: $pid (not running)"
else
say "pid: -"
fi
if [ -n "$port" ] && healthy "$port"; then
say "health: ok on http://127.0.0.1:$port"
elif [ -n "$port" ]; then
say "health: no response on port $port"
else
say "health: not started"
fi
}
case "${1:-}" in
--stop) stop ;;
--status) status ;;
--verify) verify; exit $? ;;
--browser) WINDOW=browser; start ;;
--help | -h)
cat <<'USAGE'
Luminary.app launcher
No argument starts the app (or reuses a running copy) and opens the window.
--browser open a normal browser tab instead of a Chrome/Edge app window
--stop stop the server this bundle started
--status print version, pid, port, health and the data directory
--verify check that the bundle is complete
Data: ~/Library/Application Support/Luminary/data (override with LUMINARY_DATA)
Logs: <data>/logs/server.out.log and server.err.log
USAGE
;;
"") start ;;
*)
err "unknown argument: $1 (try --help)"
exit 2
;;
esac
+73
View File
@@ -0,0 +1,73 @@
/*
* Luminary.app main executable.
*
* The bundle needs a Mach-O main executable so it can be code signed and, if a
* certificate is ever bought, notarized: Apple's notary service rejects a
* bundle whose CFBundleExecutable is a shell script. This shim resolves its own
* path, finds Contents/Resources/launcher.sh next to it, and execs bash on it,
* passing every argument through. All the actual launcher logic lives in that
* script, where it can be changed without recompiling anything.
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
/** Write this process's executable path into buf, or return -1. */
static int executable_path(char *buf, size_t size) {
#ifdef __APPLE__
uint32_t needed = (uint32_t)size;
if (_NSGetExecutablePath(buf, &needed) != 0) return -1;
return 0;
#else
/* Not used in the bundle; kept so the shim can be built and tested when
* packaging is exercised from a non-Apple host. */
ssize_t length = readlink("/proc/self/exe", buf, size - 1);
if (length < 0) return -1;
buf[length] = '\0';
return 0;
#endif
}
int main(int argc, char **argv) {
char raw[PATH_MAX];
char exe[PATH_MAX];
char script[PATH_MAX];
if (executable_path(raw, sizeof raw) != 0) {
fprintf(stderr, "luminary: cannot resolve the application path\n");
return 1;
}
if (realpath(raw, exe) == NULL) {
fprintf(stderr, "luminary: cannot resolve %s\n", raw);
return 1;
}
/* exe is .../Luminary.app/Contents/MacOS/Luminary */
char *slash = strrchr(exe, '/');
if (slash == NULL) {
fprintf(stderr, "luminary: unexpected executable path %s\n", exe);
return 1;
}
*slash = '\0';
if (snprintf(script, sizeof script, "%s/../Resources/launcher.sh", exe) >= (int)sizeof script) {
fprintf(stderr, "luminary: application path is too long\n");
return 1;
}
char *args[argc + 2];
args[0] = "/bin/bash";
args[1] = script;
for (int i = 1; i < argc; i++) args[i + 1] = argv[i];
args[argc + 1] = NULL;
execv("/bin/bash", args);
perror("luminary: could not start the launcher");
return 1;
}