Brought up to date with the private repository (6630f7f)

This commit is contained in:
S committed 2026-10-14 19:03:16 +03:00
commit c8178dce98
26 files changed
+6314

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# Electron and the Flash plugin are downloads, not source: README.md says
# which versions and where they came from.
/electron/
/electron-win/
/flash/
/dist/
/tools/bin/
/installer/node_modules/
# kept in the private repository, never here
*.md
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

+86
View File
@@ -0,0 +1,86 @@
"use strict";
const {app} = require("electron");
const fs = require("fs");
const path = require("path");
// what the client starts with: the newest copy of this folder the computer
// has. an installed build keeps the copy it came with and fetches newer ones
// into its own data folder (updater.js), which it can always write to, the
// install folder not always (/opt, the AppImage, Applications). a copy run
// from the repository (no build.json) always runs as it is.
//
// this file, Electron and the Flash plugin are the "shell", which an update
// cannot change: a version that needs a newer shell is a new download.
const SHELL = 1;
global.burrow = {shipped: __dirname, shell: SHELL, app: __dirname};
// the same data folder main.js uses
if (!app.commandLine.hasSwitch("user-data-dir")) {
app.setPath("userData", path.join(app.getPath("appData"), "AJ Private Client"));
}
const UPDATES = path.join(app.getPath("userData"), "updates");
const STAGED = path.join(UPDATES, "current.json");
const versionOf = folder => {
try {
return JSON.parse(fs.readFileSync(path.join(folder, "package.json"), "utf8")).version;
}
catch (err) {
return null;
}
};
// is version `one` ("1.2.3") later than `other`?
const newer = (one, other) => {
const a = String(one).split(".").map(Number);
const b = String(other).split(".").map(Number);
for (let i = 0; i < 3; i++) {
if ((a[i] || 0) !== (b[i] || 0)) {
return (a[i] || 0) > (b[i] || 0);
}
}
return false;
};
const chosen = (() => {
if (!fs.existsSync(path.join(__dirname, "build.json")) || app.commandLine.hasSwitch("aj-no-updates")) {
return __dirname;
}
try {
const staged = JSON.parse(fs.readFileSync(STAGED, "utf8"));
const folder = path.join(UPDATES, `app-${staged.version}`);
if (/^\d+\.\d+\.\d+$/.test(staged.version) && staged.shell <= SHELL && newer(staged.version, versionOf(__dirname))
&& versionOf(folder) === staged.version) {
return folder;
}
}
catch (err) {
// nothing fetched yet
}
return __dirname;
})();
global.burrow.app = chosen;
try {
require(path.join(chosen, "main.js"));
}
catch (err) {
if (chosen === __dirname) {
throw err;
}
// an update that does not start is forgotten, and the installed copy
// starts in a clean process (the broken one may have half set itself up).
console.error(`the update in ${chosen} did not start: ${err.stack}`);
// (updater.js does not fetch that version again.)
try {
fs.writeFileSync(path.join(UPDATES, "bad.json"), JSON.stringify({version: versionOf(chosen)}));
fs.unlinkSync(STAGED);
}
catch (writeErr) {
// already gone
}
app.relaunch();
app.exit(1);
}
+8
View File
@@ -0,0 +1,8 @@
"use strict";
const {contextBridge, ipcRenderer} = require("electron");
// for the server's /captcha page in its window (main.js): hands the answer back.
contextBridge.exposeInMainWorld("burrowCaptcha", {
done: token => ipcRenderer.send("captchaDone", String(token)),
});
Binary file not shown.
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
"use strict";
const { ipcRenderer, contextBridge } = require("electron");
const sendWhitelist = new Set()
.add("initialized")
.add("fps")
.add("printImage")
.add("reloadGame")
.add("reportError")
.add("signupCompleted");
const receiveWhitelist = new Set()
.add("flashVarsReady")
.add("hud")
.add("removed");
contextBridge.exposeInMainWorld(
"ipc", {
sendToHost: (channel, ...args) => {
if (sendWhitelist.has(channel)) {
ipcRenderer.sendToHost(channel, ...args);
}
},
on: (channel, listener) => {
if (receiveWhitelist.has(channel)) {
ipcRenderer.on(channel, listener);
}
}
}
);
ipcRenderer.on("redirect-url", (event, url) => {
console.log("REDIRECT");
});
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

