Skip to content

fix(cli): pass Authorization Bearer header in CLI helpers (closes #518)#577

Open
rohitg00 wants to merge 1 commit into
mainfrom
fix/cli-auth-bearer
Open

fix(cli): pass Authorization Bearer header in CLI helpers (closes #518)#577
rohitg00 wants to merge 1 commit into
mainfrom
fix/cli-auth-bearer

Conversation

@rohitg00
Copy link
Copy Markdown
Owner

@rohitg00 rohitg00 commented May 20, 2026

Summary

Closes #518.

When AGENTMEMORY_SECRET is set, the server enables the api-auth middleware on every mutating REST route (including /agentmemory/session/start). The CLI's own HTTP helpers — postJson and postJsonStrict — were not passing the Authorization: Bearer ${AGENTMEMORY_SECRET} header, so agentmemory demo and any other internal CLI HTTP call would 401 unauthorized the moment a secret was configured.

This matches exactly what @victorbjuliani found:

■  POST http://localhost:3111/agentmemory/session/start failed:
   401 Unauthorized — {"error":"unauthorized"}

Plugin scripts (plugin/scripts/*.mjs) already pass the Bearer correctly via authHeaders(). This PR brings the CLI helpers in line.

Diff

  • src/cli.ts+9/-2 adds jsonAuthHeaders() helper and routes both postJson + postJsonStrict through it.

Validation

  • npm test → 97/97 test files, 1081/1081 tests pass
  • npm run build → bundle clean

Note on import-jsonl + consolidation pipeline

The issue body originally framed the symptom as "consolidation pipeline halts after import-jsonl". import-jsonl itself does pass the Bearer (src/cli.ts:2329-2330) and writes sessions + observations directly via the replay function, which by current design uses synthetic compression inline rather than fanning out through the live mem::observe consolidation triggers.

If import-jsonl should also enqueue flow-compress / consolidate / graph-extract on imported observations, that's a separate behavior change worth a dedicated issue — please open a follow-up if so. This PR addresses the auth gap that was blocking demo and any other CLI HTTP path.

Summary by CodeRabbit

  • Bug Fixes
    • POST requests in the CLI now properly authenticate with the server secret when configured.

Review Change Stack

…rict

When the user sets AGENTMEMORY_SECRET in ~/.agentmemory/.env the server
enables the api-auth middleware on every mutating route, including
/agentmemory/session/start. The CLI's own helpers — postJson and
postJsonStrict — were not passing the Bearer header, so
`agentmemory demo` and any other internal CLI HTTP call would 401 with
"unauthorized" the moment a secret was configured.

Plugin scripts under plugin/scripts/*.mjs already include the Bearer
header via authHeaders(); this brings the CLI helpers in line. New
jsonAuthHeaders() centralises the header build so future helpers stay
consistent.

Tests (1081) + build pass.
@vercel
Copy link
Copy Markdown

vercel Bot commented May 20, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agentmemory Ready Ready Preview, Comment May 20, 2026 3:54pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

📝 Walkthrough

Walkthrough

The PR introduces a shared jsonAuthHeaders() helper function that builds JSON request headers with optional Bearer authentication derived from AGENTMEMORY_SECRET, then updates postJson and postJsonStrict to use this centralized header generator instead of duplicated hardcoded Content-Type-only headers.

Changes

CLI authentication headers

Layer / File(s) Summary
Shared JSON auth headers and POST helper integration
src/cli.ts
New jsonAuthHeaders() helper constructs Content-Type: application/json headers and conditionally adds Authorization: Bearer <secret> when AGENTMEMORY_SECRET is set. postJson and postJsonStrict helpers are updated to use this shared generator, enabling authenticated POST requests through the CLI's utility methods when a server secret is configured.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • rohitg00/agentmemory#380: Refactors src/cli.ts to centralize JSON/auth header creation and updates postJson/postJsonStrict to include Bearer authorization when AGENTMEMORY_SECRET is set, aligning with this PR's auth header changes.
  • rohitg00/agentmemory#69: Updates CLI JSON POST helpers to send Authorization: Bearer <secret> when AGENTMEMORY_SECRET is set, pairing with server-side validation of incoming Bearer headers for authentication.

Poem

🐰 A helper hops in, headers now shared,
Bearer tokens bloom where none were bared—
Auth flows swift through CLI's post,
No duplicate headers lost! 🎉

🚥 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding Authorization Bearer header support to CLI helpers, directly addressing the core issue.
Linked Issues check ✅ Passed The PR adds jsonAuthHeaders() helper and updates postJson/postJsonStrict to include Bearer authentication, directly addressing issue #518's requirement for CLI requests to authenticate when AGENTMEMORY_SECRET is set.
Out of Scope Changes check ✅ Passed All changes are scoped to CLI authentication helpers (jsonAuthHeaders, postJson, postJsonStrict updates) and directly address the linked issue's core requirement.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cli-auth-bearer

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

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)
src/cli.ts (1)

1719-1753: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

agentmemory demo still has an unauthenticated mutating POST.

This only fixes callers that go through postJson/postJsonStrict, but seedDemoSession() still posts to /agentmemory/observe with a hardcoded JSON-only header on Line 1794. With AGENTMEMORY_SECRET set, demo seeding can still 401 after session/start succeeds, so the CLI auth gap is not fully closed.

Proposed fix
-      const res = await fetch(url, {
-        method: "POST",
-        headers: { "Content-Type": "application/json" },
-        body: JSON.stringify(payload),
-        signal: AbortSignal.timeout(5000),
-      });
+      const res = await fetch(url, {
+        method: "POST",
+        headers: jsonAuthHeaders(),
+        body: JSON.stringify(payload),
+        signal: AbortSignal.timeout(5000),
+      });

Or route that call through postJsonStrict() as well so all CLI JSON POSTs share the same auth path.

🤖 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 `@src/cli.ts` around lines 1719 - 1753, seedDemoSession is making an
unauthenticated POST to "/agentmemory/observe" with a hardcoded JSON header;
update that code to use the existing JSON auth helper instead of a manual header
or route the call through postJsonStrict/postJson so the AGENTMEMORY_SECRET is
applied. Specifically, replace the direct fetch/header construction in
seedDemoSession with a call to postJsonStrict<T>(url, body, timeoutMs) (or at
minimum use jsonAuthHeaders() for the fetch headers) so the Authorization Bearer
header from jsonAuthHeaders() is included for the observe request.
🤖 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 `@src/cli.ts`:
- Around line 1719-1753: seedDemoSession is making an unauthenticated POST to
"/agentmemory/observe" with a hardcoded JSON header; update that code to use the
existing JSON auth helper instead of a manual header or route the call through
postJsonStrict/postJson so the AGENTMEMORY_SECRET is applied. Specifically,
replace the direct fetch/header construction in seedDemoSession with a call to
postJsonStrict<T>(url, body, timeoutMs) (or at minimum use jsonAuthHeaders() for
the fetch headers) so the Authorization Bearer header from jsonAuthHeaders() is
included for the observe request.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 28e41fc5-fdc1-4ab4-a023-6525e8a361d8

📥 Commits

Reviewing files that changed from the base of the PR and between edd1ceb and 48d54e5.

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

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.

AGENTMEMORY_SECRET enables api-auth middleware that also rejects internal worker callbacks, silently halting consolidation pipeline (v0.9.20)

1 participant