Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 106 additions & 4 deletions electron/main/ipc/mods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@ import {
type Mod,
} from '../services/mods';
import { metaKeyFor, isValidDeadlockPath } from '../services/deadlock';
import { getModMetadata, setModMetadata, setModMetadataWithHash, removeModMetadata, pruneOrphanMetadata, type ModMetadata } from '../services/metadata';
import { getModMetadata, loadMetadata, saveMetadata, setModMetadata, setModMetadataWithHash, removeModMetadata, pruneOrphanMetadata, type ModMetadata } from '../services/metadata';
import { inferHeroFromTitle } from '@grimoire/social-types/heroes';
import { inferHeroFromVpk, classifyGlobalModFromVpk, GLOBAL_CLASSIFIER_VERSION, parseVpkDirectory, parseVpkDirectoriesAsync } from '../services/vpk';
import { inferHeroFromVpk, classifyGlobalModFromVpk, GLOBAL_CLASSIFIER_VERSION, parseVpkDirectory, parseVpkDirectoriesAsync, invalidateVpkParseCache } from '../services/vpk';
import { classifyAbilitySoundsFromVpk } from '../services/abilitySounds';
import { migrateIgnoredConflictKeysForMods } from '../services/conflicts';
import { isLockerManaged } from '../services/lockerVpk';
import { retargetProfileModSha } from '../services/profiles';
import { retargetProfileModSha, loadProfiles, saveProfiles } from '../services/profiles';
import { assertCanMoveLoadedGameMod, syncRunningGameModSnapshotFromMods, syncKnownRunningGameModSnapshot } from '../services/gameSessionMods';
import { isDeadlockRunning } from '../services/launch';
import { replaceLocalVpkFile, validateReplacementVpk, replacementFileSha256, assertReplacementFileUnchanged } from '../services/localVpkReplacement';
import { retargetLocalReplacementProfiles } from '../services/localReplacementProfiles';
import {
detectUnknownModCacheMatches,
detectUnknownModFilters,
Expand Down Expand Up @@ -60,7 +64,7 @@ import {
hasAdoptionFields,
hasAnyImprint,
} from '../services/imprintMods';
import { parseAddonInfo, readEmbeddedAddonInfoText, readEmbeddedAddonInfo, carryForwardOriginalIdentity } from '../services/vpkIdentity';
import { parseAddonInfo, readEmbeddedAddonInfoText, readEmbeddedAddonInfo, carryForwardOriginalIdentity, resolveVpkIdentity } from '../services/vpkIdentity';
import { readEmbeddedModinfo, readLegacyGrimoireMergeMeta, hasLegacyGrimoireMergeMetaEntry } from '../services/modinfoFormat';
import { buildHeroSoundSwapVpk, cleanupHeroSoundSwapBuild } from '../services/foundryCatalog';
import { buildSoulContainerVpk, cleanupSoulContainerBuild, previewSoulContainerGlb } from '../services/soulContainerImport';
Expand Down Expand Up @@ -1392,12 +1396,110 @@ async function installedLocalVariantGroupProfile(
};
}

function assertReplaceableLocalVpk(target: Mod | undefined, metadata: ModMetadata | undefined): asserts target is Mod {
if (!target || !metadata?.modName || !metadata.sha256 || metadata.gameBananaId || metadata.gameBananaFileId ||
metadata.merged || metadata.forgeInstall || metadata.soulImport || metadata.urnImport || metadata.soundSwap ||
metadata.lockerCosmetics || metadata.lockerSounds || metadata.lockerColors || metadata.lockerTrippySkins ||
isLockerManaged(target.metaKey)) {
throw new Error('This item cannot be replaced here. Select an installed local VPK');
}
}

ipcMain.handle('prepare-local-vpk-replacement', async (_, metaKey: string) => {
const deadlockPath = getActiveDeadlockPath();
if (!deadlockPath) throw new Error('No Deadlock path configured');
return runExclusiveModMutation(async () => {
const target = (await scanMods(deadlockPath)).find((mod) => mod.metaKey === metaKey);
const metadata = target && getModMetadata(target.metaKey);
assertReplaceableLocalVpk(target, metadata);
return {
metaKey: target.metaKey,
expectedSha256: metadata!.sha256!,
expectedFileSha256: await replacementFileSha256(target.path),
};
});
});

