Add direct native-window launch and publish 0.5 beta
Forward a direct LuminaryWindow launch through the bundle launcher so it starts desktop mode instead of showing a signed-out page. Refresh the guide screenshots and version the release as 0.5.0 Beta.
@@ -14,3 +14,10 @@ server/data/
|
||||
.smoke/
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Windows native-window build output
|
||||
windows/launcher/webview2/bin/
|
||||
windows/launcher/webview2/obj/
|
||||
|
||||
# Transfer-only Windows release archives
|
||||
windows/releases/*.zip
|
||||
|
||||
@@ -156,7 +156,7 @@
|
||||
<div>
|
||||
<div class="rule"></div>
|
||||
<div class="foot">
|
||||
<span>VERSION 1.1 · NOVEMBER 2026</span>
|
||||
<span>VERSION 0.5 BETA · NOVEMBER 2026</span>
|
||||
<span>SCREENSHOTS FROM A LIVE CATALOG</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -216,7 +216,7 @@
|
||||
<ul>
|
||||
<li><b>Server:</b> <code>docker compose up -d</code>, then open <code>http://host:8787</code>.</li>
|
||||
<li><b>Source:</b> <code>npm ci</code> · <code>npm run build</code> · <code>npm start</code>.</li>
|
||||
<li><b>Windows:</b> unzip, double-click <code>Luminary</code>. No account needed.</li>
|
||||
<li><b>Windows:</b> unzip, double-click <code>Luminary.cmd</code> (or <code>Luminary.vbs</code>). No account needed.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="qs-box">
|
||||
@@ -379,7 +379,7 @@
|
||||
<thead><tr><th style="width:34%">Item</th><th>Purpose</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><code>Luminary.exe</code> or <code>Luminary.cmd</code></td><td>The launcher: starts the server hidden, waits for health, opens the window. <code>Luminary.vbs</code> does the same with no console window at all.</td></tr>
|
||||
<tr><td><code>LuminaryWindow.exe</code></td><td>The native window (WebView2). It is what the launcher opens when the runtime is available.</td></tr>
|
||||
<tr><td><code>LuminaryWindow.exe</code></td><td>The native window (WebView2). The launcher opens it; starting it directly also hands off to the launcher, so it opens in desktop mode.</td></tr>
|
||||
<tr><td><code>Luminary.ps1</code></td><td>The logic behind the launchers: preflight, port choice, health wait, repair, stop, status.</td></tr>
|
||||
<tr><td><code>node.exe</code></td><td>The bundled Node 24 runtime. Nothing is installed system-wide.</td></tr>
|
||||
<tr><td><code>app\</code></td><td><code>server\</code>, <code>dist\</code> and production <code>node_modules\</code> — the unchanged application.</td></tr>
|
||||
@@ -391,7 +391,7 @@
|
||||
<h2>Installing</h2>
|
||||
<ol class="steps">
|
||||
<li>Copy the folder (or the ZIP) to the PC — for example <code>D:\Apps\Luminary</code>.</li>
|
||||
<li>Double-click <code>Luminary</code>. Windows SmartScreen may warn because the build is unsigned: <b>More info → Run anyway</b>.</li>
|
||||
<li>Double-click <code>Luminary.cmd</code> (or <code>Luminary.vbs</code> for no console window; <code>Luminary.exe</code> in the Go build). Windows SmartScreen may warn because the build is unsigned: <b>More info → Run anyway</b>.</li>
|
||||
<li>The first launch creates <code>%LOCALAPPDATA%\Luminary\data</code>, starts the server on a free port and opens the window.</li>
|
||||
<li>Import a shoot. There is no sign-in screen: the app runs in single-user mode with one local administrator.</li>
|
||||
</ol>
|
||||
@@ -418,6 +418,10 @@
|
||||
<li><b>Read-only media</b> — logs and runtime state fall back to <code>%LOCALAPPDATA%</code> when the bundle folder cannot be written.</li>
|
||||
</ul>
|
||||
|
||||
<div class="note">
|
||||
<b>Starting the window directly.</b> Double-clicking <code>LuminaryWindow.exe</code> does not open a signed-out page. It hands off to the launcher, which starts the local server in desktop mode and reopens the window signed in. The launcher remains the recommended entry point — <code>Luminary.cmd</code> or <code>Luminary.vbs</code> (or <code>Luminary.exe</code> when the Go build is used).
|
||||
</div>
|
||||
|
||||
<div class="note">
|
||||
<b>Backing up the desktop app</b> is one folder: <code>%LOCALAPPDATA%\Luminary\data</code>. Copy it while the app is stopped. Restoring is copying it back; the database and originals travel together.
|
||||
</div>
|
||||
@@ -475,7 +479,7 @@
|
||||
|
||||
<figure>
|
||||
<img src="img/01-library.jpg" alt="The library with the catalog sidebar, filter bar and grid">
|
||||
<figcaption><b>Figure 2.</b> The library on a real 868-photo catalogue: events in the sidebar, the filter bar with counts, the grid with RAW badges and file metadata, and the sync state in the footer.</figcaption>
|
||||
<figcaption><b>Figure 2.</b> The library on a real portrait catalogue: events in the sidebar, the filter bar with counts, the grid with RAW badges and file metadata, and the sync state in the footer.</figcaption>
|
||||
</figure>
|
||||
|
||||
<h2>The sidebar</h2>
|
||||
@@ -512,8 +516,8 @@
|
||||
|
||||
<h2>Selecting and the batch bar</h2>
|
||||
<figure>
|
||||
<img src="img/13-selection.jpg" alt="Three photos selected with the batch toolbar">
|
||||
<figcaption><b>Figure 5.</b> A three-photo selection: stars, pick/reject, colour labels and the batch actions — Compare, Stack, Virtual copy, Merge, Reprocess RAW, Export, Print, Delete.</figcaption>
|
||||
<img src="img/13-selection.jpg" alt="Four photos selected with the batch toolbar">
|
||||
<figcaption><b>Figure 5.</b> A four-photo selection: stars, pick/reject, colour labels and the batch actions — Compare, Stack, Virtual copy, Merge, Reprocess RAW, Export, Print, Delete.</figcaption>
|
||||
</figure>
|
||||
<p>Click to select, <kbd>Shift</kbd>-click to extend, <kbd>⌘ / Ctrl</kbd>-click to toggle, drag on empty space for a rubber band. Everything in the batch bar applies to the whole selection in one action.</p>
|
||||
|
||||
@@ -1166,6 +1170,7 @@
|
||||
<tr><td>Storage quota errors</td><td>The browser storage is full. Delete rejected photos, or move the catalogue to the server.</td></tr>
|
||||
<tr><td>A photo looks different after reload</td><td>Edits are parameters; the preview is re-rendered from the original. If the original changed, the render changes with it.</td></tr>
|
||||
<tr><td>The desktop app opens no window</td><td>Run <code>Luminary.cmd -Status</code>; if the server is healthy but the window is missing, delete the WebView2 profile folder and relaunch, or use <code>-Browser</code>.</td></tr>
|
||||
<tr><td><code>LuminaryWindow.exe</code> opens a login page</td><td>Start <code>Luminary.cmd</code> or <code>Luminary.vbs</code> instead. Current builds hand off from a direct window launch to the launcher, so desktop mode is signed in.</td></tr>
|
||||
<tr><td><code>-Verify</code> fails</td><td><code>Luminary.cmd -Repair</code> re-downloads and hash-checks <code>node.exe</code>; other missing files mean the folder was copied incompletely.</td></tr>
|
||||
<tr><td>Sign-in throttled</td><td>Eight failures per account per 15 minutes. Wait, or check that the proxy forwards <code>X-Forwarded-For</code> with <code>LUMINARY_TRUST_PROXY=1</code>.</td></tr>
|
||||
</tbody>
|
||||
|
||||
|
Before Width: | Height: | Size: 528 KiB After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 793 KiB After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 639 KiB After Width: | Height: | Size: 365 KiB |
|
Before Width: | Height: | Size: 335 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 409 KiB After Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 735 KiB After Width: | Height: | Size: 501 KiB |
|
Before Width: | Height: | Size: 376 KiB After Width: | Height: | Size: 226 KiB |
|
Before Width: | Height: | Size: 436 KiB After Width: | Height: | Size: 198 KiB |
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "luminary",
|
||||
"version": "1.0.0",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "luminary",
|
||||
"version": "1.0.0",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"exifr": "^7.1.3",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "luminary",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"version": "1.0.0",
|
||||
"version": "0.5.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -126,7 +126,7 @@ import {
|
||||
startImmichImport,
|
||||
} from './immich.mjs';
|
||||
|
||||
const VERSION = '1.0.0';
|
||||
const VERSION = '0.5.0';
|
||||
const COOKIE = 'lumen_session';
|
||||
|
||||
/** Self-only policy; must allow the wasm engines and React inline styles. */
|
||||
|
||||
@@ -31,7 +31,7 @@ export default function AboutModal({ onClose }: Props) {
|
||||
<img src="/logo.png" alt="" height={28} />
|
||||
<div>
|
||||
<strong>Luminary</strong>
|
||||
<div className="muted small">Version {APP_VERSION}</div>
|
||||
<div className="muted small">Version {APP_VERSION} · Beta</div>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="cloud-stats about-facts">
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
* Versions shown in the About panel. APP_VERSION mirrors package.json; the
|
||||
* guide values are bumped when docs/user-guide/guide.html is republished.
|
||||
*/
|
||||
export const APP_VERSION = '1.0.0';
|
||||
export const GUIDE_VERSION = '1.1';
|
||||
export const APP_VERSION = '0.5.0';
|
||||
export const GUIDE_VERSION = '0.5';
|
||||
export const GUIDE_UPDATED = 'November 2026';
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Reproducible Windows bundle build on a Linux host.
|
||||
#
|
||||
# This image never touches the app's own Dockerfile or compose file; it exists
|
||||
# so the optional Windows artifact (including Luminary.exe, which needs Go) can
|
||||
# be produced from this machine:
|
||||
#
|
||||
# docker build -f windows/Dockerfile --output type=local,dest=/tmp/luminary-win .
|
||||
#
|
||||
# The output directory must be outside the checkout (see windows/README.md).
|
||||
# BuildKit is required for --output.
|
||||
#
|
||||
# `--output` exports the "artifacts" stage, which is `scratch`: only the bundle
|
||||
# zip, its checksum and the staged tree are copied out.
|
||||
|
||||
FROM node:24-bookworm AS build
|
||||
COPY --from=golang:1.23-bookworm /usr/local/go /usr/local/go
|
||||
ENV PATH="/usr/local/go/bin:${PATH}"
|
||||
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
|
||||
# Build-time dependencies for vite and tsc; the Windows runtime dependencies are
|
||||
# installed separately by build.mjs with --os=win32 --cpu=x64.
|
||||
RUN npm ci --no-audit --no-fund
|
||||
|
||||
# --allow-dirty: the build context has no .git, so the worktree check is skipped.
|
||||
# The Go toolchain makes build.mjs produce Luminary.exe instead of the .cmd/.vbs
|
||||
# pair; pass --launcher ps to force the PowerShell-only launcher.
|
||||
RUN node windows/build.mjs --out /out --allow-dirty
|
||||
|
||||
FROM scratch AS artifacts
|
||||
COPY --from=build /out/ /
|
||||
@@ -0,0 +1,11 @@
|
||||
# Context for windows/Dockerfile. The app's own Dockerfile keeps using the root
|
||||
# .dockerignore; this file only affects Windows bundle builds.
|
||||
.git
|
||||
node_modules
|
||||
dist
|
||||
.check
|
||||
.smoke
|
||||
server/data
|
||||
windows/out
|
||||
*.log
|
||||
logo.png
|
||||
@@ -0,0 +1,333 @@
|
||||
# Windows bundle (optional)
|
||||
|
||||
An additive, self-contained way to produce a double-clickable Windows install 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**.
|
||||
|
||||
- Design of the launcher: [launcher/DESIGN.md](launcher/DESIGN.md)
|
||||
- Moving this into its own repository: [SEPARATE-REPO.md](SEPARATE-REPO.md)
|
||||
|
||||
## Isolation guarantees
|
||||
|
||||
1. **The packaging tree is additive.** There is no `package.json` script for
|
||||
this, and no change to `.gitignore`, `.dockerignore`, `Dockerfile`,
|
||||
`docker-compose.yml` or `scripts/deploy.mjs`. Invoke it directly:
|
||||
`node windows/build.mjs`. The one app-side addition is an opt-in desktop mode
|
||||
in `server/config.mjs` + `server/index.mjs` (`LUMINARY_LOCAL=1`): a single
|
||||
passwordless local admin. It is off unless the Windows launcher sets it, so
|
||||
Docker and the shared server are unchanged.
|
||||
2. **Artifacts live outside the repo** (default: `~/.cache/luminary-windows`, or
|
||||
`%LOCALAPPDATA%\Luminary\build` on Windows). The script refuses an `--out`
|
||||
inside the checkout, because `scripts/deploy.mjs` rsyncs the worktree to
|
||||
production and `docker build` would pull a ~300 MB bundle into its context.
|
||||
3. **The worktree must be clean outside `windows/`** 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.
|
||||
|
||||
## What the end user needs
|
||||
|
||||
Nothing to install. This was audited from the shipped binaries' own PE imports,
|
||||
not assumed:
|
||||
|
||||
| Component | What it needs on the target PC |
|
||||
| --- | --- |
|
||||
| `node.exe` (v24.22.2) | only Windows system DLLs (`KERNEL32`, `ADVAPI32`, `WS2_32`, `CRYPT32`, `USER32`, …) — statically linked C runtime, so **no Visual C++ Redistributable** |
|
||||
| `libvips-42.dll` + `sharp` | the Universal C Runtime (`api-ms-win-crt-*`), included in Windows 10/11; older Windows needs KB2999226 |
|
||||
| `libraw.wasm` | a browser with WebAssembly |
|
||||
| launcher (`.cmd`/`.vbs`) | Windows PowerShell 5.1, included in Windows 10/11 |
|
||||
| Develop module | a current browser with WebGL2 (Edge, Chrome, Firefox) |
|
||||
|
||||
So: a clean Windows 10/11 x64 machine, a browser, and ~250 MB where the data
|
||||
folder lives. No VC++ redist, no .NET, no admin prompt, no installer.
|
||||
|
||||
What the launcher checks on every start (and `-Status` prints):
|
||||
|
||||
- Windows build ≥ 10240, `PROCESSOR_ARCHITECTURE` of `AMD64`/`ARM64`, UCRT
|
||||
present, and free space on the data drive. Windows older than 10 is refused
|
||||
with a specific message and link, exit code `4`.
|
||||
- Missing `node.exe` → offers to download it from nodejs.org and verifies the
|
||||
SHA-256 in `version.txt` before installing (same code as `-Repair`).
|
||||
- Missing `node.exe` but a system Node 24+ exists → starts on it, says which
|
||||
one, and points at `-Repair`.
|
||||
|
||||
Official links, shown in the dialogs when relevant:
|
||||
[Windows 10/11](https://www.microsoft.com/software-download/windows11) ·
|
||||
[Universal C Runtime / KB2999226](https://support.microsoft.com/help/2999226) ·
|
||||
[Microsoft Edge](https://www.microsoft.com/edge).
|
||||
|
||||
## Requirements (build host)
|
||||
|
||||
| Need | Why |
|
||||
| --- | --- |
|
||||
| Node.js 24 | the builder itself, and `npm run build` for `dist/` |
|
||||
| `npm` with `--os`/`--cpu` support (npm ≥ 10) | installs the `sharp` **win32-x64** prebuild from Linux |
|
||||
| Network | `node.exe` from nodejs.org (SHA-256 checked) and the npm registry |
|
||||
| Optional: Go 1.21+ | builds `Luminary.exe`; without it the PowerShell launcher ships |
|
||||
| Optional: Docker + BuildKit | the reproducible path, and the only way to get the Go exe on Linux |
|
||||
|
||||
No Windows machine is required for the portable zip.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
node windows/build.mjs # npm run build, then the bundle
|
||||
node windows/build.mjs --skip-build # reuse the existing dist/
|
||||
node windows/build.mjs --out /srv/builds/luminary-win
|
||||
node windows/build.mjs --launcher go # fail unless Go is installed
|
||||
node windows/build.mjs --skip-build --publish # also copy the zip to windows/releases
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
<out>/
|
||||
Luminary-0.5.0-win-x64.zip the deliverable
|
||||
stage/Luminary/ the unpacked bundle (kept for inspection)
|
||||
cache/node-v24.22.2-win-x64.exe pinned runtime, reused next time
|
||||
cache/SHASUMS256-v24.22.2.txt
|
||||
```
|
||||
|
||||
The build prints the zip size, its SHA-256, the Node version, the launcher kind
|
||||
and the staged folder.
|
||||
|
||||
### Transferring it to Windows
|
||||
|
||||
`--publish` copies the finished zip and a `SHA256SUMS.txt` into
|
||||
[`releases/`](releases/), which is the hand-off folder for a USB stick, network
|
||||
share or release upload:
|
||||
|
||||
```bash
|
||||
node windows/build.mjs --skip-build --publish
|
||||
```
|
||||
|
||||
It is the only write the builder makes inside the checkout; staging and zipping
|
||||
still happen outside it. On the Windows PC: extract the zip, then run
|
||||
`Luminary.cmd` or `Luminary.vbs` from the extracted `Luminary` folder. Note that
|
||||
`scripts/deploy.mjs` rsyncs the worktree, so remove the zip from `releases/`
|
||||
after transferring if you do not want it on the server.
|
||||
|
||||
### Reproducible path with Docker
|
||||
|
||||
```bash
|
||||
docker build -f windows/Dockerfile --output type=local,dest=/srv/builds/luminary-win .
|
||||
```
|
||||
|
||||
The image has Node 24 **and** Go, so it produces `Luminary.exe`. The final stage
|
||||
is `scratch`, so `--output` exports only the zip, checksum and staged bundle.
|
||||
`windows/Dockerfile.dockerignore` keeps `.git`, `node_modules` and `dist` out of
|
||||
the context; the app's own `Dockerfile` is unaffected.
|
||||
|
||||
### Installer (optional)
|
||||
|
||||
Inno Setup 6 on any Windows machine (or a Windows CI runner):
|
||||
|
||||
```bat
|
||||
iscc /DAppVersion=0.5.0 /DLauncher=Luminary.vbs ^
|
||||
/DSourceDir="C:\builds\luminary\stage\Luminary" windows\installer.iss
|
||||
```
|
||||
|
||||
Per-user install under `%LOCALAPPDATA%\Programs\Luminary`, Start-menu and
|
||||
optional desktop shortcuts, optional "start at login" (`HKCU\…\Run`), and an
|
||||
uninstaller that **keeps** `%LOCALAPPDATA%\Luminary\data`.
|
||||
|
||||
## What is in the bundle
|
||||
|
||||
```
|
||||
Luminary/
|
||||
node.exe Node 24 win-x64, verified against nodejs.org
|
||||
Luminary.ps1 start / -Stop / -Status / -Verify / -Repair / -Browser
|
||||
Luminary.cmd visible-console entry point
|
||||
Luminary.vbs no-console entry point
|
||||
Stop Luminary.cmd
|
||||
Luminary.exe only with a Go toolchain
|
||||
LuminaryWindow.exe optional native WebView2 window (--webview2)
|
||||
Luminary.ico icon for shortcuts and the installer
|
||||
version.txt version, commit, launcher, and the Node pin (version, SHA-256, size)
|
||||
README-windows.txt end-user instructions
|
||||
LICENSE, THIRD_PARTY_NOTICES.md, licenses/
|
||||
app/
|
||||
server/ unchanged, minus server/data and *.test.mjs
|
||||
dist/ the normal Vite build (UI, lens db, guide PDF)
|
||||
package.json provenance
|
||||
package-lock.json
|
||||
node_modules/ production deps installed with --os=win32 --cpu=x64
|
||||
runtime.json created on first start
|
||||
logs/ created on first start
|
||||
```
|
||||
|
||||
`sharp` is installed from the repository's own lockfile, so the Windows native
|
||||
package (`@img/sharp-win32-x64`) matches the version the app was tested with.
|
||||
The build verifies that its `.node` binary is present and only warns if not —
|
||||
the server degrades to PNG proxies rather than failing to boot.
|
||||
|
||||
## Running it
|
||||
|
||||
Double-click `Luminary.cmd` (brief console) or `Luminary.vbs` (silent). The
|
||||
launcher picks a free loopback port starting at 8787, sets
|
||||
`LUMINARY_DATA=%LOCALAPPDATA%\Luminary\data`, starts `node.exe` hidden, waits for
|
||||
`/api/health`, then opens the browser. `Stop Luminary.cmd` stops it;
|
||||
`Luminary.ps1 -Status` reports PID, URL, runtime and data folder.
|
||||
|
||||
### Single-user desktop mode
|
||||
|
||||
The launcher starts the server with `LUMINARY_LOCAL=1`:
|
||||
|
||||
- one admin (`local@luminary`) is created on first start and reused afterwards;
|
||||
- `/api/auth/me` answers without a cookie, so the UI never shows signup or
|
||||
sign-in, and registration returns 403;
|
||||
- the account is an admin, so every panel works; it cannot be renamed, disabled
|
||||
or deleted from the UI (403), and there is no password to remember;
|
||||
- the password is random and never shown, and the server binds `127.0.0.1`, so
|
||||
this is not reachable from the network. Starting with `HOST=0.0.0.0` and
|
||||
`LUMINARY_LOCAL=1` logs a warning at boot.
|
||||
|
||||
Without the variable, accounts, invites and email behave exactly as before —
|
||||
Docker and the shared server are untouched.
|
||||
|
||||
### App window
|
||||
|
||||
Instead of a tab, the launcher opens a chromeless window from the browser that
|
||||
is already installed:
|
||||
|
||||
```
|
||||
msedge.exe --app=http://127.0.0.1:8787 --user-data-dir=%LOCALAPPDATA%\Luminary\data\window-profile
|
||||
```
|
||||
|
||||
No tabs, no address bar, its own profile, and it remembers its window size.
|
||||
Edge ships with Windows 10/11, so nothing is installed; Chrome is the fallback
|
||||
and the default browser is the last resort. `Luminary.cmd -Browser` (or
|
||||
`LUMINARY_WINDOW=browser`) opens a normal tab instead.
|
||||
|
||||
A fully native window is available too: `windows/launcher/webview2` is a small
|
||||
WinForms host around WebView2 that owns its title bar, taskbar icon and window
|
||||
state. When the bundle contains `LuminaryWindow.exe`, the launcher uses it
|
||||
ahead of the browser window. Build it once (self-contained, no .NET needed on
|
||||
the target machine):
|
||||
|
||||
```bash
|
||||
mkdir -p /tmp/wv
|
||||
docker run --rm -v "$PWD/windows/launcher:/src" -v /tmp/wv:/out \
|
||||
-w /src/webview2 mcr.microsoft.com/dotnet/sdk:8.0 \
|
||||
dotnet publish -c Release -o /out
|
||||
node windows/build.mjs --webview2 /tmp/wv/LuminaryWindow.exe --publish
|
||||
```
|
||||
|
||||
It needs the Microsoft Edge **WebView2 runtime**, which ships with Windows
|
||||
10/11 alongside Edge; if it is ever missing, the window says so and links the
|
||||
Evergreen installer. The exe adds roughly 70 MB to the zip, which is why it is
|
||||
opt-in rather than always shipped.
|
||||
|
||||
Double-clicking `LuminaryWindow.exe` directly is safe too. Without `--url` it
|
||||
starts the bundle launcher (`Luminary.cmd`, `Luminary.vbs` or `Luminary.exe`)
|
||||
and exits; the launcher then starts desktop mode and reopens the window with
|
||||
`--url`. If the exe is copied out of a complete bundle, it explains that it is
|
||||
only the window rather than showing a signed-out page.
|
||||
|
||||
`Luminary.cmd -Verify` checks the bundle. `Luminary.cmd -Repair` re-downloads
|
||||
`node.exe` from nodejs.org and installs it only after the SHA-256 matches
|
||||
`version.txt` — the fix for an antivirus that quarantined the runtime. If
|
||||
the bundled `node.exe` is gone and a system Node 24+ exists, the app still
|
||||
starts on that runtime (with a warning) while you decide to repair.
|
||||
|
||||
Full behaviour, edge cases and the test checklist: [launcher/DESIGN.md](launcher/DESIGN.md).
|
||||
|
||||
## Data, updates and backups
|
||||
|
||||
- Catalog, originals, previews and `secret.key` live in
|
||||
`%LOCALAPPDATA%\Luminary\data` — never under `app\`, so an update cannot lose
|
||||
them.
|
||||
- Update: stop Luminary, replace `app\` (and `node.exe` when it changes) from a
|
||||
newer bundle, start again. The SQLite schema migrates on boot.
|
||||
- Back up: copy the whole data folder while Luminary is stopped, including
|
||||
`lumenroom.db`, `lumenroom.db-wal`, `lumenroom.db-shm`.
|
||||
|
||||
## Verifying a build
|
||||
|
||||
```bash
|
||||
cd <out>
|
||||
sha256sum Luminary-0.5.0-win-x64.zip
|
||||
unzip -t Luminary-0.5.0-win-x64.zip | tail -1
|
||||
unzip -l Luminary-0.5.0-win-x64.zip | grep -E 'node.exe|Luminary\.(exe|cmd|vbs)|app/server/index.mjs'
|
||||
```
|
||||
|
||||
On Windows, the real test is the checklist in `launcher/DESIGN.md` §15,
|
||||
especially a machine with **no Node installed**. The automated first pass is
|
||||
[`SMOKE-WINDOWS.ps1`](SMOKE-WINDOWS.ps1), run from the extracted bundle:
|
||||
|
||||
```bat
|
||||
powershell -ExecutionPolicy Bypass -File .\SMOKE-WINDOWS.ps1
|
||||
```
|
||||
|
||||
It checks the OS and WebView2 runtime, `-Verify`, a real desktop-mode boot
|
||||
(`local:true`, cookieless `/api/auth/me`, `/api/sync`), the native window
|
||||
launching and owning a window titled Luminary, and Stop — then writes
|
||||
`smoke-report.txt` next to the bundle.
|
||||
|
||||
## When the launcher says the bundle is incomplete
|
||||
|
||||
The bundle is a folder: `node.exe`, `Luminary.*`, and `app\server`, `app\dist`,
|
||||
`app\node_modules`. The launcher checks those three trees before starting and
|
||||
prints which one is missing:
|
||||
|
||||
- **Opened from the zip preview** — Windows extracts only the file you double-
|
||||
clicked into `%TEMP%`, so `node.exe` and `app\` are absent. Extract the whole
|
||||
zip first (right-click → "Extract All...").
|
||||
- **Antivirus/SmartScreen removed `node.exe`** — common with a freshly
|
||||
downloaded, unsigned Node runtime. Restore it from quarantine, or unblock the
|
||||
zip and extract again. `version.txt` carries the exact SHA-256 so a restored
|
||||
copy can be checked: the build verified the same hash against
|
||||
`nodejs.org/dist/<version>/SHASUMS256.txt`.
|
||||
- **Running the source launcher** — `windows\launcher\Luminary.cmd` is a template
|
||||
for the builder, not an install. Run `node windows/build.mjs` and use the zip.
|
||||
|
||||
`Luminary.cmd -Verify` prints the resolved bundle path, the size of each
|
||||
required file, the pinned Node version and the Luminary version, and exits `3`
|
||||
when something is missing or `node.exe` has the wrong size. The Go launcher
|
||||
shows the same message in a dialog box because it has no console.
|
||||
|
||||
### Repairing `node.exe`
|
||||
|
||||
```bat
|
||||
Luminary.cmd -Repair
|
||||
```
|
||||
|
||||
Reads the version and hash from `version.txt` (falling back to the published
|
||||
`SHASUMS256.txt`), downloads into a temp file, verifies the SHA-256, and only
|
||||
then replaces `node.exe`. It refuses while Luminary is running. Set
|
||||
`LUMINARY_NODE_URL` to use a mirror or an internal copy for air-gapped machines.
|
||||
`Luminary.exe -repair` does the same.
|
||||
|
||||
## Limitations
|
||||
|
||||
- The launcher is unsigned: SmartScreen may ask once, and a strict antivirus
|
||||
policy can quarantine `node.exe`; `-Repair` restores it, and the launcher can
|
||||
fall back to a system Node 24+ in the meantime.
|
||||
- No tray icon and no auto-update in this version (both are launcher features,
|
||||
not app changes).
|
||||
- Loopback only by default; set `HOST=0.0.0.0` for LAN proofing galleries.
|
||||
- The PowerShell launcher cannot clean up after a server crash; a stale
|
||||
`runtime.json` is simply ignored on the next start.
|
||||
- `windows/installer.iss` needs Inno Setup and is not exercised by the Linux
|
||||
build.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Check |
|
||||
| --- | --- |
|
||||
| "node.exe is missing" / "this folder is not a complete Luminary bundle" | run `Luminary.cmd -Verify`. Usual causes: the zip was opened instead of extracted (right-click → Extract All), antivirus removed `node.exe` after extraction, or `Luminary.cmd` was run from the source `windows\launcher` folder instead of the built bundle. For the antivirus case run `Luminary.cmd -Repair` |
|
||||
| Launch says it is using the system Node | the bundled `node.exe` is missing or truncated; `Luminary.cmd -Repair` restores the pinned runtime |
|
||||
| `Repair failed` | no network, a proxy blocking `nodejs.org`, or a checksum mismatch (nothing is installed in that case). Point `LUMINARY_NODE_URL` at a mirror of `node.exe` |
|
||||
| "Luminary needs Windows 10 or 11" (exit 4) | the launcher read `CurrentBuild` below 10240. The app targets Windows 10/11; there is no Windows 7/8 build |
|
||||
| "The Universal C Runtime is missing" | Windows 8.1 without KB2999226 — install <https://support.microsoft.com/help/2999226> or use Windows 10/11 |
|
||||
| "The data drive has only … GB free" | free space before starting; catalogs and previews grow in `%LOCALAPPDATA%` |
|
||||
| "did not answer on /api/health" | `logs\server.err.log`; run `node app\server\index.mjs` from `app\` to see the failure |
|
||||
| Browser opens an error page | the port was taken between the check and the spawn; start again |
|
||||
| RAW import fails | `app\node_modules\@img\sharp-win32-x64` must contain a `.node` binary; RAW decode itself is wasm |
|
||||
| `node.exe failed its SHA-256 check` | delete `<out>/cache` and rebuild (the download was truncated) |
|
||||
| A sign-in screen appears | the server was started without `LUMINARY_LOCAL=1`, or it is the normal server, not the bundle |
|
||||
| Opens as a normal tab | Edge/Chrome not found, or `-Browser` / `LUMINARY_WINDOW=browser` was used |
|
||||
| Build refuses `--out` | the path is inside the repo; choose one outside |
|
||||
| SmartScreen on first run | unsigned bundle: "More info" → "Run anyway" |
|
||||
@@ -0,0 +1,148 @@
|
||||
# Separate packaging repository (`luminary-windows`)
|
||||
|
||||
This is the fallback path if the `windows/` folder in this repo ever feels too
|
||||
close to the app: a second repository that builds the same bundle from a pinned
|
||||
upstream tag. It is a plan, not something that exists yet.
|
||||
|
||||
## Why a packaging repo and not a fork
|
||||
|
||||
A fork duplicates the app and forces a merge of every upstream change. Nothing
|
||||
in Luminary is Windows-specific — the server is plain ESM, `node:sqlite` and
|
||||
`sharp`/`libraw-wasm` ship Windows builds, and the only POSIX-ism
|
||||
(`secret.key` mode `0o600`) is ignored by Windows. The Windows work is
|
||||
therefore *packaging*: a fixed folder layout, a Node runtime, a launcher and an
|
||||
artifact. A packaging repo keeps that work under a separate review and release
|
||||
process while consuming the app unchanged.
|
||||
|
||||
A fork remains justified only if a Windows build ever needs an app patch
|
||||
(behaviour, not packaging). If that happens, the change belongs upstream in the
|
||||
main repo first.
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
luminary-windows/
|
||||
upstream.txt # pinned tag + commit + expected package version
|
||||
build.mjs # same script as windows/build.mjs, one copy
|
||||
launcher/ # Luminary.ps1, .cmd, .vbs, Stop, go/
|
||||
installer.iss
|
||||
Dockerfile # Go + Node 24 image for the exe build
|
||||
README.md
|
||||
CHANGELOG.md # per-release: upstream tag, node version, hashes
|
||||
```
|
||||
|
||||
`build.mjs` is copied verbatim from the main repo when it changes; there is no
|
||||
second implementation to drift.
|
||||
|
||||
## Pinning
|
||||
|
||||
`upstream.txt`:
|
||||
|
||||
```
|
||||
repo=https://git.maple-street.net/bhursey/luminary.git
|
||||
tag=v0.5.0
|
||||
commit=fb43ca8f1c2d… # full sha
|
||||
version=0.5.0 # package.json version, checked after fetch
|
||||
node=v24.22.2
|
||||
```
|
||||
|
||||
The build clones the upstream repository at the pinned commit (shallow clone of
|
||||
the tag, then `git rev-parse HEAD` must equal `commit`) into a work directory
|
||||
outside both repos, for example:
|
||||
|
||||
```
|
||||
$TMP/luminary-upstream/
|
||||
```
|
||||
|
||||
If the tag moves or the commit does not match, the build fails rather than
|
||||
silently shipping something else. A `--upstream-ref <sha>` flag allows a
|
||||
one-off build from a newer commit before the pin is updated.
|
||||
|
||||
## Build flow
|
||||
|
||||
```
|
||||
fetch pinned upstream (clone/verify)
|
||||
→ npm ci (dev deps, needed for vite)
|
||||
→ npm run build (typecheck + dist/)
|
||||
→ stage: dist, server, production node_modules (--os=win32 --cpu=x64),
|
||||
node.exe (SHA-256 verified), launcher, licences
|
||||
→ zip + sha256
|
||||
→ optional: iscc installer
|
||||
```
|
||||
|
||||
Exactly the same steps as `windows/build.mjs`; the only difference is where
|
||||
`dist/`, `server/` and `package.json` come from (a work tree, not `../`).
|
||||
|
||||
## CI (Gitea Actions, since the remote is Gitea)
|
||||
|
||||
`.gitea/workflows/windows.yml` in the packaging repo:
|
||||
|
||||
```yaml
|
||||
name: windows-bundle
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags: ['v*']
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest # or a Windows runner for the installer
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 24 }
|
||||
- run: node build.mjs --out "$RUNNER_TEMP/out"
|
||||
- run: sha256sum Luminary-*.zip >> "$RUNNER_TEMP/out/SHA256SUMS"
|
||||
working-directory: ${{ runner.temp }}/out
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: luminary-windows-${{ github.ref_name }}
|
||||
path: ${{ runner.temp }}/out/*
|
||||
```
|
||||
|
||||
Optional later steps: `softprops/action-gh-release` to attach the zip to a
|
||||
Gitea release, and a Windows runner that also builds `installer.iss` (Inno Setup
|
||||
is not available on Linux without Wine).
|
||||
|
||||
## Release and version policy
|
||||
|
||||
- One packaging release per upstream tag that should be installable on Windows;
|
||||
the artifact is `Luminary-<version>-win-x64.zip`.
|
||||
- `CHANGELOG.md` records upstream tag/commit, bundled Node version, artifact
|
||||
SHA-256 and any launcher change.
|
||||
- Security fixes: when upstream ships one, the pin moves, the packaging tag
|
||||
increments (`v1.0.1-win.1` style if needed) and the artifact is rebuilt.
|
||||
- Windows-only changes (launcher, installer) release independently — they do not
|
||||
require an upstream bump, because they never touch `app/`.
|
||||
|
||||
## Updating users
|
||||
|
||||
The bundle is portable: replacing `app\` and `node.exe` is the update. Keep the
|
||||
data folder (`%LOCALAPPDATA%\Luminary\data`) untouched. A future auto-updater
|
||||
would read a small JSON manifest beside the release and download the zip; that
|
||||
is a packaging-repo feature, not an app change.
|
||||
|
||||
## Migration from the in-repo `windows/` folder
|
||||
|
||||
1. Create the new repo.
|
||||
2. Copy `windows/` to its root (`build.mjs`, `launcher/`, `installer.iss`,
|
||||
`Dockerfile`, this plan and `README.md`), adjusting the input paths in
|
||||
`build.mjs` to the fetched upstream work tree.
|
||||
3. Add `upstream.txt`, the CI workflow, `CHANGELOG.md`.
|
||||
4. Build once from the pinned tag and compare the zip contents with the
|
||||
in-repo build (same files, same launcher) before publishing.
|
||||
5. Optionally delete `windows/` from the main repo afterwards; nothing in the
|
||||
app depends on it.
|
||||
|
||||
## Trade-offs
|
||||
|
||||
| | In-repo `windows/` (current) | Separate repo |
|
||||
| --- | --- | --- |
|
||||
| Upstream awareness | always the local checkout | explicit pin, can lag |
|
||||
| Review/CI noise | one extra folder | separate pipeline |
|
||||
| Release discipline | none required | tag + changelog per artifact |
|
||||
| Risk to the app | none (folder only) | none (no files in the app repo) |
|
||||
| Effort | zero extra repos | one more repo and workflow |
|
||||
|
||||
Stay with the in-repo folder while the Windows build changes infrequently;
|
||||
move to this layout when it needs its own release cadence or a second
|
||||
maintainer.
|
||||
@@ -0,0 +1,179 @@
|
||||
<#
|
||||
One-command smoke test for an extracted Luminary bundle on Windows.
|
||||
|
||||
Run it from the extracted bundle folder (or pass -Bundle):
|
||||
|
||||
powershell -ExecutionPolicy Bypass -File .\SMOKE-WINDOWS.ps1
|
||||
|
||||
It writes smoke-report.txt next to the bundle and prints the same lines.
|
||||
Exit code 0 means every check passed.
|
||||
|
||||
What it covers without a human clicking:
|
||||
- OS version and architecture, and whether the WebView2 runtime is present
|
||||
- the bundle files the launcher needs, and -Verify's own result
|
||||
- a real server boot in desktop mode: /api/health local:true,
|
||||
/api/auth/me 200 without a cookie, /api/sync 200
|
||||
- LuminaryWindow.exe launching, staying alive and owning a window titled
|
||||
Luminary (the native WebView2 path)
|
||||
- Stop actually stopping the server
|
||||
|
||||
It is deliberately conservative: it uses a throwaway data folder under
|
||||
%TEMP% and a port that is unlikely to collide, so it never touches a real
|
||||
catalog.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Bundle = (Split-Path -Parent $MyInvocation.MyCommand.Path),
|
||||
[int]$Port = 8912,
|
||||
[int]$WindowSeconds = 8
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:lines = @()
|
||||
$script:failed = 0
|
||||
|
||||
function Say([string]$text) {
|
||||
$script:lines += $text
|
||||
Write-Host $text
|
||||
}
|
||||
|
||||
function Check([string]$name, [bool]$ok, [string]$detail = '') {
|
||||
if ($ok) {
|
||||
Say (" PASS {0}{1}" -f $name, $(if ($detail) { " — $detail" } else { '' }))
|
||||
} else {
|
||||
$script:failed += 1
|
||||
Say (" FAIL {0}{1}" -f $name, $(if ($detail) { " — $detail" } else { '' }))
|
||||
}
|
||||
return $ok
|
||||
}
|
||||
|
||||
function Get-WebView2Version {
|
||||
$keys = @(
|
||||
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}',
|
||||
'HKLM:\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}',
|
||||
'HKCU:\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}'
|
||||
)
|
||||
foreach ($key in $keys) {
|
||||
try {
|
||||
$value = (Get-ItemProperty -Path $key -Name pv -ErrorAction Stop).pv
|
||||
if ($value) { return $value }
|
||||
} catch { }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
$nodeExe = Join-Path $Bundle 'node.exe'
|
||||
$appDir = Join-Path $Bundle 'app'
|
||||
$entry = Join-Path $appDir 'server\index.mjs'
|
||||
$windowExe = Join-Path $Bundle 'LuminaryWindow.exe'
|
||||
$launcher = Join-Path $Bundle 'Luminary.ps1'
|
||||
$dataDir = Join-Path $env:TEMP ('luminary-smoke-{0}' -f [guid]::NewGuid().ToString('N'))
|
||||
$url = "http://127.0.0.1:$Port"
|
||||
$server = $null
|
||||
$window = $null
|
||||
|
||||
Say 'Luminary Windows smoke test'
|
||||
Say (" bundle {0}" -f $Bundle)
|
||||
Say (" time {0}" -f (Get-Date).ToString('s'))
|
||||
|
||||
try {
|
||||
$os = Get-CimInstance Win32_OperatingSystem
|
||||
Say ''
|
||||
Say 'Environment'
|
||||
Say (" OS {0} (build {1})" -f $os.Caption, $os.BuildNumber)
|
||||
Say (" arch {0}" -f $env:PROCESSOR_ARCHITECTURE)
|
||||
$webview2 = Get-WebView2Version
|
||||
Say (" webview {0}" -f $(if ($webview2) { "runtime $webview2" } else { 'NOT INSTALLED' }))
|
||||
|
||||
Say ''
|
||||
Say 'Bundle'
|
||||
Check 'node.exe present' (Test-Path -LiteralPath $nodeExe) $nodeExe
|
||||
Check 'app\server\index.mjs present' (Test-Path -LiteralPath $entry) $entry
|
||||
Check 'Luminary.ps1 present' (Test-Path -LiteralPath $launcher) $launcher
|
||||
Check 'LuminaryWindow.exe present' (Test-Path -LiteralPath $windowExe) $windowExe
|
||||
if (Test-Path -LiteralPath $launcher) {
|
||||
$verify = Start-Process -FilePath 'powershell.exe' -ArgumentList @(
|
||||
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launcher, '-Verify'
|
||||
) -Wait -PassThru -WindowStyle Hidden
|
||||
Check '-Verify exits 0' ($verify.ExitCode -eq 0) ("exit {0}" -f $verify.ExitCode)
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $nodeExe)) { throw 'node.exe is missing, cannot start the server' }
|
||||
if (-not (Test-Path -LiteralPath $entry)) { throw 'app\server\index.mjs is missing, cannot start the server' }
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null
|
||||
$env:PORT = "$Port"
|
||||
$env:HOST = '127.0.0.1'
|
||||
$env:NODE_ENV = 'production'
|
||||
$env:LUMINARY_DATA = $dataDir
|
||||
$env:LUMINARY_LOCAL = '1'
|
||||
|
||||
Say ''
|
||||
Say 'Server (desktop mode)'
|
||||
$server = Start-Process -FilePath $nodeExe -ArgumentList @('"' + $entry + '"') `
|
||||
-WorkingDirectory $appDir -WindowStyle Hidden -PassThru `
|
||||
-RedirectStandardOutput (Join-Path $dataDir 'out.log') `
|
||||
-RedirectStandardError (Join-Path $dataDir 'err.log')
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(90)
|
||||
$health = $null
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri "$url/api/health"
|
||||
if ($response.StatusCode -eq 200) { $health = $response.Content | ConvertFrom-Json; break }
|
||||
} catch { }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
Check 'health answers' ($null -ne $health)
|
||||
if ($health) {
|
||||
Check 'local mode advertised' ($health.local -eq $true) ("local={0}" -f $health.local)
|
||||
Check 'no setup prompt' ($health.needsSetup -eq $false)
|
||||
Check 'registration closed' ($health.registrationOpen -eq $false)
|
||||
}
|
||||
try {
|
||||
$me = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 -Uri "$url/api/auth/me"
|
||||
$who = $me.Content | ConvertFrom-Json
|
||||
Check 'signed in without a cookie' ($me.StatusCode -eq 200) ("{0} ({1})" -f $who.user.email, $who.user.role)
|
||||
} catch {
|
||||
Check 'signed in without a cookie' $false $_.Exception.Message
|
||||
}
|
||||
try {
|
||||
$sync = Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Uri "$url/api/sync"
|
||||
Check '/api/sync answers' ($sync.StatusCode -eq 200)
|
||||
} catch {
|
||||
Check '/api/sync answers' $false $_.Exception.Message
|
||||
}
|
||||
|
||||
Say ''
|
||||
Say 'Window (WebView2)'
|
||||
if (-not (Test-Path -LiteralPath $windowExe)) {
|
||||
Say ' SKIP LuminaryWindow.exe is not in this bundle'
|
||||
} else {
|
||||
$window = Start-Process -FilePath $windowExe -ArgumentList @('--url', $url) -PassThru
|
||||
Start-Sleep -Seconds $WindowSeconds
|
||||
$window.Refresh()
|
||||
$alive = -not $window.HasExited
|
||||
Check 'window process alive' $alive $(if ($alive) { 'pid ' + $window.Id } else { 'exited early' })
|
||||
if ($alive) {
|
||||
$title = $window.MainWindowTitle
|
||||
Check 'window titled Luminary' ($title -eq 'Luminary') ("title '{0}'" -f $title)
|
||||
}
|
||||
if (-not $window.HasExited) { Stop-Process -Id $window.Id -Force }
|
||||
}
|
||||
} catch {
|
||||
Say (" ERROR {0}" -f $_.Exception.Message)
|
||||
$script:failed += 1
|
||||
} finally {
|
||||
if ($window -and -not $window.HasExited) { Stop-Process -Id $window.Id -Force -ErrorAction SilentlyContinue }
|
||||
if ($server -and -not $server.HasExited) { Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue }
|
||||
Remove-Item -LiteralPath $dataDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
|
||||
Say ''
|
||||
if ($script:failed -eq 0) {
|
||||
Say 'RESULT: PASS'
|
||||
} else {
|
||||
Say ("RESULT: FAIL ({0} check(s))" -f $script:failed)
|
||||
}
|
||||
try { $script:lines | Set-Content -LiteralPath (Join-Path $Bundle 'smoke-report.txt') -Encoding UTF8 } catch { }
|
||||
exit $(if ($script:failed -eq 0) { 0 } else { 1 })
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Build the optional Windows bundle for Luminary.
|
||||
*
|
||||
* This is deliberately *outside* the main build: 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, the deploy script or `dist/` is modified by this file, and no npm
|
||||
* script is added for it. Run it directly:
|
||||
*
|
||||
* node windows/build.mjs # build dist/ then the bundle
|
||||
* node windows/build.mjs --skip-build # reuse the existing dist/
|
||||
* node windows/build.mjs --out D:\lum # choose the output directory
|
||||
*
|
||||
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
|
||||
* the parent of `server/`), so it is a plain folder plus a launcher:
|
||||
*
|
||||
* <out>/Luminary/
|
||||
* node.exe official Node 24 win-x64, SHA-256 checked
|
||||
* Luminary.cmd / .vbs PowerShell launcher (start, health wait, browser)
|
||||
* Luminary.exe only when a Go toolchain builds it
|
||||
* Stop Luminary.cmd
|
||||
* Luminary.ps1 start/stop/status logic shared by both launchers
|
||||
* app/ unchanged server/, dist/, production node_modules/
|
||||
* README-windows.txt
|
||||
* version.txt
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(HERE, '..');
|
||||
const LAUNCHER_FILES = path.join(HERE, 'launcher');
|
||||
const RELEASES_DIR = path.join(HERE, 'releases');
|
||||
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const DEFAULT_NODE = 'v24.22.2';
|
||||
|
||||
const HELP = `Luminary Windows bundle
|
||||
|
||||
Usage: node windows/build.mjs [options]
|
||||
|
||||
--out <dir> output directory (default: <cache>/luminary-windows).
|
||||
Must be outside this repository; the bundle is staged in
|
||||
<out>/stage and zipped to <out>/Luminary-<ver>-win-x64.zip.
|
||||
--skip-build reuse the existing dist/ instead of running npm run build
|
||||
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
|
||||
--launcher <kind> auto (default), ps or go. "go" needs a Go toolchain and
|
||||
produces Luminary.exe; "ps" always works.
|
||||
--allow-dirty skip the check that the checkout is clean outside windows/
|
||||
--publish copy the finished zip to windows/releases (plus a
|
||||
SHA256SUMS.txt) so it can be transferred to a Windows PC
|
||||
--webview2 <exe> ship a prebuilt LuminaryWindow.exe (native WebView2 window).
|
||||
Build it with:
|
||||
docker run --rm -v $PWD/windows/launcher:/src \\
|
||||
-v /tmp/wv:/out -w /src/webview2 \\
|
||||
mcr.microsoft.com/dotnet/sdk:8.0 \\
|
||||
dotnet publish -c Release -o /out
|
||||
--help print this text
|
||||
|
||||
Nothing in the repository is modified: the only writes outside the output
|
||||
directory are the ones npm and nodejs.org make for their own caches.
|
||||
`;
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`windows: FAILED: ${message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function log(step, message) {
|
||||
process.stdout.write(`windows: ${step.padEnd(9)} ${message}\n`);
|
||||
}
|
||||
|
||||
function warn(message) {
|
||||
process.stderr.write(`windows: warning: ${message}\n`);
|
||||
}
|
||||
|
||||
function defaultOutDir() {
|
||||
if (process.platform === 'win32') {
|
||||
const base = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
||||
return path.join(base, 'Luminary', 'build');
|
||||
}
|
||||
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-windows');
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
out: defaultOutDir(),
|
||||
node: DEFAULT_NODE,
|
||||
launcher: 'auto',
|
||||
build: true,
|
||||
allowDirty: false,
|
||||
publish: false,
|
||||
webview2: null,
|
||||
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 === '--launcher') {
|
||||
options.launcher = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--skip-build') {
|
||||
options.build = false;
|
||||
} else if (arg === '--allow-dirty') {
|
||||
options.allowDirty = true;
|
||||
} else if (arg === '--publish') {
|
||||
options.publish = true;
|
||||
} else if (arg === '--webview2') {
|
||||
options.webview2 = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true;
|
||||
} else {
|
||||
fail(`unknown option ${arg} (see --help)`);
|
||||
}
|
||||
}
|
||||
if (!['auto', 'ps', 'go'].includes(options.launcher)) {
|
||||
fail(`--launcher must be auto, ps or go (got ${options.launcher})`);
|
||||
}
|
||||
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
|
||||
fail(`--node must look like v24.22.2 (got ${options.node})`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function git(args, { trim = true } = {}) {
|
||||
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
|
||||
if (result.error || result.status !== 0) return null;
|
||||
return trim ? result.stdout.trim() : result.stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundle must not land in the checkout: a staged Windows Node runtime and
|
||||
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
|
||||
* and grow the Docker build 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` +
|
||||
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
|
||||
'output directory outside the checkout, or omit --out to use the cache.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
|
||||
* in this checkout and is not part of the app, so it is tolerated.
|
||||
*/
|
||||
function checkRepoClean(options) {
|
||||
// Not trimmed: porcelain lines start with two status columns and a space, and
|
||||
// trimming the output would eat the leading space of the first line, shifting
|
||||
// its path by one character.
|
||||
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('windows/') && 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 windows/:\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 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}`);
|
||||
}
|
||||
|
||||
function ensureUi(options) {
|
||||
const dist = path.join(ROOT, 'dist', 'index.html');
|
||||
if (options.build) {
|
||||
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
|
||||
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" first');
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
function copyServer(bundle) {
|
||||
const server = path.join(bundle, 'app', 'server');
|
||||
cpSync(path.join(ROOT, 'server'), server, {
|
||||
recursive: true,
|
||||
filter: (source) => {
|
||||
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
|
||||
// The developer catalog and the test files never belong in a bundle.
|
||||
if (relative === 'data' || relative.startsWith('data/')) return false;
|
||||
if (/\.test\.mjs$/.test(relative)) return false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function copyLegal(bundle) {
|
||||
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
|
||||
const source = path.join(ROOT, name);
|
||||
if (existsSync(source)) cpSync(source, path.join(bundle, name));
|
||||
}
|
||||
const licenses = path.join(ROOT, 'licenses');
|
||||
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
|
||||
}
|
||||
|
||||
/** Copies a text file with CRLF endings, which cmd.exe and PowerShell expect. */
|
||||
function copyText(source, dest) {
|
||||
const body = readFileSync(source, 'utf8').replace(/\r?\n/g, '\r\n');
|
||||
writeFileSync(dest, body);
|
||||
}
|
||||
|
||||
function installWindowsDeps(bundle) {
|
||||
const appDir = path.join(bundle, 'app');
|
||||
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=win32 --cpu=x64 (sharp win32-x64 prebuild)');
|
||||
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
|
||||
// prebuilt binary through optionalDependencies, and running a Windows-only
|
||||
// script on the build host would fail for no reason.
|
||||
run(
|
||||
NPM,
|
||||
[
|
||||
'ci',
|
||||
'--omit=dev',
|
||||
'--os=win32',
|
||||
'--cpu=x64',
|
||||
'--no-audit',
|
||||
'--no-fund',
|
||||
'--ignore-scripts',
|
||||
],
|
||||
appDir,
|
||||
);
|
||||
// .bin shims are for a shell, not for `node server/index.mjs`; on a Linux
|
||||
// build they would also be POSIX symlinks inside the zip.
|
||||
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
|
||||
verifySharp(appDir);
|
||||
}
|
||||
|
||||
function verifySharp(appDir) {
|
||||
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-win32-x64');
|
||||
if (!existsSync(dir)) {
|
||||
warn('@img/sharp-win32-x64 is missing; the server will fall back to PNG proxies');
|
||||
return;
|
||||
}
|
||||
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|dll)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
if (!binaries.some((file) => file.endsWith('.node'))) {
|
||||
warn('@img/sharp-win32-x64 has no .node binary; check the installed package');
|
||||
} else {
|
||||
log('deps', `sharp win32-x64 ready (${binaries.length} native files)`);
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
async function ensureNode(outDir, version) {
|
||||
const major = Number(version.slice(1).split('.')[0]);
|
||||
if (major < 24) {
|
||||
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
|
||||
}
|
||||
const cache = path.join(outDir, 'cache');
|
||||
mkdirSync(cache, { recursive: true });
|
||||
const exe = path.join(cache, `node-${version}-win-x64.exe`);
|
||||
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
|
||||
const base = `https://nodejs.org/dist/${version}`;
|
||||
if (!existsSync(exe)) {
|
||||
log('node', `downloading ${base}/win-x64/node.exe`);
|
||||
try {
|
||||
writeFileSync(exe, await download(`${base}/win-x64/node.exe`));
|
||||
} catch (error) {
|
||||
fail(`could not download node.exe: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
log('node', `using cached ${path.basename(exe)}`);
|
||||
}
|
||||
if (!existsSync(sums)) {
|
||||
try {
|
||||
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
|
||||
} catch (error) {
|
||||
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached node.exe is unverified`);
|
||||
}
|
||||
}
|
||||
const hash = sha256File(exe);
|
||||
if (existsSync(sums)) {
|
||||
const line = readFileSync(sums, 'utf8')
|
||||
.split('\n')
|
||||
.map((row) => row.trim().split(/\s+/))
|
||||
.find((row) => row[1] === 'win-x64/node.exe');
|
||||
if (!line) fail(`SHASUMS256.txt for ${version} has no win-x64/node.exe entry`);
|
||||
if (hash !== line[0]) {
|
||||
rmSync(exe, { force: true });
|
||||
fail(`node.exe failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
|
||||
}
|
||||
log('node', `${version} win-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
|
||||
} else {
|
||||
warn(`using node.exe without a published checksum (sha256 ${hash})`);
|
||||
}
|
||||
return { exe, hash };
|
||||
}
|
||||
|
||||
function goAvailable() {
|
||||
const result = spawnSync('go', ['version'], { encoding: 'utf8' });
|
||||
return !result.error && result.status === 0;
|
||||
}
|
||||
|
||||
function chooseLauncher(requested) {
|
||||
if (requested === 'ps') return 'ps';
|
||||
if (requested === 'go') {
|
||||
if (!goAvailable()) {
|
||||
fail(
|
||||
'--launcher go needs a Go toolchain (https://go.dev/dl/), or build the exe\n' +
|
||||
'in the container: docker build -f windows/Dockerfile --output type=local,dest=<dir> .',
|
||||
);
|
||||
}
|
||||
return 'go';
|
||||
}
|
||||
return goAvailable() ? 'go' : 'ps';
|
||||
}
|
||||
|
||||
function installLauncher(bundle, kind) {
|
||||
const files = ['Luminary.ps1', 'Stop Luminary.cmd'];
|
||||
if (kind === 'go') {
|
||||
const source = path.join(LAUNCHER_FILES, 'go');
|
||||
log('launcher', 'go build -trimpath -H windowsgui (Luminary.exe)');
|
||||
run(
|
||||
'go',
|
||||
[
|
||||
'build',
|
||||
'-trimpath',
|
||||
'-ldflags',
|
||||
'-s -w -H windowsgui',
|
||||
'-o',
|
||||
path.join(bundle, 'Luminary.exe'),
|
||||
'.',
|
||||
],
|
||||
source,
|
||||
{ GOOS: 'windows', GOARCH: 'amd64', CGO_ENABLED: '0' },
|
||||
);
|
||||
} else {
|
||||
files.push('Luminary.cmd', 'Luminary.vbs');
|
||||
}
|
||||
for (const name of files) {
|
||||
copyText(path.join(LAUNCHER_FILES, name), path.join(bundle, name));
|
||||
}
|
||||
// Binary icon for shortcuts and the installer; no CRLF pass on this one.
|
||||
const icon = path.join(LAUNCHER_FILES, 'Luminary.ico');
|
||||
if (existsSync(icon)) cpSync(icon, path.join(bundle, 'Luminary.ico'));
|
||||
// The PowerShell launcher is always present: it implements the shared
|
||||
// start/stop/status logic and "Stop Luminary.cmd" calls it in both modes.
|
||||
log('launcher', kind === 'go' ? 'Luminary.exe' : 'Luminary.cmd + Luminary.vbs');
|
||||
}
|
||||
|
||||
function writeVersion(bundle, pkg, launcher, nodeVersion, nodeHash, nodeSize) {
|
||||
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
|
||||
// The hash is on the node line so the launcher can quote it verbatim when
|
||||
// node.exe goes missing (antivirus) and the user needs to verify a restore.
|
||||
const lines = [
|
||||
`Luminary ${pkg.version}`,
|
||||
`commit ${commit}`,
|
||||
`built ${new Date().toISOString()}`,
|
||||
`node ${nodeVersion} win-x64 sha256 ${nodeHash} size ${nodeSize}`,
|
||||
`launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
|
||||
];
|
||||
const text = `${lines.join('\n')}\n`;
|
||||
writeFileSync(path.join(bundle, 'version.txt'), text);
|
||||
return { version: pkg.version, commit };
|
||||
}
|
||||
|
||||
function writeBundleReadme(bundle, info) {
|
||||
const start = info.launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd (or Luminary.vbs for no console window)';
|
||||
const body = `Luminary ${info.version} for Windows (x64) — portable bundle
|
||||
=================================================
|
||||
|
||||
Start: double-click ${start}
|
||||
Stop: double-click "Stop Luminary.cmd"
|
||||
Open: the launcher opens http://127.0.0.1:8787 (the next free port if busy)
|
||||
Data: %LOCALAPPDATA%\\Luminary\\data (originals, previews, SQLite catalog)
|
||||
Logs: logs\\server.out.log and logs\\server.err.log
|
||||
Check: "Luminary.cmd -Verify" lists the files a complete bundle needs
|
||||
Repair: "Luminary.cmd -Repair" downloads node.exe again and verifies its sha256
|
||||
Sign-in: none — single-user desktop mode, no account setup
|
||||
Window: opens in its own window (native when bundled, else chromeless Edge/Chrome);
|
||||
"Luminary.cmd -Browser" for a normal tab
|
||||
|
||||
Requirements
|
||||
- Windows 10 or 11, 64-bit.
|
||||
- A current browser (Edge, Chrome or Firefox) with WebGL2 for the Develop
|
||||
module.
|
||||
- Nothing else. Node.js is included as node.exe, and no .NET, Visual C++
|
||||
Redistributable, admin rights or installer is needed.
|
||||
- About 250 MB free where the data folder lives.
|
||||
|
||||
The first launch creates the data folder and the catalog. Nothing is installed
|
||||
and nothing is written next to Windows or Program Files, so you can move this
|
||||
folder anywhere (including a USB drive) as long as it stays writable.
|
||||
|
||||
If an antivirus removes node.exe, the launcher offers to download it on the next
|
||||
start (or run "Luminary.cmd -Repair"). On Windows older than 10 the launcher
|
||||
says so before starting instead of failing halfway.
|
||||
|
||||
Back up the catalog by copying the whole data folder while Luminary is stopped,
|
||||
including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and secret.key.
|
||||
|
||||
Updating: stop Luminary, replace app\\ and node.exe from a newer bundle, then
|
||||
start it again. The data folder is outside the bundle and is untouched.
|
||||
|
||||
Notes
|
||||
- Extract the whole zip before running anything. A file opened from inside
|
||||
the zip preview is copied out on its own and will not find node.exe.
|
||||
- Windows 8.1 and older also need the Universal C Runtime (KB2999226);
|
||||
Windows 10 and 11 already include it.
|
||||
- This build is single-user: it creates one local admin on first start and
|
||||
opens signed in. It is not meant for several people sharing one Windows
|
||||
login with separate accounts.
|
||||
- The bundle is unsigned, so SmartScreen may ask once ("More info" -> "Run anyway").
|
||||
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 before starting if
|
||||
client proofing galleries must be reachable from other devices on the LAN.
|
||||
- RAW decoding uses the bundled libraw WebAssembly; sharp's Windows prebuilt
|
||||
binary is included, so there is nothing else to install.
|
||||
`;
|
||||
writeFileSync(path.join(bundle, 'README-windows.txt'), body.replace(/\r?\n/g, '\r\n'));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ zip ---- */
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buffer) {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < buffer.length; i++) c = CRC_TABLE[(c ^ buffer[i]) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function listFiles(dir) {
|
||||
const files = [];
|
||||
const walk = (current) => {
|
||||
const entries = readdirSync(current, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
for (const entry of entries) {
|
||||
const absolute = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(absolute);
|
||||
else if (entry.isFile()) files.push(absolute);
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal ZIP writer (deflate, no zip64). Keeping it here avoids a dependency,
|
||||
* and every entry carries the same fixed timestamp instead of inheriting the
|
||||
* filesystem's, so two builds differ only by the files' own content.
|
||||
*/
|
||||
function writeZip(sourceDir, zipPath) {
|
||||
// 2020-01-01 00:00:00 in MS-DOS date/time form.
|
||||
const time = 0;
|
||||
const date = (40 << 9) | (1 << 5) | 1;
|
||||
const parts = [];
|
||||
const central = [];
|
||||
let offset = 0;
|
||||
for (const absolute of listFiles(sourceDir)) {
|
||||
const name = path.relative(sourceDir, absolute).split(path.sep).join('/');
|
||||
const data = readFileSync(absolute);
|
||||
const crc = crc32(data);
|
||||
const deflated = zlib.deflateRawSync(data, { level: 9 });
|
||||
const useDeflate = deflated.length < data.length;
|
||||
const body = useDeflate ? deflated : data;
|
||||
const method = useDeflate ? 8 : 0;
|
||||
const nameBytes = Buffer.from(name, 'utf8');
|
||||
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0x0800, 6); // UTF-8 names
|
||||
local.writeUInt16LE(method, 8);
|
||||
local.writeUInt16LE(time, 10);
|
||||
local.writeUInt16LE(date, 12);
|
||||
local.writeUInt32LE(crc, 14);
|
||||
local.writeUInt32LE(body.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(nameBytes.length, 26);
|
||||
local.writeUInt16LE(0, 28);
|
||||
parts.push(local, nameBytes, body);
|
||||
|
||||
const entry = Buffer.alloc(46);
|
||||
entry.writeUInt32LE(0x02014b50, 0);
|
||||
entry.writeUInt16LE(20, 4);
|
||||
entry.writeUInt16LE(20, 6);
|
||||
entry.writeUInt16LE(0x0800, 8);
|
||||
entry.writeUInt16LE(method, 10);
|
||||
entry.writeUInt16LE(time, 12);
|
||||
entry.writeUInt16LE(date, 14);
|
||||
entry.writeUInt32LE(crc, 16);
|
||||
entry.writeUInt32LE(body.length, 20);
|
||||
entry.writeUInt32LE(data.length, 24);
|
||||
entry.writeUInt16LE(nameBytes.length, 28);
|
||||
entry.writeUInt16LE(0, 30);
|
||||
entry.writeUInt16LE(0, 32);
|
||||
entry.writeUInt16LE(0, 34);
|
||||
entry.writeUInt16LE(0, 36);
|
||||
entry.writeUInt32LE(0, 38);
|
||||
entry.writeUInt32LE(offset, 42);
|
||||
central.push(entry, nameBytes);
|
||||
|
||||
offset += local.length + nameBytes.length + body.length;
|
||||
}
|
||||
const directory = Buffer.concat(central);
|
||||
const end = Buffer.alloc(22);
|
||||
const count = central.length / 2;
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(0, 4);
|
||||
end.writeUInt16LE(0, 6);
|
||||
end.writeUInt16LE(count, 8);
|
||||
end.writeUInt16LE(count, 10);
|
||||
end.writeUInt32LE(directory.length, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
end.writeUInt16LE(0, 20);
|
||||
writeFileSync(zipPath, Buffer.concat([...parts, directory, end]));
|
||||
return { files: count, bytes: statSync(zipPath).size };
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- main ---- */
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
assertOutsideRepo(options.out);
|
||||
const pkg = readPackage();
|
||||
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
|
||||
log('out', options.out);
|
||||
checkRepoClean(options);
|
||||
ensureUi(options);
|
||||
|
||||
// Settle the launcher before anything is copied: a missing Go toolchain
|
||||
// should fail in a second, not after a download and an npm install.
|
||||
const launcher = chooseLauncher(options.launcher);
|
||||
|
||||
// Build into a sibling and swap at the end, so a failed run never replaces
|
||||
// the last complete bundle with a partial tree.
|
||||
const stageRoot = path.join(options.out, 'stage');
|
||||
const workRoot = path.join(options.out, 'stage.next');
|
||||
const bundle = path.join(workRoot, 'Luminary');
|
||||
rmSync(workRoot, { recursive: true, force: true });
|
||||
mkdirSync(path.join(bundle, 'app'), { recursive: true });
|
||||
|
||||
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
|
||||
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
|
||||
copyServer(bundle);
|
||||
copyLegal(bundle);
|
||||
installWindowsDeps(bundle);
|
||||
|
||||
const node = await ensureNode(options.out, options.node);
|
||||
const bundledNode = path.join(bundle, 'node.exe');
|
||||
cpSync(node.exe, bundledNode);
|
||||
if (statSync(bundledNode).size !== statSync(node.exe).size) {
|
||||
fail('node.exe was truncated while copying it into the bundle');
|
||||
}
|
||||
|
||||
installLauncher(bundle, launcher);
|
||||
if (options.webview2) {
|
||||
if (!existsSync(options.webview2)) fail(`--webview2 file not found: ${options.webview2}`);
|
||||
cpSync(options.webview2, path.join(bundle, 'LuminaryWindow.exe'));
|
||||
log('window', `LuminaryWindow.exe (${(statSync(options.webview2).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||
}
|
||||
|
||||
const info = writeVersion(bundle, pkg, launcher, options.node, node.hash, statSync(bundledNode).size);
|
||||
writeBundleReadme(bundle, { ...info, launcher });
|
||||
|
||||
const zipPath = path.join(options.out, `Luminary-${pkg.version}-win-x64.zip`);
|
||||
rmSync(zipPath, { force: true });
|
||||
log('zip', path.basename(zipPath));
|
||||
const zip = writeZip(workRoot, zipPath);
|
||||
|
||||
rmSync(stageRoot, { recursive: true, force: true });
|
||||
renameSync(workRoot, stageRoot);
|
||||
|
||||
// The isolation contract: nothing outside windows/ may have changed.
|
||||
if (!options.allowDirty) checkRepoClean(options);
|
||||
const stagedBundle = path.join(stageRoot, 'Luminary');
|
||||
|
||||
// Hand-off copy. The staging and the zip stay outside the checkout; this is
|
||||
// the one write into the repository, into windows/releases, for transfer to a
|
||||
// Windows machine.
|
||||
let published = null;
|
||||
if (options.publish) {
|
||||
mkdirSync(RELEASES_DIR, { recursive: true });
|
||||
const target = path.join(RELEASES_DIR, path.basename(zipPath));
|
||||
cpSync(zipPath, target);
|
||||
writeFileSync(
|
||||
path.join(RELEASES_DIR, 'SHA256SUMS.txt'),
|
||||
`${sha256File(target)} ${path.basename(target)}\n`,
|
||||
);
|
||||
published = target;
|
||||
log('publish', path.relative(ROOT, target));
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
'',
|
||||
'windows build PASSED',
|
||||
` artifact ${zipPath}`,
|
||||
` size ${(zip.bytes / 1024 / 1024).toFixed(1)} MB (${zip.files} files)`,
|
||||
` sha256 ${sha256File(zipPath)}`,
|
||||
` node ${options.node} win-x64`,
|
||||
` launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
|
||||
...(options.webview2 ? [` window LuminaryWindow.exe (native WebView2)`] : []),
|
||||
` staged ${stagedBundle}`,
|
||||
...(published ? [` publish ${path.relative(ROOT, published)}`] : []),
|
||||
'',
|
||||
published
|
||||
? 'Only windows/ was written: the zip in windows/releases is ready to transfer.'
|
||||
: 'The repository was not modified; only windows/ and the output directory were touched.',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
main().then(
|
||||
(code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
(error) => {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
; Optional per-user installer for the Luminary Windows bundle.
|
||||
;
|
||||
; Build the bundle first: node windows/build.mjs
|
||||
; Then, from the output directory:
|
||||
; iscc /DAppVersion=0.5.0 /DSourceDir="<abs path to stage\Luminary>" \
|
||||
; <repo>\windows\installer.iss
|
||||
;
|
||||
; The default SourceDir is relative to this script and only works when iscc is
|
||||
; run with the bundle's stage folder in reach. Inno Setup 6 is required:
|
||||
; https://jrsoftware.org/isinfo.php
|
||||
;
|
||||
; Per-user install: no UAC, no Program Files, data stays in
|
||||
; %LOCALAPPDATA%\Luminary\data and is kept on uninstall.
|
||||
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "0.5.0"
|
||||
#endif
|
||||
#ifndef Launcher
|
||||
; Luminary.vbs for the PowerShell launcher build, Luminary.exe for the Go one.
|
||||
#define Launcher "Luminary.vbs"
|
||||
#endif
|
||||
#ifndef SourceDir
|
||||
#define SourceDir "stage\Luminary"
|
||||
#endif
|
||||
|
||||
#define AppName "Luminary"
|
||||
#define AppPublisher "Maple Street"
|
||||
#define AppURL "https://git.maple-street.net/bhursey/luminary"
|
||||
|
||||
[Setup]
|
||||
AppId={{6E1B4C1E-8D6B-4F2E-9E3B-2C7A5D9F4A11}
|
||||
AppName={#AppName}
|
||||
AppVersion={#AppVersion}
|
||||
AppPublisher={#AppPublisher}
|
||||
AppPublisherURL={#AppURL}
|
||||
DefaultDirName={localappdata}\Programs\{#AppName}
|
||||
DefaultGroupName={#AppName}
|
||||
DisableProgramGroupPage=yes
|
||||
PrivilegesRequired=lowest
|
||||
ArchitecturesAllowed=x64compatible
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
OutputDir=installer-output
|
||||
OutputBaseFilename=Luminary-{#AppVersion}-win-x64-setup
|
||||
Compression=lzma2/max
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
UninstallDisplayName={#AppName}
|
||||
SetupIconFile={#SourceDir}\Luminary.ico
|
||||
; The uninstaller must not delete the catalog in %LOCALAPPDATA%\Luminary\data;
|
||||
; the data folder lives outside {app} on purpose.
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "Create a desktop shortcut"; GroupDescription: "Shortcuts:"; Flags: checkedonce
|
||||
Name: "startup"; Description: "Start Luminary when I sign in"; GroupDescription: "Startup:"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
; recurses into app\, node_modules\, logs placeholders and the launcher files.
|
||||
Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
|
||||
|
||||
[Icons]
|
||||
Name: "{group}\{#AppName}"; Filename: "{app}\{#Launcher}"; WorkingDir: "{app}"; IconFilename: "{app}\Luminary.ico"
|
||||
Name: "{group}\Stop {#AppName}"; Filename: "{app}\Stop Luminary.cmd"; WorkingDir: "{app}"; IconFilename: "{app}\Luminary.ico"
|
||||
Name: "{group}\{#AppName} data folder"; Filename: "%LOCALAPPDATA%\Luminary\data"
|
||||
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#Launcher}"; WorkingDir: "{app}"; Tasks: desktopicon; IconFilename: "{app}\Luminary.ico"
|
||||
|
||||
[Registry]
|
||||
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; \
|
||||
ValueName: "Luminary"; ValueData: """{app}\{#Launcher}"""; Flags: uninsdeletevalue; Tasks: startup
|
||||
|
||||
[Run]
|
||||
Filename: "{app}\{#Launcher}"; Description: "Start Luminary now"; Flags: nowait postinstall skipifsilent
|
||||
|
||||
[UninstallDelete]
|
||||
; Remove the program folder and its logs/runtime file. Never the data folder.
|
||||
Type: filesandordirs; Name: "{app}"
|
||||
|
||||
[Code]
|
||||
procedure CurStepChanged(CurStep: TSetupStep);
|
||||
begin
|
||||
if CurStep = ssPostInstall then
|
||||
begin
|
||||
// The data folder is created by the launcher on first start; tell the user
|
||||
// where it is so the "uninstall keeps my catalog" promise is obvious.
|
||||
MsgBox('Luminary stores its catalog in:' + #13#10 +
|
||||
ExpandConstant('{localappdata}') + '\Luminary\data' + #13#10#13#10 +
|
||||
'It is not removed when you uninstall. Back it up by copying that folder '
|
||||
+ 'while Luminary is stopped.', mbInformation, MB_OK);
|
||||
end;
|
||||
end;
|
||||
@@ -0,0 +1,384 @@
|
||||
# Windows launcher design
|
||||
|
||||
The launcher is not part of the app: it only chooses a port, sets environment
|
||||
variables the server already reads, starts `node.exe`, and gets the user to the
|
||||
browser. Nothing here requires a change to `server/` or `src/`.
|
||||
|
||||
Two implementations ship from the same rules:
|
||||
|
||||
| File | Built when | Process lifetime | Console |
|
||||
| --- | --- | --- | --- |
|
||||
| `Luminary.ps1` + `Luminary.cmd` / `Luminary.vbs` | always (no toolchain) | launcher exits after the browser opens, node keeps running | none via `.vbs`, brief via `.cmd` |
|
||||
| `go/main.go` → `Luminary.exe` | a Go toolchain is present (`--launcher go`, or automatically under `windows/Dockerfile`) | launcher stays alive, removes its state file when the server exits | none (`-H windowsgui`) |
|
||||
|
||||
`Luminary.ps1` is always included because `Stop Luminary.cmd` calls it in both
|
||||
modes.
|
||||
|
||||
## Bundle layout the launcher assumes
|
||||
|
||||
```
|
||||
Luminary\
|
||||
node.exe
|
||||
Luminary.exe | Luminary.cmd / Luminary.vbs
|
||||
Luminary.ps1
|
||||
Stop Luminary.cmd
|
||||
runtime.json (created at run time)
|
||||
logs\server.out.log
|
||||
logs\server.err.log
|
||||
logs\launcher.log (Go launcher only)
|
||||
app\server\index.mjs
|
||||
app\dist\
|
||||
app\node_modules\
|
||||
```
|
||||
|
||||
`root` is the folder containing the launcher executable/script, never the
|
||||
current working directory, so shortcuts and "Run as administrator" behave the
|
||||
same.
|
||||
|
||||
## 1. Single instance
|
||||
|
||||
There is no mutex and no named object. The state file `runtime.json` records
|
||||
`{ pid, port, url, data, started }`, and **health is the liveness test**:
|
||||
|
||||
```
|
||||
runtime.json exists
|
||||
└─ GET http://127.0.0.1:<port>/api/health == 200 ?
|
||||
yes → open the browser on that URL, exit 0 (do not start a second server)
|
||||
no → stale entry: start a new server and overwrite runtime.json
|
||||
```
|
||||
|
||||
Why not check the PID: Windows reuses PIDs, and `os.FindProcess`/`Get-Process`
|
||||
can succeed for an unrelated process. A health response from the recorded port
|
||||
also proves the port belongs to *this* server instance.
|
||||
|
||||
Why not a lock file: a crashed server must not lock the user out. The health
|
||||
probe self-heals in one request.
|
||||
|
||||
A second launch while the first server is still booting waits for it instead of
|
||||
racing:
|
||||
|
||||
```
|
||||
runtime.json pid is alive but health is not up yet
|
||||
└─ poll /api/health for up to 120 s
|
||||
ok → open the browser, exit 0 (no second server, no second port)
|
||||
dead → that boot crashed; fall through and start a fresh server
|
||||
alive but still unhealthy after 120 s → dialog with the log location, exit 1
|
||||
```
|
||||
|
||||
The PID is only used to ask "is a boot in progress?", never as proof of life on
|
||||
its own: health still decides whether the recorded server is usable. Two
|
||||
launches landing within the same millisecond can both pass the check before
|
||||
either writes `runtime.json`; they then bind different ports and both serve the
|
||||
same catalog (SQLite WAL tolerates that). A mutex with stale-lock recovery would
|
||||
close that window, at the cost of a failure mode where a crashed boot locks the
|
||||
user out; for a desktop launcher a second browser tab is the better trade.
|
||||
|
||||
## 2. Port policy
|
||||
|
||||
- Preference order: `8787`, then `8788` … `8887` (100 candidates).
|
||||
- A port is taken if a `TcpListener` cannot bind it on `127.0.0.1`
|
||||
(PowerShell) / `net.Listen("tcp", "127.0.0.1:<port>")` (Go).
|
||||
- The chosen port is passed as `PORT`; the server already reads it
|
||||
(`server/config.mjs`), and the browser URL is built from the same value.
|
||||
- Ports are never inherited from the environment: a stale `PORT` exported by a
|
||||
shell must not make the launcher open the wrong URL.
|
||||
- **Loopback only:** `HOST=127.0.0.1` avoids the Windows Firewall prompt and the
|
||||
app is a single-user desktop install. For LAN proofing galleries the user sets
|
||||
`HOST=0.0.0.0` in the environment before starting, or edits `Luminary.ps1` —
|
||||
documented, not the default.
|
||||
|
||||
## 3. Data directory
|
||||
|
||||
Precedence, first match wins:
|
||||
|
||||
1. `LUMINARY_DATA` — already exported (a power user or an installer can pin it).
|
||||
2. `%LOCALAPPDATA%\Luminary\data`.
|
||||
3. `%USERPROFILE%\AppData\Local\Luminary\data` if `LOCALAPPDATA` is empty.
|
||||
|
||||
Never inside `app\`: an update replaces `app\` wholesale, and `%ProgramFiles%`
|
||||
is read-only for a non-admin user. The launcher creates the directory with
|
||||
`MkdirAll`/`New-Item -Force` before starting the server; the server also creates
|
||||
it, but a clear write failure from the launcher is a better error than a stack
|
||||
trace in a hidden log.
|
||||
|
||||
The folder holds the SQLite catalog (plus `-wal`/`-shm`), `secret.key` and all
|
||||
image folders. Backups copy this folder while the server is stopped.
|
||||
|
||||
When the bundle folder is not writable (write-protected USB, `%ProgramFiles%`
|
||||
for a non-admin user) two things move into the data folder: `runtime.json` and
|
||||
the `logs` folder. The launcher probes the bundle folder with a throwaway file
|
||||
before choosing, so checklist case 6 still starts.
|
||||
|
||||
## 4. Environment contract
|
||||
|
||||
Only variables the server already understands are set:
|
||||
|
||||
| Variable | Value |
|
||||
| --- | --- |
|
||||
| `PORT` | chosen port |
|
||||
| `HOST` | `127.0.0.1` |
|
||||
| `NODE_ENV` | `production` |
|
||||
| `LUMINARY_DATA` | resolved data directory |
|
||||
|
||||
`LUMINARY_INVITE`, SMTP, quota and bridge settings are left alone; they are
|
||||
admin-editable in the UI or set by a power user in the environment.
|
||||
|
||||
The child inherits the rest of the environment (`Start-Process` and
|
||||
`cmd.Env = append(os.Environ(), …)`).
|
||||
|
||||
## 5. Start and health wait
|
||||
|
||||
```
|
||||
create data dir → create log dir → pick port → spawn node.exe (hidden)
|
||||
→ write runtime.json
|
||||
→ poll /api/health every 700 ms, up to 120 s
|
||||
ok → open http://127.0.0.1:<port> and return
|
||||
fail → print/record the last 20 lines of stderr, kill the child,
|
||||
remove runtime.json, exit 1
|
||||
```
|
||||
|
||||
- 120 s covers a Defender scan of `node.exe` plus `libraw.wasm` on a cold boot.
|
||||
- The poll interval is short enough that a warm start feels instant (usually the
|
||||
second or third attempt).
|
||||
- The PowerShell launcher checks `$process.HasExited` first, so a crash reports
|
||||
the log instead of waiting the full timeout.
|
||||
- The browser is opened only after health succeeds; opening earlier shows a
|
||||
connection error on slow machines.
|
||||
|
||||
Logs are append-only: `logs\server.out.log` and `logs\server.err.log` from the
|
||||
child, `logs\launcher.log` from the Go launcher. They fall back to
|
||||
`<data>\logs` when the bundle folder is read-only. Rotation is not implemented;
|
||||
the files are small (startup lines plus request errors) and a support note says
|
||||
they can be deleted while the server is stopped.
|
||||
|
||||
## 6. Stop
|
||||
|
||||
`Stop Luminary.cmd` → `Luminary.ps1 -Stop`:
|
||||
|
||||
1. Read `runtime.json`; if absent or the process is gone → "not running"
|
||||
(exit 0, idempotent).
|
||||
2. `taskkill /PID <pid> /T /F` — `/T` also covers any helper processes, `/F`
|
||||
because the server has no shutdown hook to answer a polite close.
|
||||
3. Delete `runtime.json`.
|
||||
|
||||
Because `runtime.json` is written only after a successful spawn, Stop never
|
||||
kills an unrelated process **unless** the file is stale and the PID has been
|
||||
reused. The window is tiny; the health probe in the start path avoids creating
|
||||
that state, and a support note explains deleting `runtime.json` by hand.
|
||||
|
||||
With the Go launcher, Stop kills the child, `cmd.Wait()` returns, the launcher
|
||||
removes `runtime.json` itself and exits 0. The launcher never outlives the
|
||||
server.
|
||||
|
||||
## 7. Status
|
||||
|
||||
`Luminary.ps1 -Status` prints PID, URL, health state and the data directory.
|
||||
Useful for support without opening Task Manager.
|
||||
|
||||
## 8. Upgrade flow
|
||||
|
||||
1. `Stop Luminary.cmd`.
|
||||
2. Replace `app\` (and `node.exe` if the bundle ships a newer runtime) from the
|
||||
new bundle. Keep `runtime.json`, `logs\` and the data folder.
|
||||
3. Start again. The server migrates the SQLite schema on boot.
|
||||
|
||||
The launcher does not version-check; `version.txt` in the bundle root records
|
||||
the Luminary version, commit and Node version for support.
|
||||
|
||||
## 9. Incomplete bundle diagnostics
|
||||
|
||||
The launcher is a few files next to a large `app\` tree, so the three realistic
|
||||
failure modes are a zip that was opened instead of extracted, an antivirus that
|
||||
quarantined `node.exe`, and a launcher copied out of the source tree. All three
|
||||
look identical from the outside ("node.exe is missing"), so the launcher checks
|
||||
`node.exe`, `app\server\index.mjs` and `app\dist\index.html`, treats zero-byte
|
||||
files as missing, and prints the fix for each cause:
|
||||
|
||||
| Entry point | Behaviour |
|
||||
| --- | --- |
|
||||
| `Luminary.cmd -Verify` | prints the bundle path, each required file with its size, the version from `version.txt`, and exits `3` on a problem |
|
||||
| `Luminary.cmd` | same diagnosis on stderr/stdout, then exits `3` instead of pretending to start |
|
||||
| `Luminary.vbs` | a message box before PowerShell is even started, because a silent exit would look like nothing happened |
|
||||
| `Luminary.exe` | a `MessageBoxW` dialog (it is linked with `-H windowsgui`, so there is no console) and a line in `logs\launcher.log` |
|
||||
|
||||
`version.txt` records `node <version> win-x64 sha256 <hash> size <bytes>`, so the
|
||||
help text can quote the exact hash the build verified against nodejs.org, and
|
||||
the launcher can spot a truncated file by size without hashing 94 MB on every
|
||||
launch.
|
||||
|
||||
## 10. Preflight checks
|
||||
|
||||
`Test-Platform` runs before the runtime is resolved, and `-Status` prints the
|
||||
same report. It checks only what the bundle actually needs — taken from the
|
||||
shipped binaries' PE imports, not from a generic checklist:
|
||||
|
||||
| Check | Source | Result |
|
||||
| --- | --- | --- |
|
||||
| Windows 10+ | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentBuild` ≥ 10240 | blocking dialog, exit 4 |
|
||||
| 64-bit | `PROCESSOR_ARCHITECTURE` is `AMD64` or `ARM64` | blocking dialog, exit 4 |
|
||||
| Universal C Runtime | `%SystemRoot%\System32\ucrtbase.dll` | blocking dialog with the KB2999226 link |
|
||||
| free space on the data drive | `DriveInfo.AvailableFreeSpace` | note below 2 GB, blocking below 200 MB |
|
||||
| ARM64 | `PROCESSOR_ARCHITECTURE` | note: x64 emulation, slower RAW decode |
|
||||
|
||||
Why the list is this short:
|
||||
|
||||
- `node.exe` imports only system DLLs (KERNEL32, ADVAPI32, WS2_32, CRYPT32,
|
||||
USER32, …) and links the C runtime statically, so the Visual C++
|
||||
Redistributable is **not** required. Checked with `objdump -p` on the bundled
|
||||
binary.
|
||||
- `libvips-42.dll` imports the UCRT (`api-ms-win-crt-*`), which ships with
|
||||
Windows 10/11. It does not import `vcruntime140.dll` or `msvcp140.dll`.
|
||||
- The only native modules in the bundle are sharp's three files plus
|
||||
`libraw.wasm`; SQLite comes from `node:sqlite`, not a native addon.
|
||||
- PowerShell 5.1 is part of Windows 10/11, and the `.vbs` entry point checks for
|
||||
it explicitly before launching anything.
|
||||
|
||||
The launcher cannot install a Windows update, so a missing UCRT is explained
|
||||
with its KB number and URL rather than "fixed". The one artefact it can fetch
|
||||
itself is `node.exe`: `-Repair` does it, and a launch with no usable runtime
|
||||
offers the same download in a Yes/No dialog.
|
||||
|
||||
## 11. Desktop mode and the app window
|
||||
|
||||
Both launchers set `LUMINARY_LOCAL=1`; nothing else does.
|
||||
|
||||
| Behaviour | Effect |
|
||||
| --- | --- |
|
||||
| boot | `prepareLocalOwner()` creates `local@luminary` (random password, admin) when missing |
|
||||
| request with no session | `currentUser()` returns the local owner |
|
||||
| `GET /api/auth/me` | 200, so the UI never shows the signup or sign-in view |
|
||||
| `POST /api/auth/register` | 403 |
|
||||
| `POST /api/auth/login` | returns the local session, so a stale login form cannot trap the user |
|
||||
| edit/delete the local owner | 403, it is launcher-managed |
|
||||
| `HOST` not loopback | a warning at boot; the random password means there is nothing to guess |
|
||||
|
||||
The app window uses the browser already on the machine:
|
||||
|
||||
```
|
||||
msedge.exe --app=http://127.0.0.1:<port>
|
||||
--user-data-dir=%LOCALAPPDATA%\Luminary\data\window-profile
|
||||
--window-size=1500,950 --no-first-run --no-default-browser-check
|
||||
```
|
||||
|
||||
`--app` removes tabs, the address bar and the browser chrome; the separate
|
||||
profile keeps the app out of the user's normal history and bookmarks.
|
||||
|
||||
Window preference, first match wins:
|
||||
|
||||
1. `LuminaryWindow.exe` in the bundle root — a WinForms + WebView2 host with its
|
||||
own icon, taskbar entry and window state (`--url <url>`). Built from
|
||||
`launcher/webview2` with the .NET 8 SDK, published self-contained, so the
|
||||
target machine needs no .NET; it does need the WebView2 runtime, which ships
|
||||
with Windows 10/11 alongside Edge. Missing runtime → a dialog with the
|
||||
Evergreen link, not a silent exit.
|
||||
2. Edge `--app`, then Chrome `--app`.
|
||||
3. The default browser (`-Browser` / `LUMINARY_WINDOW=browser` forces this).
|
||||
|
||||
The wrapper is only a window: node stays a child of the launcher, Stop still
|
||||
uses `runtime.json`, and the browser window remains the fallback when the exe
|
||||
is absent or fails to start. A direct launch without `--url` forwards to the
|
||||
bundle launcher and exits immediately; that closes the old hole where
|
||||
double-clicking the window opened port 8787 directly and showed a login page
|
||||
(or a dead URL) because no desktop-mode server was running.
|
||||
|
||||
## 12. Runtime resolution and repair
|
||||
|
||||
Three states, checked in order:
|
||||
|
||||
| Bundled `node.exe` | Runtime used | What the user sees |
|
||||
| --- | --- | --- |
|
||||
| present, size matches the pin | `node.exe` | nothing |
|
||||
| missing, empty, or wrong size | system Node 24+ from PATH, `%ProgramFiles%\nodejs`, `%ProgramFiles(x86)%\nodejs`, `%LOCALAPPDATA%\Programs\nodejs`, `%NVM_SYMLINK%` | a warning line and one information dialog naming the path, with the repair command |
|
||||
| neither | none | error dialog listing the three causes, exit 3 |
|
||||
|
||||
The fallback is deliberately not silent: an app quietly running a different
|
||||
runtime is a support mystery, and the user should be told to run `-Repair`.
|
||||
Node below 24 is rejected because `server/denoise-worker.mjs` imports a `.ts`
|
||||
module, which needs the type-stripping runtime.
|
||||
|
||||
`-Repair` (PowerShell and `Luminary.exe -repair`) does the following:
|
||||
|
||||
1. refuses while the server is running — the file is locked, and replacing a
|
||||
runtime under a live process is wrong anyway;
|
||||
2. reads the version and hash from `version.txt`, falling back to
|
||||
`nodejs.org/dist/v<version>/SHASUMS256.txt` when the bundle predates the hash
|
||||
line;
|
||||
3. downloads to a temp file (`LUMINARY_NODE_URL` overrides the URL for a mirror
|
||||
or an air-gapped copy);
|
||||
4. hashes the download and refuses to install anything that does not match the
|
||||
pin — a corporate proxy's HTML error page never becomes `node.exe`;
|
||||
5. replaces `node.exe` atomically (`node.exe.new` + rename) and re-runs the
|
||||
bundle check.
|
||||
|
||||
## 13. Security notes
|
||||
|
||||
- Binds loopback by default; no firewall rule is needed.
|
||||
- Everything runs as the logged-in user; the installer is per-user, no UAC.
|
||||
- The launcher is unsigned, so SmartScreen may warn on first run. Signing the
|
||||
launcher (and ideally `node.exe` provenance) is a distribution task, not a
|
||||
code one.
|
||||
- The data folder is protected by normal user-profile ACLs.
|
||||
|
||||
## 14. Known limitations and phase 2
|
||||
|
||||
- **No tray icon.** Closing the browser does not stop the server; Stop is a
|
||||
shortcut. A tray build needs `Shell_NotifyIcon` (Go with Win32 calls, or C#),
|
||||
roughly a day of work, and can be swapped in without touching the app.
|
||||
- **No auto-update.** Replacing `app\` is manual. An updater would read a
|
||||
version manifest next to the release and download a zip.
|
||||
- **No service mode.** Running before login needs WinSW/NSSM and a fixed
|
||||
account/data directory; that is a different install profile, not a launcher
|
||||
change.
|
||||
- **Localhost only.** Multi-device proofing galleries need `HOST=0.0.0.0` and a
|
||||
firewall rule; that is deliberate for a default desktop install.
|
||||
|
||||
## 15. Test checklist (Windows VM, no Node installed)
|
||||
|
||||
1. Fresh double-click → data folder created, browser opens, login page loads.
|
||||
2. Second double-click → the running instance is reused and the browser opens;
|
||||
no second process, whether the first server is answering or still booting.
|
||||
3. `Stop Luminary.cmd` → process gone, `runtime.json` removed, Stop again says
|
||||
"not running".
|
||||
4. Kill node.exe in Task Manager, start again → new port if the old one is held,
|
||||
otherwise the same port, and the catalog is intact.
|
||||
5. Port 8787 occupied by another app → launcher uses 8788 and opens that URL.
|
||||
6. Read-only install folder (Program Files) with data in `%LOCALAPPDATA%` →
|
||||
starts fine (data path is outside the bundle).
|
||||
7. RAW import, denoise (proves the `.ts` worker), export — i.e. the server is
|
||||
fully functional from the bundle.
|
||||
8. Path with spaces and non-ASCII characters (e.g. `C:\Users\Zoë\Luminary`) →
|
||||
the quoted entry point and `-WorkingDirectory` still work.
|
||||
9. Power loss / hard reboot → stale `runtime.json` is ignored and replaced.
|
||||
10. Delete `node.exe`, then `Luminary.cmd -Verify` → exit code 3 and the three
|
||||
causes; `Luminary.vbs` → message box instead of a silent no-op.
|
||||
11. Run `Luminary.cmd` from inside the zip preview → the "not a complete
|
||||
bundle" message, not a missing-file crash.
|
||||
12. On a machine with Node 24 installed: delete `node.exe` → the launcher warns,
|
||||
starts on the system Node and `-Status` names that path; `-Stop` still works.
|
||||
13. Double-click `LuminaryWindow.exe` with no arguments → it exits, the bundle
|
||||
launcher starts desktop mode, and the reopened window is signed in; no login
|
||||
screen appears.
|
||||
14. On a machine with no Node: delete `node.exe` → the launch offers the 90 MB
|
||||
download; Yes installs and starts, No exits 3; `-Repair` works as well.
|
||||
15. Truncate `node.exe` (keep the first 100 kB) → `-Verify` reports `damaged`,
|
||||
and `-Repair` replaces it. A partial file is the usual antivirus outcome.
|
||||
16. `-Repair` while the server is running → refused with the stop instruction.
|
||||
17. Write-protect the bundle folder (or use `%ProgramFiles%` without admin) →
|
||||
`runtime.json` and `logs` move to the data folder and the app starts.
|
||||
18. Clean Windows 10/11 VM with no Node, no .NET and no VC++ redistributable →
|
||||
the app starts (proves the import analysis above); `-Status` reports the
|
||||
build, architecture and Node source.
|
||||
19. Windows 8.1 (if available) → the UCRT dialog with the KB2999226 link;
|
||||
Windows 7 → the "needs Windows 10 or 11" dialog, exit 4.
|
||||
20. Fresh data folder → no signup and no sign-in screen; the app is signed in
|
||||
as Local, with no account pill in the top bar and no team/admin entry.
|
||||
21. Restart → the same local account and catalog; delete the data folder →
|
||||
a fresh one with no prompt.
|
||||
22. Default launch → chromeless window, no address bar, own window size;
|
||||
`-Browser` → a normal tab.
|
||||
23. Start the server by hand with `HOST=0.0.0.0` and `LUMINARY_LOCAL=1` → the
|
||||
boot log warns that every client is the local admin.
|
||||
24. Bundle with `LuminaryWindow.exe` → native window with the Luminary icon in
|
||||
the title bar and taskbar; `Stop Luminary.cmd` still ends the server.
|
||||
25. Remove the WebView2 runtime (or use an image without it) → the native
|
||||
window shows the download link instead of disappearing.
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
rem Start Luminary and open it in the default browser.
|
||||
rem The server keeps running in the background; use "Stop Luminary.cmd" to stop it.
|
||||
rem
|
||||
rem Luminary.cmd start
|
||||
rem Luminary.cmd -Verify list the files the bundle must contain
|
||||
rem Luminary.cmd -Status report pid, url, runtime and data folder
|
||||
rem Luminary.cmd -Repair download node.exe again and verify its sha256
|
||||
rem Luminary.cmd -Stop stop the server started from this folder
|
||||
rem Luminary.cmd -Browser open a normal browser tab instead of the app window
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" %*
|
||||
if errorlevel 1 pause
|
||||
|
After Width: | Height: | Size: 128 KiB |
@@ -0,0 +1,648 @@
|
||||
<#
|
||||
Luminary launcher (PowerShell).
|
||||
|
||||
This is the no-toolchain launcher: it ships in every bundle and is what
|
||||
Luminary.exe replaces when a Go build is available. It owns the three things
|
||||
the server deliberately does not do for itself:
|
||||
|
||||
1. Pick a free loopback port and pass it as PORT.
|
||||
2. Start node.exe hidden with LUMINARY_DATA outside the bundle.
|
||||
3. Wait for /api/health before opening the browser.
|
||||
|
||||
Usage:
|
||||
Luminary.ps1 start (or reuse) the server and open the browser
|
||||
Luminary.ps1 -Stop stop the server started from this folder
|
||||
Luminary.ps1 -Status report what is running and where the data lives
|
||||
Luminary.ps1 -Verify list the files the bundle must contain
|
||||
Luminary.ps1 -Repair re-download node.exe and check it against version.txt
|
||||
Luminary.ps1 -Browser open a normal browser tab instead of the app window
|
||||
|
||||
Runtime resolution: the bundled node.exe is always preferred. If an antivirus
|
||||
removed it, a system Node 24+ is used instead so the app still starts, and the
|
||||
launcher says so; -Repair restores the pinned runtime.
|
||||
|
||||
State is kept in runtime.json next to this script; logs go to logs\ (or to
|
||||
%LOCALAPPDATA%\Luminary\data\logs when the bundle is on read-only media).
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Stop,
|
||||
[switch]$Status,
|
||||
[switch]$Verify,
|
||||
[switch]$Repair,
|
||||
[switch]$Browser
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$appDir = Join-Path $root 'app'
|
||||
$nodeExe = Join-Path $root 'node.exe'
|
||||
$entry = Join-Path $appDir 'server\index.mjs'
|
||||
$uiFile = Join-Path $appDir 'dist\index.html'
|
||||
$versionFile = Join-Path $root 'version.txt'
|
||||
$logDir = Join-Path $root 'logs'
|
||||
$runtimeFile = $null # resolved below: it moves to the data folder on read-only media
|
||||
$firstPort = 8787
|
||||
$lastPort = 8887
|
||||
$minNodeMajor = 24
|
||||
|
||||
function Show-Dialog([string]$text, [string]$icon) {
|
||||
try {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$kind = [System.Windows.Forms.MessageBoxIcon]::Information
|
||||
if ($icon -eq 'Error') { $kind = [System.Windows.Forms.MessageBoxIcon]::Error }
|
||||
[void][System.Windows.Forms.MessageBox]::Show($text, 'Luminary', [System.Windows.Forms.MessageBoxButtons]::OK, $kind)
|
||||
} catch {
|
||||
Write-Host $text
|
||||
}
|
||||
}
|
||||
|
||||
function Show-ErrorDialog([string]$text) {
|
||||
# The .vbs entry point runs PowerShell hidden, so a console-only failure would
|
||||
# look like nothing happened.
|
||||
Show-Dialog $text 'Error'
|
||||
}
|
||||
|
||||
function Show-Question([string]$text) {
|
||||
try {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$answer = [System.Windows.Forms.MessageBox]::Show($text, 'Luminary', [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)
|
||||
return ($answer -eq [System.Windows.Forms.DialogResult]::Yes)
|
||||
} catch {
|
||||
Write-Host $text
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Get-DataDir {
|
||||
if ($env:LUMINARY_DATA) { return $env:LUMINARY_DATA }
|
||||
$base = $env:LOCALAPPDATA
|
||||
if (-not $base) {
|
||||
if ($env:USERPROFILE) {
|
||||
$base = Join-Path $env:USERPROFILE 'AppData\Local'
|
||||
} else {
|
||||
# Neither variable is set: a stripped environment (service account, CI)
|
||||
# rather than a normal desktop login. Never Join-Path a null.
|
||||
$base = [System.IO.Path]::GetTempPath()
|
||||
}
|
||||
}
|
||||
return (Join-Path $base 'Luminary\data')
|
||||
}
|
||||
|
||||
function Read-Runtime {
|
||||
if (-not (Test-Path -LiteralPath $runtimeFile)) { return $null }
|
||||
try { return Get-Content -Raw -LiteralPath $runtimeFile | ConvertFrom-Json } catch { return $null }
|
||||
}
|
||||
|
||||
function Test-Health([int]$port) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri ("http://127.0.0.1:{0}/api/health" -f $port)
|
||||
return ($response.StatusCode -eq 200)
|
||||
} catch { return $false }
|
||||
}
|
||||
|
||||
function Test-Process([int]$processId) {
|
||||
try { return $null -ne (Get-Process -Id $processId -ErrorAction Stop) } catch { return $false }
|
||||
}
|
||||
|
||||
function Test-PortFree([int]$port) {
|
||||
$listener = $null
|
||||
try {
|
||||
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, $port)
|
||||
$listener.Start()
|
||||
return $true
|
||||
} catch {
|
||||
return $false
|
||||
} finally {
|
||||
if ($listener) { $listener.Stop() }
|
||||
}
|
||||
}
|
||||
|
||||
function Find-Port {
|
||||
for ($port = $firstPort; $port -le $lastPort; $port++) {
|
||||
if (Test-PortFree $port) { return $port }
|
||||
}
|
||||
throw ("No free TCP port between {0} and {1}." -f $firstPort, $lastPort)
|
||||
}
|
||||
|
||||
function Open-Browser([string]$url) {
|
||||
try { Start-Process $url | Out-Null } catch { Write-Host ("Open {0} in a browser." -f $url) }
|
||||
}
|
||||
|
||||
# Edge is part of Windows 10/11, so a chromeless app window costs no extra
|
||||
# runtime. Chrome is the second choice; anything else falls back to a tab.
|
||||
function Find-AppWindowBrowser {
|
||||
$candidates = @()
|
||||
if (${env:ProgramFiles(x86)}) {
|
||||
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe')
|
||||
}
|
||||
if ($env:ProgramFiles) {
|
||||
$candidates += (Join-Path $env:ProgramFiles 'Microsoft\Edge\Application\msedge.exe')
|
||||
}
|
||||
if ($env:LOCALAPPDATA) {
|
||||
$candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\Application\msedge.exe')
|
||||
$candidates += (Join-Path $env:LOCALAPPDATA 'Google\Chrome\Application\chrome.exe')
|
||||
}
|
||||
if ($env:ProgramFiles) {
|
||||
$candidates += (Join-Path $env:ProgramFiles 'Google\Chrome\Application\chrome.exe')
|
||||
}
|
||||
if (${env:ProgramFiles(x86)}) {
|
||||
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Google\Chrome\Application\chrome.exe')
|
||||
}
|
||||
foreach ($candidate in $candidates) {
|
||||
if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --app gives a window with no tabs and no address bar, in its own profile, so
|
||||
# it reads as a desktop app rather than a web page. -Browser opts out.
|
||||
function Open-App([string]$url) {
|
||||
if ($Browser -or $env:LUMINARY_WINDOW -eq 'browser') {
|
||||
Open-Browser $url
|
||||
return
|
||||
}
|
||||
# A native WebView2 host, when the bundle ships one, is the real app window:
|
||||
# its own icon, no browser branding at all.
|
||||
$native = Join-Path $root 'LuminaryWindow.exe'
|
||||
if (Test-Path -LiteralPath $native) {
|
||||
try {
|
||||
Start-Process -FilePath $native -ArgumentList @('--url', $url) | Out-Null
|
||||
return
|
||||
} catch {
|
||||
# fall through to the browser window
|
||||
}
|
||||
}
|
||||
$exe = Find-AppWindowBrowser
|
||||
if (-not $exe) {
|
||||
Open-Browser $url
|
||||
return
|
||||
}
|
||||
$profile = Join-Path (Get-DataDir) 'window-profile'
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $profile | Out-Null
|
||||
Start-Process -FilePath $exe -ArgumentList @(
|
||||
"--app=$url",
|
||||
"--user-data-dir=$profile",
|
||||
'--window-size=1500,950',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-features=Translate'
|
||||
) | Out-Null
|
||||
} catch {
|
||||
Open-Browser $url
|
||||
}
|
||||
}
|
||||
|
||||
function Get-WindowsBuild {
|
||||
try {
|
||||
$current = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop
|
||||
return [int]$current.CurrentBuild
|
||||
} catch { return 0 }
|
||||
}
|
||||
|
||||
# What a customer machine actually needs. Everything else is in the bundle:
|
||||
# node.exe ships with it (and -Repair re-downloads it), libvips needs only the
|
||||
# Universal C Runtime that Windows 10/11 already has, and no admin rights are
|
||||
# involved. Verified against the PE imports of node.exe and libvips-42.dll.
|
||||
function Test-Platform {
|
||||
$problems = @()
|
||||
$notes = @()
|
||||
|
||||
$build = Get-WindowsBuild
|
||||
if ($build -gt 0 -and $build -lt 10240) {
|
||||
$problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build)
|
||||
}
|
||||
|
||||
$arch = $env:PROCESSOR_ARCHITECTURE
|
||||
if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') {
|
||||
$problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch)
|
||||
} elseif ($arch -eq 'ARM64') {
|
||||
$notes += 'ARM64 Windows runs the x64 runtime under emulation, so RAW decoding is slower.'
|
||||
}
|
||||
|
||||
if ($env:SystemRoot -and -not (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'System32\ucrtbase.dll'))) {
|
||||
$problems += 'The Universal C Runtime is missing (Windows 8.1 without KB2999226). Install it from support.microsoft.com/help/2999226, or use Windows 10/11.'
|
||||
}
|
||||
|
||||
# ~130 MB unpacked, plus room for catalogs and previews that grow over time.
|
||||
$dataDir = Get-DataDir
|
||||
$qualifier = $null
|
||||
try { $qualifier = Split-Path -Qualifier $dataDir -ErrorAction Stop } catch { }
|
||||
if ($qualifier) {
|
||||
try {
|
||||
$drive = New-Object System.IO.DriveInfo -ArgumentList $qualifier
|
||||
$freeGb = [math]::Round($drive.AvailableFreeSpace / 1GB, 1)
|
||||
if ($drive.AvailableFreeSpace -lt 200MB) {
|
||||
$problems += ("The data drive has only {0} GB free; Luminary needs about 0.25 GB to start." -f $freeGb)
|
||||
} elseif ($drive.AvailableFreeSpace -lt 2GB) {
|
||||
$notes += ("Only {0} GB free on the data drive; catalogs and previews grow from there." -f $freeGb)
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
|
||||
return @{ ok = ($problems.Count -eq 0); problems = $problems; notes = $notes }
|
||||
}
|
||||
|
||||
# --- runtime resolution -------------------------------------------------------
|
||||
|
||||
function Read-NodePin {
|
||||
$pin = @{ version = $null; sha256 = $null; size = [int64]0 }
|
||||
if (-not (Test-Path -LiteralPath $versionFile)) { return $pin }
|
||||
$line = Get-Content -LiteralPath $versionFile |
|
||||
Where-Object { $_ -match '^node\s+v?\d+\.\d+\.\d+\s+win-x64' } |
|
||||
Select-Object -First 1
|
||||
if (-not $line) { return $pin }
|
||||
if ($line -match '^node\s+v?(\d+\.\d+\.\d+)') { $pin.version = $Matches[1] }
|
||||
if ($line -match 'sha256\s+([0-9a-f]{64})') { $pin.sha256 = $Matches[1] }
|
||||
if ($line -match 'size\s+(\d+)') { $pin.size = [int64]$Matches[1] }
|
||||
return $pin
|
||||
}
|
||||
|
||||
function Get-SystemNode([string]$exe) {
|
||||
if (-not $exe) { return $null }
|
||||
if (-not (Test-Path -LiteralPath $exe)) { return $null }
|
||||
try { $raw = & $exe '--version' 2>$null } catch { return $null }
|
||||
if (-not $raw) { return $null }
|
||||
$raw = "$raw".Trim()
|
||||
if ($raw -notmatch '^v?(\d+)\.') { return $null }
|
||||
if ([int]$Matches[1] -lt $minNodeMajor) { return $null }
|
||||
return $raw
|
||||
}
|
||||
|
||||
# The bundled runtime wins; a system Node 24+ is a fallback, never a preference.
|
||||
function Resolve-Node {
|
||||
if (Test-Path -LiteralPath $nodeExe) {
|
||||
$info = Get-Item -LiteralPath $nodeExe
|
||||
$pin = Read-NodePin
|
||||
$intact = $info.Length -gt 0
|
||||
# A pinned size catches a truncated file that antivirus left behind; the
|
||||
# hash itself is only checked by -Verify and -Repair.
|
||||
if ($intact -and $pin.size -gt 0 -and $info.Length -ne $pin.size) { $intact = $false }
|
||||
if ($intact) { return @{ path = $nodeExe; version = 'bundled'; system = $false } }
|
||||
}
|
||||
|
||||
$candidates = @()
|
||||
$onPath = Get-Command node.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($onPath) { $candidates += $onPath.Source }
|
||||
if ($env:ProgramFiles) { $candidates += (Join-Path $env:ProgramFiles 'nodejs\node.exe') }
|
||||
if (${env:ProgramFiles(x86)}) { $candidates += (Join-Path ${env:ProgramFiles(x86)} 'nodejs\node.exe') }
|
||||
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Programs\nodejs\node.exe') }
|
||||
if ($env:NVM_SYMLINK) { $candidates += (Join-Path $env:NVM_SYMLINK 'node.exe') }
|
||||
|
||||
$seen = @{}
|
||||
foreach ($candidate in $candidates) {
|
||||
if (-not $candidate) { continue }
|
||||
$key = $candidate.ToLowerInvariant()
|
||||
if ($seen.ContainsKey($key)) { continue }
|
||||
$seen[$key] = $true
|
||||
$version = Get-SystemNode $candidate
|
||||
if ($version) { return @{ path = $candidate; version = $version; system = $true } }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- repair -------------------------------------------------------------------
|
||||
|
||||
function Get-PublishedHash([string]$version) {
|
||||
$uri = "https://nodejs.org/dist/v$version/SHASUMS256.txt"
|
||||
$text = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri $uri).Content
|
||||
foreach ($line in ($text -split "`n")) {
|
||||
$parts = $line.Trim() -split '\s+'
|
||||
if ($parts.Count -ge 2 -and $parts[1] -eq 'win-x64/node.exe') { return $parts[0].ToLowerInvariant() }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Repair-Node {
|
||||
$pin = Read-NodePin
|
||||
if (-not $pin.version) {
|
||||
throw "version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead."
|
||||
}
|
||||
|
||||
$expected = $pin.sha256
|
||||
if (-not $expected) {
|
||||
Write-Host ("Fetching the published checksum for node v{0}..." -f $pin.version)
|
||||
$expected = Get-PublishedHash $pin.version
|
||||
}
|
||||
if (-not $expected) {
|
||||
throw "No SHA-256 is available for node v$($pin.version), so the download cannot be verified. Refusing to install it."
|
||||
}
|
||||
|
||||
$url = $env:LUMINARY_NODE_URL
|
||||
if (-not $url) { $url = "https://nodejs.org/dist/v$($pin.version)/win-x64/node.exe" }
|
||||
|
||||
Write-Host ("Downloading {0}" -f $url)
|
||||
$temp = Join-Path ([System.IO.Path]::GetTempPath()) ("luminary-node-{0}.exe" -f [guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
Invoke-WebRequest -UseBasicParsing -TimeoutSec 600 -Uri $url -OutFile $temp
|
||||
$actual = (Get-FileHash -LiteralPath $temp -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
if ($actual -ne $expected.ToLowerInvariant()) {
|
||||
throw ("The downloaded node.exe does not match the expected checksum (got {0}, want {1}). Nothing was changed." -f $actual, $expected)
|
||||
}
|
||||
if (Test-Path -LiteralPath $nodeExe) {
|
||||
try { (Get-Item -LiteralPath $nodeExe).IsReadOnly = $false } catch { }
|
||||
}
|
||||
Move-Item -LiteralPath $temp -Destination $nodeExe -Force
|
||||
Write-Host ("node.exe restored: v{0}, sha256 {1}" -f $pin.version, $actual)
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
|
||||
# --- bundle checks ------------------------------------------------------------
|
||||
|
||||
# Prints a line for every file the bundle needs and returns $true when all are
|
||||
# present and non-empty. A zero-byte file is what an antivirus or a half-done
|
||||
# extraction leaves behind, so it is treated as missing.
|
||||
function Test-Bundle {
|
||||
$ok = $true
|
||||
$required = @(
|
||||
@{ Name = 'app\server\index.mjs'; Path = $entry },
|
||||
@{ Name = 'app\dist\index.html'; Path = $uiFile }
|
||||
)
|
||||
foreach ($item in $required) {
|
||||
if (-not (Test-Path -LiteralPath $item.Path)) {
|
||||
Write-Host (" missing {0}" -f $item.Name)
|
||||
$ok = $false
|
||||
} elseif ((Get-Item -LiteralPath $item.Path).Length -eq 0) {
|
||||
Write-Host (" empty {0} ({1})" -f $item.Name, $item.Path)
|
||||
$ok = $false
|
||||
}
|
||||
}
|
||||
return $ok
|
||||
}
|
||||
|
||||
function Write-BundleHelp {
|
||||
$pin = Read-NodePin
|
||||
Write-Host ''
|
||||
Write-Host 'This folder is not a complete Luminary bundle. The usual causes:'
|
||||
Write-Host ''
|
||||
Write-Host ' 1. The zip was opened, not extracted. Close it, right-click the zip,'
|
||||
Write-Host ' choose "Extract All...", then run Luminary.cmd (or Luminary.vbs)'
|
||||
Write-Host ' from the extracted Luminary folder. A file started from inside the'
|
||||
Write-Host ' zip preview is copied out on its own, without node.exe or app\.'
|
||||
Write-Host ''
|
||||
Write-Host ' 2. Antivirus or SmartScreen removed node.exe after extraction.'
|
||||
Write-Host ' Run "Luminary.cmd -Repair" to download it again and verify it'
|
||||
Write-Host ' against the checksum in version.txt.'
|
||||
if ($pin.sha256) { Write-Host (' expected sha256: {0}' -f $pin.sha256) }
|
||||
Write-Host ''
|
||||
Write-Host ' 3. This is the source checkout, not a bundle. In the repository run'
|
||||
Write-Host ' "node windows/build.mjs" and use the zip it prints.'
|
||||
Write-Host ''
|
||||
Write-Host 'Run "Luminary.cmd -Verify" to list every file the launcher needs.'
|
||||
}
|
||||
|
||||
function Get-LogDir([string]$dataDir) {
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
|
||||
return $logDir
|
||||
} catch {
|
||||
# Read-only media (USB stick with the write-protect switch, a network share
|
||||
# the user cannot write): keep the logs with the data instead of failing.
|
||||
$fallback = Join-Path $dataDir 'logs'
|
||||
New-Item -ItemType Directory -Force -Path $fallback | Out-Null
|
||||
Write-Host ("Logs go to {0} (the bundle folder is not writable)." -f $fallback)
|
||||
return $fallback
|
||||
}
|
||||
}
|
||||
|
||||
# The state file lives in the bundle folder so a copied bundle is self-contained.
|
||||
# On read-only media (write-protected USB, Program Files for a non-admin user) it
|
||||
# moves next to the data, which is always writable.
|
||||
$runtimeFile = Join-Path $root 'runtime.json'
|
||||
try {
|
||||
$probe = Join-Path $root ('.write-test-{0}' -f [guid]::NewGuid().ToString('N'))
|
||||
[System.IO.File]::WriteAllText($probe, '')
|
||||
Remove-Item -LiteralPath $probe -Force
|
||||
} catch {
|
||||
$runtimeFile = Join-Path (Get-DataDir) 'runtime.json'
|
||||
}
|
||||
|
||||
# --- commands -----------------------------------------------------------------
|
||||
|
||||
if ($Verify) {
|
||||
Write-Host ("Bundle: {0}" -f $root)
|
||||
$complete = Test-Bundle
|
||||
$pin = Read-NodePin
|
||||
if (-not (Test-Path -LiteralPath $nodeExe)) {
|
||||
Write-Host ' missing node.exe'
|
||||
$complete = $false
|
||||
} else {
|
||||
$nodeInfo = Get-Item -LiteralPath $nodeExe
|
||||
if ($nodeInfo.Length -eq 0) {
|
||||
Write-Host ' empty node.exe'
|
||||
$complete = $false
|
||||
} elseif ($pin.size -gt 0 -and $nodeInfo.Length -ne $pin.size) {
|
||||
Write-Host (" damaged node.exe ({0:N0} bytes, expected {1:N0})" -f $nodeInfo.Length, $pin.size)
|
||||
$complete = $false
|
||||
}
|
||||
}
|
||||
if ($complete) {
|
||||
foreach ($file in @($nodeExe, $entry, $uiFile)) {
|
||||
$shown = $file.Replace($root + '\', '')
|
||||
Write-Host (" ok {0} ({1:N0} bytes)" -f $shown, (Get-Item -LiteralPath $file).Length)
|
||||
}
|
||||
if ($pin.version) { Write-Host ("Node: v{0} (pinned)" -f $pin.version) }
|
||||
Write-Host 'The bundle is complete.'
|
||||
exit 0
|
||||
}
|
||||
Write-BundleHelp
|
||||
exit 3
|
||||
}
|
||||
|
||||
$runtime = Read-Runtime
|
||||
$running = $runtime -and (Test-Process ([int]$runtime.pid))
|
||||
|
||||
if ($Repair) {
|
||||
if ($running) {
|
||||
Write-Host 'Luminary is running. Stop it first: "Luminary.cmd -Stop".'
|
||||
exit 1
|
||||
}
|
||||
try {
|
||||
Repair-Node
|
||||
} catch {
|
||||
Write-Host ''
|
||||
Write-Host ("Repair failed: {0}" -f $_.Exception.Message)
|
||||
Show-ErrorDialog ("node.exe could not be restored.`n`n" + $_.Exception.Message)
|
||||
exit 1
|
||||
}
|
||||
Write-Host ''
|
||||
if (Test-Bundle) {
|
||||
Write-Host 'The bundle is complete and ready to run.'
|
||||
exit 0
|
||||
}
|
||||
Write-BundleHelp
|
||||
exit 3
|
||||
}
|
||||
|
||||
if ($Status) {
|
||||
if ($running) {
|
||||
$reachable = Test-Health ([int]$runtime.port)
|
||||
$state = 'not answering yet'
|
||||
if ($reachable) { $state = 'ok' }
|
||||
Write-Host ("Luminary is running (pid {0}) at {1}; health {2}." -f $runtime.pid, $runtime.url, $state)
|
||||
} else {
|
||||
Write-Host 'Luminary is not running.'
|
||||
}
|
||||
$platform = Test-Platform
|
||||
Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), $env:PROCESSOR_ARCHITECTURE)
|
||||
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
|
||||
foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) }
|
||||
$node = Resolve-Node
|
||||
if ($node) {
|
||||
if ($node.system) {
|
||||
Write-Host ("Node: {0} ({1}) - bundled node.exe is missing; run -Repair" -f $node.path, $node.version)
|
||||
} else {
|
||||
Write-Host 'Node: bundled node.exe'
|
||||
}
|
||||
} else {
|
||||
Write-Host 'Node: missing (run -Repair)'
|
||||
}
|
||||
Write-Host ("Data: {0}" -f (Get-DataDir))
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Stop) {
|
||||
if (-not $running) {
|
||||
Write-Host 'Luminary is not running.'
|
||||
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
|
||||
exit 0
|
||||
}
|
||||
& taskkill.exe /PID ([int]$runtime.pid) /T /F | Out-Null
|
||||
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
|
||||
Write-Host 'Luminary stopped.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# A second double-click while the first server is still booting must wait for it,
|
||||
# not start a second server on the same catalog.
|
||||
if ($running) {
|
||||
Write-Host 'Luminary is already starting; waiting for it to answer...'
|
||||
$deadline = (Get-Date).AddSeconds(120)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if (Test-Health ([int]$runtime.port)) {
|
||||
Write-Host ("Luminary is running at {0}" -f $runtime.url)
|
||||
Open-App ([string]$runtime.url)
|
||||
exit 0
|
||||
}
|
||||
if (-not (Test-Process ([int]$runtime.pid))) { break }
|
||||
Start-Sleep -Milliseconds 700
|
||||
}
|
||||
if (Test-Process ([int]$runtime.pid)) {
|
||||
$logNote = Join-Path (Get-DataDir) 'logs'
|
||||
Show-ErrorDialog ("Luminary has been starting for over two minutes and is not answering on port {0}.`n`nSee {1} for the server log." -f $runtime.port, $logNote)
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
if ($runtime -and (Test-Health ([int]$runtime.port))) {
|
||||
Write-Host ("Luminary is already running at {0}" -f $runtime.url)
|
||||
Open-App ([string]$runtime.url)
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not (Test-Bundle)) {
|
||||
Write-Host ''
|
||||
Write-Host 'Luminary cannot start: this folder is incomplete.'
|
||||
Write-BundleHelp
|
||||
Show-ErrorDialog 'This folder is not a complete Luminary bundle. See the console for the three usual causes.'
|
||||
exit 3
|
||||
}
|
||||
|
||||
$platform = Test-Platform
|
||||
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
|
||||
if (-not $platform.ok) {
|
||||
$message = ($platform.problems -join "`n`n") + "`n`nLuminary runs on Windows 10/11 (64-bit) with a current browser (Edge, Chrome or Firefox) for the Develop module. Nothing else needs to be installed."
|
||||
Write-Host $message
|
||||
Show-ErrorDialog $message
|
||||
exit 4
|
||||
}
|
||||
|
||||
$node = Resolve-Node
|
||||
if (-not $node) {
|
||||
# The only download Luminary can need is its own runtime. Offer it here so a
|
||||
# customer who never reads the README still gets a working install.
|
||||
if (Show-Question "Luminary needs its Node.js 24 runtime, but node.exe is missing from this folder.`n`nDownload it now from nodejs.org (about 90 MB)?") {
|
||||
try {
|
||||
Repair-Node
|
||||
$node = Resolve-Node
|
||||
} catch {
|
||||
Write-Host ("Download failed: {0}" -f $_.Exception.Message)
|
||||
Show-ErrorDialog ("The runtime download failed.`n`n" + $_.Exception.Message)
|
||||
exit 3
|
||||
}
|
||||
}
|
||||
if (-not $node) {
|
||||
$message = "Luminary cannot start without node.exe.`n`nRun ""Luminary.cmd -Repair"" to download it, or install Node.js 24 from nodejs.org."
|
||||
Write-Host $message
|
||||
Show-ErrorDialog $message
|
||||
exit 3
|
||||
}
|
||||
}
|
||||
|
||||
if ($node.system) {
|
||||
$warning = ("The bundled node.exe is missing; Luminary is using the system Node {0} at {1}.`n`n" +
|
||||
"Run ""Luminary.cmd -Repair"" to restore the pinned runtime." -f $node.version, $node.path)
|
||||
Write-Host $warning
|
||||
Show-Dialog $warning 'Information'
|
||||
}
|
||||
|
||||
$dataDir = Get-DataDir
|
||||
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null
|
||||
$logsOut = Get-LogDir $dataDir
|
||||
|
||||
$port = Find-Port
|
||||
$url = "http://127.0.0.1:$port"
|
||||
|
||||
# The server reads these from the environment; nothing is written into app\.
|
||||
$env:PORT = "$port"
|
||||
$env:HOST = '127.0.0.1'
|
||||
$env:NODE_ENV = 'production'
|
||||
$env:LUMINARY_DATA = $dataDir
|
||||
# Desktop mode: one local admin, no signup, no sign-in. Loopback only, so this
|
||||
# never exposes a passwordless account to the network.
|
||||
$env:LUMINARY_LOCAL = '1'
|
||||
|
||||
$outLog = Join-Path $logsOut 'server.out.log'
|
||||
$errLog = Join-Path $logsOut 'server.err.log'
|
||||
$process = Start-Process -FilePath $node.path `
|
||||
-ArgumentList ('"' + $entry + '"') `
|
||||
-WorkingDirectory $appDir `
|
||||
-WindowStyle Hidden `
|
||||
-PassThru `
|
||||
-RedirectStandardOutput $outLog `
|
||||
-RedirectStandardError $errLog
|
||||
|
||||
@{
|
||||
pid = $process.Id
|
||||
port = $port
|
||||
url = $url
|
||||
data = $dataDir
|
||||
node = $node.path
|
||||
started = (Get-Date).ToString('o')
|
||||
} | ConvertTo-Json | Set-Content -LiteralPath $runtimeFile -Encoding UTF8
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(120)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($process.HasExited) { break }
|
||||
if (Test-Health $port) {
|
||||
Write-Host ("Luminary is running at {0}" -f $url)
|
||||
Write-Host ("Data: {0}" -f $dataDir)
|
||||
Open-App $url
|
||||
exit 0
|
||||
}
|
||||
Start-Sleep -Milliseconds 700
|
||||
}
|
||||
|
||||
$tail = ''
|
||||
if (Test-Path -LiteralPath $errLog) { $tail = (Get-Content -LiteralPath $errLog -Tail 20) -join "`n" }
|
||||
Write-Host 'Luminary did not answer on /api/health.'
|
||||
if ($tail) { Write-Host $tail }
|
||||
if (-not $process.HasExited) { & taskkill.exe /PID $process.Id /T /F | Out-Null }
|
||||
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
|
||||
Show-ErrorDialog ("Luminary did not start.`n`n" + $tail)
|
||||
exit 1
|
||||
@@ -0,0 +1,36 @@
|
||||
' Start Luminary without a console window.
|
||||
' Double-click this file, or use the shortcut an installer creates.
|
||||
Option Explicit
|
||||
|
||||
Dim fso, shell, here, script, nodeExe, powershell
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
Set shell = CreateObject("WScript.Shell")
|
||||
|
||||
here = fso.GetParentFolderName(WScript.ScriptFullName)
|
||||
script = fso.BuildPath(here, "Luminary.ps1")
|
||||
nodeExe = fso.BuildPath(here, "node.exe")
|
||||
powershell = fso.BuildPath(shell.ExpandEnvironmentStrings("%SystemRoot%"), "System32\WindowsPowerShell\v1.0\powershell.exe")
|
||||
|
||||
' Windows 10/11 always has PowerShell; a stripped image may not. Say so instead
|
||||
' of letting WScript report a script error.
|
||||
If Not fso.FileExists(powershell) Then
|
||||
MsgBox "Windows PowerShell is missing, so Luminary cannot start." & vbCrLf & vbCrLf & _
|
||||
"PowerShell 5.1 is included with Windows 10 and 11. On a stripped image, " & _
|
||||
"install it from Microsoft, or run Luminary.cmd on a normal desktop.", _
|
||||
16, "Luminary"
|
||||
WScript.Quit 4
|
||||
End If
|
||||
|
||||
' A file started from inside a zip preview is copied out on its own, so the
|
||||
' launcher is the only thing present. Say so instead of failing silently.
|
||||
If Not fso.FileExists(script) Or Not fso.FileExists(nodeExe) Then
|
||||
MsgBox "This folder is not a complete Luminary bundle." & vbCrLf & vbCrLf & _
|
||||
"Right-click the zip you downloaded, choose ""Extract All..."", then run " & _
|
||||
"Luminary.vbs or Luminary.cmd from the extracted Luminary folder." & vbCrLf & vbCrLf & _
|
||||
"If node.exe is missing after extracting, antivirus or SmartScreen " & _
|
||||
"removed it: run Luminary.ps1 -Repair (or re-extract the zip) to restore it.", _
|
||||
16, "Luminary"
|
||||
WScript.Quit 3
|
||||
End If
|
||||
|
||||
shell.Run """" & powershell & """ -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & script & """", 0, False
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Stop the Luminary server started from this folder.
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" -Stop
|
||||
pause
|
||||
@@ -0,0 +1,3 @@
|
||||
module luminary/launcher
|
||||
|
||||
go 1.21
|
||||
@@ -0,0 +1,688 @@
|
||||
//go:build windows
|
||||
|
||||
// Luminary launcher (Go).
|
||||
//
|
||||
// Optional: when a Go toolchain is available, windows/build.mjs compiles this
|
||||
// into Luminary.exe and ships it instead of the PowerShell entry points. It
|
||||
// does the same jobs as Luminary.ps1, with one difference: being a real
|
||||
// process it can stay in the background and clean up after the server exits.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// Luminary.exe start (or reuse) the server and open the browser
|
||||
// Luminary.exe -stop stop the server started from this folder
|
||||
// Luminary.exe -repair re-download node.exe and verify it against version.txt
|
||||
//
|
||||
// The design and the edge cases are described in ../DESIGN.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
firstPort = 8787
|
||||
lastPort = 8887
|
||||
healthPath = "/api/health"
|
||||
startupWait = 120 * time.Second
|
||||
pollEvery = 700 * time.Millisecond
|
||||
minNodeMajor = 24
|
||||
// CREATE_NO_WINDOW keeps the console-based node.exe from flashing a window
|
||||
// even though the launcher itself is linked with -H windowsgui.
|
||||
createNoWindow = 0x08000000
|
||||
// PROCESS_QUERY_LIMITED_INFORMATION is enough to tell whether a pid is alive
|
||||
// and needs no debug privilege.
|
||||
processQueryLimitedInformation = 0x1000
|
||||
)
|
||||
|
||||
var (
|
||||
root = bundleRoot()
|
||||
logsDir = filepath.Join(root, "logs")
|
||||
// A -H windowsgui binary has no console, so a missing file would otherwise
|
||||
// fail silently. MessageBoxW is the only feedback a user can see.
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
messageBoxW = user32.NewProc("MessageBoxW")
|
||||
|
||||
client = &http.Client{Timeout: 2 * time.Second}
|
||||
downloadClient = &http.Client{Timeout: 10 * time.Minute}
|
||||
nodePinRE = regexp.MustCompile(`^node\s+v?(\d+\.\d+\.\d+)\s+win-x64(?:\s+sha256\s+([0-9a-f]{64}))?(?:\s+size\s+(\d+))?`)
|
||||
)
|
||||
|
||||
type runtimeInfo struct {
|
||||
PID int `json:"pid"`
|
||||
Port int `json:"port"`
|
||||
URL string `json:"url"`
|
||||
Data string `json:"data"`
|
||||
Node string `json:"node"`
|
||||
Started string `json:"started"`
|
||||
}
|
||||
|
||||
type nodeRuntime struct {
|
||||
path string
|
||||
label string
|
||||
system bool
|
||||
}
|
||||
|
||||
var browserOnly = false
|
||||
|
||||
func main() {
|
||||
args := os.Args[1:]
|
||||
browserOnly = hasFlag(args, "-browser", "--browser")
|
||||
switch {
|
||||
case hasFlag(args, "-repair", "--repair", "/repair"):
|
||||
if err := repair(); err != nil {
|
||||
writeLog("launcher.log", "repair: "+err.Error())
|
||||
showError("node.exe could not be restored.\n\n" + err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
showInfo("node.exe is restored and matches the checksum in version.txt.\n\n" +
|
||||
filepath.Join(root, "node.exe"))
|
||||
return
|
||||
case hasFlag(args, "-stop", "--stop", "/stop"):
|
||||
if err := stop(); err != nil {
|
||||
showError(err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
showInfo("Luminary stopped.")
|
||||
return
|
||||
}
|
||||
|
||||
if err := run(); err != nil {
|
||||
writeLog("launcher.log", "error: "+err.Error())
|
||||
showError(err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func hasFlag(args []string, names ...string) bool {
|
||||
for _, arg := range args {
|
||||
for _, name := range names {
|
||||
if strings.EqualFold(arg, name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func showError(text string) { showMessage(text, 0x10) }
|
||||
|
||||
func ask(text string) bool {
|
||||
title, titleErr := syscall.UTF16PtrFromString("Luminary")
|
||||
body, bodyErr := syscall.UTF16PtrFromString(text)
|
||||
if titleErr != nil || bodyErr != nil {
|
||||
return false
|
||||
}
|
||||
// MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND; IDYES is 6.
|
||||
result, _, _ := messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), 0x04|0x20|0x10000)
|
||||
return result == 6
|
||||
}
|
||||
|
||||
func showInfo(text string) { showMessage(text, 0x40) }
|
||||
|
||||
func showMessage(text string, kind uintptr) {
|
||||
title, titleErr := syscall.UTF16PtrFromString("Luminary")
|
||||
body, bodyErr := syscall.UTF16PtrFromString(text)
|
||||
if titleErr != nil || bodyErr != nil {
|
||||
return
|
||||
}
|
||||
// MB_SETFOREGROUND so the dialog is not hidden behind the browser.
|
||||
messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), kind|0x10000)
|
||||
}
|
||||
|
||||
func run() error {
|
||||
nodeExe := filepath.Join(root, "node.exe")
|
||||
appDir := filepath.Join(root, "app")
|
||||
entry := filepath.Join(appDir, "server", "index.mjs")
|
||||
|
||||
required := []struct {
|
||||
name string
|
||||
path string
|
||||
}{
|
||||
{"app\\server\\index.mjs", entry},
|
||||
{"app\\dist\\index.html", filepath.Join(appDir, "dist", "index.html")},
|
||||
}
|
||||
var missing []string
|
||||
for _, file := range required {
|
||||
info, err := os.Stat(file.path)
|
||||
if err != nil {
|
||||
missing = append(missing, file.name)
|
||||
continue
|
||||
}
|
||||
if info.Size() == 0 {
|
||||
// What a half-done extraction or an antivirus leaves behind.
|
||||
missing = append(missing, file.name+" (empty)")
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return fmt.Errorf("this folder is not a complete Luminary bundle (missing: %s).\n\n"+
|
||||
"Right-click the zip you downloaded, choose \"Extract All...\", then run "+
|
||||
"Luminary.exe from the extracted Luminary folder. If files disappeared "+
|
||||
"after extracting, antivirus or SmartScreen removed them: restore them "+
|
||||
"from quarantine and extract again.", strings.Join(missing, ", "))
|
||||
}
|
||||
|
||||
node, err := resolveNode(nodeExe)
|
||||
if err != nil {
|
||||
// The only download Luminary can need is its own runtime. Offer it here
|
||||
// so a customer who never reads the README still gets a working install.
|
||||
if ask("Luminary needs its Node.js 24 runtime, but node.exe is missing from this bundle.\n\n" +
|
||||
"Download it now from nodejs.org (about 90 MB)?") {
|
||||
if repairErr := repair(); repairErr != nil {
|
||||
return fmt.Errorf("the runtime download failed: %w", repairErr)
|
||||
}
|
||||
node, err = resolveNode(nodeExe)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w\n\nRun \"Luminary.exe -repair\" to download the pinned runtime "+
|
||||
"again, or install Node.js 24 from nodejs.org.", err)
|
||||
}
|
||||
}
|
||||
if node.system {
|
||||
message := fmt.Sprintf("The bundled node.exe is missing or damaged, so Luminary is using %s.\n\n"+
|
||||
"Run \"Luminary.exe -repair\" to restore the pinned runtime.", node.label)
|
||||
writeLog("launcher.log", "warning: "+message)
|
||||
showInfo(message)
|
||||
}
|
||||
|
||||
// Already running, or still booting: health is the liveness test, so a stale
|
||||
// runtime.json from a crash falls through to a fresh start instead of
|
||||
// blocking it, and a second double-click waits instead of starting a second
|
||||
// server on the same catalog.
|
||||
if info, ok := readRuntime(); ok {
|
||||
if healthy(info.Port) {
|
||||
openApp(info.URL)
|
||||
return nil
|
||||
}
|
||||
if processAlive(info.PID) {
|
||||
deadline := time.Now().Add(startupWait)
|
||||
for time.Now().Before(deadline) {
|
||||
if healthy(info.Port) {
|
||||
openApp(info.URL)
|
||||
return nil
|
||||
}
|
||||
if !processAlive(info.PID) {
|
||||
break
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
if processAlive(info.PID) {
|
||||
return fmt.Errorf("Luminary is already starting (pid %d) but is not answering on port %d. "+
|
||||
"See %s.", info.PID, info.Port, filepath.Join(dataDirectory(), "logs", "server.err.log"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dataDir := dataDirectory()
|
||||
if err := os.MkdirAll(dataDir, 0o755); err != nil {
|
||||
return fmt.Errorf("cannot create the data directory %s: %w", dataDir, err)
|
||||
}
|
||||
logDir, err := ensureLogDir(dataDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
port, err := freePort()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
url := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
|
||||
stdout, err := openLog(logDir, "server.out.log")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stdout.Close()
|
||||
stderr, err := openLog(logDir, "server.err.log")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stderr.Close()
|
||||
|
||||
cmd := exec.Command(node.path, entry)
|
||||
cmd.Dir = appDir
|
||||
cmd.Stdout = stdout
|
||||
cmd.Stderr = stderr
|
||||
cmd.Env = append(os.Environ(),
|
||||
"PORT="+strconv.Itoa(port),
|
||||
"HOST=127.0.0.1",
|
||||
"NODE_ENV=production",
|
||||
"LUMINARY_DATA="+dataDir,
|
||||
// Desktop mode: one local admin, no signup or sign-in. Loopback only,
|
||||
// so this never exposes a passwordless account to the network.
|
||||
"LUMINARY_LOCAL=1",
|
||||
)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("cannot start %s: %w", node.path, err)
|
||||
}
|
||||
|
||||
info := runtimeInfo{
|
||||
PID: cmd.Process.Pid,
|
||||
Port: port,
|
||||
URL: url,
|
||||
Data: dataDir,
|
||||
Node: node.path,
|
||||
Started: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
writeRuntime(info)
|
||||
|
||||
deadline := time.Now().Add(startupWait)
|
||||
for time.Now().Before(deadline) {
|
||||
if healthy(port) {
|
||||
openApp(url)
|
||||
// Stay alive for the server's lifetime so runtime.json is removed
|
||||
// on quit and a crash is written to the launcher log. The exit
|
||||
// code is deliberately ignored: "Stop" force-kills the child.
|
||||
_ = cmd.Wait()
|
||||
removeRuntime()
|
||||
writeLog("launcher.log", "server exited")
|
||||
return nil
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
|
||||
_ = cmd.Process.Kill()
|
||||
removeRuntime()
|
||||
return fmt.Errorf("Luminary did not answer on %s within %s; see %s",
|
||||
healthPath, startupWait, filepath.Join(logDir, "server.err.log"))
|
||||
}
|
||||
|
||||
// --- runtime resolution -------------------------------------------------------
|
||||
|
||||
func nodePin() (version, hash string, size int64) {
|
||||
data, err := os.ReadFile(filepath.Join(root, "version.txt"))
|
||||
if err != nil {
|
||||
return "", "", 0
|
||||
}
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
match := nodePinRE.FindStringSubmatch(strings.TrimSpace(line))
|
||||
if match == nil {
|
||||
continue
|
||||
}
|
||||
version = match[1]
|
||||
hash = match[2]
|
||||
if match[3] != "" {
|
||||
size, _ = strconv.ParseInt(match[3], 10, 64)
|
||||
}
|
||||
return version, hash, size
|
||||
}
|
||||
return "", "", 0
|
||||
}
|
||||
|
||||
// The bundled runtime wins; a system Node 24+ is a fallback, never a preference.
|
||||
func resolveNode(bundled string) (nodeRuntime, error) {
|
||||
if info, err := os.Stat(bundled); err == nil && info.Size() > 0 {
|
||||
_, _, pinnedSize := nodePin()
|
||||
if pinnedSize == 0 || info.Size() == pinnedSize {
|
||||
return nodeRuntime{path: bundled, label: "the bundled node.exe"}, nil
|
||||
}
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, candidate := range systemNodeCandidates() {
|
||||
key := strings.ToLower(candidate)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
info, err := os.Stat(candidate)
|
||||
if err != nil || info.Size() == 0 {
|
||||
continue
|
||||
}
|
||||
if major, ok := nodeMajor(candidate); ok && major >= minNodeMajor {
|
||||
return nodeRuntime{
|
||||
path: candidate,
|
||||
label: fmt.Sprintf("the system Node %d at %s", major, candidate),
|
||||
system: true,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nodeRuntime{}, fmt.Errorf("node.exe is missing from the bundle and no Node.js %d+ was found on this machine", minNodeMajor)
|
||||
}
|
||||
|
||||
func systemNodeCandidates() []string {
|
||||
var candidates []string
|
||||
if found, err := exec.LookPath("node.exe"); err == nil {
|
||||
candidates = append(candidates, found)
|
||||
}
|
||||
if found, err := exec.LookPath("node"); err == nil {
|
||||
candidates = append(candidates, found)
|
||||
}
|
||||
if dir := os.Getenv("ProgramFiles"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe"))
|
||||
}
|
||||
if dir := os.Getenv("ProgramFiles(x86)"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe"))
|
||||
}
|
||||
if dir := os.Getenv("LOCALAPPDATA"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "Programs", "nodejs", "node.exe"))
|
||||
}
|
||||
if dir := os.Getenv("NVM_SYMLINK"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "node.exe"))
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
func nodeMajor(exe string) (int, bool) {
|
||||
cmd := exec.Command(exe, "--version")
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
raw := strings.TrimPrefix(strings.TrimSpace(string(out)), "v")
|
||||
parts := strings.SplitN(raw, ".", 2)
|
||||
major, err := strconv.Atoi(parts[0])
|
||||
if err != nil || major <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return major, true
|
||||
}
|
||||
|
||||
// --- repair -------------------------------------------------------------------
|
||||
|
||||
func repair() error {
|
||||
nodeExe := filepath.Join(root, "node.exe")
|
||||
if info, ok := readRuntime(); ok && (healthy(info.Port) || processAlive(info.PID)) {
|
||||
return fmt.Errorf("Luminary is running (pid %d). Stop it first: Luminary.exe -stop", info.PID)
|
||||
}
|
||||
|
||||
version, expected, _ := nodePin()
|
||||
if version == "" {
|
||||
return fmt.Errorf("version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead.")
|
||||
}
|
||||
if expected == "" {
|
||||
hash, err := publishedHash(version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expected = hash
|
||||
}
|
||||
|
||||
url := os.Getenv("LUMINARY_NODE_URL")
|
||||
if url == "" {
|
||||
url = fmt.Sprintf("https://nodejs.org/dist/v%s/win-x64/node.exe", version)
|
||||
}
|
||||
writeLog("launcher.log", "repair: downloading "+url)
|
||||
|
||||
response, err := downloadClient.Get(url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot download node.exe: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("cannot download node.exe: %s answered %s", url, response.Status)
|
||||
}
|
||||
|
||||
temp := filepath.Join(root, "node.exe.new")
|
||||
file, err := os.Create(temp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot write next to the launcher: %w", err)
|
||||
}
|
||||
hasher := sha256.New()
|
||||
_, copyErr := io.Copy(io.MultiWriter(file, hasher), response.Body)
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("the download stopped early: %w", copyErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("cannot finish writing node.exe: %w", closeErr)
|
||||
}
|
||||
|
||||
actual := hex.EncodeToString(hasher.Sum(nil))
|
||||
if !strings.EqualFold(actual, expected) {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("the downloaded node.exe does not match the expected checksum (got %s, want %s). Nothing was changed.", actual, expected)
|
||||
}
|
||||
|
||||
// Windows will not rename over an existing file; a running server is already
|
||||
// refused above, so the old copy is not in use here.
|
||||
_ = os.Remove(nodeExe)
|
||||
if err := os.Rename(temp, nodeExe); err != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("cannot replace node.exe: %w", err)
|
||||
}
|
||||
writeLog("launcher.log", fmt.Sprintf("repair: restored node v%s sha256 %s", version, actual))
|
||||
return nil
|
||||
}
|
||||
|
||||
func publishedHash(version string) (string, error) {
|
||||
url := fmt.Sprintf("https://nodejs.org/dist/v%s/SHASUMS256.txt", version)
|
||||
response, err := downloadClient.Get(url)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot fetch the published checksum: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("cannot fetch the published checksum: %s answered %s", url, response.Status)
|
||||
}
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read the published checksum: %w", err)
|
||||
}
|
||||
for _, line := range strings.Split(string(body), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 2 && fields[1] == "win-x64/node.exe" {
|
||||
return strings.ToLower(fields[0]), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no win-x64/node.exe checksum for v%s", version)
|
||||
}
|
||||
|
||||
// --- commands -----------------------------------------------------------------
|
||||
|
||||
func stop() error {
|
||||
info, ok := readRuntime()
|
||||
if !ok {
|
||||
showInfo("Luminary is not running.")
|
||||
return nil
|
||||
}
|
||||
// /T also takes down sharp's helper processes and the denoise workers.
|
||||
if err := exec.Command("taskkill.exe", "/PID", strconv.Itoa(info.PID), "/T", "/F").Run(); err != nil && processAlive(info.PID) {
|
||||
return fmt.Errorf("cannot stop pid %d: %w", info.PID, err)
|
||||
}
|
||||
removeRuntime()
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------------
|
||||
|
||||
func bundleRoot() string {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return "."
|
||||
}
|
||||
return filepath.Dir(exe)
|
||||
}
|
||||
|
||||
func dataDirectory() string {
|
||||
if dir := strings.TrimSpace(os.Getenv("LUMINARY_DATA")); dir != "" {
|
||||
return dir
|
||||
}
|
||||
base := os.Getenv("LOCALAPPDATA")
|
||||
if base == "" {
|
||||
base = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
|
||||
}
|
||||
return filepath.Join(base, "Luminary", "data")
|
||||
}
|
||||
|
||||
// A bundle on read-only media still has to boot; the logs move next to the data.
|
||||
func ensureLogDir(dataDir string) (string, error) {
|
||||
if err := os.MkdirAll(logsDir, 0o755); err == nil {
|
||||
return logsDir, nil
|
||||
}
|
||||
fallback := filepath.Join(dataDir, "logs")
|
||||
if err := os.MkdirAll(fallback, 0o755); err != nil {
|
||||
return "", fmt.Errorf("cannot create a log directory: %w", err)
|
||||
}
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
func freePort() (int, error) {
|
||||
for port := firstPort; port <= lastPort; port++ {
|
||||
listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err == nil {
|
||||
listener.Close()
|
||||
return port, nil
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("no free TCP port between %d and %d", firstPort, lastPort)
|
||||
}
|
||||
|
||||
func healthy(port int) bool {
|
||||
response, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d%s", port, healthPath))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer response.Body.Close()
|
||||
return response.StatusCode == http.StatusOK
|
||||
}
|
||||
|
||||
func processAlive(pid int) bool {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
syscall.CloseHandle(handle)
|
||||
return true
|
||||
}
|
||||
|
||||
func openBrowser(url string) {
|
||||
// FileProtocolHandler goes through the user's default browser without
|
||||
// needing a protocol registration of our own.
|
||||
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||
}
|
||||
|
||||
// Edge ships with Windows 10/11, so a chromeless app window costs no extra
|
||||
// runtime. Chrome is the second choice; anything else falls back to a tab.
|
||||
func findAppBrowser() string {
|
||||
candidates := []string{}
|
||||
add := func(dir string, rest ...string) {
|
||||
if dir != "" {
|
||||
candidates = append(candidates, filepath.Join(append([]string{dir}, rest...)...))
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"} {
|
||||
add(os.Getenv(key), "Microsoft", "Edge", "Application", "msedge.exe")
|
||||
}
|
||||
for _, key := range []string{"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"} {
|
||||
add(os.Getenv(key), "Google", "Chrome", "Application", "chrome.exe")
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if info, err := os.Stat(candidate); err == nil && info.Size() > 0 {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// --app gives a window with no tabs and no address bar, in its own profile, so
|
||||
// it reads as a desktop app rather than a web page. -browser opts out.
|
||||
func openApp(url string) {
|
||||
if browserOnly || strings.EqualFold(os.Getenv("LUMINARY_WINDOW"), "browser") {
|
||||
openBrowser(url)
|
||||
return
|
||||
}
|
||||
// A native WebView2 host, when the bundle ships one, is the real app window:
|
||||
// its own icon, no browser branding at all.
|
||||
native := filepath.Join(root, "LuminaryWindow.exe")
|
||||
if info, err := os.Stat(native); err == nil && info.Size() > 0 {
|
||||
if err := exec.Command(native, "--url", url).Start(); err == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
exe := findAppBrowser()
|
||||
if exe == "" {
|
||||
openBrowser(url)
|
||||
return
|
||||
}
|
||||
profile := filepath.Join(dataDirectory(), "window-profile")
|
||||
if err := os.MkdirAll(profile, 0o755); err != nil {
|
||||
openBrowser(url)
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(exe,
|
||||
"--app="+url,
|
||||
"--user-data-dir="+profile,
|
||||
"--window-size=1500,950",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--disable-features=Translate",
|
||||
)
|
||||
if err := cmd.Start(); err != nil {
|
||||
openBrowser(url)
|
||||
}
|
||||
}
|
||||
|
||||
// The state file lives in the bundle folder so a copied bundle is self-contained.
|
||||
// On read-only media (write-protected USB, Program Files for a non-admin user)
|
||||
// it moves next to the data, which is always writable.
|
||||
func runtimePath() string {
|
||||
probe := filepath.Join(root, ".write-test")
|
||||
if err := os.WriteFile(probe, nil, 0o644); err == nil {
|
||||
_ = os.Remove(probe)
|
||||
return filepath.Join(root, "runtime.json")
|
||||
}
|
||||
return filepath.Join(dataDirectory(), "runtime.json")
|
||||
}
|
||||
|
||||
func readRuntime() (runtimeInfo, bool) {
|
||||
var info runtimeInfo
|
||||
data, err := os.ReadFile(runtimePath())
|
||||
if err != nil {
|
||||
return info, false
|
||||
}
|
||||
if json.Unmarshal(data, &info) != nil || info.PID == 0 || info.Port == 0 {
|
||||
return info, false
|
||||
}
|
||||
return info, true
|
||||
}
|
||||
|
||||
func writeRuntime(info runtimeInfo) {
|
||||
data, err := json.MarshalIndent(info, "", " ")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile(runtimePath(), append(data, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func removeRuntime() {
|
||||
_ = os.Remove(runtimePath())
|
||||
}
|
||||
|
||||
func openLog(dir, name string) (*os.File, error) {
|
||||
return os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
}
|
||||
|
||||
func writeLog(name, message string) {
|
||||
dir, err := ensureLogDir(dataDirectory())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
file, err := openLog(dir, name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
fmt.Fprintf(file, "%s %s\n", time.Now().Format(time.RFC3339), message)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Optional native window for the Windows bundle. The launcher starts it with
|
||||
a url switch pointing at the local server.
|
||||
|
||||
It is a window host only: node.exe stays a child of the launcher, so Stop
|
||||
works the same whether the UI runs here or in an Edge app window. Starting
|
||||
it without a url argument (for example, double-clicking it) forwards to the
|
||||
bundle launcher instead of showing a signed-out page.
|
||||
|
||||
Published self-contained: the customer needs no .NET install. The only
|
||||
runtime requirement is Microsoft Edge WebView2, which ships with Windows
|
||||
10/11 alongside Edge. EnableWindowsTargeting lets this be compiled on a
|
||||
Linux build host; it still only runs on Windows.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>LuminaryWindow</AssemblyName>
|
||||
<RootNamespace>Luminary</RootNamespace>
|
||||
<ApplicationIcon>../Luminary.ico</ApplicationIcon>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<!-- ~140 MB raw becomes roughly half that in the single file. -->
|
||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||
<AllowedReferenceRelatedFileExtensions>none</AllowedReferenceRelatedFileExtensions>
|
||||
<!-- WebView2Loader.dll is native; single-file must extract it at startup. -->
|
||||
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<Version>0.5.0</Version>
|
||||
<AssemblyTitle>Luminary</AssemblyTitle>
|
||||
<Product>Luminary</Product>
|
||||
<Company>Maple Street</Company>
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4370.26" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.WinForms;
|
||||
|
||||
namespace Luminary;
|
||||
|
||||
/// <summary>
|
||||
/// The whole app window: WebView2 filling the client area, the Luminary icon in
|
||||
/// the title bar and taskbar, and an explicit message when the WebView2 runtime
|
||||
/// is missing instead of a silent exit.
|
||||
/// </summary>
|
||||
internal sealed class MainForm : Form
|
||||
{
|
||||
private const string RuntimeDownload = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
|
||||
|
||||
private readonly string _url;
|
||||
private readonly WebView2 _web = new() { Dock = DockStyle.Fill };
|
||||
|
||||
public MainForm(string url)
|
||||
{
|
||||
_url = url;
|
||||
Text = "Luminary";
|
||||
Width = 1500;
|
||||
Height = 950;
|
||||
MinimumSize = new Size(900, 600);
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
Icon = LoadIcon();
|
||||
|
||||
Controls.Add(_web);
|
||||
Load += async (_, _) => await InitializeAsync();
|
||||
}
|
||||
|
||||
/// <summary>The exe carries the icon; extracting it avoids shipping a second file.</summary>
|
||||
private static Icon? LoadIcon()
|
||||
{
|
||||
try
|
||||
{
|
||||
var exe = Environment.ProcessPath;
|
||||
if (!string.IsNullOrEmpty(exe))
|
||||
{
|
||||
var icon = Icon.ExtractAssociatedIcon(exe);
|
||||
if (icon != null) return icon;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A missing icon must never stop the window from opening.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Its own profile, next to the catalog, so the app never shares
|
||||
// cookies or storage with the user's normal browsing. LUMINARY_DATA
|
||||
// wins, the same precedence the server and launcher use.
|
||||
var dataRoot = Environment.GetEnvironmentVariable("LUMINARY_DATA");
|
||||
if (string.IsNullOrWhiteSpace(dataRoot))
|
||||
{
|
||||
dataRoot = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"Luminary", "data");
|
||||
}
|
||||
var dataDir = Path.Combine(dataRoot, "webview2");
|
||||
Directory.CreateDirectory(dataDir);
|
||||
|
||||
var environment = await CoreWebView2Environment.CreateAsync(null, dataDir);
|
||||
await _web.EnsureCoreWebView2Async(environment);
|
||||
|
||||
var settings = _web.CoreWebView2.Settings;
|
||||
settings.AreDevToolsEnabled = false;
|
||||
settings.IsStatusBarEnabled = false;
|
||||
settings.AreDefaultContextMenusEnabled = true;
|
||||
|
||||
_web.CoreWebView2.Navigate(_url);
|
||||
}
|
||||
catch (WebView2RuntimeNotFoundException)
|
||||
{
|
||||
Fail(
|
||||
"The Microsoft Edge WebView2 runtime is missing.\n\n" +
|
||||
"Install it from " + RuntimeDownload + " and start Luminary again.",
|
||||
close: true);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
Fail("Luminary could not open its window.\n\n" + error.Message, close: true);
|
||||
}
|
||||
}
|
||||
|
||||
private void Fail(string message, bool close)
|
||||
{
|
||||
MessageBox.Show(this, message, "Luminary", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
if (close) Close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Luminary;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
var url = "http://127.0.0.1:8787";
|
||||
var urlProvided = false;
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var arg = args[i];
|
||||
if (arg is "--url" or "-url")
|
||||
{
|
||||
if (i + 1 < args.Length) url = args[i + 1];
|
||||
urlProvided = true;
|
||||
break;
|
||||
}
|
||||
if (arg.StartsWith("--url=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
url = arg[6..];
|
||||
urlProvided = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// This exe is the window the launcher opens. If someone double-clicks it
|
||||
// directly there is no server in desktop mode, or port 8787 may belong
|
||||
// to a full sign-in server. Start the real launcher and let it choose the
|
||||
// port, set LUMINARY_LOCAL=1 and open this window with --url.
|
||||
if (!urlProvided)
|
||||
{
|
||||
if (StartBundleLauncher()) return;
|
||||
|
||||
MessageBox.Show(
|
||||
"LuminaryWindow.exe is only the app window.\n\n" +
|
||||
"Start Luminary.exe (or Luminary.cmd) from the Luminary folder instead.",
|
||||
"Luminary",
|
||||
MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new MainForm(url));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A direct window launch forwards to the bundle launcher. That launcher
|
||||
/// starts the local server with the correct desktop-mode environment and
|
||||
/// then reopens this window with --url. Returns false when this file is not
|
||||
/// inside a complete bundle.
|
||||
/// </summary>
|
||||
private static bool StartBundleLauncher()
|
||||
{
|
||||
// Environment.ProcessPath is the exe itself even in a single-file publish;
|
||||
// AppContext.BaseDirectory is only a fallback.
|
||||
var root = Path.GetDirectoryName(Environment.ProcessPath) ?? AppContext.BaseDirectory;
|
||||
foreach (var name in new[] { "Luminary.exe", "Luminary.vbs", "Luminary.cmd" })
|
||||
{
|
||||
var launcher = Path.Combine(root, name);
|
||||
if (!File.Exists(launcher)) continue;
|
||||
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(launcher)
|
||||
{
|
||||
WorkingDirectory = root,
|
||||
UseShellExecute = true,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Try the next entry point before giving up.
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# Windows releases (transfer folder)
|
||||
|
||||
The built bundle, kept here so it can be copied to a Windows machine on a USB
|
||||
stick, a network share, or a release upload. Nothing reads it at run time; the
|
||||
app never looks in this folder.
|
||||
|
||||
| File | What to do with it |
|
||||
| --- | --- |
|
||||
| `Luminary-<version>-win-x64.zip` | Copy to the Windows PC, right-click → **Extract All…**, then run `Luminary.cmd` (or `Luminary.vbs`) from the extracted `Luminary` folder. `README-windows.txt` inside the zip is the end-user guide. |
|
||||
| `LuminaryWindow.exe` inside the zip | optional native window (WebView2); the launcher uses it automatically when present, and starting it directly forwards to the launcher |
|
||||
| `SHA256SUMS.txt` | Check the copy did not corrupt: `certutil -hashfile Luminary-<version>-win-x64.zip SHA256` |
|
||||
|
||||
## Rebuilding this folder
|
||||
|
||||
```bash
|
||||
node windows/build.mjs --publish # npm run build, then bundle + copy here
|
||||
node windows/build.mjs --skip-build --publish # reuse the existing dist/
|
||||
```
|
||||
|
||||
`--publish` copies the finished zip and writes `SHA256SUMS.txt`. The build still
|
||||
stages and zips **outside** the checkout (`~/.cache/luminary-windows`, or
|
||||
`%LOCALAPPDATA%\Luminary\build` on Windows); this folder only receives the final
|
||||
artifact. Old versions are not deleted, so remove the ones you no longer ship.
|
||||
|
||||
Add `--webview2 <path to LuminaryWindow.exe>` for the native window; without it
|
||||
the zip is about half the size (49 MB) and uses the Edge/Chrome app window.
|
||||
|
||||
## Before a deploy
|
||||
|
||||
`scripts/deploy.mjs` rsyncs the worktree, so a zip left here is also sent to the
|
||||
production server. On a Linux host it is harmless (nothing loads it), but if you
|
||||
do not want a ~110 MB file on the server, delete it after transferring, or
|
||||
publish only when you are actually shipping a build.
|
||||
|
||||
## What a Windows user needs
|
||||
|
||||
Windows 10/11 x64 and a current browser (Edge, Chrome or Firefox) with WebGL2.
|
||||
Node.js, .NET and the Visual C++ Redistributable are **not** required — they are
|
||||
bundled or part of Windows. The native window needs the Microsoft Edge WebView2
|
||||
runtime, which Windows 10/11 already has alongside Edge. See `../README.md` for
|
||||
the import-level audit.
|
||||
@@ -0,0 +1 @@
|
||||
e563cfe3be613ff3cea84030275c43fd363b4de4ef98fecf031382cbfc0d25c3 Luminary-0.5.0-win-x64.zip
|
||||