Skip to content

feat: add secure SMTP App Password onboarding - #4

Merged
404Dealer merged 10 commits into
masterfrom
feat/smtp-app-password-provider
Jul 10, 2026
Merged

404Dealer merged 10 commits into
masterfrom
feat/smtp-app-password-provider

Conversation

@404Dealer

@404Dealer 404Dealer commented Jul 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add a generic authenticated email-smtp provider with mandatory implicit TLS or required STARTTLS
  • add Gmail App Password onboarding through a human-only, root-owned wrapper that drops privileges to agentgate
  • verify Gmail SMTP credentials before storing one versioned password in the isolated pass store
  • propagate partial recipient acceptance through provider, executor, audit, and Telegram as a visible non-retryable warning
  • preserve accepted-delivery semantics even if local archive/audit finalization or Telegram notification fails
  • install/package the new agent-gate-smtp-setup binary and production wrapper
  • document the simpler Gmail SMTP path and its broader credential-scope trade-off versus gmail.send OAuth

Security properties

  • no password/secret CLI arguments or password environment-variable handoff
  • real TTY and non-root runtime checks
  • fixed executable PATH; every existing PATH directory must be root-owned and non-writable by group/world
  • root-owned trusted ancestor validation for wrapper, runtime, and resolved executables
  • pass is resolved before secret entry and forwarded as an absolute pinned executable path
  • runtime ${PASS:...} expansion uses execFileSync, not a shell
  • clean environment after privilege drop to agentgate
  • certificate verification always enabled; unencrypted SMTP unsupported
  • file and URL access disabled in Nodemailer
  • raw SMTP errors and unsafe server-controlled message IDs are not exposed
  • versioned password key plus atomic private-config update
  • draft from remains ignored; configured fromAddress is approved and sent
  • SMTP sender must match the authenticated username unless allowFromAlias: true is explicitly configured
  • partial SMTP acceptance is archived as sent, audited as partial, and shown as a Telegram warning to prevent duplicate retry
  • post-acceptance local bookkeeping failures are never reclassified as send failures

