Skip to content
Merged
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
15 changes: 8 additions & 7 deletions src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -672,24 +672,25 @@ declare global {
/** SAVE_CONFIG's verdict. `ok: false` means nothing was written to disk. */
type SaveConfigResult = { ok: true } | { ok: false; reason: SaveConfigFailureReason; refusedPaths?: string[] }

type ConfigRecoveryUnreadableCause = "invalid-json" | "not-an-object"

/**
* What `getConfig` found on the read that mattered, pulled once by the renderer through
* GET_CONFIG_RECOVERY_NOTICE (#554). Three shapes:
*
* - `kind: "unreadable"`: `config.json` parsed to bad JSON, or to valid JSON that is not an
* object. `restored` says whether a pre-migration backup was usable, or the launcher fell back
* to defaults. `preserved`/`copyName` say whether a copy of the unreadable file could be kept
* aside: when it could not, `getConfig` runs the recovered config in memory only, for this
* session, and never wrote it over the original file, so `copyName` is null and there is
* nothing to point the player at.
* object. `cause` distinguishes invalid JSON from valid JSON with an unexpected top-level
* value, so the notice can describe what happened accurately. `restored` says whether a
* pre-migration backup was usable, or the launcher fell back to defaults. `preserved`/`copyName`
* say whether a copy of the unreadable file could be kept aside: when it could not, `getConfig`
* runs the recovered config in memory only, for this session, and never wrote it over the
* original file, so `copyName` is null and there is nothing to point the player at.
* - `kind: "read-failed"`: the file itself could not even be opened (permissions, a Windows
* sharing lock). Nothing says the document inside is corrupt, so there is nothing to preserve
* and no copy name to give: this session simply runs on defaults, in memory only.
* - `kind: "import-failed"`: the first-run copy of VS Launcher's data failed (#708). The launcher
* started on an empty profile and leaves a marker so the next start tries the import again.
*/
type ConfigRecoveryUnreadableCause = "invalid-json" | "not-an-object"

type ConfigRecoveryNotice =
| { kind: "unreadable"; restored: boolean; preserved: boolean; copyName: string | null; cause: ConfigRecoveryUnreadableCause }
| { kind: "read-failed" }
Expand Down
2 changes: 2 additions & 0 deletions src/ipc/handlers/modConfigs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,8 @@ ipcMain.handle(IPC_CHANNELS.MODS_MANAGER.APPLY_MOD_CONFIGS, async (event, instal
}
if (refused.has(entry.key)) return
try {
// Copying and verifying the recovery file can take long enough for the folder to become a
// link. Recheck before the config write, and remove the copy if its path changed meanwhile.
await assertManagedPath(dirname(entry.destination), "mod config folder", { allowMissing: true })
} catch (error) {
await fse.remove(backupPath)
Expand Down
3 changes: 2 additions & 1 deletion src/ipc/handlers/worldsHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ async function removeWorldBackupArchive(archivePath: string, expectedBackupId: s
if (!stat.isFile() || stat.isSymbolicLink()) return false
await fse.remove(safePath)
return !(await fse.pathExists(safePath))
} catch {
} catch (error) {
logMessage("debug", `${LOG_PREFIX} [WORLD BACKUP] ${getErrorMessage(error)}`)
return false
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/src/locales/fr-FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -1018,8 +1018,8 @@
"configUnreadableReset": "Votre fichier de réglages n'a pas pu être lu. Une copie a été conservée sous le nom {{copyName}}, mais aucun réglage antérieur n'a pu être restauré : les valeurs par défaut sont utilisées. Pour récupérer ce qu'il contenait, fermez RiftLauncher, corrigez le JSON dans {{copyName}}, puis renommez-le en config.json.",
"configUnreadableRestoredUnsaved": "Votre fichier de réglages n'a pas pu être lu, et aucune copie n'a pu en être conservée. Cette session tourne avec les réglages d'avant la dernière mise à jour ayant changé le format des réglages, et rien ne sera enregistré durant cette session.",
"configUnreadableResetUnsaved": "Votre fichier de réglages n'a pas pu être lu, et aucune copie n'a pu en être conservée. Cette session tourne avec les réglages par défaut, et rien ne sera enregistré durant cette session.",
"configNotAnObjectRestored": "Votre fichier ne contenait aucun réglage. Une copie a été conservée sous le nom {{copyName}} et les réglages d’avant la dernière mise à jour qui a modifié leur format ont été restaurés.",
"configNotAnObjectReset": "Votre fichier ne contenait aucun réglage. Une copie a été conservée sous le nom {{copyName}} et les réglages par défaut sont utilisés.",
"configNotAnObjectRestored": "Votre fichier de réglages ne contenait aucun réglage. Une copie a été conservée sous le nom {{copyName}}, et les réglages d'avant la dernière mise à jour ayant changé le format des réglages ont été restaurés.",
"configNotAnObjectReset": "Votre fichier de réglages ne contenait aucun réglage. Une copie a été conservée sous le nom {{copyName}}, et les valeurs par défaut sont utilisées.",
"userDataImportFailed": "Vos données de VS Launcher n'ont pas pu être importées : RiftLauncher a démarré avec un profil vide. L'import sera retenté au prochain démarrage, tant que vous ne modifiez rien dans RiftLauncher d'ici là. Les données de VS Launcher n'ont pas été modifiées.",
"missingFields": "Remplissez tous les champs avant d'enregistrer.",
"compressed": "Compression terminée : {{compressName}}.",
Expand Down
92 changes: 92 additions & 0 deletions tests/ipc/modConfigs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1363,6 +1363,98 @@ describe("APPLY_MOD_CONFIGS", () => {
}
})

it("rechecks a folder swapped during config reading before keeping a recovery copy (#626)", async () => {
writeConfig()
const outside = join(temporaryRoot, "outside")
mkdirSync(outside, { recursive: true })
writeFileSync(join(outside, "target.json"), "theirs-secret", "utf-8")

mkdirSync(join(modConfigFolder(), "swapped"), { recursive: true })
writeFileSync(join(modConfigFolder(), "legit.json"), '{"legit":1}', "utf-8")
const swappedConfig = join(modConfigFolder(), "swapped", "target.json")
writeFileSync(swappedConfig, '{"target":1}', "utf-8")

const event = await createTrustedEvent()
const fse = (await import("fs-extra")).default
const originalReadFile = fse.readFile.bind(fse)
let swapped = false
const readFile = vi.spyOn(fse, "readFile").mockImplementation((async (target: unknown, ...rest: unknown[]) => {
if (!swapped && String(target) === swappedConfig) {
swapped = true
rmSync(join(modConfigFolder(), "swapped"), { recursive: true, force: true })
symlinkSync(outside, join(modConfigFolder(), "swapped"))
}
return (originalReadFile as (...args: unknown[]) => Promise<unknown>)(target, ...rest)
}) as never)
const copy = vi.spyOn(fse, "copy")

try {
const applied = await applyModConfigsHandler()(event, installationPath, [
{ name: "legit.json", ...entry('{"legit":2}') },
{ name: "swapped/target.json", ...entry('{"target":2}') }
])

assert.equal(applied.ok, true)
if (applied.ok !== true) return
assert.deepEqual(applied.failed, [{ name: "swapped/target.json", reason: "write-failed" }])
assert.deepEqual(applied.applied, [{ name: "legit.json", kind: "replace" }])
assert.notEqual(applied.backupFolder, "")
assert.equal(existsSync(join(applied.backupFolder, "swapped", "target.json")), false)
assert.equal(
copy.mock.calls.some(([from]) => String(from) === swappedConfig),
false
)
assert.equal(readFileSync(join(outside, "target.json"), "utf-8"), "theirs-secret")
} finally {
readFile.mockRestore()
copy.mockRestore()
}
})

it("rechecks a folder swapped during the recovery copy before keeping that copy (#626)", async () => {
writeConfig()
const outside = join(temporaryRoot, "outside")
mkdirSync(outside, { recursive: true })
writeFileSync(join(outside, "target.json"), "theirs-secret", "utf-8")

mkdirSync(join(modConfigFolder(), "swapped"), { recursive: true })
writeFileSync(join(modConfigFolder(), "legit.json"), '{"legit":1}', "utf-8")
const swappedConfig = join(modConfigFolder(), "swapped", "target.json")
writeFileSync(swappedConfig, '{"target":1}', "utf-8")

const event = await createTrustedEvent()
const fse = (await import("fs-extra")).default
const originalCopy = fse.copy.bind(fse)
let swapped = false
const copy = vi.spyOn(fse, "copy").mockImplementation(async (from, to, options) => {
await originalCopy(from, to, options)
if (!swapped && String(from) === swappedConfig) {
swapped = true
rmSync(join(modConfigFolder(), "swapped"), { recursive: true, force: true })
symlinkSync(outside, join(modConfigFolder(), "swapped"))
}
})

try {
const applied = await applyModConfigsHandler()(event, installationPath, [
{ name: "legit.json", ...entry('{"legit":2}') },
{ name: "swapped/target.json", ...entry('{"target":2}') }
])

assert.equal(applied.ok, true)
if (applied.ok !== true) return
assert.equal(swapped, true, "the destination folder changes only after its backup copy lands")
assert.deepEqual(applied.failed, [{ name: "swapped/target.json", reason: "write-failed" }])
assert.deepEqual(applied.applied, [{ name: "legit.json", kind: "replace" }])
assert.notEqual(applied.backupFolder, "")
assert.equal(existsSync(join(applied.backupFolder, "legit.json")), true)
assert.equal(existsSync(join(applied.backupFolder, "swapped", "target.json")), false)
assert.equal(readFileSync(join(outside, "target.json"), "utf-8"), "theirs-secret")
} finally {
copy.mockRestore()
}
})

it("refuses a linked destination file at lstat without reading, copying or writing through it", async () => {
writeConfig()
const outside = join(temporaryRoot, "outside")
Expand Down
51 changes: 43 additions & 8 deletions tests/ipc/worldsHandlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -892,9 +892,38 @@ describe("worlds IPC handlers", () => {
assert.deepEqual(resultMismatch, { ok: false, reason: "operation-failed" })
expect(existsSync(mismatchArchive)).toBe(true)

const resultInst = await handler("worlds-delete-backup")(event, "install-a", "inst-worlds-id")
assert.deepEqual(resultInst, { ok: false, reason: "operation-failed" })
expect(existsSync(instArchive)).toBe(true)
const logSpy = vi.spyOn(await import("@src/utils/logManager"), "logMessage")
try {
const resultInst = await handler("worlds-delete-backup")(event, "install-a", "inst-worlds-id")
assert.deepEqual(resultInst, { ok: false, reason: "operation-failed" })
expect(existsSync(instArchive)).toBe(true)
expect(logSpy).toHaveBeenCalledWith("warn", expect.stringContaining("[DELETE BACKUP] Could not remove world backup inst-worlds-id."))
} finally {
logSpy.mockRestore()
}
})

it("logs the reason a world backup archive could not be removed", async () => {
const sourcePath = join(installationsRoot, "install-a")
mkdirSync(join(sourcePath, "Saves"), { recursive: true })
writeFileSync(join(sourcePath, "Saves", "World.vcdbs"), "live-world", "utf8")

const backupId = "80000000-0000-4000-8000-000000000008"
const archivePath = join(backupsFolder, "Worlds", `${backupId}.tar.gz`)
mkdirSync(join(backupsFolder, "Worlds"), { recursive: true })
writeFileSync(archivePath, "archive", "utf8")
writeConfig([installation("install-a", sourcePath, "1.22.7", [{ id: backupId, date: 1, path: archivePath, worldName: "World.vcdbs" }])])
const event = await createTrustedEvent()
const logSpy = vi.spyOn(await import("@src/utils/logManager"), "logMessage")

assertManagedDeletionPathSpy.mockRejectedValueOnce(new Error("EACCES permission denied"))
try {
const result = await handler("worlds-delete-backup")(event, "install-a", backupId)
assert.deepEqual(result, { ok: false, reason: "operation-failed" })
expect(logSpy).toHaveBeenCalledWith("debug", expect.stringContaining("EACCES permission denied"))
} finally {
logSpy.mockRestore()
}
})

it("refuses to delete another world's archive when pruning older backups (#620)", async () => {
Expand All @@ -916,12 +945,18 @@ describe("worlds IPC handlers", () => {
writeConfig([inst])

const event = await createTrustedEvent()
const result = (await handler("worlds-backup")(event, "install-a", "World.vcdbs")) as WorldBackupResult
assert.equal(result.ok, true)
if (!result.ok) return
const logSpy = vi.spyOn(await import("@src/utils/logManager"), "logMessage")
try {
const result = (await handler("worlds-backup")(event, "install-a", "World.vcdbs")) as WorldBackupResult
assert.equal(result.ok, true)
if (!result.ok) return

expect(existsSync(otherWorldArchive)).toBe(true)
expect(result.deletedBackupIds).toEqual([])
expect(existsSync(otherWorldArchive)).toBe(true)
expect(result.deletedBackupIds).toEqual([])
expect(logSpy).toHaveBeenCalledWith("warn", expect.stringContaining(`[BACKUP] Could not prune world backup ${idPruned}.`))
} finally {
logSpy.mockRestore()
}
})

it("refuses to make a world backup when backupsLimit is 0", async () => {
Expand Down
33 changes: 33 additions & 0 deletions tests/renderer-dom/configRecoveryNotice.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,39 @@ describe("config not-an-object notice (#625)", () => {
expect(seen[0]?.body).toContain("A copy was kept as config.unreadable-1727690000000.json")
expect(getConfigRecoveryNotice).toHaveBeenCalledTimes(1)
})

it("does not name a preserved copy when an unreadable config could not be saved", async () => {
vi.resetModules()
const { NotificationsProvider: FreshProvider, useNotificationsContext: useFreshNotifications } = await import("@renderer/contexts/NotificationsContext")
let seen: NotificationType[] = []
function Probe(): null {
seen = useFreshNotifications().notifications
return null
}
const getConfigRecoveryNotice = vi.fn(
async () =>
({
kind: "unreadable",
cause: "not-an-object",
restored: true,
preserved: false,
copyName: null
}) as ConfigRecoveryNotice
)
installMockWindowApi({ configManager: { getConfigRecoveryNotice } })

render(
<FreshProvider>
<Probe />
</FreshProvider>
)

await waitFor(() => expect(seen).toHaveLength(1))
expect(seen[0]?.type).toBe("warning")
expect(seen[0]?.body).toContain("a copy of it could not be kept")
expect(seen[0]?.body).not.toContain("{{copyName}}")
expect(getConfigRecoveryNotice).toHaveBeenCalledTimes(1)
})
})

describe("failed VS Launcher import notice (#708)", () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/renderer-dom/manageMods.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2532,7 +2532,7 @@ describe("startup update notices on Manage Mods (#752)", () => {
if (scenario === "all" || scenario === "row") {
await waitFor(() => expect(screen.queryByText(notice)).toBeNull())
} else {
expect(screen.getByText(notice)).toBeTruthy()
await expect(waitFor(() => expect(screen.queryByText(notice)).toBeNull(), { timeout: 1_500 })).rejects.toThrow()
}
expect(downloadOnPath).toHaveBeenCalledTimes(scenario === "all" ? 2 : scenario === "offline" ? 0 : 1)
},
Expand Down
Loading