@dxv-systems/mail-graph 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -135,6 +135,12 @@ The page is fixed in the package: apps mount `<M365SetupPage />` and cannot rest
135
135
 
136
136
  States: `not_started`, `awaiting_consent`, `awaiting_script` (with `exchangeSetupError` = fallback; `objectId: null` = paste field), `awaiting_access`, `connected`, `failed`. Changing mailboxes after a sign-in asks for a new sign-in (the script route reruns the script); moving to another tenant needs an explicit reset (`POST /api/m365/reset` with `{ "confirm": true }`).
137
137
 
138
+ **Mail keeps working during a mailbox change.** The connection remembers the scope of its last passing access check (`live`). `activeScope(connection)` gives the tenant and the mailboxes an app may use right now:
139
+ - all of them once `connected`;
140
+ - while a change waits on a sign-in, the script or Microsoft, the mailboxes that worked before and are still selected.
141
+
142
+ So a removed mailbox stops at once, an added one joins when the access check passes, and the others keep syncing. A failed check (a scope leak above all) clears it and blocks the helpdesk, as before, and so does a reset. The status carries the same list as `activeMailboxes`, and the page names those mailboxes while a change is under way. Apps build their helpdesk from `activeScope`, never from `step === "connected"` (recipe `src/lib/helpdesk/deps.ts`). A row saved before 0.3 has no `live`: it gets one on the next passing check or the next mailbox change.
143
+
138
144
  ### Mounting it in an app
139
145
 
140
146
  The complete, tested integration for a `company-app-template` app (schema, adapters, routes, pages, crons, env, checks), together with `@dxv-systems/helpdesk`, is [docs/app-integration.md](docs/app-integration.md).
