@openclaw/msteams 2026.3.13 → 2026.5.1-beta.1

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 (175) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +2 -0
  4. package/config-api.ts +4 -0
  5. package/contract-api.ts +4 -0
  6. package/index.ts +15 -12
  7. package/openclaw.plugin.json +553 -1
  8. package/package.json +46 -12
  9. package/runtime-api.ts +73 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.test.ts +461 -0
  16. package/src/attachments/bot-framework.ts +362 -0
  17. package/src/attachments/download.ts +63 -19
  18. package/src/attachments/graph.test.ts +416 -0
  19. package/src/attachments/graph.ts +163 -72
  20. package/src/attachments/html.ts +33 -1
  21. package/src/attachments/payload.ts +1 -1
  22. package/src/attachments/remote-media.test.ts +137 -0
  23. package/src/attachments/remote-media.ts +75 -8
  24. package/src/attachments/shared.test.ts +138 -1
  25. package/src/attachments/shared.ts +193 -26
  26. package/src/attachments/types.ts +10 -0
  27. package/src/attachments.graph.test.ts +342 -0
  28. package/src/attachments.helpers.test.ts +246 -0
  29. package/src/attachments.test-helpers.ts +17 -0
  30. package/src/attachments.test.ts +163 -418
  31. package/src/attachments.ts +5 -5
  32. package/src/block-streaming-config.test.ts +61 -0
  33. package/src/channel-api.ts +1 -0
  34. package/src/channel.actions.test.ts +742 -0
  35. package/src/channel.directory.test.ts +145 -4
  36. package/src/channel.runtime.ts +56 -0
  37. package/src/channel.setup.ts +77 -0
  38. package/src/channel.test.ts +128 -0
  39. package/src/channel.ts +1077 -395
  40. package/src/config-schema.ts +6 -0
  41. package/src/config-ui-hints.ts +12 -0
  42. package/src/conversation-store-fs.test.ts +4 -5
  43. package/src/conversation-store-fs.ts +35 -51
  44. package/src/conversation-store-helpers.test.ts +202 -0
  45. package/src/conversation-store-helpers.ts +105 -0
  46. package/src/conversation-store-memory.ts +27 -23
  47. package/src/conversation-store.shared.test.ts +225 -0
  48. package/src/conversation-store.ts +30 -0
  49. package/src/directory-live.test.ts +156 -0
  50. package/src/directory-live.ts +7 -4
  51. package/src/doctor.ts +27 -0
  52. package/src/errors.test.ts +64 -1
  53. package/src/errors.ts +50 -9
  54. package/src/feedback-reflection-prompt.ts +117 -0
  55. package/src/feedback-reflection-store.ts +114 -0
  56. package/src/feedback-reflection.test.ts +237 -0
  57. package/src/feedback-reflection.ts +283 -0
  58. package/src/file-consent-helpers.test.ts +83 -0
  59. package/src/file-consent-helpers.ts +64 -11
  60. package/src/file-consent-invoke.ts +150 -0
  61. package/src/file-consent.test.ts +363 -0
  62. package/src/file-consent.ts +165 -4
  63. package/src/graph-chat.ts +5 -3
  64. package/src/graph-group-management.test.ts +318 -0
  65. package/src/graph-group-management.ts +168 -0
  66. package/src/graph-members.test.ts +89 -0
  67. package/src/graph-members.ts +48 -0
  68. package/src/graph-messages.actions.test.ts +243 -0
  69. package/src/graph-messages.read.test.ts +391 -0
  70. package/src/graph-messages.search.test.ts +213 -0
  71. package/src/graph-messages.test-helpers.ts +50 -0
  72. package/src/graph-messages.ts +534 -0
  73. package/src/graph-teams.test.ts +215 -0
  74. package/src/graph-teams.ts +114 -0
  75. package/src/graph-thread.test.ts +246 -0
  76. package/src/graph-thread.ts +146 -0
  77. package/src/graph-upload.test.ts +161 -4
  78. package/src/graph-upload.ts +147 -56
  79. package/src/graph.test.ts +516 -0
  80. package/src/graph.ts +233 -21
  81. package/src/inbound.test.ts +156 -1
  82. package/src/inbound.ts +101 -1
  83. package/src/media-helpers.ts +1 -1
  84. package/src/mentions.test.ts +27 -18
  85. package/src/mentions.ts +2 -2
  86. package/src/messenger.test.ts +504 -23
  87. package/src/messenger.ts +133 -52
  88. package/src/monitor-handler/access.ts +125 -0
  89. package/src/monitor-handler/inbound-media.test.ts +289 -0
  90. package/src/monitor-handler/inbound-media.ts +57 -5
  91. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  92. package/src/monitor-handler/message-handler.authz.test.ts +588 -74
  93. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  94. package/src/monitor-handler/message-handler.test-support.ts +100 -0
  95. package/src/monitor-handler/message-handler.thread-parent.test.ts +223 -0
  96. package/src/monitor-handler/message-handler.thread-session.test.ts +77 -0
  97. package/src/monitor-handler/message-handler.ts +470 -164
  98. package/src/monitor-handler/reaction-handler.test.ts +267 -0
  99. package/src/monitor-handler/reaction-handler.ts +210 -0
  100. package/src/monitor-handler/thread-session.ts +17 -0
  101. package/src/monitor-handler.adaptive-card.test.ts +162 -0
  102. package/src/monitor-handler.feedback-authz.test.ts +314 -0
  103. package/src/monitor-handler.file-consent.test.ts +281 -79
  104. package/src/monitor-handler.sso.test.ts +563 -0
  105. package/src/monitor-handler.test-helpers.ts +180 -0
  106. package/src/monitor-handler.ts +459 -115
  107. package/src/monitor-handler.types.ts +27 -0
  108. package/src/monitor-types.ts +1 -0
  109. package/src/monitor.lifecycle.test.ts +74 -10
  110. package/src/monitor.test.ts +35 -1
  111. package/src/monitor.ts +143 -46
  112. package/src/oauth.flow.ts +77 -0
  113. package/src/oauth.shared.ts +37 -0
  114. package/src/oauth.test.ts +305 -0
  115. package/src/oauth.token.ts +158 -0
  116. package/src/oauth.ts +130 -0
  117. package/src/outbound.test.ts +10 -11
  118. package/src/outbound.ts +62 -44
  119. package/src/pending-uploads-fs.test.ts +246 -0
  120. package/src/pending-uploads-fs.ts +235 -0
  121. package/src/pending-uploads.test.ts +173 -0
  122. package/src/pending-uploads.ts +34 -2
  123. package/src/policy.test.ts +11 -5
  124. package/src/policy.ts +5 -5
  125. package/src/polls.test.ts +106 -5
  126. package/src/polls.ts +15 -7
  127. package/src/presentation.ts +68 -0
  128. package/src/probe.test.ts +27 -8
  129. package/src/probe.ts +43 -9
  130. package/src/reply-dispatcher.test.ts +437 -0
  131. package/src/reply-dispatcher.ts +259 -73
  132. package/src/reply-stream-controller.test.ts +235 -0
  133. package/src/reply-stream-controller.ts +147 -0
  134. package/src/resolve-allowlist.test.ts +105 -1
  135. package/src/resolve-allowlist.ts +112 -7
  136. package/src/runtime.ts +6 -3
  137. package/src/sdk-types.ts +43 -3
  138. package/src/sdk.test.ts +666 -0
  139. package/src/sdk.ts +867 -16
  140. package/src/secret-contract.ts +49 -0
  141. package/src/secret-input.ts +1 -1
  142. package/src/send-context.ts +76 -9
  143. package/src/send.test.ts +389 -5
  144. package/src/send.ts +140 -32
  145. package/src/sent-message-cache.ts +30 -18
  146. package/src/session-route.ts +40 -0
  147. package/src/setup-core.ts +160 -0
  148. package/src/setup-surface.test.ts +202 -0
  149. package/src/setup-surface.ts +320 -0
  150. package/src/sso-token-store.test.ts +72 -0
  151. package/src/sso-token-store.ts +166 -0
  152. package/src/sso.ts +300 -0
  153. package/src/storage.ts +1 -1
  154. package/src/store-fs.ts +2 -2
  155. package/src/streaming-message.test.ts +262 -0
  156. package/src/streaming-message.ts +297 -0
  157. package/src/test-runtime.ts +1 -1
  158. package/src/thread-parent-context.test.ts +224 -0
  159. package/src/thread-parent-context.ts +159 -0
  160. package/src/token.test.ts +237 -50
  161. package/src/token.ts +162 -7
  162. package/src/user-agent.test.ts +86 -0
  163. package/src/user-agent.ts +53 -0
  164. package/src/webhook-timeouts.ts +27 -0
  165. package/src/welcome-card.test.ts +81 -0
  166. package/src/welcome-card.ts +57 -0
  167. package/test-api.ts +1 -0
  168. package/tsconfig.json +16 -0
  169. package/CHANGELOG.md +0 -107
  170. package/src/file-lock.ts +0 -1
  171. package/src/graph-users.test.ts +0 -66
  172. package/src/onboarding.ts +0 -381
  173. package/src/polls-store.test.ts +0 -38
  174. package/src/revoked-context.test.ts +0 -39
  175. package/src/token-response.test.ts +0 -23
