@openclaw/googlechat 2026.5.2-beta.2 → 2026.5.3-beta.2
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/dist/api-C67jv0ow.js +627 -0
- package/dist/api.js +3 -0
- package/dist/channel-DE2hroMn.js +682 -0
- package/dist/channel-config-api.js +5 -0
- package/dist/channel-plugin-api.js +2 -0
- package/dist/channel.runtime-CoSLc-4R.js +920 -0
- package/dist/contract-api.js +3 -0
- package/dist/doctor-contract-CG1sLToP.js +151 -0
- package/dist/doctor-contract-api.js +2 -0
- package/dist/index.js +22 -0
- package/dist/runtime-api-wkIdfwqY.js +30 -0
- package/dist/runtime-api.js +2 -0
- package/dist/secret-contract-DtQ_IO7J.js +99 -0
- package/dist/secret-contract-api.js +2 -0
- package/dist/setup-entry.js +15 -0
- package/dist/setup-plugin-api.js +75 -0
- package/dist/setup-surface-CofP-Gg9.js +309 -0
- package/dist/test-api.js +3 -0
- package/package.json +14 -6
- package/api.ts +0 -3
- package/channel-config-api.ts +0 -1
- package/channel-plugin-api.ts +0 -1
- package/contract-api.ts +0 -5
- package/doctor-contract-api.ts +0 -1
- package/index.ts +0 -20
- package/runtime-api.ts +0 -60
- package/secret-contract-api.ts +0 -5
- package/setup-entry.ts +0 -13
- package/setup-plugin-api.ts +0 -3
- package/src/accounts.ts +0 -169
- package/src/actions.test.ts +0 -265
- package/src/actions.ts +0 -227
- package/src/api.ts +0 -322
- package/src/approval-auth.test.ts +0 -24
- package/src/approval-auth.ts +0 -32
- package/src/auth.ts +0 -209
- package/src/channel-config.test.ts +0 -39
- package/src/channel.adapters.ts +0 -293
- package/src/channel.deps.runtime.ts +0 -28
- package/src/channel.runtime.ts +0 -17
- package/src/channel.setup.ts +0 -98
- package/src/channel.test.ts +0 -695
- package/src/channel.ts +0 -256
- package/src/config-schema.test.ts +0 -16
- package/src/config-schema.ts +0 -3
- package/src/doctor-contract.test.ts +0 -75
- package/src/doctor-contract.ts +0 -182
- package/src/doctor.ts +0 -57
- package/src/gateway.ts +0 -63
- package/src/google-auth.runtime.test.ts +0 -462
- package/src/google-auth.runtime.ts +0 -539
- package/src/group-policy.ts +0 -17
- package/src/monitor-access.test.ts +0 -443
- package/src/monitor-access.ts +0 -405
- package/src/monitor-reply-delivery.ts +0 -156
- package/src/monitor-routing.ts +0 -55
- package/src/monitor-types.ts +0 -33
- package/src/monitor-webhook.test.ts +0 -446
- package/src/monitor-webhook.ts +0 -285
- package/src/monitor.reply-delivery.test.ts +0 -139
- package/src/monitor.ts +0 -428
- package/src/monitor.webhook-routing.test.ts +0 -252
- package/src/runtime.ts +0 -9
- package/src/secret-contract.test.ts +0 -60
- package/src/secret-contract.ts +0 -161
- package/src/sender-allow.ts +0 -46
- package/src/setup-core.ts +0 -40
- package/src/setup-surface.ts +0 -236
- package/src/setup.test.ts +0 -560
- package/src/targets.test.ts +0 -421
- package/src/targets.ts +0 -66
- package/src/types.config.ts +0 -3
- package/src/types.ts +0 -73
- package/test-api.ts +0 -2
- package/tsconfig.json +0 -16
package/src/api.ts
DELETED
|
@@ -1,322 +0,0 @@
|
|
|
1
|
-
import crypto from "node:crypto";
|
|
2
|
-
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
3
|
-
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
4
|
-
import type { ResolvedGoogleChatAccount } from "./accounts.js";
|
|
5
|
-
import { getGoogleChatAccessToken } from "./auth.js";
|
|
6
|
-
import type { GoogleChatReaction } from "./types.js";
|
|
7
|
-
|
|
8
|
-
const CHAT_API_BASE = "https://chat.googleapis.com/v1";
|
|
9
|
-
const CHAT_UPLOAD_BASE = "https://chat.googleapis.com/upload/v1";
|
|
10
|
-
|
|
11
|
-
const headersToObject = (headers?: HeadersInit): Record<string, string> =>
|
|
12
|
-
headers instanceof Headers
|
|
13
|
-
? Object.fromEntries(headers.entries())
|
|
14
|
-
: Array.isArray(headers)
|
|
15
|
-
? Object.fromEntries(headers)
|
|
16
|
-
: headers || {};
|
|
17
|
-
|
|
18
|
-
async function withGoogleChatResponse<T>(params: {
|
|
19
|
-
account: ResolvedGoogleChatAccount;
|
|
20
|
-
url: string;
|
|
21
|
-
init?: RequestInit;
|
|
22
|
-
auditContext: string;
|
|
23
|
-
errorPrefix?: string;
|
|
24
|
-
handleResponse: (response: Response) => Promise<T>;
|
|
25
|
-
}): Promise<T> {
|
|
26
|
-
const {
|
|
27
|
-
account,
|
|
28
|
-
url,
|
|
29
|
-
init,
|
|
30
|
-
auditContext,
|
|
31
|
-
errorPrefix = "Google Chat API",
|
|
32
|
-
handleResponse,
|
|
33
|
-
} = params;
|
|
34
|
-
const token = await getGoogleChatAccessToken(account);
|
|
35
|
-
const { response, release } = await fetchWithSsrFGuard({
|
|
36
|
-
url,
|
|
37
|
-
init: {
|
|
38
|
-
...init,
|
|
39
|
-
headers: {
|
|
40
|
-
...headersToObject(init?.headers),
|
|
41
|
-
Authorization: `Bearer ${token}`,
|
|
42
|
-
},
|
|
43
|
-
},
|
|
44
|
-
auditContext,
|
|
45
|
-
});
|
|
46
|
-
try {
|
|
47
|
-
if (!response.ok) {
|
|
48
|
-
const text = await response.text().catch(() => "");
|
|
49
|
-
throw new Error(`${errorPrefix} ${response.status}: ${text || response.statusText}`);
|
|
50
|
-
}
|
|
51
|
-
return await handleResponse(response);
|
|
52
|
-
} finally {
|
|
53
|
-
await release();
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function fetchJson<T>(
|
|
58
|
-
account: ResolvedGoogleChatAccount,
|
|
59
|
-
url: string,
|
|
60
|
-
init: RequestInit,
|
|
61
|
-
): Promise<T> {
|
|
62
|
-
return await withGoogleChatResponse({
|
|
63
|
-
account,
|
|
64
|
-
url,
|
|
65
|
-
init: {
|
|
66
|
-
...init,
|
|
67
|
-
headers: {
|
|
68
|
-
...headersToObject(init.headers),
|
|
69
|
-
"Content-Type": "application/json",
|
|
70
|
-
},
|
|
71
|
-
},
|
|
72
|
-
auditContext: "googlechat.api.json",
|
|
73
|
-
handleResponse: async (response) => (await response.json()) as T,
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
async function fetchOk(
|
|
78
|
-
account: ResolvedGoogleChatAccount,
|
|
79
|
-
url: string,
|
|
80
|
-
init: RequestInit,
|
|
81
|
-
): Promise<void> {
|
|
82
|
-
await withGoogleChatResponse({
|
|
83
|
-
account,
|
|
84
|
-
url,
|
|
85
|
-
init,
|
|
86
|
-
auditContext: "googlechat.api.ok",
|
|
87
|
-
handleResponse: async () => undefined,
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
async function fetchBuffer(
|
|
92
|
-
account: ResolvedGoogleChatAccount,
|
|
93
|
-
url: string,
|
|
94
|
-
init?: RequestInit,
|
|
95
|
-
options?: { maxBytes?: number },
|
|
96
|
-
): Promise<{ buffer: Buffer; contentType?: string }> {
|
|
97
|
-
return await withGoogleChatResponse({
|
|
98
|
-
account,
|
|
99
|
-
url,
|
|
100
|
-
init,
|
|
101
|
-
auditContext: "googlechat.api.buffer",
|
|
102
|
-
handleResponse: async (res) => {
|
|
103
|
-
const maxBytes = options?.maxBytes;
|
|
104
|
-
const lengthHeader = res.headers.get("content-length");
|
|
105
|
-
if (maxBytes && lengthHeader) {
|
|
106
|
-
const length = Number(lengthHeader);
|
|
107
|
-
if (Number.isFinite(length) && length > maxBytes) {
|
|
108
|
-
throw new Error(`Google Chat media exceeds max bytes (${maxBytes})`);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
if (!maxBytes || !res.body) {
|
|
112
|
-
const buffer = Buffer.from(await res.arrayBuffer());
|
|
113
|
-
const contentType = res.headers.get("content-type") ?? undefined;
|
|
114
|
-
return { buffer, contentType };
|
|
115
|
-
}
|
|
116
|
-
const reader = res.body.getReader();
|
|
117
|
-
const chunks: Buffer[] = [];
|
|
118
|
-
let total = 0;
|
|
119
|
-
while (true) {
|
|
120
|
-
const { done, value } = await reader.read();
|
|
121
|
-
if (done) {
|
|
122
|
-
break;
|
|
123
|
-
}
|
|
124
|
-
if (!value) {
|
|
125
|
-
continue;
|
|
126
|
-
}
|
|
127
|
-
total += value.length;
|
|
128
|
-
if (total > maxBytes) {
|
|
129
|
-
await reader.cancel();
|
|
130
|
-
throw new Error(`Google Chat media exceeds max bytes (${maxBytes})`);
|
|
131
|
-
}
|
|
132
|
-
chunks.push(Buffer.from(value));
|
|
133
|
-
}
|
|
134
|
-
const buffer = Buffer.concat(chunks, total);
|
|
135
|
-
const contentType = res.headers.get("content-type") ?? undefined;
|
|
136
|
-
return { buffer, contentType };
|
|
137
|
-
},
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export async function sendGoogleChatMessage(params: {
|
|
142
|
-
account: ResolvedGoogleChatAccount;
|
|
143
|
-
space: string;
|
|
144
|
-
text?: string;
|
|
145
|
-
thread?: string;
|
|
146
|
-
attachments?: Array<{ attachmentUploadToken: string; contentName?: string }>;
|
|
147
|
-
}): Promise<{ messageName?: string } | null> {
|
|
148
|
-
const { account, space, text, thread, attachments } = params;
|
|
149
|
-
const body: Record<string, unknown> = {};
|
|
150
|
-
if (text) {
|
|
151
|
-
body.text = text;
|
|
152
|
-
}
|
|
153
|
-
if (thread) {
|
|
154
|
-
body.thread = { name: thread };
|
|
155
|
-
}
|
|
156
|
-
if (attachments && attachments.length > 0) {
|
|
157
|
-
body.attachment = attachments.map((item) =>
|
|
158
|
-
Object.assign(
|
|
159
|
-
{ attachmentDataRef: { attachmentUploadToken: item.attachmentUploadToken } },
|
|
160
|
-
item.contentName ? { contentName: item.contentName } : {},
|
|
161
|
-
),
|
|
162
|
-
);
|
|
163
|
-
}
|
|
164
|
-
const urlObj = new URL(`${CHAT_API_BASE}/${space}/messages`);
|
|
165
|
-
if (thread) {
|
|
166
|
-
urlObj.searchParams.set("messageReplyOption", "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD");
|
|
167
|
-
}
|
|
168
|
-
const url = urlObj.toString();
|
|
169
|
-
const result = await fetchJson<{ name?: string }>(account, url, {
|
|
170
|
-
method: "POST",
|
|
171
|
-
body: JSON.stringify(body),
|
|
172
|
-
});
|
|
173
|
-
return result ? { messageName: result.name } : null;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export async function updateGoogleChatMessage(params: {
|
|
177
|
-
account: ResolvedGoogleChatAccount;
|
|
178
|
-
messageName: string;
|
|
179
|
-
text: string;
|
|
180
|
-
}): Promise<{ messageName?: string }> {
|
|
181
|
-
const { account, messageName, text } = params;
|
|
182
|
-
const url = `${CHAT_API_BASE}/${messageName}?updateMask=text`;
|
|
183
|
-
const result = await fetchJson<{ name?: string }>(account, url, {
|
|
184
|
-
method: "PATCH",
|
|
185
|
-
body: JSON.stringify({ text }),
|
|
186
|
-
});
|
|
187
|
-
return { messageName: result.name };
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
export async function deleteGoogleChatMessage(params: {
|
|
191
|
-
account: ResolvedGoogleChatAccount;
|
|
192
|
-
messageName: string;
|
|
193
|
-
}): Promise<void> {
|
|
194
|
-
const { account, messageName } = params;
|
|
195
|
-
const url = `${CHAT_API_BASE}/${messageName}`;
|
|
196
|
-
await fetchOk(account, url, { method: "DELETE" });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
export async function uploadGoogleChatAttachment(params: {
|
|
200
|
-
account: ResolvedGoogleChatAccount;
|
|
201
|
-
space: string;
|
|
202
|
-
filename: string;
|
|
203
|
-
buffer: Buffer;
|
|
204
|
-
contentType?: string;
|
|
205
|
-
}): Promise<{ attachmentUploadToken?: string }> {
|
|
206
|
-
const { account, space, filename, buffer, contentType } = params;
|
|
207
|
-
const boundary = `openclaw-${crypto.randomUUID()}`;
|
|
208
|
-
const metadata = JSON.stringify({ filename });
|
|
209
|
-
const header = `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${metadata}\r\n`;
|
|
210
|
-
const mediaHeader = `--${boundary}\r\nContent-Type: ${contentType ?? "application/octet-stream"}\r\n\r\n`;
|
|
211
|
-
const footer = `\r\n--${boundary}--\r\n`;
|
|
212
|
-
const body = Buffer.concat([
|
|
213
|
-
Buffer.from(header, "utf8"),
|
|
214
|
-
Buffer.from(mediaHeader, "utf8"),
|
|
215
|
-
buffer,
|
|
216
|
-
Buffer.from(footer, "utf8"),
|
|
217
|
-
]);
|
|
218
|
-
|
|
219
|
-
const url = `${CHAT_UPLOAD_BASE}/${space}/attachments:upload?uploadType=multipart`;
|
|
220
|
-
const payload = await withGoogleChatResponse<{
|
|
221
|
-
attachmentDataRef?: { attachmentUploadToken?: string };
|
|
222
|
-
}>({
|
|
223
|
-
account,
|
|
224
|
-
url,
|
|
225
|
-
init: {
|
|
226
|
-
method: "POST",
|
|
227
|
-
headers: {
|
|
228
|
-
"Content-Type": `multipart/related; boundary=${boundary}`,
|
|
229
|
-
},
|
|
230
|
-
body,
|
|
231
|
-
},
|
|
232
|
-
auditContext: "googlechat.upload",
|
|
233
|
-
errorPrefix: "Google Chat upload",
|
|
234
|
-
handleResponse: async (response) =>
|
|
235
|
-
(await response.json()) as {
|
|
236
|
-
attachmentDataRef?: { attachmentUploadToken?: string };
|
|
237
|
-
},
|
|
238
|
-
});
|
|
239
|
-
return {
|
|
240
|
-
attachmentUploadToken: payload.attachmentDataRef?.attachmentUploadToken,
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
export async function downloadGoogleChatMedia(params: {
|
|
245
|
-
account: ResolvedGoogleChatAccount;
|
|
246
|
-
resourceName: string;
|
|
247
|
-
maxBytes?: number;
|
|
248
|
-
}): Promise<{ buffer: Buffer; contentType?: string }> {
|
|
249
|
-
const { account, resourceName, maxBytes } = params;
|
|
250
|
-
const url = `${CHAT_API_BASE}/media/${resourceName}?alt=media`;
|
|
251
|
-
return await fetchBuffer(account, url, undefined, { maxBytes });
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
export async function createGoogleChatReaction(params: {
|
|
255
|
-
account: ResolvedGoogleChatAccount;
|
|
256
|
-
messageName: string;
|
|
257
|
-
emoji: string;
|
|
258
|
-
}): Promise<GoogleChatReaction> {
|
|
259
|
-
const { account, messageName, emoji } = params;
|
|
260
|
-
const url = `${CHAT_API_BASE}/${messageName}/reactions`;
|
|
261
|
-
return await fetchJson<GoogleChatReaction>(account, url, {
|
|
262
|
-
method: "POST",
|
|
263
|
-
body: JSON.stringify({ emoji: { unicode: emoji } }),
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
export async function listGoogleChatReactions(params: {
|
|
268
|
-
account: ResolvedGoogleChatAccount;
|
|
269
|
-
messageName: string;
|
|
270
|
-
limit?: number;
|
|
271
|
-
}): Promise<GoogleChatReaction[]> {
|
|
272
|
-
const { account, messageName, limit } = params;
|
|
273
|
-
const url = new URL(`${CHAT_API_BASE}/${messageName}/reactions`);
|
|
274
|
-
if (limit && limit > 0) {
|
|
275
|
-
url.searchParams.set("pageSize", String(limit));
|
|
276
|
-
}
|
|
277
|
-
const result = await fetchJson<{ reactions?: GoogleChatReaction[] }>(account, url.toString(), {
|
|
278
|
-
method: "GET",
|
|
279
|
-
});
|
|
280
|
-
return result.reactions ?? [];
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
export async function deleteGoogleChatReaction(params: {
|
|
284
|
-
account: ResolvedGoogleChatAccount;
|
|
285
|
-
reactionName: string;
|
|
286
|
-
}): Promise<void> {
|
|
287
|
-
const { account, reactionName } = params;
|
|
288
|
-
const url = `${CHAT_API_BASE}/${reactionName}`;
|
|
289
|
-
await fetchOk(account, url, { method: "DELETE" });
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
export async function findGoogleChatDirectMessage(params: {
|
|
293
|
-
account: ResolvedGoogleChatAccount;
|
|
294
|
-
userName: string;
|
|
295
|
-
}): Promise<{ name?: string; displayName?: string } | null> {
|
|
296
|
-
const { account, userName } = params;
|
|
297
|
-
const url = new URL(`${CHAT_API_BASE}/spaces:findDirectMessage`);
|
|
298
|
-
url.searchParams.set("name", userName);
|
|
299
|
-
return await fetchJson<{ name?: string; displayName?: string }>(account, url.toString(), {
|
|
300
|
-
method: "GET",
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
export async function probeGoogleChat(account: ResolvedGoogleChatAccount): Promise<{
|
|
305
|
-
ok: boolean;
|
|
306
|
-
status?: number;
|
|
307
|
-
error?: string;
|
|
308
|
-
}> {
|
|
309
|
-
try {
|
|
310
|
-
const url = new URL(`${CHAT_API_BASE}/spaces`);
|
|
311
|
-
url.searchParams.set("pageSize", "1");
|
|
312
|
-
await fetchJson<Record<string, unknown>>(account, url.toString(), {
|
|
313
|
-
method: "GET",
|
|
314
|
-
});
|
|
315
|
-
return { ok: true };
|
|
316
|
-
} catch (err) {
|
|
317
|
-
return {
|
|
318
|
-
ok: false,
|
|
319
|
-
error: formatErrorMessage(err),
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { googleChatApprovalAuth } from "./approval-auth.js";
|
|
3
|
-
|
|
4
|
-
describe("googleChatApprovalAuth", () => {
|
|
5
|
-
it("authorizes stable users/* ids and ignores email-style approvers", () => {
|
|
6
|
-
expect(
|
|
7
|
-
googleChatApprovalAuth.authorizeActorAction({
|
|
8
|
-
cfg: { channels: { googlechat: { dm: { allowFrom: ["users/123"] } } } },
|
|
9
|
-
senderId: "users/123",
|
|
10
|
-
action: "approve",
|
|
11
|
-
approvalKind: "exec",
|
|
12
|
-
}),
|
|
13
|
-
).toEqual({ authorized: true });
|
|
14
|
-
|
|
15
|
-
expect(
|
|
16
|
-
googleChatApprovalAuth.authorizeActorAction({
|
|
17
|
-
cfg: { channels: { googlechat: { dm: { allowFrom: ["owner@example.com"] } } } },
|
|
18
|
-
senderId: "users/attacker",
|
|
19
|
-
action: "approve",
|
|
20
|
-
approvalKind: "exec",
|
|
21
|
-
}),
|
|
22
|
-
).toEqual({ authorized: true });
|
|
23
|
-
});
|
|
24
|
-
});
|
package/src/approval-auth.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
createResolvedApproverActionAuthAdapter,
|
|
3
|
-
resolveApprovalApprovers,
|
|
4
|
-
} from "openclaw/plugin-sdk/approval-auth-runtime";
|
|
5
|
-
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
|
|
6
|
-
import { resolveGoogleChatAccount } from "./accounts.js";
|
|
7
|
-
import { isGoogleChatUserTarget, normalizeGoogleChatTarget } from "./targets.js";
|
|
8
|
-
|
|
9
|
-
function normalizeGoogleChatApproverId(value: string | number): string | undefined {
|
|
10
|
-
const normalized = normalizeGoogleChatTarget(String(value));
|
|
11
|
-
if (!normalized || !isGoogleChatUserTarget(normalized)) {
|
|
12
|
-
return undefined;
|
|
13
|
-
}
|
|
14
|
-
const suffix = normalizeLowercaseStringOrEmpty(normalized.slice("users/".length));
|
|
15
|
-
if (!suffix || suffix.includes("@")) {
|
|
16
|
-
return undefined;
|
|
17
|
-
}
|
|
18
|
-
return `users/${suffix}`;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export const googleChatApprovalAuth = createResolvedApproverActionAuthAdapter({
|
|
22
|
-
channelLabel: "Google Chat",
|
|
23
|
-
resolveApprovers: ({ cfg, accountId }) => {
|
|
24
|
-
const account = resolveGoogleChatAccount({ cfg, accountId }).config;
|
|
25
|
-
return resolveApprovalApprovers({
|
|
26
|
-
allowFrom: account.dm?.allowFrom,
|
|
27
|
-
defaultTo: account.defaultTo,
|
|
28
|
-
normalizeApprover: normalizeGoogleChatApproverId,
|
|
29
|
-
});
|
|
30
|
-
},
|
|
31
|
-
normalizeSenderId: (value) => normalizeGoogleChatApproverId(value),
|
|
32
|
-
});
|
package/src/auth.ts
DELETED
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
|
|
2
|
-
import { fetchWithSsrFGuard } from "../runtime-api.js";
|
|
3
|
-
import type { ResolvedGoogleChatAccount } from "./accounts.js";
|
|
4
|
-
import {
|
|
5
|
-
__testing as googleAuthRuntimeTesting,
|
|
6
|
-
getGoogleAuthTransport,
|
|
7
|
-
loadGoogleAuthRuntime,
|
|
8
|
-
resolveValidatedGoogleChatCredentials,
|
|
9
|
-
} from "./google-auth.runtime.js";
|
|
10
|
-
|
|
11
|
-
const CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
|
|
12
|
-
const CHAT_ISSUER = "chat@system.gserviceaccount.com";
|
|
13
|
-
// Google Workspace Add-ons use a different service account pattern
|
|
14
|
-
const ADDON_ISSUER_PATTERN = /^service-\d+@gcp-sa-gsuiteaddons\.iam\.gserviceaccount\.com$/;
|
|
15
|
-
const CHAT_CERTS_URL =
|
|
16
|
-
"https://www.googleapis.com/service_accounts/v1/metadata/x509/chat@system.gserviceaccount.com";
|
|
17
|
-
|
|
18
|
-
// Size-capped to prevent unbounded growth in long-running deployments (#4948)
|
|
19
|
-
const MAX_AUTH_CACHE_SIZE = 32;
|
|
20
|
-
type GoogleAuthModule = typeof import("google-auth-library");
|
|
21
|
-
type GoogleAuthRuntime = {
|
|
22
|
-
GoogleAuth: GoogleAuthModule["GoogleAuth"];
|
|
23
|
-
OAuth2Client: GoogleAuthModule["OAuth2Client"];
|
|
24
|
-
};
|
|
25
|
-
type GoogleAuthInstance = InstanceType<GoogleAuthRuntime["GoogleAuth"]>;
|
|
26
|
-
type GoogleAuthOptions = ConstructorParameters<GoogleAuthRuntime["GoogleAuth"]>[0];
|
|
27
|
-
type GoogleAuthTransport = NonNullable<GoogleAuthOptions>["clientOptions"] extends {
|
|
28
|
-
transporter?: infer T;
|
|
29
|
-
}
|
|
30
|
-
? T
|
|
31
|
-
: never;
|
|
32
|
-
type OAuth2ClientInstance = InstanceType<GoogleAuthRuntime["OAuth2Client"]>;
|
|
33
|
-
|
|
34
|
-
const authCache = new Map<string, { key: string; auth: GoogleAuthInstance }>();
|
|
35
|
-
|
|
36
|
-
let cachedCerts: { fetchedAt: number; certs: Record<string, string> } | null = null;
|
|
37
|
-
let verifyClientPromise: Promise<OAuth2ClientInstance> | null = null;
|
|
38
|
-
|
|
39
|
-
async function getVerifyClient(): Promise<OAuth2ClientInstance> {
|
|
40
|
-
if (!verifyClientPromise) {
|
|
41
|
-
verifyClientPromise = (async () => {
|
|
42
|
-
try {
|
|
43
|
-
const { OAuth2Client } = await loadGoogleAuthRuntime();
|
|
44
|
-
// google-auth-library types its transporter through gaxios' CJS surface,
|
|
45
|
-
// while the plugin imports the ESM entrypoint directly.
|
|
46
|
-
const transporter = (await getGoogleAuthTransport()) as unknown as GoogleAuthTransport;
|
|
47
|
-
return new OAuth2Client({ transporter });
|
|
48
|
-
} catch (error) {
|
|
49
|
-
verifyClientPromise = null;
|
|
50
|
-
throw error;
|
|
51
|
-
}
|
|
52
|
-
})();
|
|
53
|
-
}
|
|
54
|
-
return await verifyClientPromise;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function buildAuthKey(account: ResolvedGoogleChatAccount): string {
|
|
58
|
-
if (account.credentialsFile) {
|
|
59
|
-
return `file:${account.credentialsFile}`;
|
|
60
|
-
}
|
|
61
|
-
if (account.credentials) {
|
|
62
|
-
return `inline:${JSON.stringify(account.credentials)}`;
|
|
63
|
-
}
|
|
64
|
-
return "none";
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async function getAuthInstance(account: ResolvedGoogleChatAccount): Promise<GoogleAuthInstance> {
|
|
68
|
-
const key = buildAuthKey(account);
|
|
69
|
-
const cached = authCache.get(account.accountId);
|
|
70
|
-
if (cached && cached.key === key) {
|
|
71
|
-
return cached.auth;
|
|
72
|
-
}
|
|
73
|
-
const [{ GoogleAuth }, rawTransporter, credentials] = await Promise.all([
|
|
74
|
-
loadGoogleAuthRuntime(),
|
|
75
|
-
getGoogleAuthTransport(),
|
|
76
|
-
resolveValidatedGoogleChatCredentials(account),
|
|
77
|
-
]);
|
|
78
|
-
const transporter = rawTransporter as unknown as GoogleAuthTransport;
|
|
79
|
-
|
|
80
|
-
const evictOldest = () => {
|
|
81
|
-
if (authCache.size > MAX_AUTH_CACHE_SIZE) {
|
|
82
|
-
const oldest = authCache.keys().next().value;
|
|
83
|
-
if (oldest !== undefined) {
|
|
84
|
-
authCache.delete(oldest);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
};
|
|
88
|
-
|
|
89
|
-
const auth = new GoogleAuth({
|
|
90
|
-
...(credentials ? { credentials } : {}),
|
|
91
|
-
clientOptions: { transporter },
|
|
92
|
-
scopes: [CHAT_SCOPE],
|
|
93
|
-
});
|
|
94
|
-
authCache.set(account.accountId, { key, auth });
|
|
95
|
-
evictOldest();
|
|
96
|
-
return auth;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export async function getGoogleChatAccessToken(
|
|
100
|
-
account: ResolvedGoogleChatAccount,
|
|
101
|
-
): Promise<string> {
|
|
102
|
-
const auth = await getAuthInstance(account);
|
|
103
|
-
const client = await auth.getClient();
|
|
104
|
-
const access = await client.getAccessToken();
|
|
105
|
-
const token = typeof access === "string" ? access : access?.token;
|
|
106
|
-
if (!token) {
|
|
107
|
-
throw new Error("Missing Google Chat access token");
|
|
108
|
-
}
|
|
109
|
-
return token;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async function fetchChatCerts(): Promise<Record<string, string>> {
|
|
113
|
-
const now = Date.now();
|
|
114
|
-
if (cachedCerts && now - cachedCerts.fetchedAt < 10 * 60 * 1000) {
|
|
115
|
-
return cachedCerts.certs;
|
|
116
|
-
}
|
|
117
|
-
const { response, release } = await fetchWithSsrFGuard({
|
|
118
|
-
url: CHAT_CERTS_URL,
|
|
119
|
-
auditContext: "googlechat.auth.certs",
|
|
120
|
-
});
|
|
121
|
-
try {
|
|
122
|
-
if (!response.ok) {
|
|
123
|
-
throw new Error(`Failed to fetch Chat certs (${response.status})`);
|
|
124
|
-
}
|
|
125
|
-
const certs = (await response.json()) as Record<string, string>;
|
|
126
|
-
cachedCerts = { fetchedAt: now, certs };
|
|
127
|
-
return certs;
|
|
128
|
-
} finally {
|
|
129
|
-
await release();
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export type GoogleChatAudienceType = "app-url" | "project-number";
|
|
134
|
-
|
|
135
|
-
export async function verifyGoogleChatRequest(params: {
|
|
136
|
-
bearer?: string | null;
|
|
137
|
-
audienceType?: GoogleChatAudienceType | null;
|
|
138
|
-
audience?: string | null;
|
|
139
|
-
expectedAddOnPrincipal?: string | null;
|
|
140
|
-
}): Promise<{ ok: boolean; reason?: string }> {
|
|
141
|
-
const bearer = params.bearer?.trim();
|
|
142
|
-
if (!bearer) {
|
|
143
|
-
return { ok: false, reason: "missing token" };
|
|
144
|
-
}
|
|
145
|
-
const audience = params.audience?.trim();
|
|
146
|
-
if (!audience) {
|
|
147
|
-
return { ok: false, reason: "missing audience" };
|
|
148
|
-
}
|
|
149
|
-
const audienceType = params.audienceType ?? null;
|
|
150
|
-
|
|
151
|
-
if (audienceType === "app-url") {
|
|
152
|
-
try {
|
|
153
|
-
const verifyClient = await getVerifyClient();
|
|
154
|
-
const ticket = await verifyClient.verifyIdToken({
|
|
155
|
-
idToken: bearer,
|
|
156
|
-
audience,
|
|
157
|
-
});
|
|
158
|
-
const payload = ticket.getPayload();
|
|
159
|
-
const email = normalizeLowercaseStringOrEmpty(payload?.email ?? "");
|
|
160
|
-
if (!payload?.email_verified) {
|
|
161
|
-
return { ok: false, reason: "email not verified" };
|
|
162
|
-
}
|
|
163
|
-
if (email === CHAT_ISSUER) {
|
|
164
|
-
return { ok: true };
|
|
165
|
-
}
|
|
166
|
-
if (!ADDON_ISSUER_PATTERN.test(email)) {
|
|
167
|
-
return { ok: false, reason: `invalid issuer: ${email}` };
|
|
168
|
-
}
|
|
169
|
-
const expectedAddOnPrincipal = normalizeLowercaseStringOrEmpty(
|
|
170
|
-
params.expectedAddOnPrincipal ?? "",
|
|
171
|
-
);
|
|
172
|
-
if (!expectedAddOnPrincipal) {
|
|
173
|
-
return { ok: false, reason: "missing add-on principal binding" };
|
|
174
|
-
}
|
|
175
|
-
const tokenPrincipal = normalizeLowercaseStringOrEmpty(payload?.sub ?? "");
|
|
176
|
-
if (!tokenPrincipal || tokenPrincipal !== expectedAddOnPrincipal) {
|
|
177
|
-
return {
|
|
178
|
-
ok: false,
|
|
179
|
-
reason: `unexpected add-on principal: ${tokenPrincipal || "<missing>"}`,
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
return { ok: true };
|
|
183
|
-
} catch (err) {
|
|
184
|
-
return { ok: false, reason: err instanceof Error ? err.message : "invalid token" };
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
if (audienceType === "project-number") {
|
|
189
|
-
try {
|
|
190
|
-
const verifyClient = await getVerifyClient();
|
|
191
|
-
const certs = await fetchChatCerts();
|
|
192
|
-
await verifyClient.verifySignedJwtWithCertsAsync(bearer, certs, audience, [CHAT_ISSUER]);
|
|
193
|
-
return { ok: true };
|
|
194
|
-
} catch (err) {
|
|
195
|
-
return { ok: false, reason: err instanceof Error ? err.message : "invalid token" };
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
return { ok: false, reason: "unsupported audience type" };
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export const __testing = {
|
|
203
|
-
resetGoogleChatAuthForTests(): void {
|
|
204
|
-
authCache.clear();
|
|
205
|
-
cachedCerts = null;
|
|
206
|
-
verifyClientPromise = null;
|
|
207
|
-
googleAuthRuntimeTesting.resetGoogleAuthRuntimeForTests();
|
|
208
|
-
},
|
|
209
|
-
};
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-types";
|
|
2
|
-
import { describe, expect, it } from "vitest";
|
|
3
|
-
import { googlechatPlugin } from "./channel.js";
|
|
4
|
-
|
|
5
|
-
describe("googlechatPlugin config adapter", () => {
|
|
6
|
-
it("keeps read-only accessors from resolving service account SecretRefs", () => {
|
|
7
|
-
const cfg = {
|
|
8
|
-
secrets: {
|
|
9
|
-
providers: {
|
|
10
|
-
google_chat_service_account: {
|
|
11
|
-
source: "file",
|
|
12
|
-
path: "/tmp/openclaw-missing-google-chat-service-account",
|
|
13
|
-
mode: "singleValue",
|
|
14
|
-
},
|
|
15
|
-
},
|
|
16
|
-
},
|
|
17
|
-
channels: {
|
|
18
|
-
googlechat: {
|
|
19
|
-
serviceAccount: {
|
|
20
|
-
source: "file",
|
|
21
|
-
provider: "google_chat_service_account",
|
|
22
|
-
id: "value",
|
|
23
|
-
},
|
|
24
|
-
dm: {
|
|
25
|
-
allowFrom: ["users/123"],
|
|
26
|
-
},
|
|
27
|
-
defaultTo: "spaces/AAA",
|
|
28
|
-
},
|
|
29
|
-
},
|
|
30
|
-
} as OpenClawConfig;
|
|
31
|
-
|
|
32
|
-
expect(googlechatPlugin.config.resolveAllowFrom?.({ cfg, accountId: "default" })).toEqual([
|
|
33
|
-
"users/123",
|
|
34
|
-
]);
|
|
35
|
-
expect(googlechatPlugin.config.resolveDefaultTo?.({ cfg, accountId: "default" })).toBe(
|
|
36
|
-
"spaces/AAA",
|
|
37
|
-
);
|
|
38
|
-
});
|
|
39
|
-
});
|