@openclaw/msteams 2026.3.1 → 2026.3.7

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 (48) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/index.ts +2 -2
  3. package/package.json +1 -1
  4. package/src/attachments/download.ts +62 -12
  5. package/src/attachments/graph.ts +28 -9
  6. package/src/attachments/payload.ts +1 -1
  7. package/src/attachments/remote-media.ts +1 -1
  8. package/src/attachments/shared.test.ts +351 -1
  9. package/src/attachments/shared.ts +188 -2
  10. package/src/attachments.test.ts +176 -9
  11. package/src/channel.directory.test.ts +1 -1
  12. package/src/channel.ts +95 -101
  13. package/src/directory-live.ts +1 -1
  14. package/src/errors.test.ts +25 -0
  15. package/src/errors.ts +15 -0
  16. package/src/file-lock.ts +1 -1
  17. package/src/graph.ts +1 -1
  18. package/src/media-helpers.ts +1 -1
  19. package/src/messenger.test.ts +74 -3
  20. package/src/messenger.ts +69 -29
  21. package/src/monitor-handler/message-handler.authz.test.ts +1 -1
  22. package/src/monitor-handler/message-handler.ts +59 -53
  23. package/src/monitor-handler.file-consent.test.ts +5 -11
  24. package/src/monitor-handler.ts +14 -4
  25. package/src/monitor.lifecycle.test.ts +214 -0
  26. package/src/monitor.test.ts +85 -0
  27. package/src/monitor.ts +50 -10
  28. package/src/onboarding.ts +33 -58
  29. package/src/outbound.test.ts +131 -0
  30. package/src/outbound.ts +1 -1
  31. package/src/policy.test.ts +1 -1
  32. package/src/policy.ts +9 -10
  33. package/src/probe.test.ts +1 -1
  34. package/src/probe.ts +6 -2
  35. package/src/reply-dispatcher.ts +30 -2
  36. package/src/resolve-allowlist.test.ts +78 -0
  37. package/src/resolve-allowlist.ts +70 -79
  38. package/src/revoked-context.test.ts +39 -0
  39. package/src/revoked-context.ts +17 -0
  40. package/src/runtime.ts +1 -1
  41. package/src/secret-input.ts +7 -0
  42. package/src/send-context.ts +1 -1
  43. package/src/send.test.ts +2 -2
  44. package/src/send.ts +42 -43
  45. package/src/store-fs.ts +1 -1
  46. package/src/test-runtime.ts +1 -1
  47. package/src/token.test.ts +72 -0
  48. package/src/token.ts +25 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.3.7
4
+
5
+ ### Changes
6
+
7
+ - Version alignment with core OpenClaw release numbers.
8
+
9
+ ## 2026.3.3
10
+
11
+ ### Changes
12
+
13
+ - Version alignment with core OpenClaw release numbers.
14
+
15
+ ## 2026.3.2
16
+
17
+ ### Changes
18
+
19
+ - Version alignment with core OpenClaw release numbers.
20
+
3
21
  ## 2026.3.1
4
22
 
5
23
  ### Changes
package/index.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
- import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk/msteams";
2
+ import { emptyPluginConfigSchema } from "openclaw/plugin-sdk/msteams";
3
3
  import { msteamsPlugin } from "./src/channel.js";
4
4
  import { setMSTeamsRuntime } from "./src/runtime.js";
5
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/msteams",
3
- "version": "2026.3.1",
3
+ "version": "2026.3.7",
4
4
  "description": "OpenClaw Microsoft Teams channel plugin",
5
5
  "type": "module",
