dredless 1.3.0 → 1.3.1

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/docs/NODE_API.md CHANGED
@@ -97,6 +97,8 @@ Dredless.fetchShipList(session: Session, server: ServerRef): Promise<ShipList>;
97
97
 
98
98
  `fetchServers()` discovers servers; it does not populate status/ping fields. Discovery metadata is cached per origin for the process/module lifetime; repeated calls do not necessarily refetch the game version or directory. Discovery/status implementations also accept an optional final `baseUrl` argument, although the root declarations omit it. Ship names preserve leading and trailing spaces. Some ship metadata fields are nullable; inspect [declared shapes](../src/index.d.ts) when persisting results.
99
99
 
100
+ Discovery reads stable named exports from the official bundle (for example `TEST_GAME_DOMAIN` and `GAME_VERSION`), then resolves their constant literals within the same module. The dependency-free scanner supports renamed bindings, reordered/combined declarations, whitespace/comments, and escaped strings and string arrays; it never evaluates downloaded JavaScript. Unsupported export expressions and invalid hostnames/array shapes produce errors naming the affected export. Failed downloads or parsing are evicted from the metadata cache so a subsequent call can retry. It deliberately does not attempt to interpret arbitrary JavaScript or fetch external script files.
101
+
100
102
  ## Join, start, and invites
101
103
 
