@dxv-systems/mail-graph 0.1.2 → 0.1.4

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
@@ -168,7 +168,7 @@ export const DELETE = m365Setup.handle;
168
168
  <M365SetupPage linkToken={params.token} />
169
169
  ```
170
170
 
171
- The route set is `/api/m365/{status, mailboxes, consent/start, consent/callback, object-id, script-ran, check, script, it-link, reset}`. Every route refuses (`403 not_production`) unless `isProduction` is true, and answers `503 not_configured` without a client id. POSTs from another `Origin` are refused. An IT link is sent in the `x-m365-link` header (or `?t=` for the script download).
171
+ The route set is `/api/m365/{status, mailboxes, consent/start, consent/callback, object-id, script-ran, check, script, it-link, reset}`. Every route refuses (`403 not_production`) unless `isProduction` is true, and answers `503 not_configured` without a client id. POSTs from another `Origin` are refused (`403 forbidden_origin`, with a message that names the `appOrigin` host). The page itself, opened on any address other than `appOrigin` (such as the app's platform address), shows only a link to the same page on `appOrigin`: the status response carries that URL as `pageUrl`. An IT link is sent in the `x-m365-link` header (or `?t=` for the script download).
172
172
 
173
173
  `store` holds one `M365Connection` (see `src/setup/types.ts`); a single row with a JSON column is enough. `runAccessCheck()` runs the same check from a cron job. The helpdesk may sync only while `step === "connected"`.
174
174
 
@@ -90,6 +90,7 @@ function createM365SetupHandlers(config) {
90
90
  const checkIntervalMs = Math.max(MIN_CHECK_INTERVAL_MS, config.checkIntervalMs ?? DEFAULT_CHECK_INTERVAL_MS);
91
91
  const clientId = config.clientId ?? "";
92
92
  const itLinkUrl = (token) => `${origin}${config.itLinkPagePath.replace(/\/$/, "")}/${token}`;
93
+ const adminPageUrl = `${origin}${config.pagePath}`;
93
94
  function emptyConnection() {
94
95
  return {
95
96
  setupId: (0, signing_1.randomId)(),
@@ -135,14 +136,14 @@ function createM365SetupHandlers(config) {
135
136
  connection.step === "connected" &&
136
137
  result.setupId === connection.setupId;
137
138
  if (afterConnect)
138
- return { viewer: "it", expiresAt: null };
139
+ return { viewer: "it", token, expiresAt: null };
139
140
  if (!result.ok)
140
141
  return fail(401, "link_invalid");
141
- return { viewer: "it", expiresAt: result.expiresAt };
142
+ return { viewer: "it", token, expiresAt: result.expiresAt };
142
143
  }
143
144
  const admin = await config.getAdmin(request);
144
145
  if (!admin)
145
- return fail(401, "unauthorized");
146
+ return fail(401, "unauthorized", { pageUrl: adminPageUrl });
146
147
  return { viewer: "admin", admin };
147
148
  }
148
149
  function toStatus(connection, viewer) {
@@ -178,6 +179,7 @@ function createM365SetupHandlers(config) {
178
179
  : connection.itLinkId
179
180
  ? connection.itLinkExpiresAt
180
181
  : null,
182
+ pageUrl: viewer.viewer === "it" ? itLinkUrl(viewer.token) : adminPageUrl,
181
183
  };
182
184
  }
183
185
  async function check(connection) {
@@ -319,7 +321,7 @@ function createM365SetupHandlers(config) {
319
321
  const claims = result.claims;
320
322
  if (!connection || !claims)
321
323
  return htmlMessage(400, "Koppelen niet gelukt", messages_1.CONSENT_ERROR_MESSAGES.state_invalid);
322
- const back = claims.via === "it" && claims.l ? itLinkUrl(claims.l) : `${origin}${config.pagePath}`;
324
+ const back = claims.via === "it" && claims.l ? itLinkUrl(claims.l) : adminPageUrl;
323
325
  if (!result.ok) {
324
326
  if (result.code !== "state_stale") {
325
327
  await save({ ...connection, consentError: result.code, consentNonce: null });
@@ -555,8 +557,10 @@ function createM365SetupHandlers(config) {
555
557
  return isCallback ? htmlMessage(503, "Koppelen niet gelukt", messages_1.SETUP_ERROR_MESSAGES.not_configured) : fail(503, "not_configured");
556
558
  }
557
559
  const requestOrigin = request.headers.get("origin");
558
- if (request.method !== "GET" && requestOrigin !== null && requestOrigin !== origin)
559
- return fail(403, "forbidden_origin");
560
+ if (request.method !== "GET" && requestOrigin !== null && requestOrigin !== origin) {
561
+ const host = new URL(origin).host;
562
+ return json(403, { error: "forbidden_origin", message: (0, messages_1.forbiddenOriginMessage)(host), appOrigin: origin });
563
+ }
560
564
  return handler(request);
561
565
  }
562
566
  async function runAccessCheck() {
@@ -5,7 +5,7 @@ export declare const SETUP_ERROR_MESSAGES: Readonly<{
5
5
  readonly setup_pending: "DXV zet Microsoft 365 nog klaar voor deze app. Probeer het later opnieuw.";
6
6
  readonly unauthorized: "Je hebt geen toegang tot deze koppeling. Log in als app-beheerder.";
7
7
  readonly link_invalid: "Deze link werkt niet (meer). Vraag de app-beheerder om een nieuwe link.";
8
- readonly forbidden_origin: "Dit verzoek komt niet van de app zelf en is geweigerd.";
8
+ readonly forbidden_origin: "Dit verzoek kwam via een ander adres dan dat van de app en is geweigerd. Open deze pagina via het adres van de app.";
9
9
  readonly invalid_input: "Controleer de ingevulde gegevens.";
10
10
  readonly not_m365: "Dit domein gebruikt geen Microsoft 365. Kies mailboxen die in Microsoft 365 staan.";
11
11
  readonly mixed_tenants: "De mailboxen staan in verschillende Microsoft 365-omgevingen. Kies mailboxen uit één omgeving.";
@@ -18,5 +18,6 @@ export declare const SETUP_ERROR_MESSAGES: Readonly<{
18
18
  readonly method_not_allowed: "Deze methode is hier niet toegestaan.";
19
19
  }>;
20
20
  export type SetupErrorCode = keyof typeof SETUP_ERROR_MESSAGES;
21
+ export declare function forbiddenOriginMessage(host: string): string;
21
22
  export declare const CONSENT_ERROR_MESSAGES: Readonly<Record<ConsentErrorCode, string>>;
22
23
  export declare const EXCHANGE_SETUP_ERROR_MESSAGES: Readonly<Record<ExchangeSetupErrorCode, string>>;
@@ -1,13 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EXCHANGE_SETUP_ERROR_MESSAGES = exports.CONSENT_ERROR_MESSAGES = exports.SETUP_ERROR_MESSAGES = void 0;
4
+ exports.forbiddenOriginMessage = forbiddenOriginMessage;
4
5
  exports.SETUP_ERROR_MESSAGES = Object.freeze({
5
6
  not_production: "Microsoft 365 koppelen kan alleen in de productieomgeving van de app.",
6
7
  not_configured: "Microsoft 365 is nog niet beschikbaar voor deze app. Neem contact op met DXV.",
7
8
  setup_pending: "DXV zet Microsoft 365 nog klaar voor deze app. Probeer het later opnieuw.",
8
9
  unauthorized: "Je hebt geen toegang tot deze koppeling. Log in als app-beheerder.",
9
10
  link_invalid: "Deze link werkt niet (meer). Vraag de app-beheerder om een nieuwe link.",
10
- forbidden_origin: "Dit verzoek komt niet van de app zelf en is geweigerd.",
11
+ forbidden_origin: "Dit verzoek kwam via een ander adres dan dat van de app en is geweigerd. Open deze pagina via het adres van de app.",
11
12
  invalid_input: "Controleer de ingevulde gegevens.",
12
13
  not_m365: "Dit domein gebruikt geen Microsoft 365. Kies mailboxen die in Microsoft 365 staan.",
13
14
  mixed_tenants: "De mailboxen staan in verschillende Microsoft 365-omgevingen. Kies mailboxen uit één omgeving.",
@@ -19,6 +20,9 @@ exports.SETUP_ERROR_MESSAGES = Object.freeze({
19
20
  not_found: "Onbekende route.",
20
21
  method_not_allowed: "Deze methode is hier niet toegestaan.",
21
22
  });
23
+ function forbiddenOriginMessage(host) {
24
+ return `Dit verzoek kwam via een ander adres dan ${host} en is geweigerd. Open deze pagina via ${host} en probeer het opnieuw.`;
25
+ }
22
26
  exports.CONSENT_ERROR_MESSAGES = Object.freeze({
23
27
  state_invalid: "Deze terugkoppeling van Microsoft is ongeldig. Ga terug naar de koppelpagina en klik opnieuw op Koppelen met Microsoft.",
24
28
  state_expired: "Het koppelen duurde te lang en is verlopen. Klik opnieuw op Koppelen met Microsoft.",
@@ -131,6 +131,19 @@ function useApi(linkToken, fetchImpl) {
131
131
  return body;
132
132
  }, [linkToken, fetchImpl]);
133
133
  }
134
+ function productionPage(pageUrl) {
135
+ if (typeof pageUrl !== "string" || typeof window === "undefined")
136
+ return null;
137
+ try {
138
+ const url = new URL(pageUrl);
139
+ if (url.protocol !== "https:" && url.protocol !== "http:")
140
+ return null;
141
+ return url.origin === window.location.origin ? null : { url: url.href, host: url.host };
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
134
147
  async function signIn(api, method) {
135
148
  const { url } = await api("consent/start", { method: "POST", body: { method } });
136
149
  window.location.assign(url);
@@ -139,6 +152,7 @@ function M365SetupPage({ linkToken, helpdeskHref, settingsHref, fetch: fetchImpl
139
152
  const api = useApi(linkToken, fetchImpl);
140
153
  const [status, setStatus] = (0, react_1.useState)(null);
141
154
  const [loadError, setLoadError] = (0, react_1.useState)(null);
155
+ const [loadErrorPageUrl, setLoadErrorPageUrl] = (0, react_1.useState)(null);
142
156
  const [view, setView] = (0, react_1.useState)("auto");
143
157
  const [busy, setBusy] = (0, react_1.useState)(false);
144
158
  const [actionError, setActionError] = (0, react_1.useState)(null);
@@ -146,22 +160,27 @@ function M365SetupPage({ linkToken, helpdeskHref, settingsHref, fetch: fetchImpl
146
160
  try {
147
161
  setStatus(await api("status"));
148
162
  setLoadError(null);
163
+ setLoadErrorPageUrl(null);
149
164
  }
150
165
  catch (error) {
151
166
  setLoadError(apiErrorText(error));
167
+ const pageUrl = error instanceof ApiError ? error.body.pageUrl : null;
168
+ setLoadErrorPageUrl(typeof pageUrl === "string" ? pageUrl : null);
152
169
  }
153
170
  }, [api]);
154
171
  (0, react_1.useEffect)(() => {
155
172
  void load();
156
173
  }, [load]);
174
+ const elsewhere = productionPage(status?.pageUrl ?? loadErrorPageUrl);
157
175
  const waiting = status?.step === "awaiting_access";
158
176
  const preparing = status !== null && !status.setupReady && (status.step === "not_started" || status.step === "awaiting_consent");
177
+ const polling = elsewhere === null && (waiting || preparing);
159
178
  (0, react_1.useEffect)(() => {
160
- if (!waiting && !preparing)
179
+ if (!polling)
161
180
  return;
162
181
  const timer = setInterval(() => void load(), waiting ? POLL_INTERVAL_MS : PREPARING_POLL_INTERVAL_MS);
163
182
  return () => clearInterval(timer);
164
- }, [waiting, preparing, load]);
183
+ }, [polling, waiting, load]);
165
184
  const run = (0, react_1.useCallback)(async (action, nextView = "auto") => {
166
185
  setBusy(true);
167
186
  setActionError(null);
@@ -178,6 +197,9 @@ function M365SetupPage({ linkToken, helpdeskHref, settingsHref, fetch: fetchImpl
178
197
  setBusy(false);
179
198
  }
180
199
  }, []);
200
+ if (elsewhere) {
201
+ return ((0, jsx_runtime_1.jsxs)("div", { className: cls.root, "data-m365-setup": "", "data-wrong-origin": "", children: [(0, jsx_runtime_1.jsx)("p", { className: cls.breadcrumb, children: linkToken ? (status ? `Verzoek van ${status.companyName}` : "Microsoft 365") : "Beheer / Microsoft 365" }), (0, jsx_runtime_1.jsx)(WrongOriginNotice, { url: elsewhere.url, host: elsewhere.host, it: Boolean(linkToken) })] }));
202
+ }
181
203
  if (!status) {
182
204
  return ((0, jsx_runtime_1.jsxs)("div", { className: cls.root, "data-m365-setup": "", children: [(0, jsx_runtime_1.jsx)("p", { className: cls.breadcrumb, children: "Beheer / Microsoft 365" }), loadError ? ((0, jsx_runtime_1.jsx)("p", { role: "alert", className: cls.error, children: loadError })) : ((0, jsx_runtime_1.jsx)("p", { className: cls.muted, "aria-live": "polite", children: "Laden\u2026" }))] }));
183
205
  }
@@ -210,6 +232,9 @@ function M365SetupPage({ linkToken, helpdeskHref, settingsHref, fetch: fetchImpl
210
232
  function Header({ title, lead, badge }) {
211
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 })] }));
212
234
  }
235
+ function WrongOriginNotice({ url, host, it }) {
236
+ return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Header, { title: `Open deze pagina via ${host}`, lead: `Je bent nu op een ander adres van de app. Koppelen met Microsoft 365 werkt alleen via ${host}, omdat Microsoft je na het aanmelden daarheen terugstuurt.` }), (0, jsx_runtime_1.jsxs)("a", { href: url, className: cls.primaryButton, children: ["Naar ", host] }), !it && (0, jsx_runtime_1.jsx)("p", { className: cls.center, children: "Log daar zo nodig opnieuw in als app-beheerder." })] }));
237
+ }
213
238
  function MicrosoftMark() {
214
239
  return ((0, jsx_runtime_1.jsxs)("svg", { "aria-hidden": "true", width: "16", height: "16", viewBox: "0 0 16 16", fill: "currentColor", children: [(0, jsx_runtime_1.jsx)("rect", { x: "1", y: "1", width: "6.5", height: "6.5" }), (0, jsx_runtime_1.jsx)("rect", { x: "8.5", y: "1", width: "6.5", height: "6.5" }), (0, jsx_runtime_1.jsx)("rect", { x: "1", y: "8.5", width: "6.5", height: "6.5" }), (0, jsx_runtime_1.jsx)("rect", { x: "8.5", y: "8.5", width: "6.5", height: "6.5" })] }));
215
240
  }
@@ -73,4 +73,5 @@ export interface SetupStatus {
73
73
  connectedAt: string | null;
74
74
  signedInAs: string | null;
75
75
  itLinkExpiresAt: string | null;
76
+ pageUrl: string;
76
77
  }
@@ -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.1.2 @dxv-systems/helpdesk@0.3.0 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.1.4 @dxv-systems/helpdesk@0.5.0 @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.
@@ -153,6 +153,9 @@ export const helpdeskThreads = pgTable(
153
153
  /** Staff id that marked "Geen antwoord nodig"; null when the noise filter ignored it. */
154
154
  dismissedBy: text("dismissed_by"),
155
155
  assigneeId: integer("assignee_id").references(() => users.id, { onDelete: "set null" }),
156
+ /** Internal note with the current assignment, for the assignee only; never mailed. */
157
+ assignmentNote: text("assignment_note"),
158
+ assignedBy: integer("assigned_by").references(() => users.id, { onDelete: "set null" }),
156
159
  },
157
160
  (table) => [
158
161
  index("helpdesk_threads_activity_idx").on(table.lastActivityAt, table.id),
@@ -266,7 +269,7 @@ export const helpdeskReplyAttachments = pgTable(
266
269
  );
267
270
  ```
