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

> Date: 2026-07-30
> Version: 1.0
> Status: Draft
> Location: spec-driven/alks-cli-keystore-keytar-replacement/spec.md
> Tracking: N/A
> Source: Draft from problem spec (`ALKS-CLI keytar Node-24 Keychain Failure — Problem Spec.md`, 2026-07-29) + codebase verification at `e618adb`

> **Provenance Key**: Content sources are marked inline:
> - **[User]** — Directly stated in the problem spec authored by the user
> - **[Inferred]** — Synthesized by the agent (confidence: HIGH from structured problem-spec content, LOW from extrapolation)
> - **[Default]** — Standard default applied
> - **[Codebase]** — Verified directly against the codebase at `e618adb`

## Project Context

**Parent Project**: See `CLAUDE.md` for project-wide principles and patterns. Notably: update `changelog.txt` before opening a PR, and lock any runtime-behavior change with at least one test. **[Codebase]**

**Scope**: This specification defines requirements for the alks-cli keystore layer — swapping the keychain-backing native library and correcting the surrounding error handling, support contract, and CI coverage. **[User]**

## Overview

`alks developer configure` validates a refresh token and then stores it in the OS keychain. On a fresh machine running **Node 24** — the version alks-cli builds and releases with — the store step fails and the CLI prints *"No keychain could be found for storing the token,"* then offers to fall back to an unencrypted plaintext file. The keychain feature is broken for **every** user who installs the CLI under Node 24. **[User]**

The true cause is that `keytar@^7.7.0` (atom/node-keytar) is archived and unmaintained (last release 7.9.0, Sept 2023) and uses the old NAN / per-Node-ABI binding model. It ships **no prebuilt binary for Node 24 (ABI 137)**; when the source-build fallback doesn't run/succeed during `npm install -g alks`, no `keytar.node` is produced, and the module fails to load at runtime with `Cannot find module '../build/Release/keytar.node'`. macOS/Apple Keychain is not involved. **[User]**

The fix replaces `keytar` with **`@napi-rs/keyring`**, which is built on Node-API (ABI-stable across Node majors) and ships per-platform-triple prebuilds (darwin arm64+x64, Windows, Linux) — eliminating the per-Node "no binary" cliff rather than moving it. The swap is confined to the single adapter (`getKeytar.ts`) so the three call sites are minimally touched. Alongside the swap, the spec corrects three defects the incident exposed: a masked/misleading error message, a stale Node `engines` contract, and a CI blind spot that lets a broken keychain path ship green. **[User]**

The expected business value: CAI engineers can authenticate the CLI on the current supported Node versions without silently downgrading to plaintext token storage, and the pipeline stops certifying a broken keychain path. **[Inferred:HIGH]**

### Current State

The keytar surface is **token-only** — the basic-auth password keystore has already been removed (no `state/password.ts`, `storePassword.ts`). All keychain access flows through **one adapter**, `src/lib/getKeytar.ts` (`await import('keytar')`), with three call sites, using service key `alkscli` and account key `alkstoken`: **[Codebase]**

- `getTokenFromKeystore.ts` — reads the stored token via `keytar.getPassword`; on any keytar failure it logs and falls back to reading the plaintext credentials file (`credentials.refresh_token`). **[Codebase]**
- `storeToken.ts` — stores via `keytar.setPassword`; on failure prints `"No keychain could be found for storing the token"` and offers a plaintext-file fallback. **[Codebase]**
- `removeToken.ts` — deletes via `keytar.deletePassword`. **[Codebase]**

`getKeytar.ts` logs the real import error only via `log()` (silent without `-v`) and re-throws a generic *"Please reinstall this cli…"* message, which `storeToken.ts` turns into the misleading *"No keychain could be found."* **[Codebase]**

`package.json` lists `"keytar": "^7.7.0"` in `optionalDependencies` and `engines.node: ">=16.0.0"`. The CI matrix (`build-and-test.yml`) is Node **20.x / 22.x / 24.x**; release builds on Node 24. CI stays green because tests mock keytar and the real adapter is never exercised (`getKeytar` shows 0 function hits in coverage). The plaintext fallback works and is the current de-facto workaround — but it silently downgrades every Node-24 user to unencrypted on-disk storage behind a false error. **[User]** **[Codebase]**

## Goals

