Skip to content

separate cli auth keys by host - #2808

Closed
drew-harris wants to merge 5 commits into
mainfrom
drewh/cli-auth-map
Closed

separate cli auth keys by host#2808
drew-harris wants to merge 5 commits into
mainfrom
drewh/cli-auth-map

Conversation

@drew-harris

@drew-harris drew-harris commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Transitions the api key storage for the instant-cli to use JSON with a map between api hosts and the key itself.
People who are upgrading will have their previous key tested against their current apiURI, then production, on first initial read.

Also updated create-instant-app to work with the new format. Uses a new export in package.json from cli for auth specific code that cia can borrow

Logging out now only removes the corresponding value from the map, rather than deleting the entire file.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Authentication is centralized in a new exported module that stores API-specific tokens, validates and migrates legacy credentials, and supports removal. CLI commands, token context, HTTP URL resolution, login flows, and create-instant-app now use the shared implementation.

Changes

CLI authentication

Layer / File(s) Summary
API URL resolution and exports
client/packages/cli/src/util/apiUrl.ts, client/packages/cli/src/util/getAuthPaths.ts, client/packages/cli/src/lib/http.ts
API URLs are resolved from environment or configuration with HTTP(S) validation and explicit development-mode values; getBaseUrl is re-exported by the HTTP module.
API-specific authentication storage
client/packages/cli/src/auth.ts, client/packages/cli/package.json
Authentication configuration supports legacy and API-mapped tokens, validation, migration, persistence, removal, and the new ./auth package export.
CLI login, logout, and token context
client/packages/cli/src/lib/login.ts, client/packages/cli/src/context/authToken.ts, client/packages/cli/src/commands/logout.ts
CLI login, logout, and token lookup use the shared API URL and authentication helpers.
Create-app authentication integration
client/packages/create-instant-app/src/login.ts
The app creation login flow reads and saves tokens through instant-cli/auth and removes its local file-writing helper.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant getBaseUrl
  participant authModule
  participant API
  participant configFile

  CLI->>getBaseUrl: resolve API base URL
  getBaseUrl-->>CLI: validated API URL
  CLI->>authModule: read or save API token
  authModule->>configFile: read or write credentials
  authModule->>API: validate token at /dash/me
  API-->>authModule: validation result
  authModule-->>CLI: token or persistence result
Loading

Possibly related PRs

  • instantdb/instant#2803: Modifies create-instant-app handling of INSTANT_CLI_API_URI, a related backend-configuration path.

Suggested reviewers: nezaj

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: separating CLI authentication keys by API host.
Description check ✅ Passed The description accurately explains host-specific key storage, migration behavior, create-instant-app updates, and logout changes.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch drewh/cli-auth-map

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

View Vercel preview at instant-www-js-drewh-cli-auth-map-jsv.vercel.app.

@drew-harris
drew-harris marked this pull request as ready for review July 30, 2026 23:23

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
client/packages/cli/src/auth.ts (1)

6-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate production URL literal.

productionApiUrl duplicates the 'https://api.instantdb.com' fallback literal defined in apiUrl.ts (Line 39). Consider exporting one and importing it here to avoid future drift.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/packages/cli/src/auth.ts` at line 6, Remove the duplicate production
URL literal from auth.ts by exporting and reusing the existing production URL
constant from apiUrl.ts. Update the productionApiUrl reference to import that
shared symbol, preserving the current URL value and fallback behavior.
client/packages/cli/src/util/apiUrl.ts (2)

22-24: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

INSTANT_CLI_API_URI isn't validated as an HTTP(S) URL.

The instant.config.ts apiURI path is validated with the HttpUrl schema, but the INSTANT_CLI_API_URI env var is returned as-is at Line 23. A malformed value here bypasses validation entirely and only fails later, deep in the HTTP client, with a less helpful error.

♻️ Suggested fix
   if (Option.isSome(setEnv)) {
-    return setEnv.value;
+    yield* Schema.decodeUnknown(HttpUrl)(setEnv.value).pipe(
+      Effect.mapError(() =>
+        BadArgsError.make({
+          message:
+            'Invalid INSTANT_CLI_API_URI. Expected a valid HTTP(S) URL.',
+        }),
+      ),
+    );
+    return setEnv.value;
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/packages/cli/src/util/apiUrl.ts` around lines 22 - 24, Validate the
value returned by the setEnv branch in the API URL resolution flow using the
same HttpUrl schema applied to instant.config.ts apiURI, rather than returning
setEnv.value directly. Preserve the existing behavior for valid HTTP(S) URLs and
surface schema validation errors before the HTTP client is invoked.

26-26: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Config-file read failures aren't mapped to a domain error.

Effect.tryPromise(readInstantConfigFile) has no Effect.mapError, so a broken instant.config.ts (e.g. a throw during load) surfaces as a raw UnknownException instead of the friendly BadArgsError used just below for invalid apiURI values.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/packages/cli/src/util/apiUrl.ts` at line 26, Update the instantConfig
loading flow around readInstantConfigFile to map Effect.tryPromise failures to
the existing BadArgsError domain error, preserving the friendly error behavior
already used for invalid apiURI values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@client/packages/cli/src/auth.ts`:
- Around line 19-31: The legacy token returned by parseAuthConfig must be
trimmed before use. Update the non-JSON fallback to return a token derived from
trimmed contents, and ensure readConfigAuthToken reuses that normalized value
during validation fallback so surrounding whitespace cannot corrupt the Bearer
token.
- Around line 62-69: Update writeAuthConfigFile to create the auth directory and
token file with restrictive permissions: use a private directory mode and a file
mode that prevents group/other access when calling mkdir and writeFile. Preserve
the existing paths, serialization, and UTF-8 encoding.