@@ -0,0 +1,166 @@
1
+ /**
2
+ * File-backed store for Bot Framework OAuth SSO tokens.
3
+ *
4
+ * Tokens are keyed by (connectionName, userId). `userId` should be the
5
+ * stable AAD object ID (`activity.from.aadObjectId`) when available,
6
+ * falling back to the Bot Framework `activity.from.id`.
7
+ *
8
+ * The store is intentionally minimal: it persists the exchanged user
9
+ * token plus its expiration so consumers (for example tool handlers
10
+ * that call Microsoft Graph with delegated permissions) can fetch a
11
+ * valid token without reaching back into Bot Framework every turn.
12
+ */
13
+
14
+ import { resolveMSTeamsStorePath } from "./storage.js";
15
+ import { readJsonFile, withFileLock, writeJsonFile } from "./store-fs.js";
16
+
17
+ type MSTeamsSsoStoredToken = {
18
+ /** Connection name from the Bot Framework OAuth connection setting. */
19
+ connectionName: string;
20
+ /** Stable user identifier (AAD object ID preferred). */
21
+ userId: string;
22
+ /** Exchanged user access token. */
23
+ token: string;
24
+ /** Expiration (ISO 8601) when the Bot Framework user token service reports one. */
25
+ expiresAt?: string;
26
+ /** ISO 8601 timestamp for the last successful exchange. */
27
+ updatedAt: string;
28
+ };
29
+
30
+ export type MSTeamsSsoTokenStore = {
31
+ get(params: { connectionName: string; userId: string }): Promise<MSTeamsSsoStoredToken | null>;
32
+ save(token: MSTeamsSsoStoredToken): Promise<void>;
33
+ remove(params: { connectionName: string; userId: string }): Promise<boolean>;
34
+ };
35
+
36
+ type SsoStoreData = {
37
+ version: 1;
38
+ // Keyed by `${connectionName}::${userId}` for a simple flat map on disk.
39
+ tokens: Record<string, MSTeamsSsoStoredToken>;
40
+ };
41
+
42
+ const STORE_FILENAME = "msteams-sso-tokens.json";
43
+ const STORE_KEY_VERSION_PREFIX = "v2:";
44
+
45
+ function makeKey(connectionName: string, userId: string): string {
46
+ return `${STORE_KEY_VERSION_PREFIX}${Buffer.from(
47
+ JSON.stringify([connectionName, userId]),
48
+ "utf8",
49
+ ).toString("base64url")}`;
50
+ }
51
+
52
+ function normalizeStoredToken(value: unknown): MSTeamsSsoStoredToken | null {
53
+ if (!value || typeof value !== "object") {
54
+ return null;
55
+ }
56
+ const token = value as Partial<MSTeamsSsoStoredToken>;
57
+ if (
58
+ typeof token.connectionName !== "string" ||
59
+ !token.connectionName ||
60
+ typeof token.userId !== "string" ||
61
+ !token.userId ||
62
+ typeof token.token !== "string" ||
63
+ !token.token ||
64
+ typeof token.updatedAt !== "string" ||
65
+ !token.updatedAt
66
+ ) {
67
+ return null;
68
+ }
69
+ return {
70
+ connectionName: token.connectionName,
71
+ userId: token.userId,
72
+ token: token.token,
73
+ ...(typeof token.expiresAt === "string" ? { expiresAt: token.expiresAt } : {}),
74
+ updatedAt: token.updatedAt,
75
+ };
76
+ }
77
+
78
+ function isSsoStoreData(value: unknown): value is SsoStoreData {
79
+ if (!value || typeof value !== "object") {
80
+ return false;
81
+ }
82
+ const obj = value as Record<string, unknown>;
83
+ return obj.version === 1 && typeof obj.tokens === "object" && obj.tokens !== null;
84
+ }
85
+
86
+ export function createMSTeamsSsoTokenStoreFs(params?: {
87
+ env?: NodeJS.ProcessEnv;
88
+ homedir?: () => string;
89
+ stateDir?: string;
90
+ storePath?: string;
91
+ }): MSTeamsSsoTokenStore {
92
+ const filePath = resolveMSTeamsStorePath({
93
+ filename: STORE_FILENAME,
94
+ env: params?.env,
95
+ homedir: params?.homedir,
96
+ stateDir: params?.stateDir,
97
+ storePath: params?.storePath,
98
+ });
99
+
100
+ const empty: SsoStoreData = { version: 1, tokens: {} };
101
+
102
+ const readStore = async (): Promise<SsoStoreData> => {
103
+ const { value } = await readJsonFile(filePath, empty);
104
+ if (!isSsoStoreData(value)) {
105
+ return { version: 1, tokens: {} };
106
+ }
107
+ const tokens: Record<string, MSTeamsSsoStoredToken> = {};
108
+ for (const stored of Object.values(value.tokens)) {
109
+ const normalized = normalizeStoredToken(stored);
110
+ if (!normalized) {
111
+ continue;
112
+ }
113
+ tokens[makeKey(normalized.connectionName, normalized.userId)] = normalized;
114
+ }
115
+ return {
116
+ version: 1,
117
+ tokens,
118
+ };
119
+ };
120
+
121
+ return {
122
+ async get({ connectionName, userId }) {
123
+ const store = await readStore();
124
+ return store.tokens[makeKey(connectionName, userId)] ?? null;
125
+ },
126
+
127
+ async save(token) {
128
+ await withFileLock(filePath, empty, async () => {
129
+ const store = await readStore();
130
+ const key = makeKey(token.connectionName, token.userId);
131
+ store.tokens[key] = { ...token };
132
+ await writeJsonFile(filePath, store);
133
+ });
134
+ },
135
+
136
+ async remove({ connectionName, userId }) {
137
+ let removed = false;
138
+ await withFileLock(filePath, empty, async () => {
139
+ const store = await readStore();
140
+ const key = makeKey(connectionName, userId);
141
+ if (store.tokens[key]) {
142
+ delete store.tokens[key];
143
+ removed = true;
144
+ await writeJsonFile(filePath, store);
145
+ }
146
+ });
147
+ return removed;
148
+ },
149
+ };
150
+ }
151
+
152
+ /** In-memory store, primarily useful for tests. */
153
+ export function createMSTeamsSsoTokenStoreMemory(): MSTeamsSsoTokenStore {
154
+ const tokens = new Map<string, MSTeamsSsoStoredToken>();
155
+ return {
156
+ async get({ connectionName, userId }) {
157
+ return tokens.get(makeKey(connectionName, userId)) ?? null;
158
+ },
159
+ async save(token) {
160
+ tokens.set(makeKey(token.connectionName, token.userId), { ...token });
161
+ },
162
+ async remove({ connectionName, userId }) {
163
+ return tokens.delete(makeKey(connectionName, userId));
164
+ },
165
+ };
166
+ }
package/src/sso.ts ADDED
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Bot Framework OAuth SSO invoke handlers for Microsoft Teams.
3
+ *
4
+ * Handles two invoke activities Teams sends when the bot has presented
5
+ * an `oauthCard` or when the user completes an interactive sign-in:
6
+ *
7
+ * 1. `signin/tokenExchange`
8
+ * The Teams client obtained an exchangeable token from the bot's
9
+ * AAD app and forwards it to the bot. The bot exchanges that token
10
+ * with the Bot Framework User Token service, which returns the real
11
+ * delegated user token (for example, a Microsoft Graph access token
12
+ * if the OAuth connection is set up for Graph).
13
+ *
14
+ * 2. `signin/verifyState`
15
+ * Fallback for the magic-code flow: the user finishes sign-in in a
16
+ * browser tab, receives a 6-digit code, and pastes it back into the
17
+ * chat. The bot then asks the User Token service for the token
18
+ * corresponding to that code.
19
+ *
20
+ * In both cases the bot must reply with an `invokeResponse` (HTTP 200)
21
+ * immediately or the Teams UI shows "Something went wrong". Callers of
22
+ * {@link handleSigninTokenExchangeInvoke} and
23
+ * {@link handleSigninVerifyStateInvoke} are responsible for sending
24
+ * that ack; these helpers encapsulate token exchange and persistence.
25
+ */
26
+
27
+ import type { MSTeamsAccessTokenProvider } from "./attachments/types.js";
28
+ import type { MSTeamsSsoTokenStore } from "./sso-token-store.js";
29
+ import { buildUserAgent } from "./user-agent.js";
30
+
31
+ /** Scope used to obtain a Bot Framework service token. */
32
+ const BOT_FRAMEWORK_TOKEN_SCOPE = "https://api.botframework.com/.default";
33
+
34
+ /** Bot Framework User Token service base URL. */
35
+ const BOT_FRAMEWORK_USER_TOKEN_BASE_URL = "https://token.botframework.com";
36
+
37
+ /**
38
+ * Response shape returned by the Bot Framework User Token service for
39
+ * `GetUserToken` and `ExchangeToken`.
40
+ *
41
+ * @see https://learn.microsoft.com/azure/bot-service/rest-api/bot-framework-rest-connector-user-token-service
42
+ */
43
+ type BotFrameworkUserTokenResponse = {
44
+ channelId?: string;
45
+ connectionName: string;
46
+ token: string;
47
+ expiration?: string;
48
+ };
49
+
50
+ export type MSTeamsSsoFetch = (
51
+ input: string,
52
+ init?: {
53
+ method?: string;
54
+ headers?: Record<string, string>;
55
+ body?: string;
56
+ },
57
+ ) => Promise<{
58
+ ok: boolean;
59
+ status: number;
60
+ json(): Promise<unknown>;
61
+ text(): Promise<string>;
62
+ }>;
63
+
64
+ export type MSTeamsSsoDeps = {
65
+ tokenProvider: MSTeamsAccessTokenProvider;
66
+ tokenStore: MSTeamsSsoTokenStore;
67
+ connectionName: string;
68
+ /** Override `fetch` for testing. */
69
+ fetchImpl?: MSTeamsSsoFetch;
70
+ /** Override the User Token service base URL (testing / sovereign clouds). */
71
+ userTokenBaseUrl?: string;
72
+ };
73
+
74
+ type MSTeamsSsoUser = {
75
+ /** Stable user identifier — AAD object ID when available. */
76
+ userId: string;
77
+ /** Bot Framework channel ID (default: "msteams"). */
78
+ channelId?: string;
79
+ };
80
+
81
+ type MSTeamsSsoResult =
82
+ | {
83
+ ok: true;
84
+ token: string;
85
+ expiresAt?: string;
86
+ }
87
+ | {
88
+ ok: false;
89
+ code:
90
+ | "missing_user"
91
+ | "missing_connection"
92
+ | "missing_token"
93
+ | "missing_state"
94
+ | "service_error"
95
+ | "unexpected_response";
96
+ message: string;
97
+ status?: number;
98
+ };
99
+
100
+ type SigninTokenExchangeValue = {
101
+ id?: string;
102
+ connectionName?: string;
103
+ token?: string;
104
+ };
105
+
106
+ type SigninVerifyStateValue = {
107
+ state?: string;
108
+ };
109
+
110
+ /**
111
+ * Extract and validate the `signin/tokenExchange` activity value. Teams
112
+ * delivers `{ id, connectionName, token }`; any field may be missing on
113
+ * malformed invocations, so callers should check the parsed result.
114
+ */
115
+ export function parseSigninTokenExchangeValue(value: unknown): SigninTokenExchangeValue | null {
116
+ if (!value || typeof value !== "object") {
117
+ return null;
118
+ }
119
+ const obj = value as Record<string, unknown>;
120
+ const id = typeof obj.id === "string" ? obj.id : undefined;
121
+ const connectionName = typeof obj.connectionName === "string" ? obj.connectionName : undefined;
122
+ const token = typeof obj.token === "string" ? obj.token : undefined;
123
+ return { id, connectionName, token };
124
+ }
125
+
126
+ /** Extract the `signin/verifyState` activity value `{ state }`. */
127
+ export function parseSigninVerifyStateValue(value: unknown): SigninVerifyStateValue | null {
128
+ if (!value || typeof value !== "object") {
129
+ return null;
130
+ }
131
+ const obj = value as Record<string, unknown>;
132
+ const state = typeof obj.state === "string" ? obj.state : undefined;
133
+ return { state };
134
+ }
135
+
136
+ type UserTokenServiceCallParams = {
137
+ baseUrl: string;
138
+ path: string;
139
+ query: Record<string, string>;
140
+ method: "GET" | "POST";
141
+ body?: unknown;
142
+ bearerToken: string;
143
+ fetchImpl: MSTeamsSsoFetch;
144
+ };
145
+
146
+ async function callUserTokenService(
147
+ params: UserTokenServiceCallParams,
148
+ ): Promise<BotFrameworkUserTokenResponse | { error: string; status: number }> {
149
+ const qs = new URLSearchParams(params.query).toString();
150
+ const url = `${params.baseUrl.replace(/\/+$/, "")}${params.path}?${qs}`;
151
+ const headers: Record<string, string> = {
152
+ Accept: "application/json",
153
+ Authorization: `Bearer ${params.bearerToken}`,
154
+ "User-Agent": buildUserAgent(),
155
+ };
156
+ if (params.body !== undefined) {
157
+ headers["Content-Type"] = "application/json";
158
+ }
159
+ const response = await params.fetchImpl(url, {
160
+ method: params.method,
161
+ headers,
162
+ body: params.body === undefined ? undefined : JSON.stringify(params.body),
163
+ });
164
+ if (!response.ok) {
165
+ const text = await response.text().catch(() => "");
166
+ return { error: text || `HTTP ${response.status}`, status: response.status };
167
+ }
168
+ let parsed: unknown;
169
+ try {
170
+ parsed = await response.json();
171
+ } catch {
172
+ return { error: "invalid JSON from User Token service", status: response.status };
173
+ }
174
+ if (!parsed || typeof parsed !== "object") {
175
+ return { error: "empty response from User Token service", status: response.status };
176
+ }
177
+ const obj = parsed as Record<string, unknown>;
178
+ const token = typeof obj.token === "string" ? obj.token : undefined;
179
+ const connectionName = typeof obj.connectionName === "string" ? obj.connectionName : undefined;
180
+ const channelId = typeof obj.channelId === "string" ? obj.channelId : undefined;
181
+ const expiration = typeof obj.expiration === "string" ? obj.expiration : undefined;
182
+ if (!token || !connectionName) {
183
+ return { error: "User Token service response missing token/connectionName", status: 502 };
184
+ }
185
+ return { channelId, connectionName, token, expiration };
186
+ }
187
+
188
+ /**
189
+ * Exchange a Teams SSO token for a delegated user token via Bot
190
+ * Framework's User Token service, then persist the result.
191
+ */
192
+ export async function handleSigninTokenExchangeInvoke(params: {
193
+ value: SigninTokenExchangeValue;
194
+ user: MSTeamsSsoUser;
195
+ deps: MSTeamsSsoDeps;
196
+ }): Promise<MSTeamsSsoResult> {
197
+ const { value, user, deps } = params;
198
+ if (!user.userId) {
199
+ return { ok: false, code: "missing_user", message: "no user id on invoke activity" };
200
+ }
201
+ const connectionName = value.connectionName?.trim() || deps.connectionName;
202
+ if (!connectionName) {
203
+ return { ok: false, code: "missing_connection", message: "no OAuth connection name" };
204
+ }
205
+ if (!value.token) {
206
+ return { ok: false, code: "missing_token", message: "no exchangeable token on invoke" };
207
+ }
208
+
209
+ const bearer = await deps.tokenProvider.getAccessToken(BOT_FRAMEWORK_TOKEN_SCOPE);
210
+ const fetchImpl = deps.fetchImpl ?? (globalThis.fetch as unknown as MSTeamsSsoFetch);
211
+ const result = await callUserTokenService({
212
+ baseUrl: deps.userTokenBaseUrl ?? BOT_FRAMEWORK_USER_TOKEN_BASE_URL,
213
+ path: "/api/usertoken/exchange",
214
+ query: {
215
+ userId: user.userId,
216
+ connectionName,
217
+ channelId: user.channelId ?? "msteams",
218
+ },
219
+ method: "POST",
220
+ body: { token: value.token },
221
+ bearerToken: bearer,
222
+ fetchImpl,
223
+ });
224
+
225
+ if ("error" in result) {
226
+ return {
227
+ ok: false,
228
+ code: result.status >= 500 ? "service_error" : "unexpected_response",
229
+ message: result.error,
230
+ status: result.status,
231
+ };
232
+ }
233
+
234
+ await deps.tokenStore.save({
235
+ connectionName,
236
+ userId: user.userId,
237
+ token: result.token,
238
+ expiresAt: result.expiration,
239
+ updatedAt: new Date().toISOString(),
240
+ });
241
+
242
+ return { ok: true, token: result.token, expiresAt: result.expiration };
243
+ }
244
+
245
+ /**
246
+ * Finish a magic-code sign-in: look up the user token for the state
247
+ * code via Bot Framework's User Token service, then persist it.
248
+ */
249
+ export async function handleSigninVerifyStateInvoke(params: {
250
+ value: SigninVerifyStateValue;
251
+ user: MSTeamsSsoUser;
252
+ deps: MSTeamsSsoDeps;
253
+ }): Promise<MSTeamsSsoResult> {
254
+ const { value, user, deps } = params;
255
+ if (!user.userId) {
256
+ return { ok: false, code: "missing_user", message: "no user id on invoke activity" };
257
+ }
258
+ if (!deps.connectionName) {
259
+ return { ok: false, code: "missing_connection", message: "no OAuth connection name" };
260
+ }
261
+ const state = value.state?.trim();
262
+ if (!state) {
263
+ return { ok: false, code: "missing_state", message: "no state code on invoke" };
264
+ }
265
+
266
+ const bearer = await deps.tokenProvider.getAccessToken(BOT_FRAMEWORK_TOKEN_SCOPE);
267
+ const fetchImpl = deps.fetchImpl ?? (globalThis.fetch as unknown as MSTeamsSsoFetch);
268
+ const result = await callUserTokenService({
269
+ baseUrl: deps.userTokenBaseUrl ?? BOT_FRAMEWORK_USER_TOKEN_BASE_URL,
270
+ path: "/api/usertoken/GetToken",
271
+ query: {
272
+ userId: user.userId,
273
+ connectionName: deps.connectionName,
274
+ channelId: user.channelId ?? "msteams",
275
+ code: state,
276
+ },
277
+ method: "GET",
278
+ bearerToken: bearer,
279
+ fetchImpl,
280
+ });
281
+
282
+ if ("error" in result) {
283
+ return {
284
+ ok: false,
285
+ code: result.status >= 500 ? "service_error" : "unexpected_response",
286
+ message: result.error,
287
+ status: result.status,
288
+ };
289
+ }
290
+
291
+ await deps.tokenStore.save({
292
+ connectionName: deps.connectionName,
293
+ userId: user.userId,
294
+ token: result.token,
295
+ expiresAt: result.expiration,
296
+ updatedAt: new Date().toISOString(),
297
+ });
298
+
299
+ return { ok: true, token: result.token, expiresAt: result.expiration };
300
+ }
package/src/storage.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { getMSTeamsRuntime } from "./runtime.js";
3
3
 
4
- export type MSTeamsStorePathOptions = {
4
+ type MSTeamsStorePathOptions = {
5
5
  env?: NodeJS.ProcessEnv;
6
6
  homedir?: () => string;
7
7
  stateDir?: string;
package/src/store-fs.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
- import { readJsonFileWithFallback, writeJsonFileAtomically } from "openclaw/plugin-sdk/msteams";
3
- import { withFileLock as withPathLock } from "./file-lock.js";
2
+ import { withFileLock as withPathLock } from "openclaw/plugin-sdk/file-lock";
3
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "openclaw/plugin-sdk/json-store";
4
4
 
5
5
  const STORE_LOCK_OPTIONS = {
6
6
  retries: {