Repository navigation
Enter Microsoft 365 credentials in Settings, with prefilled Exchange commands and a Mail.Send check - #254
Enter Microsoft 365 credentials in Settings, with prefilled Exchange commands and a Mail.Send check#254thomassicaud wants to merge 4 commits into
Conversation
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>
|
@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. |
[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
SummaryThis PR adds Microsoft 365 credentials to Settings while keeping environment variables first.
|
| ) : null} | ||
|
|
||
| {status?.state === "graph" || status?.state === "graph_missing_config" ? ( | ||
| <Microsoft365Panel onStatus={setStatus} /> |
There was a problem hiding this comment.
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 ?? {})); |
There was a problem hiding this comment.
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.
| } catch { | ||
| return []; | ||
| } |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
Closes #76. Builds on #75 (
EMAIL_DRIVER=graph), so it targets that branch's changes; it will rebase cleanly ontomainonce #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 fourMICROSOFT_GRAPH_*variables.What it does
app_settings, encrypted withsecretKeyForfromseal-identity.ts(HKDF over the auth secret, AES-256-GCM) with its own context,signudoc/email-graph/v1. No new key variable.RESEND_FROM_EMAIL. An install configured entirely by variables behaves exactly as before and reads nothing from the database.BETTER_AUTH_SECRETchanges. 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.New-ServicePrincipal, management scope, role assignment,Test-ServicePrincipalAuthorization) with the entered client ID and mailbox filled in and quoted for PowerShell, ready to copy.rolesclaim containsMail.Send(tenant-wide consent in Entra), then sends the administrator a test email from the mailbox.settings_changed. The secret never appears in the audit record.Design choices worth a look
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=graphstill picks the driver.resolveEmailDriveris 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.isEmailNotConnectedError. For the same reasoncanSendEmailis now async (its only caller is the signup page, a server component).Tests
email-graph-settings.test.ts): environment versus stored precedence, a secret sealed under anotherBETTER_AUTH_SECRET, the not-connected error, theMail.Sendwarning from the token'srolesclaim, Microsoft's refusal message, and the PowerShell quoting.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 test514/514,npm run test:db415/415 on Postgres 17,npm run typecheck,npm run buildand lint (no new warnings).docs/self-hosting.md,
.env.exampleand the CHANGELOG are updated.🤖 Generated with Claude Code
Note
Add Microsoft 365 Graph email driver with Settings-based credential entry
graphas an email driver. The Graph sender obtains OAuth client-credentials tokens, caches them until near expiry, retries 429/503 responses usingRetry-After, and enforces a ~2.9 MB attachment limit versus the existing 25 MB Resend limit./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 addsgraph_tenant_id,graph_client_id, andgraph_client_secretcolumns toapp_settings.Mail.Sendinstead of a mailbox-scoped role.canSendEmail()is now async; callers like signup/page.tsx await it.EMAIL_DRIVER=graphchanges the sender-address variable toMICROSOFT_GRAPH_SENDER; the Microsoft admin endpoints return 409 when the driver is not graph; graph batches reject attachments.Macroscope summarized 8220539.