---

Nitpick comments:
In `@client/packages/cli/src/auth.ts`:
- Line 6: Remove the duplicate production URL literal from auth.ts by exporting
and reusing the existing production URL constant from apiUrl.ts. Update the
productionApiUrl reference to import that shared symbol, preserving the current
URL value and fallback behavior.

In `@client/packages/cli/src/util/apiUrl.ts`:
- Around line 22-24: Validate the value returned by the setEnv branch in the API
URL resolution flow using the same HttpUrl schema applied to instant.config.ts
apiURI, rather than returning setEnv.value directly. Preserve the existing
behavior for valid HTTP(S) URLs and surface schema validation errors before the
HTTP client is invoked.
- Line 26: Update the instantConfig loading flow around readInstantConfigFile to
map Effect.tryPromise failures to the existing BadArgsError domain error,
preserving the friendly error behavior already used for invalid apiURI values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 05d32d46-21c8-49bb-a2f2-189767023443

📥 Commits

Reviewing files that changed from the base of the PR and between 629467f and 6d5129a.

📒 Files selected for processing (9)
  • client/packages/cli/package.json
  • client/packages/cli/src/auth.ts
  • client/packages/cli/src/commands/logout.ts
  • client/packages/cli/src/context/authToken.ts
  • client/packages/cli/src/lib/http.ts
  • client/packages/cli/src/lib/login.ts
  • client/packages/cli/src/util/apiUrl.ts
  • client/packages/cli/src/util/getAuthPaths.ts
  • client/packages/create-instant-app/src/login.ts

Comment thread client/packages/cli/src/auth.ts
Comment on lines +62 to +69
async function writeAuthConfigFile(paths: AuthPaths, tokens: AuthTokens) {
await mkdir(paths.appConfigDirPath, { recursive: true });
await writeFile(
paths.authConfigFilePath,
serializeAuthTokens(tokens),
'utf8',
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Auth token file/dir written without restrictive permissions.

writeAuthConfigFile persists bearer tokens via mkdir/writeFile with default modes (typically 644/755 after umask), making the credentials file world-readable on shared/multi-user systems.

🔒 Suggested fix
 async function writeAuthConfigFile(paths: AuthPaths, tokens: AuthTokens) {
-  await mkdir(paths.appConfigDirPath, { recursive: true });
+  await mkdir(paths.appConfigDirPath, { recursive: true, mode: 0o700 });
   await writeFile(
     paths.authConfigFilePath,
     serializeAuthTokens(tokens),
-    'utf8',
+    { encoding: 'utf8', mode: 0o600 },
   );
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function writeAuthConfigFile(paths: AuthPaths, tokens: AuthTokens) {
await mkdir(paths.appConfigDirPath, { recursive: true });
await writeFile(
paths.authConfigFilePath,
serializeAuthTokens(tokens),
'utf8',
);
}
async function writeAuthConfigFile(paths: AuthPaths, tokens: AuthTokens) {
await mkdir(paths.appConfigDirPath, { recursive: true, mode: 0o700 });
await writeFile(
paths.authConfigFilePath,
serializeAuthTokens(tokens),
{ encoding: 'utf8', mode: 0o600 },
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/packages/cli/src/auth.ts` around lines 62 - 69, Update
writeAuthConfigFile to create the auth directory and token file with restrictive
permissions: use a private directory mode and a file mode that prevents
group/other access when calling mkdir and writeFile. Preserve the existing
paths, serialization, and UTF-8 encoding.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
client/packages/cli/src/auth.ts (1)

42-45: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Trim mapped API keys before storing them.

Unlike legacy tokens, JSON-mapped token values are persisted verbatim. A token copied with trailing whitespace or a newline can therefore be returned as an invalid Bearer token. Normalize the value here, and add a regression test for mapped credentials containing surrounding whitespace.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/packages/cli/src/auth.ts` around lines 42 - 45, Update the
mapped-token loop in the parsed credentials flow to trim each token value before
assigning it to tokens using normalizeApiUrl(apiUrl). Preserve the existing
API-key normalization, and add a regression test covering mapped credentials
whose token contains surrounding whitespace.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@client/packages/cli/src/auth.ts`:
- Around line 42-45: Update the mapped-token loop in the parsed credentials flow
to trim each token value before assigning it to tokens using
normalizeApiUrl(apiUrl). Preserve the existing API-key normalization, and add a
regression test covering mapped credentials whose token contains surrounding
whitespace.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0ed8b5ec-4d14-4dc2-86e6-812651fda676

📥 Commits

Reviewing files that changed from the base of the PR and between 6d5129a and 06b7eb6.

📒 Files selected for processing (1)
  • client/packages/cli/src/auth.ts

@nezaj

nezaj commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Talked about this with the LLM and it suggested instead of having one file for all tokens we would be better of having a separate file per backend.

The benefit here is it would be fully backward compatible (if someone upgrades instant-cli and now the file type changes to JSON, if they go to a project using an older instant-cli that will break since our auth file changed).

Put up a PR for that here #2813

@nezaj nezaj closed this Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants