Skip to content

feat: surface load secrets from integrations#130

Open
andyMrtnzP wants to merge 14 commits into
mainfrom
feat/autologin-poc
Open

feat: surface load secrets from integrations#130
andyMrtnzP wants to merge 14 commits into
mainfrom
feat/autologin-poc

Conversation

@andyMrtnzP

@andyMrtnzP andyMrtnzP commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

Release Notes

  • New Features

    • Session attachment: Connect to pre-created browser sessions using a session ID instead of launching new instances.
    • New loadSecret command: Automatically inject stored credentials into form inputs during agent operations.
  • Documentation

    • Clarified login verification: Account display names may differ from entered usernames; rely on other verification signals to confirm successful authentication.

andyMrtnzP and others added 14 commits June 10, 2026 12:59
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
… fix

Lets the enterprise autologin runner own the browser session and drive
the agent against it, instead of relying on the model to emit createProfile.

- Thread x-browserless-session-id (header) / browserlessSessionId (query)
  through hybridAuthenticate → ToolRunContext → agent tool as
  attachSessionId; the agent opens /chromium/agent?sessionId=<id> to
  attach to the runner's pre-created profile session.
- Open-only fast-path: a createProfile call with no command opens the
  session and returns without hitting the agent route's id/method check.
- autonomous-login skill: a signed-in account's visible display name
  usually won't equal the typed email/username — that is not a failure;
  judge success only by URL change / password-field absence / authed
  element, never by identity mismatch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Adds an attachSessionId field (sourced from the x-browserless-session-id header) that propagates from authentication through session key fingerprinting, session lifecycle functions (getOrCreateSession, closeSession, destroySession), and the browserless_agent tool's control flow. Also introduces a new loadSecret agent command schema with a required credential reference and optional CSS selector.

Changes

attachSessionId Session Attachment

Layer / File(s) Summary
Type and context contracts for attachSessionId
src/@types/types.d.ts, src/lib/define-tool.ts
BrowserlessSession and ToolRunContext each gain an optional attachSessionId?: string field.
Auth extraction and session helper
src/index.ts, src/lib/define-tool.ts
hybridAuthenticate extracts attachSessionId from the request header/query param and injects it into all auth result paths via a shared session(token) helper. defineTool's execute callback forwards s?.attachSessionId to the tool run context.
Session key fingerprinting and lifecycle
src/lib/agent-client.ts
getSessionKey appends an attach#<hash> segment for attach-mode keys. getOrCreateSession expands to three modes (attach, profile-creation, fresh). closeSession and destroySession accept and forward attachSessionId to target the correct keyed session.
Agent tool threading and open-only branch
src/tools/agent.ts, src/skills/autonomous-login.md
All session lifecycle calls in registerAgentTools pass attachSessionId. Adds an open-only branch with try/catch that converts connection failures to UserError(formatConnectError(...)) and returns a readiness message. Autonomous-login docs clarify that post-login display names may differ from credentials entered.

loadSecret Command Schema

Layer / File(s) Summary
loadSecret schema, registration, and tests
src/tools/schemas.ts, test/tools/schemas.spec.ts
Defines LoadSecretCommandSchema (required params.ref, optional params.selector), registers it in specificCommandSchemas, and adds three test cases for valid and invalid inputs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • browserless/browserless-mcp#117: Directly related — introduces the createProfile/creationSessionId mode in getOrCreateSession, closeSession, and destroySession in src/lib/agent-client.ts, the same session-key and lifecycle functions this PR extends with attachSessionId.

Poem

🐇 Hop, hop, a session appears,
Pre-created and ready, no tears!
The x-browserless-session-id header arrives,
A key gets a hash, the attach mode thrives.
loadSecret now joins the command parade —
Credentials resolved, all neatly arrayed! 🔑

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is entirely missing. No summary, related issues, changes list, test plan, or checklist items are provided. Add a complete pull request description following the template, including summary of changes, related issues, test plan confirmation, and checklist items to indicate what was verified.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main feature being added: surfacing load secrets functionality from integrations, which aligns with the schema additions and tool implementation 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.

✏️ 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 feat/autologin-poc

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

@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

Caution

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

⚠️ Outside diff range comments (1)
src/lib/agent-client.ts (1)

234-246: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Align attach-mode session keying with attach-mode behavior.

When attachSessionId is present, getOrCreateSession skips createProfile, but getSessionKey still includes createProfile and raw attachSessionId. That can fragment cache keys for the same attached session, hurt reuse/cleanup targeting, and leak raw session-id material into key space.

Suggested fix
 const getSessionKey = (
   mcpSessionId: string | undefined,
   token: string,
   proxy?: ProxyOptions,
   profile?: string,
   createProfile?: CreateProfileParams,
   attachSessionId?: string,
 ): string =>
   (mcpSessionId ?? `stdio:${hashToken(token)}`) +
   proxyFingerprint(proxy) +
   (profile ? KEY_SEP + 'profile#' + hashToken(profile) : '') +
