@zaisma/cli 0.60.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/check.d.mts CHANGED
@@ -19,7 +19,11 @@ export type CheckProblemCode =
19
19
  | "file_download"
20
20
  | "outside_link"
21
21
  | "outside_frame"
22
- | "blocked_feature";
22
+ | "blocked_feature"
23
+ | "crypto_miner"
24
+ | "disguised_code"
25
+ | "password_field"
26
+ | "wallet_request";
23
27
 
24
28
  export type ProblemKind = "refused" | "broken";
25
29
 
package/check.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  // the upload command runs it in Node and the site imports it as it is.
5
5
  // Docs: https://github.com/zaisma/zaisma-sdk/blob/main/docs/DEVELOPER-API.md#checking-a-game
6
6
  import { findAssetNotes } from "./performance.mjs";
7
+ import { runFixedChecks } from "./fixed-checks.mjs";
7
8
 
8
9
  /** Every file type a game may contain: the extensions in CONTENT_TYPES (packages/core/src/mime.ts), in its order. */
9
10
  export const GAME_FILE_EXTENSIONS = [
@@ -47,6 +48,19 @@ export const CHECK_PROBLEM_CODES = {
47
48
  outside_link: { problemKind: "broken", isFixedByUploadCommand: false, meaning: "A link that opens another site or a new window, which the game's frame doesn't allow." },
48
49
  outside_frame: { problemKind: "broken", isFixedByUploadCommand: false, meaning: "A frame of another site, which games can't show." },
49
50
  blocked_feature: { problemKind: "broken", isFixedByUploadCommand: false, meaning: "Camera, microphone, screen capture, location, payments, USB, serial, Bluetooth or HID, which games on Zaisma can't use." },
51
+ // Zaisma's fixed checks (fixed-checks.mjs): the scan refuses a version with any of these, the same answer every time.
52
+ crypto_miner: { problemKind: "refused", isFixedByUploadCommand: false, meaning: "The code mines cryptocurrency." },
53
+ disguised_code: { problemKind: "refused", isFixedByUploadCommand: false, meaning: "The code runs text it decodes (base64, character codes or bytes) as code, which hides what it runs." },
54
+ password_field: { problemKind: "refused", isFixedByUploadCommand: false, meaning: "The game has a password field." },
55
+ wallet_request: { problemKind: "refused", isFixedByUploadCommand: false, meaning: "The game asks for a crypto wallet's seed phrase or private key, or for access to a wallet other than Bitcoin's." },
56
+ };
57
+
58
+ /** What to do about each fixed check's refusal. */
59
+ const FIXED_CHECK_FIXES = {
60
+ crypto_miner: "Take the mining code out.",
61
+ disguised_code: "Ship the code as plain files the game loads. An ordinary minified or bundled build is fine, and so is running a file from the game's own files; eval or the Function constructor on text decoded from base64, character codes or bytes isn't.",
62
+ password_field: "Take the password field out: players sign in with Zaisma, so games never ask for passwords. For a secret code players type, use a plain text field.",
63
+ wallet_request: "Take the request out: a game never asks for a seed phrase or private key, and crypto on Zaisma is Bitcoin only, with no asking for access to a player's wallet.",
50
64
  };
51
65
 
52
66
  /** Hosts that appear in nearly every file and never load anything (the scan's own list, packages/core/src/scan/static.ts). */
@@ -413,6 +427,11 @@ export function checkGameFiles(files, { slug = null, ownServerUrls = null } = {}
413
427
  const threadsMatch = THREADS_PATTERNS.map((pattern) => pattern.exec(text)).find(Boolean);
414
428
  if (threadsMatch) addThreads(COI_SERVICE_WORKER_PATTERN.test(path) ? coiServiceWorkerMessage(path) : `${path} is from a build that needs threads (SharedArrayBuffer), which only Chrome and Edge give games on Zaisma.`, lineAround(text, threadsMatch.index), path);
415
429
 
430
+ for (const finding of runFixedChecks([{ path, text }]).findings) {
431
+ if (finding.severity !== "reject") continue;
432
+ add(finding.code, { message: `${path}: ${finding.message}`, path, quote: finding.quote ?? null, fix: FIXED_CHECK_FIXES[finding.code] });
433
+ }
434
+
416
435
  if (isEngineOutput(path, lowercasePaths)) continue;
417
436
  // What the code does, not what its comments say: a library's docs mention alert() and window.open.
418
437
  const code = blankComments(text, fileKind);
@@ -0,0 +1,39 @@
1
+ // Types for fixed-checks.mjs, so the site and the tests import the fixed checks type-checked.
2
+
3
+ export type FixedCheckSeverity = "reject" | "hold" | "info";
4
+
5
+ export interface FixedCheckFile {
6
+ path: string;
7
+ text: string;
8
+ }
9
+
10
+ export interface FixedCheck {
11
+ code: string;
12
+ severity: FixedCheckSeverity;
13
+ message: string;
14
+ only?: RegExp;
15
+ /** Where in the file the check found what it looks for, or null. */
16
+ find(file: FixedCheckFile): number | null;
17
+ }
18
+
19
+ export interface FixedCheckFinding {
20
+ stage: "static";
21
+ severity: FixedCheckSeverity;
22
+ code: string;
23
+ message: string;
24
+ path?: string;
25
+ quote?: string;
26
+ }
27
+
28
+ export const MINER_PATTERN: RegExp;
29
+ export const IGNORED_HOSTS: Set<string>;
30
+ export const MINER_SEARCH_PIECE_SIZE_BYTES: number;
31
+ export const MINER_SEARCH_OVERLAP_SIZE_BYTES: number;
32
+ export const FIXED_CHECKS: FixedCheck[];
33
+ export const REFUSING_CHECK_CODES: string[];
34
+ export function isMinerPiece(bytes: Uint8Array): boolean;
35
+ export function isMinerModule(bytes: Uint8Array): boolean;
36
+ export function isWasmModule(bytes: Uint8Array): boolean;
37
+ export function embeddedWasmModules(text: string): { index: number; isMinerLike: boolean }[];
38
+ export function runFixedChecks(files: FixedCheckFile[], ownServerHosts?: readonly string[]): { findings: FixedCheckFinding[]; outsideHosts: string[] };
39
+ export function wasmFileFindings(path: string, bytes: Uint8Array): FixedCheckFinding[];
@@ -0,0 +1,528 @@
1
+ // Zaisma's fixed checks: what every upload passes before it can go live, the same answer every time. The upload's scan,
2
+ // the API's check_game and `zaisma check` all run this one list. MIT licensed.
3
+ //
4
+ // The checks are a list that grows: a new check is one more entry in FIXED_CHECKS, and changing one touches no other.
5
+ // A refusal ("reject") is something a game can't do and the sandbox can't stop while it runs; a note ("info") is
6
+ // something the sandbox already stops, so the game only bumps into it and is told how to fix it.
7
+ import { tokenizer } from "acorn";
8
+
9
+ /** Words only crypto-mining code carries: miner scripts and services, pool addresses, the CryptoNight hash. */
10
+ export const MINER_PATTERN = /coinhive|coin-hive|cryptonight|cryptoloot|webminepool|deepminer|coinimp|minero\.cc|stratum\+(tcp|ssl):\/\/|xmr-?stak|monero[-_ ]?miner|webmr\.js|crypta\.js/i;
11
+
12
+ /** Function names only a cryptocurrency miner's WebAssembly has (CryptoNight, RandomX). No \b: Emscripten prefixes C names with "_". */
13
+ const MINER_MODULE_PATTERN = /(?<![A-Za-z0-9])(?:randomx_(?:alloc_cache|init_cache|create_vm|calculate_hash(?:_first|_next)?)|cn_slow_hash|cn_fast_hash|cryptonight_hash)(?![A-Za-z0-9])/i;
14
+
15
+ const HTML = /\.(html?|svg)$/i;
16
+ const SCRIPT = /\.(m?js|cjs)$/i;
17
+
18
+ /** Hosts that appear in nearly every file and never load anything. */
19
+ export const IGNORED_HOSTS = new Set(["www.w3.org", "w3.org", "schemas.xmlsoap.org", "ns.adobe.com", "purl.org", "xmlns.com", "localhost", "127.0.0.1"]);
20
+ /** Hosts a game may connect to without listing them. */
21
+ const ROOMS_HOST = "rooms.zaisma.com";
22
+ const URL_PATTERN = /(?:https?:|wss?:)?\/\/([a-z0-9-]+(?:\.[a-z0-9-]+)+)(?::\d+)?(?=[/"'`?#\s)]|$)/gi;
23
+ /** A link opened with window.open or a new-tab link; the registered way is Zaisma.links.open. */
24
+ const UNREGISTERED_LINK_PATTERN =
25
+ /\bwindow\.open\(\s*["'`](?:https?:)?\/\/[a-z0-9]|<a\b[^>]*\btarget\s*=\s*["']?_blank[^>]*\bhref\s*=\s*["']?(?:https?:)?\/\/[a-z0-9]|<a\b[^>]*\bhref\s*=\s*["']?(?:https?:)?\/\/[a-z0-9][^>]*\btarget\s*=\s*["']?_blank/i;
26
+ /** A connection written out in full: fetch, WebSocket, EventSource, sendBeacon or XMLHttpRequest to an absolute address. */
27
+ const LITERAL_CONNECTION_PATTERN = /(?:\bfetch|new\s+WebSocket|new\s+EventSource|\bsendBeacon)\(\s*["'`](?:https?|wss?):\/\/([a-z0-9.-]+)|\.open\(\s*["'`][A-Za-z]{3,7}["'`]\s*,\s*["'`]https?:\/\/([a-z0-9.-]+)/gi;
28
+
29
+ // ---- Scripts as tokens -------------------------------------------------------------------------------------------
30
+
31
+ /**
32
+ * The longest script read as tokens; a longer one is read only by the text checks (the packer's shape, a password
33
+ * field in HTML). 5 MB of minified code reads in under half a second within 100 MB of memory; 11 MB doesn't fit a
34
+ * Worker's 128. Engines split their code across files well under this.
35
+ */
36
+ const MAXIMUM_TOKENIZED_CHARACTER_COUNT = 5_000_000;
37
+ const TOKENIZER_OPTIONS = { ecmaVersion: "latest", allowHashBang: true, allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true, allowImportExportEverywhere: true };
38
+
39
+ /** The scripts in a file: the whole file for a script, each inline <script> for a page. */
40
+ function scriptsOf(file) {
41
+ if (SCRIPT.test(file.path)) return [{ text: file.text, offset: 0 }];
42
+ if (!/\.html?$/i.test(file.path)) return [];
43
+ return [...file.text.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map((match) => ({ text: match[1], offset: match.index + match[0].indexOf(match[1]) }));
44
+ }
45
+
46
+ /** A script's tokens, or null when acorn can't read it or it's very long. Kept per file, since two checks read them. */
47
+ const tokenCache = new WeakMap();
48
+ /**
49
+ * A script's tokens, kept compact: a label number, a start and (for names and strings) a value each, so a minified
50
+ * bundle's hundreds of thousands of tokens take a few megabytes, not hundreds, in a Worker's 128.
51
+ */
52
+ class CompactTokens {
53
+ constructor(text) {
54
+ const labelNumbers = [];
55
+ const starts = [];
56
+ this.values = [];
57
+ this.labels = [];
58
+ const labelIndexes = new Map();
59
+ for (const token of tokenizer(text, TOKENIZER_OPTIONS)) {
60
+ const tokenLabel = token.type.label;
61
+ if (!labelIndexes.has(tokenLabel)) {
62
+ labelIndexes.set(tokenLabel, this.labels.length);
63
+ this.labels.push(tokenLabel);
64
+ }
65
+ const index = labelNumbers.length;
66
+ labelNumbers.push(labelIndexes.get(tokenLabel));
67
+ starts.push(token.start);
68
+ if (tokenLabel === "name" || tokenLabel === "string" || tokenLabel === "template" || tokenLabel === "+/-") this.values[index] = token.value;
69
+ }
70
+ this.labelNumbers = Uint16Array.from(labelNumbers);
71
+ this.starts = Int32Array.from(starts);
72
+ this.length = this.labelNumbers.length;
73
+ }
74
+ labelAt(index) {
75
+ return index >= 0 && index < this.length ? this.labels[this.labelNumbers[index]] : undefined;
76
+ }
77
+ valueAt(index) {
78
+ return this.values[index];
79
+ }
80
+ startAt(index) {
81
+ return this.starts[index];
82
+ }
83
+ }
84
+ function tokensOf(script) {
85
+ if (script.text.length > MAXIMUM_TOKENIZED_CHARACTER_COUNT) return null;
86
+ try {
87
+ return new CompactTokens(script.text);
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+ function scriptTokens(file) {
93
+ if (!tokenCache.has(file)) tokenCache.set(file, scriptsOf(file).map((script) => ({ ...script, tokens: tokensOf(script) })));
94
+ return tokenCache.get(file);
95
+ }
96
+
97
+ /** What turns text back into something else: base64, character codes, bytes, escapes. */
98
+ const DECODERS = new Set(["atob", "fromCharCode", "fromCodePoint", "TextDecoder", "unescape", "decodeURIComponent", "decodeURI"]);
99
+ const DECODER_WORD_PATTERN = /\b(atob|fromCharCode|fromCodePoint|TextDecoder|unescape|decodeURIComponent|decodeURI)\b/;
100
+ /** What runs text as code. */
101
+ const RUNNERS = new Set(["eval", "Function"]);
102
+
103
+ /**
104
+ * Where a script runs text it decoded: eval, an indirect eval or the Function constructor (or a name given either)
105
+ * called on a decoder's output, directly or through a name whose latest assignment in scope holds one. Decoders
106
+ * inside a nested block (a function's body, an object) don't count, so a library's decoding helpers never taint the
107
+ * names around them. Answers the token index of the runner, or -1. Engines run code they load as files (Godot's
108
+ * JavaScript bridge, Phaser's scene files): that's code in the upload, checked like the rest, and never flagged.
109
+ */
110
+ function decodedRunIndex(tokens) {
111
+ const label = (index) => tokens.labelAt(index);
112
+ const nestingLevels = new Int32Array(tokens.length + 1);
113
+ // Where the block each token is in ends, found in one pass: a minified bundle has hundreds of thousands of tokens.
114
+ const blockEnds = new Int32Array(tokens.length + 1).fill(tokens.length);
115
+ const openBlocks = [];
116
+ const openedAt = new Int32Array(tokens.length + 1).fill(-1);
117
+ for (let index = 0, nestingLevel = 0; index < tokens.length; index++) {
118
+ nestingLevels[index] = nestingLevel;
119
+ openedAt[index] = openBlocks.length ? openBlocks[openBlocks.length - 1] : -1;
120
+ const tokenLabel = label(index);
121
+ if (tokenLabel === "{" || tokenLabel === "${") {
122
+ nestingLevel++;
123
+ openBlocks.push(index);
124
+ } else if (tokenLabel === "}") {
125
+ nestingLevel--;
126
+ const openIndex = openBlocks.pop();
127
+ if (openIndex !== undefined) blockEnds[openIndex] = index;
128
+ }
129
+ }
130
+ /** Where the expression starting at startIndex ends: at a , ; or closing bracket on its own level. */
131
+ const expressionEnd = (startIndex) => {
132
+ let nestingLevel = 0;
133
+ for (let index = startIndex; index < tokens.length; index++) {
134
+ const tokenLabel = label(index);
135
+ if (tokenLabel === "(" || tokenLabel === "[" || tokenLabel === "{" || tokenLabel === "${") nestingLevel++;
136
+ else if (tokenLabel === ")" || tokenLabel === "]" || tokenLabel === "}") {
137
+ if (nestingLevel === 0) return index;
138
+ nestingLevel--;
139
+ } else if ((tokenLabel === ";" || tokenLabel === ",") && nestingLevel === 0) return index;
140
+ }
141
+ return tokens.length;
142
+ };
143
+ const blockEnd = (index) => (openedAt[index] === -1 ? tokens.length : blockEnds[openedAt[index]]);
144
+ /** Each name's assignments in order: what it holds ("runner", "decoded", "plain") and where that holds. */
145
+ const assignmentsByName = new Map();
146
+ /** Names ever given a runner or decoded text: only these are looked up, so a minified bundle's thousands of one-letter names cost nothing. */
147
+ const taintedNames = new Set();
148
+ const holds = (name, kind, atIndex) => {
149
+ if (!taintedNames.has(name)) return false;
150
+ const assignments = assignmentsByName.get(name) ?? [];
151
+ // Assignments are in token order: the last before atIndex, then back over ones whose block has ended, a few at most.
152
+ let lowIndex = 0;
153
+ let highIndex = assignments.length;
154
+ while (lowIndex < highIndex) {
155
+ const middleIndex = (lowIndex + highIndex) >> 1;
156
+ if (assignments[middleIndex].fromIndex < atIndex) lowIndex = middleIndex + 1;
157
+ else highIndex = middleIndex;
158
+ }
159
+ for (let index = lowIndex - 1, lookedCount = 0; index >= 0 && lookedCount < 64; index--, lookedCount++) {
160
+ if (atIndex < assignments[index].untilIndex) return assignments[index].kind === kind;
161
+ }
162
+ return false;
163
+ };
164
+ const hasDecoded = (startIndex, endIndex) => {
165
+ for (let index = startIndex; index < endIndex; index++) {
166
+ if (nestingLevels[index] !== nestingLevels[startIndex] || label(index) !== "name") continue;
167
+ if (DECODERS.has(tokens.valueAt(index)) || holds(tokens.valueAt(index), "decoded", index)) return true;
168
+ }
169
+ return false;
170
+ };
171
+ for (let index = 0; index < tokens.length; index++) {
172
+ if (label(index) !== "name" || label(index + 1) !== "=" || label(index - 1) === ".") continue;
173
+ const endIndex = expressionEnd(index + 2);
174
+ const kind = endIndex === index + 3 && label(index + 2) === "name" && RUNNERS.has(tokens.valueAt(index + 2)) ? "runner" : hasDecoded(index + 2, endIndex) ? "decoded" : "plain";
175
+ const name = tokens.valueAt(index);
176
+ if (kind !== "plain") taintedNames.add(name);
177
+ if (!assignmentsByName.has(name)) assignmentsByName.set(name, []);
178
+ assignmentsByName.get(name).push({ kind, fromIndex: index, untilIndex: blockEnd(index) });
179
+ }
180
+ for (let index = 0; index < tokens.length; index++) {
181
+ if (label(index) !== "name") continue;
182
+ const name = tokens.valueAt(index);
183
+ if (!RUNNERS.has(name) && !holds(name, "runner", index)) continue;
184
+ if (label(index - 1) === "." && name !== "eval") continue;
185
+ // (0, eval)(text) closes its group before the call.
186
+ const callIndex = label(index + 1) === ")" ? index + 2 : index + 1;
187
+ if (label(callIndex) !== "(") continue;
188
+ if (hasDecoded(callIndex + 1, expressionEnd(callIndex + 1))) return index;
189
+ }
190
+ return -1;
191
+ }
192
+
193
+ /** The packer's own shape (eval(function(p,a,c,k,e,…)) and eval of a decoder's output written in one go. */
194
+ const PACKED_PATTERN = /eval\(\s*function\s*\(\s*p\s*,\s*a\s*,\s*c\s*,\s*k\s*,\s*e\s*,|\beval\(\s*(atob|unescape|decodeURIComponent|String\.fromCharCode)\s*\(|new\s+Function\(\s*atob\s*\(/;
195
+
196
+ /** A script's string literals joined where it adds them up ("pass" + "word"), with where each joined run starts. */
197
+ function joinedStrings(tokens) {
198
+ const joined = [];
199
+ for (let index = 0; index < tokens.length; index++) {
200
+ if (tokens.labelAt(index) !== "string" && tokens.labelAt(index) !== "template") continue;
201
+ let text = String(tokens.valueAt(index) ?? "");
202
+ const startIndex = index;
203
+ while (tokens.labelAt(index + 1) === "+/-" && tokens.valueAt(index + 1) === "+" && tokens.labelAt(index + 2) === "string") {
204
+ text += tokens.valueAt(index + 2);
205
+ index += 2;
206
+ }
207
+ joined.push({ text, tokenIndex: startIndex });
208
+ }
209
+ return joined;
210
+ }
211
+
212
+ // ---- WebAssembly -------------------------------------------------------------------------------------------------
213
+
214
+ /** A module as embedded in a script: base64 starting with "\0asm" version 1, or a list of its byte values. */
215
+ const EMBEDDED_WASM_PATTERN = /AGFzbQEAAAA[A-Za-z0-9+/]{8,}={0,2}/g;
216
+ const EMBEDDED_WASM_BYTE_LIST_PATTERN = /\b0\s*,\s*97\s*,\s*115\s*,\s*109\s*,\s*1\s*,\s*0\s*,\s*0\s*,\s*0(?:\s*,\s*\d{1,3})+/g;
217
+ /** Bytes searched for miner words at a time, and how much each piece repeats from the one before so no word is cut in half. */
218
+ export const MINER_SEARCH_PIECE_SIZE_BYTES = 1_048_576;
219
+ export const MINER_SEARCH_OVERLAP_SIZE_BYTES = 256;
220
+
221
+ /** Whether a piece of a module's bytes (or a whole small module) carries what a miner carries: its names, its strings. */
222
+ export function isMinerPiece(bytes) {
223
+ let pieceText = "";
224
+ for (let index = 0; index < bytes.length; index += 0x8000) pieceText += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
225
+ return MINER_PATTERN.test(pieceText) || MINER_MODULE_PATTERN.test(pieceText);
226
+ }
227
+
228
+ /** Whether a whole module's bytes carry a miner, searched a piece at a time so a big module never becomes one big string. */
229
+ export function isMinerModule(bytes) {
230
+ for (let startIndex = 0; startIndex < bytes.length; startIndex += MINER_SEARCH_PIECE_SIZE_BYTES) {
231
+ if (isMinerPiece(bytes.subarray(Math.max(0, startIndex - MINER_SEARCH_OVERLAP_SIZE_BYTES), startIndex + MINER_SEARCH_PIECE_SIZE_BYTES))) return true;
232
+ }
233
+ return false;
234
+ }
235
+
236
+ class ByteReader {
237
+ constructor(bytes, byteIndex) {
238
+ this.bytes = bytes;
239
+ this.byteIndex = byteIndex;
240
+ }
241
+ byte() {
242
+ if (this.byteIndex >= this.bytes.length) throw new RangeError("past the end");
243
+ return this.bytes[this.byteIndex++];
244
+ }
245
+ unsignedNumber() {
246
+ let valueNumber = 0;
247
+ let shiftBitCount = 0;
248
+ for (;;) {
249
+ const nextByteNumber = this.byte();
250
+ valueNumber += (nextByteNumber & 0x7f) * 2 ** shiftBitCount;
251
+ if ((nextByteNumber & 0x80) === 0) return valueNumber;
252
+ shiftBitCount += 7;
253
+ if (shiftBitCount > 63) throw new RangeError("number too long");
254
+ }
255
+ }
256
+ skipName() {
257
+ const nameLengthBytes = this.unsignedNumber();
258
+ if (this.byteIndex + nameLengthBytes > this.bytes.length) throw new RangeError("past the end");
259
+ this.byteIndex += nameLengthBytes;
260
+ }
261
+ limits() {
262
+ const limitsFlagNumber = this.byte();
263
+ this.unsignedNumber();
264
+ if (limitsFlagNumber & 0x01) this.unsignedNumber();
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Whether bytes are a well-formed module with code: the "\0asm" version 1 header, known sections only, each standard
270
+ * one once and in order, imports and exports read to exactly their section's end, and a code section.
271
+ */
272
+ export function isWasmModule(bytes) {
273
+ if (bytes.length < 8 || [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00].some((byteNumber, byteIndex) => bytes[byteIndex] !== byteNumber)) return false;
274
+ let lastSectionOrderNumber = 0;
275
+ let hasCode = false;
276
+ const reader = new ByteReader(bytes, 8);
277
+ try {
278
+ while (reader.byteIndex < bytes.length) {
279
+ const sectionIdNumber = reader.byte();
280
+ const sectionSizeBytes = reader.unsignedNumber();
281
+ const sectionEndIndex = reader.byteIndex + sectionSizeBytes;
282
+ if (sectionEndIndex > bytes.length || sectionIdNumber > 13) return false;
283
+ if (sectionIdNumber !== 0) {
284
+ // The data count section (12) comes just before code (10), the tag section (13) between memory (5) and globals (6).
285
+ const sectionOrderNumber = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 11, 6][sectionIdNumber];
286
+ if (sectionOrderNumber <= lastSectionOrderNumber) return false;
287
+ lastSectionOrderNumber = sectionOrderNumber;
288
+ }
289
+ if (sectionIdNumber === 0) {
290
+ reader.skipName();
291
+ if (reader.byteIndex > sectionEndIndex) return false;
292
+ } else if (sectionIdNumber === 2) {
293
+ const importCount = reader.unsignedNumber();
294
+ for (let importIndex = 0; importIndex < importCount; importIndex++) {
295
+ reader.skipName();
296
+ reader.skipName();
297
+ const importKindNumber = reader.byte();
298
+ if (importKindNumber === 0x00) reader.unsignedNumber();
299
+ else if (importKindNumber === 0x01) {
300
+ reader.byte();
301
+ reader.limits();
302
+ } else if (importKindNumber === 0x02) reader.limits();
303
+ else if (importKindNumber === 0x03) {
304
+ reader.byte();
305
+ reader.byte();
306
+ } else if (importKindNumber === 0x04) {
307
+ reader.byte();
308
+ reader.unsignedNumber();
309
+ } else return false;
310
+ }
311
+ if (reader.byteIndex !== sectionEndIndex) return false;
312
+ } else if (sectionIdNumber === 7) {
313
+ const exportCount = reader.unsignedNumber();
314
+ for (let exportIndex = 0; exportIndex < exportCount; exportIndex++) {
315
+ reader.skipName();
316
+ reader.byte();
317
+ reader.unsignedNumber();
318
+ }
319
+ if (reader.byteIndex !== sectionEndIndex) return false;
320
+ } else if (sectionIdNumber === 10) {
321
+ hasCode = reader.unsignedNumber() > 0;
322
+ }
323
+ reader.byteIndex = sectionEndIndex;
324
+ }
325
+ } catch {
326
+ return false;
327
+ }
328
+ return hasCode;
329
+ }
330
+
331
+ const decodeBase64 = (text) => {
332
+ try {
333
+ const binary = atob(text.endsWith("=") ? text : text.slice(0, text.length - (text.length % 4)));
334
+ const bytes = new Uint8Array(binary.length);
335
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
336
+ return bytes;
337
+ } catch {
338
+ return undefined;
339
+ }
340
+ };
341
+ const decodeByteList = (text) => {
342
+ const byteNumbers = text.split(",").map((part) => Number(part.trim()));
343
+ return byteNumbers.every((byteNumber) => byteNumber <= 255) ? Uint8Array.from(byteNumbers) : undefined;
344
+ };
345
+
346
+ /** Every WebAssembly module embedded in a file's text that decodes to a well-formed module, each with where it starts and whether it's a miner's. */
347
+ export function embeddedWasmModules(text) {
348
+ const modules = [];
349
+ const read = (match, bytes) => {
350
+ if (bytes && isWasmModule(bytes)) modules.push({ index: match.index, isMinerLike: isMinerModule(bytes) });
351
+ };
352
+ for (const match of text.matchAll(EMBEDDED_WASM_PATTERN)) read(match, decodeBase64(match[0]));
353
+ for (const match of text.matchAll(EMBEDDED_WASM_BYTE_LIST_PATTERN)) read(match, decodeByteList(match[0]));
354
+ return modules;
355
+ }
356
+
357
+ // ---- The checks --------------------------------------------------------------------------------------------------
358
+
359
+ /** A text field a player types into: in a page, or made by script. */
360
+ const TEXT_FIELD_PATTERN = /<(?:input|textarea)\b|createElement\(\s*["'`](?:input|textarea)["'`]|\bprompt\(/i;
361
+ /** Asking for what opens a crypto wallet: its seed or recovery phrase, or a private key. */
362
+ const WALLET_SECRET_PATTERN = /\b(?:seed|recovery|mnemonic)[ -](?:phrase|words)\b|\b(?:12|24)[ -]word (?:seed|recovery|phrase|backup)\b|\bprivate key\b/gi;
363
+ /** How near a text field has to be to the words that ask for a wallet's secret: the same form, not anywhere in a bundle. */
364
+ const WALLET_FIELD_NEARBY_CHARACTER_COUNT = 600;
365
+ /** Asking a browser wallet other than Bitcoin's for access (Ethereum's, Solana's, WalletConnect). */
366
+ const WALLET_ACCESS_PATTERN = /\bethereum\.(?:request|enable|send(?:Async)?)\s*\(|["'`]eth_(?:requestAccounts|sendTransaction|sign(?:TypedData(?:_v\d)?)?)["'`]|\bpersonal_sign\b|\bsolana\.(?:connect|signTransaction|signAllTransactions|signAndSendTransaction)\s*\(|@walletconnect\/|\bWalletConnect(?:Modal|Provider|Connector)\b/;
367
+ /** A password field set by script, once added-up strings are joined. */
368
+ const SCRIPT_PASSWORD_PATTERN = /^password$/i;
369
+
370
+ /**
371
+ * The fixed checks, one entry each. Each reads the files whose path matches `only` (every text file when it has none)
372
+ * and answers where in the file it found what it looks for, or null. A finding's severity is the entry's.
373
+ */
374
+ export const FIXED_CHECKS = [
375
+ {
376
+ code: "crypto_miner",
377
+ severity: "reject",
378
+ message: "Contains crypto-mining code.",
379
+ find: (file) => MINER_PATTERN.exec(file.text)?.index ?? null,
380
+ },
381
+ {
382
+ code: "crypto_miner",
383
+ severity: "reject",
384
+ message: "Embeds a WebAssembly module with crypto-mining code.",
385
+ find: (file) => embeddedWasmModules(file.text).find((embedded) => embedded.isMinerLike)?.index ?? null,
386
+ },
387
+ {
388
+ code: "disguised_code",
389
+ severity: "reject",
390
+ message: "Runs code it decodes from other text (base64, character codes or bytes), which hides what it runs.",
391
+ find: (file) => {
392
+ const packed = PACKED_PATTERN.exec(file.text);
393
+ if (packed) return packed.index;
394
+ // Only a file with both a runner and a decoder in it is read token by token.
395
+ if (!/\b(eval|Function)\b/.test(file.text) || !DECODER_WORD_PATTERN.test(file.text)) return null;
396
+ for (const script of scriptTokens(file)) {
397
+ if (!script.tokens) continue;
398
+ const runIndex = decodedRunIndex(script.tokens);
399
+ if (runIndex !== -1) return script.offset + script.tokens.startAt(runIndex);
400
+ }
401
+ return null;
402
+ },
403
+ },
404
+ {
405
+ code: "password_field",
406
+ severity: "reject",
407
+ message: "Has a password field. Games don't need one, and phishing pages do.",
408
+ find: (file) => {
409
+ if (HTML.test(file.path)) {
410
+ const field = /<input[^>]*type\s*=\s*["']?password/i.exec(file.text);
411
+ if (field) return field.index;
412
+ }
413
+ // Only a file that says password, or adds up short strings that could spell it, is read token by token.
414
+ if (!/password|["'`][a-z]{0,7}["'`]\s*\+\s*["'`]/i.test(file.text)) return null;
415
+ for (const script of scriptTokens(file)) {
416
+ if (!script.tokens) continue;
417
+ // Every input type the script sets, and where it sets a password one: .type = "password",
418
+ // setAttribute("type", "password"), { type: "password" }.
419
+ const setTypes = new Set();
420
+ let typeSetAtIndex = -1;
421
+ for (const { text, tokenIndex } of joinedStrings(script.tokens)) {
422
+ const before = Array.from({ length: Math.min(4, tokenIndex) }, (_, offsetIndex) => tokenIndex - Math.min(4, tokenIndex) + offsetIndex).map((index) => String(script.tokens.valueAt(index) ?? script.tokens.labelAt(index))).join(" ");
423
+ if (!/\btype\s+=$|\btype\s+:$|setAttribute\s+\(\s+type\s+,$/.test(before)) continue;
424
+ setTypes.add(text.toLowerCase());
425
+ if (SCRIPT_PASSWORD_PATTERN.test(text) && typeSetAtIndex === -1) typeSetAtIndex = tokenIndex;
426
+ }
427
+ // An engine's text input that takes whatever kind its game's field asks for (Godot's keyboard sets text, email,
428
+ // tel, url and password in turn) is the engine's, not a field the game shows.
429
+ const isInputTypeMapper = ["email", "tel", "url", "number", "search"].filter((type) => setTypes.has(type)).length >= 2;
430
+ if (typeSetAtIndex !== -1 && !isInputTypeMapper) return script.offset + script.tokens.startAt(typeSetAtIndex);
431
+ }
432
+ return null;
433
+ },
434
+ },
435
+ {
436
+ code: "wallet_request",
437
+ severity: "reject",
438
+ message: "Asks players for a crypto wallet's seed phrase or private key, or for access to a wallet other than Bitcoin's.",
439
+ find: (file) => {
440
+ const access = WALLET_ACCESS_PATTERN.exec(file.text);
441
+ if (access) return access.index;
442
+ for (const secret of file.text.matchAll(WALLET_SECRET_PATTERN)) {
443
+ const nearby = file.text.slice(Math.max(0, secret.index - WALLET_FIELD_NEARBY_CHARACTER_COUNT), secret.index + WALLET_FIELD_NEARBY_CHARACTER_COUNT);
444
+ if (TEXT_FIELD_PATTERN.test(nearby)) return secret.index;
445
+ }
446
+ return null;
447
+ },
448
+ },
449
+ // Notes: the sandbox stops these while the game runs, so the game only bumps into them.
450
+ {
451
+ code: "top_navigation",
452
+ severity: "info",
453
+ message: "Tries to change the page outside the game (top or parent window location), which the game's frame stops.",
454
+ find: (file) => /\b(window\.)?(top|parent)\.location(\.href)?\s*=(?!=)|\b(window\.)?(top|parent)\.location\.(replace|assign)\s*\(/.exec(file.text)?.index ?? null,
455
+ },
456
+ {
457
+ code: "relay_bypass",
458
+ severity: "info",
459
+ message: "Makes a WebRTC connection from a frame of its own; Zaisma's relay still carries it, so players never see each other's internet address.",
460
+ find: (file) =>
461
+ /(\bcontentWindow|\bdefaultView|\b(window|self|top|parent|globalThis|frames)\s*\[\s*\d+\s*\])\s*(\.\s*|\[\s*["'`])(webkit)?RTCPeerConnection|\bsrcdoc\b[\s\S]{0,2000}RTCPeerConnection|RTCPeerConnection[\s\S]{0,2000}\bsrcdoc\b/.exec(file.text)?.index ?? null,
462
+ },
463
+ {
464
+ code: "external_form",
465
+ severity: "info",
466
+ message: "Has a form that would send to another site, which the game's security policy stops.",
467
+ only: HTML,
468
+ find: (file) => /<form[^>]*action\s*=\s*["']?(https?:)?\/\//i.exec(file.text)?.index ?? null,
469
+ },
470
+ {
471
+ code: "svg_script",
472
+ severity: "info",
473
+ message: "An SVG image contains script.",
474
+ only: /\.svg$/i,
475
+ find: (file) => /<script/i.exec(file.text)?.index ?? null,
476
+ },
477
+ ];
478
+
479
+ /**
480
+ * Every fixed check on a game's text files ({ path, text }), plus the notes about links and addresses (once per
481
+ * version, at the first file that has each). `ownServerHosts`: the game's own servers' hosts, lowercase. Answers
482
+ * { findings: [{ stage: "static", severity, code, message, path, quote }], outsideHosts }.
483
+ */
484
+ export function runFixedChecks(files, ownServerHosts = []) {
485
+ const findings = [];
486
+ const hosts = new Set();
487
+ const quoteAt = (text, index) => text.slice(Math.max(0, index - 60), index + 140).replace(/\s+/g, " ").trim();
488
+ for (const file of files) {
489
+ for (const check of FIXED_CHECKS) {
490
+ if (check.only && !check.only.test(file.path)) continue;
491
+ if (findings.some((finding) => finding.code === check.code && finding.path === file.path)) continue;
492
+ const index = check.find(file);
493
+ if (index !== null) findings.push({ stage: "static", severity: check.severity, code: check.code, message: check.message, path: file.path, quote: quoteAt(file.text, index) });
494
+ }
495
+ if (!findings.some((finding) => finding.code === "unregistered_link") && UNREGISTERED_LINK_PATTERN.test(file.text)) {
496
+ findings.push({ stage: "static", severity: "info", code: "unregistered_link", message: "Opens a site with window.open or a new-tab link.", path: file.path });
497
+ }
498
+ const unlistedHost = findings.some((finding) => finding.code === "unlisted_address")
499
+ ? undefined
500
+ : [...file.text.matchAll(LITERAL_CONNECTION_PATTERN)].map((match) => (match[1] ?? match[2]).toLowerCase()).find((host) => host !== ROOMS_HOST && !IGNORED_HOSTS.has(host) && !ownServerHosts.includes(host));
501
+ if (unlistedHost) findings.push({ stage: "static", severity: "info", code: "unlisted_address", message: `Connects to ${unlistedHost}, which isn't Zaisma rooms or one of the game's own servers.`, path: file.path });
502
+ for (const match of file.text.matchAll(URL_PATTERN)) {
503
+ const host = match[1].toLowerCase();
504
+ // Skip version-like numbers and file names that look like hosts ("three.min.js").
505
+ if (/^[\d.]+$/.test(host) && !/^\d+\.\d+\.\d+\.\d+$/.test(host)) continue;
506
+ if (/\.(js|mjs|css|png|jpg|json|html|wasm|map)$/i.test(host) || IGNORED_HOSTS.has(host)) continue;
507
+ hosts.add(host);
508
+ }
509
+ }
510
+ const outsideHosts = [...hosts].sort().slice(0, 100);
511
+ if (outsideHosts.length > 0) {
512
+ findings.push({
513
+ stage: "static",
514
+ severity: "info",
515
+ code: "outside_hosts",
516
+ message: `Names ${outsideHosts.length} outside site(s), in its code or comments. A game on Zaisma loads only its own files and connects only to Zaisma rooms and its own servers; zaisma check lists anything that won't work.`,
517
+ });
518
+ }
519
+ return { findings, outsideHosts };
520
+ }
521
+
522
+ /** The fixed checks on a WebAssembly file's bytes (or a piece of them, searched with overlap by the caller): a miner's module is refused. */
523
+ export function wasmFileFindings(path, bytes) {
524
+ return isMinerModule(bytes) ? [{ stage: "static", severity: "reject", code: "crypto_miner", message: "A WebAssembly file carries crypto-mining code.", path }] : [];
525
+ }
526
+
527
+ /** The codes a fixed check can refuse a version for. */
528
+ export const REFUSING_CHECK_CODES = [...new Set(FIXED_CHECKS.filter((check) => check.severity === "reject").map((check) => check.code))];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/cli",
3
- "version": "0.60.0",
3
+ "version": "0.62.0",
4
4
  "description": "Upload and publish browser games on Zaisma from the command line.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
@@ -27,6 +27,8 @@
27
27
  "zaisma.mjs",
28
28
  "check.mjs",
29
29
  "check.d.mts",
30
+ "fixed-checks.mjs",
31
+ "fixed-checks.d.mts",
30
32
  "performance.mjs",
31
33
  "performance.d.mts",
32
34
  "shader-check.mjs",
@@ -35,6 +37,9 @@
35
37
  "README.md",
36
38
  "LICENSE"
37
39
  ],
40
+ "dependencies": {
41
+ "acorn": "^8.19.0"
42
+ },
38
43
  "engines": {
39
44
  "node": ">=18"
40
45
  }