Skip to content
Closed
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
56 changes: 56 additions & 0 deletions src/commands/KeysCommand.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, test } from "bun:test";

// Point Config.KEYS_DIR at an isolated temp dir before importing anything
// that reads it. Config derives KEYS_DIR from CONFIG_DIR, which derives from
// homedir(); HOME is read at module-eval time, so we set it first.
const tempHome = mkdtempSync(join(tmpdir(), "jup-keys-test-"));
process.env.HOME = tempHome;

const { KeysCommand } = await import("./KeysCommand.ts");
const { Config } = await import("../lib/Config.ts");

// Access the private static list() handler through the class without
// invoking commander.
// @ts-expect-error test access to private static method
const list = () => KeysCommand.list();

// A valid 32-byte ed25519 private key as a JSON byte array — the Solana
// id-json shape Signer.load()/KeyPair.fromPrivateKey() accept. Deterministic
// test material only; never holds value.
const VALID_KEY = JSON.stringify(
Array.from({ length: 32 }, (_, i) => (i * 7 + 3) % 256)
);

afterAll(() => {
rmSync(tempHome, { recursive: true, force: true });
});

describe("KeysCommand.list with corrupted key files", () => {
test("survives one corrupted keypair and still lists the valid one", async () => {
Config.init();
writeFileSync(join(Config.KEYS_DIR, "good.json"), VALID_KEY);
writeFileSync(join(Config.KEYS_DIR, "bad.json"), "{not valid json");

// The old Promise.all() behavior rejected here; allSettled must not.
await expect(list()).resolves.toBeUndefined();
});

test("survives an empty key file and a valid key side by side", async () => {
Config.init();
writeFileSync(join(Config.KEYS_DIR, "good2.json"), VALID_KEY);
writeFileSync(join(Config.KEYS_DIR, "empty.json"), "");

await expect(list()).resolves.toBeUndefined();
});

test("all-corrupted keys dir does not crash either", async () => {
Config.init();
writeFileSync(join(Config.KEYS_DIR, "bad2.json"), "[]");
writeFileSync(join(Config.KEYS_DIR, "bad3.json"), "garbage");

await expect(list()).resolves.toBeUndefined();
});
});
56 changes: 47 additions & 9 deletions src/commands/KeysCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export class KeysCommand {
);
const keychainFiles = files.filter((f) => f.endsWith(".keychain.json"));

const keypairData = await Promise.all(
const results = await Promise.allSettled(
keypairFiles.map(async (file) => {
const name = file.replace(".json", "");
const signer = await Signer.load(name);
Expand All @@ -139,19 +139,57 @@ export class KeysCommand {
})
);

const keychainData = keychainFiles.map((file) => {
// One corrupted or unreadable keypair file must not hide the keys that
// are still valid: report the failures and continue with the rest.
const keypairData = results
.filter(
(
r
): r is PromiseFulfilledResult<{
name: string;
address: string;
type: string;
active: boolean;
}> => r.status === "fulfilled"
)
.map((r) => r.value);

const loadErrors = results.flatMap((r, i) =>
r.status === "rejected"
? [
`${keypairFiles[i]}: ${
r.reason instanceof Error ? r.reason.message : String(r.reason)
}`,
]
: []
);

const keychainData = keychainFiles.flatMap((file) => {
const name = file.replace(".keychain.json", "");
const config = KeychainConfig.load(name);
return {
name,
address: config.address,
type: config.backend,
active: settings.activeKey === name,
};
try {
const config = KeychainConfig.load(name);
return [
{
name,
address: config.address,
type: config.backend,
active: settings.activeKey === name,
},
];
} catch (e) {
loadErrors.push(
`${file}: ${e instanceof Error ? e.message : String(e)}`
);
return [];
}
});

const data = [...keypairData, ...keychainData];

for (const message of loadErrors) {
console.error(`Warning: skipping unreadable key — ${message}`);
}

if (Output.isJson()) {
Output.json(data);
return;
Expand Down