From 32448bd6f6f20a18bf96217160da7f3facce6153 Mon Sep 17 00:00:00 2001 From: "Nick T." <73005126+nick701@users.noreply.github.com> Date: Thu, 10 Sep 2026 11:17:12 -0400 Subject: [PATCH] fix(import): read Raycast 2.x (RAYCFG3) backups Raycast 2.x changed both halves of the export and the importer only knew the 1.x versions of each, so every 2.x `.rayconfig` failed and the failure surfaced as "Password was not valid" no matter what the user typed. The container is now `RAYCFG3\n` + UInt32LE header length + gzipped header JSON + AES-256-GCM ciphertext + a 16-byte tag, keyed by scrypt over the password and the header's salt. The old path fed the whole file to OpenSSL as salt-less AES-256-CBC, which cannot decrypt it. The payload is also category-keyed (`settings`, `quicklinks`, `notes`, ...) instead of the 1.x `builtin_package_*` keys, so even a successful decrypt would have found nothing to import. `raycast-v2-backup.ts` decrypts the container and maps the payload back onto the 1.x shape, leaving every existing importer, preview and count untouched. Detection is by container signature, so 1.x encrypted backups and plain JSON exports still take exactly the path they took before. Mapped: global hotkey, window mode, pop-to-root timeout, navigation bindings, quicklinks, notes, snippets, store extensions with their per-command enabled state and preference values, command hotkeys and aliases, and AI chats (whose messages 2.x stores in a sibling array and which are rejoined by chat id). Clipboard history and MCP servers are carried as counts only so the preview keeps reporting them unsupported. Command ids are emitted only for the kinds SuperCmd can actually resolve: store extension commands by extension name, applications by path, and built-ins through an explicit id map. Quicklink, Apple Shortcut and AI-tool entries are skipped rather than guessed at, because SuperCmd mints its own ids for those and a near-miss would bind a hotkey to the wrong command. OAuth tokens and BYOK API keys are never read. Aliases are taken verbatim from 2.x's explicit `alias` field instead of the heuristic that has to guess one out of 1.x's `searchTerms`; that heuristic discards anything under three characters and would have dropped real two-character aliases. Claude-Session: https://claude.ai/code/session_01VfHuFnP7ZZ1AYqRHURZPEo --- scripts/test-raycast-v2-import.mjs | 282 +++++++++++++++++ src/main/raycast-config-import.ts | 47 ++- src/main/raycast-v2-backup.ts | 488 +++++++++++++++++++++++++++++ 3 files changed, 812 insertions(+), 5 deletions(-) create mode 100644 scripts/test-raycast-v2-import.mjs create mode 100644 src/main/raycast-v2-backup.ts diff --git a/scripts/test-raycast-v2-import.mjs b/scripts/test-raycast-v2-import.mjs new file mode 100644 index 00000000..6d26f235 --- /dev/null +++ b/scripts/test-raycast-v2-import.mjs @@ -0,0 +1,282 @@ +#!/usr/bin/env node + +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { fileURLToPath } from 'node:url'; +import { build } from 'esbuild'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const modulePath = path.join(root, 'src/main/raycast-v2-backup.ts'); + +async function importModule() { + const result = await build({ + entryPoints: [modulePath], + bundle: true, + write: false, + format: 'esm', + platform: 'node', + target: 'node20', + logLevel: 'silent', + }); + const code = result.outputFiles[0].text; + return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +} + +const PASSWORD = 'correct horse battery staple'; +const SCRYPT_OPTIONS = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }; + +/** Builds a RAYCFG3 container the same way Raycast 2.x does. */ +function buildContainer(payload, { password = PASSWORD, appVersion = '2.3.0.0', schemaVersion = 3 } = {}) { + const salt = crypto.randomBytes(16); + const iv = crypto.randomBytes(16); + const header = zlib.gzipSync( + Buffer.from( + JSON.stringify({ appVersion, schemaVersion, encryption: { iv: iv.toString('hex'), salt: salt.toString('hex') } }) + ) + ); + const key = crypto.scryptSync(password, salt, 32, SCRYPT_OPTIONS); + const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); + const body = Buffer.concat([ + cipher.update(zlib.gzipSync(Buffer.from(JSON.stringify(payload)))), + cipher.final(), + ]); + const headerLength = Buffer.alloc(4); + headerLength.writeUInt32LE(header.length); + return Buffer.concat([Buffer.from('RAYCFG3\n'), headerLength, header, body, cipher.getAuthTag()]); +} + +const EXTENSION_UUID = '10749020-4fc4-4e10-9666-ee6da3088c2d'; + +/** Mirrors the category layout of a real Raycast 2.3 export, trimmed to one of each. */ +const PAYLOAD = { + settings: { + general: { + windowMode: 'compact', + navigationBindings: 'emacs', + popToRootTimeout: 90, + globalHotkey: { + kind: { + type: 'SingleStep', + shortcut: { modifiers: [{ modifier: 'Meta' }], key: { type: 'LayoutIndependent', code: 49 } }, + }, + locality: 'Global', + }, + }, + commands: [ + { + id: `c:n:${EXTENSION_UUID}::-::search`, + extensionId: `e:n:${EXTENSION_UUID}`, + enabled: true, + alias: 'ss', + }, + { id: `c:n:${EXTENSION_UUID}::-::move`, extensionId: `e:n:${EXTENSION_UUID}`, enabled: false }, + // AI pseudo-command: no SuperCmd counterpart, must not be emitted. + { id: `c:n:${EXTENSION_UUID}::-::__ai_extension`, enabled: false, alias: 'nope' }, + { + id: 'c:r:clipboard-history::-::history', + enabled: true, + macosHotkey: { + kind: { + type: 'SingleStep', + shortcut: { + modifiers: [{ modifier: 'Shift' }, { modifier: 'Ctrl' }, { modifier: 'Alt' }, { modifier: 'Meta' }], + key: { type: 'LayoutIndependent', code: 45 }, + }, + }, + locality: 'Global', + }, + }, + { id: 'c:r:system::-::lockScreen', enabled: true, alias: 'lock screen ' }, + { + id: 'c:r:applications::*::application::=::/System/Library/CoreServices/Finder.app', + enabled: true, + alias: 'finder', + }, + // Quicklink aliases cannot resolve: SuperCmd mints its own quicklink ids. + { id: 'c:r:quicklinks::*::quicklink::=::01KS27AC0ZVR3N3V4BNDH7DZVV', enabled: true, alias: 'google' }, + ], + nodeExtensions: [ + { + id: `e:n:${EXTENSION_UUID}`, + enabled: true, + meta: { maxResults: '25', openFolderAfterMove: true }, + preferenceTypes: [ + { name: 'maxResults', type: 'textfield' }, + { name: 'openFolderAfterMove', type: 'checkbox' }, + { name: 'neverSet', type: 'checkbox' }, + ], + oauthTokens: [{ accessToken: 'must-never-be-imported' }], + }, + ], + internalExtensions: [{ id: 'e:r:ai', enabled: true, meta: { aiByokApiKeys: 'must-never-be-imported' } }], + }, + nodeExtensions: { + extensions: [{ uuid: EXTENSION_UUID, name: 'folder-search', author: 'GastroGeek', version: 'Sat Aug 29 2026' }], + }, + quicklinks: { quicklinks: [{ id: '01KS', name: 'Google', link: 'https://google.com/search?q={Query}' }] }, + notes: { notes: [{ id: 'n1', title: 'Standup', text: 'Ship the importer.' }] }, + snippets: { snippets: [{ name: 'Sig', text: 'Best,\nNick', keyword: ';sig' }] }, + ai: { + chats: [ + { id: 'chat-1', title: 'Rename a branch', modelId: 'openai-gpt-4o-mini', createdAt: '2026-01-14T08:54:19.489Z' }, + { id: 'chat-empty', title: 'Nothing here', modelId: 'openai-gpt-4o-mini' }, + ], + messages: [ + { id: 'm1', chatId: 'chat-1', role: 'user', content: { type: 'text', text: 'How do I rename a branch?' } }, + { id: 'm2', chatId: 'chat-1', role: 'tool', content: { name: 'web', result: 'ignored' } }, + { id: 'm3', chatId: 'chat-1', role: 'assistant', content: { type: 'text', text: 'Use git branch -m.' } }, + ], + }, + clipboardHistory: { clipboardEntries: [{ title: 'a' }, { title: 'b' }] }, + mcpServers: { servers: [{ name: 'local' }] }, +}; + +const CONTAINER = buildContainer(PAYLOAD); + +test('recognises the RAYCFG3 container and nothing else', async () => { + const { isRaycastV2Backup } = await importModule(); + assert.equal(isRaycastV2Backup(CONTAINER), true); + assert.equal(isRaycastV2Backup(Buffer.from('{"raycast_version":"1.0"}')), false); + assert.equal(isRaycastV2Backup(Buffer.alloc(0)), false); +}); + +test('decrypts with the right password and reports the app version', async () => { + const { decryptRaycastV2Backup } = await importModule(); + const { appVersion, payload } = decryptRaycastV2Backup(CONTAINER, PASSWORD); + assert.equal(appVersion, '2.3.0.0'); + assert.equal(payload.settings.general.popToRootTimeout, 90); +}); + +test('a wrong password raises the exact message the retry prompt looks for', async () => { + const { decryptRaycastV2Backup, INVALID_PASSWORD_MESSAGE } = await importModule(); + assert.equal(INVALID_PASSWORD_MESSAGE, 'Failed to read import data; password is not valid.'); + assert.throws(() => decryptRaycastV2Backup(CONTAINER, 'wrong'), (error) => { + assert.equal(error.message, INVALID_PASSWORD_MESSAGE); + return true; + }); +}); + +test('a malformed container is reported as malformed, not as a bad password', async () => { + const { decryptRaycastV2Backup, INVALID_PASSWORD_MESSAGE } = await importModule(); + const truncated = CONTAINER.subarray(0, 40); + assert.throws(() => decryptRaycastV2Backup(truncated, PASSWORD), (error) => { + assert.notEqual(error.message, INVALID_PASSWORD_MESSAGE); + return true; + }); + + const wrongLength = Buffer.from(CONTAINER); + wrongLength.writeUInt32LE(0xfffffff, 8); + assert.throws(() => decryptRaycastV2Backup(wrongLength, PASSWORD), (error) => { + assert.notEqual(error.message, INVALID_PASSWORD_MESSAGE); + return true; + }); +}); + +test('an unsupported container version says so', async () => { + const { decryptRaycastV2Backup } = await importModule(); + const future = buildContainer(PAYLOAD, { schemaVersion: 4 }); + assert.throws(() => decryptRaycastV2Backup(future, PASSWORD), /container version 4/); +}); + +test('structured hotkeys become the 1.x keycode string', async () => { + const { encodeLegacyHotkey } = await importModule(); + const hotkey = (modifiers, code) => ({ + kind: { type: 'SingleStep', shortcut: { modifiers, key: { type: 'LayoutIndependent', code } } }, + }); + assert.equal(encodeLegacyHotkey(hotkey([{ modifier: 'Meta' }], 49)), 'command-49'); + assert.equal( + encodeLegacyHotkey(hotkey([{ modifier: 'Shift' }, { modifier: 'Ctrl' }, { modifier: 'Alt' }, { modifier: 'Meta' }], 45)), + 'command-control-option-shift-45' + ); + assert.equal(encodeLegacyHotkey(null), null); + assert.equal(encodeLegacyHotkey({ kind: { type: 'TwoStep' } }), null); +}); + +test('maps the 2.x payload onto the shape the 1.x importer reads', async () => { + const { loadRaycastV2Backup } = await importModule(); + const backup = loadRaycastV2Backup(CONTAINER, PASSWORD); + + assert.equal(backup.raycast_version, '2.3.0.0'); + + const preferences = backup.builtin_package_raycastPreferences; + assert.equal(preferences.preferencesGeneral.raycastGlobalHotkey, 'command-49'); + assert.equal(preferences.preferencesAppearance.raycastPreferredWindowMode, 'compact'); + assert.equal(preferences.preferencesAdvanced.popToRootTimeout, 90); + assert.equal(preferences.preferencesAdvanced.navigationCommandStyleIdentifierKey, 'emacs'); + + assert.deepEqual(backup.builtin_package_quicklinks.quicklinks, [ + { uuid: '01KS', name: 'Google', url: 'https://google.com/search?q={Query}', isEnabled: true }, + ]); + assert.deepEqual(backup.builtin_package_raycastNotes.notes, [{ title: 'Standup', text: 'Ship the importer.' }]); + assert.deepEqual(backup.builtin_package_snippets.snippets, [{ name: 'Sig', text: 'Best,\nNick', keyword: ';sig' }]); + + assert.equal(backup.builtin_package_clipboardHistory.clipboardHistoryRecords.length, 2); + assert.equal(backup.builtin_package_mcp.mcpServers.length, 1); +}); + +test('extension records carry identity, per-command enabled state and preference values', async () => { + const { loadRaycastV2Backup } = await importModule(); + const [extension] = loadRaycastV2Backup(CONTAINER, PASSWORD).builtin_package_raycastExtensions.extensions; + + assert.equal(extension.name, 'folder-search'); + assert.equal(extension.owner, 'GastroGeek'); + assert.deepEqual( + [...extension.commands].sort((a, b) => a.name.localeCompare(b.name)), + [{ name: 'move', enabled: false }, { name: 'search', enabled: true }] + ); + assert.deepEqual(extension.prefs, [ + { name: 'maxResults', type: 'textfield', value: '25' }, + { name: 'openFolderAfterMove', type: 'checkbox', value: true }, + ]); + + // A preference the user never set must not be invented. + assert.equal(extension.prefs.some((pref) => pref.name === 'neverSet'), false); + // OAuth tokens are credentials and never cross over. + assert.equal(JSON.stringify(extension).includes('must-never-be-imported'), false); +}); + +test('no part of the converted backup carries secrets', async () => { + const { loadRaycastV2Backup } = await importModule(); + const backup = loadRaycastV2Backup(CONTAINER, PASSWORD); + assert.equal(JSON.stringify(backup).includes('must-never-be-imported'), false); +}); + +test('root-search records are emitted only for commands SuperCmd can resolve', async () => { + const { loadRaycastV2Backup } = await importModule(); + const { rootSearch } = loadRaycastV2Backup(CONTAINER, PASSWORD).builtin_package_rootSearch; + + const byKey = new Map(rootSearch.filter((item) => item.key).map((item) => [item.key, item])); + + // Store extension command, addressed by extension name so `ext--` resolves. + assert.equal(byKey.get('extension_folder-search.search').alias, 'ss'); + // Built-in, addressed by its 2.x id and carrying the decoded hotkey. + assert.equal(byKey.get('c:r:clipboard-history::-::history').hotkey, 'command-control-option-shift-45'); + // Trailing space in a Raycast alias is presentation, not part of the alias. + assert.equal(byKey.get('c:r:system::-::lockScreen').alias, 'lock screen'); + // Applications resolve by path, not by key. + const application = rootSearch.find((item) => item.path); + assert.equal(application.path, '/System/Library/CoreServices/Finder.app'); + assert.equal(application.alias, 'finder'); + + // Kinds SuperCmd cannot address are dropped rather than guessed at. + assert.equal(rootSearch.some((item) => String(item.key || '').includes('__ai_extension')), false); + assert.equal(rootSearch.some((item) => String(item.key || '').includes('quicklink')), false); + // Commands with neither a hotkey nor an alias carry nothing worth importing. + assert.equal(rootSearch.some((item) => item.key === 'extension_folder-search.move'), false); +}); + +test('AI chats collect their own messages and drop tool turns', async () => { + const { loadRaycastV2Backup } = await importModule(); + const chats = loadRaycastV2Backup(CONTAINER, PASSWORD)['builtin_package_open-ai'].aiChats; + + // The chat with no messages is not carried over as an empty shell. + assert.equal(chats.length, 1); + assert.equal(chats[0].title, 'Rename a branch'); + assert.deepEqual( + chats[0].messages.map((message) => [message.role, message.content]), + [['user', 'How do I rename a branch?'], ['assistant', 'Use git branch -m.']] + ); +}); diff --git a/src/main/raycast-config-import.ts b/src/main/raycast-config-import.ts index 6f7ab86f..7a13aa14 100644 --- a/src/main/raycast-config-import.ts +++ b/src/main/raycast-config-import.ts @@ -10,6 +10,12 @@ import { getExtensionPreferences, setExtensionPreferences } from './extension-pr import { getInstalledExtensionNames, installExtension } from './extension-registry'; import { createNote, getAllNotes, updateNote } from './notes-store'; import { createQuickLink, getAllQuickLinks } from './quicklink-store'; +import { + INVALID_PASSWORD_MESSAGE, + RAYCAST_V2_BUILTIN_COMMAND_IDS, + isRaycastV2Backup, + loadRaycastV2Backup, +} from './raycast-v2-backup'; import { discoverScriptCommands, invalidateScriptCommandsCache } from './script-command-runner'; import { loadSettings, saveSettings, type AppSettings } from './settings-store'; import { createSnippet, getAllSnippets, updateSnippet } from './snippet-store'; @@ -66,6 +72,11 @@ type RaycastRootSearchRecord = { path?: string; hotkey?: string; searchTerms?: string; + /** + * Raycast 2.x records the alias explicitly, so it is used as-is. The 1.x + * exports only had `searchTerms`, from which an alias has to be guessed. + */ + alias?: string; }; type RaycastPinnedMenuItem = { @@ -76,7 +87,7 @@ type RaycastPinnedMenuItem = { type?: string; }; -type RaycastBackup = { +export type RaycastBackup = { raycast_version?: string; builtin_package_quicklinks?: { quicklinks?: RaycastQuicklinkRecord[]; @@ -206,6 +217,8 @@ const RAYCAST_SCRIPT_COMMAND_PREFIX = 'raycastScript_'; const importSessions = new Map(); const RAYCAST_BUILTIN_COMMAND_ID_MAP: Record = { + // Raycast 2.x ids arrive verbatim from the converter; 1.x ids follow below. + ...RAYCAST_V2_BUILTIN_COMMAND_IDS, builtin_command_clipboardHistory: 'system-clipboard-manager', builtin_command_createScriptCommand: 'system-create-script-command', builtin_command_developer_manageExtensions: 'system-open-extensions-settings', @@ -399,6 +412,13 @@ function decryptRaycastBuffer(raw: Buffer, password: string): Buffer { function loadRaycastBackupFromFile(filePath: string, password: string | null): RaycastBackup { const raw = fs.readFileSync(filePath); + // Checked before the plain-JSON probe so a 2.x file is not stringified whole. + if (isRaycastV2Backup(raw)) { + if (!password) { + throw new Error('A password is required to import this Raycast backup.'); + } + return loadRaycastV2Backup(raw, password); + } const plain = parseMaybePlainJson(raw); if (plain) return plain; if (!password) { @@ -410,7 +430,8 @@ function loadRaycastBackupFromFile(filePath: string, password: string | null): R function normalizeNavigationStyle(value: unknown): AppSettings['navigationStyle'] | null { const normalized = String(value || '').trim().toLowerCase(); - if (normalized === 'macos') return 'macos'; + // Raycast 2.x names the standard macOS bindings "emacs". + if (normalized === 'macos' || normalized === 'emacs') return 'macos'; if (normalized === 'vim') return 'vim'; return null; } @@ -486,6 +507,20 @@ function normalizeAliasCandidate(searchTerms: unknown): string | null { return null; } +/** + * Raycast 2.x records an explicit `alias`, so it is taken at face value; 1.x + * only had `searchTerms`, where the alias still has to be guessed. The guess + * ignores aliases shorter than three characters, which would throw away real + * two-character aliases when the export actually states them. + */ +function resolveRootSearchAlias(item: RaycastRootSearchRecord): string | null { + const explicit = String(item?.alias || '').trim().toLowerCase(); + if (explicit) { + return /^[a-z0-9][a-z0-9 -]*$/.test(explicit) ? explicit : null; + } + return normalizeAliasCandidate(item?.searchTerms); +} + function normalizeRaycastPath(rawPath: string): string { const trimmed = String(rawPath || '').trim(); if (!trimmed) return ''; @@ -592,7 +627,7 @@ function countPreviewStats(data: RaycastBackup): RaycastImportPreview['counts'] ), 0), scriptCommandFolders: data.builtin_package_scriptCommands?.scriptCommandsDirectories?.length || 0, commandHotkeys: rootSearchItems.filter((item) => Boolean(String(item?.hotkey || '').trim())).length, - commandAliases: rootSearchItems.filter((item) => Boolean(normalizeAliasCandidate(item?.searchTerms))).length, + commandAliases: rootSearchItems.filter((item) => Boolean(resolveRootSearchAlias(item))).length, pinnedCommands: data.builtin_package_navigation?.pinnedMenuItems?.length || 0, aiChats: data['builtin_package_open-ai']?.aiChats?.length || 0, quicklinks: data.builtin_package_quicklinks?.quicklinks?.length || 0, @@ -1057,7 +1092,9 @@ async function importCommandCustomizations( for (const item of rootSearchItems) { const hasHotkey = options.includeHotkeys && Boolean(String(item?.hotkey || '').trim()); - const hasSearchTerms = options.includeAliases && Boolean(String(item?.searchTerms || '').trim()); + const hasSearchTerms = + options.includeAliases && + Boolean(String(item?.alias || '').trim() || String(item?.searchTerms || '').trim()); if (!hasHotkey && !hasSearchTerms) continue; const commandId = resolveRaycastCommandId(item, appCommandIdByPath, scriptCommandIdByPath); @@ -1084,7 +1121,7 @@ async function importCommandCustomizations( } if (hasSearchTerms) { - const aliasCandidate = normalizeAliasCandidate(item.searchTerms); + const aliasCandidate = resolveRootSearchAlias(item); if (!aliasCandidate) continue; const existingAlias = String(nextAliases[commandId] || '').trim(); if (!existingAlias) { diff --git a/src/main/raycast-v2-backup.ts b/src/main/raycast-v2-backup.ts new file mode 100644 index 00000000..ddd93a27 --- /dev/null +++ b/src/main/raycast-v2-backup.ts @@ -0,0 +1,488 @@ +/** + * Raycast 2.x (`RAYCFG3`) backup reader. + * + * Raycast 1.x wrote a headerless, salt-less AES-256-CBC blob whose key was + * derived straight from the password, and `raycast-config-import.ts` still + * reads those. Raycast 2.x replaced both the container and the payload schema: + * + * file = "RAYCFG3\n" | UInt32LE(headerLength) | gzip(headerJSON) | ciphertext | tag(16) + * body = AES-256-GCM(gzip(payloadJSON)) + * key = scrypt(password, salt, N=16384, r=8, p=1, dkLen=32) + * + * The gzipped header carries `schemaVersion`, plus a hex `iv` and `salt` of 16 + * bytes each. There is no integrity check other than the GCM tag, so a wrong + * password surfaces as a tag mismatch. + * + * The payload is category-keyed (`settings`, `quicklinks`, `notes`, ...) rather + * than the 1.x `builtin_package_*` keys, so `convertRaycastV2Backup` maps it + * back onto the 1.x shape and every existing importer keeps working unchanged. + * + * This module deliberately imports nothing from Electron so the test harness + * can bundle it standalone. + */ +import * as crypto from 'crypto'; +import * as zlib from 'zlib'; + +import type { RaycastBackup } from './raycast-config-import'; + +const RAYCFG_MAGIC = Buffer.from('RAYCFG3\n', 'utf8'); +const FIXED_HEADER_LENGTH = 12; // magic (8 bytes) + UInt32LE header length +const MAX_HEADER_LENGTH = 1024 * 1024; +const AUTH_TAG_LENGTH = 16; +const IV_LENGTH = 16; +const SALT_LENGTH = 16; +const CONTAINER_SCHEMA_VERSION = 3; +const SCRYPT_N = 16384; +const SCRYPT_R = 8; +const SCRYPT_P = 1; +const SCRYPT_KEY_LENGTH = 32; + +/** Matched verbatim by the retry loop in `selectAndLoadRaycastBackup`. */ +export const INVALID_PASSWORD_MESSAGE = 'Failed to read import data; password is not valid.'; +const CORRUPT_CONTAINER_MESSAGE = 'This file is not a readable Raycast backup.'; + +type RaycastV2Header = { + appVersion?: string; + schemaVersion?: number; + encryption?: { iv?: string; salt?: string }; +}; + +/** True when the buffer opens with the Raycast 2.x container signature. */ +export function isRaycastV2Backup(raw: Buffer): boolean { + return raw.length >= FIXED_HEADER_LENGTH && raw.subarray(0, RAYCFG_MAGIC.length).equals(RAYCFG_MAGIC); +} + +function readHexField(value: unknown, expectedLength: number): Buffer | null { + const text = String(value || '').trim(); + if (!/^[0-9a-fA-F]+$/.test(text) || text.length !== expectedLength * 2) return null; + return Buffer.from(text, 'hex'); +} + +function readRaycastV2Header(raw: Buffer): { header: RaycastV2Header; payloadStart: number } { + const headerLength = raw.readUInt32LE(RAYCFG_MAGIC.length); + if ( + headerLength <= 0 || + headerLength > MAX_HEADER_LENGTH || + FIXED_HEADER_LENGTH + headerLength + AUTH_TAG_LENGTH > raw.length + ) { + throw new Error(CORRUPT_CONTAINER_MESSAGE); + } + let header: RaycastV2Header; + try { + header = JSON.parse( + zlib.gunzipSync(raw.subarray(FIXED_HEADER_LENGTH, FIXED_HEADER_LENGTH + headerLength)).toString('utf8') + ); + } catch { + throw new Error(CORRUPT_CONTAINER_MESSAGE); + } + if (Number(header?.schemaVersion) !== CONTAINER_SCHEMA_VERSION) { + throw new Error( + `This Raycast backup uses container version ${String(header?.schemaVersion ?? 'unknown')}, which SuperCmd cannot read yet.` + ); + } + return { header, payloadStart: FIXED_HEADER_LENGTH + headerLength }; +} + +/** + * Decrypts a `RAYCFG3` buffer. Throws `INVALID_PASSWORD_MESSAGE` when the GCM + * tag does not verify, so the caller's retry prompt fires; anything else is a + * malformed file and reports as such rather than blaming the password. + */ +export function decryptRaycastV2Backup( + raw: Buffer, + password: string +): { appVersion?: string; payload: Record } { + const { header, payloadStart } = readRaycastV2Header(raw); + const iv = readHexField(header?.encryption?.iv, IV_LENGTH); + const salt = readHexField(header?.encryption?.salt, SALT_LENGTH); + if (!iv || !salt) throw new Error(CORRUPT_CONTAINER_MESSAGE); + + const payloadEnd = raw.length - AUTH_TAG_LENGTH; + if (payloadEnd <= payloadStart) throw new Error(CORRUPT_CONTAINER_MESSAGE); + + const key = crypto.scryptSync(password, salt, SCRYPT_KEY_LENGTH, { + N: SCRYPT_N, + r: SCRYPT_R, + p: SCRYPT_P, + // 128 * N * r is 16 MB here, above Node's 32 MB default only once headroom + // is counted, so raise it rather than depend on the default. + maxmem: 64 * 1024 * 1024, + }); + + let compressed: Buffer; + try { + const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); + decipher.setAuthTag(raw.subarray(payloadEnd)); + compressed = Buffer.concat([decipher.update(raw.subarray(payloadStart, payloadEnd)), decipher.final()]); + } catch { + // The tag is the only wrong-password signal the container offers. + throw new Error(INVALID_PASSWORD_MESSAGE); + } + + try { + // Past the tag the bytes are authenticated, so a failure here is corruption + // rather than a bad password. + return { appVersion: header?.appVersion, payload: JSON.parse(zlib.gunzipSync(compressed).toString('utf8')) }; + } catch { + throw new Error(CORRUPT_CONTAINER_MESSAGE); + } +} + +// --------------------------------------------------------------------------- +// Payload conversion: Raycast 2.x categories -> the 1.x shape the importer reads +// --------------------------------------------------------------------------- + +const MODIFIER_ALIASES: Record = { + meta: 'command', + cmd: 'command', + command: 'command', + ctrl: 'control', + control: 'control', + alt: 'option', + option: 'option', + shift: 'shift', + fn: 'fn', + function: 'fn', +}; + +// `decodeRaycastHotkey` emits modifiers in the order it reads them, and +// `normalizeAccelerator` canonicalises to Command, Control, Alt, Shift, Fn. +const MODIFIER_ORDER = ['command', 'control', 'option', 'shift', 'fn']; + +const NODE_COMMAND_PATTERN = /^c:n:([0-9a-fA-F-]{8,})::-::(.+)$/; +const INTERNAL_COMMAND_PATTERN = /^c:r:([a-zA-Z0-9-]+)::-::(.+)$/; +const APPLICATION_COMMAND_PATTERN = /^c:r:applications::\*::application::=::(.+)$/; +const NODE_EXTENSION_ID_PATTERN = /^e:n:([0-9a-fA-F-]{8,})$/; + +/** AI-tool entry points Raycast synthesises per extension; they have no SuperCmd command. */ +function isAiPseudoCommand(commandName: string): boolean { + return commandName === '__ai_extension' || /aiExtension$/i.test(commandName); +} + +/** + * Turns Raycast 2.x's structured hotkey into the 1.x `modifier-...-keycode` + * string so `decodeRaycastHotkey` stays the single decoder. The virtual key + * codes are unchanged between the two formats. + */ +export function encodeLegacyHotkey(hotkey: unknown): string | null { + const record = hotkey as any; + const kind = record?.kind; + if (!kind || (kind.type && kind.type !== 'SingleStep')) return null; + const shortcut = kind.shortcut; + const key = shortcut?.key; + if (!key || (key.type && key.type !== 'LayoutIndependent')) return null; + const code = Number(key.code); + if (!Number.isFinite(code)) return null; + + const present = new Set(); + for (const entry of Array.isArray(shortcut?.modifiers) ? shortcut.modifiers : []) { + const name = MODIFIER_ALIASES[String((entry as any)?.modifier || '').trim().toLowerCase()]; + if (name) present.add(name); + } + return [...MODIFIER_ORDER.filter((modifier) => present.has(modifier)), String(code)].join('-'); +} + +/** + * Raycast 2.x built-in command ids that have a direct SuperCmd counterpart. + * Ids without a clean equivalent are left out on purpose: an approximate match + * would silently bind a hotkey to the wrong command. + */ +export const RAYCAST_V2_BUILTIN_COMMAND_IDS: Record = { + 'c:r:calendar::-::mySchedule': 'system-my-schedule', + 'c:r:clipboard-history::-::history': 'system-clipboard-manager', + 'c:r:developer::-::manageExtensions': 'system-open-extensions-settings', + 'c:r:emoji-picker::-::searchEmoji': 'system-emoji-picker', + 'c:r:file-search::-::searchFiles': 'system-search-files', + 'c:r:navigation::-::searchMenuItems': 'system-menu-item-search', + 'c:r:notes::-::create': 'system-create-note', + 'c:r:notes::-::open': 'system-search-notes', + 'c:r:notes::-::search': 'system-search-notes', + 'c:r:quicklinks::-::create': 'system-create-quicklink', + 'c:r:quicklinks::-::search': 'system-search-quicklinks', + 'c:r:raycast-core::-::checkForUpdates': 'system-check-for-updates', + 'c:r:raycast-core::-::openCamera': 'system-camera', + 'c:r:raycast-core::-::openSearchStore': 'system-open-extension-store', + 'c:r:raycast-core::-::quitApp': 'system-quit-launcher', + 'c:r:raycast-core::-::resetPosition': 'system-reset-launcher-position', + 'c:r:raycast-settings::-::openLauncherSettings': 'system-open-settings', + 'c:r:script-commands::-::createScriptCommand': 'system-create-script-command', + 'c:r:snippets::-::createSnippet': 'system-create-snippet', + 'c:r:snippets::-::exportSnippets': 'system-export-snippets', + 'c:r:snippets::-::importSnippets': 'system-import-snippets', + 'c:r:snippets::-::searchSnippets': 'system-search-snippets', + 'c:r:system::-::emptyTrash': 'system-empty-trash', + 'c:r:system::-::lockScreen': 'system-lock-screen', + 'c:r:system::-::logOut': 'system-logout', + 'c:r:system::-::quitAllApplications': 'system-close-all-apps', + 'c:r:system::-::restart': 'system-restart', + 'c:r:system::-::shutDown': 'system-shutdown', + 'c:r:system::-::sleep': 'system-sleep', + // Window management: only placements SuperCmd implements with the same geometry. + 'c:r:window-management::-::bottomCenterSixth': 'system-window-management-bottom-center-sixth', + 'c:r:window-management::-::bottomHalf': 'system-window-management-bottom', + 'c:r:window-management::-::bottomLeftQuarter': 'system-window-management-bottom-left', + 'c:r:window-management::-::bottomLeftSixth': 'system-window-management-bottom-left-sixth', + 'c:r:window-management::-::bottomRightQuarter': 'system-window-management-bottom-right', + 'c:r:window-management::-::bottomRightSixth': 'system-window-management-bottom-right-sixth', + 'c:r:window-management::-::center': 'system-window-management-center', + 'c:r:window-management::-::centerThird': 'system-window-management-center-third', + 'c:r:window-management::-::centerThreeFourth': 'system-window-management-center-three-fourths', + 'c:r:window-management::-::centerTwoThird': 'system-window-management-center-two-thirds', + 'c:r:window-management::-::firstFourth': 'system-window-management-first-fourth', + 'c:r:window-management::-::firstThird': 'system-window-management-first-third', + 'c:r:window-management::-::firstThreeFourth': 'system-window-management-first-three-fourths', + 'c:r:window-management::-::firstTwoThird': 'system-window-management-first-two-thirds', + 'c:r:window-management::-::lastFourth': 'system-window-management-last-fourth', + 'c:r:window-management::-::lastThird': 'system-window-management-last-third', + 'c:r:window-management::-::lastThreeFourth': 'system-window-management-last-three-fourths', + 'c:r:window-management::-::lastTwoThird': 'system-window-management-last-two-thirds', + 'c:r:window-management::-::leftHalf': 'system-window-management-left', + 'c:r:window-management::-::makeLarger': 'system-window-management-increase-size-10', + 'c:r:window-management::-::makeSmaller': 'system-window-management-decrease-size-10', + 'c:r:window-management::-::maximize': 'system-window-management-fill', + 'c:r:window-management::-::maximizeAlmost': 'system-window-management-center-80', + 'c:r:window-management::-::maximizeHeight': 'system-window-management-maximize-height', + 'c:r:window-management::-::maximizeWidth': 'system-window-management-maximize-width', + 'c:r:window-management::-::rightHalf': 'system-window-management-right', + 'c:r:window-management::-::secondFourth': 'system-window-management-second-fourth', + 'c:r:window-management::-::thirdFourth': 'system-window-management-third-fourth', + 'c:r:window-management::-::topCenterSixth': 'system-window-management-top-center-sixth', + 'c:r:window-management::-::topHalf': 'system-window-management-top', + 'c:r:window-management::-::topLeftQuarter': 'system-window-management-top-left', + 'c:r:window-management::-::topLeftSixth': 'system-window-management-top-left-sixth', + 'c:r:window-management::-::topRightQuarter': 'system-window-management-top-right', + 'c:r:window-management::-::topRightSixth': 'system-window-management-top-right-sixth', +}; + +function asArray(value: unknown): any[] { + return Array.isArray(value) ? value : []; +} + +function asObject(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {}; +} + +function trimmed(value: unknown): string { + return String(value ?? '').trim(); +} + +/** + * Joins `ai.messages` onto `ai.chats` by `chatId`. Raycast 2.x splits them into + * sibling arrays, whereas the 1.x importer expects each chat to carry its own + * messages. Tool-call turns are dropped: SuperCmd's chat store has no + * representation for them. + */ +function convertAiChats(ai: Record): any[] { + const messagesByChat = new Map(); + for (const message of asArray(ai.messages)) { + const role = trimmed(message?.role).toLowerCase(); + if (role !== 'user' && role !== 'assistant') continue; + const text = trimmed(message?.content?.text); + if (!text) continue; + const chatId = trimmed(message?.chatId); + if (!chatId) continue; + const bucket = messagesByChat.get(chatId); + const entry = { role, content: text, createdAt: message?.createdAt ?? message?.updatedAt }; + if (bucket) bucket.push(entry); + else messagesByChat.set(chatId, [entry]); + } + + const chats: any[] = []; + for (const chat of asArray(ai.chats)) { + const id = trimmed(chat?.id); + const messages = messagesByChat.get(id) || []; + if (messages.length === 0) continue; + chats.push({ + id, + title: trimmed(chat?.title), + createdAt: chat?.createdAt, + updatedAt: chat?.updatedAt, + model: trimmed(chat?.modelId) || undefined, + messages, + }); + } + return chats; +} + +/** + * Rebuilds the 1.x per-extension records from the two places 2.x splits them + * across: `nodeExtensions.extensions` holds identity, `settings.nodeExtensions` + * holds the enabled flag and preference values, and `settings.commands` holds + * each command's enabled flag. + * + * OAuth tokens (`settings.nodeExtensions[].oauthTokens`) are never read: they + * are live credentials and SuperCmd has nothing to do with them. + */ +function convertExtensions(payload: Record): { extensions: any[]; extensionNameByUuid: Map } { + const extensionNameByUuid = new Map(); + for (const entry of asArray(payload?.nodeExtensions?.extensions)) { + const uuid = trimmed(entry?.uuid); + const name = trimmed(entry?.name); + if (uuid && name) extensionNameByUuid.set(uuid, name); + } + + const settingsByUuid = new Map>(); + for (const entry of asArray(payload?.settings?.nodeExtensions)) { + const match = NODE_EXTENSION_ID_PATTERN.exec(trimmed(entry?.id)); + if (match) settingsByUuid.set(match[1], asObject(entry)); + } + + const commandsByUuid = new Map>(); + for (const command of asArray(payload?.settings?.commands)) { + const match = NODE_COMMAND_PATTERN.exec(trimmed(command?.id)); + if (!match) continue; + const [, uuid, commandName] = match; + if (isAiPseudoCommand(commandName)) continue; + const bucket = commandsByUuid.get(uuid) || []; + bucket.push({ name: commandName, enabled: command?.enabled !== false }); + commandsByUuid.set(uuid, bucket); + } + + const extensions: any[] = []; + for (const entry of asArray(payload?.nodeExtensions?.extensions)) { + const uuid = trimmed(entry?.uuid); + const name = trimmed(entry?.name); + if (!uuid || !name) continue; + const extensionSettings = settingsByUuid.get(uuid) || {}; + const preferenceValues = asObject(extensionSettings.meta); + const prefs = asArray(extensionSettings.preferenceTypes) + .map((type) => ({ name: trimmed(type?.name), type: trimmed(type?.type) })) + .filter((type) => type.name && Object.prototype.hasOwnProperty.call(preferenceValues, type.name)) + .map((type) => ({ ...type, value: preferenceValues[type.name] })); + + extensions.push({ + name, + owner: trimmed(entry?.owner) || trimmed(entry?.author), + title: name, + commands: commandsByUuid.get(uuid) || [], + ...(prefs.length > 0 ? { prefs } : {}), + }); + } + return { extensions, extensionNameByUuid }; +} + +/** + * Flattens `settings.commands` into 1.x root-search records. Only the kinds + * whose SuperCmd command id can actually be resolved are emitted: store + * extension commands (by extension name), applications (by path) and mapped + * built-ins. Quicklink, Apple Shortcut and AI-tool entries are skipped because + * SuperCmd mints its own ids for those and a guess would bind the wrong thing. + */ +function convertRootSearch( + payload: Record, + extensionNameByUuid: Map +): { rootSearch: any[]; unmapped: number } { + const rootSearch: any[] = []; + let unmapped = 0; + + for (const command of asArray(payload?.settings?.commands)) { + const id = trimmed(command?.id); + if (!id) continue; + const hotkey = encodeLegacyHotkey(command?.macosHotkey); + // Raycast stores an alias's trailing space to mean "alias then space". + const alias = trimmed(command?.alias); + if (!hotkey && !alias) continue; + + const applicationMatch = APPLICATION_COMMAND_PATTERN.exec(id); + if (applicationMatch) { + rootSearch.push({ path: applicationMatch[1], ...(hotkey ? { hotkey } : {}), ...(alias ? { alias } : {}) }); + continue; + } + + const nodeMatch = NODE_COMMAND_PATTERN.exec(id); + if (nodeMatch) { + const [, uuid, commandName] = nodeMatch; + const extensionName = extensionNameByUuid.get(uuid); + if (!extensionName || isAiPseudoCommand(commandName)) { + unmapped += 1; + continue; + } + rootSearch.push({ + key: `extension_${extensionName}.${commandName}`, + ...(hotkey ? { hotkey } : {}), + ...(alias ? { alias } : {}), + }); + continue; + } + + const internalMatch = INTERNAL_COMMAND_PATTERN.exec(id); + if (internalMatch && RAYCAST_V2_BUILTIN_COMMAND_IDS[id]) { + rootSearch.push({ key: id, ...(hotkey ? { hotkey } : {}), ...(alias ? { alias } : {}) }); + continue; + } + + unmapped += 1; + } + + return { rootSearch, unmapped }; +} + +/** + * Maps a decrypted Raycast 2.x payload onto the 1.x `builtin_package_*` shape. + * + * Categories with no SuperCmd destination (emoji frecency, focus categories, + * window layouts, usage activity) are dropped; clipboard history and MCP + * servers are passed through as counts only so the preview can keep reporting + * them as unsupported. + */ +export function convertRaycastV2Backup(payload: Record, appVersion?: string): RaycastBackup { + const source = asObject(payload); + const { extensions, extensionNameByUuid } = convertExtensions(source); + const { rootSearch } = convertRootSearch(source, extensionNameByUuid); + const general = asObject(source?.settings?.general); + + const quicklinks = asArray(source?.quicklinks?.quicklinks) + .map((quicklink) => ({ + uuid: trimmed(quicklink?.id), + name: trimmed(quicklink?.name), + url: trimmed(quicklink?.link), + isEnabled: true, + })) + .filter((quicklink) => quicklink.name && quicklink.url); + + const snippets = asArray(source?.snippets?.snippets) + .map((snippet) => ({ + name: trimmed(snippet?.name) || trimmed(snippet?.title), + text: trimmed(snippet?.text) || trimmed(snippet?.content), + keyword: trimmed(snippet?.keyword), + })) + .filter((snippet) => snippet.name && snippet.text); + + const notes = asArray(source?.notes?.notes) + .map((note) => ({ title: trimmed(note?.title), text: trimmed(note?.text) })) + .filter((note) => note.title || note.text); + + return { + raycast_version: trimmed(appVersion) || undefined, + builtin_package_raycastPreferences: { + preferencesGeneral: { + raycastGlobalHotkey: encodeLegacyHotkey(general.globalHotkey) || undefined, + }, + preferencesAppearance: { + raycastPreferredWindowMode: trimmed(general.windowMode) || undefined, + }, + preferencesAdvanced: { + navigationCommandStyleIdentifierKey: trimmed(general.navigationBindings) || undefined, + popToRootTimeout: Number.isFinite(Number(general.popToRootTimeout)) + ? Number(general.popToRootTimeout) + : undefined, + }, + }, + builtin_package_quicklinks: { quicklinks }, + builtin_package_snippets: { snippets }, + builtin_package_raycastNotes: { notes }, + builtin_package_raycastExtensions: { extensions }, + builtin_package_rootSearch: { rootSearch }, + 'builtin_package_open-ai': { aiChats: convertAiChats(asObject(source?.ai)) }, + builtin_package_clipboardHistory: { + clipboardHistoryRecords: asArray(source?.clipboardHistory?.clipboardEntries), + }, + builtin_package_mcp: { mcpServers: asArray(source?.mcpServers?.servers) }, + }; +} + +/** Reads a `RAYCFG3` file end to end: decrypt, then map onto the 1.x shape. */ +export function loadRaycastV2Backup(raw: Buffer, password: string): RaycastBackup { + const { appVersion, payload } = decryptRaycastV2Backup(raw, password); + return convertRaycastV2Backup(payload, appVersion); +}