Skip to content

[CLI] Auth token per host - #2813

Merged
nezaj merged 2 commits into
mainfrom
auth-token-by-host
Jul 31, 2026
Merged

[CLI] Auth token per host#2813
nezaj merged 2 commits into
mainfrom
auth-token-by-host

Conversation

@nezaj

@nezaj nezaj commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Previously, the CLI stored one auth token. Switching from Instant Cloud to a self-hosted backend could send the Cloud token to the self-hosted API.

With this PR tokens are now stored per backend and shared by instant-cli and create-instant-app. Logging out only removes the token for the current backend.

Existing cloud/localhost tokens will migrate automatically and remain compatible with older CLI versions.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7d69e5a6-ea73-4af3-bf8f-14c4be8be490

📥 Commits

Reviewing files that changed from the base of the PR and between 7ddbc19 and 29c5f80.

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

📝 Walkthrough

Walkthrough

CLI authentication now resolves validated API and dashboard URLs, stores credentials per backend with legacy migration support, and routes login, logout, context, legacy requests, and create-instant-app through shared authentication helpers.

Changes

Backend-scoped authentication

Layer / File(s) Summary
Centralized URL configuration
client/packages/cli/src/lib/config.ts, client/packages/cli/src/lib/http.ts, client/packages/cli/src/commands/login.ts, client/packages/create-instant-app/src/utils/*, client/packages/cli/__tests__/config.test.ts
API and dashboard URLs use environment overrides, validated config values, and development or production defaults.
Scoped credential storage and compatibility
client/packages/cli/src/auth/index.ts, client/packages/cli/package.json, client/packages/cli/__tests__/auth.test.ts
Tokens are stored by normalized backend URI, with legacy migration, mirroring, removal, permissions, and filesystem error handling.
CLI login, logout, and token consumers
client/packages/cli/src/lib/login.ts, client/packages/cli/src/commands/logout.ts, client/packages/cli/src/context/authToken.ts, client/packages/cli/src/old.js
CLI authentication flows use shared token helpers and pass the configured API URI through legacy request paths.
Create-app authentication integration
client/packages/create-instant-app/src/login.ts, client/packages/create-instant-app/src/utils/*
create-instant-app uses shared authentication helpers and supports configured dashboard origins.
Release version update
client/packages/version/src/version.ts
The shared package version changes from v1.0.56 to v1.0.57.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant Config
  participant Auth
  participant Filesystem
  CLI->>Config: resolve configured API URL
  Config-->>CLI: return validated backend URI
  CLI->>Auth: readAuthToken(backend URI)
  Auth->>Filesystem: read scoped credential
  Filesystem-->>Auth: return token or legacy credential
  Auth-->>CLI: return authentication token
Loading

Possibly related PRs

Suggested reviewers: stopachka

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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
Title check ✅ Passed The title clearly summarizes the main change: storing CLI authentication tokens separately for each backend host.
Description check ✅ Passed The description accurately explains per-backend token storage, logout behavior, migration, and compatibility changes.
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.
✨ 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 auth-token-by-host

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-auth-token-by-host-jsv.vercel.app.

@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: 1

🧹 Nitpick comments (3)
client/packages/cli/__tests__/config.test.ts (1)

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

Add coverage for getBaseUrl, defaults, and invalid-URL validation.

Only getDashUrl's config-file and env-var precedence paths are tested. Given getBaseUrl mirrors this logic, consider adding equivalent tests for it, plus cases for the dev/prod default fallback and the BadArgsError path when apiURI/dashURI is not a valid HTTP(S) URL.

🤖 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/__tests__/config.test.ts` around lines 26 - 47, Expand
the dashboard URL configuration tests around getDashUrl and the corresponding
getBaseUrl tests to cover config-file values, INSTANT_CLI_* environment-variable
precedence, and development/production default fallbacks. Add validation cases
asserting BadArgsError when apiURI or dashURI is not a valid HTTP(S) URL, while
preserving the existing valid URL behavior.
client/packages/create-instant-app/src/utils/fetch.ts (1)

6-8: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider validating INSTANT_CLI_DASH_URI like the CLI's URL resolvers.

This mirrors the pre-existing unvalidated pattern for instantBackendOrigin, but the broader PR introduces HTTP(S) validation for resolved URLs elsewhere (e.g. the CLI's auth module rejects non-http(s) URIs). A malformed INSTANT_CLI_DASH_URI here would silently flow into openInBrowser at login.ts:319 with no early, clear error.

🤖 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/create-instant-app/src/utils/fetch.ts` around lines 6 - 8,
Validate INSTANT_CLI_DASH_URI when resolving instantDashOrigin, requiring a
valid HTTP(S) URL before it can reach openInBrowser. Reuse the CLI’s existing
URL-validation/resolution helper and preserve the localhost/production fallback
when the environment variable is unset.
client/packages/cli/src/auth/index.ts (1)

22-46: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Minor: normalizeApiURI is re-parsed twice per call.

readAuthToken, writeAuthToken, and removeAuthToken each call both getAuthConfigFilePath and getLegacyAuthConfigFilePath, each of which independently re-runs normalizeApiURI(apiURI) on the same input. Negligible cost here, but could be consolidated by normalizing once and passing the normalized string down.

♻️ Sketch
-function getAuthConfigFilePath(apiURI: string) {
-  const normalizedApiURI = normalizeApiURI(apiURI);
+function getAuthConfigFilePath(normalizedApiURI: string) {
   const backendKey = createHash('sha256')
     .update(normalizedApiURI)
     .digest('hex');
   const { config: configDir } = envPaths('instantdb-prod');

   return join(configDir, 'auth', backendKey);
 }

-function getLegacyAuthConfigFilePath(apiURI: string) {
-  const normalizedApiURI = normalizeApiURI(apiURI);
+function getLegacyAuthConfigFilePath(normalizedApiURI: string) {
   ...
 }

Then call normalizeApiURI(apiURI) once at the top of each exported function and pass the result down.

Also applies to: 59-105

🤖 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/index.ts` around lines 22 - 46, Normalize the
API URI once at the start of each exported readAuthToken, writeAuthToken, and
removeAuthToken function, then pass that normalized value to
getAuthConfigFilePath and getLegacyAuthConfigFilePath. Update both helper
signatures to accept the normalized URI without calling normalizeApiURI again,
preserving their existing path-selection behavior.
🤖 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/lib/config.ts`:
- Around line 14-68: Consolidate getBaseUrl and getDashUrl into one parametrized
helper that selects the environment key, config property, fallback URL, and
validation message for each URL type. Validate both environment-sourced and
instant.config.ts values with HttpUrl before returning them, mapping failures to
the appropriate BadArgsError. Keep the existing development and production
fallbacks unchanged while having both public functions delegate to the shared
helper.

---

Nitpick comments:
In `@client/packages/cli/__tests__/config.test.ts`:
- Around line 26-47: Expand the dashboard URL configuration tests around
getDashUrl and the corresponding getBaseUrl tests to cover config-file values,
INSTANT_CLI_* environment-variable precedence, and development/production
default fallbacks. Add validation cases asserting BadArgsError when apiURI or
dashURI is not a valid HTTP(S) URL, while preserving the existing valid URL
behavior.

In `@client/packages/cli/src/auth/index.ts`:
- Around line 22-46: Normalize the API URI once at the start of each exported
readAuthToken, writeAuthToken, and removeAuthToken function, then pass that
normalized value to getAuthConfigFilePath and getLegacyAuthConfigFilePath.
Update both helper signatures to accept the normalized URI without calling
normalizeApiURI again, preserving their existing path-selection behavior.

In `@client/packages/create-instant-app/src/utils/fetch.ts`:
- Around line 6-8: Validate INSTANT_CLI_DASH_URI when resolving
instantDashOrigin, requiring a valid HTTP(S) URL before it can reach
openInBrowser. Reuse the CLI’s existing URL-validation/resolution helper and
preserve the localhost/production fallback when the environment variable is
unset.
🪄 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: 113a0197-7704-4de5-8f73-ee99fd0afbce

📥 Commits

Reviewing files that changed from the base of the PR and between ab9d690 and 7ddbc19.

⛔ Files ignored due to path filters (1)
  • client/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (16)
  • client/packages/cli/__tests__/auth.test.ts
  • client/packages/cli/__tests__/config.test.ts
  • client/packages/cli/package.json
  • client/packages/cli/src/auth/index.ts
  • client/packages/cli/src/commands/login.ts
  • client/packages/cli/src/commands/logout.ts
  • client/packages/cli/src/context/authToken.ts
  • client/packages/cli/src/lib/config.ts
  • client/packages/cli/src/lib/http.ts
  • client/packages/cli/src/lib/login.ts
  • client/packages/cli/src/old.js
  • client/packages/cli/src/util/getAuthPaths.ts
  • client/packages/create-instant-app/package.json
  • client/packages/create-instant-app/src/login.ts
  • client/packages/create-instant-app/src/utils/fetch.test.ts
  • client/packages/create-instant-app/src/utils/fetch.ts
💤 Files with no reviewable changes (2)
  • client/packages/create-instant-app/package.json
  • client/packages/cli/src/util/getAuthPaths.ts

Comment thread client/packages/cli/src/lib/config.ts

@stopachka stopachka 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.

SGTM!

@nezaj
nezaj merged commit ab36fd6 into main Jul 31, 2026
24 checks passed
@nezaj
nezaj deleted the auth-token-by-host branch July 31, 2026 16:13
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