268
271
 
269
- Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id` is 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).
272
+ 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).
270
273
 
271
274
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
272
275
 
@@ -814,18 +817,20 @@ export const helpdeskStore: HelpdeskStore = {
814
817
  };
815
818
  ```
816
819
 
817
- `src/lib/helpdesk/inbox.ts`: `HelpdeskInboxQueries` (newest activity first, keyset cursor, assignment = `helpdesk_threads.assignee_id`).
820
+ `src/lib/helpdesk/inbox.ts`: `HelpdeskInboxQueries` (newest activity first, keyset cursor, assignment = `helpdesk_threads.assignee_id` with its note; candidates = everyone with `helpdesk:use`).
818
821
 
819
822
  ```ts
820
823
  import "server-only";
821
- import { and, asc, desc, eq, inArray, isNull, sql, type SQL } from "drizzle-orm";
824
+ import { and, asc, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
822
825
  import type { HelpdeskInboxQueries } from "@dxv-systems/helpdesk/server";
826
+ import { rolesWithPermission } from "@/lib/auth/permissions";
823
827
  import { db } from "@/lib/db";
824
828
  import { helpdeskMessages, helpdeskThreads, users } from "@/lib/db/schema";
825
829
  import { toMessage, toThread } from "./store";
826
830
 
827
- // Reads and assignment for the staff inbox. Not user-scoped: the inbox route
828
- // guards every call with getStaff.
831
+ // Reads and assignment for the staff inbox. The inbox route checks the signed-in
832
+ // person's mailboxes (getStaff) first; listThreads gets them as query.mailboxes,
833
+ // and tickets assigned to query.viewerId show whatever their mailbox.
829
834
 
830
835
  function encodeCursor(at: Date, id: string): string {
831
836
  return Buffer.from(JSON.stringify([at.toISOString(), id])).toString("base64url");
@@ -843,7 +848,13 @@ function decodeCursor(cursor: string): [Date, string] | null {
843
848
 
844
849
  export const helpdeskInbox: HelpdeskInboxQueries = {
845
850
  async listThreads(query) {
846
- const where: SQL[] = [];
851
+ // The viewer's mailboxes (may be empty) OR assigned to the viewer. Filtered here so pages stay full.
852
+ const access: SQL[] = [];
853
+ if (query.mailboxes.length > 0) access.push(inArray(helpdeskThreads.mailbox, query.mailboxes));
854
+ const viewer = Number(query.viewerId);
855
+ if (Number.isInteger(viewer)) access.push(eq(helpdeskThreads.assigneeId, viewer));
856
+ if (access.length === 0) return { rows: [], nextCursor: null };
857
+ const where: SQL[] = [or(...access)!];
847
858
  if (query.states) where.push(inArray(helpdeskThreads.state, query.states));
848
859
  if (query.mailbox) where.push(eq(helpdeskThreads.mailbox, query.mailbox));
849
860
  if (query.assigneeId === null) where.push(isNull(helpdeskThreads.assigneeId));
@@ -861,7 +872,7 @@ export const helpdeskInbox: HelpdeskInboxQueries = {
861
872
  .select({ thread: helpdeskThreads, assigneeName: users.name })
862
873
  .from(helpdeskThreads)
863
874
  .leftJoin(users, eq(users.id, helpdeskThreads.assigneeId))
864
- .where(where.length ? and(...where) : undefined)
875
+ .where(and(...where))
865
876
  .orderBy(desc(helpdeskThreads.lastActivityAt), desc(helpdeskThreads.id))
866
877
  .limit(query.limit + 1);
867
878
  const page = rows.slice(0, query.limit);
@@ -897,10 +908,23 @@ export const helpdeskInbox: HelpdeskInboxQueries = {
897
908
  return row ? { id: String(row.id), name: row.name } : null;
898
909
  },
899
910
 
900
- async setAssignee(threadId, assignee) {
911
+ async listAssignees() {
912
+ const rows = await db
913
+ .select({ id: users.id, name: users.name })
914
+ .from(users)
915
+ .where(inArray(users.role, rolesWithPermission("helpdesk:use")))
916
+ .orderBy(asc(users.name));
917
+ return rows.map((row) => ({ id: String(row.id), name: row.name }));
918
+ },
919
+
920
+ async setAssignee(threadId, assignee, assignment) {
901
921
  await db
902
922
  .update(helpdeskThreads)
903
- .set({ assigneeId: assignee ? Number(assignee.id) : null })
923
+ .set({
924
+ assigneeId: assignee ? Number(assignee.id) : null,
925
+ assignmentNote: assignee ? assignment.note : null,
926
+ assignedBy: Number(assignment.by.id),
927
+ })
904
928
  .where(eq(helpdeskThreads.id, threadId));
905
929
  },
906
930
  };
@@ -972,7 +996,7 @@ export async function releaseSyncLease(): Promise<void> {
972
996
 
973
997
  **No drafter yet.** `HelpdeskDeps.drafter` is optional and left out: every new customer mail opens its ticket in review (`reviewReason: "no_draft"`, label "Zelf antwoorden") with an empty "Jouw antwoord" box. Staff write the reply; saving it creates a staff run (an ordinary draft run with `text: null`, `reason: "staff"`), and "Goedkeuren en versturen" saves and sends it. A blank reply is refused (422 `empty_reply`). When the DXV AI gateway drafter is published, add it as `drafter` in `deps.ts` (its `start` calls the published agent with the idempotency key) and call `completeDraft` when it reports; nothing else changes.
974
998
 
975
- `src/lib/helpdesk/deps.ts`: one `HelpdeskDeps` per call, built from the stored connection. The notifier sends in-app notifications (template `notifyUsers`) to everyone with `helpdesk:use`, linking to the ticket.
999
+ `src/lib/helpdesk/deps.ts`: one `HelpdeskDeps` per call, built from the stored connection. The notifier sends in-app notifications (template `notifyUsers`) to everyone with `helpdesk:use`, linking to the ticket. That matches this recipe's `getStaff`, where every helpdesk user has access to every connected mailbox; an app with access per person sends each event only to the people with access to `event.mailbox` (helpdesk README, Access per mailbox). `assigned` goes to the assignee only, with the internal note.
976
1000
 
977
1001
  ```ts
