@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,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GRAPH_SETUP_SCOPES = exports.CONSENT_CALLBACK_PATH = void 0;
4
+ exports.buildAdminConsentUrl = buildAdminConsentUrl;
5
+ exports.buildSetupAuthorizeUrl = buildSetupAuthorizeUrl;
6
+ exports.createConsentState = createConsentState;
7
+ exports.verifyConsentCallback = verifyConsentCallback;
8
+ const address_1 = require("./address");
9
+ const signing_1 = require("./signing");
10
+ exports.CONSENT_CALLBACK_PATH = "/api/m365/consent/callback";
11
+ function buildAdminConsentUrl(input) {
12
+ const tenantId = (0, address_1.normalizeGuid)(input.tenantId);
13
+ if (!tenantId)
14
+ throw new Error("buildAdminConsentUrl needs a tenant GUID.");
15
+ if (!input.clientId)
16
+ throw new Error("buildAdminConsentUrl needs the client id.");
17
+ const params = new URLSearchParams({ client_id: input.clientId, redirect_uri: input.redirectUri, state: input.state });
18
+ return `https://login.microsoftonline.com/${tenantId}/adminconsent?${params.toString()}`;
19
+ }
20
+ exports.GRAPH_SETUP_SCOPES = [
21
+ "openid",
22
+ "https://graph.microsoft.com/User.Read",
23
+ "https://graph.microsoft.com/RoleManagement.ReadWrite.Exchange",
24
+ ];
25
+ function buildSetupAuthorizeUrl(input) {
26
+ const tenantId = (0, address_1.normalizeGuid)(input.tenantId);
27
+ if (!tenantId)
28
+ throw new Error("buildSetupAuthorizeUrl needs a tenant GUID.");
29
+ if (!input.clientId)
30
+ throw new Error("buildSetupAuthorizeUrl needs the client id.");
31
+ const params = new URLSearchParams({
32
+ client_id: input.clientId,
33
+ response_type: "code",
34
+ response_mode: "query",
35
+ redirect_uri: input.redirectUri,
36
+ scope: exports.GRAPH_SETUP_SCOPES.join(" "),
37
+ state: input.state,
38
+ prompt: "consent",
39
+ });
40
+ return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?${params.toString()}`;
41
+ }
42
+ function createConsentState(secret, claims, expiresAt) {
43
+ return (0, signing_1.signToken)(secret, "consent_state", claims, expiresAt);
44
+ }
45
+ function verifyConsentCallback(params, expected) {
46
+ const verified = (0, signing_1.verifyToken)(expected.secret, "consent_state", params.get("state"), expected.now);
47
+ if (!verified.ok) {
48
+ if (verified.reason === "expired" && verified.expiredClaims) {
49
+ return { ok: false, code: "state_expired", claims: verified.expiredClaims };
50
+ }
51
+ return { ok: false, code: "state_invalid" };
52
+ }
53
+ const claims = verified.claims;
54
+ if (claims.s !== expected.setupId ||
55
+ !expected.nonce ||
56
+ claims.n !== expected.nonce ||
57
+ !expected.tenantId ||
58
+ claims.t !== expected.tenantId) {
59
+ return { ok: false, code: "state_stale", claims };
60
+ }
61
+ const error = params.get("error");
62
+ if (error) {
63
+ const description = params.get("error_description")?.slice(0, 500) ?? undefined;
64
+ return { ok: false, code: error === "access_denied" ? "consent_denied" : "consent_failed", claims, description };
65
+ }
66
+ if (claims.m === "graph") {
67
+ const code = params.get("code");
68
+ if (!code)
69
+ return { ok: false, code: "consent_failed", claims };
70
+ return { ok: true, tenantId: expected.tenantId, claims, code };
71
+ }
72
+ if ((params.get("admin_consent") ?? "").toLowerCase() !== "true")
73
+ return { ok: false, code: "consent_failed", claims };
74
+ const tenant = (0, address_1.normalizeGuid)(params.get("tenant") ?? "");
75
+ if (!tenant || tenant !== expected.tenantId)
76
+ return { ok: false, code: "wrong_tenant", claims };
77
+ return { ok: true, tenantId: tenant, claims };
78
+ }
@@ -0,0 +1,2 @@
1
+ export declare const SETUP_BASE_PATH = "/api/m365";
2
+ export declare const IT_LINK_HEADER = "x-m365-link";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IT_LINK_HEADER = exports.SETUP_BASE_PATH = void 0;
4
+ exports.SETUP_BASE_PATH = "/api/m365";
5
+ exports.IT_LINK_HEADER = "x-m365-link";
@@ -0,0 +1,23 @@
1
+ import type { FetchLike } from "../util";
2
+ import type { ExchangeSetupErrorCode } from "./types";
3
+ export declare function exchangeScopeName(appId: string): string;
4
+ export declare function mailboxRecipientFilter(mailboxes: string[]): string;
5
+ export type ExchangeGrantResult = {
6
+ ok: true;
7
+ scopeId: string;
8
+ createdScope: boolean;
9
+ createdRoles: string[];
10
+ } | {
11
+ ok: false;
12
+ code: ExchangeSetupErrorCode;
13
+ detail?: string;
14
+ };
15
+ interface GrantInput {
16
+ accessToken: string;
17
+ servicePrincipalId: string;
18
+ appId: string;
19
+ mailboxes: string[];
20
+ fetch: FetchLike;
21
+ }
22
+ export declare function grantExchangeAccess(input: GrantInput): Promise<ExchangeGrantResult>;
23
+ export {};
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exchangeScopeName = exchangeScopeName;
4
+ exports.mailboxRecipientFilter = mailboxRecipientFilter;
5
+ exports.grantExchangeAccess = grantExchangeAccess;
6
+ const BASE = "https://graph.microsoft.com/beta/roleManagement/exchange";
7
+ const EXCHANGE_APP_ROLES = [
8
+ "Application Mail.ReadWrite",
9
+ "Application Mail.Send",
10
+ "Application MailboxSettings.Read",
11
+ ];
12
+ function exchangeScopeName(appId) {
13
+ return `DXV Helpdesk ${appId.trim().toLowerCase().slice(0, 8)}`;
14
+ }
15
+ function mailboxRecipientFilter(mailboxes) {
16
+ if (mailboxes.length === 0)
17
+ throw new Error("mailboxRecipientFilter needs at least one mailbox.");
18
+ for (const m of mailboxes) {
19
+ if (!/^[^\s'"@]+@[^\s'"@]+$/.test(m))
20
+ throw new Error(`Unsafe mailbox address for a recipient filter: ${m}`);
21
+ }
22
+ return mailboxes.map((m) => `PrimarySmtpAddress -eq '${m.toLowerCase()}'`).join(" -or ");
23
+ }
24
+ class GraphCallError extends Error {
25
+ constructor(status, code, message) {
26
+ super(message);
27
+ this.status = status;
28
+ this.code = code;
29
+ }
30
+ }
31
+ async function grantExchangeAccess(input) {
32
+ const call = async (method, path, body) => {
33
+ const response = await input.fetch(path.startsWith("https://") ? path : `${BASE}${path}`, {
34
+ method,
35
+ headers: {
36
+ Authorization: `Bearer ${input.accessToken}`,
37
+ Accept: "application/json",
38
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
39
+ },
40
+ body: body === undefined ? undefined : JSON.stringify(body),
41
+ signal: AbortSignal.timeout(30000),
42
+ });
43
+ const text = await response.text();
44
+ const parsed = text ? JSON.parse(text) : {};
45
+ if (!response.ok) {
46
+ const error = (parsed.error ?? {});
47
+ throw new GraphCallError(response.status, error.code ?? "error", error.message ?? `HTTP ${response.status}`);
48
+ }
49
+ return parsed;
50
+ };
51
+ const list = async (path) => {
52
+ const items = [];
53
+ let next = path;
54
+ while (next) {
55
+ const page = await call("GET", next);
56
+ items.push(...(page.value ?? []));
57
+ next = page["@odata.nextLink"];
58
+ }
59
+ return items;
60
+ };
61
+ try {
62
+ const roleIds = [];
63
+ for (const name of EXCHANGE_APP_ROLES) {
64
+ const defs = await list(`/roleDefinitions?$filter=${encodeURIComponent(`displayName eq '${name}'`)}&$select=id,displayName`);
65
+ const id = defs.find((d) => d.displayName === name)?.id;
66
+ if (!id)
67
+ return { ok: false, code: "exchange_failed", detail: `role definition not found: ${name}` };
68
+ roleIds.push(id);
69
+ }
70
+ const scopeName = exchangeScopeName(input.appId);
71
+ const filter = mailboxRecipientFilter(input.mailboxes);
72
+ const scopes = await list("/customAppScopes");
73
+ let scope = scopes.find((s) => s.displayName === scopeName);
74
+ let createdScope = false;
75
+ if (!scope) {
76
+ scope = await call("POST", "/customAppScopes", {
77
+ type: "RecipientScope",
78
+ displayName: scopeName,
79
+ customAttributes: { Exclusive: false, RecipientFilter: filter },
80
+ });
81
+ createdScope = true;
82
+ }
83
+ else if (scope.customAttributes?.RecipientFilter !== filter) {
84
+ await call("PATCH", `/customAppScopes/${encodeURIComponent(scope.id)}`, {
85
+ customAttributes: { RecipientFilter: filter },
86
+ });
87
+ }
88
+ const scopeId = scope.id;
89
+ const principalId = `/ServicePrincipals/${input.servicePrincipalId}`;
90
+ let existing;
91
+ try {
92
+ existing = await list(`/roleAssignments?$filter=${encodeURIComponent(`principalId eq '${principalId}'`)}`);
93
+ }
94
+ catch (err) {
95
+ if (!(err instanceof GraphCallError) || err.status !== 400)
96
+ throw err;
97
+ existing = (await list("/roleAssignments")).filter((a) => a.principalId?.toLowerCase() === principalId.toLowerCase());
98
+ }
99
+ const createdRoles = [];
100
+ for (const [i, roleDefinitionId] of roleIds.entries()) {
101
+ if (existing.some((a) => a.roleDefinitionId === roleDefinitionId && a.appScopeId === scopeId))
102
+ continue;
103
+ await call("POST", "/roleAssignments", { principalId, roleDefinitionId, appScopeId: scopeId });
104
+ createdRoles.push(EXCHANGE_APP_ROLES[i]);
105
+ }
106
+ return { ok: true, scopeId, createdScope, createdRoles };
107
+ }
108
+ catch (err) {
109
+ if (err instanceof GraphCallError) {
110
+ const detail = `${err.status} ${err.code}: ${err.message}`.slice(0, 500);
111
+ if (/OrganizationCustomization|dehydrat/i.test(err.message))
112
+ return { ok: false, code: "exchange_org_customization", detail };
113
+ if (err.status === 401 || err.status === 403)
114
+ return { ok: false, code: "exchange_forbidden", detail };
115
+ return { ok: false, code: "exchange_failed", detail };
116
+ }
117
+ return { ok: false, code: "exchange_failed", detail: err instanceof Error ? err.message.slice(0, 500) : undefined };
118
+ }
119
+ }
@@ -0,0 +1 @@
1
+ export declare const EXCHANGE_SCRIPT_LINES: readonly string[];
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EXCHANGE_SCRIPT_LINES = void 0;
4
+ exports.EXCHANGE_SCRIPT_LINES = [
5
+ "# DXV Helpdesk: gives the helpdesk app access to the chosen mailboxes, and to nothing else.",
6
+ "# Safe to run twice: every step checks what already exists.",
7
+ "param(",
8
+ " [Parameter(Mandatory)] [string] $AppId,",
9
+ " [Parameter(Mandatory)] [string] $ObjectId,",
10
+ " [Parameter(Mandatory)] [string[]] $Mailboxes,",
11
+ " [Parameter(Mandatory)] [string] $CheckMailbox,",
12
+ " # Exchange object names. Leave them empty: they are derived from the AppId, so two apps",
13
+ " # in one tenant never share a group, scope or role assignment.",
14
+ " [string] $GroupName,",
15
+ " [string] $ScopeName,",
16
+ " # Set when signing in as an IT partner (GDAP): the client's tenant domain.",
17
+ " [string] $PartnerTenant,",
18
+ " # The admin account to sign in with, so a cached account from another tenant is not reused.",
19
+ " [string] $AdminAccount,",
20
+ " # Skips the confirmation for a user mailbox, for repeat runs.",
21
+ " [switch] $AllowUserMailbox,",
22
+ " # Signs in through the browser instead of the Windows sign-in broker (WAM), for when",
23
+ " # WAM fails, e.g. \"A window handle must be configured\" (spike result 2026-11-10).",
24
+ " [switch] $DisableWAM",
25
+ ")",
26
+ "$ErrorActionPreference = \"Stop\"",
27
+ "",
28
+ "# One set of Exchange objects per app: the names carry the first 8 characters of its AppId.",
29
+ "$AppKey = $AppId.Trim().ToLower().Substring(0, 8)",
30
+ "if (-not $GroupName) { $GroupName = \"DXV Helpdesk $AppKey\" }",
31
+ "if (-not $ScopeName) { $ScopeName = \"DXV Helpdesk $AppKey mailboxes\" }",
32
+ "",
33
+ "if (-not (Get-Module -ListAvailable ExchangeOnlineManagement)) {",
34
+ " # Windows PowerShell 5.1 ships PowerShellGet 1.0.0.1: it needs TLS 1.2 for the gallery",
35
+ " # and -AllowClobber, or the install fails on a PackageManagement command conflict",
36
+ " # (spike result 2026-11-09).",
37
+ " [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12",
38
+ " Install-Module ExchangeOnlineManagement -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop",
39
+ "}",
40
+ "Import-Module ExchangeOnlineManagement -ErrorAction Stop",
41
+ "if (-not (Get-Command Connect-ExchangeOnline -ErrorAction SilentlyContinue)) {",
42
+ " throw \"The ExchangeOnlineManagement module did not load. Install it with: Install-Module ExchangeOnlineManagement -Scope CurrentUser -Force -AllowClobber\"",
43
+ "}",
44
+ "# Close connections left in this window, so every command below runs against the",
45
+ "# organization signed in to here and nowhere else (spike result 2026-11-09).",
46
+ "if (Get-ConnectionInformation) { Disconnect-ExchangeOnline -Confirm:$false }",
47
+ "if ($PartnerTenant) {",
48
+ " try {",
49
+ " Connect-ExchangeOnline -DelegatedOrganization $PartnerTenant -DisableWAM:$DisableWAM",
50
+ " } catch {",
51
+ " throw \"Could not sign in as a partner: $_. Use an admin account in the client's own tenant and run the script without -PartnerTenant.\"",
52
+ " }",
53
+ "} else {",
54
+ " if ($AdminAccount) {",
55
+ " Connect-ExchangeOnline -UserPrincipalName $AdminAccount -ShowBanner:$false -DisableWAM:$DisableWAM",
56
+ " } else {",
57
+ " Connect-ExchangeOnline -ShowBanner:$false -DisableWAM:$DisableWAM",
58
+ " }",
59
+ "}",
60
+ "",
61
+ "# Sign-in can silently reuse a cached account from another tenant (spike result",
62
+ "# 2026-11-09). Stop unless every mailbox domain is accepted in the connected organization.",
63
+ "$Connection = Get-ConnectionInformation | Select-Object -First 1",
64
+ "$Accepted = @(Get-AcceptedDomain | ForEach-Object { $_.DomainName.ToString().ToLower() })",
65
+ "$Foreign = @($Mailboxes + $CheckMailbox | ForEach-Object { ($_ -split \"@\")[-1].ToLower() } |",
66
+ " Where-Object { $Accepted -notcontains $_ } | Select-Object -Unique)",
67
+ "if ($Foreign.Count -gt 0) {",
68
+ " Disconnect-ExchangeOnline -Confirm:$false",
69
+ " throw \"Signed in as $($Connection.UserPrincipalName), whose organization does not own: $($Foreign -join ', '). Nothing was changed. Run the script again and sign in with an admin account of the organization that owns these mailboxes.\"",
70
+ "}",
71
+ "Write-Host \"Connected as $($Connection.UserPrincipalName).\"",
72
+ "",
73
+ "# Exchange only loads the cmdlets the signed-in account's role allows. Check them all",
74
+ "# before changing anything (spike result 2026-11-09: Get-ServicePrincipal was missing",
75
+ "# after the group had been created).",
76
+ "$Needed = \"New-DistributionGroup\", \"Add-DistributionGroupMember\", \"Get-ServicePrincipal\", \"New-ServicePrincipal\",",
77
+ " \"New-ManagementScope\", \"New-ManagementRoleAssignment\", \"Test-ServicePrincipalAuthorization\",",
78
+ " \"Get-OrganizationConfig\", \"Enable-OrganizationCustomization\"",
79
+ "$Missing = @($Needed | Where-Object { -not (Get-Command $_ -ErrorAction SilentlyContinue) })",
80
+ "if ($Missing.Count -gt 0) {",
81
+ " Disconnect-ExchangeOnline -Confirm:$false",
82
+ " throw \"This account lacks the Exchange role for: $($Missing -join ', '). Nothing was changed. Sign in with an account in the Organization Management role group (a Global Administrator usually is; in a new tenant this can take a few hours to apply).\"",
83
+ "}",
84
+ "",
85
+ "# A new or small tenant is \"dehydrated\": custom management scopes and role assignments",
86
+ "# are refused until organization customization is turned on (spike result 2026-11-10).",
87
+ "# It is a one-time switch that changes nothing else.",
88
+ "if ((Get-OrganizationConfig).IsDehydrated) {",
89
+ " Write-Host \"Turning on organization customization (needed once in this organization)...\"",
90
+ " Enable-OrganizationCustomization -ErrorAction Stop",
91
+ "}",
92
+ "",
93
+ "# Check every address before changing anything. Any kind of mailbox can be connected, but",
94
+ "# a user mailbox needs confirmation. An alias resolves to its mailbox, so it is caught too.",
95
+ "$Problems = @()",
96
+ "$UserMailboxes = @()",
97
+ "foreach ($Mailbox in $Mailboxes) {",
98
+ " $Recipient = Get-Recipient -Identity $Mailbox -ErrorAction SilentlyContinue",
99
+ " if (-not $Recipient) {",
100
+ " $Problems += \"${Mailbox}: not found\"",
101
+ " } elseif ($Recipient.RecipientTypeDetails -eq \"UserMailbox\") {",
102
+ " $UserMailboxes += \"${Mailbox} (mailbox of $($Recipient.PrimarySmtpAddress))\"",
103
+ " } elseif ($Recipient.RecipientTypeDetails -ne \"SharedMailbox\") {",
104
+ " $Problems += \"${Mailbox}: is a $($Recipient.RecipientTypeDetails). Only shared mailboxes and user mailboxes can be connected; for a group, connect a shared mailbox instead\"",
105
+ " }",
106
+ "}",
107
+ "if ($Problems) {",
108
+ " $Problems | ForEach-Object { Write-Warning $_ }",
109
+ " throw \"Nothing was changed. Correct these addresses on the setup page and run the new script.\"",
110
+ "}",
111
+ "if ($UserMailboxes -and -not $AllowUserMailbox) {",
112
+ " Write-Warning \"These are mailboxes of a person, not shared mailboxes. All mail in their Inbox goes into the helpdesk:\"",
113
+ " $UserMailboxes | ForEach-Object { Write-Warning $_ }",
114
+ " if ((Read-Host \"Type YES to connect them anyway\") -cne \"YES\") {",
115
+ " throw \"Nothing was changed.\"",
116
+ " }",
117
+ "}",
118
+ "",
119
+ "# Mail-enabled group with exactly the chosen mailboxes as direct members.",
120
+ "$Group = Get-DistributionGroup -Identity $GroupName -ErrorAction SilentlyContinue",
121
+ "if (-not $Group) {",
122
+ " $Alias = ($GroupName -replace '[^a-zA-Z0-9]', '')",
123
+ " $Group = New-DistributionGroup -Name $GroupName -Alias $Alias -Type Security -ErrorAction Stop",
124
+ "}",
125
+ "$Current = @(Get-DistributionGroupMember -Identity $GroupName -ResultSize Unlimited | ForEach-Object { $_.PrimarySmtpAddress.ToString().ToLower() })",
126
+ "foreach ($Mailbox in $Mailboxes) {",
127
+ " if ($Current -notcontains $Mailbox.ToLower()) {",
128
+ " Add-DistributionGroupMember -Identity $GroupName -Member $Mailbox -ErrorAction Stop",
129
+ " }",
130
+ "}",
131
+ "",
132
+ "# Register the enterprise app in Exchange.",
133
+ "if (-not (Get-ServicePrincipal -Identity $ObjectId -ErrorAction SilentlyContinue)) {",
134
+ " New-ServicePrincipal -AppId $AppId -ObjectId $ObjectId -DisplayName $GroupName -ErrorAction Stop | Out-Null",
135
+ "}",
136
+ "",
137
+ "# Limit access to the group.",
138
+ "$Filter = \"MemberOfGroup -eq '$($Group.DistinguishedName)'\"",
139
+ "if (-not (Get-ManagementScope -Identity $ScopeName -ErrorAction SilentlyContinue)) {",
140
+ " try {",
141
+ " New-ManagementScope -Name $ScopeName -RecipientRestrictionFilter $Filter -ErrorAction Stop | Out-Null",
142
+ " } catch {",
143
+ " # IsDehydrated turns False at once, but Exchange keeps refusing scopes for a while",
144
+ " # after Enable-OrganizationCustomization (spike result 2026-11-10).",
145
+ " if (\"$_\" -match \"Enable-OrganizationCustomization\") {",
146
+ " throw \"Exchange is still applying the one-time organization setup. The group and app registration are in place. Wait an hour and run this script again; it continues where it stopped.\"",
147
+ " }",
148
+ " throw",
149
+ " }",
150
+ "}",
151
+ "",
152
+ "# Grant the two roles inside that scope.",
153
+ "# Each assignment gets a fixed name, and the check looks it up by that name. Do not use",
154
+ "# Get-ManagementRoleAssignment -RoleAssignee <app>: it returned every Organization",
155
+ "# Management assignment (including the delegating Application Mail.* ones), so the",
156
+ "# script skipped the grant (spike result 2026-11-10).",
157
+ "foreach ($Role in \"Application Mail.ReadWrite\", \"Application Mail.Send\") {",
158
+ " $AssignmentName = \"$GroupName - $Role\"",
159
+ " if (-not (Get-ManagementRoleAssignment -Identity $AssignmentName -ErrorAction SilentlyContinue)) {",
160
+ " New-ManagementRoleAssignment -Name $AssignmentName -App $ObjectId -Role $Role -CustomResourceScope $ScopeName -ErrorAction Stop | Out-Null",
161
+ " }",
162
+ "}",
163
+ "",
164
+ "# Warn about rules that move mail out of the Inbox.",
165
+ "foreach ($Mailbox in $Mailboxes) {",
166
+ " $Rules = @(Get-InboxRule -Mailbox $Mailbox | Where-Object { $_.Enabled -and ($_.MoveToFolder -or $_.DeleteMessage) })",
167
+ " foreach ($Rule in $Rules) {",
168
+ " Write-Warning \"${Mailbox}: rule '$($Rule.Name)' moves mail out of the Inbox. The helpdesk may not see that mail.\"",
169
+ " }",
170
+ " # Forwarded copies reach another system too, which may then handle the same mail twice.",
171
+ " $Forwards = @(Get-InboxRule -Mailbox $Mailbox | Where-Object { $_.Enabled -and ($_.ForwardTo -or $_.ForwardAsAttachmentTo -or $_.RedirectTo) })",
172
+ " foreach ($Rule in $Forwards) {",
173
+ " Write-Warning \"${Mailbox}: rule '$($Rule.Name)' forwards mail elsewhere. Check that the other system does not also handle it.\"",
174
+ " }",
175
+ " $Box = Get-Mailbox -Identity $Mailbox",
176
+ " if ($Box.ForwardingSmtpAddress -or $Box.ForwardingAddress) {",
177
+ " $Target = if ($Box.ForwardingSmtpAddress) { $Box.ForwardingSmtpAddress } else { $Box.ForwardingAddress }",
178
+ " $Copy = if ($Box.DeliverToMailboxAndForward) { \"keeps a copy and forwards\" } else { \"forwards WITHOUT keeping a copy, so the helpdesk sees nothing\" }",
179
+ " Write-Warning \"${Mailbox}: mailbox forwarding to $Target ($Copy). Check that the other system does not also handle it.\"",
180
+ " }",
181
+ "}",
182
+ "",
183
+ "# Expected: InScope True for each mailbox, False for the check mailbox.",
184
+ "foreach ($Resource in @($Mailboxes) + $CheckMailbox) {",
185
+ " Test-ServicePrincipalAuthorization -Identity $ObjectId -Resource $Resource |",
186
+ " Select-Object @{ Name = \"Mailbox\"; Expression = { $Resource } }, RoleName, InScope",
187
+ "}",
188
+ "Write-Host \"The mailboxes are in the group '$GroupName'. To change them later, change that group and the list on the setup page.\"",
189
+ "Write-Host \"Done. Microsoft usually needs 1 to 2 hours to apply the rights. The setup page keeps checking for up to 4 hours.\"",
190
+ ];
@@ -0,0 +1,30 @@
1
+ import type { GraphClient } from "../client";
2
+ import type { FetchLike } from "../util";
3
+ import type { ConnectionStore, M365Connection, SetupAdmin } from "./types";
4
+ export interface M365SetupConfig {
5
+ isProduction: boolean;
6
+ clientId: string | null | undefined;
7
+ setupReady: boolean;
8
+ appOrigin: string;
9
+ secret: string;
10
+ store: ConnectionStore;
11
+ getAdmin(request: Request): Promise<SetupAdmin | null>;
12
+ createGraphClient(tenantId: string): GraphClient;
13
+ getClientAssertion: () => Promise<string>;
14
+ companyName: string;
15
+ entraAppName: string;
16
+ pagePath: string;
17
+ itLinkPagePath: string;
18
+ onConnected?(connection: M365Connection): Promise<void> | void;
19
+ onReset?(previous: M365Connection): Promise<void> | void;
20
+ fetch?: FetchLike;
21
+ now?: () => number;
22
+ itLinkTtlMs?: number;
23
+ consentStateTtlMs?: number;
24
+ checkIntervalMs?: number;
25
+ }
26
+ export interface M365SetupHandlers {
27
+ handle(request: Request): Promise<Response>;
28
+ runAccessCheck(): Promise<M365Connection | null>;
29
+ }
30
+ export declare function createM365SetupHandlers(config: M365SetupConfig): M365SetupHandlers;