-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevel-items.mjs
More file actions
275 lines (240 loc) · 10.3 KB
/
Copy pathlevel-items.mjs
File metadata and controls
275 lines (240 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env node
/**
* Level Items for Borderlands 4: sync every backpack and equipped item to the character's own level.
*
* Runs in two phases:
* 1. Scan every character save and back all of them up (verified by SHA-256).
* 2. Rewrite the item serials, re-encrypt, verify the round trip, and write atomically.
*
* No prompts, no network, no npm dependencies. The platform ID is read from the save folder name.
*
* Usage:
* node level-items.mjs apply (default)
* node level-items.mjs --dry-run report what would change, write nothing
* node level-items.mjs --verify decrypt/re-encrypt check only, no item changes
* node level-items.mjs --root "D:/path/to/SaveGames"
* node level-items.mjs --force proceed even if Borderlands 4 looks like it is running
*/
import { copyFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { basename, dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { decryptSav, encryptSav, verifyRoundTrip } from './lib/savcrypt.mjs';
import { findProfiles, findSaveFiles, findSaveRoots, isGameRunning } from './lib/saves.mjs';
import { findCharacterSerials, readCharacterLevel, replaceSerialOnLine } from './lib/yamledit.mjs';
import { updateSerialLevel } from './lib/serial.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const argv = process.argv.slice(2);
const has = (flag) => argv.includes(flag);
const valueOf = (flag) => {
const i = argv.findIndex((a) => a === flag || a.startsWith(flag + '='));
if (i === -1) return undefined;
return argv[i].includes('=') ? argv[i].split('=').slice(1).join('=') : argv[i + 1];
};
const DRY_RUN = has('--dry-run');
const VERIFY_ONLY = has('--verify');
const FORCE = has('--force');
const log = [];
function say(line = '') {
console.log(line);
log.push(line);
}
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
const stamp = () => new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
const mask = (id) => (id.length > 6 ? id.slice(0, 4) + '...' + id.slice(-2) : id);
if (has('--help') || has('-h')) {
console.log(`
Syncs every backpack and equipped item to each character's own level.
Backs up all saves first; runs entirely offline with no dependencies.
node level-items.mjs back up, then apply (default)
node level-items.mjs --dry-run report what would change, write nothing
node level-items.mjs --verify decrypt/re-encrypt check only, no changes
node level-items.mjs --root "PATH" use PATH instead of auto-detection
node level-items.mjs --force run even if the game appears to be open
Close Borderlands 4 before applying: it holds saves in memory and overwrites
them on exit, so changes made while it runs are lost.
`.trim());
process.exit(0);
}
// ---------------------------------------------------------------- discovery
const rootOverride = valueOf('--root');
const roots = findSaveRoots(rootOverride);
if (roots.length === 0) {
if (rootOverride) {
say(`ERROR: --root path not found or not a directory: ${rootOverride}`);
} else {
say('ERROR: no Borderlands 4 SaveGames folder found.');
say(' Looked under %USERPROFILE%\\Documents and %USERPROFILE%\\OneDrive\\Documents.');
say(' Pass an explicit path with: --root "D:\\path\\to\\SaveGames"');
}
process.exit(1);
}
say('Level Items for Borderlands 4');
say('='.repeat(72));
if (DRY_RUN) say('MODE: dry run - nothing will be written');
if (VERIFY_ONLY) say('MODE: verify only - no item changes will be made');
say();
const game = isGameRunning();
if (game.running && !FORCE) {
say(`ABORTED: Borderlands 4 appears to be running (${game.matches.join(', ')}).`);
say(' The game keeps saves in memory and overwrites them on exit, so changes would be lost.');
say(' Close the game and run again, or pass --force to override.');
process.exit(2);
}
if (!game.checked) say('NOTE: could not check whether the game is running; make sure it is closed.');
// ---------------------------------------------------------------- phase 1: scan
/** @type {Array<{file: string, id: string, level: number, yaml: string, targets: any[], plan: any[]}>} */
const jobs = [];
const allSavFiles = [];
for (const root of roots) {
say(`save root: ${root}`);
for (const profile of findProfiles(root)) {
const files = findSaveFiles(profile.clientDir);
allSavFiles.push(...files.all);
say(` profile ${mask(profile.id)} (${profile.platform}): ` +
`${files.characters.length} character save(s)` + (files.profile ? ' + profile.sav' : ''));
for (const file of files.characters) {
const name = basename(file);
let yaml;
try {
yaml = decryptSav(readFileSync(file), profile.id).yaml;
} catch (err) {
say(` ${name}: SKIPPED - ${err.message}`);
continue;
}
const lines = yaml.split('\n');
const level = readCharacterLevel(lines);
if (level === null) {
say(` ${name}: SKIPPED - could not read character level`);
continue;
}
const { targets, excluded, total, unaccounted } = findCharacterSerials(lines);
// Compute the rewrite plan without touching anything yet.
const plan = targets.map((t) => ({ ...t, result: updateSerialLevel(t.value, level) }));
const counts = plan.reduce((acc, p) => {
acc[p.result.status] = (acc[p.result.status] || 0) + 1;
return acc;
}, {});
const changing = plan.filter((p) => ['updated', 'inserted'].includes(p.result.status));
say(` ${name}: level ${level} | ${targets.length} targeted ` +
`(${targets.filter((t) => t.group === 'backpack').length} backpack, ` +
`${targets.filter((t) => t.group === 'equipped').length} equipped) | ` +
`${excluded} lostloot excluded | ${changing.length} to change`);
say(` status: ${JSON.stringify(counts)}`);
if (unaccounted.length) {
say(` NOTE: ${unaccounted.length} serial line(s) outside targeted subtrees, left alone`);
}
for (const p of plan.filter((x) => ['rejected', 'error'].includes(x.result.status))) {
say(` WARN line ${p.line + 1} (${p.group}): ${p.result.status} - ${p.result.reason}`);
}
if (total !== targets.length + excluded + unaccounted.length) {
say(` ERROR: serial accounting mismatch; refusing to modify ${name}`);
continue;
}
jobs.push({ file, id: profile.id, level, yaml, targets, plan, name });
}
}
}
if (jobs.length === 0) {
say();
say('Nothing to do - no readable character saves found.');
process.exit(1);
}
// ---------------------------------------------------------------- phase 1b: backup
const backupDir = join(HERE, 'backups', stamp());
/**
* Backup destination for a save file.
*
* Two roots can contain the same platform-ID folder name (a real save folder and a copy of it), so
* the source directory is hashed into the backup subfolder name. Without this, backing up the
* second file silently overwrote the first file's backup - a data-loss bug, since the backup is
* the only rollback path.
*/
function backupPathFor(file) {
const idFolder = basename(dirname(dirname(dirname(file))));
const tag = createHash('sha256').update(dirname(file)).digest('hex').slice(0, 6);
return join(backupDir, `${idFolder}-${tag}`, basename(file));
}
say();
if (DRY_RUN) {
say(`backup: skipped (dry run) - would back up ${allSavFiles.length} file(s)`);
} else {
let ok = 0;
for (const file of allSavFiles) {
const dest = backupPathFor(file);
mkdirSync(dirname(dest), { recursive: true });
copyFileSync(file, dest);
if (sha256(readFileSync(file)) !== sha256(readFileSync(dest))) {
say(`ABORTED: backup verification failed for ${file}`);
process.exit(1);
}
ok++;
}
say(`backup: ${ok} file(s) verified by SHA-256 -> ${backupDir}`);
}
// ---------------------------------------------------------------- phase 2: apply
say();
let written = 0;
let itemsChanged = 0;
for (const job of jobs) {
const changing = job.plan.filter((p) => ['updated', 'inserted'].includes(p.result.status));
if (changing.length === 0) {
say(`${job.name}: already in sync at level ${job.level}, no write needed`);
continue;
}
if (DRY_RUN) {
say(`${job.name}: would rewrite ${changing.length} item(s) to level ${job.level}`);
itemsChanged += changing.length;
continue;
}
const lines = job.yaml.split('\n');
if (!VERIFY_ONLY) {
for (const p of changing) lines[p.line] = replaceSerialOnLine(lines[p.line], p.result.serial);
}
const newYaml = lines.join('\n');
const encrypted = encryptSav(newYaml, job.id);
if (!verifyRoundTrip(newYaml, encrypted, job.id)) {
say(`${job.name}: ERROR round-trip verification failed - not written`);
continue;
}
if (VERIFY_ONLY) {
say(`${job.name}: round trip OK (${encrypted.length} bytes), no changes written`);
continue;
}
const tmp = job.file + '.tmp';
writeFileSync(tmp, encrypted);
renameSync(tmp, job.file);
// Read back from disk and confirm; restore the backup if anything is off.
try {
const readBack = decryptSav(readFileSync(job.file), job.id).yaml;
if (readBack !== newYaml) throw new Error('on-disk content does not match what we wrote');
} catch (err) {
copyFileSync(backupPathFor(job.file), job.file);
say(`${job.name}: ERROR ${err.message} - original restored from backup`);
continue;
}
written++;
itemsChanged += changing.length;
const levels = [...new Set(changing.map((p) => p.result.oldLevel))].sort((a, b) => a - b);
say(`${job.name}: ${changing.length} item(s) -> level ${job.level} ` +
`(were: ${levels.join(', ')})`);
}
// ---------------------------------------------------------------- summary
say();
say('='.repeat(72));
if (DRY_RUN) {
say(`Dry run complete: ${itemsChanged} item(s) across ${jobs.length} save(s) would change.`);
} else if (VERIFY_ONLY) {
say(`Verify complete: ${jobs.length} save(s) round-tripped without modification.`);
} else {
say(`Done: ${itemsChanged} item(s) updated across ${written} save file(s).`);
say(`Backup: ${backupDir}`);
if (written > 0) say('Load the game and check your gear. If anything is wrong, restore the backup.');
}
if (!DRY_RUN) {
try {
writeFileSync(join(backupDir, 'run.log'), log.join('\n') + '\n', 'utf8');
} catch {
// logging is best-effort
}
}