redirect-map-plan 0.1.0 → 0.2.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/CHANGELOG.md +6 -0
- package/README.md +36 -2
- package/bin/redirect-map-plan.js +72 -1
- package/package.json +2 -2
- package/src/open.js +22 -0
- package/src/plan.js +40 -8
- package/src/ui/client.js +527 -0
- package/src/ui/page.js +265 -0
- package/src/ui/server.js +554 -0
- package/src/write.js +7 -2
package/src/ui/server.js
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
// The local browser interface: `redirect-map-plan ui`.
|
|
2
|
+
//
|
|
3
|
+
// A small server on 127.0.0.1 that serves one page and a JSON/SSE API around buildPlan. It
|
|
4
|
+
// follows redirect-map-check's interface, with the same protections, because any website you
|
|
5
|
+
// visit could try to talk to it:
|
|
6
|
+
// - it listens on loopback only;
|
|
7
|
+
// - the API needs the session token printed in the terminal. The page reads it from its
|
|
8
|
+
// address once, keeps it in sessionStorage and removes it from the address bar; API calls
|
|
9
|
+
// send it in a header (only the event stream, which can't set headers, uses the query);
|
|
10
|
+
// - the Host header must be our own address (stops DNS-rebinding attacks);
|
|
11
|
+
// - writes need our exact Origin, a JSON body and the token header (stops cross-site requests);
|
|
12
|
+
// - the browser can never make it read a local path: local files come only from uploads or
|
|
13
|
+
// from the command line, sitemap URLs typed in the page must be http(s), and a dropped
|
|
14
|
+
// sitemap index may only point at other files dropped with it (confineTo);
|
|
15
|
+
// - uploads are size-capped, one plan runs at a time, temp files are removed afterwards, and
|
|
16
|
+
// the temp folder's path never reaches the page or the files it hands over.
|
|
17
|
+
|
|
18
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
19
|
+
import { createServer } from 'node:http';
|
|
20
|
+
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
21
|
+
import { tmpdir } from 'node:os';
|
|
22
|
+
import { basename, join, resolve, sep } from 'node:path';
|
|
23
|
+
import { pathToFileURL } from 'node:url';
|
|
24
|
+
import { buildPlan, detectSource } from '../plan.js';
|
|
25
|
+
import { PLATFORMS, SOURCES, TARGETS, pairProblem } from '../platforms/index.js';
|
|
26
|
+
import { settingEffect } from '../report/terminal.js';
|
|
27
|
+
import { writePlan } from '../write.js';
|
|
28
|
+
import { renderPage } from './page.js';
|
|
29
|
+
|
|
30
|
+
export const DEFAULT_PORT = 47471; // redirect-map-check uses 47470, so both can run at once
|
|
31
|
+
const MAX_BODY = 64 * 1024 * 1024; // uploads arrive base64-encoded in JSON
|
|
32
|
+
const MAX_CLIENTS = 8; // event streams; the oldest is closed beyond this
|
|
33
|
+
const REPLAY_PAGES = 200; // page events replayed to a page that connects mid-run
|
|
34
|
+
const SLOW_CLIENT_BYTES = 1024 * 1024; // above this backlog a stream only gets the important events
|
|
35
|
+
const SECURITY_HEADERS = {
|
|
36
|
+
'x-content-type-options': 'nosniff',
|
|
37
|
+
'referrer-policy': 'no-referrer',
|
|
38
|
+
'x-frame-options': 'DENY',
|
|
39
|
+
'cache-control': 'no-store',
|
|
40
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
41
|
+
'cross-origin-opener-policy': 'same-origin',
|
|
42
|
+
};
|
|
43
|
+
const CSV = 'text/csv; charset=utf-8';
|
|
44
|
+
const JSON_TYPE = 'application/json; charset=utf-8';
|
|
45
|
+
const downloadType = (name) => (name.endsWith('.csv') ? CSV : name.endsWith('.json') ? JSON_TYPE : 'text/html; charset=utf-8');
|
|
46
|
+
|
|
47
|
+
// Command-line flags as the page labels them, for messages shown in the page.
|
|
48
|
+
const FLAG_LABELS = {
|
|
49
|
+
sitemap: 'Old sitemap',
|
|
50
|
+
urls: 'Old URLs file',
|
|
51
|
+
'old-base': "Old site's address",
|
|
52
|
+
'old-redirects': 'Old redirects export',
|
|
53
|
+
rules: 'Rules file',
|
|
54
|
+
from: 'From',
|
|
55
|
+
to: 'To',
|
|
56
|
+
'blog-handle': 'Blog handle',
|
|
57
|
+
'posts-collection': 'Posts Collection',
|
|
58
|
+
titles: 'Read the old pages’ titles',
|
|
59
|
+
limit: 'Plan only the first N URLs',
|
|
60
|
+
'ignore-robots': 'Ignore robots.txt',
|
|
61
|
+
'allow-private-network': 'Allow private network addresses',
|
|
62
|
+
};
|
|
63
|
+
// Only a flag that starts the text or follows a space or "(" is a flag; "/summer-sale--limit" is a URL.
|
|
64
|
+
export const forPage = (text) =>
|
|
65
|
+
String(text ?? '')
|
|
66
|
+
.replace(/(^|[\s(])--([a-z][a-z-]*)(?![\w-])/g, (m, pre, name) => (FLAG_LABELS[name] ? `${pre}“${FLAG_LABELS[name]}”` : m))
|
|
67
|
+
// The planner's own advice for an unreadable child sitemap names its flags; say it the page's way.
|
|
68
|
+
.replace(/Re-run, or save the child sitemaps that load and pass each one with “Old sitemap”, or plan from a URL list with “Old URLs file”\./, 'Run it again, or drop the child sitemaps that load as files, or drop a list of URLs instead.');
|
|
69
|
+
|
|
70
|
+
const isHttpUrl = (v) => {
|
|
71
|
+
try {
|
|
72
|
+
const u = new URL(String(v));
|
|
73
|
+
return u.protocol === 'http:' || u.protocol === 'https:';
|
|
74
|
+
} catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
function sameToken(given, token) {
|
|
80
|
+
const a = Buffer.from(String(given ?? ''));
|
|
81
|
+
const b = Buffer.from(token);
|
|
82
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function send(res, status, body, headers = {}) {
|
|
86
|
+
const isText = typeof body === 'string' || Buffer.isBuffer(body);
|
|
87
|
+
const payload = isText ? body : JSON.stringify(body);
|
|
88
|
+
res.writeHead(status, {
|
|
89
|
+
...SECURITY_HEADERS,
|
|
90
|
+
'content-type': isText ? 'text/plain; charset=utf-8' : JSON_TYPE,
|
|
91
|
+
...headers,
|
|
92
|
+
});
|
|
93
|
+
res.end(payload);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const httpError = (status, message) => Object.assign(new Error(message), { status });
|
|
97
|
+
|
|
98
|
+
async function readJson(req, limit = MAX_BODY) {
|
|
99
|
+
const tooBig = () => httpError(413, `The upload is larger than ${Math.round(limit / 1024 / 1024)} MB.`);
|
|
100
|
+
if (Number(req.headers['content-length']) > limit) throw tooBig();
|
|
101
|
+
const chunks = [];
|
|
102
|
+
let size = 0;
|
|
103
|
+
for await (const chunk of req) {
|
|
104
|
+
size += chunk.length;
|
|
105
|
+
if (size > limit) throw tooBig();
|
|
106
|
+
chunks.push(chunk);
|
|
107
|
+
}
|
|
108
|
+
let value;
|
|
109
|
+
try {
|
|
110
|
+
value = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
111
|
+
} catch {
|
|
112
|
+
throw httpError(400, 'The request body is not valid JSON.');
|
|
113
|
+
}
|
|
114
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw httpError(400, 'Expected a JSON object.');
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Digits only, like the command line: "0x10", "1e3" and " 5 " are refused. */
|
|
119
|
+
function numberIn(value, name, min, max) {
|
|
120
|
+
if (value === undefined || value === null || value === '') return undefined;
|
|
121
|
+
const n = /^\d+$/.test(String(value)) ? Number(value) : NaN;
|
|
122
|
+
if (!Number.isInteger(n) || n < min || n > max) throw httpError(400, `${name} must be a whole number from ${min} to ${max}.`);
|
|
123
|
+
return n;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** URLs: one per line or space. Commas are allowed inside URLs, so they don't separate. */
|
|
127
|
+
function urlList(value) {
|
|
128
|
+
if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter(Boolean);
|
|
129
|
+
return String(value ?? '').split(/\s+/).filter(Boolean);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A file name that is safe inside our folder: no path, no control characters, unique. */
|
|
133
|
+
function safeName(raw, taken, fallback) {
|
|
134
|
+
let name = basename(String(raw ?? '')).replace(/[^\w.\-() ]+/g, '_').replace(/^\.+/, '').slice(0, 120) || fallback;
|
|
135
|
+
if (taken.has(name.toLowerCase())) {
|
|
136
|
+
const dot = name.lastIndexOf('.');
|
|
137
|
+
const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
|
|
138
|
+
let i = 2;
|
|
139
|
+
while (taken.has(`${stem}-${i}${ext}`.toLowerCase())) i += 1;
|
|
140
|
+
name = `${stem}-${i}${ext}`;
|
|
141
|
+
}
|
|
142
|
+
taken.add(name.toLowerCase());
|
|
143
|
+
return name;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function upload(value, label) {
|
|
147
|
+
if (value === undefined || value === null) return null;
|
|
148
|
+
if (typeof value !== 'object' || Array.isArray(value) || typeof value.data !== 'string') throw httpError(400, `${label}: expected a file.`);
|
|
149
|
+
return { name: value.name, bytes: Buffer.from(value.data, 'base64') };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const HANDLE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Turn the page's form into buildPlan options. Uploaded files are written to a private temp
|
|
156
|
+
* folder under their own names (so an index and its children dropped together still find each
|
|
157
|
+
* other); command-line defaults (paths) are used only when the page asks for them.
|
|
158
|
+
*/
|
|
159
|
+
async function buildOptions(form, defaults, dir) {
|
|
160
|
+
const options = { confineTo: dir };
|
|
161
|
+
const taken = new Set();
|
|
162
|
+
const save = async (file, fallback) => {
|
|
163
|
+
const path = join(dir, safeName(file.name, taken, fallback));
|
|
164
|
+
await writeFile(path, file.bytes);
|
|
165
|
+
return path;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const sitemaps = urlList(form.sitemaps);
|
|
169
|
+
for (const s of sitemaps) if (!isHttpUrl(s)) throw httpError(400, `Sitemap "${s.slice(0, 80)}" must be an http(s) URL. Drop a saved file instead.`);
|
|
170
|
+
options.sitemaps = [...sitemaps];
|
|
171
|
+
options.urlLists = [];
|
|
172
|
+
if (form.useDefaultOld) {
|
|
173
|
+
// Local files given on the command line (URLs from there are prefilled in the page instead).
|
|
174
|
+
options.sitemaps.push(...(defaults.sitemaps ?? []).filter((s) => !isHttpUrl(s)));
|
|
175
|
+
options.urlLists.push(...(defaults.urlLists ?? []));
|
|
176
|
+
}
|
|
177
|
+
if (form.oldFiles !== undefined && form.oldFiles !== null && !Array.isArray(form.oldFiles)) throw httpError(400, 'oldFiles: expected a list of files.');
|
|
178
|
+
for (const file of form.oldFiles ?? []) {
|
|
179
|
+
const f = upload(file, 'old URLs file');
|
|
180
|
+
const head = f.bytes.subarray(0, 512);
|
|
181
|
+
const isSitemap = (head[0] === 0x1f && head[1] === 0x8b) || /^\s*()?</.test(head.toString('utf8'));
|
|
182
|
+
(isSitemap ? options.sitemaps : options.urlLists).push(await save(f, isSitemap ? 'sitemap.xml' : 'urls.txt'));
|
|
183
|
+
}
|
|
184
|
+
if (!options.sitemaps.length && !options.urlLists.length) throw httpError(400, 'Add the old sitemap URL, or drop a saved sitemap or a list of URLs.');
|
|
185
|
+
|
|
186
|
+
const oldBase = String(form.oldBase ?? '').trim();
|
|
187
|
+
if (oldBase) {
|
|
188
|
+
if (!isHttpUrl(oldBase)) throw httpError(400, "The old site's address must be an http(s) URL.");
|
|
189
|
+
options.oldBase = oldBase;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const oldRedirects = upload(form.oldRedirectsFile, 'old redirects export');
|
|
193
|
+
if (oldRedirects) options.oldRedirects = await save(oldRedirects, 'old-redirects.csv');
|
|
194
|
+
else if (form.useDefaultOldRedirects && defaults.oldRedirects) options.oldRedirects = defaults.oldRedirects;
|
|
195
|
+
const rules = upload(form.rulesFile, 'rules file');
|
|
196
|
+
if (rules) options.rulesFile = await save(rules, 'rules.csv');
|
|
197
|
+
else if (form.useDefaultRules && defaults.rulesFile) options.rulesFile = defaults.rulesFile;
|
|
198
|
+
|
|
199
|
+
const from = String(form.from ?? '');
|
|
200
|
+
options.suggest = from === 'suggest';
|
|
201
|
+
if (!options.suggest) {
|
|
202
|
+
if (!SOURCES.includes(from)) throw httpError(400, 'Pick the platform the old site is on, or “Not sure, suggest one”.');
|
|
203
|
+
const to = String(form.to ?? '');
|
|
204
|
+
if (!TARGETS.includes(to)) throw httpError(400, 'Pick where the site is going.');
|
|
205
|
+
const problem = pairProblem(from, to);
|
|
206
|
+
if (problem) throw httpError(400, problem);
|
|
207
|
+
options.from = from;
|
|
208
|
+
options.to = to;
|
|
209
|
+
const handle = String(form.blogHandle ?? '').trim();
|
|
210
|
+
if (handle && to === 'shopify') {
|
|
211
|
+
if (!HANDLE.test(handle)) throw httpError(400, 'The blog handle must be lowercase letters, numbers and hyphens (e.g. news).');
|
|
212
|
+
options.blogHandle = handle;
|
|
213
|
+
}
|
|
214
|
+
const collection = String(form.postsCollection ?? '').trim();
|
|
215
|
+
if (collection && to === 'webflow') {
|
|
216
|
+
if (!HANDLE.test(collection)) throw httpError(400, 'The posts Collection slug must be lowercase letters, numbers and hyphens (e.g. blog).');
|
|
217
|
+
options.postsCollection = collection;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
options.titles = Boolean(form.titles);
|
|
222
|
+
options.concurrency = numberIn(form.concurrency, 'Requests at once', 1, 16);
|
|
223
|
+
options.delayMs = numberIn(form.delay, 'Delay between requests', 0, 60_000);
|
|
224
|
+
options.timeoutMs = numberIn(form.timeout, 'Timeout', 1000, 120_000);
|
|
225
|
+
options.limit = numberIn(form.limit, 'Plan only the first N URLs', 1, 10_000_000);
|
|
226
|
+
options.respectRobots = !form.ignoreRobots;
|
|
227
|
+
options.allowPrivateNetwork = Boolean(form.allowPrivateNetwork);
|
|
228
|
+
for (const k of Object.keys(options)) if (options[k] === undefined) delete options[k];
|
|
229
|
+
return options;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** What the page may know about command-line defaults: values and file names, never paths. */
|
|
233
|
+
function publicDefaults(defaults) {
|
|
234
|
+
const localNames = (list) => (list ?? []).filter((s) => !isHttpUrl(s)).map((s) => basename(s));
|
|
235
|
+
return {
|
|
236
|
+
sitemaps: (defaults.sitemaps ?? []).filter(isHttpUrl),
|
|
237
|
+
localOld: [...localNames(defaults.sitemaps), ...localNames(defaults.urlLists)],
|
|
238
|
+
oldRedirects: defaults.oldRedirects ? basename(defaults.oldRedirects) : null,
|
|
239
|
+
rulesFile: defaults.rulesFile ? basename(defaults.rulesFile) : null,
|
|
240
|
+
oldBase: defaults.oldBase ?? '',
|
|
241
|
+
from: SOURCES.includes(defaults.from) ? defaults.from : '',
|
|
242
|
+
to: TARGETS.includes(defaults.to) ? defaults.to : '',
|
|
243
|
+
blogHandle: defaults.blogHandle ?? '',
|
|
244
|
+
postsCollection: defaults.postsCollection ?? '',
|
|
245
|
+
titles: Boolean(defaults.titles),
|
|
246
|
+
ignoreRobots: Boolean(defaults.ignoreRobots),
|
|
247
|
+
allowPrivateNetwork: Boolean(defaults.allowPrivateNetwork),
|
|
248
|
+
numbers: Object.fromEntries(
|
|
249
|
+
['delay', 'concurrency', 'timeout', 'limit'].filter((k) => defaults[k] !== undefined && defaults[k] !== null && defaults[k] !== '').map((k) => [k, String(defaults[k])]),
|
|
250
|
+
),
|
|
251
|
+
platforms: {
|
|
252
|
+
from: SOURCES.map((id) => ({ id, name: PLATFORMS[id].name })),
|
|
253
|
+
to: TARGETS.map((id) => ({ id, name: id === 'custom' ? 'Custom code' : PLATFORMS[id].name })),
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Replace our temp folder in any string inside a value (notes, inputs, sitemap file names). */
|
|
259
|
+
function scrubDeep(value, prefixes, depth = 0) {
|
|
260
|
+
if (typeof value === 'string') return prefixes.reduce((s, p) => s.split(p).join(''), value);
|
|
261
|
+
if (depth > 6 || !value || typeof value !== 'object') return value;
|
|
262
|
+
if (Array.isArray(value)) {
|
|
263
|
+
for (let i = 0; i < value.length; i += 1) value[i] = scrubDeep(value[i], prefixes, depth + 1);
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
for (const key of Object.keys(value)) value[key] = scrubDeep(value[key], prefixes, depth + 1);
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const itemRow = (p) => ({
|
|
271
|
+
path: p.path,
|
|
272
|
+
query: p.query || '',
|
|
273
|
+
type: p.type,
|
|
274
|
+
outcome: p.outcome,
|
|
275
|
+
newPath: p.newPath ?? null,
|
|
276
|
+
notes: [p.problem?.text, p.typeNote, ...(p.notes ?? [])].filter(Boolean).map(forPage),
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
/** Start the interface. Returns { url, port, token, close() }. */
|
|
280
|
+
export async function startUi({ port = 0, open = true, defaults = {}, version = '', userAgent, outDir = 'redirect-plan', openBrowser, maxBody = MAX_BODY, log = () => {} } = {}) {
|
|
281
|
+
const token = randomBytes(24).toString('hex');
|
|
282
|
+
let current = { events: [], recentPages: [], status: 'idle' }; // the last (or running) plan
|
|
283
|
+
const clients = new Set();
|
|
284
|
+
let busy = false; // reserved synchronously, so two requests can't both start a plan
|
|
285
|
+
let stopping = false; // a cancel was asked for and the plan is still winding down
|
|
286
|
+
let actualPort = port;
|
|
287
|
+
let launcherDir = null;
|
|
288
|
+
|
|
289
|
+
const allowedHosts = () => new Set([`127.0.0.1:${actualPort}`, `localhost:${actualPort}`, `[::1]:${actualPort}`]);
|
|
290
|
+
const allowedOrigins = () => new Set([...allowedHosts()].map((h) => `http://${h}`));
|
|
291
|
+
const origin = () => `http://127.0.0.1:${actualPort}`;
|
|
292
|
+
|
|
293
|
+
const write = (client, event) => {
|
|
294
|
+
// A stream that isn't keeping up gets only the events that matter (no per-page noise).
|
|
295
|
+
if ((event.type === 'page' || event.type === 'progress') && client.writableLength > SLOW_CLIENT_BYTES) return;
|
|
296
|
+
client.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
297
|
+
};
|
|
298
|
+
const emit = (state, event) => {
|
|
299
|
+
if (state !== current) return; // a cancelled plan that is still winding down
|
|
300
|
+
if (event.type === 'page') {
|
|
301
|
+
state.recentPages.push(event);
|
|
302
|
+
if (state.recentPages.length > REPLAY_PAGES) state.recentPages.shift();
|
|
303
|
+
} else if (event.type === 'progress') {
|
|
304
|
+
state.progress = event;
|
|
305
|
+
} else {
|
|
306
|
+
state.events.push(event);
|
|
307
|
+
}
|
|
308
|
+
for (const client of clients) write(client, event);
|
|
309
|
+
};
|
|
310
|
+
const TERMINAL = ['done', 'suggested', 'cancelled', 'error'];
|
|
311
|
+
const replay = (client) => {
|
|
312
|
+
const terminal = current.events.filter((e) => TERMINAL.includes(e.type));
|
|
313
|
+
for (const e of current.events) if (!terminal.includes(e)) write(client, e);
|
|
314
|
+
if (current.progress) write(client, current.progress);
|
|
315
|
+
for (const e of current.recentPages) write(client, e);
|
|
316
|
+
for (const e of terminal) write(client, e);
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
async function startRun(form) {
|
|
320
|
+
// A plan that was just cancelled may take a moment to stop; wait for it rather than refuse.
|
|
321
|
+
for (let i = 0; i < 100 && busy && stopping; i += 1) await new Promise((r) => setTimeout(r, 20));
|
|
322
|
+
if (busy) throw httpError(409, 'A plan is already running. Cancel it first.');
|
|
323
|
+
busy = true;
|
|
324
|
+
let dir;
|
|
325
|
+
let inputs;
|
|
326
|
+
let options;
|
|
327
|
+
try {
|
|
328
|
+
dir = await mkdtemp(join(tmpdir(), 'rmp-ui-'));
|
|
329
|
+
inputs = join(dir, 'in');
|
|
330
|
+
await mkdir(inputs);
|
|
331
|
+
options = await buildOptions(form, defaults, inputs);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
busy = false;
|
|
334
|
+
if (dir) await rm(dir, { recursive: true, force: true });
|
|
335
|
+
throw err;
|
|
336
|
+
}
|
|
337
|
+
if (current.dir) await rm(current.dir, { recursive: true, force: true });
|
|
338
|
+
const controller = new AbortController();
|
|
339
|
+
const state = { controller, events: [], recentPages: [], progress: null, status: 'running', dir, filesDir: join(dir, 'plan'), plan: null, files: null };
|
|
340
|
+
current = state;
|
|
341
|
+
const prefixes = [inputs + sep, dir + sep, inputs, dir];
|
|
342
|
+
const clean = (text) => forPage(scrubDeep(String(text ?? ''), prefixes));
|
|
343
|
+
const { suggest, ...planOptions } = options;
|
|
344
|
+
emit(state, { type: 'start', suggest, at: Date.now() });
|
|
345
|
+
|
|
346
|
+
const common = { userAgent, signal: controller.signal };
|
|
347
|
+
const work = suggest
|
|
348
|
+
? (emit(state, { type: 'phase', name: 'suggest' }),
|
|
349
|
+
detectSource({ ...planOptions, ...common }).then((suggestions) => {
|
|
350
|
+
if (controller.signal.aborted) throw Object.assign(new Error('Cancelled.'), { code: 'ECANCELLED' });
|
|
351
|
+
state.status = 'suggested';
|
|
352
|
+
busy = false;
|
|
353
|
+
stopping = false;
|
|
354
|
+
emit(state, { type: 'suggested', suggestions: suggestions.slice(0, 3).map((s) => ({ id: s.id, name: s.name, evidence: (s.evidence ?? []).map(clean) })) });
|
|
355
|
+
}))
|
|
356
|
+
: buildPlan({
|
|
357
|
+
...planOptions,
|
|
358
|
+
...common,
|
|
359
|
+
onPhase: (name, detail) => emit(state, { type: 'phase', name, ...detail }),
|
|
360
|
+
onProgress: (done, total) => emit(state, { type: 'progress', done, total }),
|
|
361
|
+
onPage: (p) => emit(state, { type: 'page', url: p.url, title: p.title, status: p.status }),
|
|
362
|
+
}).then(async (plan) => {
|
|
363
|
+
if (controller.signal.aborted) throw Object.assign(new Error('Cancelled.'), { code: 'ECANCELLED' });
|
|
364
|
+
scrubDeep(plan.inputs, prefixes);
|
|
365
|
+
scrubDeep(plan.notes, prefixes);
|
|
366
|
+
scrubDeep(plan.warnings, prefixes);
|
|
367
|
+
for (const p of plan.items) p.sitemapFile &&= scrubDeep(p.sitemapFile, prefixes);
|
|
368
|
+
state.plan = plan;
|
|
369
|
+
state.files = await writePlan(plan, state.filesDir, { version, commandDir: '.' });
|
|
370
|
+
state.status = 'done';
|
|
371
|
+
busy = false; // before the event, so the page can start the next plan straight away
|
|
372
|
+
stopping = false;
|
|
373
|
+
emit(state, { type: 'done', summary: plan.summary });
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
work
|
|
377
|
+
.catch((err) => {
|
|
378
|
+
state.status = err?.code === 'ECANCELLED' || controller.signal.aborted ? 'cancelled' : 'failed';
|
|
379
|
+
busy = false;
|
|
380
|
+
stopping = false;
|
|
381
|
+
emit(state, state.status === 'cancelled' ? { type: 'cancelled', message: 'The plan was cancelled.' } : { type: 'error', message: clean(err?.message ?? err) });
|
|
382
|
+
})
|
|
383
|
+
.finally(async () => {
|
|
384
|
+
// Uploaded inputs are no longer needed; the plan's files stay until the next run or exit.
|
|
385
|
+
busy = false;
|
|
386
|
+
stopping = false;
|
|
387
|
+
await rm(inputs, { recursive: true, force: true });
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function downloads() {
|
|
392
|
+
const f = current.files;
|
|
393
|
+
if (!f) return [];
|
|
394
|
+
return [f.html, f.redirects, f.map, f.json, f.pages].filter(Boolean).map((p) => basename(p));
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function results() {
|
|
398
|
+
const plan = current.plan;
|
|
399
|
+
if (!plan) return null;
|
|
400
|
+
return {
|
|
401
|
+
from: plan.from,
|
|
402
|
+
to: { ...plan.to, name: plan.to.id === 'custom' ? 'custom code' : plan.to.name },
|
|
403
|
+
summary: plan.summary,
|
|
404
|
+
redirectFile: plan.redirectFile.name,
|
|
405
|
+
files: downloads(),
|
|
406
|
+
command: current.files.command,
|
|
407
|
+
settings: plan.settings.map((x) => ({ text: x.text, effect: settingEffect(x), examples: x.examples })),
|
|
408
|
+
warnings: plan.warnings.map((w) => ({ text: forPage(w.text), examples: w.examples ?? [] })),
|
|
409
|
+
notes: plan.notes.map(forPage),
|
|
410
|
+
items: [...plan.items.map(itemRow), ...plan.rows.filter((r) => r.origin === 'old-redirect').map((r) => ({ ...itemRow(r.item), outcome: 'old-redirect', newPath: r.to }))],
|
|
411
|
+
rules: plan.rules.length,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const server = createServer(async (req, res) => {
|
|
416
|
+
try {
|
|
417
|
+
// 1. Only our own address (DNS rebinding sends a foreign Host header).
|
|
418
|
+
if (!allowedHosts().has(String(req.headers.host ?? '').toLowerCase())) return send(res, 403, 'Host not allowed.');
|
|
419
|
+
const url = new URL(req.url, origin());
|
|
420
|
+
const path = url.pathname;
|
|
421
|
+
const headerToken = req.headers['x-rmp-token'];
|
|
422
|
+
|
|
423
|
+
if (req.method === 'GET' && path === '/') {
|
|
424
|
+
// The page itself holds no data, so it needs no token: it reads the token from its
|
|
425
|
+
// address (then removes it) or from sessionStorage, and sends it with every API call.
|
|
426
|
+
const nonce = randomBytes(16).toString('base64');
|
|
427
|
+
res.writeHead(200, {
|
|
428
|
+
...SECURITY_HEADERS,
|
|
429
|
+
'content-type': 'text/html; charset=utf-8',
|
|
430
|
+
'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
|
|
431
|
+
});
|
|
432
|
+
return res.end(renderPage({ nonce, version }));
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// 2. Everything else needs the token: in a header, or in the query for the event stream.
|
|
436
|
+
if (req.method === 'GET') {
|
|
437
|
+
const given = path === '/api/events' ? url.searchParams.get('t') : headerToken;
|
|
438
|
+
if (!sameToken(given, token)) return send(res, 403, 'Missing or wrong access token. Open the address printed in the terminal.');
|
|
439
|
+
} else if (req.method === 'POST') {
|
|
440
|
+
const reqOrigin = req.headers.origin;
|
|
441
|
+
if (reqOrigin !== undefined && !allowedOrigins().has(String(reqOrigin).toLowerCase())) return send(res, 403, 'Cross-site request refused.');
|
|
442
|
+
if (!sameToken(headerToken, token)) return send(res, 403, 'Missing or wrong access token.');
|
|
443
|
+
if (!/^application\/json\b/i.test(String(req.headers['content-type'] ?? ''))) return send(res, 415, 'Expected JSON.');
|
|
444
|
+
} else {
|
|
445
|
+
return send(res, 405, 'Method not allowed.');
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
if (req.method === 'GET' && path === '/api/defaults') return send(res, 200, publicDefaults(defaults));
|
|
449
|
+
if (req.method === 'GET' && path === '/api/status') return send(res, 200, { busy, status: current.status });
|
|
450
|
+
|
|
451
|
+
if (req.method === 'GET' && path === '/api/events') {
|
|
452
|
+
res.writeHead(200, { ...SECURITY_HEADERS, 'content-type': 'text/event-stream; charset=utf-8', connection: 'keep-alive' });
|
|
453
|
+
res.write(': connected\n\n');
|
|
454
|
+
if (clients.size >= MAX_CLIENTS) [...clients][0].end();
|
|
455
|
+
clients.add(res);
|
|
456
|
+
replay(res);
|
|
457
|
+
const keepAlive = setInterval(() => res.write(': keep-alive\n\n'), 15_000);
|
|
458
|
+
const drop = () => {
|
|
459
|
+
clearInterval(keepAlive);
|
|
460
|
+
clients.delete(res);
|
|
461
|
+
};
|
|
462
|
+
req.on('close', drop);
|
|
463
|
+
res.on('close', drop);
|
|
464
|
+
return undefined;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
if (req.method === 'GET' && path === '/api/results') {
|
|
468
|
+
const data = results();
|
|
469
|
+
return data ? send(res, 200, data) : send(res, 404, 'No finished plan yet.');
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (req.method === 'GET' && path.startsWith('/api/download/')) {
|
|
473
|
+
const name = path.slice('/api/download/'.length);
|
|
474
|
+
// Only the names this plan wrote: nothing else in the folder, no paths.
|
|
475
|
+
if (!downloads().includes(name)) return send(res, 404, 'Not found.');
|
|
476
|
+
let body;
|
|
477
|
+
try {
|
|
478
|
+
body = await readFile(join(current.filesDir, name));
|
|
479
|
+
} catch {
|
|
480
|
+
return send(res, 404, 'Not found.');
|
|
481
|
+
}
|
|
482
|
+
return send(res, 200, body, {
|
|
483
|
+
'content-type': downloadType(name),
|
|
484
|
+
'content-disposition': `attachment; filename="${name}"`,
|
|
485
|
+
...(name === 'plan.html' ? { 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox" } : {}),
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
if (req.method === 'POST' && path === '/api/run') {
|
|
490
|
+
const form = await readJson(req, maxBody);
|
|
491
|
+
await startRun(form);
|
|
492
|
+
return send(res, 202, { ok: true });
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (req.method === 'POST' && path === '/api/cancel') {
|
|
496
|
+
await readJson(req, 64 * 1024);
|
|
497
|
+
if (current.status === 'running') {
|
|
498
|
+
stopping = true;
|
|
499
|
+
current.controller.abort();
|
|
500
|
+
}
|
|
501
|
+
return send(res, 200, { ok: true });
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (req.method === 'POST' && path === '/api/save') {
|
|
505
|
+
const body = await readJson(req, 64 * 1024);
|
|
506
|
+
if (!current.plan) return send(res, 409, { error: 'There is no finished plan to save yet.' });
|
|
507
|
+
const target = resolve(outDir);
|
|
508
|
+
const exists = await access(join(target, 'plan.html')).then(() => true, () => false);
|
|
509
|
+
// Not an error: the page asks the user and sends overwrite: true if they agree.
|
|
510
|
+
if (exists && !body.overwrite) return send(res, 200, { ok: false, exists: true, path: target });
|
|
511
|
+
const files = await writePlan(current.plan, target, { version });
|
|
512
|
+
return send(res, 200, { ok: true, path: target, command: files.command, stalePages: Boolean(files.stalePages) });
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
return send(res, 404, 'Not found.');
|
|
516
|
+
} catch (err) {
|
|
517
|
+
// After refusing an oversized upload, close the connection: the rest of the body is still
|
|
518
|
+
// in flight, and a kept-alive socket would make the browser's next request wait behind it.
|
|
519
|
+
const closing = err?.status === 413 ? { connection: 'close' } : {};
|
|
520
|
+
return send(res, err?.status ?? 500, { error: err?.message ?? 'Something went wrong.' }, closing);
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
await new Promise((r, reject) => {
|
|
525
|
+
server.once('error', reject);
|
|
526
|
+
server.listen(port, '127.0.0.1', r);
|
|
527
|
+
});
|
|
528
|
+
actualPort = server.address().port;
|
|
529
|
+
const address = `${origin()}/?t=${token}`;
|
|
530
|
+
log(address);
|
|
531
|
+
if (open) {
|
|
532
|
+
// Open a small private file that forwards to the address, so the token isn't in the
|
|
533
|
+
// browser launcher's command line (visible to other users in `ps`).
|
|
534
|
+
launcherDir = await mkdtemp(join(tmpdir(), 'rmp-open-'));
|
|
535
|
+
const launcher = join(launcherDir, 'open.html');
|
|
536
|
+
await writeFile(launcher, `<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${address}"><title>redirect-map-plan</title><p>Opening redirect-map-plan…</p>`, { mode: 0o600 });
|
|
537
|
+
(openBrowser ?? (await import('../open.js')).openInBrowser)(pathToFileURL(launcher).href);
|
|
538
|
+
setTimeout(() => rm(launcherDir, { recursive: true, force: true }).catch(() => {}), 60_000).unref();
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
return {
|
|
542
|
+
url: address,
|
|
543
|
+
port: actualPort,
|
|
544
|
+
token,
|
|
545
|
+
async close() {
|
|
546
|
+
if (current.status === 'running') current.controller.abort();
|
|
547
|
+
for (const client of clients) client.end();
|
|
548
|
+
await new Promise((r) => server.close(r));
|
|
549
|
+
server.closeAllConnections?.();
|
|
550
|
+
if (current.dir) await rm(current.dir, { recursive: true, force: true });
|
|
551
|
+
if (launcherDir) await rm(launcherDir, { recursive: true, force: true });
|
|
552
|
+
},
|
|
553
|
+
};
|
|
554
|
+
}
|
package/src/write.js
CHANGED
|
@@ -38,7 +38,12 @@ export function checkerMapCsv(plan) {
|
|
|
38
38
|
return toCsv([['old', 'new'], ...plan.rows.map((r) => [r.oldUrl, r.to])]);
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Write the files to outDir. commandDir: the folder the printed redirect-map-check command names
|
|
43
|
+
* for redirect-map.csv (default outDir; the browser interface passes '.' for files it hands over
|
|
44
|
+
* as downloads, which land wherever the browser saves them).
|
|
45
|
+
*/
|
|
46
|
+
export async function writePlan(plan, outDir, { version = '', commandDir } = {}) {
|
|
42
47
|
await mkdir(outDir, { recursive: true });
|
|
43
48
|
const files = {
|
|
44
49
|
redirects: join(outDir, plan.redirectFile.name),
|
|
@@ -46,7 +51,7 @@ export async function writePlan(plan, outDir, { version = '' } = {}) {
|
|
|
46
51
|
html: join(outDir, 'plan.html'),
|
|
47
52
|
json: join(outDir, 'plan.json'),
|
|
48
53
|
};
|
|
49
|
-
const command = checkCommand(plan, outDir);
|
|
54
|
+
const command = checkCommand(plan, commandDir ?? outDir);
|
|
50
55
|
// A redirect file for another target, left by an earlier run, could be imported by mistake.
|
|
51
56
|
for (const name of REDIRECT_FILES) if (name !== plan.redirectFile.name) await rm(join(outDir, name), { force: true });
|
|
52
57
|
await writeFile(files.redirects, redirectFileCsv(plan));
|