@dxv-systems/mail-graph 0.0.0-stage → 0.1.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.
Files changed (52) hide show
  1. package/README.md +201 -3
  2. package/dist/auth.d.ts +41 -0
  3. package/dist/auth.js +184 -0
  4. package/dist/client.d.ts +18 -0
  5. package/dist/client.js +34 -0
  6. package/dist/errors.d.ts +25 -0
  7. package/dist/errors.js +35 -0
  8. package/dist/http.d.ts +44 -0
  9. package/dist/http.js +182 -0
  10. package/dist/index.d.ts +9 -0
  11. package/dist/index.js +14 -0
  12. package/dist/limiter.d.ts +7 -0
  13. package/dist/limiter.js +29 -0
  14. package/dist/links.d.ts +2 -0
  15. package/dist/links.js +25 -0
  16. package/dist/mailbox.d.ts +41 -0
  17. package/dist/mailbox.js +429 -0
  18. package/dist/setup/access.d.ts +20 -0
  19. package/dist/setup/access.js +71 -0
  20. package/dist/setup/address.d.ts +32 -0
  21. package/dist/setup/address.js +69 -0
  22. package/dist/setup/consent.d.ts +40 -0
  23. package/dist/setup/consent.js +78 -0
  24. package/dist/setup/constants.d.ts +2 -0
  25. package/dist/setup/constants.js +5 -0
  26. package/dist/setup/exchange-graph.d.ts +23 -0
  27. package/dist/setup/exchange-graph.js +119 -0
  28. package/dist/setup/exchange-script.d.ts +1 -0
  29. package/dist/setup/exchange-script.js +190 -0
  30. package/dist/setup/handlers.d.ts +30 -0
  31. package/dist/setup/handlers.js +571 -0
  32. package/dist/setup/index.d.ts +18 -0
  33. package/dist/setup/index.js +38 -0
  34. package/dist/setup/it-link.d.ts +17 -0
  35. package/dist/setup/it-link.js +17 -0
  36. package/dist/setup/messages.d.ts +22 -0
  37. package/dist/setup/messages.js +36 -0
  38. package/dist/setup/react.d.ts +8 -0
  39. package/dist/setup/react.js +451 -0
  40. package/dist/setup/script.d.ts +27 -0
  41. package/dist/setup/script.js +74 -0
  42. package/dist/setup/signing.d.ts +18 -0
  43. package/dist/setup/signing.js +56 -0
  44. package/dist/setup/tenant.d.ts +38 -0
  45. package/dist/setup/tenant.js +45 -0
  46. package/dist/setup/types.d.ts +76 -0
  47. package/dist/setup/types.js +2 -0
  48. package/dist/types.d.ts +98 -0
  49. package/dist/types.js +2 -0
  50. package/dist/util.d.ts +4 -0
  51. package/dist/util.js +17 -0
  52. package/package.json +70 -6