102
104
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dredless",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "A fully-featured and from-scratch headless drednot.io client implementation written in pure js.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/certainhuman/dredless#readme",
@@ -0,0 +1,191 @@
1
+ // A deliberately limited reader, not a JavaScript evaluator. Only constant
2
+ // strings, booleans, and arrays of strings may back the requested exports.
3
+ const identifier = /^[A-Za-z_$][\w$]*$/;
4
+ const regexPrefix = new Set(['(', '[', '{', '=', ':', ',', ';', '!', '?', '&', '|', '=>', 'return', 'throw', 'case', 'typeof', 'void', 'delete']);
5
+
6
+ function quoted(source, start) {
7
+ const quote = source[start];
8
+ let value = '', valid = true, i = start + 1;
9
+ for (; i < source.length; i++) {
10
+ const c = source[i];
11
+ if (c === quote) return {value, valid, end: i + 1};
12
+ if (c !== '\\') { value += c; if (c === '\n' || c === '\r') valid = false; continue; }
13
+ const escape = source[++i];
14
+ const simple = {n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', '0': '\0'};
15
+ if (escape === '\n') continue;
16
+ if (escape === '\r') { if (source[i + 1] === '\n') i++; continue; }
17
+ if (escape === 'x' || escape === 'u') {
18
+ const braced = escape === 'u' && source[i + 1] === '{';
19
+ const first = i + (braced ? 2 : 1);
20
+ const end = braced ? source.indexOf('}', first) : first + (escape === 'x' ? 2 : 4);
21
+ const digits = source.slice(first, end);
22
+ if (end < first) return {value, valid: false, end: source.length};
23
+ if (!/^[\da-f]+$/i.test(digits) || Number.parseInt(digits, 16) > 0x10ffff) valid = false;
24
+ else value += String.fromCodePoint(Number.parseInt(digits, 16));
25
+ i = braced ? end : end - 1;
26
+ } else if (escape === '0' && /\d/.test(source[i + 1] || '')) valid = false;
27
+ else if (escape in simple) value += simple[escape];
28
+ else if (escape && !/[1-9]/.test(escape)) value += escape;
29
+ else valid = false;
30
+ }
31
+ return {value, valid: false, end: i};
32
+ }
33
+
34
+ function skipRegex(source, start) {
35
+ let inClass = false, i = start + 1;
36
+ for (; i < source.length; i++) {
37
+ if (source[i] === '\\') { i++; continue; }
38
+ if (source[i] === '[') inClass = true;
39
+ if (source[i] === ']') inClass = false;
40
+ if (source[i] === '/' && !inClass) {
41
+ while (/[a-z]/i.test(source[i + 1] || '')) i++;
42
+ return i + 1;
43
+ }
44
+ if (source[i] === '\n') break;
45
+ }
46
+ return i;
47
+ }
48
+
49
+ function skipTemplate(source, start) {
50
+ let i = start + 1;
51
+ while (i < source.length) {
52
+ if (source[i] === '\\') { i += 2; continue; }
53
+ if (source[i] === '`') return i + 1;
54
+ if (source[i] === '$' && source[i + 1] === '{') {
55
+ const expression = lex(source, i + 2, true);
56
+ i = expression.end;
57
+ } else i++;
58
+ }
59
+ return i;
60
+ }
61
+
62
+ function lex(source, start = 0, interpolation = false) {
63
+ const tokens = [];
64
+ let i = start, depth = 0;
65
+ while (i < source.length) {
66
+ const c = source[i];
67
+ if (/\s/.test(c)) { i++; continue; }
68
+ if (source.startsWith('//', i)) { const end = source.indexOf('\n', i); i = end < 0 ? source.length : end; continue; }
69
+ if (source.startsWith('/*', i)) { const end = source.indexOf('*/', i + 2); i = end < 0 ? source.length : end + 2; continue; }
70
+ let token;
71
+ if (c === '"' || c === "'") {
72
+ const string = quoted(source, i);
73
+ token = {kind: 'string', value: string.value, valid: string.valid}; i = string.end;
74
+ } else if (c === '`') { i = skipTemplate(source, i); token = {kind: 'opaque', value: 'template'}; }
75
+ else if (c === '/' && (!tokens.length || regexPrefix.has(tokens.at(-1).value))) {
76
+ i = skipRegex(source, i); token = {kind: 'opaque', value: 'regex'};
77
+ } else if (/[A-Za-z_$]/.test(c)) {
78
+ const first = i++;
79
+ while (/[\w$]/.test(source[i] || '')) i++;
80
+ token = {kind: 'identifier', value: source.slice(first, i)};
81
+ } else {
82
+ token = {kind: 'punctuation', value: source.startsWith('=>', i) ? '=>' : c};
83
+ i += token.value.length;
84
+ }
85
+ if (interpolation && token.kind === 'punctuation' && token.value === '}' && depth === 0) return {tokens, end: i};
86
+ if (token.value === '{' && token.kind === 'punctuation') depth++;
87
+ if (token.value === '}' && token.kind === 'punctuation') depth--;
88
+ tokens.push(token);
89
+ }
90
+ return {tokens, end: i};
91
+ }
92
+
93
+ function literal(tokens, start) {
94
+ const token = tokens[start];
95
+ if (token?.kind === 'string' && token.valid) return {value: token.value, end: start + 1};
96
+ if (token?.kind === 'identifier' && ['true', 'false'].includes(token.value)) return {value: token.value === 'true', end: start + 1};
97
+ if (token?.kind !== 'punctuation' || token.value !== '[') return null;
98
+ const value = [];
99
+ let i = start + 1;
100
+ while (!(tokens[i]?.kind === 'punctuation' && tokens[i].value === ']')) {
101
+ if (tokens[i]?.kind !== 'string' || !tokens[i].valid) return null;
102
+ value.push(tokens[i++].value);
103
+ if (tokens[i]?.kind === 'punctuation' && tokens[i].value === ']') break;
104
+ if (tokens[i++]?.value !== ',') return null;
105
+ }
106
+ return tokens[i]?.value === ']' ? {value, end: i + 1} : null;
107
+ }
108
+
109
+ function getter(tokens, start) {
110
+ let i = start;
111
+ if (tokens[i++]?.value !== '(' || tokens[i++]?.value !== ')' || tokens[i++]?.value !== '=>') return null;
112
+ if (tokens[i]?.kind === 'identifier' && identifier.test(tokens[i].value) && [',', '}'].includes(tokens[i + 1]?.value)) return tokens[i].value;
113
+ if (tokens[i++]?.value !== '{' || tokens[i++]?.value !== 'return') return null;
114
+ const name = tokens[i++];
115
+ if (tokens[i]?.value === ';') i++;
116
+ return name?.kind === 'identifier' && tokens[i]?.value === '}' ? name.value : null;
117
+ }
118
+
119
+ export function readBundleExports(text, names) {
120
+ const wanted = new Set(names), found = new Map();
121
+ // HTML and raw JS are both accepted. Never scan markup as JavaScript.
122
+ const scripts = /^\s*</.test(text) ? [...text.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script\s*>/gi)].map((match) => match[1]) : [];
123
+ for (const source of scripts.length ? scripts : [text]) {
124
+ const {tokens} = lex(source);
125
+ const root = new Map(), scopes = [root];
126
+ const brackets = [];
127
+ for (const [index, token] of tokens.entries()) {
128
+ token.scope = scopes.at(-1);
129
+ if (token.kind !== 'punctuation') continue;
130
+ if (['(', '[', '{'].includes(token.value)) brackets.push(index);
131
+ if ([')', ']', '}'].includes(token.value)) {
132
+ const opening = brackets.pop();
133
+ if (opening !== undefined) tokens[opening].close = index;
134
+ }
135
+ if (token.value === '{') { token.child = new Map(); scopes.push(token.child); }
136
+ if (token.value === '}' && scopes.length > 1) scopes.pop();
137
+ }
138
+ // Resolve after scanning declarations, so export/definition order is irrelevant.
139
+ for (let i = 0; i < tokens.length; i++) {
140
+ if (tokens[i].kind !== 'identifier' || tokens[i].value !== 'const') continue;
141
+ const scope = tokens[i].scope;
142
+ let j = i + 1;
143
+ while (tokens[j]?.kind === 'identifier' && tokens[j + 1]?.value === '=') {
144
+ const name = tokens[j].value, result = literal(tokens, j + 2);
145
+ let end = j + 2;
146
+ while (end < tokens.length) {
147
+ const token = tokens[end];
148
+ if (token.scope === scope && token.kind === 'punctuation' && [';', ',', '}'].includes(token.value)) break;
149
+ end = token.close !== undefined ? token.close + 1 : end + 1;
150
+ }
151
+ const valid = result && result.end === end;
152
+ scope.set(name, scope.has(name) ? null : valid ? result.value : null);
153
+ if (tokens[end]?.value !== ',') break;
154
+ j = end + 1;
155
+ }
156
+ }
157
+ const record = (name, binding, scope) => {
158
+ if (!wanted.has(name)) return;
159
+ const value = binding ? scope.get(binding) : undefined;
160
+ if (value == null) throw new Error(`Unable to resolve bundle export ${name}: expected a constant literal in the same module`);
161
+ if (found.has(name) && JSON.stringify(found.get(name)) !== JSON.stringify(value)) throw new Error(`Ambiguous bundle export ${name}`);
162
+ found.set(name, value);
163
+ };
164
+ for (let i = 0; i < tokens.length; i++) {
165
+ if (tokens[i].kind !== 'identifier') continue;
166
+ const method = tokens[i].value === 'Object' && tokens[i + 1]?.value === '.' ? tokens[i + 2]?.value : null;
167
+ // The game also uses a minified helper: helper(exports,{NAME:()=>x}).
168
+ const call = ['defineProperties', 'defineProperty'].includes(method) ? i + 3 : i + 1;
169
+ if (tokens[call]?.value !== '(' || tokens[call + 1]?.kind !== 'identifier' || tokens[call + 2]?.value !== ',') continue;
170
+ let j = call + 3;
171
+ if (method === 'defineProperty') {
172
+ const name = tokens[j++];
173
+ if (name?.kind !== 'string' || !wanted.has(name.value) || tokens[j++]?.value !== ',') continue;
174
+ const object = tokens[j++];
175
+ if (object?.value !== '{' || !object.child) continue;
176
+ for (; j < tokens.length && tokens[j].scope !== object.scope; j++) {
177
+ if (tokens[j].scope === object.child && tokens[j].value === 'get' && tokens[j + 1]?.value === ':') record(name.value, getter(tokens, j + 2), tokens[i].scope);
178
+ }
179
+ } else {
180
+ const object = tokens[j++];
181
+ if (object?.value !== '{' || !object.child) continue;
182
+ for (; j < tokens.length && tokens[j].scope !== object.scope; j++) {
183
+ const key = tokens[j];
184
+ if (key.scope === object.child && ['identifier', 'string'].includes(key.kind) && wanted.has(key.value) && tokens[j + 1]?.value === ':') record(key.value, getter(tokens, j + 2), tokens[i].scope);
185
+ }
186
+ }
187
+ }
188
+ }
189
+ for (const name of wanted) if (!found.has(name)) throw new Error(`Missing bundle export ${name}`);
190
+ return Object.fromEntries(found);
191
+ }
@@ -1,6 +1,7 @@
1
1
  import {DEFAULT_BASE_URL} from "../constants.js";
