@open-everywhere/provider-google-chat 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +51 -0
  3. package/README.md +40 -2
  4. package/agent/channels/google-chat-auth.ts +145 -0
  5. package/agent/channels/google-chat-front.ts +337 -0
  6. package/agent/channels/google-chat-identity.ts +97 -0
  7. package/agent/channels/google-chat-message-ops.ts +30 -0
  8. package/agent/channels/google-chat-origin-codec.ts +32 -0
  9. package/agent/channels/google-chat-post-arm.ts +36 -0
  10. package/agent/channels/google-chat-rest.ts +87 -0
  11. package/agent/channels/google-chat.ts +193 -0
  12. package/agent/contributions.ts +16 -0
  13. package/agent/docs-generated.ts +15 -0
  14. package/agent/policy.ts +101 -0
  15. package/agent/provider-events.ts +18 -0
  16. package/agent/register.ts +48 -0
  17. package/agent/surface-parity.ts +63 -0
  18. package/dist/agent/channels/google-chat-auth.d.ts +39 -0
  19. package/dist/agent/channels/google-chat-auth.d.ts.map +1 -0
  20. package/dist/agent/channels/google-chat-auth.js +118 -0
  21. package/dist/agent/channels/google-chat-auth.js.map +1 -0
  22. package/dist/agent/channels/google-chat-front.d.ts +101 -0
  23. package/dist/agent/channels/google-chat-front.d.ts.map +1 -0
  24. package/dist/agent/channels/google-chat-front.js +258 -0
  25. package/dist/agent/channels/google-chat-front.js.map +1 -0
  26. package/dist/agent/channels/google-chat-identity.d.ts +28 -0
  27. package/dist/agent/channels/google-chat-identity.d.ts.map +1 -0
  28. package/dist/agent/channels/google-chat-identity.js +70 -0
  29. package/dist/agent/channels/google-chat-identity.js.map +1 -0
  30. package/dist/agent/channels/google-chat-message-ops.d.ts +10 -0
  31. package/dist/agent/channels/google-chat-message-ops.d.ts.map +1 -0
  32. package/dist/agent/channels/google-chat-message-ops.js +25 -0
  33. package/dist/agent/channels/google-chat-message-ops.js.map +1 -0
  34. package/dist/agent/channels/google-chat-origin-codec.d.ts +6 -0
  35. package/dist/agent/channels/google-chat-origin-codec.d.ts.map +1 -0
  36. package/dist/agent/channels/google-chat-origin-codec.js +31 -0
  37. package/dist/agent/channels/google-chat-origin-codec.js.map +1 -0
  38. package/dist/agent/channels/google-chat-post-arm.d.ts +11 -0
  39. package/dist/agent/channels/google-chat-post-arm.d.ts.map +1 -0
  40. package/dist/agent/channels/google-chat-post-arm.js +31 -0
  41. package/dist/agent/channels/google-chat-post-arm.js.map +1 -0
  42. package/dist/agent/channels/google-chat-rest.d.ts +21 -0
  43. package/dist/agent/channels/google-chat-rest.d.ts.map +1 -0
  44. package/dist/agent/channels/google-chat-rest.js +81 -0
  45. package/dist/agent/channels/google-chat-rest.js.map +1 -0
  46. package/dist/agent/channels/google-chat.d.ts +3 -0
  47. package/dist/agent/channels/google-chat.d.ts.map +1 -0
  48. package/dist/agent/channels/google-chat.js +156 -0
  49. package/dist/agent/channels/google-chat.js.map +1 -0
  50. package/dist/agent/contributions.d.ts +12 -0
  51. package/dist/agent/contributions.d.ts.map +1 -0
  52. package/dist/agent/contributions.js +16 -0
  53. package/dist/agent/contributions.js.map +1 -0
  54. package/dist/agent/docs-generated.d.ts +3 -0
  55. package/dist/agent/docs-generated.d.ts.map +1 -0
  56. package/dist/agent/docs-generated.js +13 -0
  57. package/dist/agent/docs-generated.js.map +1 -0
  58. package/dist/agent/policy.d.ts +38 -0
  59. package/dist/agent/policy.d.ts.map +1 -0
  60. package/dist/agent/policy.js +78 -0
  61. package/dist/agent/policy.js.map +1 -0
  62. package/dist/agent/provider-events.d.ts +3 -0
  63. package/dist/agent/provider-events.d.ts.map +1 -0
  64. package/dist/agent/provider-events.js +16 -0
  65. package/dist/agent/provider-events.js.map +1 -0
  66. package/dist/agent/register.d.ts +3 -0
  67. package/dist/agent/register.d.ts.map +1 -0
  68. package/dist/agent/register.js +37 -0
  69. package/dist/agent/register.js.map +1 -0
  70. package/dist/agent/surface-parity.d.ts +3 -0
  71. package/dist/agent/surface-parity.d.ts.map +1 -0
  72. package/dist/agent/surface-parity.js +59 -0
  73. package/dist/agent/surface-parity.js.map +1 -0
  74. package/package.json +116 -4
  75. package/tsconfig.build.json +22 -0
  76. package/tsconfig.json +15 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your Exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Tommy Long
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,51 @@
1
+ Open Everywhere
2
+ Copyright 2026 Tommy Long
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ ---
7
+
8
+ Built on Vercel Eve (https://github.com/vercel/eve), licensed under the
9
+ Apache License, Version 2.0.
10
+
11
+ ---
12
+
13
+ Modifications to eve
14
+
15
+ The @open-everywhere/core package distributes patches/eve+0.71.0.patch. That
16
+ patch file is a modification of eve 0.71.0. Vercel licenses eve 0.71.0 under the
17
+ Apache License, Version 2.0. The copyright notice of eve 0.71.0 reads
18
+ "Copyright 2026 Vercel, Inc. and contributors". The Open Everywhere authors made
19
+ the changes in the patch file.
20
+
21
+ The patch modifies four files of eve 0.71.0:
22
+
23
+ dist/src/execution/web-fetch/request.js
24
+ dist/src/harness/tool-loop.js
25
+ dist/src/internal/authored-package-boundary.js
26
+ dist/src/protocol/message.d.ts
27
+
28
+ Open Everywhere does not ship the eve package. eve is a peer dependency, so the
29
+ consumer installs eve 0.71.0 from the registry. The patch file carries the
30
+ modified portions of eve. The oe-eve-patch command, which
31
+ @open-everywhere/core ships, applies them to the eve that the consumer
32
+ installed. The command patches no file outside the consumer's own project. To
33
+ restore an eve that holds an older Open Everywhere patch, it also writes to npm's
34
+ cache and to a temporary directory.
35
+
36
+ The attribution notice of eve 0.71.0 follows, as section 4(d) of the Apache
37
+ License, Version 2.0 requires. The notices for eve's bundled code-mode runtime
38
+ are not reproduced, because the patch modifies no part of that runtime.
39
+
40
+ eve
41
+ Copyright 2026 Vercel, Inc. and contributors
42
+
43
+ This product includes software developed at Vercel, Inc.
44
+ (https://vercel.com/).
45
+
46
+ ---
47
+
48
+ Open Everywhere is an independent, open-source project. It is NOT affiliated
49
+ with, endorsed by, or sponsored by Anthropic. "Claude", "Claude Code", and
50
+ "Claude Tag" are referenced only to describe the prior art Open Everywhere is
51
+ inspired by, and are trademarks of their respective owner.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @open-everywhere/provider-google-chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Google Chat for Open Everywhere: the agent as a Google Chat app. An @mention in a space or a direct message wakes a
4
+ seat, and the seat answers in the same thread.
5
+
6
+ Part of [Open Everywhere](https://github.com/open-everywhere/open-everywhere) — an open, self-hostable autonomous
7
+ teammate you tag where your team works. This package is the Google Chat provider. It supplies the identity mapper,
8
+ the capability manifest, the post arm, the wake-origin codec, the host-notice transport and the policy schema.
9
+
10
+ `@open-everywhere/core` owns the runtime. This package holds the vendor half. The boundary between them is a
11
+ vendor-coupling one, and `packages/core/scripts/boundary-test.ts` checks it: the Google Chat fingerprints
12
+ (`chat.googleapis.com`, `GOOGLE_CHAT_SERVICE_ACCOUNT_KEY`) appear under this package and nowhere under
13
+ `packages/core/agent`.
14
+
15
+ ## What it does
16
+
17
+ - A **space** is a surface. A domain lists `google-chat/<workspace>/<space id>` in its `reach`, and an @mention of the
18
+ app in that space wakes the domain's standing seat.
19
+ - A person's **direct message** with the app wakes that person's DM seat. Only people on the policy's
20
+ `internalDomainIds` get one.
21
+ - Every event is verified against Google's keys and the policy's audience before it is read. The surface ships off:
22
+ until `agent/google-chat/policy.ts` enables it, the endpoint answers 503.
23
+
24
+ The operator guide is the "Google Chat" surface page of the manual (`docs/deploy/surfaces/google-chat.md`).
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm i @open-everywhere/core @open-everywhere/provider-google-chat eve@0.71.0
30
+ npx oe-eve-patch
31
+ ```
32
+
33
+ **Both commands are required.** Core refuses to boot on an unpatched `eve`. A registry `eve` carries
34
+ no patch, so `npx oe-eve-patch` applies the copy `@open-everywhere/core` ships.
35
+
36
+ `eve` is a peer dependency, pinned to the exact version above, which is the pin
37
+ `@open-everywhere/core` declares as `peerDependencies.eve`. Node 24 or newer.
38
+
39
+ ## License
40
+
41
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,145 @@
1
+ // google-chat-auth — the two credentials the Google Chat surface handles, and nothing else:
2
+ //
3
+ // 1. INBOUND: every event Google Chat POSTs to the app carries `Authorization: Bearer <JWT>`. The token is
4
+ // checked fully — signature against Google's published keys, issuer, audience and expiry — before the
5
+ // body is read as an event. The audience is the policy's (agent/google-chat/policy.ts in the app), never
6
+ // the request's own Host header, so a token minted for another app cannot open this route.
7
+ // 2. OUTBOUND: the app's service-account key (an operator secret, `GOOGLE_CHAT_SERVICE_ACCOUNT_KEY`) signs a
8
+ // JWT-bearer grant for a short-lived access token with the `chat.bot` scope. The token endpoint is PINNED
9
+ // here: the key file's own `token_uri` is ignored, so an edited key cannot send the signed grant elsewhere.
10
+ //
11
+ // Error messages name the failed check only. They never echo a token, a claim value or the key.
12
+
13
+ import { createRemoteJWKSet, importPKCS8, jwtVerify, SignJWT, type JWTVerifyGetKey } from "jose";
14
+ import { getOperatorSecret } from "@open-everywhere/core/agent/adapter-api.js";
15
+ import type { GoogleChatAudience } from "../policy.js";
16
+
17
+ /** The service account Google Chat signs its events as. */
18
+ export const CHAT_ISSUER_ACCOUNT = "chat@system.gserviceaccount.com";
19
+ /** The JWKS of {@link CHAT_ISSUER_ACCOUNT} — the keys of a "project number" audience token. */
20
+ const CHAT_SYSTEM_JWKS_URL = "https://www.googleapis.com/service_accounts/v1/jwk/chat@system.gserviceaccount.com";
21
+ /** Google's OIDC keys — the keys of an "HTTP endpoint URL" audience token. */
22
+ const GOOGLE_OIDC_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
23
+ const GOOGLE_OIDC_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
24
+ /** The pinned token endpoint of the JWT-bearer grant. */
25
+ const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
26
+ /** The one scope the app asks for: act as the Chat app (post into spaces it is a member of). */
27
+ const CHAT_BOT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
28
+ /** The operator secret holding the service-account key JSON. */
29
+ const SERVICE_ACCOUNT_SECRET = "GOOGLE_CHAT_SERVICE_ACCOUNT_KEY";
30
+
31
+ export type GoogleChatTokenVerdict = { readonly ok: true } | { readonly ok: false; readonly reason: string };
32
+
33
+ export interface GoogleChatVerifyDeps {
34
+ /** The key resolvers, injectable so a test signs with its own key. Live default: Google's JWKS. */
35
+ readonly chatSystemKeys?: JWTVerifyGetKey;
36
+ readonly googleOidcKeys?: JWTVerifyGetKey;
37
+ }
38
+
39
+ let liveChatKeys: JWTVerifyGetKey | undefined;
40
+ let liveOidcKeys: JWTVerifyGetKey | undefined;
41
+
42
+ function bearer(authorization: string | undefined): string | undefined {
43
+ const m = /^Bearer\s+([A-Za-z0-9._-]+)$/u.exec(authorization?.trim() ?? "");
44
+ return m?.[1];
45
+ }
46
+
47
+ /**
48
+ * Verify one event's bearer token against the policy's audience. Fail closed: no header, a malformed token,
49
+ * a bad signature, a wrong issuer or audience, an expired token, or (endpoint-URL mode) a token for any
50
+ * account but Google Chat's own is refused.
51
+ */
52
+ export async function verifyGoogleChatToken(
53
+ authorization: string | undefined,
54
+ audience: GoogleChatAudience | null,
55
+ deps: GoogleChatVerifyDeps = {},
56
+ ): Promise<GoogleChatTokenVerdict> {
57
+ if (audience === null) return { ok: false, reason: "no audience is configured" };
58
+ const token = bearer(authorization);
59
+ if (token === undefined) return { ok: false, reason: "no bearer token" };
60
+ try {
61
+ if (audience.kind === "project-number") {
62
+ const keys = deps.chatSystemKeys ?? (liveChatKeys ??= createRemoteJWKSet(new URL(CHAT_SYSTEM_JWKS_URL)));
63
+ await jwtVerify(token, keys, { issuer: CHAT_ISSUER_ACCOUNT, audience: audience.projectNumber, algorithms: ["RS256"] });
64
+ return { ok: true };
65
+ }
66
+ const keys = deps.googleOidcKeys ?? (liveOidcKeys ??= createRemoteJWKSet(new URL(GOOGLE_OIDC_JWKS_URL)));
67
+ const { payload } = await jwtVerify(token, keys, { issuer: GOOGLE_OIDC_ISSUERS, audience: audience.url, algorithms: ["RS256"] });
68
+ // Any Google account can mint an id token for any audience URL, so the token must name Chat's own account.
69
+ if (payload["email"] !== CHAT_ISSUER_ACCOUNT || payload["email_verified"] !== true) {
70
+ return { ok: false, reason: "the token is not Google Chat's" };
71
+ }
72
+ return { ok: true };
73
+ } catch (e) {
74
+ const code = (e as { code?: unknown }).code;
75
+ return { ok: false, reason: `the token did not verify${typeof code === "string" ? ` (${code})` : ""}` };
76
+ }
77
+ }
78
+
79
+ // --- outbound ------------------------------------------------------------------------------------
80
+
81
+ interface ServiceAccountKey {
82
+ readonly clientEmail: string;
83
+ readonly privateKey: string;
84
+ }
85
+
86
+ /** Parse the key JSON. Throws a key-free error on anything that is not a service-account key. */
87
+ export function parseServiceAccountKey(raw: string): ServiceAccountKey {
88
+ let j: unknown;
89
+ try {
90
+ j = JSON.parse(raw);
91
+ } catch {
92
+ throw new Error(`${SERVICE_ACCOUNT_SECRET} is not JSON.`);
93
+ }
94
+ const o = (typeof j === "object" && j !== null ? j : {}) as Record<string, unknown>;
95
+ if (o["type"] !== "service_account" || typeof o["client_email"] !== "string" || typeof o["private_key"] !== "string") {
96
+ throw new Error(`${SERVICE_ACCOUNT_SECRET} is not a Google service-account key.`);
97
+ }
98
+ return { clientEmail: o["client_email"], privateKey: o["private_key"] };
99
+ }
100
+
101
+ export interface GoogleChatTokenDeps {
102
+ readonly fetch?: typeof fetch;
103
+ /** The raw key JSON. Live default: the operator secret store. */
104
+ readonly serviceAccountKey?: () => Promise<string>;
105
+ readonly now?: () => number;
106
+ }
107
+
108
+ let cached: { readonly token: string; readonly expiresAt: number; readonly account: string } | undefined;
109
+
110
+ /** Forget the cached access token (tests). */
111
+ export function resetGoogleChatTokenCache(): void {
112
+ cached = undefined;
113
+ }
114
+
115
+ /** A `chat.bot` access token for the app's service account, cached until a minute before it expires. */
116
+ export async function googleChatAccessToken(deps: GoogleChatTokenDeps = {}): Promise<string> {
117
+ const now = (deps.now ?? Date.now)();
118
+ const key = parseServiceAccountKey(await (deps.serviceAccountKey ?? (async () => (await getOperatorSecret(SERVICE_ACCOUNT_SECRET)).value))());
119
+ if (cached && cached.account === key.clientEmail && cached.expiresAt - 60_000 > now) return cached.token;
120
+ let signingKey: CryptoKey;
121
+ try {
122
+ signingKey = await importPKCS8(key.privateKey, "RS256");
123
+ } catch {
124
+ throw new Error(`${SERVICE_ACCOUNT_SECRET} holds a private key that does not import.`);
125
+ }
126
+ const iat = Math.floor(now / 1000);
127
+ const assertion = await new SignJWT({ scope: CHAT_BOT_SCOPE })
128
+ .setProtectedHeader({ alg: "RS256", typ: "JWT" })
129
+ .setIssuer(key.clientEmail)
130
+ .setAudience(GOOGLE_TOKEN_URL)
131
+ .setIssuedAt(iat)
132
+ .setExpirationTime(iat + 3600)
133
+ .sign(signingKey);
134
+ const res = await (deps.fetch ?? fetch)(GOOGLE_TOKEN_URL, {
135
+ method: "POST",
136
+ headers: { "content-type": "application/x-www-form-urlencoded" },
137
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion }).toString(),
138
+ });
139
+ if (!res.ok) throw new Error(`the Google token endpoint refused the service-account grant (HTTP ${res.status}).`);
140
+ const body = (await res.json().catch(() => ({}))) as { access_token?: unknown; expires_in?: unknown };
141
+ if (typeof body.access_token !== "string" || body.access_token === "") throw new Error("the Google token endpoint returned no access token.");
142
+ const ttl = typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 3600;
143
+ cached = { token: body.access_token, expiresAt: now + ttl * 1000, account: key.clientEmail };
144
+ return body.access_token;
145
+ }