@mshindi-labs/google 0.0.0-stage → 1.0.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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/dist/chunk-JVP7HHFU.js +76 -0
  4. package/dist/chunk-JVP7HHFU.js.map +1 -0
  5. package/dist/chunk-KJPQ3DMR.cjs +76 -0
  6. package/dist/chunk-KJPQ3DMR.cjs.map +1 -0
  7. package/dist/chunk-RWT25QHA.js +190 -0
  8. package/dist/chunk-RWT25QHA.js.map +1 -0
  9. package/dist/chunk-SHDP4A3A.cjs +190 -0
  10. package/dist/chunk-SHDP4A3A.cjs.map +1 -0
  11. package/dist/chunk-SIDO26T7.js +949 -0
  12. package/dist/chunk-SIDO26T7.js.map +1 -0
  13. package/dist/chunk-V22QP2AM.cjs +49 -0
  14. package/dist/chunk-V22QP2AM.cjs.map +1 -0
  15. package/dist/chunk-VN5VWVCT.cjs +949 -0
  16. package/dist/chunk-VN5VWVCT.cjs.map +1 -0
  17. package/dist/chunk-Z7O6GO3C.js +49 -0
  18. package/dist/chunk-Z7O6GO3C.js.map +1 -0
  19. package/dist/core.cjs +289 -0
  20. package/dist/core.cjs.map +1 -0
  21. package/dist/core.d.cts +173 -0
  22. package/dist/core.d.ts +173 -0
  23. package/dist/core.js +289 -0
  24. package/dist/core.js.map +1 -0
  25. package/dist/create-google-CPGcK-3G.d.cts +107 -0
  26. package/dist/create-google-nP9f9jd9.d.ts +107 -0
  27. package/dist/events-BsWOMtza.d.cts +160 -0
  28. package/dist/events-BsWOMtza.d.ts +160 -0
  29. package/dist/gmail.cjs +489 -0
  30. package/dist/gmail.cjs.map +1 -0
  31. package/dist/gmail.d.cts +53 -0
  32. package/dist/gmail.d.ts +53 -0
  33. package/dist/gmail.js +489 -0
  34. package/dist/gmail.js.map +1 -0
  35. package/dist/key-provider-Cq_14Bh6.d.cts +53 -0
  36. package/dist/key-provider-Cq_14Bh6.d.ts +53 -0
  37. package/dist/postgres.cjs +455 -0
  38. package/dist/postgres.cjs.map +1 -0
  39. package/dist/postgres.d.cts +22 -0
  40. package/dist/postgres.d.ts +22 -0
  41. package/dist/postgres.js +455 -0
  42. package/dist/postgres.js.map +1 -0
  43. package/dist/static-key-provider-BhyRhY6-.d.ts +18 -0
  44. package/dist/static-key-provider-CPNt4YvF.d.cts +18 -0
  45. package/dist/testing.cjs +829 -0
  46. package/dist/testing.cjs.map +1 -0
  47. package/dist/testing.d.cts +147 -0
  48. package/dist/testing.d.ts +147 -0
  49. package/dist/testing.js +829 -0
  50. package/dist/testing.js.map +1 -0
  51. package/dist/transport-CVOgr9XP.d.cts +20 -0
  52. package/dist/transport-CVOgr9XP.d.ts +20 -0
  53. package/package.json +143 -4