+1417
View File
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+529
View File
@@ -0,0 +1,529 @@
"use strict";
const {app, BrowserWindow, ipcMain, net, session, shell, webContents} = require("electron");
const fs = require("fs");
const path = require("path");
const relay = require("./relay.js");
const updater = require("./updater.js");
// Burrow: a minimal client for the Burrow private server (Animal Jam Classic,
// under a name of its own): a login form, then the
// game and little else. it needs Electron 11 (the last with Flash support)
// and a Flash plugin from before Adobe's January 2021 shut-off; both sit
// beside this folder (../electron or ../electron-win, ../flash) and
// ../run.sh or ../run.bat starts it.
// the client was "AJ Private Client" until it was named Burrow. what it
// keeps on this computer (remembered accounts, settings, the game's cache)
// stays in the folder of that name, so that nobody is signed out by the
// change of name.
// (Not when the caller chose the folder itself, --user-data-dir.)
if (!app.commandLine.hasSwitch("user-data-dir")) {
app.setPath("userData", path.join(app.getPath("appData"), "AJ Private Client"));
}
// the folder the client was installed with. this one may be an update
// (boot.js), kept elsewhere; the plugin and build.json stay beside that one.
const SHIPPED = global.burrow ? global.burrow.shipped : __dirname;
const VERSION = require("./package.json").version;
// a packaged build names its server in build.json (tools/build.sh --server)
const builtFor = () => {
try {
const {server} = JSON.parse(fs.readFileSync(path.join(SHIPPED, "build.json"), "utf8"));
return typeof server === "string" && /^https?:\/\/[^\s]+$/.test(server) ? server : "";
} catch (error) {
return "";
}
};
const DEFAULT_SERVER = process.env.AJ_SERVER || builtFor() || "http://127.0.0.1:8080";
const FLASH_VERSION = "32.0.0.330";
const LAUNCHER_VERSION = "1.5.7"; // the official launcher this stands in for
const FLASH_PLUGIN = process.env.AJ_FLASH_PLUGIN || path.join(SHIPPED, "..", "flash",
process.platform === "win32" ? "pepflashplayer.dll" : process.platform === "darwin" ? "PepperFlashPlayer.plugin" : "libpepflashplayer.so");
const GAME_PRELOAD = path.join(__dirname, "gamePreload.js");
const CAPTCHA_PRELOAD = path.join(__dirname, "captchaPreload.js");
// where cloudflare's captcha widget comes from
const CAPTCHA_ORIGIN = "https://challenges.cloudflare.com";
const MAX_COPIES = 8;
// what has to be known before Chromium starts, so cannot live in the page's
// own storage: {gpu: false} when the graphics card is not to be used.
const SETTINGS_FILE = path.join(app.getPath("userData"), "client-settings.json");
const readSettings = () => {
try {
return JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf8")) || {};
}
catch (err) {
return {};
}
};
let win = null;
// the server the game is being played on ("https://play.burrow.moe"),
// once a login chose it: the one address the game page may load from.
let gameOrigin = null;
// the captcha window (below), while it is open, and its server's origin
let captchaBox = null;
let captchaServer = null;
// it has a session of its own, with a rule of its own on what it may load:
// electron does not say which window a page itself is being loaded for.
const CAPTCHA_PARTITION = "aj-captcha";
// --aj-no-renderer-sandbox: the pages' processes outside Chromium's sandbox,
// as they were, should the Flash plugin not start with it.
const SANDBOXED = !app.commandLine.hasSwitch("aj-no-renderer-sandbox");
// the main process's own calls to a server get a session to themselves, so
// that the rule below about what pages may load does not apply to them.
const API_PARTITION = "aj-api";
// two copies cannot share one HTTP cache: the second to start moves the
// first one's cache aside, and the first then gets broken game files out of
// it. so each copy running takes a numbered slot, and every slot but the
// first has a cache folder of its own. the folders stay, so a second window
// loads the game from disk as fast as the first does. A slot is a lock file
// holding the process id of the copy that has it.
const pidRuns = pid => {
try {
process.kill(pid, 0);
return true;
}
catch (err) {
return err.code === "EPERM";
}
};
const takeSlot = () => {
const folder = app.getPath("userData");
fs.mkdirSync(folder, {recursive: true});
for (let slot = 1; slot <= MAX_COPIES; slot++) {
const lock = path.join(folder, `copy-${slot}.lock`);
try {
const holder = Number(fs.readFileSync(lock, "utf8"));
if (holder && holder !== process.pid && pidRuns(holder)) {
continue;
}
fs.unlinkSync(lock);
}
catch (err) {
// no such lock: the slot is free.
}
try {
fs.writeFileSync(lock, String(process.pid), {flag: "wx"});
app.on("quit", () => {
try {
fs.unlinkSync(lock);
}
catch (quitErr) {
// the next copy to want the slot sees that this one is gone.
}
});
return slot;
}
catch (err) {
// another copy took it this instant; try the next.
}
}
return 0;
};
// not when the caller chose the folders itself (--user-data-dir).
if (!app.commandLine.hasSwitch("user-data-dir")) {
const slot = takeSlot();
if (slot !== 1) {
app.commandLine.appendSwitch("disk-cache-dir", path.join(app.getPath("userData"), slot ? `Cache-copy-${slot}` : `Cache-copy-pid-${process.pid}`));
}
}
// the game reads the launcher's version out of the browser's user agent and
// refuses to start below 1.5.3, so the client names itself as the official
// launcher there.
app.userAgentFallback = `${app.userAgentFallback.replace(/ AJPrivateClient\/\S+/, "")} AJClassic/${LAUNCHER_VERSION}`;
// the 2019 flash plugin cannot start inside chromium's sandbox on linux; an
// installed copy is started from a menu entry or an AppImage, not run.sh
if (process.platform === "linux" && !app.commandLine.hasSwitch("no-sandbox")) {
app.commandLine.appendSwitch("no-sandbox");
}
app.commandLine.appendSwitch("ppapi-flash-path", FLASH_PLUGIN);
app.commandLine.appendSwitch("ppapi-flash-version", FLASH_VERSION);
// Chromium slows a page down once its window is covered, minimised or out
// of focus. with two game windows side by side that is one of them always:
// its animal stutters and its connection can time out. keep both at speed.
app.commandLine.appendSwitch("disable-renderer-backgrounding");
app.commandLine.appendSwitch("disable-background-timer-throttling");
app.commandLine.appendSwitch("disable-backgrounding-occluded-windows");
// the game is Flash, which draws with the processor whatever happens; the
// graphics card only puts the finished picture on the screen. Chromium's GPU
// process costs about 120 MB for that (measured: 134 MB of the client's 437
// MB of private memory, 18 MB without it). it is used unless "Use GPU" under
// Advanced was turned off (the owner's choice, once the game drew more
// pictures a second than its own 24); without it the little that is left
// runs inside the main process. --aj-gpu turns it on whatever is set.
const usesGpu = readSettings().gpu !== false || app.commandLine.hasSwitch("aj-gpu");
if (!usesGpu) {
app.commandLine.appendSwitch("disable-gpu");
app.commandLine.appendSwitch("in-process-gpu");
}
// automatic updates (updater.js): on unless turned off, and only for an
// installed build, which knows its server.
ipcMain.handle("setAutoUpdate", (event, on) => {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify({...readSettings(), autoUpdate: on === true}));
if (on === true && updates) {
updates.check();
}
});
ipcMain.on("restartToUpdate", () => {
app.relaunch();
app.exit(0);
});
let updates = null;
let updateState = null; // the last thing the updater said, for a page loaded after it
ipcMain.handle("setGpu", (event, on) => {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify({...readSettings(), gpu: on === true}));
});
ipcMain.handle("info", () => ({
// as this run was started; a change takes effect at the next start.
gpu: usesGpu,
gpuSetting: readSettings().gpu !== false,
defaultServer: DEFAULT_SERVER,
version: VERSION,
// null when this copy is not one that updates itself
autoUpdate: builtFor() && global.burrow ? readSettings().autoUpdate !== false : null,
update: updateState,
launcherVersion: LAUNCHER_VERSION,
// what the game is told it runs on; it only knows these two.
os: process.platform === "darwin" ? "mac" : "win",
flashPluginFound: fs.existsSync(FLASH_PLUGIN),
}));
// resolves to the local port the game is to connect to (see relay.js), 0
// when none could be opened.
ipcMain.handle("useServer", (event, serverUrl, gamePort, gameHost) => {
const url = new URL(serverUrl);
gameOrigin = url.origin;
// the server may name another host for the game: a web address behind
// cloudflare carries no game port. a local server is never sent elsewhere.
const loopback = ["127.0.0.1", "localhost", "::1"];
const named = /^[a-z0-9.-]{1,253}$/i.test(String(gameHost || "")) && !loopback.includes(gameHost) && !loopback.includes(url.hostname);
return relay.use(named ? gameHost : url.hostname, Number(gamePort), url.protocol === "https:");
});
// what a page may load. the login page is ours and talks to whichever server
// was typed in. the game page gets its own server and nothing else: the
// game is an old Flash plugin in an old browser, and anything that made it
// fetch from elsewhere (a picture named in a chat line once did) would hand
// a stranger the player's address, or the plugin a stranger's file.
const LOCAL_SCHEMES = ["file:", "devtools:", "chrome-devtools:", "chrome:", "data:", "blob:", "about:"];
const mayLoad = details => {
let url;
try {
url = new URL(details.url);
}
catch (err) {
return false;
}
if (LOCAL_SCHEMES.includes(url.protocol)) {
return true;
}
if (win && details.webContentsId === win.webContents.id) {
return url.protocol === "http:" || url.protocol === "https:";
}
return gameOrigin !== null && url.origin === gameOrigin;
};
// the server's /api only answers its own pages (it checks the Origin
// header), and this client's page is a file. so the calls the page
// needs are made from here, where a request carries no origin.
const API_CALLS = {status: ["GET", "/api/status"], register: ["POST", "/api/register"], ban: ["POST", "/api/ban"]};
ipcMain.handle("api", (event, serverUrl, call, body) => new Promise(resolve => {
if (!API_CALLS[call] || !/^https?:\/\//.test(String(serverUrl))) {
resolve({status: 0, body: {}});
return;
}
const [method, apiPath] = API_CALLS[call];
const started = Date.now();
const request = net.request({method, url: new URL(apiPath, serverUrl).href, partition: API_PARTITION});
const give = (status, text) => {
let parsed = {};
try {
parsed = JSON.parse(text);
}
catch (err) {
// not this server, or not there.
}
resolve({status, body: parsed, ms: Date.now() - started});
};
const timer = setTimeout(() => request.abort(), 8000);
request.on("response", response => {
const chunks = [];
response.on("data", chunk => chunks.push(chunk));
response.on("end", () => {
clearTimeout(timer);
give(response.statusCode, Buffer.concat(chunks).toString("utf8"));
});
});
request.on("error", () => {
clearTimeout(timer);
give(0, "");
});
request.on("abort", () => give(0, ""));
if (method === "POST") {
request.setHeader("Content-Type", "application/json");
request.write(JSON.stringify(body || {}));
}
request.end();
}));
// the server's captcha (its lib/captcha.js). cloudflare's widget does not
// run in the login page, which is a file, so it is the server's own
// /captcha page in a small window over the login screen. resolves to the
// answer, or "" when the window is closed without one.
ipcMain.handle("captcha", (event, serverUrl, action) => new Promise(resolve => {
let server;
try {
server = new URL(String(serverUrl));
}
catch (err) {
resolve("");
return;
}
if (!win || event.sender.id !== win.webContents.id || !/^https?:$/.test(server.protocol) || captchaBox) {
resolve("");
return;
}
captchaServer = server.origin;
const box = new BrowserWindow({
parent: win,
modal: true,
width: 360,
height: 200,
useContentSize: true,
resizable: false,
minimizable: false,
maximizable: false,
fullscreenable: false,
backgroundColor: "#000000",
title: "Burrow",
icon: path.join(__dirname, "icon.png"),
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: SANDBOXED,
preload: CAPTCHA_PRELOAD,
partition: CAPTCHA_PARTITION,
},
});
box.setMenu(null);
captchaBox = box;
const id = box.webContents.id;
let answered = false;
const answer = token => {
if (!answered) {
answered = true;
resolve(token);
}
};
const onDone = (doneEvent, token) => {
if (doneEvent.sender.id === id) {
answer(typeof token === "string" && token.length <= 2048 ? token : "");
box.close();
}
};
ipcMain.on("captchaDone", onDone);
box.on("closed", () => {
ipcMain.removeListener("captchaDone", onDone);
captchaBox = null;
captchaServer = null;
answer("");
});
box.loadURL(new URL(`/captcha?action=${action === "signup" ? "signup" : "login"}`, server).href);
}));
// what the client's processes use: the game is the "Pepper Plugin" one.
// memory is each process's own (private) memory where the system says it
// (Windows does). the working set, the other figure there is, counts what
// processes share once for each of them, and came to nearly twice as much.
ipcMain.handle("metrics", () => {
const all = app.getAppMetrics();
const sum = rows => ({
cpu: Math.round(rows.reduce((total, row) => total + row.cpu.percentCPUUsage, 0)),
memoryMb: Math.round(rows.reduce((total, row) => total + (row.memory.privateBytes || row.memory.workingSetSize), 0) / 1024),
});
return {total: sum(all), game: sum(all.filter(row => /plugin/i.test(row.type))), processes: all.length};
});
// how often the game's picture really changes on the screen: the frames
// the window's compositor presents for the game's page, counted for a
// second. this is what reaches the eye, whatever the game says it drew.
// the count stops near 60, which is as fast as frames are handed over.
let countingFrames = false;
ipcMain.handle("painted", async (event, gameContentsId) => {
const game = webContents.fromId(Number(gameContentsId));
if (!game || game.hostWebContents !== event.sender || countingFrames) {
return null;
}
countingFrames = true;
let frames = 0;
try {
game.beginFrameSubscription(true, () => {
frames++;
});
await new Promise(resolve => setTimeout(resolve, 1000));
game.endFrameSubscription();
return frames;
}
catch (err) {
return null;
}
finally {
countingFrames = false;
}
});
ipcMain.handle("screenshot", async (event, gameContentsId) => {
const game = webContents.fromId(Number(gameContentsId));
if (!game || game.hostWebContents !== event.sender) {
return null;
}
const image = await game.capturePage();
if (image.isEmpty()) {
return null;
}
const folder = path.join(app.getPath("pictures"), "Burrow");
await fs.promises.mkdir(folder, {recursive: true});
const stamp = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace("T", " ").replace(/:/g, ".");
const file = path.join(folder, `${stamp}.png`);
await fs.promises.writeFile(file, image.toPNG());
return file;
});
ipcMain.on("showFile", (event, file) => {
// only what the handler above wrote.
if (path.dirname(String(file)) === path.join(app.getPath("pictures"), "Burrow")) {
shell.showItemInFolder(String(file));
}
});
ipcMain.on("openPage", (event, url) => {
if (/^https?:\/\//.test(String(url))) {
shell.openExternal(String(url));
}
});
ipcMain.on("toggleFullscreen", () => {
if (win) {
win.setFullScreen(!win.isFullScreen());
}
});
app.on("web-contents-created", (event, contents) => {
// the game page is a guest: it gets our preload and nothing more.
contents.on("will-attach-webview", (attachEvent, webPreferences) => {
webPreferences.preload = GAME_PRELOAD;
webPreferences.nodeIntegration = false;
webPreferences.contextIsolation = true;
webPreferences.backgroundThrottling = false;
webPreferences.sandbox = SANDBOXED;
});
// the login page stays the login page, and the game page stays on its
// server: a page that arrived any other way would inherit what these have.
contents.on("will-navigate", (navigateEvent, url) => {
let origin = null;
try {
origin = new URL(url).origin;
}
catch (err) {
// not an address: refused below.
}
if (contents.getType() !== "webview" || gameOrigin === null || origin !== gameOrigin) {
navigateEvent.preventDefault();
}
});
contents.on("new-window", (windowEvent, url) => {
windowEvent.preventDefault();
if (/^https?:\/\//.test(url)) {
shell.openExternal(url);
}
});
// keys are seen here even while the Flash plugin has the keyboard.
contents.on("before-input-event", (inputEvent, input) => {
if (input.type !== "keyDown" || !win) {
return;
}
if (input.key === "F11") {
win.setFullScreen(!win.isFullScreen());
inputEvent.preventDefault();
}
else if (input.key === "Escape" && win.isFullScreen()) {
win.setFullScreen(false);
}
else if (input.key === "F12") {
contents.isDevToolsOpened() ? contents.closeDevTools() : contents.openDevTools({mode: "detach"});
inputEvent.preventDefault();
}
else if (input.key === "F10" || input.key === "F7") {
win.webContents.send("shortcut", input.key);
inputEvent.preventDefault();
}
});
});
app.whenReady().then(() => {
session.defaultSession.webRequest.onBeforeRequest((details, answer) => answer({cancel: !mayLoad(details)}));
session.fromPartition(CAPTCHA_PARTITION).webRequest.onBeforeRequest((details, answer) => {
let url = null;
try {
url = new URL(details.url);
}
catch (err) {
// not an address: refused.
}
answer({cancel: !url || !(["data:", "blob:", "about:"].includes(url.protocol) || url.origin === captchaServer || url.origin === CAPTCHA_ORIGIN)});
});
win = new BrowserWindow({
width: 1240,
height: 780,
minWidth: 900,
minHeight: 578,
useContentSize: true,
backgroundColor: "#0f1012",
title: "Burrow",
icon: path.join(__dirname, "icon.png"),
// --aj-hidden: no window on the desktop, for looking at the pages by script.
show: !app.commandLine.hasSwitch("aj-hidden"),
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: SANDBOXED,
webviewTag: true,
plugins: true,
backgroundThrottling: false,
preload: path.join(__dirname, "preload.js"),
},
});
win.setMenu(null);
win.loadFile(path.join(__dirname, "index.html"));
if (builtFor() && global.burrow) {
updates = updater.start({
server: builtFor(),
shell: global.burrow.shell,
running: VERSION,
on: () => readSettings().autoUpdate !== false,
tell: state => {
updateState = state;
if (win) {
win.webContents.send("update", state);
}
},
});
}
for (const [name, on] of [["enter-full-screen", true], ["leave-full-screen", false]]) {
win.on(name, () => win.webContents.send("fullscreen", on));
}
win.on("closed", () => {
win = null;
});
});
app.on("window-all-closed", () => app.quit());
+8
View File
@@ -0,0 +1,8 @@
{
"name": "aj-private-client",
"productName": "Burrow",
"version": "1.1.0",
"description": "The client for the Burrow private server",
"main": "boot.js",
"license": "UNLICENSED"
}
+29
View File
@@ -0,0 +1,29 @@
"use strict";
const {contextBridge, ipcRenderer} = require("electron");
contextBridge.exposeInMainWorld("client", {
info: () => ipcRenderer.invoke("info"),
// makes the game socket reach `serverUrl` (see relay.js).
useServer: (serverUrl, gamePort, gameHost) => ipcRenderer.invoke("useServer", serverUrl, gamePort, gameHost),
// one of the server's /api calls ("status", "register", "ban"): {status, body, ms}.
api: (serverUrl, call, body) => ipcRenderer.invoke("api", serverUrl, call, body),
// the server's captcha ("login" or "signup") in a window of its own: its answer, or "" when there is none.
captcha: (serverUrl, action) => ipcRenderer.invoke("captcha", serverUrl, action),
setGpu: on => ipcRenderer.invoke("setGpu", on),
setAutoUpdate: on => ipcRenderer.invoke("setAutoUpdate", on),
restartToUpdate: () => ipcRenderer.send("restartToUpdate"),
// {state: "ready" | "download", version} from updater.js
onUpdate: listener => ipcRenderer.on("update", (event, state) => listener(state)),
// {total, game}, each {cpu, memoryMb}; processes, how many there are.
metrics: () => ipcRenderer.invoke("metrics"),
// how many times the game's picture changed on the screen in a second, or null.
painted: gameContentsId => ipcRenderer.invoke("painted", gameContentsId),
// saves a picture of the game; resolves to the file's path, or null.
screenshot: gameContentsId => ipcRenderer.invoke("screenshot", gameContentsId),
showFile: file => ipcRenderer.send("showFile", file),
toggleFullscreen: () => ipcRenderer.send("toggleFullscreen"),
openPage: url => ipcRenderer.send("openPage", url),
onFullscreen: listener => ipcRenderer.on("fullscreen", (event, on) => listener(on)),
onShortcut: listener => ipcRenderer.on("shortcut", (event, key) => listener(key)),
});
+50
View File
@@ -0,0 +1,50 @@
"use strict";
const net = require("net");
const tls = require("tls");
// the patched ajclient.swf always opens its game socket to 127.0.0.1. when
// the private server runs on another machine, this relays that local port to
// it, over TLS when the server's address is an https:// one.
let server = null;
const stop = () => {
if (server) {
server.close();
server = null;
}
};
// relays a local port of this copy's own to remoteHost:port and resolves to
// that local port, which the game is then told to connect to; for a local
// server it relays nothing and resolves to `port` itself. 0 when no port
// could be opened.
//
// A port of its own, because two copies logged in to different servers
// cannot share one: the second used to fail to open the game's port, say
// nothing, and send its game (and its login token) through the first copy's
// relay to the first copy's server.
module.exports.use = (remoteHost, port, secure) => new Promise(resolve => {
stop();
if (["127.0.0.1", "localhost", "::1"].includes(remoteHost)) {
resolve(port);
return;
}
const relay = net.createServer(local => {
const remote = secure ? tls.connect({host: remoteHost, port}) : net.connect(port, remoteHost);
local.pipe(remote);
remote.pipe(local);
const close = () => {
local.destroy();
remote.destroy();
};
local.on("error", close);
remote.on("error", close);
local.on("close", close);
remote.on("close", close);
});
server = relay;
relay.on("error", () => resolve(0));
relay.listen(0, "127.0.0.1", () => resolve(relay.address().port));
});
+178
View File
@@ -0,0 +1,178 @@
"use strict";
const {app, net} = require("electron");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const zlib = require("zlib");
// automatic updates of this folder (boot.js starts the newest). an installed
// build asks the server it was built for, at <server>/client/latest.json,
// which names a bundle: every file of the folder, gzipped JSON, signed with
// a key whose private half stays on the machine the builds are made on
// (tools/make-update.js). a bundle that fails the signature is never
// unpacked, so a server that was broken into cannot hand out code.
// the new version is unpacked into the data folder and starts with the next
// start of the client.
const PUBLIC_KEY = crypto.createPublicKey(`-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAvFgBu6kqSLUj9RSK16gBvpGtUoHHuoqtMqZhUzaOEHo=
-----END PUBLIC KEY-----
`);
const FIRST_CHECK_MS = 10000;
const CHECK_EVERY_MS = 6 * 3600000;
const TIMEOUT_MS = 60000;
const MAX_MANIFEST_BYTES = 64 * 1024;
const MAX_BUNDLE_BYTES = 20 * 1024 * 1024;
const PARTITION = "aj-update";
const FILE_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*(\/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*$/;
const VERSION = /^\d{1,5}\.\d{1,5}\.\d{1,5}$/;
const newer = (one, other) => {
const a = String(one).split(".").map(Number);
const b = String(other).split(".").map(Number);
for (let i = 0; i < 3; i++) {
if ((a[i] || 0) !== (b[i] || 0)) {
return (a[i] || 0) > (b[i] || 0);
}
}
return false;
};
const readJson = file => {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
}
catch (err) {
return null;
}
};
// writes `text` so that a reader sees the old file or the new, never half
const writeWhole = (file, text) => {
fs.writeFileSync(`${file}.tmp`, text);
fs.renameSync(`${file}.tmp`, file);
};
const get = (url, maxBytes) => new Promise((resolve, reject) => {
const request = net.request({url, partition: PARTITION});
const timer = setTimeout(() => request.abort(), TIMEOUT_MS);
request.on("response", response => {
if (response.statusCode !== 200) {
clearTimeout(timer);
reject(new Error(`${url}: ${response.statusCode}`));
request.abort();
return;
}
const chunks = [];
let size = 0;
response.on("data", chunk => {
size += chunk.length;
if (size > maxBytes) {
request.abort();
}
else {
chunks.push(chunk);
}
});
response.on("end", () => {
clearTimeout(timer);
resolve(Buffer.concat(chunks));
});
});
request.on("abort", () => {
clearTimeout(timer);
reject(new Error(`${url}: stopped`));
});
request.on("error", err => {
clearTimeout(timer);
reject(err);
});
request.end();
});
// `options`: {server: the address the build was made for, shell: boot.js's
// SHELL, running: the version running now, tell(state): {state: "ready" |
// "download", version}, on(): whether updates are wanted (a setting)}.
const start = options => {
const updates = path.join(app.getPath("userData"), "updates");
const source = new URL("/client/", options.server).href;
let busy = false;
const unpack = (manifest, bundle) => {
const signature = Buffer.from(String(manifest.signature || ""), "base64");
if (!crypto.verify(null, bundle, PUBLIC_KEY, signature)) {
throw new Error("the signature does not match");
}
const {version, shell, files} = JSON.parse(zlib.gunzipSync(bundle).toString("utf8"));
if (version !== manifest.version || !VERSION.test(version) || !Number.isInteger(shell) || shell > options.shell) {
throw new Error("the bundle is not the version named");
}
const names = Object.keys(files || {});
if (!["boot.js", "main.js", "index.html", "package.json"].every(name => names.includes(name))
|| !names.every(name => FILE_NAME.test(name) && typeof files[name] === "string")) {
throw new Error("the bundle's files are not a client");
}
const folder = path.join(updates, `app-${version}`);
const part = `${folder}.part`;
fs.rmdirSync(part, {recursive: true});
for (const name of names) {
const file = path.join(part, ...name.split("/"));
fs.mkdirSync(path.dirname(file), {recursive: true});
fs.writeFileSync(file, Buffer.from(files[name], "base64"));
}
fs.rmdirSync(folder, {recursive: true});
fs.renameSync(part, folder);
writeWhole(path.join(updates, "current.json"), JSON.stringify({version, shell}));
// older ones go, but never the one running
for (const name of fs.readdirSync(updates)) {
const full = path.join(updates, name);
if (/^app-/.test(name) && full !== folder && full !== global.burrow.app) {
fs.rmdirSync(full, {recursive: true});
}
}
return version;
};
const check = async () => {
if (busy || !options.on()) {
return;
}
busy = true;
try {
fs.mkdirSync(updates, {recursive: true});
const manifest = JSON.parse((await get(`${source}latest.json`, MAX_MANIFEST_BYTES)).toString("utf8"));
const staged = readJson(path.join(updates, "current.json"));
const have = staged && newer(staged.version, options.running) ? staged.version : options.running;
const bad = readJson(path.join(updates, "bad.json"));
if (!VERSION.test(manifest.version) || !newer(manifest.version, have) || (bad && bad.version === manifest.version)) {
if (have !== options.running) {
options.tell({state: "ready", version: have});
}
return;
}
if (!Number.isInteger(manifest.shell) || manifest.shell > options.shell) {
options.tell({state: "download", version: manifest.version});
return;
}
if (!/^app-[\d.]+\.burrow$/.test(String(manifest.file))) {
throw new Error("latest.json names no bundle");
}
const version = unpack(manifest, await get(`${source}${manifest.file}`, MAX_BUNDLE_BYTES));
console.log(`[update] ${version} is ready for the next start`);
options.tell({state: "ready", version});
}
catch (err) {
console.log(`[update] ${err.message}`);
}
finally {
busy = false;
}
};
setTimeout(check, FIRST_CHECK_MS);
setInterval(check, CHECK_EVERY_MS);
return {check};
};
module.exports = {start};
+48
View File
@@ -0,0 +1,48 @@
"use strict";
// electron-builder's settings for the linux packages (the windows wizard is
// burrow.nsi). tools/build.sh hands over the staged app, the electron to use
// and where to put the result.
const path = require("path");
const root = path.join(__dirname, "..");
const flash = path.join(root, "flash");
module.exports = {
appId: "software.burrow.client",
productName: "Burrow",
copyright: "",
electronVersion: "11.5.0",
electronDist: process.env.BURROW_ELECTRON,
directories: {app: process.env.BURROW_APP, output: process.env.BURROW_OUT},
// the client finds flash beside its own folder (app/main.js), so no asar
asar: false,
npmRebuild: false,
nodeGypRebuild: false,
publish: null,
// the .deb and .rpm want a homepage and a maintainer; the server's address
// stands in when the build was given one
extraMetadata: {
// the package's name in apt and dnf
name: "burrow",
homepage: process.env.BURROW_HOMEPAGE || "https://play.burrow.moe",
author: {name: "Burrow", email: "[email protected]"},
desktopName: "burrow.desktop",
},
linux: {
target: [{target: "AppImage", arch: ["x64"]}, {target: "deb", arch: ["x64"]}, {target: "rpm", arch: ["x64"]}],
icon: path.join(root, "app", "icon.png"),
category: "Game",
maintainer: "Burrow",
synopsis: "The client for the Burrow server",
description: "The client for Burrow, an AJ Classic private server.",
executableName: "burrow",
// the 2019 flash plugin cannot start inside chromium's sandbox on linux
executableArgs: ["--no-sandbox"],
extraResources: [{from: flash, to: "flash", filter: ["libpepflashplayer.so", "manifest.json"]}],
},
appImage: {artifactName: "Burrow-x86_64.AppImage"},
deb: {artifactName: "burrow_amd64.deb"},
rpm: {artifactName: "burrow.x86_64.rpm"},
};
+69
View File
@@ -0,0 +1,69 @@
; the windows setup wizard. tools/build.sh compiles it with -DVERSION, -DSOURCE
; (the folder to install), -DOUTFILE, -DICON and -DFILES (what the uninstaller removes).
Unicode true
!include "MUI2.nsh"
Name "Burrow"
OutFile "${OUTFILE}"
; per user: no administrator prompt, and an update needs none either
RequestExecutionLevel user
InstallDir "$LOCALAPPDATA\Programs\Burrow"
InstallDirRegKey HKCU "Software\Burrow" "InstallDir"
SetCompressor /SOLID lzma
BrandingText "Burrow ${VERSION}"
VIProductVersion "${VERSION}.0"
VIAddVersionKey "ProductName" "Burrow"
VIAddVersionKey "FileDescription" "Burrow Setup"
VIAddVersionKey "FileVersion" "${VERSION}"
VIAddVersionKey "ProductVersion" "${VERSION}"
VIAddVersionKey "LegalCopyright" ""
!define MUI_ICON "${ICON}"
!define MUI_UNICON "${ICON}"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_RUN "$INSTDIR\Burrow.exe"
!define MUI_FINISHPAGE_RUN_TEXT "Start Burrow"
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\Burrow"
Section "Burrow"
SetOutPath "$INSTDIR"
File /r "${SOURCE}\*.*"
WriteUninstaller "$INSTDIR\Uninstall Burrow.exe"
CreateShortcut "$SMPROGRAMS\Burrow.lnk" "$INSTDIR\Burrow.exe"
CreateShortcut "$DESKTOP\Burrow.lnk" "$INSTDIR\Burrow.exe"
WriteRegStr HKCU "Software\Burrow" "InstallDir" "$INSTDIR"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Burrow"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "Burrow"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\Burrow.exe"
WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall Burrow.exe"'
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
SectionEnd
; only what was installed goes: the folder may be one the player chose, with
; other things in it. remembered accounts and settings live elsewhere and stay.
Section "Uninstall"
!include "${FILES}"
Delete "$INSTDIR\Uninstall Burrow.exe"
RMDir "$INSTDIR"
Delete "$SMPROGRAMS\Burrow.lnk"
Delete "$DESKTOP\Burrow.lnk"
DeleteRegKey HKCU "${UNINSTALL_KEY}"
DeleteRegKey HKCU "Software\Burrow"
SectionEnd
+3487
View File
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
{
"name": "burrow-installers",
"private": true,
"description": "builds the installers; not part of the client",
"devDependencies": {
"electron-builder": "26.16.1"
}
}
Executable
+2
View File
@@ -0,0 +1,2 @@
@echo off
start "" "%~dp0electron-win\electron.exe" "%~dp0app" %*
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
# starts Burrow, the client of the Burrow private server. extra arguments go to Electron.
#
# --no-sandbox: the 2019 Flash plugin cannot start inside Chromium's sandbox
# on a current Linux, so the game would never load without it. the client only
# ever opens its own login page and the private server's game page.
here=$(dirname "$(readlink -f "$0")")
exec "$here/electron/electron" "$here/app" --no-sandbox "$@"
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
# makes the macOS disk image players get: dist/Burrow-macos.dmg, Burrow beside a
# shortcut to Applications to drag it onto. run it on a Mac (BUILDING.md).
#
# tools/build-mac.sh [--server https://play.burrow.moe] [--flash /path/to/PepperFlashPlayer.plugin]
#
# not yet run by anyone: written on linux from electron's layout.
set -euo pipefail
here=$(cd "$(dirname "$0")/.." && pwd)
version=11.5.0
server="https://play.burrow.moe" # --server for another (http://127.0.0.1:8080 to try a build here)
flash=$here/flash/PepperFlashPlayer.plugin
while [ $# -gt 0 ]; do
case "$1" in
--server) server=$2; shift 2 ;;
--flash) flash=$2; shift 2 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
done
[ -d "$flash" ] || { echo "no flash plugin at $flash (BUILDING.md says where to get it)" >&2; exit 1; }
dist=$here/dist
work=$(mktemp -d)
mkdir -p "$dist"
cd "$work"
base=https://github.com/electron/electron/releases/download/v$version
zip=electron-v$version-darwin-x64.zip
curl -fLO "$base/$zip"
curl -fLO "$base/SHASUMS256.txt"
grep " \*$zip\$" SHASUMS256.txt | shasum -a 256 -c -
# ditto keeps the symlinks inside the frameworks, which unzip may not
ditto -x -k "$zip" .
mv Electron.app Burrow.app
res=Burrow.app/Contents/Resources
rm -f "$res/default_app.asar"
cp -R "$here/app" "$res/app"
mkdir "$res/flash"
cp -R "$flash" "$res/flash/PepperFlashPlayer.plugin"
if [ -n "$server" ]; then
printf '{"server": "%s"}\n' "$server" > "$res/app/build.json"
fi
plist=Burrow.app/Contents/Info.plist
/usr/libexec/PlistBuddy -c "Set :CFBundleName Burrow" -c "Set :CFBundleDisplayName Burrow" -c "Set :CFBundleIdentifier software.burrow.client" "$plist"
mkdir icon.iconset
for size in 16 32 128 256; do
sips -z $size $size "$here/app/icon.png" --out icon.iconset/icon_${size}x${size}.png >/dev/null
sips -z $((size * 2)) $((size * 2)) "$here/app/icon.png" --out icon.iconset/icon_${size}x${size}@2x.png >/dev/null
done
iconutil -c icns icon.iconset -o "$res/electron.icns"
# unsigned by a developer; an ad-hoc signature at least keeps the bundle whole
codesign --force --deep --sign - Burrow.app
mkdir image
mv Burrow.app image/
ln -s /Applications image/Applications
rm -f "$dist/Burrow-macos.dmg"
hdiutil create -volname Burrow -srcfolder image -ov -format UDZO "$dist/Burrow-macos.dmg"
shasum -a 256 "$dist/Burrow-macos.dmg"
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env bash
# makes the installers players get, into dist/:
# Burrow-Setup.exe (windows), Burrow-x86_64.AppImage, burrow_amd64.deb, burrow.x86_64.rpm (linux)
#
# tools/build.sh [--server https://play.burrow.moe] [linux] [windows]
#
# needs electron/, electron-win/ and flash/ beside app/, tools/bin/rcedit-x64.exe,
# installer/node_modules (npm install in installer/) and rpmbuild (BUILDING.md).
# the windows wizard is installer/burrow.nsi; the linux packages, installer/builder.config.js.
# the macOS one is tools/build-mac.sh, run on a Mac.
set -euo pipefail
here=$(cd "$(dirname "$0")/.." && pwd)
server="https://play.burrow.moe" # --server for another (http://127.0.0.1:8080 to try a build here)
targets=()
while [ $# -gt 0 ]; do
case "$1" in
--server) server=$2; shift 2 ;;
linux|windows) targets+=("$1"); shift ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
done
[ ${#targets[@]} -gt 0 ] || targets=(linux windows)
if [ -n "$server" ] && ! [[ $server =~ ^https?://[^[:space:]]+$ ]]; then
echo "--server wants an http(s) address" >&2
exit 2
fi
need() {
[ -e "$1" ] || { echo "missing $1 (BUILDING.md)" >&2; exit 1; }
}
need "$here/installer/node_modules/.bin/electron-builder"
version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' "$here/app/package.json")
dist=$here/dist
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$dist"
# the app as players get it, with the server's address
cp -r "$here/app" "$work/app"
if [ -n "$server" ]; then
printf '{"server": "%s"}\n' "$server" > "$work/app/build.json"
fi
# electron.exe gets the logo and the name Burrow before electron-builder
# renames it. rcedit is a windows program: run through wsl, or wine elsewhere.
stamp() {
local rcedit=$here/tools/bin/rcedit-x64.exe exe=$1 ico=$here/tools/icon.ico
need "$rcedit"
local run=("$rcedit")
if grep -qi microsoft /proc/version 2>/dev/null; then
exe=$(wslpath -w "$exe")
ico=$(wslpath -w "$ico")
elif command -v wine >/dev/null; then
run=(wine "$rcedit")
else
echo "setting Burrow.exe's icon needs WSL or wine" >&2
exit 1
fi
"${run[@]}" "$exe" --set-icon "$ico" --set-file-version "$version" --set-product-version "$version" \
--set-version-string ProductName Burrow --set-version-string FileDescription Burrow \
--set-version-string InternalName Burrow --set-version-string OriginalFilename Burrow.exe \
--set-version-string CompanyName Burrow --set-version-string LegalCopyright ""
}
# electron-builder makes the linux packages
builder() {
(cd "$here/installer" && BURROW_APP="$work/app" BURROW_OUT="$work/out" BURROW_ELECTRON="$1" BURROW_HOMEPAGE="$server" \
npx --no-install electron-builder --config builder.config.js "${@:2}")
}
for target in "${targets[@]}"; do
case "$target" in
windows)
need "$here/electron-win/electron.exe"
need "$here/flash/pepflashplayer.dll"
win=$work/windows
cp -r "$here/electron-win" "$win"
rm -f "$win/resources/default_app.asar"
cp -r "$work/app" "$win/resources/app"
mkdir -p "$win/resources/flash"
cp "$here/flash/pepflashplayer.dll" "$win/resources/flash/"
mv "$win/electron.exe" "$win/Burrow.exe"
stamp "$win/Burrow.exe"
# what the uninstaller takes away: the files and folders put there, by name
(cd "$win" && for name in *; do
if [ -d "$name" ]; then printf 'RMDir /r "$INSTDIR\\%s"\n' "$name"; else printf 'Delete "$INSTDIR\\%s"\n' "$name"; fi
done) > "$work/files.nsh"
# electron-builder's own copy of the nsis compiler, fetched and checked by it
nsis=$(cd "$here/installer" && node -e 'require("app-builder-lib/out/toolsets/windows.js").getMakeNsisPath().then(r => console.log(r.path))')
NSISDIR=$(dirname "$(dirname "$nsis")") "$nsis" -V2 -DVERSION="$version" -DSOURCE="$win" -DOUTFILE="$dist/Burrow-Setup.exe" \
-DICON="$here/tools/icon.ico" -DFILES="$work/files.nsh" "$here/installer/burrow.nsi"
;;
linux)
need "$here/electron/electron"
need "$here/flash/libpepflashplayer.so"
command -v rpmbuild >/dev/null || { echo "missing rpmbuild (sudo pacman -S rpm-tools)" >&2; exit 1; }
cp -r "$here/electron" "$work/electron"
chmod 755 "$work/electron/electron" "$work/electron/chrome-sandbox"
builder "$work/electron" --linux --x64
cp "$work/out/Burrow-x86_64.AppImage" "$work/out/burrow_amd64.deb" "$work/out/burrow.x86_64.rpm" "$dist/"
;;
esac
rm -rf "$work/out"
done
(cd "$dist" && sha256sum Burrow-Setup.exe Burrow-x86_64.AppImage burrow_amd64.deb burrow.x86_64.rpm Burrow-macos.dmg 2>/dev/null) > "$dist/SHA256SUMS" || true
ls -lh "$dist"
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env node
"use strict";
// makes an update for the clients already installed (app/updater.js): app/
// as it is, minus build.json, gzipped and signed, plus the latest.json that
// names it. both go to the server's client-updates/ folder, which it serves
// at /client/; committing and pushing the server is what hands it out.
//
// tools/make-update.js [--out <folder>] [--key <file>]
//
// raise "version" in app/package.json first: an update must be newer than
// the one published. the key is ~/.config/burrow/update-key.pem; without it
// no update can be signed that installed clients accept (BUILDING.md).
const crypto = require("crypto");
const fs = require("fs");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
const root = path.join(__dirname, "..");
const args = process.argv.slice(2);
const option = (name, fallback) => (args.includes(name) ? args[args.indexOf(name) + 1] : fallback);
const out = path.resolve(option("--out", path.join(os.homedir(), "ajc-private-server", "client-updates")));
const keyFile = option("--key", path.join(os.homedir(), ".config", "burrow", "update-key.pem"));
const fail = message => {
console.error(message);
process.exit(1);
};
const newer = (one, other) => {
const a = String(one).split(".").map(Number);
const b = String(other).split(".").map(Number);
for (let i = 0; i < 3; i++) {
if ((a[i] || 0) !== (b[i] || 0)) {
return (a[i] || 0) > (b[i] || 0);
}
}
return false;
};
const app = path.join(root, "app");
const {version} = JSON.parse(fs.readFileSync(path.join(app, "package.json"), "utf8"));
const shellMatch = /^const SHELL = (\d+);$/m.exec(fs.readFileSync(path.join(app, "boot.js"), "utf8"));
if (!/^\d+\.\d+\.\d+$/.test(version) || !shellMatch) {
fail("app/package.json needs a version like 1.2.3, and app/boot.js its SHELL");
}
if (!fs.existsSync(keyFile)) {
fail(`no signing key at ${keyFile}`);
}
fs.mkdirSync(out, {recursive: true});
const published = path.join(out, "latest.json");
if (fs.existsSync(published)) {
const before = JSON.parse(fs.readFileSync(published, "utf8")).version;
if (!newer(version, before)) {
fail(`${before} is published already: raise "version" in app/package.json above it`);
}
}
const files = {};
const walk = folder => {
for (const entry of fs.readdirSync(folder, {withFileTypes: true})) {
const full = path.join(folder, entry.name);
const name = path.relative(app, full).split(path.sep).join("/");
if (entry.isDirectory()) {
walk(full);
}
else if (name !== "build.json") {
files[name] = fs.readFileSync(full).toString("base64");
}
}
};
walk(app);
const shell = Number(shellMatch[1]);
const bundle = zlib.gzipSync(JSON.stringify({version, shell, files}), {level: 9});
const signature = crypto.sign(null, bundle, crypto.createPrivateKey(fs.readFileSync(keyFile)));
const file = `app-${version}.burrow`;
for (const old of fs.readdirSync(out).filter(name => /^app-.*\.burrow$/.test(name))) {
fs.unlinkSync(path.join(out, old));
}
fs.writeFileSync(path.join(out, file), bundle);
fs.writeFileSync(published, `${JSON.stringify({version, shell, file, signature: signature.toString("base64")}, null, 2)}\n`);
console.log(`${file}: ${Object.keys(files).length} files, ${Math.round(bundle.length / 1024)} KB, in ${out}`);
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env bash
# copies this repository as it stands at its last commit, minus what stays
# private, into the public one and pushes it:
#
# tools/publish-public.sh [--no-push]
#
# no markdown file of any kind goes public. the public repository has a
# history of its own: nothing of this one's
# history goes there, so a file that was ever committed here and is private
# never shows up in an old public commit. its .gitignore names the private
# paths too, so they are not added there by hand either.
set -euo pipefail
name=burrow-client
remote=[email protected]:burrow-dev/$name.git
# what stays private: nothing beyond what .gitignore keeps out already
# (Electron, the Flash plugin, the builds)
private=()
here=$(cd "$(dirname "$0")/.." && pwd)
public=${BURROW_PUBLIC_DIR:-$HOME/burrow-public/$name}
push=1
[ "${1:-}" = "--no-push" ] && push=0
cd "$here"
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
echo "commit first: the public copy is made from the last commit" >&2
exit 1
fi
source=$(git rev-parse --short HEAD)
ssh_command=$(git config --get core.sshCommand || true)
if [ ! -d "$public/.git" ]; then
mkdir -p "$public"
git -C "$public" init -q -b main
git -C "$public" remote add origin "$remote"
fi
git -C "$public" config user.name "$(git config user.name)"
git -C "$public" config user.email "$(git config user.email)"
[ -n "$ssh_command" ] && git -C "$public" config core.sshCommand "$ssh_command"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
git archive HEAD | tar -x -C "$work"
for path in "${private[@]+"${private[@]}"}"; do
rm -rf "${work:?}/$path"
done
# no markdown file goes public, of any kind (the owner's rule)
find "$work" -name '*.md' -delete
# a last look before anything leaves: none of the game's code or SWFs
leaked=$(find "$work" \( -name '*.swf' -o -name '*.as' -o -name '*.pem' -o -name '*.md' \) -print)
if [ -n "$leaked" ]; then
echo "refused: these would have gone public:" >&2
echo "$leaked" >&2
exit 1
fi
{
cat "$work/.gitignore"
printf '\n# kept in the private repository, never here\n'
printf '*.md\n'
for path in "${private[@]+"${private[@]}"}"; do
printf '/%s\n' "$path"
done
} > "$work/.gitignore.public"
mv "$work/.gitignore.public" "$work/.gitignore"
# the public tree becomes exactly this
find "$public" -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} +
cp -a "$work/." "$public/"
cd "$public"
git add -A
if git diff --cached --quiet; then
echo "the public copy is already up to date"
exit 0
fi
git commit -q -m "Brought up to date with the private repository ($source)"
echo "committed in $public: $(git log -1 --format='%h %s')"
if [ "$push" = 1 ]; then
git push -q -u origin main
echo "pushed to $remote"
fi