### Primary Goal
Restore working OS-keychain refresh-token storage for all users on every CI-matrix Node version (20/22/24) — with no forced plaintext fallback and no per-Node "no binary" cliff. **[User]**

### Secondary Goals
1. Make keychain failures self-diagnosing: surface the real reason for a keystore failure without requiring `-v`, instead of a misleading "No keychain could be found." **[User]**
2. Prevent recurrence: exercise the real (non-mocked) keystore adapter in CI so a "keychain can't load on a supported Node" regression fails the build instead of shipping green. **[User]**
3. Align the Node support contract: make `package.json` `engines` reflect CI reality (drop the stale `>=16`). **[User]**
4. Preserve existing users' stored tokens so no one is forced to re-authenticate after upgrade. **[User]**

### Non-Goals (Explicitly Out of Scope)
- Any ALKS Core / server change. **[User]**
- The basic-auth removal (already landed). **[User]**
- Changes to the `alks.js` SDK. **[User]**
- ALKS Desktop (`alks-client`) — its keychain integration is worth a parallel audit if it shares the keytar pattern, but it is not part of this work. **[User]**
- Removing the plaintext fallback — it is kept as a legitimate last resort for headless/unsupported environments. **[User]**

## Users

### Primary Users
| User Type | Description | Goals | Pain Points |
|-----------|-------------|-------|-------------|
| CLI end users (CAI engineers) | Engineers who run `alks developer configure` / `alks sessions open` to obtain AWS credentials | Store their refresh token securely in the OS keychain and authenticate without friction | On Node 24 the keychain store fails with a misleading error and they are silently pushed to plaintext token storage **[User]** |
| alks-cli maintainers | Developers who build, test, and release the CLI | A pipeline that fails when the real keychain path is broken on a supported Node version | CI certifies a broken configuration because the keytar path is mocked and never exercised **[User]** |

### Secondary Users
| User Type | Description | Goals | Pain Points |
|-----------|-------------|-------|-------------|
| Upgrading users | Users who already have a token stored under `alkscli`/`alkstoken` | Upgrade without re-authenticating | A library swap could orphan the existing keychain entry **[Inferred:HIGH]** |

## Functional Requirements

### FR-1: Replace keytar with an ABI-stable keychain library behind the single adapter

**Description**: Replace `keytar@^7.7.0` with `@napi-rs/keyring` and back the existing `getKeytar.ts` adapter with it, exposing exactly the three operations the CLI uses — `getPassword(service, account)`, `setPassword(service, account, secret)`, `deletePassword(service, account)` — so `getTokenFromKeystore.ts`, `storeToken.ts`, and `removeToken.ts` need no logic change. The adapter uses `@napi-rs/keyring`'s Promise-based `AsyncEntry(service, account)` API and translates its behavior to match the previous keytar contract. Service/account keys stay `alkscli` / `alkstoken`. **[User]**

**User Story**: As a CLI end user on Node 24, I want `alks developer configure` to store my refresh token in the OS keychain so that I authenticate securely without being pushed to plaintext storage.

**Acceptance Criteria**:

| ID | Criterion | Given | When | Then |
|----|-----------|-------|------|------|
| AC-1.1 | Store on supported Node | A fresh install on any CI-matrix Node (20/22/24), macOS arm64 or x64 | The user runs `alks developer configure` and enters a valid refresh token | The token is stored in the OS keychain — no "No keychain could be found" and no forced plaintext fallback **[User]** |
| AC-1.2 | Round-trip via adapter | A token has been stored through the adapter | `getTokenFromKeystore` reads it back | The same token value is returned, with call-site logic unchanged **[User]** |
| AC-1.3 | Missing entry returns undefined | No token is stored under `alkscli`/`alkstoken` | The adapter's `getPassword` is called (`@napi-rs/keyring` raises `NoEntry`) | The adapter catches `NoEntry` and returns `undefined`, so `getTokenFromKeystore`'s `?? undefined` + plaintext fallback still behaves **[User]** |
| AC-1.4 | Delete non-existent entry is a no-op | No token is stored | `removeToken` calls the adapter's `deletePassword` | The `NoEntry` case is treated as a no-op success (no thrown error) **[User]** |
| AC-1.5 | Existing tokens remain readable | A token was previously stored by keytar under `alkscli`/`alkstoken` | The user upgrades and reads the token | The previously-stored token is returned with no re-authentication prompt **[User]** |
| AC-1.6 | Adapter boundary preserved | The new library is in place | Reviewing the call sites | The library's API appears only inside the adapter; `getTokenFromKeystore`/`storeToken`/`removeToken` reference the adapter, not the library **[User]** |

