---
title: "Plan: ALKS CLI Keystore — Replace keytar with a Node-24-Compatible Keychain Library"
spec_source: spec-driven/alks-cli-keystore-keytar-replacement/spec.md
spec_hash: sha256:898ed80fae7828d162c4b3efcaf98fdd0bbeaa80c77a351fec5ca4386e37fad9
spec_tier: 1
status: final
version: 1.0
date: 2026-07-30
total_steps: 8
total_phases: 5
estimated_effort: L
risk_level: medium
test_approach: tdd
---

# Implementation Plan: ALKS CLI Keystore — Replace keytar with a Node-24-Compatible Keychain Library

> Spec: spec-driven/alks-cli-keystore-keytar-replacement/spec.md | Generated: 2026-07-30 | Status: Final

## Overview

This plan replaces the archived `keytar@^7.7.0` (NAN / per-Node-ABI, no Node 24 prebuild) with `@napi-rs/keyring` (Node-API, ABI-stable prebuilds per platform triple) behind the single existing adapter, `src/lib/getKeytar.ts`. The adapter's returned shape is preserved — an object exposing `getPassword(service, account)` / `setPassword(service, account, secret)` / `deletePassword(service, account)` — so the three call sites (`getTokenFromKeystore.ts`, `storeToken.ts`, `removeToken.ts`) need no logic change. This is an extension/refactor of existing architecture, not a new subsystem.

The implementation strategy is vertical-slice with a walking skeleton first: Phase 1 proves the dependency/import layer — that `@napi-rs/keyring` installs and its native binding loads on the target Node (the exact thing that regressed with keytar on Node 24). Phase 2 then proves full adapter behavior end-to-end (the core value — keychain storage functioning behind the unchanged call sites) and corrects the two surrounding defects the incident exposed — the misleading error message in `storeToken.ts` and the stale `engines` contract. Phase 3 closes the CI blind spot with a non-mocked keystore check. Phase 4 records the change (changelog + release note). Phase 5 runs full verification, including the empirical stored-secret migration check.

Test approach is **TDD**: for behavioral STEPs, failing tests are written before implementation, using the existing jest + ts-jest setup with co-located `*.test.ts` files. The keystore modules currently have zero tests and keytar is nowhere mocked, so the adapter/behavior tests and the non-mocked round-trip are all new coverage.

```mermaid
graph TD
  STEP1[STEP-1: swap dependency] --> STEP2[STEP-2: rewrite getKeytar adapter]
  STEP1 --> STEP4[STEP-4: engines >=20]
  STEP2 --> STEP3[STEP-3: honest storeToken error]
  STEP2 --> STEP5[STEP-5: non-mocked round-trip test]
  STEP5 --> STEP6[STEP-6: CI secret-service + check]
  STEP4 --> STEP7[STEP-7: changelog + release note]
  STEP3 --> STEP8[STEP-8: full verification + migration check]
  STEP6 --> STEP8
  STEP7 --> STEP8
```

## Test Strategy

- **Approach**: tdd
- **Framework**: jest 29 + ts-jest
- **Pattern reference**: `src/lib/promptForToken.test.ts` (collaborator mocking via `jest.mock('./dep')`, `jest.resetAllMocks()`)
- **Files needing tests**: `src/lib/getKeytar.ts` (adapter behavior), `src/lib/storeToken.ts` (error messaging + fallback), `src/lib/getTokenFromKeystore.ts` (fallback read-back)
- **Integration/E2E**: needed — a non-mocked keystore round-trip (STEP-5) exercised in CI (STEP-6); this is the FR-4 regression guard

## Traceability

| Requirement | Priority | Steps | Status |
|-------------|----------|-------|--------|
| FR-1 (library swap behind adapter) | Must Have | STEP-1, STEP-2, STEP-5, STEP-8 | Covered |
| FR-2 (honest error + keep fallback) | Must Have | STEP-2, STEP-3, STEP-8 | Covered |
| FR-3 (engines contract) | Must Have | STEP-4, STEP-7, STEP-8 | Covered |
| FR-4 (non-mocked CI round-trip) | Must Have | STEP-5, STEP-6, STEP-8 | Covered |