async function replaceCustomModSource(deadlockPath: string, args: ImportCustomModArgs): Promise<number> {
const requested = args.replacement!;
if (!requested.metaKey || !/^[0-9a-f]{64}$/i.test(requested.expectedSha256 ?? '') ||
!/^[0-9a-f]{64}$/i.test(requested.expectedFileSha256 ?? '')) {
throw new Error('Select the installed VPK again before replacing it');
}
if (!args.vpkPath?.toLowerCase().endsWith('.vpk') || args.localGroupId || args.localGroupBatchKey) {
throw new Error('Replacement supports one standalone VPK at a time');
}
const mods = await scanMods(deadlockPath);
const target = mods.find((mod) => mod.metaKey === requested.metaKey);
const previous = target && getModMetadata(target.metaKey);
assertReplaceableLocalVpk(target, previous);
await syncRunningGameModSnapshotFromMods(mods);
assertCanMoveLoadedGameMod(target);
const expectedSha = requested.expectedSha256.toLowerCase();
if (previous!.sha256!.toLowerCase() !== expectedSha) {
throw new Error('The installed VPK changed. Select it again before replacing it');
}
await assertReplacementFileUnchanged(target.path, requested.expectedFileSha256);
const oldMetadata = { ...previous };
let replacementMetadata: ModMetadata;
await replaceLocalVpkFile(args.vpkPath, target.path, {
validate: async (staged) => {
await validateReplacementVpk(staged);
const embedded = readEmbeddedAddonInfo(staged);
const record = readEmbeddedModinfo(staged);
if (embedded?.gamebananaId || embedded?.gamebananaFileId || record?.source?.gamebananaId ||
record?.source?.gamebananaFileId || record?.kind === 'merge' || hasLegacyGrimoireMergeMetaEntry(staged)) {
throw new Error('This VPK carries GameBanana or merged-mod identity. Import it separately');
}
const classification = classifyImportedLocalVariant(staged, undefined);
if (oldMetadata.localGroupId) {
const profile = await installedLocalVariantGroupProfile(deadlockPath, oldMetadata.localGroupId, true);
if (profile?.classification) assertCompatibleLocalVariantClassifications(profile.classification, classification);
}
replacementMetadata = {
...oldMetadata,
...(!oldMetadata.localGroupId && oldMetadata.lockerHeroSource !== 'manual' && !oldMetadata.globalType
? classification : {}),
sha256: (await resolveVpkIdentity(staged)).sha256,
abilitySounds: classifyAbilitySoundsFromVpk(staged),
imprinted: hasAnyImprint(staged),
imprintStale: false,
};
if (replacementMetadata.imprinted) {
replacementMetadata.imprintStale = classifyEmbedFreshnessAt(staged, oldMetadata.modName!, replacementMetadata) === 'stale';
}
},
beforeSwap: async () => {
await assertReplacementFileUnchanged(target.path, requested.expectedFileSha256);
// The mutation scope caches running state. Large source copies can outlive
// that snapshot, so query the process again at the actual swap boundary.
syncKnownRunningGameModSnapshot(await isDeadlockRunning(), mods);
assertCanMoveLoadedGameMod(target);
},
commit: () => {
const metadata = loadMetadata();
const profiles = loadProfiles();
const retargeted = retargetLocalReplacementProfiles(profiles, mods,
(key) => key === target.metaKey ? oldMetadata : metadata[key], target.metaKey, replacementMetadata.sha256!);
saveMetadata({ ...metadata, [target.metaKey]: replacementMetadata });
if (retargeted.some((profile, index) => profile.mods.some((entry, j) => entry !== profiles[index].mods[j]))) {
saveProfiles(retargeted);
}
},
rollback: () => saveMetadata({ ...loadMetadata(), [target.metaKey]: oldMetadata }),
});
invalidateVpkParseCache(target.path);
await clearSoulModelCache(target.metaKey).catch((error) => console.warn('[mods] Replacement preview cleanup failed:', error));
return 1;
}