2
2
  import {getWebSocket, hostName, normalizeBaseUrl} from "../runtime.js";
3
3
  import {HttpClient} from "./http.js";
4
+ import {readBundleExports} from "./bundle-metadata.js";
4
5
 
5
6
  const cache = new Map();
6
7
 
@@ -11,20 +12,26 @@ class ServerDirectory {
11
12
  }
12
13
 
13
14
  async load() {
14
- if (cache.has(this.baseUrl)) {
15
- this.meta = await cache.get(this.baseUrl);
16
- return this;
15
+ if (!cache.has(this.baseUrl)) cache.set(this.baseUrl, this.#fetchMeta());
16
+ const pending = cache.get(this.baseUrl);
17
+ try {
18
+ this.meta = await pending;
19
+ } catch (error) {
20
+ if (cache.get(this.baseUrl) === pending) cache.delete(this.baseUrl);
21
+ throw error;
17
22
  }
18
- const promise = this.#fetchMeta();
19
- cache.set(this.baseUrl, promise);
20
- this.meta = await promise;
21
23
  return this;
22
24
  }
23
25
 
24
26
  async version() {
25
27
  await this.load();
26
- if (!this.meta.version) throw new Error("Unable to locate GAME_VERSION in drednot bundle");
27
- return this.meta.version;
28
+ try {
29
+ this.meta.version ??= parseGameVersion(this.meta.text);
30
+ return this.meta.version;
31
+ } catch (error) {
32
+ cache.delete(this.baseUrl);
33
+ throw error;
34
+ }
28
35
  }
29
36
 
30
37
  async list() {
@@ -33,8 +40,13 @@ class ServerDirectory {
33
40
 
34
41
  async servers() {
35
42
  await this.load();
36
- if (!this.meta.serverInfo) throw new Error("Unable to locate server list in drednot bundle");
37
- return this.meta.serverInfo.servers;
43
+ try {
44
+ this.meta.serverInfo ??= parseServerInfo(this.meta.text, this.baseUrl);
45
+ return this.meta.serverInfo.servers;
46
+ } catch (error) {
47
+ cache.delete(this.baseUrl);
48
+ throw error;
49
+ }
38
50
  }
39
51
 
40
52
  async get(id = null) {
@@ -50,7 +62,7 @@ class ServerDirectory {
50
62
  const response = await new HttpClient({baseUrl: this.baseUrl}).request("index.html");
51
63
  if (!response.ok) throw new Error(`Failed to fetch bundle: ${response.status} ${response.statusText}`);
52
64
  const text = await response.text();
53
- return {text, version: parseGameVersion(text), serverInfo: parseServerInfo(text, this.baseUrl)};
65
+ return {text};
54
66
  }
55
67
  }
56
68
 
@@ -132,7 +144,9 @@ export function serverId(server) {
132
144
  }
133
145
 
134
146
  function parseGameVersion(text) {
135
- return text.match(/Object\.defineProperty\(exports,"GAME_VERSION",\{enumerable:true,get:\(\)=>e\}\);const e="([^"]+)"/)?.[1] || null;
147
+ const {GAME_VERSION} = readBundleExports(text, ["GAME_VERSION"]);
148
+ if (typeof GAME_VERSION !== "string" || !GAME_VERSION.trim()) throw new Error("Invalid bundle export GAME_VERSION: expected a nonempty string");
149
+ return GAME_VERSION;
136
150
  }
137
151
 
138
152
  function parseNoticeVersion(text) {
@@ -159,18 +173,29 @@ function parseNoticeVersion(text) {
159
173
 
160
174
  function parseServerInfo(text, baseUrl) {
161
175
  const host = hostName(baseUrl);
162
- const match = text.match(/const n=(true|false);const \$="([^"]+)";const o="([^"]+)";const T="([^"]+)";const t="([^"]+)";const S=\[([^\]]+)\];const c=\[([^\]]+)\];const A="([^"]+)";const I="([^"]+)"/s);
163
- if (!match) return null;
164
- const [localDomain, baseDomain, testDomain, testGameDomain] = match.slice(2, 6);
165
- const domains = [...match[6].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1]);
166
- const names = [...match[7].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1]);
176
+ const config = readBundleExports(text, ["LOCAL_DOMAIN", "BASE_DOMAIN", "TEST_DOMAIN", "TEST_GAME_DOMAIN",
177
+ "GAME_DOMAINS", "GAME_SERVER_NAMES", "MASTER_DOMAIN", "TEST_MASTER_DOMAIN"]);
178
+ const domain = (value, name) => {
179
+ if (typeof value !== "string" || value.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(value)) {
180
+ throw new Error(`Invalid bundle export ${name}: expected a hostname`);
181
+ }
182
+ return value;
183
+ };
184
+ const localDomain = domain(config.LOCAL_DOMAIN, "LOCAL_DOMAIN");
185
+ const baseDomain = domain(config.BASE_DOMAIN, "BASE_DOMAIN");
186
+ const testDomain = domain(config.TEST_DOMAIN, "TEST_DOMAIN");
187
+ const testGameDomain = domain(config.TEST_GAME_DOMAIN, "TEST_GAME_DOMAIN");
188
+ const domains = config.GAME_DOMAINS;
189
+ const names = config.GAME_SERVER_NAMES;
190
+ if (!Array.isArray(domains) || !domains.length) throw new Error("Invalid bundle export GAME_DOMAINS: expected nonempty hostname array");
191
+ domains.forEach((value) => domain(value, "GAME_DOMAINS"));
192
+ if (!Array.isArray(names) || names.length !== domains.length || names.some((name) => typeof name !== "string")) {
193
+ throw new Error("Invalid bundle export GAME_SERVER_NAMES: expected one string per game domain");
194
+ }
167
195
  const meta = {
168
- localDomain,
169
- baseDomain,
170
- testDomain,
171
- testGameDomain,
172
- masterDomain: match[8],
173
- testMasterDomain: match[9]
196
+ localDomain, baseDomain, testDomain, testGameDomain,
197
+ masterDomain: domain(config.MASTER_DOMAIN, "MASTER_DOMAIN"),
198
+ testMasterDomain: domain(config.TEST_MASTER_DOMAIN, "TEST_MASTER_DOMAIN")
174
199
  };
175
200
  if (host === localDomain) return {mode: "local", servers: [server(0, localDomain, "Local Test 1")], meta};
176
201
  if (host === testDomain) return {mode: "test", servers: [server(0, testGameDomain, "Public Test")], meta};