**Priority**: Must Have

**Goal**: Primary (also satisfies Secondary-4 — preserve existing users' stored tokens, via AC-1.5 / NFR-2)

**Dependencies**: None

---

### FR-2: Surface the real keystore error and keep an honest plaintext fallback

**Description**: The adapter must not swallow the underlying cause into a generic "reinstall" string, and `storeToken.ts` must not report "No keychain could be found" for what is actually a module-load / availability failure. Bubble up the real reason (or at minimum print it without requiring `-v`) so future breakage is self-diagnosing. The plaintext fallback is kept, but it must be reached via an honest error, not a false "no keychain" claim. **[User]**

**User Story**: As a CLI end user, I want the real reason a keystore operation failed so that I (or a maintainer) can diagnose it without re-running with `-v`.

**Acceptance Criteria**:

| ID | Criterion | Given | When | Then |
|----|-----------|-------|------|------|
| AC-2.1 | Real cause is visible without `-v` | The keychain library genuinely cannot load or be used | The user runs a keystore operation without `-v` | The printed message includes the caught error's message/type (e.g., the module-load error text) and does not print the generic "reinstall" string or the string "No keychain could be found" **[User]** |
| AC-2.2 | Honest fallback path | The keychain genuinely can't be used | `storeToken` reaches the plaintext-file offer | The caught error's message is printed before the plaintext-storage prompt, in place of the current "No keychain could be found for storing the token" text **[User]** |
| AC-2.3 | Fallback still functions | The user accepts the plaintext offer | The token is written to the credentials file | `getTokenFromKeystore` can read it back via the existing `credentials.refresh_token` path **[Codebase]** |

**Priority**: Must Have

**Goal**: Secondary-1

**Dependencies**: FR-1

---

### FR-3: Align the Node support contract with CI

**Description**: Update `package.json` `engines.node` to match CI reality — drop `>=16.0.0` and set the floor to `>=20`. Keep the CI matrix on the maintained Node majors. **[User]**

**User Story**: As an alks-cli maintainer, I want `engines` to reflect the Node versions we actually build, test, and release on so that the support contract is not misleading.

**Acceptance Criteria**:

| ID | Criterion | Given | When | Then |
|----|-----------|-------|------|------|
| AC-3.1 | Engines matches CI | The CI matrix is Node 20/22/24 | Inspecting `package.json` `engines.node` | It is set to `>=20` (or equivalent range with a floor of 20) with no reference to unsupported Node 16 **[User]** |
| AC-3.2 | Chosen library satisfies the floor | `@napi-rs/keyring` declares `engines node >= 10` | Comparing against the new floor | The library comfortably satisfies the `>=20` floor **[User]** |

**Priority**: Must Have

**Goal**: Secondary-3

**Dependencies**: None

---

### FR-4: Exercise the real keystore adapter in CI

**Description**: Add a test (or a smoke step in the build matrix) that exercises the **real** keystore adapter — not a mock — so a "keychain can't load on a supported Node" regression fails CI instead of shipping green. A minimal integration check that `setPassword`/`getPassword`/`deletePassword` round-trips on each matrix Node version would have caught this incident. **[User]**

**User Story**: As an alks-cli maintainer, I want CI to fail when the native keychain binding can't load on a supported Node version so that a broken artifact never ships.

**Acceptance Criteria**:

| ID | Criterion | Given | When | Then |
|----|-----------|-------|------|------|
| AC-4.1 | Non-mocked round-trip runs in matrix | The build matrix runs on Node 20/22/24 | The keystore check executes | It performs a real `setPassword` → `getPassword` → `deletePassword` round-trip against the adapter (not a mock) **[User]** |
| AC-4.2 | Binding-load failure fails CI | The native binding cannot load on a matrix Node version | CI runs the keystore check | The build fails rather than passing green **[User]** |

**Priority**: Must Have

**Goal**: Secondary-2

**Dependencies**: FR-1

---

## Non-Functional Requirements

### NFR-1: Cross-platform & cross-Node portability

**Category**: Portability / Compatibility

**Description**: The keychain binding must load without a per-Node source build across all supported Node majors and target platforms. **[User]**

**Metric**: Prebuilt binary availability per (platform-triple × Node major).

**Target**: `@napi-rs/keyring` ships prebuilds for darwin-arm64, darwin-x64, win32-{x64,arm64,ia32}-msvc, and linux-{x64,arm64}-{gnu,musl} (among 12 triples); its Node-API binding is ABI-stable across Node 10→24+, so every CI-matrix Node (20/22/24) installs a prebuild with no node-gyp step. **[User]**

**Verification**: Clean install on each matrix Node on macOS arm64 and x64 produces a loadable binding (covered by FR-4's CI check). **[Inferred:HIGH]**

---

### NFR-2: Backward compatibility of stored secrets

**Category**: Compatibility

**Description**: Tokens stored by the previous keytar-backed CLI must remain readable after the library swap. **[User]**

**Metric**: Read success of a pre-existing `alkscli`/`alkstoken` keychain entry.

**Target**: 100% — no user is forced to re-authenticate after upgrade. **[User]**

**Verification**: Empirically confirm on macOS during implementation (write with keytar, read with `@napi-rs/keyring`) before relying on it; if it fails, add a one-time read-old-write-new migration. **[User]**

---

### NFR-3: Security of token storage

**Category**: Security

**Description**: The refresh token is stored encrypted in the OS keychain by default; unencrypted plaintext storage occurs only as an explicit, user-confirmed last resort. **[Inferred:HIGH]**

**Metric**: Storage location of the token on a supported Node version.

**Target**: OS keychain on all CI-matrix Node versions; plaintext only after an honest failure and explicit user confirmation. **[User]**

**Verification**: On a clean supported-Node install, verify the token lands in the OS keychain (Keychain Access: service `alkscli`, account `alkstoken`) and no plaintext file is written. **[User]**

---

### NFR-4: Reliability — no silent downgrade

**Category**: Reliability

**Description**: A keystore failure must never silently downgrade the user to plaintext behind a misleading message. **[User]**

**Metric**: Correctness of the failure message relative to the actual cause.

**Target**: The displayed reason matches the real failure cause (module-load vs. genuine keychain unavailability), visible without `-v`. **[User]**

**Verification**: Manual/automated check that a simulated binding-load failure surfaces the real cause. **[Inferred:HIGH]**

---

### NFR-5: Operability — regression caught in CI

**Category**: Operability

**Description**: A broken keychain path on a supported Node version must fail the pipeline rather than release. **[User]**

**Metric**: CI outcome when the native binding can't load on a matrix Node.

**Target**: Build fails (red) — no green artifact with a broken keychain path. **[User]**

**Verification**: FR-4's non-mocked round-trip check in the build matrix. **[User]**

---

## Scope

### In Scope
- Swap `keytar` for `@napi-rs/keyring` behind `getKeytar.ts`, using `AsyncEntry` and catching `NoEntry`→`undefined`. **[User]**
- Fix the masked/misleading keystore error messaging in `getKeytar.ts` and `storeToken.ts`. **[User]**
- Correct `package.json` `engines` to match the CI matrix. **[User]**
- Add a non-mocked real-keystore round-trip check in the build matrix. **[User]**
- Adjust keystore tests that currently mock keytar to exercise the adapter for real. **[User]**

### Out of Scope
- ALKS Core / server changes; the `alks.js` SDK; ALKS Desktop (`alks-client`). **[User]**
- Basic-auth removal (already landed). **[User]**
- Removing the plaintext fallback. **[User]**

### Constraints
- Preserve service/account keys `alkscli` / `alkstoken` so existing keychain entries remain readable. **[User]**
- Keep the swap confined to the single adapter boundary; do not spread the library's API across call sites. **[User]**
- Follow project conventions: update `changelog.txt` before the PR, and lock the new runtime behavior with at least one test. **[Codebase]**
- Linux runtime still requires `libsecret` present (same caveat keytar carried) — carry the doc note. **[User]**

### Assumptions
- Setting `engines` to `>=20` is an acceptable (soft) breaking change for anyone still on Node 16/18, given those are EOL — call it out in release notes. **[User]**
- `@napi-rs/keyring`'s macOS Keychain / Windows Credential Manager / Linux libsecret coverage is parity with keytar. **[User]**
- Keeping the keys makes existing entries readable — to be confirmed empirically (see NFR-2 / Open Questions). **[User]**

### Risks
| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|------------|
| Stored-secret migration doesn't work (new lib can't read keytar-written entries despite same keys) | High | Low | Confirm empirically on macOS before relying on it; if it fails, add a one-time read-old-write-new migration **[User]** |
| Release build on Node 24 still doesn't produce/test a working native binary post-swap | High | Low | FR-4 CI round-trip on the matrix; verify the publish pipeline produces a loadable binding on Node 24 **[User]** |
| `@napi-rs/keyring` API differences beyond the known `NoEntry`/entry-object translation | Medium | Low | Keep translation inside the adapter; cover with the round-trip test **[Inferred:HIGH]** |
| Node floor change breaks users still on 16/18 | Low | Medium | Document in release notes; 16/18 are EOL **[User]** |

## Success Metrics

### Primary Metrics
| Metric | Current Baseline | Target | Measurement Method |
|--------|------------------|--------|-------------------|
| Keychain store success on Node 24 (clean install) | Fails (forced plaintext) | Succeeds | Post-deploy: `alks developer configure` on clean Node 24, verify via Keychain Access **[User]** |
| Matrix Node versions with working keychain | 0 of 3 (real path) | 3 of 3 (20/22/24) | FR-4 CI round-trip **[User]** |

### Secondary Metrics
| Metric | Target | Measurement Method |
|--------|--------|-------------------|
| Keystore failures reported with real cause (no `-v`) | 100% | Manual/automated message check **[Inferred:HIGH]** |
| Upgrading users forced to re-authenticate | 0 | Post-deploy check with a pre-existing keychain entry **[User]** |

## Dependencies

### External Systems
- OS keychain services: macOS Keychain, Windows Credential Manager, Linux libsecret. **[User]**
- `@napi-rs/keyring` (new dependency) and its per-platform-triple prebuild packages. **[User]**
- npm / Artifactory publish pipeline (release builds on Node 24). **[User]**

### Internal Dependencies
- None beyond the keystore layer itself. **[Inferred:HIGH]**

### Data Dependencies
- Existing keychain entries under `alkscli`/`alkstoken`; plaintext `credentials.refresh_token` fallback file. **[Codebase]**

## Timeline Constraints
- None stated. **[User]**

## Open Questions

> Questions that need stakeholder input or empirical confirmation before/at implementation

1. **Stored-secret migration**: Confirm empirically on macOS that `@napi-rs/keyring` reads keytar-written entries under the same `alkscli`/`alkstoken` keys. If not, add a one-time read-old-write-new migration. (Affects FR-1 / NFR-2) **[User]**
2. **Publish pipeline**: Confirm the release build on Node 24 actually produces and tests a working native binding after the swap. (Affects FR-4 / Risks) **[User]**

> **Resolved**: Node `engines` floor = `>=20` (matches the CI matrix; Node 16/18 are EOL). **[User]**

## Agent Decisions

> Decisions made by the agent during elicitation. Review these — they represent assumptions that may need validation.

| # | Decision | Context | Rationale | Affects |
|---|----------|---------|-----------|---------|
| 1 | Modeled the work as 4 FRs (library swap, honest errors, engines alignment, CI check) rather than one monolithic requirement | The problem spec's "Proposed change" is a 5-point list mixing the core swap with supporting fixes | Separating them gives each its own acceptance criteria and priority, and lets the CI check and error-messaging fixes be verified independently | FR-1..FR-4 |
| 2 | Folded "preserve stored tokens" into FR-1 (AC-1.5) + NFR-2 rather than a standalone FR | It's a compatibility constraint on the swap, not an independent capability | Keeps the swap cohesive while still making backward compatibility a testable acceptance criterion | FR-1, NFR-2 |
| 3 | Left the `getKeytar.ts` → `keystore.ts` rename out of the FRs | The problem spec offers it as an optional "(or a renamed `keystore.ts`)" | Filename is a HOW detail for the plan/implementation, not a spec-level requirement; the adapter-boundary requirement (AC-1.6) is what matters | FR-1 |
