Compare commits

...
15 Commits
Author SHA1 Message Date
Burrowdev 22ed8c6792 Client 1.4.0: a client log for bug reports, and sign-up is for players 18 and over
- the client keeps a log (app/log.js): its own messages, the pages' and
  the game's warnings and errors, pages that would not load, crashes. at
  most two files of 1 MB; sign-in tokens and passwords are kept out.
  "Show client log" in the settings opens its folder
- the sign-up box says 18 or older
- "Guide (client side)" is just "Guide"
2026-10-24 05:55:18 +03:00
Burrowdev 8a1b60ad42 fix: a game the graphics card keeps from drawing restarts the client without it 2026-10-24 01:57:49 +03:00
Burrowdev 77be498599 feat: print the pictures the game's print kits send
the game page's ajPrint (printImage) had nothing taking it: the picture now goes on a page of its own in a hidden window that runs no script, and the system print dialog opens.
2026-10-23 21:52:59 +03:00
Burrowdev b52c9194f5 feat: burrow:// links sign the account page in
The account page's "Sign in with the Burrow client" opens
burrow://account?n=<nonce>. The copy already running takes the link (a
copy started with one gives way at once); it uses the account being
played, or the one remembered for its server (a choice when there are
several), gets a ticket from the server and opens it in the browser.
Installed copies register the protocol when they start; the Windows
installer, the Linux packages and the macOS app declare it too.
2026-10-23 07:04:45 +03:00
BurrowdevandClaude Opus 5.5 b1dd733a9d chore: make run.sh executable
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 04:46:27 +03:00
burrow-dev 96774f9f5b Merge pull request #1 from Snipzil/main
feat(auth): add weak password error message & fix URL load fails on captcha
2026-10-22 03:39:12 +03:00
Snipzil 3cb8764603 fix(app): handle captcha URL load failures
Add error handling to the captcha URL loading process to prevent
unhandled promise rejections. If the URL fails to load, the captcha
answer is cleared and the window is closed if it hasn't been destroyed.
2026-10-21 20:34:59 -04:00
BurrowdevandClaude Opus 5.5 17347462cc feat: the theatre browser (client 1.3.3)
The game page can put a web page on the theatre's screen for its player
alone, when the server allows it (the admin panel's switch).

- the page is a <webview> of its own partition (aj-browser): no preload,
  sandboxed, no plugins, no webviews of its own; any other partition is
  refused. it loads http(s) only and opens links in place; its session
  denies every permission and download, and its user agent names no
  Electron or Burrow.
- placed and clipped as the game page says (where the screen is and what
  the game draws over it), and closed with the game.
- the page asks with ipc "browser"; it is told "browserSupported" when
  this client can, and "browserState" for back, forward and the address.
  a webview made inside a webview's ipc handler crashed the window, so
  the message is handled a moment later.
- the old "Theatre browser (experimental)" tick under Advanced is gone:
  the server turns it on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:59 +03:00
BurrowdevandClaude Opus 5.5 66f0c80430 feat: sign-up is for players 16 and over
The sign-up box said "I am 13 or older"; it says 16 now, as the
server's terms, privacy policy and website sign-up do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 20:50:59 +03:00
BurrowdevandClaude Opus 5.5 1d12b7c238 feat: theatre videos (client 1.3.2)
The game page could load nothing but its own server, so the theatre's
YouTube video (staff's, for the room) and a player's own video link were
blocked and showed black. It may now load the YouTube and Vimeo players'
hosts, and the one sound or video file link the player put in the
theatre's box, which the page passes on through the login page. Requests
of the Flash plugin itself stay on the game's server.

Not with onBeforeSendHeaders: in Electron 11 a listener there, even one
that changes nothing, stops YouTube's player.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 02:13:42 +03:00
Snipzil ab8bfd5a9d feat(auth): add weak password error message 2026-10-18 20:12:17 -04:00
Burrowdev 2b70e10624 fix: discord presence on windows (client 1.3.1)
crypto.randomUUID does not exist in Electron 11's Node 12.18, so every
presence update threw in the main process on Windows. Request ids come
from crypto.randomBytes now.
2026-10-18 19:46:27 +03:00
Burrowdev 92c5042c5e feat: discord rich presence
Client 1.3.0 shows "Playing Burrow" on the player's Discord profile while
the game is open: where they are (the game's ajPresence, dens and player
parties never named), the time since they started and a button to the
download page. It goes through the Discord app's local IPC socket (no
packages; Windows pipe, Linux and macOS sockets, Flatpak and Snap too) and
retries quietly while Discord is not running. The server names its Discord
application in its flashvars (discordAppId); none, no presence.
2026-10-18 18:52:34 +03:00
Burrowdev 164e2e8adc Client 1.3.0: checks for updates every 30 minutes, not 6 hours, and shows a ready update on the game's bar too, asking before the restart 2026-10-17 23:45:55 +03:00
Burrowdev a2b70affcc Client 1.3.0: sends one-way hashes of the device's ids at sign-in and sign-up (device.js), for the server's hardware bans; says when the server needs a newer client, and when a device is banned 2026-10-17 21:35:38 +03:00
13 changed files with 1094 additions and 31 deletions

No files matched your search

+184
View File
@@ -0,0 +1,184 @@
"use strict";
const {app} = require("electron");
const {execFile} = require("child_process");
const crypto = require("crypto");
const fs = require("fs");
const os = require("os");
const path = require("path");
// what the server is told about this computer at every sign-in, for
// keeping a banned player's computer out (the server's lib/devices.js).
// nothing is sent as it is: each value is SHA-256 of
// "burrow-device:<kind>:<value>", the value in small letters.
//
// os the system's own id: MachineGuid (Windows), IOPlatformUUID
// (macOS), /etc/machine-id (Linux)
// board the board's id (Windows: the SMBIOS UUID) or the computer's
// serial number (macOS); Linux keeps both from users
// disk the disks' serial numbers
// mac the network cards' addresses, not virtual ones
// install an id of the client's own, kept in two or three places
//
// what looks wrong (the system id missing, or not shaped as it always is,
// or the client's own ids disagreeing) goes as notes. it is read once, at
// start, and takes a second or two on Windows (PowerShell).
const TIMEOUT_MS = 15000;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const MACHINE_ID = /^[0-9a-f]{32}$/;
const TOKEN = /^[0-9a-f]{64}$/;
// network cards that are not one: virtual machines' and containers' own.
const VIRTUAL_NAME = /^(lo|docker|veth|br-|virbr|vmnet|vboxnet|tun|tap|wg|zt|utun|awdl|llw|bridge|ham|tailscale|vEthernet)/i;
const VIRTUAL_MAC = /^(00:05:69|00:0c:29|00:1c:14|00:50:56|08:00:27|0a:00:27|52:54:00|00:15:5d|00:1c:42|00:16:3e|02:42)/;
const hash = (kind, value) => crypto.createHash("sha256").update(`burrow-device:${kind}:${String(value).trim().toLowerCase()}`).digest("hex");
const run = (file, args) => new Promise(resolve => {
execFile(file, args, {timeout: TIMEOUT_MS, windowsHide: true, maxBuffer: 1024 * 1024}, (error, stdout) => resolve(error ? "" : String(stdout)));
});
const readFile = file => {
try {
return fs.readFileSync(file, "utf8").trim();
}
catch (err) {
return "";
}
};
const writeFile = (file, text) => {
try {
fs.mkdirSync(path.dirname(file), {recursive: true});
fs.writeFileSync(file, text);
}
catch (err) {
// somewhere it cannot be kept; the others may do.
}
};
const windows = async () => {
const guid = (/MachineGuid\s+REG_SZ\s+(\S+)/i.exec(await run("reg", ["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid"])) || [])[1] || "";
const cim = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command",
"(Get-CimInstance Win32_ComputerSystemProduct).UUID; '--'; Get-CimInstance Win32_DiskDrive | ForEach-Object { $_.SerialNumber }"]);
const [board, disks] = cim.split(/^--\s*$/m);
return {os: guid, osShape: UUID, board: (board || "").trim(), disks: (disks || "").split(/\r?\n/)};
};
const mac = async () => {
const ioreg = await run("ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"]);
const field = name => ((new RegExp(`"${name}"\\s*=\\s*"([^"]+)"`)).exec(ioreg) || [])[1] || "";
const storage = await run("system_profiler", ["SPNVMeDataType", "SPSerialATADataType"]);
const disks = [];
const serial = /Serial Number:\s*(\S+)/g;
let found = serial.exec(storage);
while (found) {
disks.push(found[1]);
found = serial.exec(storage);
}
return {os: field("IOPlatformUUID"), osShape: UUID, board: field("IOPlatformSerialNumber"), disks};
};
const linux = async () => {
let disks = [];
try {
// the names say the model and the serial ("ata-Samsung_SSD_860_S3Z9NB0K123456X"),
// and anyone may read them; not partitions, USB sticks or their other names.
disks = fs.readdirSync("/dev/disk/by-id").filter(name => /^(ata|nvme|scsi|mmc)-/.test(name) && !/-part\d+$/.test(name)
&& !/^nvme-(eui|nvme)\./.test(name));
}
catch (err) {
// no such folder: a container, say.
}
return {os: readFile("/etc/machine-id") || readFile("/var/lib/dbus/machine-id"), osShape: MACHINE_ID, board: "", disks};
};
const macAddresses = () => {
const found = new Set();
const cards = os.networkInterfaces();
for (const name of Object.keys(cards)) {
for (const card of cards[name]) {
const address = String(card.mac || "").toLowerCase();
// the second bit of the first byte marks an address made up by the system (random, or virtual).
const madeUp = (parseInt(address.slice(0, 2), 16) & 2) === 2;
if (!card.internal && address && address !== "00:00:00:00:00:00" && !madeUp && !VIRTUAL_NAME.test(name) && !VIRTUAL_MAC.test(address)) {
found.add(address);
}
}
}
return [...found].sort();
};
// the client's own id: the same one wherever it is found, written back
// where it is missing. a new one when there is none.
const installId = async notes => {
const places = [path.join(app.getPath("userData"), "install-id")];
if (process.platform === "darwin") {
places.push(path.join(os.homedir(), "Library", "Preferences", ".moe.burrow.install"));
}
else if (process.platform !== "win32") {
places.push(path.join(os.homedir(), ".local", "share", ".burrow-install"));
}
const found = places.map(readFile).filter(text => TOKEN.test(text));
// on Windows the registry is the other place.
const registry = process.platform === "win32"
? (/Install\s+REG_SZ\s+(\S+)/i.exec(await run("reg", ["query", "HKCU\\Software\\Burrow", "/v", "Install"])) || [])[1] || "" : "";
if (TOKEN.test(registry)) {
found.push(registry);
}
if (new Set(found).size > 1) {
notes.push("install_mismatch");
}
const id = found[0] || crypto.randomBytes(32).toString("hex");
for (const place of places) {
if (readFile(place) !== id) {
writeFile(place, id);
}
}
if (process.platform === "win32" && registry !== id) {
await run("reg", ["add", "HKCU\\Software\\Burrow", "/v", "Install", "/t", "REG_SZ", "/d", id, "/f"]);
}
return id;
};
const collect = async () => {
const notes = [];
let read = {os: "", osShape: null, board: "", disks: []};
try {
read = process.platform === "win32" ? await windows() : process.platform === "darwin" ? await mac() : await linux();
}
catch (err) {
// what could be read is sent; the rest is not.
}
const system = String(read.os || "").trim().toLowerCase().replace(/^\{|\}$/g, "");
if (!system) {
notes.push("os_missing");
}
else if (read.osShape && !read.osShape.test(system)) {
notes.push("os_odd");
}
const disks = [...new Set((read.disks || []).map(serial => String(serial).trim()).filter(Boolean))].slice(0, 8);
const ids = {
install: hash("install", await installId(notes)),
disk: disks.map(serial => hash("disk", serial)),
mac: macAddresses().slice(0, 8).map(address => hash("mac", address)),
};
if (system) {
ids.os = hash("os", system);
}
if (String(read.board || "").trim()) {
ids.board = hash("board", read.board);
}
return {v: 1, ids, notes};
};
let collecting = null;
// {v: 1, ids, notes}, read once and kept.
const device = () => {
if (!collecting) {
collecting = collect().catch(() => ({v: 1, ids: {}, notes: ["failed"]}));
}
return collecting;
};
module.exports = {device};
+193
View File
@@ -0,0 +1,193 @@
"use strict";
// Discord rich presence: "Playing Burrow" on the player's Discord profile,
// with where they are in the game, the time since they started and a button
// to the download page. it goes through the Discord app on this computer
// (its local IPC socket, as Discord's own SDK does), so nothing about it
// leaves the computer from here. the server names its Discord application
// (its flashvars' discordAppId); a server that names none gets no presence.
// Discord not running, or started later: tried again now and then, quietly.
const crypto = require("crypto");
const net = require("net");
const path = require("path");
const OP_HANDSHAKE = 0;
const OP_FRAME = 1;
const OP_CLOSE = 2;
const OP_PING = 3;
const OP_PONG = 4;
const RETRY_MS = 30000;
const MAX_FRAME = 64 * 1024;
// where the Discord app listens: a named pipe on Windows; elsewhere a socket
// in the runtime or temporary folder, or inside a Flatpak or Snap Discord's.
const socketPaths = () => {
const numbers = [...Array(10).keys()];
if (process.platform === "win32") {
return numbers.map(n => `\\\\?\\pipe\\discord-ipc-${n}`);
}
const bases = [...new Set([process.env.XDG_RUNTIME_DIR, process.env.TMPDIR, process.env.TMP, process.env.TEMP, "/tmp"].filter(Boolean))];
const inside = ["", "app/com.discordapp.Discord", "app/com.discordapp.DiscordCanary", "snap.discord", "snap.discord-canary"];
return bases.flatMap(base => inside.flatMap(folder => numbers.map(n => path.join(base, folder, `discord-ipc-${n}`))));
};
let wanted = null; // {appId, activity} to show, or null
let socket = null;
let socketAppId = null;
let ready = false;
let retry = null;
let buffer = Buffer.alloc(0);
// a request's id. (not crypto.randomUUID: Electron 11's Node 12 has none)
const nonce = () => crypto.randomBytes(16).toString("hex");
const frame = (op, data) => {
const body = Buffer.from(JSON.stringify(data));
const head = Buffer.alloc(8);
head.writeInt32LE(op, 0);
head.writeInt32LE(body.length, 4);
return Buffer.concat([head, body]);
};
const send = () => {
if (!socket || !ready || !wanted || wanted.appId !== socketAppId) {
return;
}
socket.write(frame(OP_FRAME, {cmd: "SET_ACTIVITY", args: {pid: process.pid, activity: wanted.activity},
nonce: nonce()}));
};
const drop = () => {
if (socket) {
socket.removeAllListeners();
socket.on("error", () => {});
socket.destroy();
}
socket = null;
socketAppId = null;
ready = false;
buffer = Buffer.alloc(0);
};
const later = () => {
if (!retry && wanted) {
retry = setTimeout(() => {
retry = null;
connect();
}, RETRY_MS);
}
};
const onData = chunk => {
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 8) {
const op = buffer.readInt32LE(0);
const length = buffer.readInt32LE(4);
if (length < 0 || length > MAX_FRAME) {
drop();
later();
return;
}
if (buffer.length < 8 + length) {
return;
}
const body = buffer.subarray(8, 8 + length);
buffer = buffer.subarray(8 + length);
let data = {};
try {
data = JSON.parse(body.toString("utf8"));
}
catch (err) {
// not ours to understand; go on
}
if (op === OP_PING) {
socket.write(frame(OP_PONG, data));
}
else if (op === OP_CLOSE) {
drop();
later();
return;
}
else if (op === OP_FRAME && data.evt === "READY") {
ready = true;
send();
}
}
};
// tries each place Discord may listen, in turn.
const connect = (places = socketPaths()) => {
if (!wanted || socket) {
return;
}
if (!places.length) {
later();
return;
}
const appId = wanted.appId;
const attempt = net.createConnection(places[0]);
attempt.once("error", () => {
attempt.destroy();
if (socket === null) {
connect(places.slice(1));
}
});
attempt.once("connect", () => {
if (!wanted || wanted.appId !== appId) {
attempt.destroy();
connect();
return;
}
socket = attempt;
socketAppId = appId;
socket.removeAllListeners("error");
socket.on("data", onData);
socket.on("error", () => {});
socket.on("close", () => {
if (socket === attempt) {
drop();
later();
}
});
socket.write(frame(OP_HANDSHAKE, {v: 1, client_id: appId}));
});
};
// what to show: {appId, state, start, url} while the game is open, or null.
const set = info => {
const appId = info && /^\d{5,25}$/.test(String(info.appId)) ? String(info.appId) : null;
if (!appId) {
if (wanted) {
wanted = null;
if (socket && ready) {
socket.write(frame(OP_FRAME, {cmd: "SET_ACTIVITY", args: {pid: process.pid}, nonce: nonce()}));
}
}
return;
}
const activity = {
details: "Playing Burrow",
timestamps: {start: Number.isFinite(info.start) ? Math.floor(info.start) : Date.now()},
assets: {large_image: "burrow", large_text: "Burrow"},
instance: false,
};
if (typeof info.state === "string" && info.state.trim().length >= 2) {
activity.state = info.state.trim().slice(0, 100);
}
if (typeof info.url === "string" && /^https:\/\/[^\s]{1,200}$/.test(info.url)) {
activity.buttons = [{label: "Play Burrow", url: info.url}];
}
wanted = {appId, activity};
if (socket && socketAppId !== appId) {
drop();
}
if (socket) {
send();
}
else if (!retry) {
connect();
}
};
module.exports = {set};
+6
View File
@@ -6,6 +6,9 @@ const sendWhitelist = new Set()
.add("initialized")
.add("fps")
.add("openPage")
.add("browser")
.add("ownVideo")
.add("presence")
.add("printImage")
.add("reloadGame")
.add("reportError")
@@ -14,6 +17,9 @@ const sendWhitelist = new Set()
const receiveWhitelist = new Set()
.add("flashVarsReady")
.add("hud")
.add("ownVideoReady")
.add("browserSupported")
.add("browserState")
.add("removed");
contextBridge.exposeInMainWorld(
+275 -23
View File
@@ -168,11 +168,11 @@
a { color: inherit; text-underline-offset: 3px; }
a:hover { color: var(--text); }
#ban-popup, #rename-popup { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 10; display: flex; align-items: center; justify-content: center; padding: 20px; background: rgba(0, 0, 0, 0.85); }
#rename-box { width: 100%; max-width: 400px; padding: 28px 28px 24px; background: var(--panel); border: 1px solid var(--line); border-radius: 22px; }
#rename-box h2 { margin: 0 0 16px; font-size: 22px; font-weight: 700; }
#rename-box .buttons { display: flex; gap: 10px; margin-top: 6px; }
#rename-box .buttons button { flex: 1; margin: 0; padding: 10px 16px 11px; font-size: 16px; }
#ban-popup, #rename-popup, #link-popup { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 10; display: flex; align-items: center; justify-content: center; padding: 20px; background: rgba(0, 0, 0, 0.85); }
#rename-box, #link-box { width: 100%; max-width: 400px; padding: 28px 28px 24px; background: var(--panel); border: 1px solid var(--line); border-radius: 22px; }
#rename-box h2, #link-box h2 { margin: 0 0 16px; font-size: 22px; font-weight: 700; }
#rename-box .buttons, #link-box .buttons { display: flex; gap: 10px; margin-top: 6px; }
#rename-box .buttons button, #link-box .buttons button { flex: 1; margin: 0; padding: 10px 16px 11px; font-size: 16px; }
#ban-box { width: 100%; max-width: 480px; max-height: 100%; overflow-y: auto; padding: 30px 30px 26px; background: var(--panel); border: 1px solid var(--line); border-radius: 22px; }
#ban-head { display: flex; align-items: center; gap: 14px; }
#ban-head img { flex: none; width: 48px; height: 48px; }
@@ -193,8 +193,9 @@
#ban-buttons button { flex: 1; margin: 0; padding: 10px 16px 11px; font-size: 16px; }
#saved { margin: 0 0 16px; padding: 0; list-style: none; }
#saved li { display: flex; gap: 6px; margin: 0 0 6px; }
#saved .account {
#saved li, #link-accounts li { display: flex; gap: 6px; margin: 0 0 6px; }
#link-accounts { margin: 0 0 16px; padding: 0; list-style: none; }
#saved .account, #link-accounts .account {
flex: 1;
min-width: 0;
display: flex;
@@ -204,10 +205,10 @@
text-align: left;
font-weight: 700;
}
#saved .account::after { content: "→"; margin-left: auto; color: var(--muted); font-weight: 400; }
#saved .account:hover { background: var(--text); border-color: var(--text); color: #000; }
#saved .account::after, #link-accounts .account::after { content: "→"; margin-left: auto; color: var(--muted); font-weight: 400; }
#saved .account:hover, #link-accounts .account:hover { background: var(--text); border-color: var(--text); color: #000; }
#saved .account:hover::after, #saved .account:hover .where { color: #000; }
#saved .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#saved .name, #link-accounts .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#saved .where { font-size: 12px; font-weight: 400; color: var(--muted); white-space: nowrap; }
#saved .forget { flex: none; width: 40px; padding: 0; border-color: transparent; color: var(--muted); font-size: 18px; }
#saved .forget:hover { color: var(--text); border-color: var(--line); }
@@ -250,6 +251,7 @@
#bar button { border: 0; padding: 3px 10px 4px; font-size: 13px; color: var(--muted); }
#bar button:hover { color: var(--text); background: var(--raised); }
#bar button[aria-pressed="true"], #bar button[aria-expanded="true"] { color: #000; background: var(--text); }
#bar #bar-update { color: #000; background: var(--text); font-weight: 700; }
body.fullscreen { --bar-height: 0px; }
body.fullscreen #bar, body.fullscreen #stats { display: none; }
#stage { position: relative; flex: 1; display: flex; align-items: center; justify-content: center; background: #000; min-height: 0; }
@@ -258,6 +260,12 @@
width: min(100vw, calc((100vh - var(--bar-height)) * 900 / 550));
height: min(calc(100vh - var(--bar-height)), calc(100vw * 550 / 900));
}
/* the theatre's browser, over the theatre screen (theatreBrowser below) */
#theatre-browser-view {
position: absolute;
z-index: 1;
background: #fff;
}
#loading {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
@@ -336,7 +344,7 @@
<label>2FA code
<input id="totp" type="text" inputmode="numeric" maxlength="20" spellcheck="false">
</label>
<label class="check"><input id="remember-device" type="checkbox"> Trust this computer for 30 days</label>
<label class="check"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
</div>
<label class="check"><input id="remember" type="checkbox"> Remember me</label>
<button id="log-in" class="main" type="submit">Log in</button>
@@ -363,7 +371,7 @@
</label>
<label class="check"><input id="new-remember" type="checkbox"> Remember me</label>
<label class="check agree"><input id="new-agreed" type="checkbox">
<span>I am 13 or older, and old enough in my country to agree to this myself. I agree to the <a href="#" id="terms-signup">Terms of Service</a> and the <a href="#" id="privacy-signup">Privacy Policy</a>.</span></label>
<span>I am 18 or older, and old enough in my country to agree to this myself. I agree to the <a href="#" id="terms-signup">Terms of Service</a> and the <a href="#" id="privacy-signup">Privacy Policy</a>.</span></label>
<button id="sign-up" class="main" type="submit">Create account</button>
</div>
<p id="signup-status" class="status" role="status"></p>
@@ -383,7 +391,7 @@
<option value="4">Developer</option>
</select>
</label>
<label class="check"><input id="guide" type="checkbox" data-choice> Guide (client side)</label>
<label class="check"><input id="guide" type="checkbox" data-choice> Guide</label>
<label>Starting room
<input id="starting-room" type="text" spellcheck="false" placeholder="jamaa_township.room_main">
</label>
@@ -394,6 +402,8 @@
<label class="check"><input id="allow-unencrypted" type="checkbox"> Allow unencrypted</label>
<label class="check" id="auto-update-part" hidden><input id="auto-update" type="checkbox"> Automatic updates</label>
<p class="hint" id="version-hint"></p>
<button type="button" id="show-log">Show client log</button>
<p class="hint">Attach client.log to a bug report.</p>
</details>
</div>
</main>
@@ -433,9 +443,20 @@
</form>
</div>
<div id="link-popup" role="dialog" aria-modal="true" aria-labelledby="link-title" hidden>
<div id="link-box">
<h2 id="link-title">Sign in to the account page as</h2>
<ul id="link-accounts"></ul>
<div class="buttons">
<button id="link-cancel" type="button">Cancel</button>
</div>
</div>
</div>
<div id="game" hidden>
<div id="bar">
<span id="who"></span>
<button id="bar-update" type="button" hidden></button>
<span id="glance"><span id="glance-badge" class="badge off" hidden>Offline</span><span id="glance-text"></span><span id="fps" title="Pictures the game drew in the last second"></span><span id="note" role="status"></span></span>
<button id="stats-toggle" type="button" aria-expanded="false" aria-controls="stats">Stats</button>
<button id="mute" type="button" aria-pressed="false" title="F7">Mute</button>
@@ -495,9 +516,11 @@
username_taken: "That username is already taken.",
name_not_allowed: "That username is not allowed.",
invalid_password: "Passwords need 10 characters or more, with a capital letter, a small letter and a digit.",
weak_password: "That password is too easy to guess: it is a common one, or has your username in it.",
choose_animal: "Choose an animal first.",
too_many_registrations: "Too many accounts were created from your address. Try again in an hour.",
address_banned: "Your address is banned.",
device_banned: "This device is banned.",
agree_first: "Tick the box to agree first.",
same_name: "That is the name that was rejected.",
captcha_required: "Complete the captcha.",
@@ -508,6 +531,11 @@
const METRICS_EVERY_MS = 2000;
// the game says when it is drawn; if it never does, show it anyway.
const LOADING_AT_MOST_MS = 25000;
// a game not drawn this long after it started, with the graphics card
// in use, is taken for one the card keeps from drawing (main.js
// gpuFallback): the client starts again without it.
const GPU_WATCH_MS = 60000;
let gpuWatch = null;
let info = null;
let session = null; // {server, flashVars, since} while the game is open
@@ -646,7 +674,7 @@
remove.type = "button";
remove.className = "forget";
remove.textContent = "×";
remove.title = `Forget ${entry.username} on this computer`;
remove.title = `Forget ${entry.username} on this device`;
remove.setAttribute("aria-label", remove.title);
remove.addEventListener("click", () => {
forget(entry.server, entry.username);
@@ -783,13 +811,13 @@
let banServer = null;
// the popup of a ban: how long, why, and where to ask about it (and,
// when it is for good, where the account can be deleted).
// `ofAddress`: it is the address that is banned, not the account.
const showBan = (server, username, seconds, reason, ofAddress = false) => {
// `of`: what is banned: false the account, true its address, "device" this device.
const showBan = (server, username, seconds, reason, of = false) => {
banServer = server;
const left = Number(seconds);
$("ban-title").textContent = banTitle(left);
$("ban-name").textContent = username;
$("ban-address").textContent = ofAddress ? " · your address" : "";
$("ban-address").textContent = of === "device" ? " · this device" : of ? " · your address" : "";
$("ban-reason-part").hidden = !reason;
$("ban-facts").classList.toggle("bare", !reason);
$("ban-until").textContent = left < 0 ? "Permanent"
@@ -872,10 +900,13 @@
remember_device: !$("code-part").hidden && $("remember-device").checked,
captcha_pass: given ? given.captchaPass : passFor(server, username),
};
// which computer this is (the client's device.js): the server lets no
// sign-in in without it.
const device = await window.client.device();
const authenticate = body => getJson(`${server}/authenticate`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
body: JSON.stringify({...body, device}),
});
let auth = await authenticate(request);
if (auth.body.error === "captcha_required") {
@@ -891,6 +922,9 @@
if (SIGNUP_MESSAGES[auth.body.error] && /^captcha_/.test(auth.body.error)) {
throw new Error(SIGNUP_MESSAGES[auth.body.error]);
}
if (auth.status === 426 || auth.body.error === "client_outdated") {
throw new Error("This server needs a newer Burrow client. Update it from the server's download page.");
}
if (auth.status === 401 && auth.body.error === "totp_required") {
showCodePart(true);
$("totp").focus();
@@ -904,9 +938,10 @@
// banned: for good, or for how much longer. (A saved sign-in is
// kept: it is the ban that is in the way, not the sign-in.)
// An address is banned for good, whoever signs in from it.
if (auth.status === 401 && (auth.body.error === "account_banned" || auth.body.error === "address_banned")) {
const ofAddress = auth.body.error === "address_banned";
showBan(server, username, ofAddress ? -1 : Number(auth.body.banned_seconds), String(auth.body.ban_reason || ""), ofAddress);
// A computer likewise (the server's lib/devices.js).
if (auth.status === 401 && ["account_banned", "address_banned", "device_banned"].includes(auth.body.error)) {
const of = auth.body.error === "device_banned" ? "device" : auth.body.error === "address_banned";
showBan(server, username, of ? -1 : Number(auth.body.banned_seconds), String(auth.body.ban_reason || ""), of);
throw new Error("Banned.");
}
if (auth.status === 401 && auth.body.error === "name_rejected") {
@@ -1048,12 +1083,27 @@
}
};
// Discord rich presence (discord.js), while the game is open: the
// server's Discord application (flashvars discordAppId), where the
// player is and since when they have played.
const showPresence = state => {
if (!session || !session.flashVars || !session.flashVars.discordAppId) {
return;
}
session.presenceState = state || session.presenceState || "";
window.client.presence({appId: session.flashVars.discordAppId, state: session.presenceState,
start: session.since || Date.now(), url: session.flashVars.presenceUrl});
};
const closeGame = message => {
clearTimeout(gpuWatch);
window.client.presence(null);
$("fps").textContent = "";
if (webview) {
webview.remove();
webview = null;
}
theatreBrowser.close();
session = null;
$("game").hidden = true;
$("login").hidden = false;
@@ -1085,7 +1135,7 @@
closeGame();
}
showBan(ended.server, ended.flashVars.username, Number(answer.body.banned_seconds), String(answer.body.ban_reason || ""),
answer.body.banned === "address");
answer.body.banned === "device" ? "device" : answer.body.banned === "address");
}
};
@@ -1098,12 +1148,117 @@
$("hud").textContent = "HUD";
};
// the theatre's browser (experimental; the server's admin turns it on
// for its game page): the game page (the server's game.html) says where the
// theatre screen is and what to show, and a webview of its own is laid
// over it here, in a session that keeps nothing (main.js). nothing of
// it goes to the server, and it sees nothing of the game.
const theatreBrowser = (() => {
let view = null;
let ready = false; // a webview answers nothing before its first dom-ready
const webAddress = text => {
try {
const url = new URL(String(text));
return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
}
catch (err) {
return null;
}
};
const tell = () => {
if (view && ready && webview) {
let url = "";
try {
url = view.getURL();
}
catch (err) {
// not attached yet
}
webview.send("browserState", {url, back: view.canGoBack(), forward: view.canGoForward(), loading: view.isLoading()});
}
};
const close = () => {
if (view) {
view.remove();
view = null;
ready = false;
}
};
const open = url => {
if (view && ready) {
view.loadURL(url);
return;
}
if (view) {
view.src = url;
return;
}
view = document.createElement("webview");
view.id = "theatre-browser-view";
view.setAttribute("partition", "aj-browser");
view.src = url;
view.style.visibility = "hidden";
view.addEventListener("dom-ready", () => {
ready = true;
tell();
});
for (const name of ["did-navigate", "did-navigate-in-page", "did-start-loading", "did-stop-loading", "did-fail-load"]) {
view.addEventListener(name, tell);
}
$("stage").append(view);
};
// where: {x, y, w, h} in the game page's pixels, `clip` its CSS
// clip-path (what the game draws over it cut out), `shown`.
const place = where => {
if (!view || !webview || !where) {
return;
}
const game = webview.getBoundingClientRect();
const stage = $("stage").getBoundingClientRect();
const number = value => (Number.isFinite(Number(value)) ? Number(value) : 0);
view.style.left = `${game.left - stage.left + number(where.x)}px`;
view.style.top = `${game.top - stage.top + number(where.y)}px`;
view.style.width = `${Math.max(0, number(where.w))}px`;
view.style.height = `${Math.max(0, number(where.h))}px`;
view.style.clipPath = typeof where.clip === "string" && /^(?:none|polygon\(evenodd,[0-9a-z%.,\s]*\))$/.test(where.clip) ? where.clip : "none";
view.style.visibility = where.shown === true ? "visible" : "hidden";
};
return {
close,
// one message from the game page: {action, url?, where?}
handle(message) {
if (!message || typeof message !== "object") {
return;
}
const url = webAddress(message.url);
if (message.action === "go" && url) {
open(url);
}
else if (message.action === "close") {
close();
}
else if (view && ready && message.action === "back" && view.canGoBack()) {
view.goBack();
}
else if (view && ready && message.action === "forward" && view.canGoForward()) {
view.goForward();
}
else if (view && ready && message.action === "reload") {
view.reload();
}
place(message.where);
tell();
},
};
})();
const openGame = () => {
// A reload keeps the sound as it was; a login starts as the setting says.
const muted = webview ? isMuted() : fieldValue("start-muted");
if (webview) {
webview.remove();
}
theatreBrowser.close();
// A fresh webview each time: the page and the plugin start clean.
webview = document.createElement("webview");
webview.setAttribute("plugins", "");
@@ -1112,6 +1267,8 @@
webview.addEventListener("dom-ready", () => {
setMuted(muted);
webview.send("flashVarsReady", session.flashVars);
// this client can show the theatre's browser; the server says whether it is offered
webview.send("browserSupported", true);
}, {once: true});
webview.addEventListener("did-fail-load", event => {
if (event.isMainFrame) {
@@ -1123,6 +1280,7 @@
$("fps").textContent = `· ${Number(event.args[0]) || 0} fps`;
}
if (event.channel === "initialized") {
clearTimeout(gpuWatch);
gameIsDrawn();
}
else if (event.channel === "reloadGame") {
@@ -1139,14 +1297,41 @@
else if (event.channel === "reportError") {
reportError(event.args[0]);
}
else if (event.channel === "printImage") {
// the game's print kits and art studios (game.html ajPrint)
window.client.printImage(event.args[0]);
}
else if (event.channel === "openPage") {
// main.js opens http and https addresses only
window.client.openPage(String(event.args[0]));
}
else if (event.channel === "browser") {
// not inside this handler: Electron 11 takes the whole window
// down when a webview is made while another's message is handled.
const message = event.args[0];
setTimeout(() => theatreBrowser.handle(message), 0);
}
else if (event.channel === "ownVideo") {
// the player's own theatre video (the game page's link box): main.js
// lets that one address load, then the page plays it.
const link = String(event.args[0] || "");
window.client.ownVideo(link).then(() => webview.send("ownVideoReady", link));
}
else if (event.channel === "presence") {
// where the player is now (the game's AJClient.presenceRoom)
showPresence(String(event.args[0] || ""));
}
});
$("loading").hidden = false;
clearTimeout(loadingTimer);
loadingTimer = setTimeout(gameIsDrawn, LOADING_AT_MOST_MS);
clearTimeout(gpuWatch);
if (info && info.gpu) {
gpuWatch = setTimeout(() => {
closeGame("The game did not start with the graphics card. Burrow is restarting without it (Use GPU, under Advanced, turns it back on).");
setTimeout(() => window.client.gpuFallback(), 4000);
}, GPU_WATCH_MS);
}
$("stage").prepend(webview);
$("who").textContent = `${session.flashVars.username} · ${new URL(session.server).host}`;
$("stats-tip").textContent = fieldValue("account-type") === "4"
@@ -1166,6 +1351,7 @@
session = await login();
setStatus("", false, statusId);
openGame();
showPresence("");
}
catch (err) {
$("log-in").disabled = false;
@@ -1186,6 +1372,62 @@
setStatus("");
});
// "Sign in with the Burrow client" on the server's account page (its
// lib/manage.js; the link comes through main.js): the account played
// now, or one remembered here, gets a ticket from the server that
// opens the page signed in, in the browser that asked. the browser
// already asked whether to open Burrow, so with one account there is
// nothing more to ask.
const tellAccountPage = (text, bad) => (session ? note(text) : setStatus(text, bad));
const pickAccount = choices => new Promise(resolve => {
const list = $("link-accounts");
list.textContent = "";
const done = choice => {
$("link-popup").hidden = true;
$("link-cancel").onclick = null;
resolve(choice);
};
for (const choice of choices) {
const row = document.createElement("li");
const button = document.createElement("button");
button.type = "button";
button.className = "account";
const name = document.createElement("span");
name.className = "name";
name.textContent = choice.username;
button.append(name);
button.addEventListener("click", () => done(choice));
row.append(button);
list.append(row);
}
$("link-cancel").onclick = () => done(null);
$("link-popup").hidden = false;
list.querySelector("button").focus();
});
window.client.onAccountLink(async nonce => {
if (!$("link-popup").hidden) {
return;
}
const choices = session
? [{server: session.server, username: session.flashVars.username, token: session.flashVars.auth_token}]
: remembered().filter(entry => entry.server === serverUrl());
if (choices.length === 0) {
tellAccountPage("Log in here first, then try the account page again.", true);
return;
}
const choice = choices.length === 1 ? choices[0] : await pickAccount(choices);
if (!choice) {
return;
}
const answer = await window.client.api(choice.server, "accountTicket", {token: choice.token, nonce});
if (answer.status !== 200 || !/^https?:\/\//.test(String(answer.body.url))) {
tellAccountPage(answer.body.error || "The account page could not be signed in.", true);
return;
}
window.client.openPage(answer.body.url);
tellAccountPage(`Account page signed in as ${answer.body.username}.`, false);
});
// another name is another account: its code is not this one's.
$("username").addEventListener("input", () => showCodePart(false));
@@ -1384,24 +1626,34 @@
// updates (the client's updater.js): one fetched waits for a restart,
// and one that needs a new install is a download from the server's site.
// shown on the login card, and on the game's bar for those playing.
let update = null;
const showUpdate = state => {
update = state;
$("update-line").hidden = !state;
$("bar-update").hidden = !state;
if (state) {
$("update-button").textContent = state.state === "ready" ? `Update ${state.version} ready · Restart` : `Burrow ${state.version} · Download`;
$("bar-update").textContent = state.state === "ready" ? `Update ${state.version} · Restart` : `Burrow ${state.version} · Download`;
}
};
window.client.onUpdate(showUpdate);
$("update-button").addEventListener("click", () => {
const takeUpdate = () => {
if (update && update.state === "ready") {
window.client.restartToUpdate();
}
else if (update) {
window.client.openPage(`${info.defaultServer}/`);
}
};
$("update-button").addEventListener("click", takeUpdate);
$("bar-update").addEventListener("click", () => {
if (!update || update.state !== "ready" || window.confirm("Restart Burrow now to update? This leaves the game.")) {
takeUpdate();
}
});
$("auto-update").addEventListener("change", () => window.client.setAutoUpdate($("auto-update").checked));
$("show-log").addEventListener("click", () => window.client.showLog());
window.client.info().then(result => {
info = result;
+139
View File
@@ -0,0 +1,139 @@
"use strict";
const {app} = require("electron");
const fs = require("fs");
const os = require("os");
const path = require("path");
const util = require("util");
// the client's log, for players to attach to a bug report: what the client
// itself says, what its pages and the game print to their consoles
// (warnings and errors), and crashes and pages that would not load. it is
// <data folder>/logs/client.log; once that is MAX_BYTES it becomes
// client.old.log (the one before it goes) and a new one starts, so the two
// are never more than twice that. "Show client log" in the client's
// settings (index.html) opens the folder.
//
// what could let someone into an account is kept out: an address's query
// (where sign-in tokens travel) and anything written as password=, token=
// and the like.
const MAX_BYTES = 1024 * 1024;
const MAX_ENTRY = 4000; // characters of one entry; a long stack is cut
// a page printing in a loop fills the log with one thing: past this many
// entries in BURST_MS the rest are counted, not written
const BURST_ENTRIES = 200;
const BURST_MS = 10000;
let file = null;
let oldFile = null;
let size = 0;
let header = ""; // which client and computer: the first line of each file
let burstStart = 0;
let burstCount = 0;
let leftOut = 0;
const SECRET = /\b(password|passwd|pass|token|session|secret|auth|nonce|code|key)(["']?\s*[:=]\s*["']?)[^\s&"',;}]+/gi;
const QUERY = /\b(https?:\/\/[^\s?#"'<>]+)\?[^\s"'<>]*/gi;
const scrub = text => text.replace(QUERY, "$1?…").replace(SECRET, "$1$2[hidden]");
const stamp = () => new Date().toISOString();
const append = text => {
if (file === null) {
return;
}
try {
const bytes = Buffer.byteLength(text);
if (size + bytes > MAX_BYTES) {
fs.renameSync(file, oldFile);
fs.writeFileSync(file, header);
size = Buffer.byteLength(header);
}
fs.appendFileSync(file, text);
size += bytes;
}
catch (err) {
// a log that cannot be written is no reason to stop the client
}
};
// `level` "info", "warn" or "error"; `source` what said it ("main", "page",
// "game"); `parts` as console.log takes them.
const write = (level, source, ...parts) => {
const now = Date.now();
if (now - burstStart > BURST_MS) {
if (leftOut > 0) {
append(`${stamp()} warn [log] ${leftOut} more entries in ${BURST_MS / 1000} seconds were left out\n`);
}
burstStart = now;
burstCount = 0;
leftOut = 0;
}
if (++burstCount > BURST_ENTRIES) {
leftOut++;
return;
}
let text = scrub(util.format(...parts));
if (text.length > MAX_ENTRY) {
text = `${text.slice(0, MAX_ENTRY)}… (${text.length - MAX_ENTRY} more characters)`;
}
append(`${stamp()} ${level.padEnd(5)} [${source}] ${text.replace(/\r?\n/g, "\n ")}\n`);
};
// Chromium's console levels: 0 verbose, 1 info, 2 warning, 3 error
const CONSOLE_LEVELS = [null, null, "warn", "error"];
const watchContents = contents => {
const source = contents.getType() === "webview" ? "game" : "page";
contents.on("console-message", (event, level, message, line, sourceId) => {
if (CONSOLE_LEVELS[level]) {
write(CONSOLE_LEVELS[level], source, `${message}${sourceId ? ` (${path.basename(String(sourceId).split("?")[0])}:${line})` : ""}`);
}
});
contents.on("did-fail-load", (event, code, description, url, isMainFrame) => {
if (code !== -3) { // -3: the load was stopped for another, not a failure
write("warn", source, `could not load ${url}${isMainFrame ? "" : " (part of the page)"}: ${description} (${code})`);
}
});
contents.on("plugin-crashed", (event, name, version) => write("error", source, `the ${name} plugin ${version} crashed`));
contents.on("unresponsive", () => write("warn", source, "stopped responding"));
contents.on("responsive", () => write("info", source, "responding again"));
};
// starts the log; the data folder must be chosen by then
const start = version => {
const dir = path.join(app.getPath("userData"), "logs");
try {
fs.mkdirSync(dir, {recursive: true});
file = path.join(dir, "client.log");
oldFile = path.join(dir, "client.old.log");
size = fs.existsSync(file) ? fs.statSync(file).size : 0;
}
catch (err) {
file = null;
return;
}
header = `${stamp()} info [main] Burrow ${version}, Electron ${process.versions.electron}, ${os.type()} ${os.release()} ${process.arch}, ${Math.round(os.totalmem() / 1048576)} MB\n`;
append(header);
// the main process's own console goes to the log as well
for (const [method, level] of [["log", "info"], ["info", "info"], ["warn", "warn"], ["error", "error"]]) {
const original = console[method].bind(console);
console[method] = (...parts) => {
original(...parts);
write(level, "main", ...parts);
};
}
process.on("uncaughtExceptionMonitor", err => write("error", "main", `uncaught: ${err && err.stack ? err.stack : err}`));
process.on("unhandledRejection", err => write("error", "main", `unhandled rejection: ${err && err.stack ? err.stack : err}`));
app.on("web-contents-created", (event, contents) => watchContents(contents));
app.on("render-process-gone", (event, contents, details) => write("error", "main", `a page's process ended: ${details.reason} (exit code ${details.exitCode})`));
app.on("child-process-gone", (event, details) => {
if (details.reason !== "clean-exit") {
write("error", "main", `the ${details.name || details.type} process ended: ${details.reason} (exit code ${details.exitCode})`);
}
});
app.on("will-quit", () => write("info", "main", "quit"));
};
module.exports = {start, write, file: () => file};
+264 -6
View File
@@ -3,6 +3,9 @@
const {app, BrowserWindow, ipcMain, net, session, shell, webContents} = require("electron");
const fs = require("fs");
const path = require("path");
const device = require("./device.js");
const discord = require("./discord.js");
const log = require("./log.js");
const relay = require("./relay.js");
const updater = require("./updater.js");
@@ -22,10 +25,24 @@ if (!app.commandLine.hasSwitch("user-data-dir")) {
app.setPath("userData", path.join(app.getPath("appData"), "AJ Private Client"));
}
// burrow:// links: the server's account page asks the client to sign it in
// ("Sign in with the Burrow client", burrow://account?n=<nonce>; index.html
// does the rest). windows and linux start a new copy with the link: the copy
// already running takes it, and the new one goes at once. a copy started to
// play beside the first still plays; only one that came with a link gives way.
// macOS hands the link to the running app (open-url) instead.
const LINK_PROTOCOL = "burrow";
const linkIn = argv => argv.find(arg => String(arg).toLowerCase().startsWith(`${LINK_PROTOCOL}://`)) || null;
let pendingLink = linkIn(process.argv);
if (!app.requestSingleInstanceLock() && pendingLink) {
process.exit(0);
}
// 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;
log.start(VERSION);
// a packaged build names its server in build.json (tools/build.sh --server)
const builtFor = () => {
@@ -74,6 +91,21 @@ 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";
// the theatre's browser (experimental, index.html): a webview of its own
// over the theatre screen, in a session of its own that is kept in memory
// only, so nothing it visits stays and none of it reaches the game.
const BROWSER_PARTITION = "aj-browser";
let browserSession = null;
const isBrowser = contents => browserSession !== null && contents.session === browserSession;
const webAddress = text => {
try {
const url = new URL(String(text));
return url.protocol === "https:" || url.protocol === "http:";
}
catch (err) {
return false;
}
};
// 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
@@ -181,6 +213,20 @@ let updateState = null; // the last thing the updater said, for a page loaded af
ipcMain.handle("setGpu", (event, on) => {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify({...readSettings(), gpu: on === true}));
});
// some graphics cards (or their drivers) leave the game on its loading
// screen for good; players got past it by turning "Use GPU" off. the page
// asks for that itself when the game has not drawn in time (index.html).
ipcMain.on("gpuFallback", () => {
if (!usesGpu || app.commandLine.hasSwitch("aj-gpu")) {
return;
}
fs.writeFileSync(SETTINGS_FILE, JSON.stringify({...readSettings(), gpu: false}));
app.relaunch();
app.exit(0);
});
// what the server is told about this computer at sign-in (device.js).
ipcMain.handle("device", () => device.device());
ipcMain.handle("info", () => ({
// as this run was started; a change takes effect at the next start.
@@ -215,6 +261,25 @@ ipcMain.handle("useServer", (event, serverUrl, gamePort, gameHost) => {
// 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:"];
// the theatre's video (the server's game page: the room's, played by staff,
// and the player's own from its link box): the YouTube and Vimeo players
// and what they load, measured in this Electron. a host here counts with
// every host under it.
const VIDEO_PLAYER_HOSTS = [
"youtube-nocookie.com", "youtube.com", "ytimg.com", "ggpht.com", "googlevideo.com",
"jnn-pa.googleapis.com", "gstatic.com", "www.google.com",
"vimeo.com", "vimeocdn.com",
];
const videoPlayerHost = host => VIDEO_PLAYER_HOSTS.some(known => host === known || host.endsWith(`.${known}`));
// the player's own sound or video file (the game page's link box): the one
// address they typed, as the game page says it (ownVideo below), and where
// it redirects. a <video>'s file is an "other" request in this Electron, as
// is everything the Flash plugin asks for; those stay on the game's server
// otherwise.
let ownMedia = null;
const ownMediaRequests = new Set(); // request ids of it, through redirects
const withoutHash = url => url.href.replace(/#.*$/, "");
const mayLoad = details => {
let url;
try {
@@ -229,13 +294,47 @@ const mayLoad = details => {
if (win && details.webContentsId === win.webContents.id) {
return url.protocol === "http:" || url.protocol === "https:";
}
return gameOrigin !== null && url.origin === gameOrigin;
if (gameOrigin !== null && url.origin === gameOrigin) {
return true;
}
if (gameOrigin === null || (url.protocol !== "https:" && url.protocol !== "http:") || details.resourceType === "object") {
return false;
}
if (details.resourceType === "other" || details.resourceType === "media") {
if (ownMediaRequests.has(details.id) || (ownMedia !== null && withoutHash(url) === ownMedia)) {
ownMediaRequests.add(details.id);
return true;
}
return false;
}
return url.protocol === "https:" && videoPlayerHost(url.hostname.toLowerCase());
};
// the link the player put in the theatre's box, or "" when it stopped: from
// the login page (index.html), which hears it from the game page. resolves
// once requests for it may go.
ipcMain.handle("ownVideo", (event, link) => {
if (!win || event.sender !== win.webContents) {
return false;
}
ownMedia = null;
try {
const url = new URL(String(link || ""));
if (url.protocol === "https:" || url.protocol === "http:") {
ownMedia = withoutHash(url);
}
}
catch (err) {
// stopped, or not an address
}
return ownMedia !== null;
});
// 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"]};
const API_CALLS = {status: ["GET", "/api/status"], register: ["POST", "/api/register"], ban: ["POST", "/api/ban"],
accountTicket: ["POST", "/account/api/client-ticket"]};
const apiRequest = (serverUrl, call, body) => new Promise(resolve => {
const [method, apiPath] = API_CALLS[call];
const started = Date.now();
@@ -274,7 +373,8 @@ ipcMain.handle("api", async (event, serverUrl, call, body) => {
if (!API_CALLS[call] || !/^https?:\/\//.test(String(serverUrl))) {
return {status: 0, body: {}};
}
const first = await apiRequest(serverUrl, call, body);
// a sign-up says which computer it is on, as a sign-in does (device.js).
const first = await apiRequest(serverUrl, call, call === "register" ? {...body, device: await device.device()} : body);
if (call !== "status" || first.status === 0) {
return first;
}
@@ -347,7 +447,12 @@ ipcMain.handle("captcha", (event, serverUrl, action) => new Promise(resolve => {
captchaServer = null;
answer("");
});
box.loadURL(new URL(`/captcha?action=${action === "signup" ? "signup" : "login"}`, server).href);
box.loadURL(new URL(`/captcha?action=${action === "signup" ? "signup" : "login"}`, server).href).catch(() => {
answer("");
if (!box.isDestroyed()) {
box.close();
}
});
}));
// what the client's processes use: the game is the "Pepper Plugin" one.
@@ -415,12 +520,106 @@ ipcMain.on("showFile", (event, file) => {
}
});
// the client's log (log.js), shown in its folder for a bug report
ipcMain.on("showLog", event => {
if (win && event.sender === win.webContents && log.file()) {
shell.showItemInFolder(log.file());
}
});
ipcMain.on("openPage", (event, url) => {
if (/^https?:\/\//.test(String(url))) {
shell.openExternal(String(url));
}
});
// a picture the game prints (its print kits and art studios, through the
// game page's ajPrint): {image, a JPEG in base64; width; height}. it goes on
// a page of its own, in a window that is never shown and runs no script,
// and the system's print dialog opens for it; nothing of it is kept after.
const MAX_PRINT_BASE64 = 40 * 1024 * 1024;
ipcMain.on("printImage", (event, picture) => {
const image = picture && typeof picture.image === "string" ? picture.image : "";
if (!image || image.length > MAX_PRINT_BASE64 || !/^[A-Za-z0-9+/=\r\n]+$/.test(image)) {
return;
}
const landscape = Number(picture.width) > Number(picture.height);
let folder;
try {
folder = fs.mkdtempSync(path.join(app.getPath("temp"), "burrow-print-"));
fs.writeFileSync(path.join(folder, "picture.jpg"), Buffer.from(image, "base64"));
fs.writeFileSync(path.join(folder, "print.html"), "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>"
+ `@page { margin: 0; size: ${landscape ? "landscape" : "portrait"}; } html, body { margin: 0; height: 100%; }`
+ " img { display: block; width: 100%; height: 100%; object-fit: contain; }</style></head><body><img src=\"picture.jpg\"></body></html>");
}
catch (error) {
return;
}
const cleanUp = () => {
try {
fs.rmdirSync(folder, {recursive: true});
}
catch (error) {
// the temporary folder goes another time
}
};
const page = new BrowserWindow({show: false, webPreferences: {javascript: false, sandbox: true, contextIsolation: true}});
page.webContents.once("did-finish-load", () => {
page.webContents.print({silent: false, printBackground: true}, () => {
page.destroy();
cleanUp();
});
});
page.webContents.once("did-fail-load", () => {
page.destroy();
cleanUp();
});
page.loadFile(path.join(folder, "print.html"));
});
// a burrow:// link (above), once the login page is there to take it: only
// the account page's nonce goes on, and the window comes to the front.
const accountNonce = link => {
try {
const url = new URL(link);
const nonce = url.searchParams.get("n") || "";
return url.protocol === `${LINK_PROTOCOL}:` && url.hostname === "account" && /^[0-9a-f]{48}$/.test(nonce) ? nonce : null;
}
catch (err) {
return null;
}
};
const takeLink = () => {
if (!pendingLink || !win || win.webContents.isLoading()) {
return;
}
const nonce = accountNonce(pendingLink);
pendingLink = null;
if (nonce) {
if (win.isMinimized()) {
win.restore();
}
win.show();
win.focus();
win.webContents.send("accountLink", nonce);
}
};
app.on("second-instance", (event, argv) => {
pendingLink = linkIn(argv) || pendingLink;
takeLink();
});
app.on("open-url", (event, link) => {
event.preventDefault();
pendingLink = link;
takeLink();
});
// Discord rich presence (discord.js): {appId, state, start, url} while the
// game is open, null when it is not.
ipcMain.on("presence", (event, info) => {
discord.set(info && typeof info === "object" ? info : null);
});
ipcMain.on("toggleFullscreen", () => {
if (win) {
win.setFullScreen(!win.isFullScreen());
@@ -429,16 +628,38 @@ ipcMain.on("toggleFullscreen", () => {
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;
contents.on("will-attach-webview", (attachEvent, webPreferences, params) => {
webPreferences.nodeIntegration = false;
webPreferences.contextIsolation = true;
// the theatre's browser: a web page like any, with nothing of ours.
if (params.partition === BROWSER_PARTITION) {
delete webPreferences.preload;
delete webPreferences.preloadURL;
webPreferences.sandbox = true;
webPreferences.plugins = false;
webPreferences.webviewTag = false;
if (!webAddress(params.src)) {
params.src = "about:blank";
}
return;
}
if (params.partition) {
attachEvent.preventDefault();
return;
}
webPreferences.preload = GAME_PRELOAD;
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) => {
if (isBrowser(contents)) {
if (!webAddress(url)) {
navigateEvent.preventDefault();
}
return;
}
let origin = null;
try {
origin = new URL(url).origin;
@@ -452,6 +673,13 @@ app.on("web-contents-created", (event, contents) => {
});
contents.on("new-window", (windowEvent, url) => {
windowEvent.preventDefault();
// the theatre's browser opens a new window's page in itself
if (isBrowser(contents)) {
if (webAddress(url)) {
contents.loadURL(url);
}
return;
}
if (/^https?:\/\//.test(url)) {
shell.openExternal(url);
}
@@ -480,7 +708,30 @@ app.on("web-contents-created", (event, contents) => {
});
app.whenReady().then(() => {
device.device(); // read now, so the first sign-in does not wait
session.defaultSession.webRequest.onBeforeRequest((details, answer) => answer({cancel: !mayLoad(details)}));
// only watching: in Electron 11 a listener that may change requests
// (onBeforeSendHeaders, even one that changes nothing) stops YouTube's player.
session.defaultSession.webRequest.onCompleted(details => ownMediaRequests.delete(details.id));
session.defaultSession.webRequest.onErrorOccurred(details => ownMediaRequests.delete(details.id));
// the theatre's browser: the web, and nothing of this computer's; no
// camera, microphone, notifications or the like, and no downloads. it says
// it is plain Chrome, which sites know, not this client.
browserSession = session.fromPartition(BROWSER_PARTITION);
browserSession.setUserAgent(browserSession.getUserAgent().replace(/ (?:Electron|Burrow|aj-private-client)\/\S+/gi, ""));
browserSession.setPermissionRequestHandler((contents, permission, answer) => answer(false));
browserSession.setPermissionCheckHandler(() => false);
browserSession.on("will-download", downloadEvent => downloadEvent.preventDefault());
browserSession.webRequest.onBeforeRequest((details, answer) => {
let url = null;
try {
url = new URL(details.url);
}
catch (err) {
// not an address: refused.
}
answer({cancel: !url || !["https:", "http:", "data:", "blob:", "about:"].includes(url.protocol)});
});
session.fromPartition(CAPTCHA_PARTITION).webRequest.onBeforeRequest((details, answer) => {
let url = null;
try {
@@ -513,7 +764,14 @@ app.whenReady().then(() => {
},
});
win.setMenu(null);
win.webContents.on("did-finish-load", takeLink);
win.loadFile(path.join(__dirname, "index.html"));
// an installed copy answers burrow:// links (the installers say so too;
// this keeps it so after an update or a move). a copy run from the
// repository leaves them to the installed one.
if (builtFor() && !app.isDefaultProtocolClient(LINK_PROTOCOL)) {
app.setAsDefaultProtocolClient(LINK_PROTOCOL);
}
if (builtFor() && global.burrow) {
updates = updater.start({
server: builtFor(),
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "aj-private-client",
"productName": "Burrow",
"version": "1.2.0",
"version": "1.4.0",
"description": "The client for the Burrow private server",
"main": "boot.js",
"license": "UNLICENSED"
+15
View File
@@ -8,9 +8,14 @@ contextBridge.exposeInMainWorld("client", {
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),
// hashes of this computer's ids, for the server's sign-in (device.js).
device: () => ipcRenderer.invoke("device"),
// 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),
// the game did not start drawing with the graphics card: it is turned off
// (as "Use GPU" would) and the client starts again.
gpuFallback: () => ipcRenderer.send("gpuFallback"),
setAutoUpdate: on => ipcRenderer.invoke("setAutoUpdate", on),
restartToUpdate: () => ipcRenderer.send("restartToUpdate"),
// {state: "ready" | "download", version} from updater.js
@@ -22,8 +27,18 @@ contextBridge.exposeInMainWorld("client", {
// 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),
// the client's log file in its folder, to attach to a bug report (log.js)
showLog: () => ipcRenderer.send("showLog"),
toggleFullscreen: () => ipcRenderer.send("toggleFullscreen"),
openPage: url => ipcRenderer.send("openPage", url),
// a picture from the game to print (main.js): {image, width, height}
printImage: picture => ipcRenderer.send("printImage", picture),
// the player's own theatre video file, which the game page may then load; "" when stopped.
ownVideo: link => ipcRenderer.invoke("ownVideo", link),
// Discord rich presence (discord.js): {appId, state, start, url}, or null.
presence: info => ipcRenderer.send("presence", info),
onFullscreen: listener => ipcRenderer.on("fullscreen", (event, on) => listener(on)),
onShortcut: listener => ipcRenderer.on("shortcut", (event, key) => listener(key)),
// the server's account page asking to be signed in (main.js): its nonce.
onAccountLink: listener => ipcRenderer.on("accountLink", (event, nonce) => listener(String(nonce))),
});
+1 -1
View File
@@ -20,7 +20,7 @@ MCowBQYDK2VwAyEAvFgBu6kqSLUj9RSK16gBvpGtUoHHuoqtMqZhUzaOEHo=
-----END PUBLIC KEY-----
`);
const FIRST_CHECK_MS = 10000;
const CHECK_EVERY_MS = 6 * 3600000;
const CHECK_EVERY_MS = 30 * 60000; // latest.json is a few hundred bytes
const TIMEOUT_MS = 60000;
const MAX_MANIFEST_BYTES = 64 * 1024;
const MAX_BUNDLE_BYTES = 20 * 1024 * 1024;
+4
View File
@@ -30,6 +30,10 @@ module.exports = {
desktopName: "burrow.desktop",
},
// burrow:// links, from the account page's "Sign in with the Burrow
// client" (the .desktop file's MimeType; app/main.js asks for them too)
protocols: [{name: "Burrow", schemes: ["burrow"]}],
linux: {
target: [{target: "AppImage", arch: ["x64"]}, {target: "deb", arch: ["x64"]}, {target: "rpm", arch: ["x64"]}],
icon: path.join(root, "app", "icon.png"),
+7
View File
@@ -53,6 +53,12 @@ Section "Burrow"
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall Burrow.exe"'
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
; burrow:// links, from the account page's "Sign in with the Burrow client"
; (app/main.js writes the same when it starts)
WriteRegStr HKCU "Software\Classes\burrow" "" "URL:burrow"
WriteRegStr HKCU "Software\Classes\burrow" "URL Protocol" ""
WriteRegStr HKCU "Software\Classes\burrow\shell\open\command" "" '"$INSTDIR\Burrow.exe" "%1"'
SectionEnd
; only what was installed goes: the folder may be one the player chose, with
@@ -66,4 +72,5 @@ Section "Uninstall"
Delete "$DESKTOP\Burrow.lnk"
DeleteRegKey HKCU "${UNINSTALL_KEY}"
DeleteRegKey HKCU "Software\Burrow"
DeleteRegKey HKCU "Software\Classes\burrow"
SectionEnd
Regular → Executable
View File
File mode changed.
+5
View File
@@ -53,6 +53,11 @@ 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"
# burrow:// links (the account page's "Sign in with the Burrow client"):
# macOS takes only those the app names here.
/usr/libexec/PlistBuddy -c "Add :CFBundleURLTypes array" -c "Add :CFBundleURLTypes:0 dict" \
-c "Add :CFBundleURLTypes:0:CFBundleURLName string Burrow" -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes array" \
-c "Add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string burrow" "$plist"
mkdir icon.iconset
for size in 16 32 128 256; do