6
6
  "dependencies": {
@@ -1,4 +1,3 @@
1
- import { fetchWithBearerAuthScopeFallback } from "openclaw/plugin-sdk";
2
1
  import { getMSTeamsRuntime } from "../runtime.js";
3
2
  import { downloadAndStoreMSTeamsRemoteMedia } from "./remote-media.js";
4
3
  import {
@@ -7,11 +6,12 @@ import {
7
6
  isDownloadableAttachment,
8
7
  isRecord,
9
8
  isUrlAllowed,
9
+ type MSTeamsAttachmentFetchPolicy,
10
10
  normalizeContentType,
11
11
  resolveMediaSsrfPolicy,
12
+ resolveAttachmentFetchPolicy,
12
13
  resolveRequestUrl,
13
- resolveAuthAllowedHosts,
14
- resolveAllowedHosts,
14
+ safeFetchWithPolicy,
15
15
  } from "./shared.js";
16
16
  import type {
17
17
  MSTeamsAccessTokenProvider,
@@ -86,22 +86,69 @@ function scopeCandidatesForUrl(url: string): string[] {
86
86
  }
87
87
  }
88
88
 
89
+ function isRedirectStatus(status: number): boolean {
90
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
91
+ }
92
+
89
93
  async function fetchWithAuthFallback(params: {
90
94
  url: string;
91
95
  tokenProvider?: MSTeamsAccessTokenProvider;
92
96
  fetchFn?: typeof fetch;
93
97
  requestInit?: RequestInit;
94
- authAllowHosts: string[];
98
+ policy: MSTeamsAttachmentFetchPolicy;
95
99
  }): Promise<Response> {
96
- return await fetchWithBearerAuthScopeFallback({
100
+ const firstAttempt = await safeFetchWithPolicy({
97
101
  url: params.url,
98
- scopes: scopeCandidatesForUrl(params.url),
99
- tokenProvider: params.tokenProvider,
102
+ policy: params.policy,
100
103
  fetchFn: params.fetchFn,
101
104
  requestInit: params.requestInit,
102
- requireHttps: true,
103
- shouldAttachAuth: (url) => isUrlAllowed(url, params.authAllowHosts),
104
105
  });
106
+ if (firstAttempt.ok) {
107
+ return firstAttempt;
108
+ }
109
+ if (!params.tokenProvider) {
110
+ return firstAttempt;
111
+ }
112
+ if (firstAttempt.status !== 401 && firstAttempt.status !== 403) {
113
+ return firstAttempt;
114
+ }
115
+ if (!isUrlAllowed(params.url, params.policy.authAllowHosts)) {
116
+ return firstAttempt;
117
+ }
118
+
119
+ const scopes = scopeCandidatesForUrl(params.url);
120
+ const fetchFn = params.fetchFn ?? fetch;
121
+ for (const scope of scopes) {
122
+ try {
123
+ const token = await params.tokenProvider.getAccessToken(scope);
124
+ const authHeaders = new Headers(params.requestInit?.headers);
125
+ authHeaders.set("Authorization", `Bearer ${token}`);
126
+ const authAttempt = await safeFetchWithPolicy({
127
+ url: params.url,
128
+ policy: params.policy,
129
+ fetchFn,
130
+ requestInit: {
131
+ ...params.requestInit,
132
+ headers: authHeaders,
133
+ },
134
+ });
135
+ if (authAttempt.ok) {
136
+ return authAttempt;
137
+ }
138
+ if (isRedirectStatus(authAttempt.status)) {
139
+ // Redirects in guarded fetch mode must propagate to the outer guard.
140
+ return authAttempt;
141
+ }
142
+ if (authAttempt.status !== 401 && authAttempt.status !== 403) {
143
+ // Preserve scope fallback semantics for non-auth failures.
144
+ continue;
145
+ }
146
+ } catch {
147
+ // Try the next scope.
148
+ }
149
+ }
150
+
151
+ return firstAttempt;
105
152
  }
106
153
 
107
154
  /**
@@ -122,8 +169,11 @@ export async function downloadMSTeamsAttachments(params: {
122
169
  if (list.length === 0) {
123
170
  return [];
124
171
  }
125
- const allowHosts = resolveAllowedHosts(params.allowHosts);
126
- const authAllowHosts = resolveAuthAllowedHosts(params.authAllowHosts);
172
+ const policy = resolveAttachmentFetchPolicy({
173
+ allowHosts: params.allowHosts,
174
+ authAllowHosts: params.authAllowHosts,
175
+ });
176
+ const allowHosts = policy.allowHosts;
127
177
  const ssrfPolicy = resolveMediaSsrfPolicy(allowHosts);
128
178
 
129
179
  // Download ANY downloadable attachment (not just images)
@@ -200,7 +250,7 @@ export async function downloadMSTeamsAttachments(params: {
200
250
  tokenProvider: params.tokenProvider,
201
251
  fetchFn: params.fetchFn,
202
252
  requestInit: init,
203
- authAllowHosts,
253
+ policy,
204
254
  }),
205
255
  });
206
256
  out.push(media);
@@ -1,16 +1,19 @@
1
- import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk";
1
+ import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk/msteams";
2
2
  import { getMSTeamsRuntime } from "../runtime.js";
3
3
  import { downloadMSTeamsAttachments } from "./download.js";
4
4
  import { downloadAndStoreMSTeamsRemoteMedia } from "./remote-media.js";
5
5
  import {
6
+ applyAuthorizationHeaderForUrl,
6
7
  GRAPH_ROOT,
7
8
  inferPlaceholder,
8
9
  isRecord,
9
10
  isUrlAllowed,
11
+ type MSTeamsAttachmentFetchPolicy,
10
12
  normalizeContentType,
11
13
  resolveMediaSsrfPolicy,
14
+ resolveAttachmentFetchPolicy,
12
15
  resolveRequestUrl,
13
- resolveAllowedHosts,
16
+ safeFetchWithPolicy,
14
17
  } from "./shared.js";
15
18
  import type {
16
19
  MSTeamsAccessTokenProvider,
@@ -241,8 +244,11 @@ export async function downloadMSTeamsGraphMedia(params: {
241
244
  if (!params.messageUrl || !params.tokenProvider) {
242
245
  return { media: [] };
243
246
  }
244
- const allowHosts = resolveAllowedHosts(params.allowHosts);
245
- const ssrfPolicy = resolveMediaSsrfPolicy(allowHosts);
247
+ const policy: MSTeamsAttachmentFetchPolicy = resolveAttachmentFetchPolicy({
248
+ allowHosts: params.allowHosts,
249
+ authAllowHosts: params.authAllowHosts,
250
+ });
251
+ const ssrfPolicy = resolveMediaSsrfPolicy(policy.allowHosts);
246
252
  const messageUrl = params.messageUrl;
247
253
  let accessToken: string;
248
254
  try {
@@ -288,7 +294,7 @@ export async function downloadMSTeamsGraphMedia(params: {
288
294
  try {
289
295
  // SharePoint URLs need to be accessed via Graph shares API
290
296
  const shareUrl = att.contentUrl!;
291
- if (!isUrlAllowed(shareUrl, allowHosts)) {
297
+ if (!isUrlAllowed(shareUrl, policy.allowHosts)) {
292
298
  continue;
293
299
  }
294
300
  const encodedUrl = Buffer.from(shareUrl).toString("base64url");
@@ -304,8 +310,21 @@ export async function downloadMSTeamsGraphMedia(params: {
304
310
  fetchImpl: async (input, init) => {
305
311
  const requestUrl = resolveRequestUrl(input);
306
312
  const headers = new Headers(init?.headers);
307
- headers.set("Authorization", `Bearer ${accessToken}`);
308
- return await fetchFn(requestUrl, { ...init, headers });
313
+ applyAuthorizationHeaderForUrl({
314
+ headers,
315
+ url: requestUrl,
316
+ authAllowHosts: policy.authAllowHosts,
317
+ bearerToken: accessToken,
318
+ });
319
+ return await safeFetchWithPolicy({
320
+ url: requestUrl,
321
+ policy,
322
+ fetchFn,
323
+ requestInit: {
324
+ ...init,
325
+ headers,
326
+ },
327
+ });
309
328
  },
310
329
  });
311
330
  sharePointMedia.push(media);
@@ -357,8 +376,8 @@ export async function downloadMSTeamsGraphMedia(params: {
357
376
  attachments: filteredAttachments,
358
377
  maxBytes: params.maxBytes,
359
378
  tokenProvider: params.tokenProvider,
360
- allowHosts,
361
- authAllowHosts: params.authAllowHosts,
379
+ allowHosts: policy.allowHosts,
380
+ authAllowHosts: policy.authAllowHosts,
362
381
  fetchFn: params.fetchFn,
363
382
  preserveFilenames: params.preserveFilenames,
364
383
  });
@@ -1,4 +1,4 @@
1
- import { buildMediaPayload } from "openclaw/plugin-sdk";
1
+ import { buildMediaPayload } from "openclaw/plugin-sdk/msteams";
2
2
 
3
3
  export function buildMSTeamsMediaPayload(
4
4
  mediaList: Array<{ path: string; contentType?: string }>,
@@ -1,4 +1,4 @@
1
- import type { SsrFPolicy } from "openclaw/plugin-sdk";
1
+ import type { SsrFPolicy } from "openclaw/plugin-sdk/msteams";
2
2
  import { getMSTeamsRuntime } from "../runtime.js";
3
3
  import { inferPlaceholder } from "./shared.js";
4
4
  import type { MSTeamsInboundMedia } from "./types.js";
@@ -1,17 +1,54 @@
1
- import { describe, expect, it } from "vitest";
1
+ import { describe, expect, it, vi } from "vitest";
2
2
  import {
3
+ applyAuthorizationHeaderForUrl,
4
+ isPrivateOrReservedIP,
3
5
  isUrlAllowed,
6
+ resolveAndValidateIP,
7
+ resolveAttachmentFetchPolicy,
4
8
  resolveAllowedHosts,
5
9
  resolveAuthAllowedHosts,
6
10
  resolveMediaSsrfPolicy,
11
+ safeFetch,
12
+ safeFetchWithPolicy,
7
13
  } from "./shared.js";
8
14
 
15
+ const publicResolve = async () => ({ address: "13.107.136.10" });
16
+ const privateResolve = (ip: string) => async () => ({ address: ip });
17
+ const failingResolve = async () => {
18
+ throw new Error("DNS failure");
19
+ };
20
+
21
+ function mockFetchWithRedirect(redirectMap: Record<string, string>, finalBody = "ok") {
22
+ return vi.fn(async (url: string, init?: RequestInit) => {
23
+ const target = redirectMap[url];
24
+ if (target && init?.redirect === "manual") {
25
+ return new Response(null, {
26
+ status: 302,
27
+ headers: { location: target },
28
+ });
29
+ }
30
+ return new Response(finalBody, { status: 200 });
31
+ });
32
+ }
33
+
9
34
  describe("msteams attachment allowlists", () => {
10
35
  it("normalizes wildcard host lists", () => {
11
36
  expect(resolveAllowedHosts(["*", "graph.microsoft.com"])).toEqual(["*"]);
12
37
  expect(resolveAuthAllowedHosts(["*", "graph.microsoft.com"])).toEqual(["*"]);
13
38
  });
14
39
 
40
+ it("resolves a normalized attachment fetch policy", () => {
41
+ expect(
42
+ resolveAttachmentFetchPolicy({
43
+ allowHosts: ["sharepoint.com"],
44
+ authAllowHosts: ["graph.microsoft.com"],
45
+ }),
46
+ ).toEqual({
47
+ allowHosts: ["sharepoint.com"],
48
+ authAllowHosts: ["graph.microsoft.com"],
49
+ });
50
+ });
51
+
15
52
  it("requires https and host suffix match", () => {
16
53
  const allowHosts = resolveAllowedHosts(["sharepoint.com"]);
17
54
  expect(isUrlAllowed("https://contoso.sharepoint.com/file.png", allowHosts)).toBe(true);
@@ -25,4 +62,317 @@ describe("msteams attachment allowlists", () => {
25
62
  });
26
63
  expect(resolveMediaSsrfPolicy(["*"])).toBeUndefined();
27
64
  });
65
+
66
+ it.each([
67
+ ["999.999.999.999", true],
68
+ ["256.0.0.1", true],
69
+ ["10.0.0.256", true],
70
+ ["-1.0.0.1", false],
71
+ ["1.2.3.4.5", false],
72
+ ["0:0:0:0:0:0:0:1", true],
73
+ ] as const)("malformed/expanded %s → %s (SDK fails closed)", (ip, expected) => {
74
+ expect(isPrivateOrReservedIP(ip)).toBe(expected);
75
+ });
76
+ });
77
+
78
+ // ─── resolveAndValidateIP ────────────────────────────────────────────────────
79
+
80
+ describe("resolveAndValidateIP", () => {
81
+ it("accepts a hostname resolving to a public IP", async () => {
82
+ const ip = await resolveAndValidateIP("teams.sharepoint.com", publicResolve);
83
+ expect(ip).toBe("13.107.136.10");
84
+ });
85
+
86
+ it("rejects a hostname resolving to 10.x.x.x", async () => {
87
+ await expect(resolveAndValidateIP("evil.test", privateResolve("10.0.0.1"))).rejects.toThrow(
88
+ "private/reserved IP",
89
+ );
90
+ });
91
+
92
+ it("rejects a hostname resolving to 169.254.169.254", async () => {
93
+ await expect(
94
+ resolveAndValidateIP("evil.test", privateResolve("169.254.169.254")),
95
+ ).rejects.toThrow("private/reserved IP");
96
+ });
97
+
98
+ it("rejects a hostname resolving to loopback", async () => {
99
+ await expect(resolveAndValidateIP("evil.test", privateResolve("127.0.0.1"))).rejects.toThrow(
100
+ "private/reserved IP",
101
+ );
102
+ });
103
+
104
+ it("rejects a hostname resolving to IPv6 loopback", async () => {
105
+ await expect(resolveAndValidateIP("evil.test", privateResolve("::1"))).rejects.toThrow(
106
+ "private/reserved IP",
107
+ );
108
+ });
109
+
110
+ it("throws on DNS resolution failure", async () => {
111
+ await expect(resolveAndValidateIP("nonexistent.test", failingResolve)).rejects.toThrow(
112
+ "DNS resolution failed",
113
+ );
114
+ });
115
+ });
116
+
117
+ // ─── safeFetch ───────────────────────────────────────────────────────────────
118
+
119
+ describe("safeFetch", () => {
120
+ it("fetches a URL directly when no redirect occurs", async () => {
121
+ const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => {
122
+ return new Response("ok", { status: 200 });
123
+ });
124
+ const res = await safeFetch({
125
+ url: "https://teams.sharepoint.com/file.pdf",
126
+ allowHosts: ["sharepoint.com"],
127
+ fetchFn: fetchMock as unknown as typeof fetch,
128
+ resolveFn: publicResolve,
129
+ });
130
+ expect(res.status).toBe(200);
131
+ expect(fetchMock).toHaveBeenCalledOnce();
132
+ // Should have used redirect: "manual"
133
+ expect(fetchMock.mock.calls[0][1]).toHaveProperty("redirect", "manual");
134
+ });
135
+
136
+ it("follows a redirect to an allowlisted host with public IP", async () => {
137
+ const fetchMock = mockFetchWithRedirect({
138
+ "https://teams.sharepoint.com/file.pdf": "https://cdn.sharepoint.com/storage/file.pdf",
139
+ });
140
+ const res = await safeFetch({
141
+ url: "https://teams.sharepoint.com/file.pdf",
142
+ allowHosts: ["sharepoint.com"],
143
+ fetchFn: fetchMock as unknown as typeof fetch,
144
+ resolveFn: publicResolve,
145
+ });
146
+ expect(res.status).toBe(200);
147
+ expect(fetchMock).toHaveBeenCalledTimes(2);
148
+ });
149
+
150
+ it("returns the redirect response when dispatcher is provided by an outer guard", async () => {
151
+ const redirectedTo = "https://cdn.sharepoint.com/storage/file.pdf";
152
+ const fetchMock = mockFetchWithRedirect({
153
+ "https://teams.sharepoint.com/file.pdf": redirectedTo,
154
+ });
155
+ const res = await safeFetch({
156
+ url: "https://teams.sharepoint.com/file.pdf",
157
+ allowHosts: ["sharepoint.com"],
158
+ fetchFn: fetchMock as unknown as typeof fetch,
159
+ requestInit: { dispatcher: {} } as RequestInit,
160
+ resolveFn: publicResolve,
161
+ });
162
+ expect(res.status).toBe(302);
163
+ expect(res.headers.get("location")).toBe(redirectedTo);
164
+ expect(fetchMock).toHaveBeenCalledOnce();
165
+ });
166
+
167
+ it("still enforces allowlist checks before returning dispatcher-mode redirects", async () => {
168
+ const fetchMock = mockFetchWithRedirect({
169
+ "https://teams.sharepoint.com/file.pdf": "https://evil.example.com/steal",
170
+ });
171
+ await expect(
172
+ safeFetch({
173
+ url: "https://teams.sharepoint.com/file.pdf",
174
+ allowHosts: ["sharepoint.com"],
175
+ fetchFn: fetchMock as unknown as typeof fetch,
176
+ requestInit: { dispatcher: {} } as RequestInit,
177
+ resolveFn: publicResolve,
178
+ }),
179
+ ).rejects.toThrow("blocked by allowlist");
180
+ expect(fetchMock).toHaveBeenCalledOnce();
181
+ });
182
+
183
+ it("blocks a redirect to a non-allowlisted host", async () => {
184
+ const fetchMock = mockFetchWithRedirect({
185
+ "https://teams.sharepoint.com/file.pdf": "https://evil.example.com/steal",
186
+ });
187
+ await expect(
188
+ safeFetch({
189
+ url: "https://teams.sharepoint.com/file.pdf",
190
+ allowHosts: ["sharepoint.com"],
191
+ fetchFn: fetchMock as unknown as typeof fetch,
192
+ resolveFn: publicResolve,
193
+ }),
194
+ ).rejects.toThrow("blocked by allowlist");
195
+ // Should not have fetched the evil URL
196
+ expect(fetchMock).toHaveBeenCalledTimes(1);
197
+ });
198
+
199
+ it("blocks a redirect to an allowlisted host that resolves to a private IP (DNS rebinding)", async () => {
200
+ let callCount = 0;
201
+ const rebindingResolve = async () => {
202
+ callCount++;
203
+ // First call (initial URL) resolves to public IP
204
+ if (callCount === 1) return { address: "13.107.136.10" };
205
+ // Second call (redirect target) resolves to private IP
206
+ return { address: "169.254.169.254" };
207
+ };
208
+
209
+ const fetchMock = mockFetchWithRedirect({
210
+ "https://teams.sharepoint.com/file.pdf": "https://evil.trafficmanager.net/metadata",
211
+ });
212
+ await expect(
213
+ safeFetch({
214
+ url: "https://teams.sharepoint.com/file.pdf",
215
+ allowHosts: ["sharepoint.com", "trafficmanager.net"],
216
+ fetchFn: fetchMock as unknown as typeof fetch,
217
+ resolveFn: rebindingResolve,
218
+ }),
219
+ ).rejects.toThrow("private/reserved IP");
220
+ expect(fetchMock).toHaveBeenCalledTimes(1);
221
+ });
222
+
223
+ it("blocks when the initial URL resolves to a private IP", async () => {
224
+ const fetchMock = vi.fn();
225
+ await expect(
226
+ safeFetch({
227
+ url: "https://evil.sharepoint.com/file.pdf",
228
+ allowHosts: ["sharepoint.com"],
229
+ fetchFn: fetchMock as unknown as typeof fetch,
230
+ resolveFn: privateResolve("10.0.0.1"),
231
+ }),
232
+ ).rejects.toThrow("Initial download URL blocked");
233
+ expect(fetchMock).not.toHaveBeenCalled();
234
+ });
235
+
236
+ it("blocks when initial URL DNS resolution fails", async () => {
237
+ const fetchMock = vi.fn();
238
+ await expect(
239
+ safeFetch({
240
+ url: "https://nonexistent.sharepoint.com/file.pdf",
241
+ allowHosts: ["sharepoint.com"],
242
+ fetchFn: fetchMock as unknown as typeof fetch,
243
+ resolveFn: failingResolve,
244
+ }),
245
+ ).rejects.toThrow("Initial download URL blocked");
246
+ expect(fetchMock).not.toHaveBeenCalled();
247
+ });
248
+
249
+ it("follows multiple redirects when all are valid", async () => {
250
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
251
+ if (url === "https://a.sharepoint.com/1" && init?.redirect === "manual") {
252
+ return new Response(null, {
253
+ status: 302,
254
+ headers: { location: "https://b.sharepoint.com/2" },
255
+ });
256
+ }
257
+ if (url === "https://b.sharepoint.com/2" && init?.redirect === "manual") {
258
+ return new Response(null, {
259
+ status: 302,
260
+ headers: { location: "https://c.sharepoint.com/3" },
261
+ });
262
+ }
263
+ return new Response("final", { status: 200 });
264
+ });
265
+
266
+ const res = await safeFetch({
267
+ url: "https://a.sharepoint.com/1",
268
+ allowHosts: ["sharepoint.com"],
269
+ fetchFn: fetchMock as unknown as typeof fetch,
270
+ resolveFn: publicResolve,
271
+ });
272
+ expect(res.status).toBe(200);
273
+ expect(fetchMock).toHaveBeenCalledTimes(3);
274
+ });
275
+
276
+ it("throws on too many redirects", async () => {
277
+ let counter = 0;
278
+ const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
279
+ if (init?.redirect === "manual") {
280
+ counter++;
281
+ return new Response(null, {
282
+ status: 302,
283
+ headers: { location: `https://loop${counter}.sharepoint.com/x` },
284
+ });
285
+ }
286
+ return new Response("ok", { status: 200 });
287
+ });
288
+
289
+ await expect(
290
+ safeFetch({
291
+ url: "https://start.sharepoint.com/x",
292
+ allowHosts: ["sharepoint.com"],
293
+ fetchFn: fetchMock as unknown as typeof fetch,
294
+ resolveFn: publicResolve,
295
+ }),
296
+ ).rejects.toThrow("Too many redirects");
297
+ });
298
+
299
+ it("blocks redirect to HTTP (non-HTTPS)", async () => {
300
+ const fetchMock = mockFetchWithRedirect({
301
+ "https://teams.sharepoint.com/file": "http://internal.sharepoint.com/file",
302
+ });
303
+ await expect(
304
+ safeFetch({
305
+ url: "https://teams.sharepoint.com/file",
306
+ allowHosts: ["sharepoint.com"],
307
+ fetchFn: fetchMock as unknown as typeof fetch,
308
+ resolveFn: publicResolve,
309
+ }),
310
+ ).rejects.toThrow("blocked by allowlist");
311
+ });
312
+
313
+ it("strips authorization across redirects outside auth allowlist", async () => {
314
+ const seenAuth: string[] = [];
315
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
316
+ const auth = new Headers(init?.headers).get("authorization") ?? "";
317
+ seenAuth.push(`${url}|${auth}`);
318
+ if (url === "https://teams.sharepoint.com/file.pdf") {
319
+ return new Response(null, {
320
+ status: 302,
321
+ headers: { location: "https://cdn.sharepoint.com/storage/file.pdf" },
322
+ });
323
+ }
324
+ return new Response("ok", { status: 200 });
325
+ });
326
+
327
+ const headers = new Headers({ Authorization: "Bearer secret" });
328
+ const res = await safeFetch({
329
+ url: "https://teams.sharepoint.com/file.pdf",
330
+ allowHosts: ["sharepoint.com"],
331
+ authorizationAllowHosts: ["graph.microsoft.com"],
332
+ fetchFn: fetchMock as unknown as typeof fetch,
333
+ requestInit: { headers },
334
+ resolveFn: publicResolve,
335
+ });
336
+ expect(res.status).toBe(200);
337
+ expect(seenAuth[0]).toContain("Bearer secret");
338
+ expect(seenAuth[1]).toMatch(/\|$/);
339
+ });
340
+ });
341
+
342
+ describe("attachment fetch auth helpers", () => {
343
+ it("sets and clears authorization header by auth allowlist", () => {
344
+ const headers = new Headers();
345
+ applyAuthorizationHeaderForUrl({
346
+ headers,
347
+ url: "https://graph.microsoft.com/v1.0/me",
348
+ authAllowHosts: ["graph.microsoft.com"],
349
+ bearerToken: "token-1",
350
+ });
351
+ expect(headers.get("authorization")).toBe("Bearer token-1");
352
+
353
+ applyAuthorizationHeaderForUrl({
354
+ headers,
355
+ url: "https://evil.example.com/collect",
356
+ authAllowHosts: ["graph.microsoft.com"],
357
+ bearerToken: "token-1",
358
+ });
359
+ expect(headers.get("authorization")).toBeNull();
360
+ });
361
+
362
+ it("safeFetchWithPolicy forwards policy allowlists", async () => {
363
+ const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => {
364
+ return new Response("ok", { status: 200 });
365
+ });
366
+ const res = await safeFetchWithPolicy({
367
+ url: "https://teams.sharepoint.com/file.pdf",
368
+ policy: resolveAttachmentFetchPolicy({
369
+ allowHosts: ["sharepoint.com"],
370
+ authAllowHosts: ["graph.microsoft.com"],
371
+ }),
372
+ fetchFn: fetchMock as unknown as typeof fetch,
373
+ resolveFn: publicResolve,
374
+ });
375
+ expect(res.status).toBe(200);
376
+ expect(fetchMock).toHaveBeenCalledOnce();
377
+ });
28
378
  });