-  (createProfile ? KEY_SEP + 'create#' + hashToken(createProfile.name) : '') +
-  (attachSessionId ? KEY_SEP + 'attach#' + attachSessionId : '');
+  (!attachSessionId && createProfile
+    ? KEY_SEP + 'create#' + hashToken(createProfile.name)
+    : '') +
+  (attachSessionId
+    ? KEY_SEP + 'attach#' + hashToken(attachSessionId)
+    : '');

Also applies to: 639-651

🤖 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/lib/agent-client.ts` around lines 234 - 246, The getSessionKey function
includes both createProfile and raw attachSessionId in the key, but this
misaligns with how getOrCreateSession actually behaves—it skips createProfile
when attachSessionId is present. This causes cache key fragmentation and leaks
raw session ID material. Fix this by conditionally excluding createProfile from
the key when attachSessionId is provided, and hash the attachSessionId value
instead of including it raw (similar to how token, profile, and
createProfile.name are hashed), so the key generation logic matches the actual
session creation behavior.
🧹 Nitpick comments (1)
test/tools/schemas.spec.ts (1)

245-285: ⚡ Quick win

Add empty/whitespace ref negative cases to this block.

This suite checks missing ref, but not ref: '' or whitespace-only input. Adding both cases will harden the command contract and prevent silent regressions.

Suggested tests
 describe('loadSecret command', () => {
@@
   it('rejects a loadSecret command missing ref', () => {
@@
     expect(result.success).to.equal(false);
   });
+
+  it('rejects an empty ref', () => {
+    const result = AgentParamsSchema.safeParse({
+      commands: [{ method: 'loadSecret', params: { ref: '' } }],
+    });
+    expect(result.success).to.equal(false);
+  });
+
+  it('rejects a whitespace-only ref', () => {
+    const result = AgentParamsSchema.safeParse({
+      commands: [{ method: 'loadSecret', params: { ref: '   ' } }],
+    });
+    expect(result.success).to.equal(false);
+  });
 });
🤖 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 `@test/tools/schemas.spec.ts` around lines 245 - 285, The loadSecret command
test suite in the describe block currently only tests the case where ref is
completely missing, but does not test cases where ref is present but empty or
contains only whitespace. Add two additional test cases after the existing
negative test: one that uses safeParse to verify AgentParamsSchema rejects a
loadSecret command with ref set to an empty string, and another that verifies it
rejects a loadSecret command with ref set to a whitespace-only string (such as
spaces or tabs). Both tests should expect result.success to equal false to
ensure the schema contract prevents silent regressions from invalid ref 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 `@src/tools/agent.ts`:
- Around line 239-241: The text assignment logic currently prioritizes
createProfile over attachSessionId, but attach mode should take precedence
during session creation. Modify the ternary operator to check for
attachSessionId first before evaluating createProfile. When attachSessionId is
set, the text should return the generic browser session message or
attach-specific guidance instead of the profile-creation message, ensuring that
in mixed-input scenarios the correct guidance is provided based on which session
mode actually takes precedence.

In `@src/tools/schemas.ts`:
- Around line 168-178: Add validation to both the `ref` and `selector` fields to
prevent empty or whitespace-only strings. In the `ref` field definition, chain
`.trim().min(1)` after the `.describe()` method. In the `selector` field
definition, chain `.trim().min(1)` before the `.optional()` method so the
validation applies to non-empty trimmed strings when the field is provided. This
ensures both fields reject empty values and whitespace-only strings during
schema validation.

---

Outside diff comments:
In `@src/lib/agent-client.ts`:
- Around line 234-246: The getSessionKey function includes both createProfile
and raw attachSessionId in the key, but this misaligns with how
getOrCreateSession actually behaves—it skips createProfile when attachSessionId
is present. This causes cache key fragmentation and leaks raw session ID
material. Fix this by conditionally excluding createProfile from the key when
attachSessionId is provided, and hash the attachSessionId value instead of
including it raw (similar to how token, profile, and createProfile.name are
hashed), so the key generation logic matches the actual session creation
behavior.

---

Nitpick comments:
In `@test/tools/schemas.spec.ts`:
- Around line 245-285: The loadSecret command test suite in the describe block
currently only tests the case where ref is completely missing, but does not test
cases where ref is present but empty or contains only whitespace. Add two
additional test cases after the existing negative test: one that uses safeParse
to verify AgentParamsSchema rejects a loadSecret command with ref set to an
empty string, and another that verifies it rejects a loadSecret command with ref
set to a whitespace-only string (such as spaces or tabs). Both tests should
expect result.success to equal false to ensure the schema contract prevents
silent regressions from invalid ref 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6f4d666d-c882-41ad-8201-e9b30e5dc878

📥 Commits

Reviewing files that changed from the base of the PR and between f4b0122 and 1e3a402.

📒 Files selected for processing (8)
  • src/@types/types.d.ts
  • src/index.ts
  • src/lib/agent-client.ts
  • src/lib/define-tool.ts
  • src/skills/autonomous-login.md
  • src/tools/agent.ts
  • src/tools/schemas.ts
  • test/tools/schemas.spec.ts

Comment thread src/tools/agent.ts
Comment thread src/tools/schemas.ts
@andyMrtnzP andyMrtnzP marked this pull request as ready for review June 20, 2026 06:28
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.

1 participant