Skip to content

Enter Microsoft 365 credentials in Settings, with prefilled Exchange commands and a Mail.Send check - #254

Open
thomassicaud wants to merge 4 commits into
NYLLON-SOFTWARE:mainfrom
thomassicaud:feat/microsoft-365-settings
Open

thomassicaud wants to merge 4 commits into
NYLLON-SOFTWARE:mainfrom
thomassicaud:feat/microsoft-365-settings

Conversation

@thomassicaud

@thomassicaud thomassicaud commented Nov 23, 2026 •

Copy link
Copy Markdown

Closes #76. Builds on #75 (EMAIL_DRIVER=graph), so it targets that branch's changes; it will rebase cleanly onto main once #75 is merged.

With EMAIL_DRIVER=graph, an administrator can now enter the Microsoft 365 credentials in Settings, Organization, Email setup instead of setting the four MICROSOFT_GRAPH_* variables.

What it does

  • Credentials in Settings. Tenant ID, client ID, client secret and mailbox. The client secret is stored in app_settings, encrypted with secretKeyFor from seal-identity.ts (HKDF over the auth secret, AES-256-GCM) with its own context, signudoc/email-graph/v1. No new key variable.
  • Environment variables still win, field by field, and their fields are shown locked, as with RESEND_FROM_EMAIL. An install configured entirely by variables behaves exactly as before and reads nothing from the database.
  • BETTER_AUTH_SECRET changes. The form says the secret must be entered again if it changes, and a stored secret that can no longer be opened is reported as such, rather than as a generic sign-in failure.
  • Prefilled PowerShell. The page shows the Exchange commands (shared mailbox, New-ServicePrincipal, management scope, role assignment, Test-ServicePrincipalAuthorization) with the entered client ID and mailbox filled in and quoted for PowerShell, ready to copy.
  • Verify connection. Gets a fresh token, warns when its roles claim contains Mail.Send (tenant-wide consent in Entra), then sends the administrator a test email from the mailbox.
  • Saving or removing credentials clears the "email works" mark and is recorded as settings_changed. The secret never appears in the audit record.
  • Resend is left out, as you asked.

Design choices worth a look

  • The mailbox is the existing sender_address, not a new column. With Graph the sender has to be the mailbox the app may use, so storing it twice could only let the two drift apart.
  • EMAIL_DRIVER=graph still picks the driver. resolveEmailDriver is synchronous and called in many places. Picking Graph from stored settings would make all of them async, so I kept that out of this PR. Only the credentials move to Settings.
  • Because the credentials may now live in the database, the Graph email service looks them up when it sends, not when it is created. An unfinished setup still fails as isEmailNotConnectedError. For the same reason canSendEmail is now async (its only caller is the signup page, a server component).

Tests

  • Unit (email-graph-settings.test.ts): environment versus stored precedence, a secret sealed under another BETTER_AUTH_SECRET, the not-connected error, the Mail.Send warning from the token's roles claim, Microsoft's refusal message, and the PowerShell quoting.
  • Database (email-graph-settings.dbtest.ts): the secret is stored sealed, a blank secret keeps the saved one, validation, a variable-locked field is not saved, and removing credentials keeps the sender.
  • npm test 514/514, npm run test:db 415/415 on Postgres 17, npm run typecheck, npm run build and lint (no new warnings).

docs/self-hosting.md, .env.example and the CHANGELOG are updated.

🤖 Generated with Claude Code

Note

Add Microsoft 365 Graph email driver with Settings-based credential entry

  • Adds graph as an email driver. The Graph sender obtains OAuth client-credentials tokens, caches them until near expiry, retries 429/503 responses using Retry-After, and enforces a ~2.9 MB attachment limit versus the existing 25 MB Resend limit.
  • Credentials can be stored in Settings via new admin endpoints at /api/admin/email/microsoft (GET/PUT/DELETE/verify) instead of environment variables. Environment values take precedence per field; the stored client secret is sealed at rest, excluded from audit logs, and a blank submission keeps the existing secret. New migration 20261123090000_email_graph_settings.sql adds graph_tenant_id, graph_client_id, and graph_client_secret columns to app_settings.
  • Settings UI in microsoft-365-panel.tsx supports saving, verifying permissions, sending a test email, removing credentials, and copying prefilled Exchange Online PowerShell setup commands. Verification warns when the token has tenant-wide Mail.Send instead of a mailbox-scoped role.
  • canSendEmail() is now async; callers like signup/page.tsx await it.
  • Behavioral Change: EMAIL_DRIVER=graph changes the sender-address variable to MICROSOFT_GRAPH_SENDER; the Microsoft admin endpoints return 409 when the driver is not graph; graph batches reject attachments.

Macroscope summarized 8220539.

thomassicaud-asi and others added 4 commits November 17, 2026 16:32
Organizations whose mail already lives in Microsoft 365 can send from one
of their own mailboxes through Microsoft Graph instead of bringing in
Resend. The app signs in with OAuth client credentials and calls
POST /users/{mailbox}/sendMail, with no new dependency.

- New driver in src/lib/services/email-graph.ts: token cache, retries on
  429/503 within the same bounds as Resend, one token refresh on 401, and
  Microsoft's own error words passed through to the test email.
