12 Commits

Author SHA1 Message Date
b5e772f51c feat: replace Cloudflare Access gate with Scribase owner-only auth
Cloudflare Access was permanently blocking this Worker (500 Cloudflare
Access must be configured in production): Zero Trust was never enabled
on the account and no available credential had Access-write scope.
Instead of waiting on that credential, access control now lives in code
against Scribase (this portfolio's self-hosted, Supabase-compatible
auth backend): a request is let through only if its Scribase access
token resolves to the exact OWNER_EMAIL account.

- workers/lib/scribase-auth.ts: token extraction, remote verification
  via GET /auth/v1/user, sign-in/refresh/sign-out via the password and
  refresh_token grants, with 25 unit tests.
- workers/lib/login-page.ts: dependency-free HTML sign-in page.
- workers/app.ts: new middleware (fail-closed on missing config, silent
  refresh-token retry, uniform 401 for API/MCP callers vs redirect for
  HTML), /login (rate-limited via a native Workers ratelimits binding)
  and /logout (also revokes the session server-side) routes. Removes
  the old jose/JWKS Cloudflare Access check entirely.
- wrangler.jsonc, .dev.vars.example, workers/types.ts, README.md:
  SCRIBASE_URL/SCRIBASE_ANON_KEY/OWNER_EMAIL replace
  POLICY_AUD/TEAM_DOMAIN; jose dropped from package.json.

Reviewed by code-reviewer and security-reviewer subagents; every
MEDIUM/HIGH finding fixed. Deployed and verified live: the Worker now
fails closed with the new Scribase message instead of the old
Cloudflare one. Provisioning the actual Scribase project is blocked on
a one-time $1 card check on the Scribase org (owner-only payment
action) -- see NOTES.md and ~/products/plans/agentic-inbox.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-24 17:10:54 +03:00
a60303e7b4 fix: guard folder rename against system folders, empty names, and dupes
PUT /api/v1/mailboxes/:id/folders/:id had no validation at all: any caller
could rename a system folder (inbox, sent, draft, archive, trash, spam) to
anything, rename it to an empty string, or collide its name with another
folder and trigger an unhandled SQLite UNIQUE-constraint exception.
deleteFolder already protected system folders via is_deletable -- give
updateFolder the same guard, reject empty names, and turn the UNIQUE
collision into a clean 409 instead of a 500.