---

## Phase 1: Foundation (Walking Skeleton)

> Prove the architecture end-to-end with the thinnest possible slice: the new library working behind the existing adapter with call sites untouched.

### STEP-1: Swap the keychain dependency
[FR-1 → AC-1.1] | modify `package.json`, `npm-shrinkwrap.json` | Effort: S

> **Intent**: Removes the root cause — the archived, per-Node-ABI keytar with no Node 24 prebuild — and brings in `@napi-rs/keyring`, whose Node-API binding is ABI-stable across Node majors so one prebuild covers 20/22/24. Placed in `dependencies` (not `optionalDependencies` as keytar was) because napi ships reliable per-triple prebuilds; runtime import is still guarded (STEP-2) for the plaintext fallback on unsupported platforms. See AD-2.

- Remove `keytar` from `optionalDependencies` in `package.json`
- Add `@napi-rs/keyring` (latest 1.3.x) to `dependencies`
- Regenerate `npm-shrinkwrap.json` against the public npm registry per the repo's shrinkwrap note in `build-and-test.yml`, then reinstall
- **Verify**: `npm ci` (or `jf npm ci`) completes; `node -e "require('@napi-rs/keyring')"` exits 0; `npm ls keytar` reports keytar absent
- `[Test approach: none — structural step]`

> Depends on: — | Enables: STEP-2, STEP-4

---

## Phase 2: Adapter, Honest Errors, and Support Contract

> Deliver the working, honest keystore adapter and align the Node support contract.

### STEP-2: Rewrite getKeytar.ts as the adapter over @napi-rs/keyring
[FR-1 → AC-1.2, AC-1.3, AC-1.4, AC-1.6 | FR-2 → AC-2.1] | modify `src/lib/getKeytar.ts`, create `src/lib/getKeytar.test.ts` | Effort: M

> **Intent**: The single adapter boundary is what keeps this migration small — the library's `AsyncEntry(service, account)` object API is translated here so the three call sites keep calling `getPassword/setPassword/deletePassword(service, account)` unchanged. Two behavioral gotchas carry real risk: `@napi-rs/keyring` raises a `NoEntry` error where keytar returned `null`, so `getPassword` must catch `NoEntry` and return `undefined` (else `getTokenFromKeystore`'s `?? undefined` + plaintext fallback breaks), and `deletePassword` must treat `NoEntry` as a no-op success. This STEP also stops swallowing the real import/load error into a generic "reinstall" string (NFR-4: no silent, misleading failure).