async function importCustomModSource(
deadlockPath: string,
args: ImportCustomModArgs,
thumbnailFetchTargets: AdoptedThumbnailTarget[],
requireExistingGroup = false
): Promise<number> {
if (args.replacement) return replaceCustomModSource(deadlockPath, args);
const {
vpkPath,
name,
Expand Down
43 changes: 43 additions & 0 deletions electron/main/services/localReplacementProfiles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest';
import type { Mod } from '../../../src/types/mod';
import type { Profile, ProfileMod } from '../../../src/types/electron';
import { retargetLocalReplacementProfiles } from './localReplacementProfiles';

const oldSha = 'a'.repeat(64);
const newSha = 'b'.repeat(64);
const mod = (fileName: string, sha256 = oldSha): Mod => ({
id: fileName, metaKey: fileName, fileName, path: `/mods/${fileName}`, name: 'Local mod',
enabled: true, priority: 1, size: 10, installedAt: '', sha256,
});
const entry = (fileName: string, sha256: string | undefined = oldSha): ProfileMod => ({ fileName, sha256, enabled: true, priority: 1 });
const profile = (mods: ProfileMod[]): Profile => ({ id: 'p', name: 'Profile', mods, createdAt: '', updatedAt: '' });

describe('profile ownership during local replacement', () => {
it('retargets a local mod after its slot changed without mutating the saved input', () => {
const target = mod('pak02_dir.vpk');
const saved = [profile([entry('pak01_dir.vpk')])];
const updated = retargetLocalReplacementProfiles(saved, [target], () => target, target.metaKey, newSha);
expect(updated[0].mods[0].sha256).toBe(newSha);
expect(saved[0].mods[0].sha256).toBe(oldSha);
});
it('preserves an identical twin and updates only the resolved target', () => {
const target = mod('pak01_dir.vpk');
const twin = mod('pak02_dir.vpk');
const mods = [target, twin];
const updated = retargetLocalReplacementProfiles([profile([entry(twin.fileName), entry(target.fileName)])],
mods, (key) => mods.find((m) => m.metaKey === key), target.metaKey, newSha);
expect(updated[0].mods.map((m) => m.sha256)).toEqual([oldSha, newSha]);
});
it('does not retarget a different local mod that reused a saved filename', () => {
const target = mod('pak01_dir.vpk', 'c'.repeat(64));
const saved = [profile([entry(target.fileName)])];
const updated = retargetLocalReplacementProfiles(saved, [target], () => target, target.metaKey, newSha);
expect(updated[0].mods[0].sha256).toBe(oldSha);
});
it('upgrades a legacy filename-only profile that resolves to the target', () => {
const target = mod('pak01_dir.vpk');
const updated = retargetLocalReplacementProfiles([profile([{ fileName: target.fileName, enabled: false, priority: 5 }])],
[target], () => target, target.metaKey, newSha);
expect(updated[0].mods[0]).toMatchObject({ sha256: newSha, enabled: false, priority: 5 });
});
});
18 changes: 18 additions & 0 deletions electron/main/services/localReplacementProfiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Profile } from '../../../src/types/electron';
import type { Mod } from '../../../src/types/mod';
import { buildProfileModResolver, type MetaLookup } from './profileResolver';

/** Follow the profile resolver's pre-replacement ownership, including identical twins. */
export function retargetLocalReplacementProfiles(
profiles: Profile[], mods: Mod[], getMetadata: MetaLookup, targetMetaKey: string, newSha: string,
): Profile[] {
return profiles.map((profile) => {
const resolve = buildProfileModResolver(mods, getMetadata);
return {
...profile,
mods: profile.mods.map((entry) => resolve(entry).mod?.metaKey === targetMetaKey
? { ...entry, sha256: newSha }
: entry),
};
});
}
130 changes: 130 additions & 0 deletions electron/main/services/localVpkReplacement.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { promises as fs } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { replaceLocalVpkFile, validateReplacementVpk, replacementFileSha256, assertReplacementFileUnchanged } from './localVpkReplacement';

const directories: string[] = [];
async function fixture() {
const directory = await fs.mkdtemp(join(tmpdir(), 'grimoire-replacement-test-'));
directories.push(directory);
const source = join(directory, 'new.vpk');
const destination = join(directory, 'pak01_dir.vpk');
await fs.writeFile(source, vpk());
await fs.writeFile(destination, 'original');
return { directory, source, destination };
}

function vpk(options: { version?: number; archive?: number; length?: number; terminator?: number; payload?: string; name?: string } = {}) {
const payload = Buffer.from(options.payload ?? 'new');
const entry = Buffer.alloc(18);
entry.writeUInt16LE(options.archive ?? 0x7fff, 6);
entry.writeUInt32LE(options.length ?? payload.length, 12);
entry.writeUInt16LE(options.terminator ?? 0xffff, 16);
const tree = Buffer.concat([Buffer.from(`txt\0 \0${options.name ?? 'asset'}\0`), entry, Buffer.from([0, 0, 0])]);
const version = options.version ?? 2;
const header = Buffer.alloc(version === 2 ? 28 : 12);
header.writeUInt32LE(0x55aa1234);
header.writeUInt32LE(version, 4);
header.writeUInt32LE(tree.length, 8);
if (version === 2) header.writeUInt32LE(payload.length, 12);
return Buffer.concat([header, tree, payload]);
}

afterEach(async () => {
await Promise.all(directories.splice(0).map((directory) => fs.rm(directory, { recursive: true, force: true })));
});

describe('standalone replacement validation', () => {
it.each([1, 2])('accepts a complete inline v%s VPK', async (version) => {
const { source } = await fixture();
await fs.writeFile(source, vpk({ version }));
await expect(validateReplacementVpk(source)).resolves.toBeUndefined();
});
it.each([
['unsupported version', vpk({ version: 9 })],
['external chunks', vpk({ archive: 0 })],
['missing payload', vpk({ length: 100 })],
['invalid entry terminator', vpk({ terminator: 0 })],
['truncated file', vpk().subarray(0, 42)],
['HTML response', Buffer.from('<html>not a VPK</html>')],
])('rejects %s', async (_name, bytes) => {
const { source } = await fixture();
await fs.writeFile(source, bytes);
await expect(validateReplacementVpk(source)).rejects.toThrow();
});
});

describe('replacement transaction', () => {
it('detects changed physical bytes even when the embedded original hash is unchanged', async () => {
const { destination } = await fixture();
const originalHash = 'a'.repeat(64);
const payload = `AddonInfo { "originalSha256" "${originalHash}" "note" "old" }`;
await fs.writeFile(destination, vpk({ name: 'addoninfo', payload }));
const reviewedHash = await replacementFileSha256(destination);
await fs.writeFile(destination, vpk({ name: 'addoninfo', payload: payload.replace('old', 'new') }));
await expect(assertReplacementFileUnchanged(destination, reviewedHash)).rejects.toThrow('changed');
});
it('rechecks game state after source preparation and leaves the original in place', async () => {
const { source, destination } = await fixture();
let gameRunning = false;
const commit = vi.fn();
const rollback = vi.fn();
await expect(replaceLocalVpkFile(source, destination, {
validate: async (staged) => { await validateReplacementVpk(staged); gameRunning = true; },
beforeSwap: async () => { if (gameRunning) throw new Error('Game is running'); },
commit,
rollback,
})).rejects.toThrow('Game is running');
expect(await fs.readFile(destination, 'utf8')).toBe('original');
expect(commit).not.toHaveBeenCalled();
expect(rollback).not.toHaveBeenCalled();
});
it('rechecks reviewed bytes after staging instead of overwriting an externally changed target', async () => {
const { source, destination } = await fixture();
const reviewedHash = await replacementFileSha256(destination);
await expect(replaceLocalVpkFile(source, destination, {
validate: async (staged) => { await validateReplacementVpk(staged); await fs.writeFile(destination, 'external edit'); },
beforeSwap: () => assertReplacementFileUnchanged(destination, reviewedHash),
commit: vi.fn(), rollback: vi.fn(),
})).rejects.toThrow('changed');
expect(await fs.readFile(destination, 'utf8')).toBe('external edit');
});
it('commits one VPK in the existing slot and cleans staging files', async () => {
const { source, destination, directory } = await fixture();
const commit = vi.fn();
const rollback = vi.fn();
await replaceLocalVpkFile(source, destination, { validate: validateReplacementVpk, commit, rollback });
expect(await fs.readFile(destination)).toEqual(vpk());
expect(commit).toHaveBeenCalledOnce();
expect(rollback).not.toHaveBeenCalled();
expect((await fs.readdir(directory)).sort()).toEqual(['new.vpk', 'pak01_dir.vpk']);
});
it('restores old bytes and metadata when profile or metadata commit fails', async () => {
const { source, destination } = await fixture();
let metadata = 'old';
await expect(replaceLocalVpkFile(source, destination, {
validate: validateReplacementVpk,
commit: () => { metadata = 'new'; throw new Error('profile save denied'); },
rollback: () => { metadata = 'old'; },
})).rejects.toThrow('profile save denied');
expect(await fs.readFile(destination, 'utf8')).toBe('original');
expect(metadata).toBe('old');
});
it('never touches the original when validation or source copy fails', async () => {
const { source, destination } = await fixture();
const commit = vi.fn();
const rollback = vi.fn();
await fs.writeFile(source, 'invalid');
await expect(replaceLocalVpkFile(source, destination, { validate: validateReplacementVpk, commit, rollback })).rejects.toThrow();
await expect(replaceLocalVpkFile(`${source}.missing`, destination, { validate: validateReplacementVpk, commit, rollback })).rejects.toThrow();
expect(await fs.readFile(destination, 'utf8')).toBe('original');
expect(commit).not.toHaveBeenCalled();
expect(rollback).not.toHaveBeenCalled();
});
it('can replace from the same source path because staging precedes the swap', async () => {
const { source } = await fixture();
await replaceLocalVpkFile(source, source, { validate: validateReplacementVpk, commit: () => {}, rollback: () => {} });
expect(await fs.readFile(source)).toEqual(vpk());
});
});
Loading