@@ -0,0 +1,571 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createM365SetupHandlers = createM365SetupHandlers;
4
+ const auth_1 = require("../auth");
5
+ const access_1 = require("./access");
6
+ const address_1 = require("./address");
7
+ const consent_1 = require("./consent");
8
+ const exchange_graph_1 = require("./exchange-graph");
9
+ const it_link_1 = require("./it-link");
10
+ const messages_1 = require("./messages");
11
+ const script_1 = require("./script");
12
+ const constants_1 = require("./constants");
13
+ const signing_1 = require("./signing");
14
+ const tenant_1 = require("./tenant");
15
+ const DEFAULT_IT_LINK_TTL_MS = 7 * 24 * 60 * 60000;
16
+ const DEFAULT_CONSENT_STATE_TTL_MS = 60 * 60000;
17
+ const DEFAULT_CHECK_INTERVAL_MS = 60000;
18
+ const MIN_CHECK_INTERVAL_MS = 15000;
19
+ const MAX_BODY_CHARS = 20000;
20
+ function json(status, body) {
21
+ return new Response(JSON.stringify(body), {
22
+ status,
23
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" },
24
+ });
25
+ }
26
+ function fail(status, code, extra = {}) {
27
+ return json(status, { error: code, message: messages_1.SETUP_ERROR_MESSAGES[code], ...extra });
28
+ }
29
+ function escapeHtml(text) {
30
+ return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
31
+ }
32
+ function htmlMessage(status, title, message) {
33
+ const body = `<!doctype html><html lang="nl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title></head><body><main><h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p></main></body></html>`;
34
+ return new Response(body, {
35
+ status,
36
+ headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" },
37
+ });
38
+ }
39
+ function redirect(location) {
40
+ return new Response(null, { status: 303, headers: { Location: location, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" } });
41
+ }
42
+ async function readJson(request) {
43
+ const text = await request.text().catch(() => "");
44
+ if (text.length > MAX_BODY_CHARS)
45
+ return null;
46
+ if (text.trim() === "")
47
+ return {};
48
+ try {
49
+ const parsed = JSON.parse(text);
50
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
56
+ function automaticCheckMailbox(mailboxes, candidates) {
57
+ const domains = new Set(mailboxes.map((m) => (0, address_1.mailboxDomain)(m)));
58
+ for (const raw of candidates) {
59
+ const address = raw ? (0, address_1.normalizeMailbox)(raw) : null;
60
+ if (address && !mailboxes.includes(address) && domains.has((0, address_1.mailboxDomain)(address)))
61
+ return address;
62
+ }
63
+ return null;
64
+ }
65
+ async function readSignedInUser(accessToken, fetchImpl) {
66
+ try {
67
+ const response = await fetchImpl("https://graph.microsoft.com/v1.0/me?$select=userPrincipalName,mail", {
68
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
69
+ signal: AbortSignal.timeout(15000),
70
+ });
71
+ if (!response.ok)
72
+ return null;
73
+ const body = (await response.json());
74
+ return {
75
+ userPrincipalName: typeof body.userPrincipalName === "string" ? body.userPrincipalName : null,
76
+ mail: typeof body.mail === "string" ? body.mail : null,
77
+ };
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
83
+ function createM365SetupHandlers(config) {
84
+ (0, signing_1.assertSecret)(config.secret);
85
+ const origin = new URL(config.appOrigin).origin;
86
+ const now = config.now ?? Date.now;
87
+ const iso = () => new Date(now()).toISOString();
88
+ const itLinkTtlMs = config.itLinkTtlMs ?? DEFAULT_IT_LINK_TTL_MS;
89
+ const consentStateTtlMs = config.consentStateTtlMs ?? DEFAULT_CONSENT_STATE_TTL_MS;
90
+ const checkIntervalMs = Math.max(MIN_CHECK_INTERVAL_MS, config.checkIntervalMs ?? DEFAULT_CHECK_INTERVAL_MS);
91
+ const clientId = config.clientId ?? "";
92
+ const itLinkUrl = (token) => `${origin}${config.itLinkPagePath.replace(/\/$/, "")}/${token}`;
93
+ function emptyConnection() {
94
+ return {
95
+ setupId: (0, signing_1.randomId)(),
96
+ step: "not_started",
97
+ tenantId: null,
98
+ mailboxes: [],
99
+ checkMailbox: null,
100
+ objectId: null,
101
+ objectIdSource: null,
102
+ consentNonce: null,
103
+ consentError: null,
104
+ failure: null,
105
+ checks: null,
106
+ itLinkId: null,
107
+ itLinkExpiresAt: null,
108
+ consentedAt: null,
109
+ setupMethod: null,
110
+ exchangeSetupError: null,
111
+ scriptRanAt: null,
112
+ lastCheckedAt: null,
113
+ connectedAt: null,
114
+ updatedAt: iso(),
115
+ };
116
+ }
117
+ const graphSetupAvailable = Boolean(config.getClientAssertion);
118
+ async function save(connection) {
119
+ const next = { ...connection, updatedAt: iso() };
120
+ await config.store.save(next);
121
+ return next;
122
+ }
123
+ function linkToken(request) {
124
+ return request.headers.get(constants_1.IT_LINK_HEADER) ?? new URL(request.url).searchParams.get("t");
125
+ }
126
+ async function resolveViewer(request, connection, allowItLink, statusOnly = false) {
127
+ const token = linkToken(request);
128
+ if (token !== null) {
129
+ if (!allowItLink || !connection)
130
+ return fail(401, "link_invalid");
131
+ const result = (0, it_link_1.verifyItLinkToken)(config.secret, token, connection, now());
132
+ const afterConnect = !result.ok &&
133
+ result.reason === "revoked" &&
134
+ statusOnly &&
135
+ connection.step === "connected" &&
136
+ result.setupId === connection.setupId;
137
+ if (afterConnect)
138
+ return { viewer: "it", expiresAt: null };
139
+ if (!result.ok)
140
+ return fail(401, "link_invalid");
141
+ return { viewer: "it", expiresAt: result.expiresAt };
142
+ }
143
+ const admin = await config.getAdmin(request);
144
+ if (!admin)
145
+ return fail(401, "unauthorized");
146
+ return { viewer: "admin", admin };
147
+ }
148
+ function toStatus(connection, viewer) {
149
+ const scriptRanAt = connection.scriptRanAt ? Date.parse(connection.scriptRanAt) : null;
150
+ const mine = viewer.viewer;
151
+ return {
152
+ viewer: mine,
153
+ step: connection.step,
154
+ companyName: config.companyName,
155
+ entraAppName: config.entraAppName,
156
+ appId: clientId,
157
+ tenantId: connection.tenantId,
158
+ mailboxes: connection.mailboxes,
159
+ checkMailbox: connection.checkMailbox,
160
+ objectId: connection.objectId,
161
+ consentError: connection.consentError,
162
+ setupMethod: connection.setupMethod ?? null,
163
+ exchangeSetupError: connection.exchangeSetupError ?? null,
164
+ graphSetupAvailable,
165
+ setupReady: config.setupReady,
166
+ notices: connection.notices ?? [],
167
+ failure: connection.failure,
168
+ checks: connection.checks,
169
+ scriptRanAt: connection.scriptRanAt,
170
+ lastCheckedAt: connection.lastCheckedAt,
171
+ checkDeadline: scriptRanAt === null ? null : new Date(scriptRanAt + access_1.ACCESS_CHECK_WINDOW_MS).toISOString(),
172
+ connectedAt: connection.connectedAt,
173
+ signedInAs: connection.signedInAs ?? null,
174
+ itLinkExpiresAt: viewer.viewer === "it"
175
+ ? viewer.expiresAt === null
176
+ ? null
177
+ : new Date(viewer.expiresAt).toISOString()
178
+ : connection.itLinkId
179
+ ? connection.itLinkExpiresAt
180
+ : null,
181
+ };
182
+ }
183
+ async function check(connection) {
184
+ if (!connection.tenantId || connection.mailboxes.length === 0)
185
+ return connection;
186
+ if (!connection.checkMailbox) {
187
+ return save({ ...connection, step: "failed", failure: "check_mailbox_missing", checks: null, lastCheckedAt: iso() });
188
+ }
189
+ const graph = config.createGraphClient(connection.tenantId);
190
+ const checks = await (0, access_1.checkMailboxes)(graph, connection.mailboxes, connection.checkMailbox);
191
+ const scriptRanAt = connection.scriptRanAt ? Date.parse(connection.scriptRanAt) : null;
192
+ const evaluation = (0, access_1.evaluateAccess)(checks, scriptRanAt, now());
193
+ const latest = (await config.store.load()) ?? connection;
194
+ if (latest.setupId !== connection.setupId || latest.step !== connection.step)
195
+ return latest;
196
+ const next = { ...latest, checks, lastCheckedAt: iso() };
197
+ const wasConnected = latest.step === "connected";
198
+ if (evaluation.outcome === "connected") {
199
+ next.step = "connected";
200
+ next.failure = null;
201
+ next.connectedAt = wasConnected ? latest.connectedAt : iso();
202
+ if (!wasConnected || latest.noticesComplete !== true) {
203
+ const read = await (0, access_1.readSetupNotices)(graph, connection.mailboxes);
204
+ if (read.complete || !wasConnected)
205
+ next.notices = read.notices;
206
+ next.noticesComplete = read.complete;
207
+ }
208
+ next.itLinkId = null;
209
+ next.itLinkExpiresAt = null;
210
+ }
211
+ else if (evaluation.outcome === "pending") {
212
+ next.step = "awaiting_access";
213
+ next.failure = null;
214
+ }
215
+ else if (evaluation.outcome === "failed") {
216
+ next.step = "failed";
217
+ next.failure = evaluation.failure;
218
+ }
219
+ const saved = await save(next);
220
+ if (!wasConnected && saved.step === "connected")
221
+ await config.onConnected?.(saved);
222
+ return saved;
223
+ }
224
+ const checkable = (c) => c.scriptRanAt !== null && (c.step === "awaiting_access" || c.step === "connected" || c.step === "failed");
225
+ async function status(request) {
226
+ let connection = (await config.store.load()) ?? null;
227
+ const viewer = await resolveViewer(request, connection, true, true);
228
+ if (viewer instanceof Response)
229
+ return viewer;
230
+ if (!connection)
231
+ return json(200, toStatus(emptyConnection(), viewer));
232
+ const last = connection.lastCheckedAt ? Date.parse(connection.lastCheckedAt) : 0;
233
+ if (connection.step === "awaiting_access" && now() - last >= checkIntervalMs)
234
+ connection = await check(connection);
235
+ return json(200, toStatus(connection, viewer));
236
+ }
237
+ async function saveMailboxes(request) {
238
+ const existing = await config.store.load();
239
+ const viewer = await resolveViewer(request, existing, false);
240
+ if (viewer instanceof Response)
241
+ return viewer;
242
+ const body = await readJson(request);
243
+ if (!body)
244
+ return fail(400, "invalid_input");
245
+ const input = (0, address_1.validateMailboxInput)(body.mailboxes, body.checkMailbox);
246
+ if (!input.ok)
247
+ return fail(400, "invalid_input", { errors: input.errors });
248
+ const tenant = await (0, tenant_1.resolveMailboxTenant)(input.checkMailbox ? [...input.mailboxes, input.checkMailbox] : input.mailboxes, {
249
+ fetch: config.fetch,
250
+ });
251
+ if (!tenant.ok) {
252
+ const { ok: _ok, code, ...detail } = tenant;
253
+ return fail(code === "lookup_failed" ? 503 : 422, code, detail);
254
+ }
255
+ if (body.validateOnly === true)
256
+ return json(200, { tenantId: tenant.tenantId });
257
+ const current = existing ?? emptyConnection();
258
+ if (current.consentedAt && current.tenantId && current.tenantId !== tenant.tenantId) {
259
+ return fail(409, "tenant_change_needs_reset");
260
+ }
261
+ const sameMailboxes = current.mailboxes.length === input.mailboxes.length && input.mailboxes.every((m) => current.mailboxes.includes(m));
262
+ const checkMailbox = input.checkMailbox ??
263
+ automaticCheckMailbox(input.mailboxes, [current.checkMailbox, viewer.viewer === "admin" ? viewer.admin.email : null]);
264
+ const next = { ...current, tenantId: tenant.tenantId, mailboxes: input.mailboxes, checkMailbox };
265
+ if (!current.consentedAt) {
266
+ next.step = "awaiting_consent";
267
+ }
268
+ else if (!sameMailboxes) {
269
+ const step = current.setupMethod === "graph" ? "awaiting_consent" : "awaiting_script";
270
+ Object.assign(next, { step, scriptRanAt: null, checks: null, failure: null, lastCheckedAt: null, exchangeSetupError: null });
271
+ }
272
+ else if (current.checkMailbox !== checkMailbox) {
273
+ next.lastCheckedAt = null;
274
+ }
275
+ const saved = await save(next);
276
+ if (checkable(saved) && current.checkMailbox !== checkMailbox && sameMailboxes) {
277
+ return json(200, toStatus(await check(saved), viewer));
278
+ }
279
+ return json(200, toStatus(saved, viewer));
280
+ }
281
+ async function startConsent(request) {
282
+ const connection = await config.store.load();
283
+ const viewer = await resolveViewer(request, connection, true);
284
+ if (viewer instanceof Response)
285
+ return viewer;
286
+ if (!connection?.tenantId || !["awaiting_consent", "awaiting_script", "failed"].includes(connection.step)) {
287
+ return fail(409, "wrong_step");
288
+ }
289
+ if (!config.setupReady)
290
+ return fail(503, "setup_pending");
291
+ const body = await readJson(request);
292
+ const method = body?.method === "script" || !graphSetupAvailable ? "script" : "graph";
293
+ const nonce = (0, signing_1.randomId)();
294
+ const state = (0, consent_1.createConsentState)(config.secret, {
295
+ s: connection.setupId,
296
+ t: connection.tenantId,
297
+ n: nonce,
298
+ m: method,
299
+ via: viewer.viewer,
300
+ ...(viewer.viewer === "it" ? { l: linkToken(request) ?? undefined } : {}),
301
+ }, now() + consentStateTtlMs);
302
+ await save({ ...connection, consentNonce: nonce, consentError: null });
303
+ const urlInput = { tenantId: connection.tenantId, clientId, redirectUri: `${origin}${consent_1.CONSENT_CALLBACK_PATH}`, state };
304
+ const url = method === "graph" ? (0, consent_1.buildSetupAuthorizeUrl)(urlInput) : (0, consent_1.buildAdminConsentUrl)(urlInput);
305
+ return json(200, { url, method });
306
+ }
307
+ async function consentCallback(request) {
308
+ const connection = await config.store.load();
309
+ const params = new URL(request.url).searchParams;
310
+ const result = connection
311
+ ? (0, consent_1.verifyConsentCallback)(params, {
312
+ secret: config.secret,
313
+ setupId: connection.setupId,
314
+ tenantId: connection.tenantId,
315
+ nonce: connection.consentNonce,
316
+ now: now(),
317
+ })
318
+ : { ok: false, code: "state_invalid" };
319
+ const claims = result.claims;
320
+ if (!connection || !claims)
321
+ 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}`;
323
+ if (!result.ok) {
324
+ if (result.code !== "state_stale") {
325
+ await save({ ...connection, consentError: result.code, consentNonce: null });
326
+ }
327
+ return redirect(back);
328
+ }
329
+ if (claims.m === "graph" && result.code)
330
+ return graphSetup(connection, result.tenantId, result.code, back);
331
+ const next = {
332
+ ...connection,
333
+ consentNonce: null,
334
+ consentError: null,
335
+ consentedAt: iso(),
336
+ step: connection.step === "awaiting_consent" ? "awaiting_script" : connection.step,
337
+ };
338
+ try {
339
+ const identity = await config.createGraphClient(result.tenantId).getAppIdentity();
340
+ const objectId = (0, address_1.normalizeGuid)(identity.objectId);
341
+ if (objectId && identity.tenantId.toLowerCase() === result.tenantId) {
342
+ next.objectId = objectId;
343
+ next.objectIdSource = "token";
344
+ }
345
+ }
346
+ catch {
347
+ }
348
+ await save(next);
349
+ return redirect(back);
350
+ }
351
+ async function graphSetup(connection, tenantId, code, back) {
352
+ const base = {
353
+ ...connection,
354
+ consentNonce: null,
355
+ consentError: null,
356
+ consentedAt: connection.consentedAt ?? iso(),
357
+ setupMethod: "graph",
358
+ };
359
+ const toScript = async (exchangeSetupError, objectId = connection.objectId) => {
360
+ await save({
361
+ ...base,
362
+ step: "awaiting_script",
363
+ exchangeSetupError,
364
+ objectId,
365
+ objectIdSource: objectId ? "token" : connection.objectIdSource,
366
+ });
367
+ return redirect(back);
368
+ };
369
+ if (!config.getClientAssertion)
370
+ return toScript("sign_in_failed");
371
+ let delegated;
372
+ try {
373
+ delegated = await (0, auth_1.redeemAuthorizationCode)({
374
+ tenantId,
375
+ clientId,
376
+ code,
377
+ redirectUri: `${origin}${consent_1.CONSENT_CALLBACK_PATH}`,
378
+ scopes: consent_1.GRAPH_SETUP_SCOPES,
379
+ getClientAssertion: config.getClientAssertion,
380
+ fetch: config.fetch ?? fetch,
381
+ });
382
+ }
383
+ catch (err) {
384
+ console.warn("m365 setup: code redemption failed", { detail: err instanceof Error ? err.message.slice(0, 500) : String(err) });
385
+ return toScript("sign_in_failed");
386
+ }
387
+ if (delegated.tenantId.toLowerCase() !== tenantId) {
388
+ await save({ ...connection, consentNonce: null, consentError: "wrong_tenant" });
389
+ return redirect(back);
390
+ }
391
+ const me = await readSignedInUser(delegated.accessToken, config.fetch ?? fetch);
392
+ base.signedInAs = me?.userPrincipalName ?? null;
393
+ if (!connection.checkMailbox || connection.mailboxes.includes(connection.checkMailbox)) {
394
+ base.checkMailbox = automaticCheckMailbox(connection.mailboxes, [me?.mail ?? null]);
395
+ }
396
+ let objectId = null;
397
+ try {
398
+ const identity = await config.createGraphClient(tenantId).getAppIdentity();
399
+ if (identity.tenantId.toLowerCase() === tenantId)
400
+ objectId = (0, address_1.normalizeGuid)(identity.objectId);
401
+ }
402
+ catch {
403
+ objectId = null;
404
+ }
405
+ if (!objectId)
406
+ return toScript("no_object_id", null);
407
+ const grant = await (0, exchange_graph_1.grantExchangeAccess)({
408
+ accessToken: delegated.accessToken,
409
+ servicePrincipalId: objectId,
410
+ appId: clientId,
411
+ mailboxes: connection.mailboxes,
412
+ fetch: config.fetch ?? fetch,
413
+ });
414
+ if (!grant.ok) {
415
+ console.warn("m365 setup: Exchange access through Graph failed", { code: grant.code, detail: grant.detail });
416
+ return toScript(grant.code, objectId);
417
+ }
418
+ const saved = await save({
419
+ ...base,
420
+ objectId,
421
+ objectIdSource: "token",
422
+ exchangeSetupError: null,
423
+ step: "awaiting_access",
424
+ scriptRanAt: iso(),
425
+ failure: null,
426
+ checks: null,
427
+ lastCheckedAt: null,
428
+ });
429
+ await check(saved).catch(() => undefined);
430
+ return redirect(back);
431
+ }
432
+ async function setObjectId(request) {
433
+ const connection = await config.store.load();
434
+ const viewer = await resolveViewer(request, connection, true);
435
+ if (viewer instanceof Response)
436
+ return viewer;
437
+ if (!connection || connection.step !== "awaiting_script" || connection.objectIdSource === "token") {
438
+ return fail(409, "wrong_step");
439
+ }
440
+ const body = await readJson(request);
441
+ const objectId = typeof body?.objectId === "string" ? (0, address_1.normalizeGuid)(body.objectId) : null;
442
+ if (!objectId)
443
+ return fail(400, "invalid_object_id");
444
+ return json(200, toStatus(await save({ ...connection, objectId, objectIdSource: "manual" }), viewer));
445
+ }
446
+ async function scriptRan(request) {
447
+ const connection = await config.store.load();
448
+ const viewer = await resolveViewer(request, connection, true);
449
+ if (viewer instanceof Response)
450
+ return viewer;
451
+ if (!connection?.objectId || !["awaiting_script", "awaiting_access", "failed"].includes(connection.step)) {
452
+ return fail(409, "wrong_step");
453
+ }
454
+ const saved = await save({
455
+ ...connection,
456
+ step: "awaiting_access",
457
+ setupMethod: "script",
458
+ exchangeSetupError: null,
459
+ scriptRanAt: iso(),
460
+ failure: null,
461
+ checks: null,
462
+ lastCheckedAt: null,
463
+ });
464
+ return json(200, toStatus(await check(saved), viewer));
465
+ }
466
+ async function checkNow(request) {
467
+ let connection = await config.store.load();
468
+ const viewer = await resolveViewer(request, connection, true);
469
+ if (viewer instanceof Response)
470
+ return viewer;
471
+ if (!connection || !checkable(connection))
472
+ return fail(409, "wrong_step");
473
+ const last = connection.lastCheckedAt ? Date.parse(connection.lastCheckedAt) : 0;
474
+ if (now() - last >= MIN_CHECK_INTERVAL_MS)
475
+ connection = await check(connection);
476
+ return json(200, toStatus(connection, viewer));
477
+ }
478
+ async function downloadScript(request) {
479
+ const connection = await config.store.load();
480
+ const viewer = await resolveViewer(request, connection, true);
481
+ if (viewer instanceof Response)
482
+ return viewer;
483
+ return new Response((0, script_1.buildExchangeScript)(), {
484
+ status: 200,
485
+ headers: {
486
+ "Content-Type": "application/octet-stream",
487
+ "Content-Disposition": `attachment; filename="${script_1.SCRIPT_FILE_NAME}"`,
488
+ "Cache-Control": "no-store",
489
+ },
490
+ });
491
+ }
492
+ async function createItLink(request) {
493
+ const connection = await config.store.load();
494
+ const viewer = await resolveViewer(request, connection, false);
495
+ if (viewer instanceof Response)
496
+ return viewer;
497
+ if (!connection?.tenantId || connection.step === "not_started")
498
+ return fail(409, "wrong_step");
499
+ const linkId = (0, signing_1.randomId)();
500
+ const expiresAt = now() + itLinkTtlMs;
501
+ await save({ ...connection, itLinkId: linkId, itLinkExpiresAt: new Date(expiresAt).toISOString() });
502
+ const token = (0, it_link_1.createItLinkToken)(config.secret, connection.setupId, linkId, expiresAt);
503
+ return json(200, { url: itLinkUrl(token), expiresAt: new Date(expiresAt).toISOString() });
504
+ }
505
+ async function revokeItLink(request) {
506
+ const connection = await config.store.load();
507
+ const viewer = await resolveViewer(request, connection, false);
508
+ if (viewer instanceof Response)
509
+ return viewer;
510
+ if (!connection)
511
+ return fail(409, "wrong_step");
512
+ return json(200, toStatus(await save({ ...connection, itLinkId: null, itLinkExpiresAt: null }), viewer));
513
+ }
514
+ async function reset(request) {
515
+ const connection = await config.store.load();
516
+ const viewer = await resolveViewer(request, connection, false);
517
+ if (viewer instanceof Response)
518
+ return viewer;
519
+ const body = await readJson(request);
520
+ if (body?.confirm !== true)
521
+ return fail(400, "confirm_required");
522
+ const saved = await save(emptyConnection());
523
+ if (connection)
524
+ await config.onReset?.(connection);
525
+ return json(200, toStatus(saved, viewer));
526
+ }
527
+ const routes = {
528
+ status: { GET: status },
529
+ mailboxes: { POST: saveMailboxes },
530
+ "consent/start": { POST: startConsent },
531
+ "consent/callback": { GET: consentCallback },
532
+ "object-id": { POST: setObjectId },
533
+ "script-ran": { POST: scriptRan },
534
+ check: { POST: checkNow },
535
+ script: { GET: downloadScript },
536
+ "it-link": { POST: createItLink, DELETE: revokeItLink },
537
+ reset: { POST: reset },
538
+ };
539
+ async function handle(request) {
540
+ const url = new URL(request.url);
541
+ const sub = url.pathname.startsWith(`${constants_1.SETUP_BASE_PATH}/`) ? url.pathname.slice(constants_1.SETUP_BASE_PATH.length + 1).replace(/\/$/, "") : null;
542
+ const route = sub === null ? undefined : routes[sub];
543
+ if (!route)
544
+ return fail(404, "not_found");
545
+ const handler = route[request.method.toUpperCase()];
546
+ if (!handler)
547
+ return fail(405, "method_not_allowed");
548
+ const isCallback = sub === "consent/callback";
549
+ if (!config.isProduction) {
550
+ return isCallback
551
+ ? htmlMessage(403, "Koppelen niet gelukt", messages_1.SETUP_ERROR_MESSAGES.not_production)
552
+ : fail(403, "not_production");
553
+ }
554
+ if (!clientId) {
555
+ return isCallback ? htmlMessage(503, "Koppelen niet gelukt", messages_1.SETUP_ERROR_MESSAGES.not_configured) : fail(503, "not_configured");
556
+ }
557
+ const requestOrigin = request.headers.get("origin");
558
+ if (request.method !== "GET" && requestOrigin !== null && requestOrigin !== origin)
559
+ return fail(403, "forbidden_origin");
560
+ return handler(request);
561
+ }
562
+ async function runAccessCheck() {
563
+ if (!config.isProduction || !clientId)
564
+ return null;
565
+ const connection = await config.store.load();
566
+ if (!connection || !checkable(connection))
567
+ return null;
568
+ return check(connection);
569
+ }
570
+ return { handle, runAccessCheck };
571
+ }
@@ -0,0 +1,18 @@
1
+ export { createM365SetupHandlers } from "./handlers";
2
+ export { IT_LINK_HEADER, SETUP_BASE_PATH } from "./constants";
3
+ export type { M365SetupConfig, M365SetupHandlers } from "./handlers";
4
+ export { ACCESS_CHECK_WINDOW_MS, checkMailboxes, evaluateAccess } from "./access";
5
+ export type { AccessEvaluation } from "./access";
6
+ export { MAX_MAILBOXES, normalizeMailbox, validateMailboxInput } from "./address";
7
+ export type { MailboxInputError, MailboxInputResult } from "./address";
8
+ export { buildAdminConsentUrl, CONSENT_CALLBACK_PATH, createConsentState, verifyConsentCallback } from "./consent";
9
+ export type { AdminConsentUrlInput, ConsentCallbackExpectation, ConsentCallbackResult, ConsentStateClaims } from "./consent";
10
+ export { createItLinkToken, verifyItLinkToken } from "./it-link";
11
+ export type { ItLinkResult } from "./it-link";
12
+ export { CONSENT_ERROR_MESSAGES, SETUP_ERROR_MESSAGES } from "./messages";
13
+ export type { SetupErrorCode } from "./messages";
14
+ export { buildExchangeScript, buildScriptInvocation, EXECUTION_POLICY_TIP, exchangeGroupName, psQuote, SCRIPT_FILE_NAME, ScriptInputInvalid, } from "./script";
15
+ export type { ScriptInputError, ScriptInvocationInput, ScriptSignIn } from "./script";
16
+ export { lookupTenant, resolveMailboxTenant } from "./tenant";
17
+ export type { DomainLookup, TenantLookupOptions, TenantResolution } from "./tenant";
18
+ export type { ConnectionStore, ConsentErrorCode, FailureCode, M365Connection, MailboxCheck, MailboxRole, SetupAdmin, SetupStatus, SetupStep, SetupViewer, } from "./types";
@@ -0,0 +1,38 @@
1
+ "use strict";
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;
4
+ var handlers_1 = require("./handlers");
5
+ Object.defineProperty(exports, "createM365SetupHandlers", { enumerable: true, get: function () { return handlers_1.createM365SetupHandlers; } });
6
+ var constants_1 = require("./constants");
7
+ Object.defineProperty(exports, "IT_LINK_HEADER", { enumerable: true, get: function () { return constants_1.IT_LINK_HEADER; } });
8
+ Object.defineProperty(exports, "SETUP_BASE_PATH", { enumerable: true, get: function () { return constants_1.SETUP_BASE_PATH; } });
9
+ var access_1 = require("./access");
10
+ Object.defineProperty(exports, "ACCESS_CHECK_WINDOW_MS", { enumerable: true, get: function () { return access_1.ACCESS_CHECK_WINDOW_MS; } });
11
+ Object.defineProperty(exports, "checkMailboxes", { enumerable: true, get: function () { return access_1.checkMailboxes; } });
12
+ Object.defineProperty(exports, "evaluateAccess", { enumerable: true, get: function () { return access_1.evaluateAccess; } });
13
+ var address_1 = require("./address");
14
+ Object.defineProperty(exports, "MAX_MAILBOXES", { enumerable: true, get: function () { return address_1.MAX_MAILBOXES; } });
15
+ Object.defineProperty(exports, "normalizeMailbox", { enumerable: true, get: function () { return address_1.normalizeMailbox; } });
16
+ Object.defineProperty(exports, "validateMailboxInput", { enumerable: true, get: function () { return address_1.validateMailboxInput; } });
17
+ var consent_1 = require("./consent");
18
+ Object.defineProperty(exports, "buildAdminConsentUrl", { enumerable: true, get: function () { return consent_1.buildAdminConsentUrl; } });
19
+ Object.defineProperty(exports, "CONSENT_CALLBACK_PATH", { enumerable: true, get: function () { return consent_1.CONSENT_CALLBACK_PATH; } });
20
+ Object.defineProperty(exports, "createConsentState", { enumerable: true, get: function () { return consent_1.createConsentState; } });
21
+ Object.defineProperty(exports, "verifyConsentCallback", { enumerable: true, get: function () { return consent_1.verifyConsentCallback; } });
22
+ var it_link_1 = require("./it-link");
23
+ Object.defineProperty(exports, "createItLinkToken", { enumerable: true, get: function () { return it_link_1.createItLinkToken; } });
24
+ Object.defineProperty(exports, "verifyItLinkToken", { enumerable: true, get: function () { return it_link_1.verifyItLinkToken; } });
25
+ var messages_1 = require("./messages");
26
+ Object.defineProperty(exports, "CONSENT_ERROR_MESSAGES", { enumerable: true, get: function () { return messages_1.CONSENT_ERROR_MESSAGES; } });
27
+ Object.defineProperty(exports, "SETUP_ERROR_MESSAGES", { enumerable: true, get: function () { return messages_1.SETUP_ERROR_MESSAGES; } });
28
+ var script_1 = require("./script");
29
+ Object.defineProperty(exports, "buildExchangeScript", { enumerable: true, get: function () { return script_1.buildExchangeScript; } });
30
+ Object.defineProperty(exports, "buildScriptInvocation", { enumerable: true, get: function () { return script_1.buildScriptInvocation; } });
31
+ Object.defineProperty(exports, "EXECUTION_POLICY_TIP", { enumerable: true, get: function () { return script_1.EXECUTION_POLICY_TIP; } });
32
+ Object.defineProperty(exports, "exchangeGroupName", { enumerable: true, get: function () { return script_1.exchangeGroupName; } });
33
+ Object.defineProperty(exports, "psQuote", { enumerable: true, get: function () { return script_1.psQuote; } });
34
+ Object.defineProperty(exports, "SCRIPT_FILE_NAME", { enumerable: true, get: function () { return script_1.SCRIPT_FILE_NAME; } });
35
+ Object.defineProperty(exports, "ScriptInputInvalid", { enumerable: true, get: function () { return script_1.ScriptInputInvalid; } });
36
+ var tenant_1 = require("./tenant");
37
+ Object.defineProperty(exports, "lookupTenant", { enumerable: true, get: function () { return tenant_1.lookupTenant; } });
38
+ Object.defineProperty(exports, "resolveMailboxTenant", { enumerable: true, get: function () { return tenant_1.resolveMailboxTenant; } });
@@ -0,0 +1,17 @@
1
+ import { type VerifyFailure } from "./signing";
2
+ export declare function createItLinkToken(secret: string, setupId: string, linkId: string, expiresAt: number): string;
3
+ export type ItLinkResult = {
4
+ ok: true;
5
+ expiresAt: number;
6
+ } | {
7
+ ok: false;
8
+ reason: VerifyFailure;
9
+ } | {
10
+ ok: false;
11
+ reason: "revoked";
12
+ setupId: string;
13
+ };
14
+ export declare function verifyItLinkToken(secret: string, token: unknown, current: {
15
+ setupId: string;
16
+ itLinkId: string | null;
17
+ }, now: number): ItLinkResult;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createItLinkToken = createItLinkToken;
4
+ exports.verifyItLinkToken = verifyItLinkToken;
5
+ const signing_1 = require("./signing");
6
+ function createItLinkToken(secret, setupId, linkId, expiresAt) {
7
+ return (0, signing_1.signToken)(secret, "it_link", { s: setupId, l: linkId }, expiresAt);
8
+ }
9
+ function verifyItLinkToken(secret, token, current, now) {
10
+ const verified = (0, signing_1.verifyToken)(secret, "it_link", token, now);
11
+ if (!verified.ok)
12
+ return { ok: false, reason: verified.reason };
13
+ if (verified.claims.s !== current.setupId || !current.itLinkId || verified.claims.l !== current.itLinkId) {
14
+ return { ok: false, reason: "revoked", setupId: verified.claims.s };
15
+ }
16
+ return { ok: true, expiresAt: verified.claims.exp };
17
+ }