@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.
- package/README.md +201 -3
- package/dist/auth.d.ts +41 -0
- package/dist/auth.js +184 -0
- package/dist/client.d.ts +18 -0
- package/dist/client.js +34 -0
- package/dist/errors.d.ts +25 -0
- package/dist/errors.js +35 -0
- package/dist/http.d.ts +44 -0
- package/dist/http.js +182 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +14 -0
- package/dist/limiter.d.ts +7 -0
- package/dist/limiter.js +29 -0
- package/dist/links.d.ts +2 -0
- package/dist/links.js +25 -0
- package/dist/mailbox.d.ts +41 -0
- package/dist/mailbox.js +429 -0
- package/dist/setup/access.d.ts +20 -0
- package/dist/setup/access.js +71 -0
- package/dist/setup/address.d.ts +32 -0
- package/dist/setup/address.js +69 -0
- package/dist/setup/consent.d.ts +40 -0
- package/dist/setup/consent.js +78 -0
- package/dist/setup/constants.d.ts +2 -0
- package/dist/setup/constants.js +5 -0
- package/dist/setup/exchange-graph.d.ts +23 -0
- package/dist/setup/exchange-graph.js +119 -0
- package/dist/setup/exchange-script.d.ts +1 -0
- package/dist/setup/exchange-script.js +190 -0
- package/dist/setup/handlers.d.ts +30 -0
- package/dist/setup/handlers.js +571 -0
- package/dist/setup/index.d.ts +18 -0
- package/dist/setup/index.js +38 -0
- package/dist/setup/it-link.d.ts +17 -0
- package/dist/setup/it-link.js +17 -0
- package/dist/setup/messages.d.ts +22 -0
- package/dist/setup/messages.js +36 -0
- package/dist/setup/react.d.ts +8 -0
- package/dist/setup/react.js +451 -0
- package/dist/setup/script.d.ts +27 -0
- package/dist/setup/script.js +74 -0
- package/dist/setup/signing.d.ts +18 -0
- package/dist/setup/signing.js +56 -0
- package/dist/setup/tenant.d.ts +38 -0
- package/dist/setup/tenant.js +45 -0
- package/dist/setup/types.d.ts +76 -0
- package/dist/setup/types.js +2 -0
- package/dist/types.d.ts +98 -0
- package/dist/types.js +2 -0
- package/dist/util.d.ts +4 -0
- package/dist/util.js +17 -0
- package/package.json +70 -6
package/README.md
CHANGED
|
@@ -1,3 +1,201 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @dxv-systems/mail-graph
|
|
2
|
+
|
|
3
|
+
Microsoft Graph mail for DXV apps: app-only authentication with a caller-supplied client assertion, per-mailbox delta sync, messages and attachments, threaded replies that land in Sent Items, folders, forward and send.
|
|
4
|
+
|
|
5
|
+
Zero runtime dependencies: everything is `fetch` against Graph and the Microsoft identity platform. The package reads no environment variables and has no database. The guided setup page lives in its own entry points (`/setup`, `/setup/react`), so an app that only uses the Graph client never loads React. Delta links and tokens are the caller's to store (links) or the client's to cache (tokens).
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @dxv-systems/mail-graph
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Never deletes customer mail
|
|
12
|
+
|
|
13
|
+
There is no delete except `deleteDraft`, which refuses anything that is not a draft. The general request layer accepts only `GET`, `POST` and `PATCH`; anything else throws `GraphUsageError` (`MethodNotAllowed`) before a request is made. The one `PUT` is a chunk of an attachment upload session, sent to the `uploadUrl` Graph returned for that session. Customer mail is moved (`moveMessage`), never removed.
|
|
14
|
+
|
|
15
|
+
`deleteDraft(draftId)` is for drafts the helpdesk created itself. It first reads `isDraft`; unless that is exactly `true` it returns `{ status: "not_draft" }` and sends no DELETE. It returns `{ status: "gone" }` on a 404 (at the read or at the DELETE) and `{ status: "deleted" }` after a successful DELETE. A 429 or 503 on the DELETE is retried (a repeat is harmless); a network error is not. Per Graph's documentation a DELETE moves the item to Deleted Items; that is unverified until the real-tenant test. There is a small window: if someone sends the draft from Outlook between the read and the DELETE, the sent copy could end up in Deleted Items. Tests prove every DELETE is preceded by an `isDraft: true` read of the same message.
|
|
16
|
+
|
|
17
|
+
## Setup
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { createGraphClient } from "@dxv-systems/mail-graph";
|
|
21
|
+
|
|
22
|
+
const graph = createGraphClient({
|
|
23
|
+
tenantId: "contoso.onmicrosoft.com", // the mailbox tenant
|
|
24
|
+
clientId: "…", // the DXV-owned Entra app
|
|
25
|
+
getClientAssertion: async () => getVercelOidcToken(), // or sign a JWT with the app's certificate
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const support = graph.mailbox("support@contoso.example");
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`getClientAssertion` returns a JWT and is called again for every token request (assertions are single use). It can be a Vercel OIDC token (`getVercelOidcToken()` from `@vercel/oidc`, with Vercel's default audience `https://vercel.com/<team-slug>`: that is the audience the app's federated credential accepts, tested against a real tenant) or a certificate-signed JWT; this package does neither itself and never inspects, stores or logs the value.
|
|
32
|
+
|
|
33
|
+
Tokens come from `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` (client credentials, scope `https://graph.microsoft.com/.default`, jwt-bearer assertion) and are cached per client instance until five minutes before they expire. A new federated credential can take minutes to become visible: `AADSTS70021` is retried with exponential backoff (default 5 attempts, 2 s doubling, 20 s cap; `federationRetry` changes it).
|
|
34
|
+
|
|
35
|
+
### The app's Object ID
|
|
36
|
+
|
|
37
|
+
Exchange needs the service principal's Object ID. It is the `oid` claim of any token:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
const { objectId, tenantId } = await graph.getAppIdentity();
|
|
41
|
+
// or, for a token you already have (the signature is NOT verified):
|
|
42
|
+
import { readTokenIdentity } from "@dxv-systems/mail-graph";
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Reading mail
|
|
46
|
+
|
|
47
|
+
All calls are per mailbox. Every request sends `Prefer: IdType="ImmutableId"`, so ids stay the same after a move.
|
|
48
|
+
|
|
49
|
+
### Delta sync
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
let page = await support.delta({ folderId: "inbox", since: "2026-11-01T00:00:00Z", pageSize: 50 });
|
|
53
|
+
// or continue where you stopped: support.delta({ link: storedNextOrDeltaLink })
|
|
54
|
+
for (;;) {
|
|
55
|
+
for (const item of page.items) {
|
|
56
|
+
if (item.removed) {/* item.id, item.removedReason */} else {/* summary fields */}
|
|
57
|
+
}
|
|
58
|
+
if (page.nextLink) page = await support.delta({ link: page.nextLink });
|
|
59
|
+
else break;
|
|
60
|
+
}
|
|
61
|
+
save(page.deltaLink); // next round: support.delta({ link: saved })
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The caller stores the links. `since` (a `receivedDateTime ge` filter) applies to the first page only. A message moved out of the folder shows up as removed with reason `deleted`.
|
|
65
|
+
|
|
66
|
+
If Graph answers 410 / `syncStateNotFound` to a delta request, `delta` throws `GraphDeltaExpiredError`: drop the stored link, start a new round and reconcile with a normal listing.
|
|
67
|
+
|
|
68
|
+
Only links on `https://graph.microsoft.com/v1.0/` are followed. Any other link throws `GraphUsageError` (`InvalidLink`) and nothing is sent, so a stored link can never carry the bearer token elsewhere.
|
|
69
|
+
|
|
70
|
+
### Messages and attachments
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const message = await support.getMessage(id, { bodyType: "text", includeHeaders: true });
|
|
74
|
+
// message.body, conversationId, internetMessageId, toRecipients…
|
|
75
|
+
// with includeHeaders: inReplyTo, references[] (null when the message is gone)
|
|
76
|
+
const attachments = await support.listAttachments(id); // id, name, contentType, size, isInline, kind
|
|
77
|
+
const bytes = await support.downloadAttachment(id, attachments[0].id); // Uint8Array
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Replying
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const draft = await support.createReply(messageId); // or { replyAll: true, comment }
|
|
84
|
+
await support.updateDraftBody(draft.id, { contentType: "html", content });
|
|
85
|
+
await support.addAttachment(draft.id, { name, contentType, content }); // 3 MB and up: upload session
|
|
86
|
+
await support.sendDraft(draft.id); // threads natively, lands in Sent Items
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## State, folders, sending
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
await support.markRead(id); // markRead(id, false) to unread
|
|
93
|
+
await support.setCategories(id, ["Handled"]); // replaces all categories
|
|
94
|
+
await support.listFolders("inbox"); // children of the inbox; "root" for top level
|
|
95
|
+
await support.getInboxFolderId();
|
|
96
|
+
await support.createInboxFolder("Handled");
|
|
97
|
+
await support.moveMessage(id, folderId);
|
|
98
|
+
await support.forward(id, { to: ["a@b.example"], comment: "" });
|
|
99
|
+
await support.sendMail({ to, subject, body: { contentType: "html", content }, attachments }); // saveToSentItems: true
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`sendMail` attachments must total under 3 MB (a Graph request limit); for larger files create a draft by replying, or forward.
|
|
103
|
+
|
|
104
|
+
### Access check
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
await support.checkAccess(); // { status: "ok" | "denied" | "not_found" }
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
It requests `$top=1&$select=id` and maps 200 / 403 / 404. It returns the status only, never mail content. Exchange RBAC changes can take 30 minutes to 2 hours to apply, so `denied` right after setup is expected for a while. Any other failure (401, 5xx after retries) throws.
|
|
111
|
+
|
|
112
|
+
## Guided Microsoft 365 setup
|
|
113
|
+
|
|
114
|
+
The client connects Microsoft 365 themselves on one page in the app. Two entry points:
|
|
115
|
+
|
|
116
|
+
- `@dxv-systems/mail-graph/setup`: server side. Route handlers, consent URL and `state`, the signed IT link, tenant lookup, the access check and the script generator. Uses `node:crypto`; no React.
|
|
117
|
+
- `@dxv-systems/mail-graph/setup/react`: the `M365SetupPage` component (`"use client"`). React is an optional peer dependency.
|
|
118
|
+
|
|
119
|
+
### Flow
|
|
120
|
+
|
|
121
|
+
The page is fixed in the package: apps mount `<M365SetupPage />` and cannot restyle it, change its copy, or reorder or skip steps. It takes only `linkToken`, `helpdeskHref` and `settingsHref` (and `fetch`, for tests). The route handlers enforce every step on the server as well.
|
|
122
|
+
|
|
123
|
+
1. **Start** (one screen): the admin types the mailbox(es) as chips; the tenant is looked up from each domain in Microsoft's public `https://login.microsoftonline.com/<domain>/.well-known/openid-configuration` (issuer `https://sts.windows.net/<tenantId>/`), and the page shows "Microsoft 365 gevonden". Then one button, "Koppelen met Microsoft". A domain not on Microsoft 365, or mailboxes in different tenants, are refused right away. Not a Microsoft 365 admin? A small link creates a **signed IT link** (7 days, one live link at a time, revocable, no secrets: only the setup id, link id and expiry). The IT link opens the same start screen, sign-in, script and status only; it needs no app account. Once connected the link is revoked: it then only reads the status of that same setup, so an IT admin with the page open sees it succeed.
|
|
124
|
+
2. **Sign-in, no script.** An authorization-code sign-in on the tenant (never `/common`), `prompt=consent`, scopes `openid`, `User.Read` and delegated `RoleManagement.ReadWrite.Exchange`, no `offline_access`. The callback (`/api/m365/consent/callback`, fixed by the Entra app's redirect URI) checks that `state` is signed, unexpired (1 hour), single use and bound to this setup; redeems the code once with the app's client assertion (`getClientAssertion`, required); checks the token's tenant; reads the signed-in admin (`/me`: shown as "Aangemeld als", and their mailbox becomes the check mailbox when none was set); reads the Object ID from an app-only token; and sets up Exchange RBAC for Applications through Graph beta (`/roleManagement/exchange`): one scope per app, `DXV Helpdesk <first 8 characters of the AppId>`, whose `RecipientFilter` names the mailboxes (`PrimarySmtpAddress -eq '…'`, so enter each mailbox's primary address), and the roles `Application Mail.ReadWrite`, `Application Mail.Send` and the read-only `Application MailboxSettings.Read` in it. Graph registers the app in Exchange by itself. Each step is idempotent; an existing scope is updated with only its `RecipientFilter` (Exchange refuses a PATCH that names `Exclusive`). The delegated token is not stored. Refusals are logged (`m365 setup:`).
|
|
125
|
+
3. **Bijna klaar**: a checklist (signed in as, access set up for the mailboxes, Microsoft switching it on). The access check runs on every status request (at most once a minute) and from the cron, for 4 hours. Connected = every mailbox `ok` and the check mailbox `denied`. A reachable check mailbox is a scope leak: the setup fails and the helpdesk stays blocked. A missing mailbox (404) fails at once. Without any check mailbox (the app admin's address is in another domain and the Microsoft admin has no mailbox) the setup fails with `check_mailbox_missing` and asks for one.
|
|
126
|
+
4. **Gekoppeld**: "Naar de helpdesk", the warnings from MailboxSettings.Read (a person's mailbox; Inbox rules that move, delete or forward mail), the mailboxes, who connected them, and a link to the helpdesk settings.
|
|
127
|
+
5. **Fallback** ("Dat lukte niet in één keer"): when Graph refuses (`exchangeSetupError`: no Exchange rights, a tenant that still needs `Enable-OrganizationCustomization`, any other error), the page explains why and offers "Opnieuw proberen" first, the IT link second, and "Liever met PowerShell" folded away (open at once when only the script can finish). The PowerShell route (also "Gebruik het script" on the start screen) uses the tenant `adminconsent` URL, then "Script downloaden" (`dxv-helpdesk-koppelen.ps1`, tested against a real tenant, ASCII, CRLF) and "Opdracht kopiëren": a hashtable splat with the app id, Object ID, mailboxes, check mailbox and either `AdminAccount` or `PartnerTenant` (GDAP). Every value is validated strictly and quoted for a PowerShell double-quoted string. The script names its Exchange objects per app: group `DXV Helpdesk <first 8 characters of the AppId>`, scope `<group> mailboxes`, role assignments `<group> - Application …`. `exchangeGroupName(appId)` gives the same group name for the page.
|
|
128
|
+
|
|
129
|
+
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 }`).
|
|
130
|
+
|
|
131
|
+
### Mounting it in an app
|
|
132
|
+
|
|
133
|
+
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).
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// lib/m365-setup.ts
|
|
137
|
+
import { createGraphClient } from "@dxv-systems/mail-graph";
|
|
138
|
+
import { createM365SetupHandlers } from "@dxv-systems/mail-graph/setup";
|
|
139
|
+
|
|
140
|
+
export const m365Setup = createM365SetupHandlers({
|
|
141
|
+
isProduction: process.env.VERCEL_ENV === "production",
|
|
142
|
+
clientId: process.env.M365_CLIENT_ID,
|
|
143
|
+
setupReady: process.env.M365_SETUP_READY === "true", // set once the Entra app is publisher verified
|
|
144
|
+
appOrigin: "https://app.klant.nl",
|
|
145
|
+
secret: setupKey, // 32+ chars; apps derive it from SESSION_SECRET with HKDF (docs/app-integration.md)
|
|
146
|
+
store: { load: loadConnectionRow, save: saveConnectionRow },
|
|
147
|
+
getAdmin: async (request) => currentAppAdmin(request), // { id, email } or null
|
|
148
|
+
createGraphClient: (tenantId) =>
|
|
149
|
+
createGraphClient({ tenantId, clientId: process.env.M365_CLIENT_ID!, getClientAssertion: getVercelOidcToken }),
|
|
150
|
+
getClientAssertion: getVercelOidcToken, // required: the app sets up Exchange on the admin's sign-in
|
|
151
|
+
companyName: "Klant",
|
|
152
|
+
entraAppName: "DXV Helpdesk – Klant",
|
|
153
|
+
pagePath: "/beheer/microsoft-365",
|
|
154
|
+
itLinkPagePath: "/microsoft-365/koppelen",
|
|
155
|
+
onConnected: async () => { /* notify the admin, start the first delta sync */ },
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// app/api/m365/[...path]/route.ts
|
|
159
|
+
export const GET = m365Setup.handle;
|
|
160
|
+
export const POST = m365Setup.handle;
|
|
161
|
+
export const DELETE = m365Setup.handle;
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
```tsx
|
|
165
|
+
// admin page
|
|
166
|
+
<M365SetupPage helpdeskHref="/helpdesk" settingsHref="/helpdesk/instellingen" />
|
|
167
|
+
// IT link page: /microsoft-365/koppelen/[token], public, Referrer-Policy: no-referrer
|
|
168
|
+
<M365SetupPage linkToken={params.token} />
|
|
169
|
+
```
|
|
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).
|
|
172
|
+
|
|
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
|
+
|
|
175
|
+
Styling is fixed in the package and uses the template's shadcn tokens (`bg-primary`, `border-border`, `text-muted-foreground`, `text-destructive`), so it follows the app's theme and dark mode; the app's Tailwind must scan the package (`@source`). Buttons and inputs are at least 44 px high.
|
|
176
|
+
|
|
177
|
+
## Throttling and concurrency
|
|
178
|
+
|
|
179
|
+
- `429` and `503` are retried honouring `Retry-After` (seconds or date), at most 4 attempts. Without the header the backoff doubles from 1 s, capped at 20 s. A `Retry-After` above `maxRetryWaitMs` (default 20 s, so a function is not outlasted) is not waited for: the `GraphError` is thrown with `retryAfterMs` set, for the next cron run. The same rule applies to the token request (cap `federationRetry.maxDelayMs`, 20 s).
|
|
180
|
+
- `sendDraft`, `sendMail` and `forward` are not retried on `503`, because the mail may already have gone out; they still retry on `429`.
|
|
181
|
+
- At most 4 requests run at once per mailbox address per client instance (Graph's limit); further calls queue.
|
|
182
|
+
- A `401` fetches one new token and retries once.
|
|
183
|
+
- Network errors and timeouts (30 s per attempt, token requests included; `requestTimeoutMs`) are not retried: a repeated `send` could double-send.
|
|
184
|
+
|
|
185
|
+
## Errors
|
|
186
|
+
|
|
187
|
+
`GraphError` has `status`, `code` (Graph's error code, such as `ErrorAccessDenied`) and `requestId`. Subclasses: `GraphAuthError` (token endpoint or assertion; `code` is `AADSTS…`), `GraphDeltaExpiredError`, `GraphUsageError` (caught before sending: `InvalidArgument`, `InvalidLink`, `MethodNotAllowed`, `AttachmentTooLarge`).
|
|
188
|
+
|
|
189
|
+
Messages are English and contain only the status and code. Graph's free-text message, tokens, assertions, upload URLs and mail content are never put in an error.
|
|
190
|
+
|
|
191
|
+
## Testing
|
|
192
|
+
|
|
193
|
+
Pass `fetch` (and optionally `sleep`, `now`) to `createGraphClient` and answer Graph requests yourself; see `src/__tests__/helpers.ts` for a small harness.
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
npm ci
|
|
199
|
+
npm run build -w @dxv-systems/mail-graph
|
|
200
|
+
npm test -w @dxv-systems/mail-graph
|
|
201
|
+
```
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type FetchLike, type SleepFn } from "./util";
|
|
2
|
+
export interface ClientCredentials {
|
|
3
|
+
tenantId: string;
|
|
4
|
+
clientId: string;
|
|
5
|
+
getClientAssertion: () => Promise<string>;
|
|
6
|
+
}
|
|
7
|
+
export interface FederationRetryOptions {
|
|
8
|
+
maxAttempts?: number;
|
|
9
|
+
baseDelayMs?: number;
|
|
10
|
+
maxDelayMs?: number;
|
|
11
|
+
}
|
|
12
|
+
export interface TokenProviderDeps {
|
|
13
|
+
fetch: FetchLike;
|
|
14
|
+
sleep?: SleepFn;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
retry?: FederationRetryOptions;
|
|
17
|
+
requestTimeoutMs?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface TokenProvider {
|
|
20
|
+
getToken(): Promise<string>;
|
|
21
|
+
invalidate(token: string): void;
|
|
22
|
+
}
|
|
23
|
+
export declare function createTokenProvider(credentials: ClientCredentials, deps: TokenProviderDeps): TokenProvider;
|
|
24
|
+
export interface TokenIdentity {
|
|
25
|
+
objectId: string;
|
|
26
|
+
tenantId: string;
|
|
27
|
+
}
|
|
28
|
+
export declare function readTokenIdentity(accessToken: string): TokenIdentity;
|
|
29
|
+
export interface AuthorizationCodeInput {
|
|
30
|
+
tenantId: string;
|
|
31
|
+
clientId: string;
|
|
32
|
+
code: string;
|
|
33
|
+
redirectUri: string;
|
|
34
|
+
scopes: string[];
|
|
35
|
+
getClientAssertion: () => Promise<string>;
|
|
36
|
+
fetch: FetchLike;
|
|
37
|
+
}
|
|
38
|
+
export declare function redeemAuthorizationCode(input: AuthorizationCodeInput): Promise<{
|
|
39
|
+
accessToken: string;
|
|
40
|
+
tenantId: string;
|
|
41
|
+
}>;
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createTokenProvider = createTokenProvider;
|
|
4
|
+
exports.readTokenIdentity = readTokenIdentity;
|
|
5
|
+
exports.redeemAuthorizationCode = redeemAuthorizationCode;
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
const util_1 = require("./util");
|
|
8
|
+
const ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
9
|
+
const SCOPE = "https://graph.microsoft.com/.default";
|
|
10
|
+
const SKEW_MS = 5 * 60000;
|
|
11
|
+
const TRANSIENT = new Set([429, 500, 502, 503, 504]);
|
|
12
|
+
const TENANT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;
|
|
13
|
+
function describeTokenFailure(body) {
|
|
14
|
+
const record = body && typeof body === "object" ? body : {};
|
|
15
|
+
const codes = Array.isArray(record.error_codes) ? record.error_codes.filter((c) => typeof c === "number") : [];
|
|
16
|
+
const description = typeof record.error_description === "string" ? record.error_description : "";
|
|
17
|
+
const federationLag = codes.includes(70021) || /AADSTS70021\b/.test(description);
|
|
18
|
+
const code = codes.length > 0 ? `AADSTS${codes[0]}` : typeof record.error === "string" && record.error ? record.error : "token_error";
|
|
19
|
+
return { code, federationLag };
|
|
20
|
+
}
|
|
21
|
+
function createTokenProvider(credentials, deps) {
|
|
22
|
+
if (!TENANT_PATTERN.test(credentials.tenantId)) {
|
|
23
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "tenantId must be a tenant GUID or domain name.");
|
|
24
|
+
}
|
|
25
|
+
if (!credentials.clientId)
|
|
26
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "clientId is required.");
|
|
27
|
+
const sleep = deps.sleep ?? util_1.defaultSleep;
|
|
28
|
+
const now = deps.now ?? Date.now;
|
|
29
|
+
const maxAttempts = Math.max(1, deps.retry?.maxAttempts ?? 5);
|
|
30
|
+
const baseDelayMs = deps.retry?.baseDelayMs ?? 2000;
|
|
31
|
+
const maxDelayMs = deps.retry?.maxDelayMs ?? 20000;
|
|
32
|
+
const timeoutMs = deps.requestTimeoutMs ?? 30000;
|
|
33
|
+
const url = `https://login.microsoftonline.com/${encodeURIComponent(credentials.tenantId)}/oauth2/v2.0/token`;
|
|
34
|
+
let cached = null;
|
|
35
|
+
let inFlight = null;
|
|
36
|
+
async function requestToken() {
|
|
37
|
+
for (let attempt = 1;; attempt++) {
|
|
38
|
+
let assertion;
|
|
39
|
+
try {
|
|
40
|
+
assertion = await credentials.getClientAssertion();
|
|
41
|
+
}
|
|
42
|
+
catch (cause) {
|
|
43
|
+
throw new errors_1.GraphAuthError({
|
|
44
|
+
message: "Could not obtain a client assertion from getClientAssertion.",
|
|
45
|
+
status: 0,
|
|
46
|
+
code: "AssertionUnavailable",
|
|
47
|
+
cause,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
if (typeof assertion !== "string" || assertion === "") {
|
|
51
|
+
throw new errors_1.GraphAuthError({
|
|
52
|
+
message: "getClientAssertion returned an empty value.",
|
|
53
|
+
status: 0,
|
|
54
|
+
code: "AssertionUnavailable",
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
let response;
|
|
58
|
+
try {
|
|
59
|
+
response = await deps.fetch(url, {
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
62
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
63
|
+
body: new URLSearchParams({
|
|
64
|
+
client_id: credentials.clientId,
|
|
65
|
+
scope: SCOPE,
|
|
66
|
+
grant_type: "client_credentials",
|
|
67
|
+
client_assertion_type: ASSERTION_TYPE,
|
|
68
|
+
client_assertion: assertion,
|
|
69
|
+
}).toString(),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
catch (cause) {
|
|
73
|
+
throw new errors_1.GraphAuthError({ message: "Token request failed: network error.", status: 0, code: "NetworkError", cause });
|
|
74
|
+
}
|
|
75
|
+
if (response.ok) {
|
|
76
|
+
const body = (await response.json().catch(() => null));
|
|
77
|
+
if (!body || typeof body.access_token !== "string" || body.access_token === "") {
|
|
78
|
+
throw new errors_1.GraphAuthError({
|
|
79
|
+
message: "Token response did not contain an access token.",
|
|
80
|
+
status: response.status,
|
|
81
|
+
code: "InvalidTokenResponse",
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const lifetimeMs = (Number(body.expires_in) > 0 ? Number(body.expires_in) : 3600) * 1000;
|
|
85
|
+
const skew = Math.min(SKEW_MS, lifetimeMs / 2);
|
|
86
|
+
return { token: body.access_token, refreshAt: now() + lifetimeMs - skew };
|
|
87
|
+
}
|
|
88
|
+
const failure = describeTokenFailure(await response.json().catch(() => null));
|
|
89
|
+
const retryAfterMs = (0, util_1.parseRetryAfter)(response.headers.get("Retry-After"), now());
|
|
90
|
+
const retryable = failure.federationLag || TRANSIENT.has(response.status);
|
|
91
|
+
if (retryable && attempt < maxAttempts && (retryAfterMs === null || retryAfterMs <= maxDelayMs)) {
|
|
92
|
+
const backoff = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);
|
|
93
|
+
await sleep(Math.max(backoff, retryAfterMs ?? 0));
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
throw new errors_1.GraphAuthError({
|
|
97
|
+
message: `Token request failed (${response.status} ${failure.code}).`,
|
|
98
|
+
status: response.status,
|
|
99
|
+
code: failure.code,
|
|
100
|
+
requestId: response.headers.get("x-ms-request-id") ?? undefined,
|
|
101
|
+
retryAfterMs: retryAfterMs ?? undefined,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
async getToken() {
|
|
107
|
+
if (cached && now() < cached.refreshAt)
|
|
108
|
+
return cached.token;
|
|
109
|
+
if (!inFlight) {
|
|
110
|
+
inFlight = requestToken()
|
|
111
|
+
.then((fresh) => {
|
|
112
|
+
cached = fresh;
|
|
113
|
+
return fresh.token;
|
|
114
|
+
})
|
|
115
|
+
.finally(() => {
|
|
116
|
+
inFlight = null;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return inFlight;
|
|
120
|
+
},
|
|
121
|
+
invalidate(token) {
|
|
122
|
+
if (cached?.token === token)
|
|
123
|
+
cached = null;
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function readTokenIdentity(accessToken) {
|
|
128
|
+
const part = accessToken.split(".")[1];
|
|
129
|
+
let claims = {};
|
|
130
|
+
if (part) {
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
133
|
+
if (parsed && typeof parsed === "object")
|
|
134
|
+
claims = parsed;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
claims = {};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (typeof claims.oid !== "string" || typeof claims.tid !== "string" || !claims.oid || !claims.tid) {
|
|
141
|
+
throw new errors_1.GraphAuthError({
|
|
142
|
+
message: "Access token has no oid and tid claims.",
|
|
143
|
+
status: 0,
|
|
144
|
+
code: "InvalidToken",
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return { objectId: claims.oid, tenantId: claims.tid };
|
|
148
|
+
}
|
|
149
|
+
async function redeemAuthorizationCode(input) {
|
|
150
|
+
if (!TENANT_PATTERN.test(input.tenantId)) {
|
|
151
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "tenantId must be a tenant GUID or domain name.");
|
|
152
|
+
}
|
|
153
|
+
let response;
|
|
154
|
+
try {
|
|
155
|
+
response = await input.fetch(`https://login.microsoftonline.com/${encodeURIComponent(input.tenantId)}/oauth2/v2.0/token`, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
158
|
+
signal: AbortSignal.timeout(30000),
|
|
159
|
+
body: new URLSearchParams({
|
|
160
|
+
client_id: input.clientId,
|
|
161
|
+
grant_type: "authorization_code",
|
|
162
|
+
code: input.code,
|
|
163
|
+
redirect_uri: input.redirectUri,
|
|
164
|
+
scope: input.scopes.join(" "),
|
|
165
|
+
client_assertion_type: ASSERTION_TYPE,
|
|
166
|
+
client_assertion: await input.getClientAssertion(),
|
|
167
|
+
}).toString(),
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
catch (cause) {
|
|
171
|
+
throw new errors_1.GraphAuthError({ message: "Code redemption failed: network error.", status: 0, code: "NetworkError", cause });
|
|
172
|
+
}
|
|
173
|
+
const body = (await response.json().catch(() => null));
|
|
174
|
+
if (!response.ok || !body || typeof body.access_token !== "string" || body.access_token === "") {
|
|
175
|
+
const failure = describeTokenFailure(body);
|
|
176
|
+
throw new errors_1.GraphAuthError({
|
|
177
|
+
message: `Code redemption failed (${response.status} ${failure.code}).`,
|
|
178
|
+
status: response.status,
|
|
179
|
+
code: failure.code,
|
|
180
|
+
requestId: response.headers.get("x-ms-request-id") ?? undefined,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return { accessToken: body.access_token, tenantId: readTokenIdentity(body.access_token).tenantId };
|
|
184
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ClientCredentials, type FederationRetryOptions, type TokenIdentity } from "./auth";
|
|
2
|
+
import { type MailboxClient } from "./mailbox";
|
|
3
|
+
import type { FetchLike, SleepFn } from "./util";
|
|
4
|
+
export interface GraphClientOptions extends ClientCredentials {
|
|
5
|
+
fetch?: FetchLike;
|
|
6
|
+
sleep?: SleepFn;
|
|
7
|
+
now?: () => number;
|
|
8
|
+
federationRetry?: FederationRetryOptions;
|
|
9
|
+
maxAttempts?: number;
|
|
10
|
+
maxRetryWaitMs?: number;
|
|
11
|
+
requestTimeoutMs?: number;
|
|
12
|
+
maxConcurrentPerMailbox?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface GraphClient {
|
|
15
|
+
mailbox(address: string): MailboxClient;
|
|
16
|
+
getAppIdentity(): Promise<TokenIdentity>;
|
|
17
|
+
}
|
|
18
|
+
export declare function createGraphClient(options: GraphClientOptions): GraphClient;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createGraphClient = createGraphClient;
|
|
4
|
+
const auth_1 = require("./auth");
|
|
5
|
+
const http_1 = require("./http");
|
|
6
|
+
const mailbox_1 = require("./mailbox");
|
|
7
|
+
function createGraphClient(options) {
|
|
8
|
+
const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
9
|
+
const tokens = (0, auth_1.createTokenProvider)(options, {
|
|
10
|
+
fetch: fetchImpl,
|
|
11
|
+
sleep: options.sleep,
|
|
12
|
+
now: options.now,
|
|
13
|
+
retry: options.federationRetry,
|
|
14
|
+
requestTimeoutMs: options.requestTimeoutMs,
|
|
15
|
+
});
|
|
16
|
+
const httpOptions = {
|
|
17
|
+
fetch: fetchImpl,
|
|
18
|
+
getToken: tokens.getToken,
|
|
19
|
+
invalidateToken: tokens.invalidate,
|
|
20
|
+
sleep: options.sleep,
|
|
21
|
+
now: options.now,
|
|
22
|
+
maxAttempts: options.maxAttempts,
|
|
23
|
+
maxRetryWaitMs: options.maxRetryWaitMs,
|
|
24
|
+
requestTimeoutMs: options.requestTimeoutMs,
|
|
25
|
+
maxConcurrentPerMailbox: options.maxConcurrentPerMailbox,
|
|
26
|
+
};
|
|
27
|
+
const http = (0, http_1.createHttp)(httpOptions);
|
|
28
|
+
return {
|
|
29
|
+
mailbox: (address) => (0, mailbox_1.createMailboxClient)(http, address),
|
|
30
|
+
async getAppIdentity() {
|
|
31
|
+
return (0, auth_1.readTokenIdentity)(await tokens.getToken());
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface GraphErrorInit {
|
|
2
|
+
message: string;
|
|
3
|
+
status: number;
|
|
4
|
+
code: string;
|
|
5
|
+
requestId?: string;
|
|
6
|
+
retryAfterMs?: number;
|
|
7
|
+
cause?: unknown;
|
|
8
|
+
}
|
|
9
|
+
export declare class GraphError extends Error {
|
|
10
|
+
readonly status: number;
|
|
11
|
+
readonly code: string;
|
|
12
|
+
readonly requestId?: string;
|
|
13
|
+
readonly retryAfterMs?: number;
|
|
14
|
+
constructor(init: GraphErrorInit);
|
|
15
|
+
}
|
|
16
|
+
export declare class GraphAuthError extends GraphError {
|
|
17
|
+
constructor(init: GraphErrorInit);
|
|
18
|
+
}
|
|
19
|
+
export declare class GraphDeltaExpiredError extends GraphError {
|
|
20
|
+
constructor(init: GraphErrorInit);
|
|
21
|
+
}
|
|
22
|
+
export type UsageErrorCode = "InvalidArgument" | "InvalidLink" | "MethodNotAllowed" | "AttachmentTooLarge";
|
|
23
|
+
export declare class GraphUsageError extends GraphError {
|
|
24
|
+
constructor(code: UsageErrorCode, message: string);
|
|
25
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GraphUsageError = exports.GraphDeltaExpiredError = exports.GraphAuthError = exports.GraphError = void 0;
|
|
4
|
+
class GraphError extends Error {
|
|
5
|
+
constructor(init) {
|
|
6
|
+
super(init.message, init.cause !== undefined ? { cause: init.cause } : undefined);
|
|
7
|
+
this.name = "GraphError";
|
|
8
|
+
this.status = init.status;
|
|
9
|
+
this.code = init.code;
|
|
10
|
+
this.requestId = init.requestId;
|
|
11
|
+
this.retryAfterMs = init.retryAfterMs;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
exports.GraphError = GraphError;
|
|
15
|
+
class GraphAuthError extends GraphError {
|
|
16
|
+
constructor(init) {
|
|
17
|
+
super(init);
|
|
18
|
+
this.name = "GraphAuthError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.GraphAuthError = GraphAuthError;
|
|
22
|
+
class GraphDeltaExpiredError extends GraphError {
|
|
23
|
+
constructor(init) {
|
|
24
|
+
super(init);
|
|
25
|
+
this.name = "GraphDeltaExpiredError";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
exports.GraphDeltaExpiredError = GraphDeltaExpiredError;
|
|
29
|
+
class GraphUsageError extends GraphError {
|
|
30
|
+
constructor(code, message) {
|
|
31
|
+
super({ message, status: 0, code });
|
|
32
|
+
this.name = "GraphUsageError";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.GraphUsageError = GraphUsageError;
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type FetchLike, type SleepFn } from "./util";
|
|
2
|
+
export type GraphMethod = "GET" | "POST" | "PATCH";
|
|
3
|
+
export interface RequestSpec {
|
|
4
|
+
mailbox: string;
|
|
5
|
+
method: GraphMethod;
|
|
6
|
+
path?: string;
|
|
7
|
+
link?: string;
|
|
8
|
+
body?: unknown;
|
|
9
|
+
retryOn503?: boolean;
|
|
10
|
+
prefer?: string[];
|
|
11
|
+
binary?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface HttpResult {
|
|
14
|
+
status: number;
|
|
15
|
+
data: unknown;
|
|
16
|
+
bytes?: Uint8Array;
|
|
17
|
+
}
|
|
18
|
+
export interface HttpOptions {
|
|
19
|
+
fetch: FetchLike;
|
|
20
|
+
getToken: () => Promise<string>;
|
|
21
|
+
invalidateToken: (token: string) => void;
|
|
22
|
+
sleep?: SleepFn;
|
|
23
|
+
now?: () => number;
|
|
24
|
+
maxAttempts?: number;
|
|
25
|
+
maxRetryWaitMs?: number;
|
|
26
|
+
baseBackoffMs?: number;
|
|
27
|
+
requestTimeoutMs?: number;
|
|
28
|
+
maxConcurrentPerMailbox?: number;
|
|
29
|
+
}
|
|
30
|
+
export interface Http {
|
|
31
|
+
request(spec: RequestSpec): Promise<HttpResult>;
|
|
32
|
+
deleteMessage(spec: {
|
|
33
|
+
mailbox: string;
|
|
34
|
+
path: string;
|
|
35
|
+
}): Promise<HttpResult>;
|
|
36
|
+
uploadChunk(spec: {
|
|
37
|
+
mailbox: string;
|
|
38
|
+
uploadUrl: string;
|
|
39
|
+
start: number;
|
|
40
|
+
total: number;
|
|
41
|
+
bytes: Uint8Array;
|
|
42
|
+
}): Promise<HttpResult>;
|
|
43
|
+
}
|
|
44
|
+
export declare function createHttp(options: HttpOptions): Http;
|