@@ -0,0 +1,949 @@
1
+ import {
2
+ AUTH_ENDPOINT,
3
+ InvalidGrantError,
4
+ codeChallenge,
5
+ randomToken,
6
+ sha256
7
+ } from "./chunk-Z7O6GO3C.js";
8
+ import {
9
+ ConnectionNotFoundError,
10
+ ConnectionRevokedError,
11
+ CredentialIntegrityError,
12
+ GoogleApiError,
13
+ InvalidConfigError,
14
+ InvalidOAuthStateError,
15
+ KeyProviderUnavailableError,
16
+ MissingPeerDependencyError,
17
+ MissingScopeError,
18
+ NoRefreshTokenError,
19
+ OAuthClientNotConfiguredError,
20
+ OAuthConsentDeniedError,
21
+ UnexpectedAccountError
22
+ } from "./chunk-RWT25QHA.js";
23
+
24
+ // src/core/scopes.ts
25
+ var BASE_SCOPES = ["openid", "email"];
26
+ var SERVICE_SCOPES = {
27
+ gmail: ["https://www.googleapis.com/auth/gmail.send"]
28
+ };
29
+ function scopesFor(services) {
30
+ const out = new Set(BASE_SCOPES);
31
+ for (const s of services)
32
+ for (const scope of SERVICE_SCOPES[s]) out.add(scope);
33
+ return [...out];
34
+ }
35
+ function assertServiceScopes(granted, services, ids = {}) {
36
+ const have = new Set(granted);
37
+ const required = /* @__PURE__ */ new Set();
38
+ for (const s of services)
39
+ for (const scope of SERVICE_SCOPES[s]) required.add(scope);
40
+ const missing = [...required].filter((s) => !have.has(s));
41
+ if (missing.length > 0) {
42
+ throw new MissingScopeError(missing, void 0, ids);
43
+ }
44
+ }
45
+
46
+ // src/core/crypto/envelope.ts
47
+ import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
48
+ var RECORDS = [
49
+ "oauth_client",
50
+ "connection",
51
+ "oauth_state"
52
+ ];
53
+ var IV_BYTES = 12;
54
+ var TAG_BYTES = 16;
55
+ var DEK_BYTES = 32;
56
+ function part(name, value) {
57
+ if (typeof value !== "string" || value.length === 0) {
58
+ throw new InvalidConfigError(`AAD ${name} must be a non-empty string`);
59
+ }
60
+ if (value.includes("|") || value.includes("=")) {
61
+ throw new InvalidConfigError(`AAD ${name} must not contain "|" or "="`);
62
+ }
63
+ return value;
64
+ }
65
+ function buildAad(p) {
66
+ if (!RECORDS.includes(p.record)) {
67
+ throw new InvalidConfigError(`Unknown AAD record type`);
68
+ }
69
+ return `mshindi-google/v1|tenant=${part("tenantId", p.tenantId)}|record=${p.record}:${part("recordId", p.recordId)}|field=${part("field", p.field)}`;
70
+ }
71
+ var b64 = (b) => Buffer.from(b).toString("base64url");
72
+ var unb64 = (s) => {
73
+ if (typeof s !== "string" || !/^[A-Za-z0-9_-]*$/.test(s)) {
74
+ throw new CredentialIntegrityError();
75
+ }
76
+ const decoded = Buffer.from(s, "base64url");
77
+ if (decoded.toString("base64url") !== s) throw new CredentialIntegrityError();
78
+ return decoded;
79
+ };
80
+ async function encryptValue(plaintext, aad, kp) {
81
+ const dek = randomBytes(DEK_BYTES);
82
+ try {
83
+ const iv = randomBytes(IV_BYTES);
84
+ const cipher = createCipheriv("aes-256-gcm", dek, iv, {
85
+ authTagLength: TAG_BYTES
86
+ });
87
+ cipher.setAAD(Buffer.from(aad, "utf8"));
88
+ const ct = Buffer.concat([
89
+ cipher.update(plaintext, "utf8"),
90
+ cipher.final()
91
+ ]);
92
+ const tag = cipher.getAuthTag();
93
+ const { kid, wdek } = await kp.wrap(dek, aad);
94
+ return {
95
+ v: 1,
96
+ kid,
97
+ wdek: b64(wdek),
98
+ iv: b64(iv),
99
+ ct: b64(ct),
100
+ tag: b64(tag)
101
+ };
102
+ } finally {
103
+ dek.fill(0);
104
+ }
105
+ }
106
+ async function decryptValue(value, aad, kp) {
107
+ let dek;
108
+ try {
109
+ if (!value || value.v !== 1) throw new CredentialIntegrityError();
110
+ dek = await kp.unwrap(value.kid, unb64(value.wdek), aad);
111
+ const iv = unb64(value.iv);
112
+ const tag = unb64(value.tag);
113
+ if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {
114
+ throw new CredentialIntegrityError();
115
+ }
116
+ const decipher = createDecipheriv("aes-256-gcm", dek, iv, {
117
+ authTagLength: TAG_BYTES
118
+ });
119
+ decipher.setAAD(Buffer.from(aad, "utf8"));
120
+ decipher.setAuthTag(tag);
121
+ return Buffer.concat([
122
+ decipher.update(unb64(value.ct)),
123
+ decipher.final()
124
+ ]).toString("utf8");
125
+ } catch (err) {
126
+ if (err instanceof KeyProviderUnavailableError || err instanceof MissingPeerDependencyError) {
127
+ throw err;
128
+ }
129
+ throw new CredentialIntegrityError();
130
+ } finally {
131
+ dek?.fill(0);
132
+ }
133
+ }
134
+ async function rewrapValue(value, aad, kp) {
135
+ let dek;
136
+ try {
137
+ if (!value || value.v !== 1) throw new CredentialIntegrityError();
138
+ dek = await kp.unwrap(value.kid, unb64(value.wdek), aad);
139
+ const { kid, wdek } = await kp.wrap(dek, aad);
140
+ return { ...value, kid, wdek: b64(wdek) };
141
+ } catch (err) {
142
+ if (err instanceof KeyProviderUnavailableError || err instanceof MissingPeerDependencyError) {
143
+ throw err;
144
+ }
145
+ throw new CredentialIntegrityError();
146
+ } finally {
147
+ dek?.fill(0);
148
+ }
149
+ }
150
+
151
+ // src/core/oauth/auth-url.ts
152
+ var STATE_TTL_MS = 6e5;
153
+ var hex = (b) => Buffer.from(b).toString("hex");
154
+ async function createAuthUrl(deps, p) {
155
+ if (!p.tenantId) throw new InvalidConfigError("tenantId must be non-empty");
156
+ if (!p.actorId) throw new InvalidConfigError("actorId must be non-empty");
157
+ if (!Array.isArray(p.services) || p.services.length === 0) {
158
+ throw new InvalidConfigError("services must be a non-empty list");
159
+ }
160
+ for (const s of p.services) {
161
+ if (!Object.prototype.hasOwnProperty.call(SERVICE_SCOPES, s)) {
162
+ throw new InvalidConfigError(`Unknown service: ${String(s)}`);
163
+ }
164
+ }
165
+ const client = await deps.store.getOAuthClient(p.tenantId);
166
+ if (!client) {
167
+ throw new OAuthClientNotConfiguredError(void 0, {
168
+ tenantId: p.tenantId
169
+ });
170
+ }
171
+ if (p.connectionId) {
172
+ const existing = await deps.store.getConnection(p.tenantId, p.connectionId);
173
+ if (!existing) {
174
+ throw new ConnectionNotFoundError(void 0, {
175
+ tenantId: p.tenantId,
176
+ connectionId: p.connectionId
177
+ });
178
+ }
179
+ }
180
+ const intendedEmail = p.intendedEmail?.trim().toLowerCase() || null;
181
+ const scopes = scopesFor(p.services);
182
+ const state = randomToken();
183
+ const verifier = randomToken();
184
+ const stateHash = sha256(state);
185
+ const codeVerifier = await encryptValue(
186
+ verifier,
187
+ buildAad({
188
+ tenantId: p.tenantId,
189
+ record: "oauth_state",
190
+ recordId: hex(stateHash),
191
+ field: "code_verifier"
192
+ }),
193
+ deps.keyProvider
194
+ );
195
+ const expiresAt = new Date(deps.now().getTime() + STATE_TTL_MS);
196
+ await deps.store.insertOAuthState({
197
+ stateHash,
198
+ tenantId: p.tenantId,
199
+ actorId: p.actorId,
200
+ intendedEmail,
201
+ connectionId: p.connectionId ?? null,
202
+ scopes,
203
+ codeVerifier,
204
+ expiresAt
205
+ });
206
+ const url = new URL(AUTH_ENDPOINT);
207
+ const q = url.searchParams;
208
+ q.set("client_id", client.clientId);
209
+ q.set("redirect_uri", deps.callbackUrl);
210
+ q.set("response_type", "code");
211
+ q.set("scope", scopes.join(" "));
212
+ q.set("state", state);
213
+ q.set("access_type", "offline");
214
+ q.set("prompt", "consent");
215
+ q.set("include_granted_scopes", "true");
216
+ q.set("code_challenge", codeChallenge(verifier));
217
+ q.set("code_challenge_method", "S256");
218
+ if (intendedEmail) q.set("login_hint", intendedEmail);
219
+ if (client.hostedDomain) q.set("hd", client.hostedDomain);
220
+ return { url: url.toString(), expiresAt };
221
+ }
222
+
223
+ // src/core/oauth/callback.ts
224
+ import { randomUUID } from "crypto";
225
+ var hex2 = (b) => Buffer.from(b).toString("hex");
226
+ var servicesOf = (scopes) => Object.keys(SERVICE_SCOPES).filter(
227
+ (s) => SERVICE_SCOPES[s].every((scope) => scopes.includes(scope))
228
+ );
229
+ function toView(rec) {
230
+ const { refreshToken: _omit, ...view } = rec;
231
+ return view;
232
+ }
233
+ async function handleCallback(deps, p) {
234
+ if (typeof p.state !== "string" || p.state.length === 0) {
235
+ throw new InvalidOAuthStateError();
236
+ }
237
+ const stateHash = hex2(sha256(p.state));
238
+ const state = await deps.store.consumeOAuthState(stateHash, deps.now());
239
+ if (!state) throw new InvalidOAuthStateError();
240
+ const { tenantId, actorId } = state;
241
+ if (p.error) throw new OAuthConsentDeniedError(void 0, { tenantId });
242
+ if (typeof p.code !== "string" || p.code.length === 0) {
243
+ throw new InvalidOAuthStateError(void 0, { tenantId });
244
+ }
245
+ const client = await deps.store.getOAuthClient(tenantId);
246
+ if (!client) {
247
+ throw new OAuthClientNotConfiguredError(void 0, { tenantId });
248
+ }
249
+ const clientSecret = await decryptValue(
250
+ client.clientSecret,
251
+ buildAad({
252
+ tenantId,
253
+ record: "oauth_client",
254
+ recordId: tenantId,
255
+ field: "client_secret"
256
+ }),
257
+ deps.keyProvider
258
+ );
259
+ const codeVerifier = await decryptValue(
260
+ state.codeVerifier,
261
+ buildAad({
262
+ tenantId,
263
+ record: "oauth_state",
264
+ recordId: stateHash,
265
+ field: "code_verifier"
266
+ }),
267
+ deps.keyProvider
268
+ );
269
+ const tokens = await deps.gateway.exchangeCode({
270
+ clientId: client.clientId,
271
+ clientSecret,
272
+ code: p.code,
273
+ codeVerifier,
274
+ redirectUri: deps.callbackUrl
275
+ });
276
+ const issued = tokens.refreshToken ?? tokens.accessToken;
277
+ const reject = async (err) => {
278
+ try {
279
+ await deps.gateway.revokeToken(issued);
280
+ } catch {
281
+ try {
282
+ deps.logger?.warn("google token revoke failed");
283
+ } catch {
284
+ }
285
+ }
286
+ throw err;
287
+ };
288
+ const at = deps.now();
289
+ let rec;
290
+ let existing;
291
+ try {
292
+ const id = await deps.gateway.verifyIdToken({
293
+ idToken: tokens.idToken,
294
+ clientId: client.clientId
295
+ });
296
+ if (typeof id.email !== "string" || id.emailVerified !== true) {
297
+ throw new UnexpectedAccountError(void 0, { tenantId });
298
+ }
299
+ const email2 = id.email.trim().toLowerCase();
300
+ if (client.hostedDomain && (id.hd ?? "").trim().toLowerCase() !== client.hostedDomain.toLowerCase()) {
301
+ throw new UnexpectedAccountError(void 0, { tenantId });
302
+ }
303
+ if (state.intendedEmail && email2 !== state.intendedEmail) {
304
+ throw new UnexpectedAccountError(void 0, { tenantId });
305
+ }
306
+ if (state.connectionId) {
307
+ existing = await deps.store.getConnection(tenantId, state.connectionId);
308
+ if (!existing || existing.googleSub !== id.sub) {
309
+ throw new UnexpectedAccountError(void 0, {
310
+ tenantId,
311
+ connectionId: state.connectionId
312
+ });
313
+ }
314
+ } else {
315
+ existing = await deps.store.findConnectionBySub(tenantId, id.sub);
316
+ }
317
+ assertServiceScopes(tokens.scopes, servicesOf(state.scopes), { tenantId });
318
+ if (!tokens.refreshToken) {
319
+ throw new NoRefreshTokenError(void 0, { tenantId });
320
+ }
321
+ const connectionId2 = existing?.id ?? randomUUID();
322
+ const refreshToken = await encryptValue(
323
+ tokens.refreshToken,
324
+ buildAad({
325
+ tenantId,
326
+ record: "connection",
327
+ recordId: connectionId2,
328
+ field: "refresh_token"
329
+ }),
330
+ deps.keyProvider
331
+ );
332
+ rec = {
333
+ id: connectionId2,
334
+ tenantId,
335
+ googleSub: id.sub,
336
+ email: email2,
337
+ displayName: existing?.displayName ?? null,
338
+ scopes: [.../* @__PURE__ */ new Set([...existing?.scopes ?? [], ...tokens.scopes])],
339
+ refreshToken,
340
+ status: "active",
341
+ statusReason: null,
342
+ connectedBy: existing?.connectedBy ?? actorId,
343
+ connectedAt: existing?.connectedAt ?? at,
344
+ updatedAt: at,
345
+ lastUsedAt: existing?.lastUsedAt ?? null
346
+ };
347
+ await deps.store.upsertConnection(rec);
348
+ const latest = await deps.store.getOAuthClient(tenantId);
349
+ if (!latest || latest.clientId !== client.clientId) {
350
+ await deps.store.updateConnectionStatus(
351
+ tenantId,
352
+ connectionId2,
353
+ "revoked",
354
+ "client_changed"
355
+ );
356
+ throw new ConnectionRevokedError("client_changed", {
357
+ tenantId,
358
+ connectionId: connectionId2
359
+ });
360
+ }
361
+ } catch (err) {
362
+ return reject(err);
363
+ }
364
+ const connectionId = rec.id;
365
+ const scopes = rec.scopes;
366
+ const email = rec.email;
367
+ deps.tokens.prime(
368
+ tenantId,
369
+ connectionId,
370
+ tokens.accessToken,
371
+ tokens.expiresAt
372
+ );
373
+ await deps.emit({
374
+ type: existing ? "connection.scopes_added" : "connection.created",
375
+ tenantId,
376
+ actorId,
377
+ connectionId,
378
+ email,
379
+ scopes,
380
+ at
381
+ });
382
+ return {
383
+ connection: toView(rec),
384
+ tenantId,
385
+ actorId,
386
+ created: !existing
387
+ };
388
+ }
389
+
390
+ // src/core/oauth/google-gateway.ts
391
+ import { OAuth2Client } from "google-auth-library";
392
+ function statusOf(e) {
393
+ const s = e.response?.status ?? e.status;
394
+ return typeof s === "number" ? s : 0;
395
+ }
396
+ function reasonOf(e) {
397
+ const r = e.response?.data?.error;
398
+ return typeof r === "string" ? r : null;
399
+ }
400
+ function isInvalidGrant(e) {
401
+ return reasonOf(e) === "invalid_grant" || typeof e.message === "string" && e.message.includes("invalid_grant");
402
+ }
403
+ function wrap(e) {
404
+ const g = typeof e === "object" && e !== null ? e : {};
405
+ return new GoogleApiError(statusOf(g), reasonOf(g), { cause: e });
406
+ }
407
+ function createGoogleAuthGateway() {
408
+ return {
409
+ async exchangeCode(p) {
410
+ const client = new OAuth2Client(
411
+ p.clientId,
412
+ p.clientSecret,
413
+ p.redirectUri
414
+ );
415
+ let tokens;
416
+ try {
417
+ ({ tokens } = await client.getToken({
418
+ code: p.code,
419
+ codeVerifier: p.codeVerifier,
420
+ redirect_uri: p.redirectUri
421
+ }));
422
+ } catch (e) {
423
+ throw wrap(e);
424
+ }
425
+ if (!tokens.id_token) throw new Error("Token response had no id_token");
426
+ if (!tokens.access_token)
427
+ throw new Error("Token response had no access_token");
428
+ return {
429
+ refreshToken: tokens.refresh_token ?? null,
430
+ accessToken: tokens.access_token,
431
+ expiresAt: new Date(tokens.expiry_date ?? 0),
432
+ scopes: (tokens.scope ?? "").split(" ").filter(Boolean),
433
+ idToken: tokens.id_token
434
+ };
435
+ },
436
+ async verifyIdToken(p) {
437
+ const client = new OAuth2Client(p.clientId);
438
+ let payload;
439
+ try {
440
+ const ticket = await client.verifyIdToken({
441
+ idToken: p.idToken,
442
+ audience: p.clientId
443
+ });
444
+ payload = ticket.getPayload();
445
+ } catch (e) {
446
+ throw wrap(e);
447
+ }
448
+ if (!payload?.email || !payload.sub) {
449
+ throw new Error("ID token is missing email or sub");
450
+ }
451
+ return {
452
+ sub: payload.sub,
453
+ email: payload.email,
454
+ emailVerified: payload.email_verified === true,
455
+ hd: payload.hd ?? null
456
+ };
457
+ },
458
+ async refreshAccessToken(p) {
459
+ const client = new OAuth2Client(p.clientId, p.clientSecret);
460
+ client.setCredentials({ refresh_token: p.refreshToken });
461
+ let token;
462
+ try {
463
+ ({ token } = await client.getAccessToken());
464
+ } catch (e) {
465
+ const g = typeof e === "object" && e !== null ? e : {};
466
+ if (isInvalidGrant(g)) throw new InvalidGrantError();
467
+ throw wrap(e);
468
+ }
469
+ if (!token) throw new Error("Refresh response had no access_token");
470
+ return {
471
+ accessToken: token,
472
+ expiresAt: new Date(client.credentials.expiry_date ?? 0)
473
+ };
474
+ },
475
+ async revokeToken(token) {
476
+ try {
477
+ await new OAuth2Client().revokeToken(token);
478
+ } catch (e) {
479
+ throw wrap(e);
480
+ }
481
+ }
482
+ };
483
+ }
484
+
485
+ // src/core/events.ts
486
+ import { createHash } from "crypto";
487
+ function sha256hex(address) {
488
+ return createHash("sha256").update(address.trim().toLowerCase(), "utf8").digest("hex");
489
+ }
490
+ function redactRecipients(e) {
491
+ if (e.type !== "message.sent" && e.type !== "message.failed") return e;
492
+ return {
493
+ ...e,
494
+ to: e.to.map(sha256hex),
495
+ cc: e.cc.map(sha256hex),
496
+ bcc: e.bcc.map(sha256hex)
497
+ };
498
+ }
499
+ function createEmitter(opts) {
500
+ const fail = (type) => {
501
+ try {
502
+ opts.logger?.error("google event handler failed", { type });
503
+ } catch {
504
+ }
505
+ };
506
+ return async (event, perCall) => {
507
+ const redact = perCall?.redactRecipients ?? opts.redactRecipients;
508
+ const e = redact ? redactRecipients(event) : event;
509
+ try {
510
+ await opts.onEvent?.(e);
511
+ } catch {
512
+ fail(e.type);
513
+ }
514
+ try {
515
+ await opts.store.insertAuditEvent?.(e);
516
+ } catch {
517
+ fail(e.type);
518
+ }
519
+ };
520
+ }
521
+
522
+ // src/core/clients.ts
523
+ var CLIENT_ID = /^[\w-]+\.apps\.googleusercontent\.com$/;
524
+ var nonEmpty = (v, name) => {
525
+ if (typeof v !== "string" || v.length === 0) {
526
+ throw new InvalidConfigError(`${name} must be a non-empty string`);
527
+ }
528
+ return v;
529
+ };
530
+ function createClientsApi(deps) {
531
+ return {
532
+ async configure(p) {
533
+ const tenantId = nonEmpty(p.tenantId, "tenantId");
534
+ const actorId = nonEmpty(p.actorId, "actorId");
535
+ if (typeof p.clientId !== "string" || !CLIENT_ID.test(p.clientId)) {
536
+ throw new InvalidConfigError(
537
+ "clientId must look like <id>.apps.googleusercontent.com"
538
+ );
539
+ }
540
+ if (typeof p.clientSecret !== "string" || p.clientSecret.length === 0 || /\s/.test(p.clientSecret)) {
541
+ throw new InvalidConfigError(
542
+ "clientSecret must be non-empty and contain no whitespace"
543
+ );
544
+ }
545
+ const hostedDomain = p.hostedDomain?.trim().toLowerCase() || null;
546
+ const existing = await deps.store.getOAuthClient(tenantId);
547
+ const clientIdChanged = existing !== null && existing.clientId !== p.clientId;
548
+ const at = deps.now();
549
+ const rec = {
550
+ tenantId,
551
+ clientId: p.clientId,
552
+ clientSecret: await encryptValue(
553
+ p.clientSecret,
554
+ buildAad({
555
+ tenantId,
556
+ record: "oauth_client",
557
+ recordId: tenantId,
558
+ field: "client_secret"
559
+ }),
560
+ deps.keyProvider
561
+ ),
562
+ secretHint: p.clientSecret.slice(-4),
563
+ hostedDomain,
564
+ createdBy: existing?.createdBy ?? actorId,
565
+ createdAt: existing?.createdAt ?? at,
566
+ updatedBy: actorId,
567
+ updatedAt: at
568
+ };
569
+ await deps.store.upsertOAuthClient(rec, {
570
+ revokeConnections: clientIdChanged
571
+ });
572
+ if (clientIdChanged) deps.tokens().evictTenant(tenantId);
573
+ await deps.emit({
574
+ type: existing ? "oauth_client.rotated" : "oauth_client.configured",
575
+ tenantId,
576
+ actorId,
577
+ clientIdChanged,
578
+ at
579
+ });
580
+ },
581
+ async get(tenantId) {
582
+ const r = await deps.store.getOAuthClient(tenantId);
583
+ if (!r) return null;
584
+ return {
585
+ clientId: r.clientId,
586
+ secretHint: r.secretHint,
587
+ hostedDomain: r.hostedDomain,
588
+ updatedAt: r.updatedAt
589
+ };
590
+ }
591
+ };
592
+ }
593
+
594
+ // src/core/tokens.ts
595
+ var EXPIRY_SKEW_MS = 6e4;
596
+ var DEFAULT_MAX_ENTRIES = 1e3;
597
+ var keyOf = (tenantId, connectionId) => `${tenantId}:${connectionId}`;
598
+ function createTokenManager(deps) {
599
+ const maxEntries = deps.maxEntries ?? DEFAULT_MAX_ENTRIES;
600
+ const cache = /* @__PURE__ */ new Map();
601
+ const flights = /* @__PURE__ */ new Map();
602
+ const remember = (e) => {
603
+ const k = keyOf(e.tenantId, e.connectionId);
604
+ cache.delete(k);
605
+ cache.set(k, e);
606
+ while (cache.size > maxEntries) {
607
+ const oldest = cache.keys().next();
608
+ if (oldest.done) break;
609
+ cache.delete(oldest.value);
610
+ }
611
+ };
612
+ const evictWhere = (match) => {
613
+ for (const [k, e] of cache) if (match(e)) cache.delete(k);
614
+ for (const f of flights.values()) if (match(f)) f.cancelled = true;
615
+ };
616
+ const refresh = async (tenantId, connectionId, connection, flight) => {
617
+ const client = await deps.store.getOAuthClient(tenantId);
618
+ if (!client) {
619
+ throw new OAuthClientNotConfiguredError(void 0, {
620
+ tenantId,
621
+ connectionId
622
+ });
623
+ }
624
+ if (!connection.refreshToken) {
625
+ throw new ConnectionRevokedError("disconnected", {
626
+ tenantId,
627
+ connectionId
628
+ });
629
+ }
630
+ const clientSecret = await decryptValue(
631
+ client.clientSecret,
632
+ buildAad({
633
+ tenantId,
634
+ record: "oauth_client",
635
+ recordId: tenantId,
636
+ field: "client_secret"
637
+ }),
638
+ deps.keyProvider
639
+ );
640
+ const refreshToken = await decryptValue(
641
+ connection.refreshToken,
642
+ buildAad({
643
+ tenantId,
644
+ record: "connection",
645
+ recordId: connection.id,
646
+ field: "refresh_token"
647
+ }),
648
+ deps.keyProvider
649
+ );
650
+ let result;
651
+ try {
652
+ result = await deps.gateway.refreshAccessToken({
653
+ clientId: client.clientId,
654
+ clientSecret,
655
+ refreshToken
656
+ });
657
+ } catch (err) {
658
+ if (!(err instanceof InvalidGrantError)) throw err;
659
+ await deps.store.updateConnectionStatus(
660
+ tenantId,
661
+ connectionId,
662
+ "revoked",
663
+ "invalid_grant"
664
+ );
665
+ evictWhere(
666
+ (e) => e.tenantId === tenantId && e.connectionId === connectionId
667
+ );
668
+ await deps.emit({
669
+ type: "connection.revoked",
670
+ tenantId,
671
+ connectionId,
672
+ reason: "invalid_grant",
673
+ at: deps.now()
674
+ });
675
+ throw new ConnectionRevokedError("invalid_grant", {
676
+ tenantId,
677
+ connectionId
678
+ });
679
+ }
680
+ if (!flight().cancelled) {
681
+ remember({
682
+ tenantId,
683
+ connectionId,
684
+ accessToken: result.accessToken,
685
+ expiresAt: result.expiresAt
686
+ });
687
+ }
688
+ try {
689
+ await deps.store.touchConnection(tenantId, connectionId, deps.now());
690
+ } catch {
691
+ try {
692
+ deps.logger?.warn("google touchConnection failed");
693
+ } catch {
694
+ }
695
+ }
696
+ return result.accessToken;
697
+ };
698
+ return {
699
+ async getAccessToken(tenantId, connectionId, opts) {
700
+ const connection = await deps.store.getConnection(tenantId, connectionId);
701
+ if (!connection) {
702
+ throw new ConnectionNotFoundError(void 0, {
703
+ tenantId,
704
+ connectionId
705
+ });
706
+ }
707
+ if (connection.status !== "active") {
708
+ throw new ConnectionRevokedError(connection.statusReason ?? "revoked", {
709
+ tenantId,
710
+ connectionId
711
+ });
712
+ }
713
+ const key = keyOf(tenantId, connectionId);
714
+ const hit = cache.get(key);
715
+ if (hit && hit.tenantId === tenantId && !opts?.forceRefresh && hit.expiresAt.getTime() - deps.now().getTime() > EXPIRY_SKEW_MS) {
716
+ cache.delete(key);
717
+ cache.set(key, hit);
718
+ return { accessToken: hit.accessToken, connection };
719
+ }
720
+ let flight = flights.get(key);
721
+ if (!flight) {
722
+ const created = {
723
+ tenantId,
724
+ connectionId,
725
+ cancelled: false,
726
+ promise: Promise.resolve("")
727
+ };
728
+ created.promise = refresh(
729
+ tenantId,
730
+ connectionId,
731
+ connection,
732
+ () => created
733
+ ).finally(() => {
734
+ if (flights.get(key) === created) flights.delete(key);
735
+ });
736
+ flights.set(key, created);
737
+ flight = created;
738
+ }
739
+ return { accessToken: await flight.promise, connection };
740
+ },
741
+ prime(tenantId, connectionId, accessToken, expiresAt) {
742
+ remember({ tenantId, connectionId, accessToken, expiresAt });
743
+ },
744
+ evict(connectionId) {
745
+ evictWhere((e) => e.connectionId === connectionId);
746
+ },
747
+ evictTenant(tenantId) {
748
+ evictWhere((e) => e.tenantId === tenantId);
749
+ }
750
+ };
751
+ }
752
+
753
+ // src/core/connections.ts
754
+ var MAX_DISPLAY_NAME = 100;
755
+ function toView2(rec) {
756
+ const { refreshToken: _omit, ...view } = rec;
757
+ return view;
758
+ }
759
+ function sanitizeDisplayName(v) {
760
+ if (v === null) return null;
761
+ const s = v.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
762
+ return Array.from(s).slice(0, MAX_DISPLAY_NAME).join("").trim() || null;
763
+ }
764
+ function createConnectionsApi(deps) {
765
+ const load = async (tenantId, connectionId) => {
766
+ const rec = await deps.store.getConnection(tenantId, connectionId);
767
+ if (!rec) {
768
+ throw new ConnectionNotFoundError(void 0, { tenantId, connectionId });
769
+ }
770
+ return rec;
771
+ };
772
+ const warn = (msg) => {
773
+ try {
774
+ deps.logger?.warn(msg);
775
+ } catch {
776
+ }
777
+ };
778
+ return {
779
+ async list(tenantId) {
780
+ return (await deps.store.listConnections(tenantId)).map(toView2);
781
+ },
782
+ async get(tenantId, connectionId) {
783
+ return toView2(await load(tenantId, connectionId));
784
+ },
785
+ async disconnect({ tenantId, connectionId, actorId }) {
786
+ const rec = await load(tenantId, connectionId);
787
+ let googleRevoke = "ok";
788
+ if (rec.refreshToken) {
789
+ try {
790
+ const token = await decryptValue(
791
+ rec.refreshToken,
792
+ buildAad({
793
+ tenantId,
794
+ record: "connection",
795
+ recordId: rec.id,
796
+ field: "refresh_token"
797
+ }),
798
+ deps.keyProvider
799
+ );
800
+ await deps.gateway.revokeToken(token);
801
+ } catch {
802
+ googleRevoke = "failed";
803
+ warn("google token revoke failed");
804
+ }
805
+ }
806
+ const at = deps.now();
807
+ const found = await deps.store.disconnectConnection(
808
+ tenantId,
809
+ connectionId,
810
+ at
811
+ );
812
+ deps.tokens.evict(connectionId);
813
+ if (!found) {
814
+ throw new ConnectionNotFoundError(void 0, {
815
+ tenantId,
816
+ connectionId
817
+ });
818
+ }
819
+ await deps.emit({
820
+ type: "connection.disconnected",
821
+ tenantId,
822
+ actorId,
823
+ connectionId,
824
+ googleRevoke,
825
+ at
826
+ });
827
+ },
828
+ async setDisplayName({ tenantId, connectionId, displayName }) {
829
+ const found = await deps.store.setConnectionDisplayName(
830
+ tenantId,
831
+ connectionId,
832
+ sanitizeDisplayName(displayName),
833
+ deps.now()
834
+ );
835
+ if (!found) {
836
+ throw new ConnectionNotFoundError(void 0, {
837
+ tenantId,
838
+ connectionId
839
+ });
840
+ }
841
+ return toView2(await load(tenantId, connectionId));
842
+ }
843
+ };
844
+ }
845
+
846
+ // src/core/create-google.ts
847
+ var internals = /* @__PURE__ */ Symbol.for("mshindi-google.internals");
848
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
849
+ function assertCallbackUrl(raw) {
850
+ let u;
851
+ try {
852
+ u = new URL(raw);
853
+ } catch {
854
+ throw new InvalidConfigError("callbackUrl must be a valid URL");
855
+ }
856
+ const ok = u.protocol === "https:" || u.protocol === "http:" && LOCAL_HOSTS.has(u.hostname);
857
+ if (!ok) {
858
+ throw new InvalidConfigError(
859
+ "callbackUrl must use https (http is allowed only for localhost, 127.0.0.1 and [::1])"
860
+ );
861
+ }
862
+ }
863
+ function createGoogle(opts) {
864
+ assertCallbackUrl(opts.callbackUrl);
865
+ const now = opts.now ?? (() => /* @__PURE__ */ new Date());
866
+ const emit = createEmitter({
867
+ ...opts.onEvent ? { onEvent: opts.onEvent } : {},
868
+ store: opts.store,
869
+ ...opts.logger ? { logger: opts.logger } : {},
870
+ redactRecipients: opts.redactRecipients ?? false
871
+ });
872
+ const gateway = opts.oauthGateway ?? createGoogleAuthGateway();
873
+ const tokens = createTokenManager({
874
+ store: opts.store,
875
+ keyProvider: opts.keyProvider,
876
+ gateway,
877
+ emit,
878
+ now,
879
+ ...opts.logger ? { logger: opts.logger } : {}
880
+ });
881
+ const clients = createClientsApi({
882
+ store: opts.store,
883
+ keyProvider: opts.keyProvider,
884
+ emit,
885
+ now,
886
+ tokens: () => tokens
887
+ });
888
+ return {
889
+ clients,
890
+ oauth: {
891
+ createAuthUrl: (p) => createAuthUrl(
892
+ {
893
+ store: opts.store,
894
+ keyProvider: opts.keyProvider,
895
+ now,
896
+ callbackUrl: opts.callbackUrl
897
+ },
898
+ p
899
+ ),
900
+ handleCallback: (p) => handleCallback(
901
+ {
902
+ store: opts.store,
903
+ keyProvider: opts.keyProvider,
904
+ emit,
905
+ now,
906
+ callbackUrl: opts.callbackUrl,
907
+ gateway,
908
+ tokens,
909
+ ...opts.logger ? { logger: opts.logger } : {}
910
+ },
911
+ p
912
+ ),
913
+ purgeExpiredStates: () => opts.store.deleteExpiredOAuthStates(now())
914
+ },
915
+ connections: createConnectionsApi({
916
+ store: opts.store,
917
+ keyProvider: opts.keyProvider,
918
+ gateway,
919
+ tokens,
920
+ emit,
921
+ now,
922
+ ...opts.logger ? { logger: opts.logger } : {}
923
+ }),
924
+ [internals]: {
925
+ store: opts.store,
926
+ keyProvider: opts.keyProvider,
927
+ emit,
928
+ now,
929
+ callbackUrl: opts.callbackUrl,
930
+ ...opts.logger ? { logger: opts.logger } : {},
931
+ gateway,
932
+ tokens
933
+ }
934
+ };
935
+ }
936
+
937
+ export {
938
+ buildAad,
939
+ decryptValue,
940
+ rewrapValue,
941
+ BASE_SCOPES,
942
+ SERVICE_SCOPES,
943
+ scopesFor,
944
+ assertServiceScopes,
945
+ sanitizeDisplayName,
946
+ internals,
947
+ createGoogle
948
+ };
949
+ //# sourceMappingURL=chunk-SIDO26T7.js.map