Navigation
ELOWEN · Documentation

Last updated: October 27, 2026

Browse documentation · Microsoft 365 operations
Developer reference

msteams — operations

Running the plugin in production: Azure setup, what each config field actually changes, failure modes and what they look like in the log. The code walkthrough is in architecture.md; the config reference and file map are in maintainer.md.


Selected-work rollout and recovery

Apply core before the coordinated plugin candidate. The loader applies SQL-only tasks v1 then digest v2; fresh/repeat/v1-upgrade fixtures cover the ledger. Never reset the task journal to retry an unknown create: keep operationId, inspect remote tasks and obtain genuinely new approval if needed. Retain the journal on code rollback; an old create path forfeits durable dispatch protection.

Do not grant every possible scope. Use the operation matrix in permissions.md; flags do not request consent themselves. Transcript and Presence are default-off instance booleans under existing Microsoft 365 settings. Transcript rollout needs administrator-approved OnlineMeetingTranscript.Read.All and optional OnlineMeetings.Read for join-URL lookup. Presence is instantaneous and never a background attendance poller. Personal Email credentials do not authorize these tools.

Digest is independently default-off per human account, in the existing MS Teams Settings tab. Ordinary users see only their own toggle and selection cards, never credentials or people-administration hooks. The local preference is canonical; there is no m365DigestEnabled config or enable tool. A human explicitly enables it, after selecting files or libraries using reviewed existing tool actions. No new page/navigation exists.

Public HTTPS publicWebUrl must route existing /hooks/msteams/digest to the plugin. Do not log raw query strings: channel is a secret. Callbacks authenticate nonce/clientState hashes and are hints, never arbitrary prompts. Digest uses core alerts only. Files.ReadWrite.All is the supported delegated subscription lifecycle bundle; CREATE's lower Files.Read.All table alone does not establish renewal/removal permission.

Disable/removal stop local reads immediately; cleanup_pending means remote deletion is not confirmed. Unlink/rebind/sign-out attempts cleanup before invalidating credentials and preserves failures. Removed accounts lose local rows even if cleanup cannot authenticate; requested one-hour subscription expiration bounds remote leftovers. An unconfigured, stopped, disabled or uninstalled plugin cannot renew. Process stop retains recoverable subscriptions, not a disconnect claim. Restart recovers interrupted subscription POSTs via callback nonce hashes; it never blindly repeats an unknown create.

Failures remain visible: grant/identity/403 failures disable opt-in and require a fresh human decision after reconnect; expired delta is a silent baseline reset, not a burst of false deletion alerts. Large libraries exceeding 2,000 indexed files or twenty pages fail explicitly. Generic 403 is neither licence nor consent evidence. Mock-only suites do not establish real tenant access.

1. Azure app registration

The click-path is carried in the manifest itself, as the sec_connection section help in elowen-plugin.json, so the Settings UI shows it next to the fields:

  1. Entra admin center → App registrations → New registration, single tenant. Copy the Application (client) ID → appId, and the Directory (tenant) ID → tenantId.
  2. Certificates & secrets → New client secret → appPassword.
  3. Azure portal → Create an Azure Bot bound to that app id. Set the messaging endpoint to https://<your-domain>/hooks/msteams/messages and enable the Microsoft Teams channel.

The plugin authenticates outbound calls as this app registration, against https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/token for the https://api.botframework.com/.default scope (TokenSource in lib/token.mjs, SCOPE in lib/connector.mjs).

Inbound, it verifies Microsoft's JWT with the audience pinned to appId and the issuer pinned to https://api.botframework.com (makeTokenVerifier in lib/auth.mjs). The issuer being the connector service and not your tenant is correct and deliberate — the tenant-scoped issuer applies to user tokens, never to service-to-bot callbacks (see the comment at the top of lib/auth.mjs).

2. The Teams app package