978
1002
  import "server-only";
@@ -995,6 +1019,16 @@ const notifier: Notifier = {
995
1019
  .select({ id: users.id })
996
1020
  .from(users)
997
1021
  .where(inArray(users.role, rolesWithPermission("helpdesk:use")));
1022
+ if (event.type === "assigned") {
1023
+ await notifyUsers([Number(event.assigneeId)], {
1024
+ type: "helpdesk.assigned",
1025
+ title: "Ticket aan jou toegewezen",
1026
+ body: [event.subject || "(geen onderwerp)", event.note].filter(Boolean).join(" · "),
1027
+ href: `/dashboard/helpdesk?ticket=${encodeURIComponent(event.threadId)}`,
1028
+ severity: "info",
1029
+ });
1030
+ return;
1031
+ }
998
1032
  if (event.type === "sync_failing" || event.type === "sync_recovered") {
999
1033
  const failing = event.type === "sync_failing";
1000
1034
  await notifyUsers(
@@ -1300,9 +1334,10 @@ async function handle(request: Request): Promise<Response> {
1300
1334
  isProduction: true,
1301
1335
  async getStaff() {
1302
1336
  const user = await getVerifiedUser();
1303
- return user && hasPermission(user.role, "helpdesk:use")
1304
- ? { id: String(user.id), name: user.name, email: user.email }
1305
- : null;
1337
+ if (!user || !hasPermission(user.role, "helpdesk:use")) return null;
1338
+ // The mailboxes this person may see. One shared mailbox: every helpdesk user gets it.
1339
+ // Per-person access: resolve the list from the app's own assignment instead.
1340
+ return { id: String(user.id), name: user.name, email: user.email, mailboxes: deps.config.connectedMailboxes };
1306
1341
  },
1307
1342
  });
1308
1343
  return inbox(request);
@@ -1719,7 +1754,7 @@ describe("helpdesk store on Postgres", () => {
1719
1754
  await syncMailbox(deps, MAILBOX);
1720
1755
  await syncMailbox(deps, MAILBOX);
1721
1756
 
1722
- const { rows } = await helpdeskInbox.listThreads({ states: null, mailbox: null, cursor: null, limit: 10 });
1757
+ const { rows } = await helpdeskInbox.listThreads({ states: null, mailboxes: [MAILBOX], viewerId: String(staffId), mailbox: null, cursor: null, limit: 10 });
1723
1758
  expect(rows).toHaveLength(1);
1724
1759
  const thread = rows[0]!.thread;
1725
1760
  expect(thread).toMatchObject({ state: "review", reviewReason: "no_draft" });
@@ -1738,17 +1773,22 @@ describe("helpdesk store on Postgres", () => {
1738
1773
  mailbox.deliver({ id: "m3", from: "derde@example.test", subject: "Offerte", conversationId: "c3", receivedDateTime: soon(3_000) });
1739
1774
  await syncMailbox(deps, MAILBOX);
1740
1775
 
1741
- const first = await helpdeskInbox.listThreads({ states: ["review"], mailbox: MAILBOX, cursor: null, limit: 1 });
1776
+ const first = await helpdeskInbox.listThreads({ states: ["review"], mailboxes: [MAILBOX], viewerId: String(staffId), mailbox: MAILBOX, cursor: null, limit: 1 });
1742
1777
  expect(first.rows).toHaveLength(1);
1743
- const second = await helpdeskInbox.listThreads({ states: ["review"], mailbox: MAILBOX, cursor: first.nextCursor, limit: 1 });
1778
+ const second = await helpdeskInbox.listThreads({ states: ["review"], mailboxes: [MAILBOX], viewerId: String(staffId), mailbox: MAILBOX, cursor: first.nextCursor, limit: 1 });
1744
1779
  expect(second.rows).toHaveLength(1);
1745
1780
  expect(second.nextCursor).toBeNull();
1746
1781
  expect(second.rows[0]!.thread.id).not.toBe(first.rows[0]!.thread.id);
1747
1782
 
1748
1783
  const target = first.rows[0]!.thread.id;
1749
- await helpdeskInbox.setAssignee(target, { id: String(staffId), name: "Medewerker Mia" });
1750
- const mine = await helpdeskInbox.listThreads({ states: null, mailbox: null, assigneeId: String(staffId), cursor: null, limit: 10 });
1784
+ const mia = { id: String(staffId), name: "Medewerker Mia" };
1785
+ await helpdeskInbox.setAssignee(target, mia, { by: mia, note: "Graag vandaag" });
1786
+ const mine = await helpdeskInbox.listThreads({ states: null, mailboxes: [MAILBOX], viewerId: mia.id, mailbox: null, assigneeId: mia.id, cursor: null, limit: 10 });
1751
1787
  expect(mine.rows.map((r) => r.assignee?.name)).toEqual(["Medewerker Mia"]);
1788
+ // Without mailboxes, only the tickets assigned to the viewer.
1789
+ const assignedOnly = await helpdeskInbox.listThreads({ states: null, mailboxes: [], viewerId: mia.id, mailbox: null, cursor: null, limit: 10 });
1790
+ expect(assignedOnly.rows.map((r) => r.thread.id)).toEqual([target]);
1791
+ expect((await helpdeskInbox.listAssignees()).map((p) => p.id)).toContain(mia.id);
1752
1792
 
1753
1793
  await dismissThread(deps, { threadId: target, dismissedBy: String(staffId) });
1754
1794
  const dismissed = await helpdeskStore.getThread(target);
@@ -1768,7 +1808,7 @@ describe("helpdesk store on Postgres", () => {
1768
1808
  });
1769
1809
 
1770
1810
  it("keeps reply attachments in order and never removes a sent one", async () => {
1771
- const { rows } = await helpdeskInbox.listThreads({ states: null, mailbox: null, cursor: null, limit: 10 });
1811
+ const { rows } = await helpdeskInbox.listThreads({ states: null, mailboxes: [MAILBOX], viewerId: String(staffId), mailbox: null, cursor: null, limit: 10 });
1772
1812
  const threadId = rows[0]!.thread.id;
1773
1813
  const store = helpdeskReplyFiles.store;
1774
1814
  const base = { threadId, mailbox: MAILBOX, contentType: "application/pdf", size: 10, addedBy: String(staffId), placedDraftId: null, sentIntentId: null };
@@ -1794,7 +1834,7 @@ describe("helpdesk store on Postgres", () => {
1794
1834
  await helpdeskStore.saveSyncState(MAILBOX, { ...state, failingSince: null, failures: 0, lastError: null });
1795
1835
  expect(await helpdeskStore.getSyncState(MAILBOX)).toMatchObject({ failingSince: null, failures: 0, lastError: null });
1796
1836
 
1797
- const { rows } = await helpdeskInbox.listThreads({ states: null, mailbox: null, cursor: null, limit: 10 });
1837
+ const { rows } = await helpdeskInbox.listThreads({ states: null, mailboxes: [MAILBOX], viewerId: String(staffId), mailbox: null, cursor: null, limit: 10 });
1798
1838
  const now = new Date().toISOString();
1799
1839
  const intent = { id: "send-x", mailbox: MAILBOX, threadId: rows[0]!.thread.id, draftId: "d-x", approvedBy: String(staffId), status: "unknown" as const, createdAt: now, updatedAt: now, error: null };
1800
1840
  await helpdeskStore.createSendIntentIfAbsent(intent);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
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",