@@ -0,0 +1,6 @@
1
+ import type { M365Connection } from "./types";
2
+ export interface ActiveScope {
3
+ tenantId: string;
4
+ mailboxes: string[];
5
+ }
6
+ export declare function activeScope(connection: M365Connection | null | undefined): ActiveScope | null;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.activeScope = activeScope;
4
+ function activeScope(connection) {
5
+ if (!connection?.tenantId)
6
+ return null;
7
+ if (connection.step === "connected") {
8
+ return connection.mailboxes.length ? { tenantId: connection.tenantId, mailboxes: connection.mailboxes } : null;
9
+ }
10
+ const live = connection.live;
11
+ if (!live || live.tenantId !== connection.tenantId)
12
+ return null;
13
+ const kept = live.mailboxes.filter((mailbox) => connection.mailboxes.includes(mailbox));
14
+ return kept.length ? { tenantId: live.tenantId, mailboxes: kept } : null;
15
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createM365SetupHandlers = createM365SetupHandlers;
4
4
  const auth_1 = require("../auth");
5
5
  const access_1 = require("./access");
6
+ const active_1 = require("./active");
6
7
  const address_1 = require("./address");
7
8
  const consent_1 = require("./consent");
8
9
  const exchange_graph_1 = require("./exchange-graph");
@@ -171,6 +172,7 @@ function createM365SetupHandlers(config) {
171
172
  lastCheckedAt: connection.lastCheckedAt,
172
173
  checkDeadline: scriptRanAt === null ? null : new Date(scriptRanAt + access_1.ACCESS_CHECK_WINDOW_MS).toISOString(),
173
174
  connectedAt: connection.connectedAt,
175
+ activeMailboxes: (0, active_1.activeScope)(connection)?.mailboxes ?? [],
174
176
  signedInAs: connection.signedInAs ?? null,
175
177
  itLinkExpiresAt: viewer.viewer === "it"
176
178
  ? viewer.expiresAt === null
@@ -201,6 +203,7 @@ function createM365SetupHandlers(config) {
201
203
  next.step = "connected";
202
204
  next.failure = null;
203
205
  next.connectedAt = wasConnected ? latest.connectedAt : iso();
206
+ next.live = { tenantId: connection.tenantId, mailboxes: connection.mailboxes, since: next.connectedAt ?? iso() };
204
207
  if (!wasConnected || latest.noticesComplete !== true) {
205
208
  const read = await (0, access_1.readSetupNotices)(graph, connection.mailboxes);
206
209
  if (read.complete || !wasConnected)
@@ -217,6 +220,7 @@ function createM365SetupHandlers(config) {
217
220
  else if (evaluation.outcome === "failed") {
218
221
  next.step = "failed";
219
222
  next.failure = evaluation.failure;
223
+ next.live = null;
220
224
  }
221
225
  const saved = await save(next);
222
226
  if (!wasConnected && saved.step === "connected")
@@ -268,6 +272,8 @@ function createM365SetupHandlers(config) {
268
272
  next.step = "awaiting_consent";
269
273
  }
270
274
  else if (!sameMailboxes) {
275
+ const scope = (0, active_1.activeScope)(current);
276
+ next.live = scope ? { ...scope, since: current.live?.since ?? current.connectedAt ?? iso() } : null;
271
277
  const step = current.setupMethod === "graph" ? "awaiting_consent" : "awaiting_script";
272
278
  Object.assign(next, { step, scriptRanAt: null, checks: null, failure: null, lastCheckedAt: null, exchangeSetupError: null });
273
279
  }
@@ -1,4 +1,6 @@
1
1
  export { createM365SetupHandlers } from "./handlers";
2
+ export { activeScope } from "./active";
3
+ export type { ActiveScope } from "./active";
2
4
  export { IT_LINK_HEADER, SETUP_BASE_PATH } from "./constants";
3
5
  export type { M365SetupConfig, M365SetupHandlers } from "./handlers";
4
6
  export { ACCESS_CHECK_WINDOW_MS, checkMailboxes, evaluateAccess } from "./access";
@@ -15,4 +17,4 @@ export { buildExchangeScript, buildScriptInvocation, EXECUTION_POLICY_TIP, excha
15
17
  export type { ScriptInputError, ScriptInvocationInput, ScriptSignIn } from "./script";
16
18
  export { lookupTenant, resolveMailboxTenant } from "./tenant";
17
19
  export type { DomainLookup, TenantLookupOptions, TenantResolution } from "./tenant";
18
- export type { ConnectionStore, ConsentErrorCode, FailureCode, M365Connection, MailboxCheck, MailboxRole, SetupAdmin, SetupStatus, SetupStep, SetupViewer, } from "./types";
20
+ export type { ConnectionStore, ConsentErrorCode, FailureCode, LiveScope, M365Connection, MailboxCheck, MailboxRole, SetupAdmin, SetupStatus, SetupStep, SetupViewer, } from "./types";
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveMailboxTenant = exports.lookupTenant = exports.ScriptInputInvalid = exports.SCRIPT_FILE_NAME = exports.psQuote = exports.exchangeGroupName = exports.EXECUTION_POLICY_TIP = exports.buildScriptInvocation = exports.buildExchangeScript = exports.SETUP_ERROR_MESSAGES = exports.CONSENT_ERROR_MESSAGES = exports.verifyItLinkToken = exports.createItLinkToken = exports.verifyConsentCallback = exports.createConsentState = exports.CONSENT_CALLBACK_PATH = exports.buildAdminConsentUrl = exports.validateMailboxInput = exports.normalizeMailbox = exports.MAX_MAILBOXES = exports.evaluateAccess = exports.checkMailboxes = exports.ACCESS_CHECK_WINDOW_MS = exports.SETUP_BASE_PATH = exports.IT_LINK_HEADER = exports.createM365SetupHandlers = void 0;
3
+ exports.resolveMailboxTenant = exports.lookupTenant = exports.ScriptInputInvalid = exports.SCRIPT_FILE_NAME = exports.psQuote = exports.exchangeGroupName = exports.EXECUTION_POLICY_TIP = exports.buildScriptInvocation = exports.buildExchangeScript = exports.SETUP_ERROR_MESSAGES = exports.CONSENT_ERROR_MESSAGES = exports.verifyItLinkToken = exports.createItLinkToken = exports.verifyConsentCallback = exports.createConsentState = exports.CONSENT_CALLBACK_PATH = exports.buildAdminConsentUrl = exports.validateMailboxInput = exports.normalizeMailbox = exports.MAX_MAILBOXES = exports.evaluateAccess = exports.checkMailboxes = exports.ACCESS_CHECK_WINDOW_MS = exports.SETUP_BASE_PATH = exports.IT_LINK_HEADER = exports.activeScope = exports.createM365SetupHandlers = void 0;
4
4
  var handlers_1 = require("./handlers");
5
5
  Object.defineProperty(exports, "createM365SetupHandlers", { enumerable: true, get: function () { return handlers_1.createM365SetupHandlers; } });
6
+ var active_1 = require("./active");
7
+ Object.defineProperty(exports, "activeScope", { enumerable: true, get: function () { return active_1.activeScope; } });
6
8
  var constants_1 = require("./constants");
7
9
  Object.defineProperty(exports, "IT_LINK_HEADER", { enumerable: true, get: function () { return constants_1.IT_LINK_HEADER; } });
8
10
  Object.defineProperty(exports, "SETUP_BASE_PATH", { enumerable: true, get: function () { return constants_1.SETUP_BASE_PATH; } });
@@ -227,7 +227,7 @@ function M365SetupPage({ linkToken, helpdeskHref, settingsHref, fetch: fetchImpl
227
227
  body = (0, jsx_runtime_1.jsx)(WaitingStep, { ...shared });
228
228
  return ((0, jsx_runtime_1.jsxs)("div", { className: cls.root, "data-m365-setup": "", "data-step": status.step, children: [(0, jsx_runtime_1.jsx)("p", { className: cls.breadcrumb, children: isIt
229
229
  ? `Verzoek van ${status.companyName}${status.itLinkExpiresAt ? `, link geldig tot ${formatDate(status.itLinkExpiresAt)}` : ""}`
230
- : "Beheer / Microsoft 365" }), status.consentError && start && ((0, jsx_runtime_1.jsx)("p", { role: "alert", className: cls.error, children: messages_1.CONSENT_ERROR_MESSAGES[status.consentError] })), actionError && ((0, jsx_runtime_1.jsx)("p", { role: "alert", className: cls.error, children: actionError })), body] }));
230
+ : "Beheer / Microsoft 365" }), status.consentError && start && ((0, jsx_runtime_1.jsx)("p", { role: "alert", className: cls.error, children: messages_1.CONSENT_ERROR_MESSAGES[status.consentError] })), status.step !== "connected" && status.activeMailboxes.length > 0 && ((0, jsx_runtime_1.jsxs)("p", { className: cls.muted, "data-m365-active": "", children: ["Mail blijft werken voor ", status.activeMailboxes.join(", "), " terwijl deze wijziging wordt afgerond."] })), actionError && ((0, jsx_runtime_1.jsx)("p", { role: "alert", className: cls.error, children: actionError })), body] }));
231
231
  }
232
232
  function Header({ title, lead, badge }) {
233
233
  return ((0, jsx_runtime_1.jsxs)("div", { className: cls.header, children: [(0, jsx_runtime_1.jsxs)("div", { className: cls.actions, children: [(0, jsx_runtime_1.jsx)("h1", { className: cls.title, children: title }), badge && (0, jsx_runtime_1.jsx)("span", { className: cls.badgeOk, children: badge })] }), lead && (0, jsx_runtime_1.jsx)("p", { className: cls.lead, children: lead })] }));
@@ -15,6 +15,11 @@ export interface MailboxCheck {
15
15
  role: MailboxRole;
16
16
  status: AccessStatus | "error";
17
17
  }
18
+ export interface LiveScope {
19
+ tenantId: string;
20
+ mailboxes: string[];
21
+ since: string;
22
+ }
18
23
  export interface M365Connection {
19
24
  setupId: string;
20
25
  step: SetupStep;
@@ -38,6 +43,7 @@ export interface M365Connection {
38
43
  noticesComplete?: boolean;
39
44
  lastCheckedAt: string | null;
40
45
  connectedAt: string | null;
46
+ live?: LiveScope | null;
41
47
  updatedAt: string;
42
48
  }
43
49
  export interface ConnectionStore {
@@ -71,6 +77,7 @@ export interface SetupStatus {
71
77
  lastCheckedAt: string | null;
72
78
  checkDeadline: string | null;
73
79
  connectedAt: string | null;
80
+ activeMailboxes: string[];
74
81
  signedInAs: string | null;
75
82
  itLinkExpiresAt: string | null;
76
83
  pageUrl: string;
@@ -17,7 +17,7 @@ The code below was compiled, linted, knip-checked, built and tested against a fr
17
17
  ## 1. Install
18
18
 
19
19
  ```bash
20
- npm install --save-exact @dxv-systems/mail-graph@0.2.1 @dxv-systems/helpdesk@0.10.0 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.3.0 @dxv-systems/helpdesk@0.10.1 @vercel/oidc@4.0.1
21
21
  ```
22
22
 
23
23
  Use the published versions (exact, never a range; upgrading is a deliberate change). **Vendored variant** (before publication, e.g. the rehearsal): `npm pack` each package into `vendor/` and install `file:vendor/dxv-systems-mail-graph-<version>.tgz file:vendor/dxv-systems-helpdesk-<version>.tgz` instead; commit the tarballs with `package.json` and the lockfile.
@@ -276,7 +276,7 @@ export const helpdeskReplyAttachments = pgTable(
276
276
  );
277
277
  ```
278
278
 
279
- Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (eight `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState` (see the helpdesk README, Upgrading from 0.5).
279
+ Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (eight `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5).
280
280
 
281
281
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
282
282
 
@@ -1106,6 +1106,7 @@ export async function releaseSyncLease(): Promise<void> {
1106
1106
  import "server-only";
1107
1107
  import { inArray } from "drizzle-orm";
1108
1108
  import type { HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
1109
+ import { activeScope } from "@dxv-systems/mail-graph/setup";
1109
1110
  import { rolesWithPermission } from "@/lib/auth/permissions";
1110
1111
  import { db } from "@/lib/db";
1111
1112
  import { users } from "@/lib/db/schema";
@@ -1179,14 +1180,15 @@ function ownAddresses(): string[] {
1179
1180
  export async function getHelpdeskDeps(): Promise<HelpdeskDeps | null> {
1180
1181
  const env = readM365Env();
1181
1182
  if (!env) return null;
1182
- const connection = await loadM365Connection();
1183
- if (connection?.step !== "connected" || !connection.tenantId) return null;
1184
- const graph = graphClientFor(env.clientId, connection.tenantId);
1183
+ // Also while a mailbox change waits on Microsoft: the mailboxes that already work keep syncing.
1184
+ const scope = activeScope(await loadM365Connection());
1185
+ if (!scope) return null;
1186
+ const graph = graphClientFor(env.clientId, scope.tenantId);
1185
1187
  return {
1186
1188
  store: helpdeskStore,
1187
1189
  gatewayFor: (mailbox) => graph.mailbox(mailbox),
1188
1190
  clock: { now: () => new Date() },
1189
- config: { ownAddresses: ownAddresses(), connectedMailboxes: connection.mailboxes },
1191
+ config: { ownAddresses: ownAddresses(), connectedMailboxes: scope.mailboxes },
1190
1192
  controls: loadHelpdeskControls,
1191
1193
  notifier,
1192
1194
  attachments: helpdeskReplyFiles,
@@ -1359,7 +1361,7 @@ export async function getHelpdeskSettingsForAdmin(): Promise<HelpdeskSettingsVie
1359
1361
  return readHelpdeskSettings();
1360
1362
  }
1361
1363
 
1362
- /** Whether the inbox can work: Microsoft 365 on and the connection `connected`. */
1364
+ /** Whether the inbox can work: Microsoft 365 on and at least one mailbox whose access works (`activeScope`). */
1363
1365
  export async function isHelpdeskConnected(): Promise<boolean> {
1364
1366
  await requirePermission("helpdesk:use");
1365
1367
  return (await getHelpdeskDeps()) !== null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Microsoft Graph mail for DXV apps — app-only auth via a caller-supplied client assertion (federated or certificate), per-mailbox delta sync, messages, attachments, threaded replies, folders, forward and send. Never deletes. Guided Microsoft 365 setup (route handlers and a React page) under ./setup. Zero runtime dependencies.",
5
5
  "keywords": [
6
6
  "dxv",