The plugin builds the sideloadable package itself from the live config — there is no file to maintain.

  • Served at GET /plugins/msteams/app-package, admin-only, as chetty-teams-app.zip (register in index.mjs).
  • The route is registered before the credential check on purpose (register in index.mjs): while the plugin is enabled but unconfigured it answers 503, not 404. Registering it after the gate would make an enabled-but-unconfigured instance look like a missing route.
  • Contents (buildAppPackage in lib/appPackage.mjs): manifest.json, a 192 px colour icon and a 32 px white outline.png, in a hand-rolled stored (uncompressed) ZIP. The colour icon is the PNG named by appIconPath when set, otherwise a solid Teams-purple square.
  • Each download reads ctx.publicWebUrl() from core deployment metadata. Its normalized origin fills all three developer links and the optional channel-message RSC resource. Missing or unusable metadata returns the existing HTTP 500 error; no environment variable or upstream-project URL substitutes for it.
  • The Teams manifest (appManifest in lib/appPackage.mjs, schema version in MANIFEST_VERSION) sets id and botId to your appId, scopes the bot to personal, team and groupChat, declares supportsFiles: true and supportsTargetedMessages: true, sets validDomains (token.botframework.com only when personal-chat sign-in is on, otherwise empty) and the permissions identity and messageTeamMembers. The command lists take the first twelve entries of helpCommands(), the host's live chat commands plus the synthetic display entry that ADAPTER_STATE_COMMANDS adds. Team and group chats offer them in the / menu and after an @mention; personal chats offer them after an @mention only. The same list backs /help.
  • The package version is a UTC build stamp (packageVersion). Teams refuses an upload whose version is not higher than the one already in the catalog, so every download carries a newer number.

Upload it in Teams admin center → Manage apps. tests/msteams.test.ts verifies the ZIP framing, the manifest id/botId/scopes/icons and that both PNGs are really there.

3. The webhook route