Also notes that Cloudflare R2/AI/Durable Object infra is now actually
provisioned and the Worker is live at
https://agentic-inbox.subasiarhan3.workers.dev (fails closed pending the
owner-only Access + domain/Email Routing setup).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-22 03:48:31 +03:00
f2953ade9b feat: wire up vacation auto-reply and inbound forwarding settings
Mailbox settings already had forwarding{enabled,email} and
autoReply{enabled,subject,message} in the data model (set via the API),
but receiveEmail() never read them -- they were stored and silently
ignored. Add workers/lib/auto-respond.ts: maybeForwardEmail() sends a
copy of inbound mail to the configured address, and maybeSendAutoReply()
sends the configured vacation-responder reply once per thread per 24h
(enforced by new MailboxDO.shouldSendAutoReply, backed by DO storage so
it's wiped by purgeAllData() on mailbox delete). Both skip automated
senders/RFC 3834 Auto-Submitted messages and self-loops to avoid
auto-responder ping-pong. 14 new tests, full suite + typecheck pass.
2026-10-21 18:09:07 +03:00
0aac677af2 fix: purge DO data + R2 attachments on mailbox delete, fix draft-save ordering
Deleting a mailbox only removed its R2 settings file; the mailbox's
Durable Object (keyed by email address via idFromName, so a mailbox
recreated with the same address resolves to the same DO) kept every
email and attachment forever, silently resurrecting a "deleted"
mailbox's full history. Add MailboxDO.purgeAllData() to wipe the DO's
storage via storage.deleteAll() and return attachment keys for R2
cleanup, chunked at 1000 keys per R2Bucket.delete() call.

Also fix the drafts autosave endpoint: it deleted the superseded draft
before creating the new one, so a failure in createEmail() (DO
unavailable, storage error) silently lost the user's latest edits with
nothing left to recover. Create-then-delete means the same failure
just leaves a harmless duplicate instead of losing data.

Adds chunkArray() + tests; all 18 vitest tests and typecheck pass.
2026-10-21 15:44:16 +03:00
3548b394ab fix: carry original attachments over when forwarding an email
The web UI has no attachment-upload control, so Forward always sent the
new message with an empty attachments list — any attachment on the
original email was silently dropped instead of being included, unlike
every real email client. Copy the original email's R2-stored
attachments to the forwarded message's id and include them both in the
outgoing send and the stored Sent-folder copy.

Added workers/lib/attachments.test.ts (RED before the copyAttachments
implementation, GREEN after).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 03:39:51 +03:00
6a17c0580a fix: give the agent an explicit way to decline drafting a reply
handleNewEmail's auto-draft fallback treated any text the model
returned, without calling draft_reply/draft_email, as an inline draft
to save to the Drafts folder. The default system prompt gave the model
no supported way to decline a reply, so when it correctly judged an
email as spam, a sales pitch, or a newsletter and explained why in
plain text instead of calling a tool, that explanation got passed
through verifyDraft and saved as a nonsense draft addressed to the
sender — one click from being sent back to the spammer.

Add a skip_email tool the model can call instead of draft_reply, with
a short reason. handleNewEmail now checks for that tool call (only
when draft_reply/draft_email was NOT also called in the same run, so
an already-created draft's side effect always takes priority) and
logs "Skipped: <reason>" to the agent chat instead of falling through
to the inline-text draft fallback. DEFAULT_SYSTEM_PROMPT now documents
when to use it.

Fixes cloudflare/agentic-inbox#73.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 15:50:36 +03:00
90234d6437 fix: chunk long search values to avoid DO SQLite LIKE pattern limit
MailboxDO#buildSearchConditions wrapped the query/from/to/subject
search filters directly as `%value%` LIKE patterns. Durable Object
SQLite rejects LIKE patterns above roughly 50 characters with an HTTP
500 (confirmed empirically: a 48-char value -> 50-char pattern
succeeds, a 49-char value -> 51-char pattern 500s) — so any search
long enough, including a user searching by a long exact subject,
crashed the search endpoint instead of returning results or a
validation error.

Split search values longer than 48 characters into <=48-char chunks
before wildcarding, AND the per-chunk LIKE conditions together, so no
single bound pattern can exceed the limit. Long values degrade to an
"all chunks present" match rather than 500ing. Extracted into
workers/lib/like-search.ts as pure, independently testable helpers,
with unit tests covering the chunk boundary (incl. the 49-char value
from the original report) and multi-column conditions.

Also adds vitest (previously absent from this repo) with a standalone
vitest.config.ts, since the project's main vite.config.ts loads the
Cloudflare Workers runtime plugin which isn't needed for, and breaks
under, plain unit tests of pure logic.

Fixes cloudflare/agentic-inbox#36.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 15:50:25 +03:00
0a5a6a362a fix: route inbound mail by SMTP envelope recipient, not To: header
receiveEmail() picked the destination mailbox by parsing the message's
To: header. For mailing-list traffic the To: header is the list
address and the actual subscriber only appears in the SMTP envelope;
for BCC-only delivery and some forwarders the header doesn't name this
mailbox at all. In both cases the header-based lookup missed,
mailboxes/<address>.json was absent in R2, and the email was silently
dropped with no retry and no visible error — Email Routing's Activity
Log still shows Handled/pass.

Resolve the mailbox from the envelope recipient (event.to on
ForwardableEmailMessage — the RCPT TO address Email Routing actually
matched before invoking this Worker) instead. This is also strictly
more trustworthy than the header, which comes straight from
attacker-controlled raw email bytes. Header-parsed recipients are kept
only for the stored "recipient" display field, falling back to the
envelope address when the header has none.

Fixes cloudflare/agentic-inbox#32.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 15:50:04 +03:00
e402dc0a7d fix: resolve auto-draft agent stub via SDK handshake, not raw DO get
receiveEmail() called env.EMAIL_AGENT.get(idFromName(mailboxId)).fetch()
directly to trigger the auto-draft agent. partyserver's Server.fetch()
requires the Durable Object instance to already have a persisted name
before it will route a request; that name is normally set by the
set-name handshake the /agents/* route performs when the mailbox is
opened in the UI. A mailbox that only ever receives mail and is never
opened in the UI has no persisted name, so this call throws "Missing
namespace or room headers" and the auto-draft feature silently never
runs for it (the error was swallowed by the surrounding .catch()).

Resolve the agent stub through getAgentByName() from the "agents" SDK
instead, which performs the set-name handshake before returning the
stub.

Fixes cloudflare/agentic-inbox#57.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 15:49:33 +03:00
6a1cff38c9 fix: await real email delivery before confirming send as successful
The reply, forward, and new-email HTTP routes (used by the compose UI)
recorded the outgoing message in the Sent folder and returned
{status: "sent"} to the client BEFORE the actual delivery via the
Cloudflare Email Service binding had even started — sendEmail() was
fired through c.executionCtx.waitUntil() with a .catch() that only did
console.error(). A real delivery failure (bad domain config, a
suppressed/bounced recipient, API errors, etc.) was therefore
completely invisible to the operator: the UI shows "Email sent!", the
message sits in Sent, and the recipient never receives anything, with
no trace outside server logs.

The MCP/agent tool-calling path (toolSendReply/toolSendEmail in
workers/lib/tools.ts) already does this correctly — it awaits the real
send and only writes the Sent record on success, surfacing failures as
tool errors. Apply the same fix to handleReplyEmail and
handleForwardEmail (workers/routes/reply-forward.ts) and the direct
send endpoint (workers/index.ts): await sendEmail() first, return a
502 with the real error message if it throws, and only persist the
Sent record (and mark the thread read) once delivery is confirmed.
2026-10-18 00:51:47 +03:00
Thomas Gauvin
0d8e52ea57 Support full Access cert URLs for TEAM_DOMAIN 2026-04-16 23:50:39 -04:00
Thomas Gauvin
cff1a79a39 Agentic Inbox: self-hosted email client with AI agent on Cloudflare Workers 2026-04-16 00:54:30 -04:00