- MICROSOFT_GRAPH_SENDER fixes the sender, like RESEND_FROM_EMAIL does;
  Settings names whichever variable is in use.
- Settings, Organization shows a Microsoft 365 status instead of the
  Resend domain steps, and asks for a test email to confirm the mailbox.
- Attachments above about 3 MB go out as links, since Graph takes at most
  4 MB per message.
- docs/self-hosting.md explains how to scope the app to that one mailbox
  with Exchange RBAC for Applications.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Addresses two review notes on NYLLON-SOFTWARE#75:

- One Graph sender per configuration for the whole process, so the token
  is reused by every email service instead of fetched again for each
  envelope. A rotated secret or another mailbox gets a sender of its own.
- A 401 that follows a throttled try now still replaces the token once:
  token refresh and throttling retries are counted apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With EMAIL_DRIVER=graph, an administrator can enter the tenant ID, client
ID, client secret and mailbox in Settings, Organization, Email setup
instead of setting the MICROSOFT_GRAPH_* variables (issue NYLLON-SOFTWARE#76).

- The client secret is stored in app_settings, encrypted with a key
  derived from BETTER_AUTH_SECRET (secretKeyFor, context
  signudoc/email-graph/v1). Settings says it must be entered again if that
  secret changes, and reports a stored secret it can no longer read.
- Each variable still wins over what is stored, field by field, and its
  field is shown locked. The mailbox is the install's sender address, so
  it is not stored twice.
- Settings shows the Exchange PowerShell (shared mailbox, management
  scope, role assignment, Test-ServicePrincipalAuthorization) with the
  entered IDs filled in, ready to copy.
- Verify connection signs in with a fresh token, warns when its roles
  claim carries Mail.Send (tenant-wide consent in Entra), and sends a
  test email.
- Saving or removing credentials clears the email-ready mark and is
  recorded as settings_changed, without the secret.
- The Graph email service looks its credentials up when it sends, and an
  unfinished setup fails as email not being connected. canSendEmail is
  now async for that reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 23, 2026

Copy link
Copy Markdown

@thomassicaud-asi is attempting to deploy a commit to the Basic Intelligence Team on Vercel.

A member of the Team first needs to authorize it.

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The changes affect outbound email across the app when an operator selects the Graph driver.

Fix the mailbox overwrite and separate audit commit before merging.

Findings

  1. P1 Organization saves overwrite the mailbox ▶
  2. P1 Credential changes can go unrecorded ▶
  3. P2 Unreadable permissions look safe ▶
  4. P2 Old tests approve new credentials ▶

Summary

This PR adds Microsoft 365 credentials to Settings while keeping environment variables first.

  • Microsoft Graph sends app email from one configured mailbox.
  • Admins can set up Microsoft 365 email from Settings.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Administrator] --> B[Microsoft 365 settings]
  B --> C[Require administrator]
  C --> D[Save encrypted credentials and mailbox]
  D --> E[(App settings)]
  D --> F[Write audit event separately]
  B --> G[Verify connection]
  G --> H[Get fresh token]
  H --> I[Read Mail.Send roles]
  I --> J[Send test email]
  E --> K[Resolve email configuration]
  L[Environment variables] --> K
  K --> M[Send through Microsoft Graph]
Loading

Reviews (1) · Last reviewed commit: "Enter Microsoft 365 credentials in Setti..." · Reviewed by Greptile

) : null}

{status?.state === "graph" || status?.state === "graph_missing_config" ? (
<Microsoft365Panel onStatus={setStatus} />

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Organization saves overwrite the mailbox

Saving a mailbox in Microsoft365Panel leaves the Organization form's values.senderAddress unchanged. With no MICROSOFT_GRAPH_SENDER variable, saving an unrelated Organization setting sends that old address and overwrites the mailbox just saved. If the old address is empty or outside the Exchange grant, email stops working. Pass the saved mailbox back to the Organization form, or keep this shared value in one place.

const body: unknown = await request.json().catch(() => null);

try {
await audit(request, session, await saveGraphSettings(body ?? {}));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Credential changes can go unrecorded

saveGraphSettings commits before audit runs. If the audit insert fails, the credentials have already changed, but the route returns an error and leaves no record of the change. Removing credentials has the same problem. Write the settings and settings_changed event in one transaction, as the existing Organization settings route does.

Comment on lines +402 to +404
} catch {
return [];
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Unreadable permissions look safe

If Microsoft returns a token the app cannot read, readTokenRoles returns an empty list and checkGraphPermissions treats that as proof that Mail.Send is absent. After a successful test email, the page then claims there is no organization-wide permission. Keep an unreadable token distinct from a readable token with no roles, and show an inconclusive check instead of a clean result.

graph_client_id = $2,
graph_client_secret = $3,
sender_address = $4,
email_ready_at = null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Old tests approve new credentials

Clearing email_ready_at does not protect against a test email already in progress. A test can send with the old credentials, then an administrator saves new credentials for the same mailbox. When the old test finishes, markEmailReady checks only the mailbox and restores the ready mark for the untested credentials. Tie the test result to the credential version as well as the sender.

This branch has not been deployed

No deployments
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.

"Connect to Microsoft 365" in Settings, without granting tenant-wide Mail.Send

2 participants