register in index.mjs mounts messages, which the daemon serves at /hooks/msteams/messages. The bearer-auth layer treats /hooks/* as public (src/api/auth.ts) — the plugin authenticates every request itself.

Your reverse proxy must forward /hooks/ to the daemon port, before the catch-all / location. The managed nginx vhost that elowen setup writes already does (src/cli/install/proxy.ts), and the config health check reports <vhost> does not route /hooks/ with a fix hint when it does not (src/api/routes/system.ts).

Symptom of a missing proxy rule: the Azure Bot channel health check fails and nothing at all appears in the daemon log — the request never reaches the plugin.

4. What the config fields do at runtime

The full table is in maintainer.md. Operationally, the ones with consequences beyond cosmetics:

  • rolePolicies is the access boundary. First match wins, and a sender matching no policy is ignored in complete silence — no reply, no log line, no outbound traffic (the accessFor check in handleActivity). If "the bot ignores me" is the report, this is almost always the cause.
    • A roleId may be an Entra object ID (a GUID), a UPN/e-mail, or a whole conversation id, which grants everyone in that chat. Matching is case-insensitive whenever either side contains an @ (sameId in lib/ids.mjs) — so UPNs, e-mails and conversation ids like 19:…@thread.tacv2 are all case-insensitive; only GUIDs and 29: account ids must match exactly.
    • For a team channel, either the full 19:…@thread.tacv2;messageid=… form or the bare 19:…@thread.tacv2 from a Teams deep link works (senderIds in lib/ids.mjs).
    • admin: true marks the operator: it unlocks /model, /reasoning, /display, /context, /stats, /compact and /stop, lets that person act on a card opened by someone else, and drives senderIsAdmin (lib/ids.mjs).
  • respondWithoutMention only affects non-personal conversations. A personal chat always answers (the mention gate in handleActivity). A team-channel post reaches the bot without a mention only when channel message consent is active (see permissions.md). Otherwise Teams delivers a team-channel post only when the bot is @mentioned, and this setting does not change that.
  • historyLimit is the only field that makes the plugin persist message text to disk. 0 (the default) writes nothing at all. Lowering it takes effect on the next recorded message, which trims the stored list to the new limit rather than leaving a tail a later raise would resurrect (recordHistory in lib/transcript.mjs).
  • language changes the bot's own service texts only (errors, command replies); the agent answers in the user's language regardless. Note the coverage is uneven: the service texts exist in all three languages (lib/messages.mjs), but Adaptive Card button labels are switched by a single language === 'cs' boolean (the cs flag passed to buildAskCard and buildPickerCard in lib/cards.mjs, set in TeamsAsks and TeamsCommands), so with language: 'sk' the buttons ("Submit", "➤ Send custom answer", "‹ Prev", "Next ›") come out in English.
  • toolActivity / answerMode / toolOutput / toolMessageMode are global defaults; each is overridable per chat with /display. The /display card has a default option on every axis, which removes that axis's override (updateDisplayOverrides, used by TeamsCommands).

Per-channel / per-role policy in practice

Access is per sender, not per channel — but a policy whose roleId is a conversation id applies to the whole room, which is how a channel-wide policy is expressed. The matched policy contributes the role name, the extra role prompt and the admin flag; the conversation's own state contributes the model and the reasoning level (elowen-plugin-shared/access.mjs, buildRoleAccess). Project and tool scope are not part of that descriptor at all — they come from the linked account.

admin: true in a role policy grants the operator role inside the chat for platform behavior such as slash commands. It does not decide which Teams* tools the person may call. Tool availability comes from the linked account's plugin grants and per-user tool deny-list in the users modal.

5. The notify (cron) target

notifyConversationId is where a scheduled job's result lands when the job names no channel of its own. A scheduled job may override it with its own notifyChannelId.

Either value may be:

  • a conversation id the bot has already seen, or
  • a person — e-mail, Entra object ID, 29:… account id or display name — whose 1:1 chat the plugin opens and then remembers (notifyConversationFor in lib/proactive.mjs).

Every way a push can be dropped has its own warning:

Log line (all warn) Cause
msteams notify: no target — set the plugin's notifyConversationId, or give the job a notifyChannelId … (notify in lib/proactive.mjs) Neither the job nor the config named anywhere.
msteams notify: no serviceUrl known yet — send the bot one message first (notify) The bot has never received an activity, so there is no service host to send through.
msteams notify: "<x>" matches N people — name the person exactly or use their e-mail; the push was dropped (notifyConversationFor) An ambiguous display name. It is refused, never guessed.
msteams notify: could not open a conversation with <x> (notifyConversationFor) Teams accepted the create call but returned no conversation id.
msteams notify: could not reach <x>: … (notifyConversationFor) Resolving or opening the conversation threw (see §6).

An explicit destination:msteams: envelope does not drop silently. It rejects instead, so the consumer can keep its notice pending and retry.

6. The optional Microsoft Graph layer

Off by default. With graphLookup unset or false, no GraphClient is constructed at all (the adapter constructor in lib/adapter.mjs), so no directory Graph call is even possible — tests/msteams.test.ts asserts zero outbound requests on an unknown e-mail in that state.

Layer 1 (the people directory) needs no Microsoft permission whatsoever: it is assembled from inbound activities and conversation rosters the bot already reads. Turn Graph on only when you need the bot to write to people it has never met.

Every application Graph request, including channel history and profile photos, has a 15-second per-request deadline covering both response headers and the complete response body. The client uses AbortSignal.timeout and does not retry. Token requests for both Graph and the Bot Connector have their own 15-second deadline, including successful JSON and failed-request diagnostic bodies. The Graph request's deadline starts after its token is obtained, so these are separate budgets, not a whole-turn limit. An aborted token refresh releases the shared in-flight promise; a later caller can refresh again.

A channel-history timeout follows the existing recorded-history fallback, logging the Graph failure once per adapter. Directory lookup, app installation and photo timeouts reject through their existing caller error handling. Completed Graph 401/403 responses still report application consent instructions, while optional photo refusals keep their avatar fallback and five-minute permission cooldown. The delegated Microsoft 365 client keeps its own request deadlines and refusal handling.

What a Microsoft admin must grant

This section covers the app-only Graph layer alone. For the full picture — the four separate consent surfaces, the delegated Microsoft 365 scopes, resource-specific consent and a per-tenant setup checklist — see permissions.md.

Both are application permissions on the bot's app registration, and both need tenant admin consent:

Permission Needed for
User.ReadBasic.All Resolving an e-mail to a tenant user (findUser in lib/graph.mjs).
TeamsAppInstallation.ReadWriteSelfForUser.All Installing the Teams app for that user so a 1:1 chat can be opened (installApp in lib/graph.mjs).

Path: Entra admin center → App registrations → the bot's app → API permissions → Add a permission → Microsoft Graph → Application permissions → the permission → Grant admin consent for the tenant. The plugin quotes exactly this back at you when Graph answers 401/403, instead of forwarding a bare status (consentHelp and GraphClient.call in lib/graph.mjs). Pinned by tests/msteams.test.ts.

Additionally, installing the app for a user requires graphCatalogAppId — the app's id in the org Teams catalog (Teams admin center → Manage apps → the uploaded Elowen app), which is not the bot's appId. Leave it empty only when the app is already deployed to users by Teams app policy; the plugin then skips the install and opens the chat directly (findPersonViaGraph in lib/proactive.mjs).

Graph failure modes, all translated into an instruction rather than a status code:

An e-mail is resolved in two steps (findUser in lib/graph.mjs): a direct GET /users/{address} first, which covers the common case where the e-mail is the UPN, then a $filter search on mail or userPrincipalName for users whose mail differs. An install that answers 409 (the user already has the app) counts as success (installApp).

Situation What the operator sees
401/403 on any call The permission name plus the full consent path (GraphClient.call).
No such address in the tenant Microsoft Graph found no user with the address "…" in this tenant. (findPersonViaGraph in lib/proactive.mjs)
Address matches several users Refused, with a suggestion to address the person by Entra object id (findUser).
graphCatalogAppId empty when an install is needed An explicit instruction naming the Teams admin center column (installApp).
Catalog id not found (404) The app must be uploaded and approved in the org catalog first (installApp).

7. Common failures and what they look like in the log

Log line Level Meaning / what to do
enabled but appId/appPassword/tenantId are not all configured — not connecting (register in index.mjs) warn The plugin loaded but registered no platform, no webhook and no tools. Fill in all three.
msteams platform registered (webhook /hooks/msteams/messages + Teams and delegated Microsoft 365 tools) (register) info Registration succeeded.
msteams webhook locally available (app <appId>); provider transport unknown (connect in lib/adapter.mjs) info Local credential initialization succeeded; this is not a provider connectivity/health observation.
msteams credential check failed: … (connect) warn The token call failed at enable time — usually a wrong secret or tenant id. Initialization rejects and readiness stays unknown; no successful connection is claimed. Inbound JWT validation retains its separate boundary.
webhook token rejected: … (makeTokenVerifier in lib/auth.mjs) warn An inbound activity failed JWT validation → 401. Wrong appId, a clock far out of the 300 s tolerance, an unreachable JWKS, or a spoofed/replayed serviceUrl.
msteams turn failed in <conv>: <stack> (runTurn log in handleActivity) error The brain turn threw. The same message is also replied into the chat as ⚠️ ….
msteams turn failed: … (handleWebhook) error The detached webhook work rejected outside the per-turn catch — a card action, or a failure before onActivity reached its own try/catch.
msteams send: no stored route for conversation <id> (tmSend) warn No ref.serviceUrl for that conversation and no _meta.serviceUrl either. The bot must receive one activity before it can send.
msteams send failed: … / msteams edit failed: … (tmSend, tmEdit) error / warn A Connector call failed. The message body carries the HTTP status and the first 300 characters of Microsoft's response (ConnectorClient.call).
msteams roster lookup failed for <id>: … (roster) warn Membership could not be refreshed; the previous roster is reused, so mentions still resolve for up to 5 minutes.
image download failed: … (collectMedia) error An inbound image exceeded maxImageBytes or the download failed; the turn continues with [Attachment: image (download failed or too large)].
image upload failed: … (sendImages) error An outbound image Connector send failed. The callback logs msteams.file_upload_failed and rejects with the original cause to the shared finalizer/turn owner; notify stops before final result text. No upload replay is added.
msteams shared file offer failed for <name>: … (offerSharedFiles in lib/files.mjs) error An actual consent-card offer failed in a 1:1 chat. The original cause rejects the callback and stops later files; earlier confirmed offers stay valid. The canonical turn owner handles failure without a second local chat notice or replay. Declared size-cap notices still permit later eligible files; unsupported scopes remain no-ops.
msteams file upload failed for <name>: … (onFileConsent in lib/files.mjs) error The recipient accepted an offer and the upload to their OneDrive URL failed; the card is replaced with ⚠️ <name> could not be uploaded. Please try again.
msteams directory: could not persist <key>: … (PeopleDirectory.remember) warn The people directory could not be written. Harmless in itself — it is re-learned from the next roster read.
stateStore: failed to persist … (elowen-plugin-shared/stateStore) error The state file could not be written; this one is re-thrown, so the command that caused it fails visibly rather than confirming a change that never stuck.

Two quiet failure modes with no log line at all, worth knowing about:

  • An unmapped sender is dropped silently by the admission check in handleActivity. Check rolePolicies.
  • In a group chat with respondWithoutMention: false, a message with no bot mention returns at the mention gate in handleActivity.

Secrets never appear in any of this: the token layer echoes the response of a failed token call and never the request that carried the secret (TokenSource.token), and tests/msteams.test.ts asserts the app password is absent from tool output, the log, the persisted state file and every outbound connector payload.

8. What a redeploy or config save does — and does not — change

Saving plugin configuration persists it through the host revision boundary and requests a daemon restart. The adapter keeps its current configuration until that restart completes. A saved change with pending activation must not be presented as already effective.

Changes / is rebuilt:

  • The adapter instance and its whole config snapshot — register spreads ctx.config (normalized by normalizeConfig) once, so a field change only takes effect on the next daemon start.
  • Whether the directory Graph layer exists at all (graphLookup is read once, in the adapter constructor).
  • Every in-memory cache: the connector and Graph bearers, the JWKS handle, upnCache, rosterCache.
  • Open interactive cards stop working. pendingAsks and pendingPickers are in-memory, so a button tapped after a reload finds no pending entry and is ignored (onAskAction in lib/asks.mjs, onPickerAction in lib/commands.mjs). The card is left visibly un-settled.

Does not change:

  • channel-state.json and everything in it: conversation routes (ref), /new generations, per-chat model / reasoning / display overrides, the transcript, and the whole _people directory. A restart loses no person and no opened 1:1 chat.
  • Azure-side state: the app registration, the bot resource, the messaging endpoint, the uploaded Teams app package. Nothing in a redeploy touches those.
  • The webhook URL. It is derived from the plugin name, not from config.

A redeploy that changes the plugin's data directory (the plugin data root is derived from the daemon's data directory, see src/daemon/brainCore.ts) would orphan channel-state.json, and the bot would then have no route to any conversation until it receives a message again.

9. The agentName caveat

The app and publisher names, transcript label and help heading are built-in Chetty; the download is chetty-teams-app.zip. There is no configurable product identity or instance-brand lookup.

The manifest declares retiredConfigKeys: ["agentName", "productName"]. On the next enabled load, the authoritative core loader removes only present listed instance-config properties before register(ctx), using ConfigStore.update with the snapshot revision. Unlisted and undeclared settings, secrets and other plugins' slices are retained. A repeated load with neither key makes no write; runners do not prune, and a disabled plugin is cleaned when next enabled. A revision conflict or failed write fails that plugin load without overwriting newer configuration. The app ID, credentials, permissions and configurable icon are unchanged.

10. Delegated request budget, retries and output caps

Microsoft Graph reads made as the signed-in person are tried up to three times in total when Graph throttles them, returns a server error or the connection drops. Those attempts share the one 15-second deadline. Writes, and every call made with the bot's own application permissions, are sent once. A Bot Connector call is repeated only after a throttling response, never after an unknown outcome.

Delegated tool output is capped at 20,000 characters, a roster lists up to 50 members and person search returns up to 25 matches. TeamsApi output is truncated at 4,000 characters.

Other plugins receive separate drive- and mail-scoped clients through microsoftIdentity; neither client returns a token or its underlying Graph client.

11. Personal web mail sign-in

This flow belongs to lib/mailOAuth.mjs and uses the existing bot app's appId, appPassword and tenant GUID, independently of accountLinking, oauthConnectionName, web SSO and MicrosoftOutlook. Existing Teams/Microsoft 365 tool credentials and policy are unchanged.

Before enabling Microsoft mail for users, the tenant administrator must configure the bot app:

  1. In Entra admin center → App registrations → the bot app → Authentication → Add a platform → Web, add https://elowen.example.com/p/msteams/mail/callback, replacing the origin with the installation's canonical public web URL. The plugin uses ctx.publicWebUrl(), never a request Host header or ssoRedirectBase.
  2. In API permissions → Add a permission → Microsoft Graph → Delegated permissions, add User.Read, Mail.ReadWrite, Mail.Send and MailboxSettings.ReadWrite; grant tenant administrator consent. The authorization request also includes offline_access so the connection survives the access token's expiry.
  3. Keep the registration single-tenant. The flow addresses that tenant's v2 authorization/token endpoints, not common, organizations or consumers. Personal Microsoft accounts and mailboxes from other tenants are outside this integration.
  4. Install the coordinated core and plugin artifacts before offering the Email sign-in action. No tenant configuration is changed automatically.

After administrator consent, owners of existing mailboxes whose stored grant lacks MailboxSettings.ReadWrite must use Email's explicit reconnect flow once. Reconnect the existing mailbox; do not delete and re-add it. Its ref, Email account ID, access and alert preferences, and polling cursor are retained. Token refresh cannot add this scope: mailGraphFor returns null for the old grant until explicit sign-in and consent.

Control contract

Email resolves the complete shared MicrosoftIdentityControl through ctx.control('microsoftIdentity', microsoftIdentityMethods) with its existing declared consumer and approved control:microsoftIdentity consent. Its mail members are:

  • mailSignIn(userId, returnTo): Promise<string> returns a PKCE authorization URL with prompt=select_account. Each user has one pending sign-in; starting another supersedes it. returnTo must normalize to a local same-origin path.
  • mailAccounts(): Promise<{ref, address, displayName}[]> is projected by the host from GET /plugins/msteams/api/mail/accounts, not registered as a second native control method. The JSON route returns the array directly, selects its owner only from req.auth.userId, and reads only that owner's saved local account index. Query/body ownership claims cannot select another account. Listing does not retrieve tokens, refresh OAuth or contact Graph. The route admits authenticated user, agent and personal API-token callers under their existing account/plugin gates. An absent authenticated HTTP actor rejects peer invocation. Email uses it for listing, import and reconnect while preserving its own response envelopes and refusal of agent writes. The opaque ref is the immutable Graph profile object ID. Teams readiness calls the internal explicit-owner runtime operation directly; it is not exported through the native peer control.
  • mailGraphFor(userId, ref): Promise<MailScopedGraph | null> acquires the owner's vault inside the attributed control call. Missing accounts/tokens, grants predating MailboxSettings.ReadWrite, and invalid_grant return null; provider/storage failures reject. Old credentials retain their account index for Email's explicit reconnect flow, not silent refresh-based scope escalation. A returned client's later requests also refresh credentials when needed.
  • mailDisconnect(userId, ref): Promise<void> cancels and awaits local in-flight mailbox work, invalidates pending sign-in, and deletes that token and index entry under the same credential locks. Previously returned clients stay revoked even after a later explicit sign-in.

MailScopedGraph exposes only request(method, path, options), json(method, path, options) and binary(path, options), with the existing delegated request options. Results are a Response, unknown JSON, and {body: Uint8Array, contentType: string}, respectively. mailScopedPath(method, path) authorizes before client acquisition:

Path family Methods
/me/messages GET list, POST draft
/me/messages/{id} GET, PATCH
message createReply, createReplyAll, createForward, send, move POST
message attachment collection GET, POST
one attachment; its /$value GET/DELETE; GET
/me/mailFolders; one folder GET/POST; GET/PATCH/DELETE
folder /childFolders; /messages; /messages/delta GET/POST; GET; GET
folder-scoped /messages/{id}/permanentDelete POST
/me/outlook/masterCategories; one category GET/POST; GET/PATCH/DELETE
/me/sendMail POST

No wildcard descendants or unscoped message deletion are admitted. Microsoft Teams 0.10.25 admits PATCH only on the exact /me/outlook/masterCategories/{id} resource so Email 0.2.5 can update category colour with the existing MailboxSettings.ReadWrite grant. Category collection PATCH, extra descendants, other namespaces and methods remain refused. Graph permits only colour updates, not category rename; Email validates the closed palette and sends only {color: preset}. Scalar $select fields and supported paging/filter/search query names are bounded; navigation expansion is refused. Encoded slashes within opaque IDs remain encoded, while traversal, double encoding, fragments, absolute URLs and other namespaces reject. Consumers validate next/delta links' origin and exact resource before converting them to relative paths; the scoped client never accepts an absolute continuation. The Email GraphBackend is the consumer; no token or arbitrary Microsoft settings endpoint crosses this seam.

Vault, callback and lifetime

The encrypted personal msteams namespace holds mail.<oid> credentials, the mail.accounts index and mail.pending state. State expires after ten minutes, is tied to the Elowen account and is marked consumed under a vault lock before code exchange. The code and PKCE verifier never reach a consumer. Refresh runs inside withLock('mail.<oid>'), rereads after locking, keeps an omitted replacement refresh token and persists rotation before releasing the lock. A malformed stored value fails rather than silently resetting credentials. Tokens also record their granted scopes; explicit token responses must include MailboxSettings.ReadWrite. Microsoft's documented omitted-scope code-flow response means the requested scope set, not a narrower grant. Older stored records lacking that field require reconnect without losing their identity index.

The authoritative daemon uses ctx.userSecretsFor(userId); its retained bag rechecks current owner, existence, live plugin grants and attributed control callers. Tool runners use ctx.userSecrets() only after an explicit current-owner match; the returned client checks that runner owner again on use. No instance vault, database query or emulated identity substitutes for these seams.

The browser page /p/msteams/mail/callback removes callback parameters from the address bar, POSTs once to authenticated /plugins/msteams/mail/callback, then uses host navigate(returnTo, { replace: true }). The failure return action uses host navigate('/p/email', { replace: true }), without a full reload. The callback is the exact web.userPages route mail/callback, with a separate web-src/mail-callback.tsx → web/mail-callback.js + web/mail-callback.css build requiring UI API 73. Its registration's third argument and usePluginStrings('msteams', 'mail/callback') select that same page identity. English copy belongs to the page's strings; locale overrides live in web.userPages["mail/callback"].strings, never the admin workspace record.

The host requests /plugins/ui?plugin=msteams&page=mail%2Fcallback&lang=<locale> and receives only that page's descriptor and copy. Assets retain their content hash in the path, for example /plugins/msteams/web/<hash>.js?page=mail%2Fcallback. Both metadata and assets require an authenticated account and the existing plugin grant. The main manifest no longer declares web.adminOnly: its account-linked surface and navigation follow normal authenticated plugin-grant admission. Administrative workspace actions retain their own route authorization; loading presentation does not grant them. The callback bundle imports no Teams workspace or policy editor; the main entry no longer registers it.

The API derives the owner from the host's PluginApiRequest.auth.userId, refuses account-less/agent credentials, and never accepts an owner from the body. A refusal displays a localized explanation and a return action; restarting sign-in is required because state is single-use. The API route registers only after all Entra app credentials (appId, appPassword, tenantId) are present and the mail runtime exists; it is absent on an unconfigured plugin. The setup-tolerant administrator app-package and people routes remain registered separately.

registerUserRemoved first aborts the owner's work and awaits every tracked operation, then deletes all indexed mail tokens, pending state and the index. It keeps that owner closed for this runtime, so a late refresh/callback cannot recreate secrets. The microsoft-mail service owns its mail-work abort and drain. The host stops platform producers before registry services; only that platform lifetime disconnects the adapter and drains its shared requests. There is no second service-stop disconnect registration.

Verification and release boundary

Focused backend suites are plugins/msteams/tests/mail{Graph,OAuth,Routes,Registration}.test.mjs; tests/msteams-mail-callback.test.tsx covers single exchange, loading/error, query removal and the scoped string hook. tests/msteams-mail-user-page.test.ts checks the exact manifest, moved translations, source registrations and both independent shipped bundles. The language, string-key, design-token and bundle-layout gates include user pages; check:web checks every shipped browser JS/CSS output.

tests/e2e/msteams/mail-callback.mjs is an explicit manual test entry in knip.json. It launches the selected ELOWEN_CORE_ROOT checkout's web/tests/e2e/specs/msteams.mail-callback.e2e.ts against these registry manifest/assets, read-only. Provide owned FAKE_DAEMON_PORT/E2E_WEB_PORT, E2E_SCREENSHOT_DIR and E2E_BROWSER_PATH. Run inside the core test filesystem sandbox through the host's heavy-work gate; no live account or database is used. The opt-in native fixture owns Next, the synthetic session, native plugin UI preparation/routes and mail callback handler, and a disposable socket-only PostgreSQL encrypted vault. Only Microsoft's remote token/profile HTTP is substituted; listing, scoped assets, authorization, PKCE state validation and vault writes are real. The harness stops its servers and database. The six cs/sk/en × 320-touch/1440 cases cover loading, successful single exchange and return, provider denial, query removal, no Teams navigation for members, API55 root JS/CSS 403 with/without page selector, and same-document API55 root/API69 callback registration isolation for admins. The admin root is held in its real loading frame; Teams bot settings transport is outside this check. Screenshots cover loading/error in all six cases. Successful live tenant consent remains separate acceptance.

The current manifest requires shared API 16 and UI API 73. web.userPages was introduced at UI API 69; that historical level is not the current bundle requirement. Publishing remains blocked until the coordinated core archive actually supplies oauthCodeFlow, userSecretsFor and the required web runtime. An API match or the existing numeric requiresCore value alone does not certify those exports. Native core release preparation assigns its package version, not plugin compatibility floors. After verifying the paired archive, explicitly set the plugin manifest's requiresCore to the exact first release shipping these contracts. Then prepare the plugin patch through the registry release mechanism, which only copies the existing requiresCore into registry metadata. Ordinary-user browser acceptance must run against that host; a component-only fixture cannot establish the admin boundary.