- Write failing tests in `src/lib/getKeytar.test.ts` (mock `@napi-rs/keyring`'s `AsyncEntry`): `getPassword` returns the stored secret and `setPassword` forwards to the entry (AC-1.2); `getPassword` catches `NoEntry` and resolves `undefined` (AC-1.3); `deletePassword` treats `NoEntry` as a no-op success, not a throw (AC-1.4); the returned object exposes `getPassword`/`setPassword`/`deletePassword` with `(service, account[, secret])` signatures so call sites are unchanged (AC-1.6); a load/import failure surfaces the real underlying error, not a generic "reinstall" string (AC-2.1)
- Rewrite `getKeytar()` to return an adapter object whose methods construct `new AsyncEntry(service, account)` and delegate to `.getPassword()` / `.setPassword(secret)` / `.deletePassword()`, mapping `NoEntry` → `undefined` (get) and `NoEntry` → no-op (delete)
- On import/instantiation failure, throw/propagate the real error message (keep the Linux `libsecret` install hint, but include the underlying cause rather than replacing it)
- Follow pattern from `src/lib/promptForToken.test.ts` for mocking and `resetAllMocks`
- **Verify**: `npm test -- --no-watch --testPathPattern=getKeytar`; then `npm run build`

> Depends on: STEP-1 | Enables: STEP-3, STEP-5

### STEP-3: Make storeToken.ts report the real failure and keep an honest fallback
[FR-2 → AC-2.2, AC-2.3] | modify `src/lib/storeToken.ts`, create `src/lib/storeToken.test.ts` | Effort: S

> **Intent**: `storeToken` currently prints "No keychain could be found for storing the token" for any keystore failure — a false claim, since the real cause was a native module that never loaded. It must print the caught error's actual message before offering the plaintext fallback, so future breakage is self-diagnosing without `-v` (NFR-4). The plaintext fallback itself (write to `credentials.refresh_token`, read back via `getTokenFromKeystore`) stays intact — it is a legitimate last resort (a Non-Goal to remove).

- Write failing tests in `src/lib/storeToken.test.ts` (mock `./getKeytar`, `./confirm`, `./state/credentials`, `./log`): when the adapter throws, the caught error's message is surfaced and the literal string "No keychain could be found for storing the token" is not printed (AC-2.2); on user confirmation the token is written via `setCredentials` and is subsequently readable through `getTokenFromKeystore`'s plaintext path (AC-2.3)
- Modify `storeToken.ts` to print the caught error's message in place of the current hardcoded "No keychain could be found…" line, then proceed to the existing plaintext-fallback confirmation/write
- Add a companion assertion (in the same test file or `getTokenFromKeystore.test.ts`) that `getTokenFromKeystore` returns `credentials.refresh_token` when the adapter fails (AC-2.3)
- Follow pattern from `src/lib/state/token.test.ts` for mocking keystore collaborators
- **Verify**: `npm test -- --no-watch --testPathPattern="storeToken|getTokenFromKeystore"`; then `npm run build`

> Depends on: STEP-2 | Enables: STEP-8 | Parallel with: STEP-4, STEP-5

### STEP-4: Align package.json engines with the CI matrix
[FR-3 → AC-3.1, AC-3.2] | modify `package.json` | Effort: XS

> **Intent**: `engines.node` says `>=16.0.0`, contradicting the CI matrix (20/22/24) and the release Node (24). Setting it to `>=20` makes the support contract honest; `@napi-rs/keyring` declares `node >= 10`, so it comfortably satisfies the new floor. This is a soft breaking change for anyone on EOL Node 16/18 — recorded in the release note (STEP-7).

- Change `engines.node` from `">=16.0.0"` to `">=20"`
- Confirm `@napi-rs/keyring`'s own `engines.node` (declared `>=10`) is satisfied by the new `>=20` floor, so the dependency imposes no higher floor (AC-3.2)
- **Verify**: `node -e "const e=require('./package.json').engines.node; if(!/(^|[^0-9])20/.test(e) || /16/.test(e)) process.exit(1)"` exits 0 (floor is 20, no reference to 16); `node -e "const k=require('@napi-rs/keyring/package.json').engines?.node||'>=10'; process.exit(0)"` confirms the lib's declared floor (≤20)
- `[Test approach: none — structural step]`

> Depends on: STEP-1 | Enables: STEP-7 | Parallel with: STEP-3, STEP-5

---

## Phase 3: Regression Guard (Non-Mocked) and CI

> Ensure a "keychain can't load on a supported Node" regression fails CI instead of shipping green.

### STEP-5: Add a non-mocked keystore round-trip integration test
[FR-4 → AC-4.1, AC-4.2 | FR-1 → AC-1.1] | create `src/lib/getKeytar.integration.test.ts` | Effort: M

> **Intent**: The incident shipped green because every keystore test mocked keytar and the real binding was never loaded (`getKeytar` had 0 function hits in coverage). This test exercises the real adapter — no mocks. Per AD-3 it does two things: a binding-load assertion (import + instantiate `AsyncEntry`) that runs on every environment and would have caught the exact `Cannot find module keytar.node` failure, plus a full `setPassword → getPassword → deletePassword` round-trip that runs only when a secret service is available (macOS always; Linux when gnome-keyring/D-Bus is provisioned in STEP-6). A binding-load failure must fail the test (AC-4.2).

- Write `src/lib/getKeytar.integration.test.ts` that does NOT mock `@napi-rs/keyring`: assert the adapter loads and an `AsyncEntry('alkscli','alkstoken')` can be instantiated (binding-load assertion — fails the test if the native binding can't load, AC-4.2); when a secret service is available, perform a real `setPassword` → `getPassword` (value matches) → `deletePassword` → `getPassword` (returns `undefined`) round-trip against a disposable service/account key, cleaning up after (AC-4.1, AC-1.1)
- Detect secret-service availability (e.g., env flag set by CI / presence of `DBUS_SESSION_BUS_ADDRESS` on Linux, always-on for darwin) to gate the round-trip vs. the load-only floor
- Ensure this test is discovered by the existing jest config (co-located `*.test.ts`) so it runs under `npm test` on each matrix Node
- **Verify**: `npm test -- --no-watch --testPathPattern=getKeytar.integration` (round-trip locally on macOS; load assertion always)

> Depends on: STEP-2 | Enables: STEP-6 | Parallel with: STEP-3, STEP-4

### STEP-6: Provision the secret service in CI and fail on keystore breakage
[FR-4 → AC-4.1, AC-4.2] | modify `.github/workflows/build-and-test.yml` | Effort: M

> **Intent**: CI runs on headless `cai-standard-x86-linux`, which has no secret service by default, so the STEP-5 round-trip would otherwise skip on Linux. Installing `libsecret` + `gnome-keyring` and running the keystore test under `dbus-run-session` with an unlocked keyring lets the full round-trip execute on every matrix Node (20/22/24); the binding-load assertion is the guaranteed floor even if daemon setup is skipped. A keystore failure now fails the build (NFR-1, NFR-5) instead of shipping green.

- Add a step to install `libsecret-1-0`/`libsecret-tools` and `gnome-keyring` (and `dbus-x11`) on the Linux runner before tests
- Run the keystore integration test (or the whole suite) under `dbus-run-session -- sh -c '... unlock gnome-keyring ...; npm test ...'`, exporting the secret-service availability flag consumed by STEP-5
- Ensure a non-zero exit from the keystore test fails the matrix job (do not `|| true`); confirm it runs across Node 20/22/24
- **Verify**: workflow YAML lints/parses (e.g., `python -c "import yaml,sys; yaml.safe_load(open('.github/workflows/build-and-test.yml'))"` exits 0); on a pushed branch, the matrix job runs the keystore round-trip green on all three Node versions and goes red if the binding is removed (spot-check by temporarily breaking the import locally)

> Depends on: STEP-5 | Enables: STEP-8

---

## Phase 4: Documentation and Release Notes

> Record the change per project convention (CLAUDE.md: update changelog before PR).

### STEP-7: Update changelog.txt and release note
[FR-3 → AC-3.1] | modify `changelog.txt` | Effort: XS

> **Intent**: Project convention requires a `changelog.txt` entry before opening a PR. The entry must call out the `engines` floor bump to `>=20` as a soft breaking change for EOL Node 16/18 users, the keytar → `@napi-rs/keyring` swap, and the retained Linux `libsecret` runtime requirement.

- Add a `changelog.txt` entry: replaced keytar with `@napi-rs/keyring` (fixes keychain storage failing on Node 24), honest keystore error reporting, `engines.node` now `>=20` (Node 16/18 no longer supported), Linux still requires `libsecret` at runtime
- **Verify**: `grep -iq "napi-rs/keyring" changelog.txt && grep -iq "engines\|node.*20\|keychain" changelog.txt`
- `[Test approach: none — structural step]`

> Depends on: STEP-4 | Enables: STEP-8 | Parallel with: STEP-5, STEP-6

---

## Phase 5: Verification

> Full verification pass, plus the empirical stored-secret migration check (Open Question 1).

### STEP-8: Full suite, build, and empirical migration check
[FR-1 → AC-1.5 | All FRs] | execute test suite + manual keychain check (execution-only; may modify `src/lib/getKeytar.ts` if a migration is needed) | Effort: S

> **Intent**: Confirms zero regressions and validates the one thing that can't be unit-tested: that a token written by the old keytar build under `alkscli`/`alkstoken` is still readable by `@napi-rs/keyring` after the swap (AC-1.5, NFR-2). If it is not, the default is to add a one-time read-old-write-new migration in the adapter before release (Open Question 1).

- Run `npm run build` (clean typecheck) and `npm test -- --no-watch` (full suite green, including the new keystore tests)
- Empirical migration check on macOS: with a keytar-written entry present (service `alkscli`, account `alkstoken`), confirm the new adapter reads it back with no re-auth prompt; if it fails, add a one-time migration in `getKeytar.ts` and a covering test, then re-run
- Confirm `alks developer configure` stores to the OS keychain (Keychain Access: service `alkscli`, account `alkstoken`) with no "No keychain could be found" message and no forced plaintext fallback
- **Verify**: `npm run build && npm test -- --no-watch` exit 0; on macOS, confirm the pre-existing `alkscli`/`alkstoken` entry's value is returned unchanged by `getTokenFromKeystore` with no credential/re-auth prompt shown

> Depends on: STEP-3, STEP-6, STEP-7

---

## Architecture Decisions

### AD-1: Keep getKeytar.ts as the adapter; preserve its returned shape
- **Context**: The library API changed from module-level functions (`keytar.getPassword(service, account)`) to an entry-object model (`new AsyncEntry(service, account).getPassword()`). The spec offered an optional rename to `keystore.ts`. Renaming touches every import; not renaming keeps the diff minimal.
- **Decision**: We will keep the file `src/lib/getKeytar.ts` and have `getKeytar()` return an object exposing `getPassword(service, account)` / `setPassword(service, account, secret)` / `deletePassword(service, account)`, so the three call sites and their imports are unchanged (AC-1.6).
- **Rationale**: The adapter boundary is what makes the migration small and low-risk; a rename adds churn without behavioral value.
- **Alternatives Considered**: Rename to `keystore.ts` (rejected — cosmetic, expands the diff and the review surface; can be a future cleanup). Spread the library API across call sites (rejected — violates the single-boundary constraint).

### AD-2: Place @napi-rs/keyring in `dependencies`, not `optionalDependencies`
- **Context**: keytar lived in `optionalDependencies` so a failed native source-build wouldn't hard-fail `npm install` — but that is exactly how the Node 24 install silently produced no binary. napi-rs ships reliable per-triple prebuilds.
- **Decision**: We will add `@napi-rs/keyring` as a regular `dependencies` entry; the adapter still guards `import`/instantiation at runtime so an unsupported platform degrades to the plaintext fallback via an honest error.
- **Rationale**: A prebuilt-backed native module should be reliably present; runtime guarding (not install-optionality) is the correct mechanism for graceful degradation.
- **Alternatives Considered**: Keep it optional (rejected — reintroduces the "silently missing binary" failure mode the incident was about).

### AD-3: FR-4 CI verification = binding-load assertion everywhere + round-trip where a secret service exists
- **Context**: AC-4.1 wants a real `set/get/delete` round-trip on the matrix, but CI runs on headless Linux where `@napi-rs/keyring` → libsecret needs a secret-service daemon. The actual regression was a native-binding load failure.
- **Decision**: We will assert the native binding loads on every matrix Node (the essential regression guard) and run the full round-trip gated on secret-service availability, provisioning gnome-keyring + D-Bus on the Linux runner so the round-trip runs there too.
- **Rationale**: The load assertion alone would have caught this incident and needs no daemon; the gated round-trip fulfills AC-4.1 without making the whole matrix hostage to keyring-daemon flakiness.
- **Alternatives Considered**: Round-trip only (rejected — brittle on headless CI, and overkill to catch a load failure). Load-only (rejected — does not satisfy AC-4.1's round-trip requirement).

### AD-4: Defer stored-secret migration; verify empirically, add only if needed
- **Context**: Whether `@napi-rs/keyring` can read keytar-written entries under the same `alkscli`/`alkstoken` keys is unconfirmed (Open Question 1). Building a migration preemptively may be unnecessary work.
- **Decision**: We will not add a migration STEP up front; STEP-8 performs an empirical keytar→napi read check, and a one-time read-old-write-new migration is added only if that check fails.
- **Rationale**: Same OS keychain, same service/account keys — reads are expected to work; a speculative migration adds risk and code for a case that likely doesn't exist.
- **Alternatives Considered**: Always ship a migration (rejected — probable dead code; still gated behind the same empirical check).

---

## Risks and Mitigations

| Risk | Impact | Probability | Mitigation | Affected Steps |
|------|--------|-------------|------------|----------------|
| `@napi-rs/keyring` cannot read keytar-written entries (forces re-auth) | H | L | Empirical check in STEP-8; add one-time read-old-write-new migration if it fails (AD-4) | STEP-2, STEP-8 |
| Headless Linux round-trip flaky due to gnome-keyring/D-Bus setup | M | M | Binding-load assertion is the guaranteed floor; round-trip is gated on service availability (AD-3) | STEP-5, STEP-6 |
| napi-rs API differences beyond the known `NoEntry`/entry-object translation | M | L | Translation confined to the adapter; covered by STEP-2 unit tests and STEP-5 round-trip | STEP-2 |
| Node-24 publish/release build doesn't produce a working binding post-swap | H | L | STEP-6 exercises the real binding on the matrix; verify the release build on Node 24 post-merge (Open Question 2) | STEP-6, STEP-8 |
| `engines >=20` breaks users still on EOL Node 16/18 | L | M | Call out as a breaking change in the release note (STEP-7); 16/18 are EOL | STEP-4, STEP-7 |

---

## Open Questions

1. Does `@napi-rs/keyring` read keytar-written entries under the same `alkscli`/`alkstoken` keys?
   - Affects: STEP-2, STEP-8
   - Default if unresolved: assume readable (same OS keychain + keys); if the STEP-8 empirical check fails, add a one-time read-old-write-new migration in the adapter.
2. Does the Node-24 publish/release pipeline produce and test a working native binding after the swap?
   - Affects: STEP-6
   - Default if unresolved: the STEP-6 matrix round-trip covers Node 20/22/24 in CI; verify the actual release build on Node 24 as a manual post-merge check.

---

## Non-Functional Verification

| NFR | Target | Method | Step |
|-----|--------|--------|------|
| NFR-1: Portability | ABI-stable Node-API prebuild (darwin-arm64/x64, win32-*-msvc, linux-*-{gnu,musl}; 12 triples) loads on Node 20/22/24 with no node-gyp/source build | Binding-load assertion runs on each matrix Node (no source build invoked) | STEP-6 |
| NFR-2: Backward compatibility | Pre-existing `alkscli`/`alkstoken` entry readable, 0 forced re-auth | Empirical keytar→napi read check on macOS | STEP-8 |
| NFR-3: Security of token storage | Token in OS keychain by default; plaintext only via explicit confirmation | Round-trip proves keychain path; fallback reached only on honest failure | STEP-5, STEP-3 |
| NFR-4: Reliability — no silent downgrade | Displayed reason matches real cause, visible without `-v` | Unit tests assert real error surfaced, not "No keychain could be found" | STEP-2, STEP-3 |
| NFR-5: Operability — regression caught in CI | Build fails red when binding can't load | Non-mocked keystore check wired into the matrix job | STEP-6 |

---

## Effort Legend

| Size | Guideline |
|------|-----------|
| XS | < 1 hour: trivial change, single function/config |
| S | 1-4 hours: small feature, single file |
| M | 4-8 hours: moderate feature, 2-3 files |
| L | 1-3 days: significant feature, multiple files |
| XL | 3+ days: complex feature, consider splitting |