Verification

  • npm test — 92/92 passing
  • npm run build — passing
  • installed-tarball test covers agent-gate, agent-gate-oauth, and agent-gate-smtp-setup
  • npm pack --dry-run — expected 39 files, including SMTP runtime/docs
  • npm audit --omit=dev — 0 vulnerabilities
  • git diff --check — clean
  • bash -n scripts/*.sh — clean
  • ShellCheck — clean when available
  • adversarial test rejects an attacker-writable executable PATH before child launch
  • executor/bot tests cover partial delivery, post-acceptance persistence failure, callback-before-SMTP ordering, and Telegram notification failure

Review fixes incorporated

  • omit SMTP SNI for IP literals while retaining certificate verification
  • pin privileged wrapper startup tools and the pass executable
  • exclude local .hermes/ planning state from production deployment
  • replace inaccurate App Password success wording
  • surface partial recipient acceptance explicitly to operators
  • require explicit sender-alias opt-in
  • refresh npm binary metadata and pin Nodemailer exactly
  • preserve accepted-delivery semantics across local persistence and Telegram notification failures
  • acknowledge Telegram approval callbacks before potentially slow SMTP work
  • require complete structured fields for every typed partial result and normalize SMTP usernames before authentication
  • make normal-runtime password-store writes honor the installer-pinned absolute AGENT_GATE_PASS_BIN; adversarial PATH substitution is covered by test

Independent review

  • latest-head password-store executable pinning recheck — PASS
  • latest-head SMTP delivery-state and Telegram outcome recheck — PASS
  • targeted review suite — 25/25 passing
  • no blocking findings remain

Production verification

  • live /opt/agent-gate installation upgraded successfully
  • Gmail App Password verified over TLS and stored only in the isolated agentgate password store
  • agent-gate.service restarted healthy with production isolation checks passing
  • controlled self-addressed message was explicitly approved in Telegram and received successfully

@cursor

cursor Bot commented Jul 10, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds authenticated SMTP email delivery, Gmail App Password onboarding, secure password-store integration, structured partial-delivery results, Telegram delivery notifications, deployment wiring, tests, and operator documentation.

Changes

SMTP delivery and secure onboarding

Layer / File(s) Summary
SMTP provider contract and delivery implementation
src/config.ts, src/providers/*, config.example.yaml, README.md, package.json, tests/smtp-provider.test.ts
Adds validated email-smtp configuration, Nodemailer delivery with implicit TLS or STARTTLS, sender enforcement, redacted failures, and partial recipient results.
Gmail App Password onboarding
src/smtp-setup.ts, src/smtp/*, src/oauth/*, scripts/smtp-setup.sh, scripts/install-production.sh, tests/smtp-setup.test.ts, tests/oauth-setup.test.ts, tests/package.test.ts
Adds interactive Gmail setup, password normalization and verification, versioned secret persistence, trusted executable handling, privilege dropping, service restart checks, and a published setup command.
Structured delivery outcomes and Telegram notifications
src/executor.ts, src/bot.ts, tests/executor.test.ts
Preserves sent, partial, failed, and persistence-warning outcomes through execution, auditing, and Telegram approval notifications.
Deployment and credential-handling documentation
README.md, docs/*.md, .gitignore
Documents SMTP setup, operator-only credential handoff, deployment checks, Hermes boundaries, and SMTP delivery behavior; .hermes/ is ignored.

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

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant smtp-setup.sh
  participant smtp-setup.ts
  participant pass
  participant agent-gate.service
  Operator->>smtp-setup.sh: start Gmail setup
  smtp-setup.sh->>smtp-setup.ts: run with trusted environment
  smtp-setup.ts->>smtp-setup.ts: verify Gmail SMTP credentials
  smtp-setup.ts->>pass: store SMTP password
  smtp-setup.ts->>agent-gate.service: write provider configuration
  smtp-setup.sh->>agent-gate.service: restart and health-check
Loading

Possibly related PRs

🚥 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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: secure SMTP App Password onboarding.
✨ 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/smtp-app-password-provider

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.

@cursor

cursor Bot commented Jul 10, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@404Dealer
404Dealer marked this pull request as ready for review July 10, 2026 04:11
Copilot AI review requested due to automatic review settings July 10, 2026 04:11

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 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 `@config.example.yaml`:
- Around line 20-29: Update the gmail-smtp example to match the isolated pass
onboarding flow: replace the direct GMAIL_APP_PASSWORD environment reference
with a PASS-based credential reference, or revise the comments to direct
operators to agent-gate-smtp-setup for storing and configuring the App Password.

In `@docs/deployment.md`:
- Around line 161-170: Update the deployment documentation near the gmail-smtp
configuration to explicitly instruct operators to set defaults.provider to
"gmail-smtp" when SMTP delivery is intended, or clearly state that the provider
remains non-default and logging is used otherwise.

In `@src/config.ts`:
- Around line 119-123: Move AGENT_GATE_PASS_BIN resolution and its isAbsolute
validation out of the try block in the placeholder/pass-resolution function,
while keeping only execFileSync and related lookup failures inside the
try/catch. Preserve the specific “Configured pass executable must be absolute”
error so it is not replaced by the generic unresolved-placeholder error.

In `@src/oauth/persist.ts`:
- Around line 89-104: Make the credential write and provider configuration
update reconcilable in the persistence flow containing transactionId,
passReference, and updateProviderConfig. Track whether the password-store write
and configuration commit completed, and on failures reconcile the persisted
configuration before retaining or removing the newly created secret; if the
config already references it, keep the secret, otherwise clean up the
unreferenced credential. Ensure retries do not create unnecessary additional
credential versions.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: d001685b-e3d4-4658-a50a-b51127f155df

📥 Commits

Reviewing files that changed from the base of the PR and between c932474 and b32003f.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (27)
  • .gitignore
  • README.md
  • config.example.yaml
  • docs/credential-handoff.md
  • docs/deployment.md
  • docs/hermes.md
  • docs/smtp-onboarding.md
  • package.json
  • scripts/install-production.sh
  • scripts/smtp-setup.sh
  • src/bot.ts
  • src/config.ts
  • src/executor.ts
  • src/oauth/config-writer.ts
  • src/oauth/persist.ts
  • src/oauth/secret-store.ts
  • src/providers/email-smtp.ts
  • src/providers/index.ts
  • src/smtp-setup.ts
  • src/smtp/cli-options.ts
  • src/smtp/normalize.ts
  • src/smtp/verify.ts
  • tests/executor.test.ts
  • tests/oauth-setup.test.ts
  • tests/package.test.ts
  • tests/smtp-provider.test.ts
  • tests/smtp-setup.test.ts

Comment thread config.example.yaml
Comment on lines +20 to +29
# Simplest self-hosted Gmail path: create a dedicated Google App Password,
# store it under agentgate, and use authenticated SMTP over implicit TLS.
gmail-smtp:
type: "email-smtp"
host: "smtp.gmail.com"
port: 465
tlsMode: "implicit"
username: "[email protected]"
password: "${GMAIL_APP_PASSWORD}"
fromAddress: "[email protected]"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Align this example with the isolated pass onboarding path.

Line 28 reads the App Password from the service environment, while the comments and onboarding flow promise storage in the isolated password store. Direct operators to agent-gate-smtp-setup or demonstrate a PASS reference instead.

🤖 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 `@config.example.yaml` around lines 20 - 29, Update the gmail-smtp example to
match the isolated pass onboarding flow: replace the direct GMAIL_APP_PASSWORD
environment reference with a PASS-based credential reference, or revise the
comments to direct operators to agent-gate-smtp-setup for storing and
configuring the App Password.

Comment thread docs/deployment.md
Comment on lines +161 to +170
gmail-smtp:
type: "email-smtp"
host: "smtp.gmail.com"
port: 465
tlsMode: "implicit"
username: "[email protected]"
password: "${PASS:agent-gate/smtp-password-VERSION}"
fromAddress: "[email protected]"
displayName: "Your Name"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Document or select the SMTP default provider.

The manual configuration adds gmail-smtp, but the example’s defaults.provider remains log. An operator following this configuration will not send email through Gmail SMTP; drafts will continue using the log-only provider. Add an explicit instruction to set defaults.provider: "gmail-smtp" when SMTP delivery is intended, or clearly label the provider as non-default.

🤖 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 `@docs/deployment.md` around lines 161 - 170, Update the deployment
documentation near the gmail-smtp configuration to explicitly instruct operators
to set defaults.provider to "gmail-smtp" when SMTP delivery is intended, or
clearly state that the provider remains non-default and logging is used
otherwise.

Comment thread src/config.ts
Comment on lines +119 to +123
const passExecutable = process.env.AGENT_GATE_PASS_BIN ?? 'pass';
if (process.env.AGENT_GATE_PASS_BIN && !isAbsolute(passExecutable)) {
throw new Error('Configured pass executable must be absolute');
}
return execFileSync(passExecutable, ['show', key], { encoding: 'utf8' }).trimEnd();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Move the AGENT_GATE_PASS_BIN absolute-path check outside the try block.

The check at line 120–122 throws a specific, actionable error ("Configured pass executable must be absolute"), but it's inside the try at line 118, so the catch at line 124 swallows it and replaces it with the generic "Unresolved placeholder: ${PASS:key}". An operator who misconfigures the env var gets a misleading message pointing at the placeholder, not the real cause.

Proposed fix
     try {
-      const passExecutable = process.env.AGENT_GATE_PASS_BIN ?? 'pass';
-      if (process.env.AGENT_GATE_PASS_BIN && !isAbsolute(passExecutable)) {
-        throw new Error('Configured pass executable must be absolute');
-      }
       return execFileSync(passExecutable, ['show', key], { encoding: 'utf8' }).trimEnd();
     } catch {
       throw new Error(`Unresolved placeholder: \${${name}}`);
     }

Move the executable resolution and validation above the try:

+    const passExecutable = process.env.AGENT_GATE_PASS_BIN ?? 'pass';
+    if (process.env.AGENT_GATE_PASS_BIN && !isAbsolute(passExecutable)) {
+      throw new Error('Configured pass executable must be absolute');
+    }
     try {
       return execFileSync(passExecutable, ['show', key], { encoding: 'utf8' }).trimEnd();
     } catch {
       throw new Error(`Unresolved placeholder: \${${name}}`);
     }
📝 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
const passExecutable = process.env.AGENT_GATE_PASS_BIN ?? 'pass';
if (process.env.AGENT_GATE_PASS_BIN && !isAbsolute(passExecutable)) {
throw new Error('Configured pass executable must be absolute');
}
return execFileSync(passExecutable, ['show', key], { encoding: 'utf8' }).trimEnd();
const passExecutable = process.env.AGENT_GATE_PASS_BIN ?? 'pass';
if (process.env.AGENT_GATE_PASS_BIN && !isAbsolute(passExecutable)) {
throw new Error('Configured pass executable must be absolute');
}
try {
return execFileSync(passExecutable, ['show', key], { encoding: 'utf8' }).trimEnd();
} catch {
throw new Error(`Unresolved placeholder: \${${name}}`);
}
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync } from 'node:child_process';
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🤖 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/config.ts` around lines 119 - 123, Move AGENT_GATE_PASS_BIN resolution
and its isAbsolute validation out of the try block in the
placeholder/pass-resolution function, while keeping only execFileSync and
related lookup failures inside the try/catch. Preserve the specific “Configured
pass executable must be absolute” error so it is not replaced by the generic
unresolved-placeholder error.

Comment thread src/oauth/persist.ts
Comment on lines +89 to +104
const id = transactionId();
const passwordKey = versionedKey('smtp-password', id);
await options.store.set(passwordKey, options.password);

const provider: Record<string, unknown> = {
type: 'email-smtp',
host: options.host,
port: options.port,
tlsMode: options.tlsMode,
username: options.username,
password: passReference(passwordKey),
fromAddress: options.fromAddress
};
if (options.displayName) provider.displayName = options.displayName;

await updateProviderConfig(options.configPath, options.providerName, provider, options.setAsDefault);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make password-store and configuration commits reconcilable.

A failure before updateProviderConfig renames the file leaves an unreferenced App Password; a failure after rename—such as directory fsync—can report failure despite the config already referencing it. Retrying then creates additional credential versions.

Return commit state or reconcile the written config before deciding whether to retain or remove the new secret.

🤖 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/oauth/persist.ts` around lines 89 - 104, Make the credential write and
provider configuration update reconcilable in the persistence flow containing
transactionId, passReference, and updateProviderConfig. Track whether the
password-store write and configuration commit completed, and on failures
reconcile the persisted configuration before retaining or removing the newly
created secret; if the config already references it, keep the secret, otherwise
clean up the unreferenced credential. Ensure retries do not create unnecessary
additional credential versions.

@404Dealer
404Dealer merged commit 43148b6 into master Jul 10, 2026
2 checks passed
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