@superdurable/connector-google-gmail 0.1.2 → 0.2.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.
package/dist/index.cjs CHANGED
@@ -74,6 +74,29 @@ var import_zod2 = require("zod");
74
74
  // src/generated/models.ts
75
75
  var import_zod = require("zod");
76
76
  var import_connectors_sdk = require("@superdurable/connectors-sdk");
77
+ var goTimeJSONPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
78
+ function isGoTimeJSON(value) {
79
+ const match = goTimeJSONPattern.exec(value);
80
+ if (!match) return false;
81
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText, , zone, , zoneHourText, zoneMinuteText] = match;
82
+ const year = Number(yearText);
83
+ const month = Number(monthText);
84
+ const day = Number(dayText);
85
+ const isLeap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
86
+ const monthDays = [31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
87
+ return month >= 1 && month <= 12 && day >= 1 && day <= monthDays[month - 1] && Number(hourText) <= 23 && Number(minuteText) <= 59 && Number(secondText) <= 59 && (zone === "Z" || Number(zoneHourText) <= 24 && Number(zoneMinuteText) <= 60);
88
+ }
89
+ function canonicalGoTimeJSON(value) {
90
+ const match = goTimeJSONPattern.exec(value);
91
+ const [, year, month, day, hour, minute, second, fraction, zone, sign, zoneHour, zoneMinute] = match;
92
+ const clock = year + "-" + month + "-" + day + "T" + hour.padStart(2, "0") + ":" + minute + ":" + second;
93
+ const digits = (fraction ?? "").slice(0, 9).replace(/0+$/, "");
94
+ const offsetMinutes = zone === "Z" ? 0 : (Number(zoneHour) * 60 + Number(zoneMinute)) * (sign === "+" ? 1 : -1);
95
+ if (Math.abs(offsetMinutes) >= 1440) return value;
96
+ const offset = offsetMinutes === 0 ? "Z" : (offsetMinutes > 0 ? "+" : "-") + String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0") + ":" + String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
97
+ return clock + (digits ? "." + digits : "") + offset;
98
+ }
99
+ var GoTimeJSONSchema = import_zod.z.string().refine(isGoTimeJSON, "invalid Go time.Time JSON timestamp").transform(canonicalGoTimeJSON);
77
100
  var ConfigSchema = import_zod.z.object({
78
101
  "endpoint": import_zod.z.string().optional(),
79
102
  "maxResponseBytes": import_zod.z.number().int().optional(),
@@ -81,6 +104,82 @@ var ConfigSchema = import_zod.z.object({
81
104
  "pollIntervalMs": import_zod.z.number().int().optional(),
82
105
  "pollPageSize": import_zod.z.number().int().optional()
83
106
  });
107
+ function decodeCredentials(value) {
108
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
109
+ const fields = value;
110
+ const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "primary_email", "refresh_token", "service_account_key"]);
111
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
112
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
113
+ if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
114
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
115
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
116
+ if (fields["primary_email"] != null && !(typeof fields["primary_email"] === "string")) throw new TypeError("credential primary_email has an invalid type");
117
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
118
+ if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
119
+ const selectedMethod = fields["auth_method"] ?? "";
120
+ if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
121
+ const method = selectedMethod || "google-oauth";
122
+ const credentials = { authMethodId: method };
123
+ if (method === "google-oauth") {
124
+ if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
125
+ if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
126
+ if (!fields["oauth_client_secret"]) throw new TypeError("credential oauth_client_secret is required");
127
+ if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new import_connectors_sdk.SecretString(fields["oauth_client_secret"]);
128
+ if (!fields["access_token"]) throw new TypeError("credential access_token is required");
129
+ if (fields["access_token"]) credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"]);
130
+ if (!fields["refresh_token"]) throw new TypeError("credential refresh_token is required");
131
+ if (fields["refresh_token"]) credentials.refreshToken = new import_connectors_sdk.SecretString(fields["refresh_token"]);
132
+ if (!fields["primary_email"]) throw new TypeError("credential primary_email is required");
133
+ if (fields["primary_email"]) credentials.primaryEmail = fields["primary_email"];
134
+ } else if (method === "workspace-domain-delegation") {
135
+ if (!fields["service_account_key"]) throw new TypeError("credential service_account_key is required");
136
+ if (fields["service_account_key"]) credentials.serviceAccountKey = new import_connectors_sdk.SecretString(fields["service_account_key"]);
137
+ if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
138
+ if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
139
+ credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"] ?? "");
140
+ credentials.primaryEmail = fields["primary_email"] ?? "";
141
+ } else {
142
+ throw new TypeError("credential auth_method is invalid");
143
+ }
144
+ return credentials;
145
+ }
146
+ function decodeSharedCredentials(value) {
147
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
148
+ const fields = value;
149
+ const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "delegated_user", "oauth_client_id", "oauth_client_secret", "primary_email", "refresh_token", "service_account_key"]);
150
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
151
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
152
+ if (fields["delegated_user"] != null && !(typeof fields["delegated_user"] === "string")) throw new TypeError("credential delegated_user has an invalid type");
153
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
154
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
155
+ if (fields["primary_email"] != null && !(typeof fields["primary_email"] === "string")) throw new TypeError("credential primary_email has an invalid type");
156
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
157
+ if (fields["service_account_key"] != null && !(typeof fields["service_account_key"] === "string")) throw new TypeError("credential service_account_key has an invalid type");
158
+ const selectedMethod = fields["auth_method"] ?? "";
159
+ if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
160
+ const method = selectedMethod || "google-oauth";
161
+ const credentials = { authMethodId: method };
162
+ if (method === "google-oauth") {
163
+ if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
164
+ if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
165
+ if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new import_connectors_sdk.SecretString(fields["oauth_client_secret"]);
166
+ if (!fields["access_token"]) throw new TypeError("credential access_token is required");
167
+ if (fields["access_token"]) credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"]);
168
+ if (fields["refresh_token"]) credentials.refreshToken = new import_connectors_sdk.SecretString(fields["refresh_token"]);
169
+ if (!fields["primary_email"]) throw new TypeError("credential primary_email is required");
170
+ if (fields["primary_email"]) credentials.primaryEmail = fields["primary_email"];
171
+ } else if (method === "workspace-domain-delegation") {
172
+ if (fields["service_account_key"]) credentials.serviceAccountKey = new import_connectors_sdk.SecretString(fields["service_account_key"]);
173
+ if (!fields["delegated_user"]) throw new TypeError("credential delegated_user is required");
174
+ if (fields["delegated_user"]) credentials.delegatedUser = fields["delegated_user"];
175
+ if (!fields["access_token"]) throw new TypeError("credential access_token is required");
176
+ credentials.accessToken = new import_connectors_sdk.SecretString(fields["access_token"] ?? "");
177
+ credentials.primaryEmail = fields["primary_email"] ?? "";
178
+ } else {
179
+ throw new TypeError("credential auth_method is invalid");
180
+ }
181
+ return credentials;
182
+ }
84
183
  var GetMessageInputSchema = import_zod.z.strictObject({
85
184
  "messageId": import_zod.z.string()
86
185
  });
@@ -97,7 +196,7 @@ var MessageSchema = import_zod.z.strictObject({
97
196
  "textBody": import_zod.z.string().optional(),
98
197
  "htmlBody": import_zod.z.string().optional(),
99
198
  "snippet": import_zod.z.string().optional(),
100
- "receivedAt": import_zod.z.iso.datetime({ offset: true }),
199
+ "receivedAt": GoTimeJSONSchema,
101
200
  "labelIds": import_zod.z.array(import_zod.z.string()).optional()
102
201
  });
103
202
  var SendMessageInputSchema = import_zod.z.strictObject({
@@ -557,74 +656,208 @@ function parseSentResponse(response) {
557
656
  // src/refresh.ts
558
657
  var import_connectors_sdk3 = require("@superdurable/connectors-sdk");
559
658
  var import_oauthtoken = require("@superdurable/connectors-sdk/oauthtoken");
560
- var import_zod5 = require("zod");
561
- var GoogleOAuthTokenEndpoint = "https://oauth2.googleapis.com/token";
562
- var RequiredGmailScopes = ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.send"];
563
- var TerminalErrorCodes = ["invalid_grant", "invalid_client", "unauthorized_client"];
564
- var ServiceAccountKeySchema = import_zod5.z.object({ client_email: import_zod5.z.string().min(1), private_key: import_zod5.z.string().min(1), token_uri: import_zod5.z.url() });
659
+
660
+ // src/generated/refresh.ts
661
+ var Authorization = {
662
+ "defaultMethod": "google-oauth",
663
+ "methods": [
664
+ {
665
+ "fields": [
666
+ {
667
+ "name": "oauth_client_id",
668
+ "required": true,
669
+ "type": "string"
670
+ },
671
+ {
672
+ "name": "oauth_client_secret",
673
+ "required": true,
674
+ "type": "secretString"
675
+ },
676
+ {
677
+ "name": "access_token",
678
+ "required": true,
679
+ "type": "secretString"
680
+ },
681
+ {
682
+ "name": "refresh_token",
683
+ "required": true,
684
+ "type": "secretString"
685
+ },
686
+ {
687
+ "name": "primary_email",
688
+ "required": true,
689
+ "type": "string"
690
+ }
691
+ ],
692
+ "id": "google-oauth",
693
+ "oauth2": {
694
+ "clientIDCredential": "oauth_client_id",
695
+ "clientSecretCredential": "oauth_client_secret",
696
+ "credentialMappings": [
697
+ {
698
+ "credential": "access_token",
699
+ "source": "access_token"
700
+ },
701
+ {
702
+ "credential": "refresh_token",
703
+ "source": "refresh_token"
704
+ }
705
+ ],
706
+ "refresh": {
707
+ "missingExpiry": "reject",
708
+ "requiredScopes": [
709
+ "https://www.googleapis.com/auth/gmail.readonly",
710
+ "https://www.googleapis.com/auth/gmail.send"
711
+ ],
712
+ "scopeSeparators": "whitespace",
713
+ "storedMissingExpiry": "refresh",
714
+ "terminalErrorCodes": [
715
+ "invalid_grant",
716
+ "invalid_client",
717
+ "unauthorized_client"
718
+ ],
719
+ "tokenExchangeTimeout": "25s"
720
+ },
721
+ "scopes": [
722
+ "openid",
723
+ "https://www.googleapis.com/auth/userinfo.email",
724
+ "https://www.googleapis.com/auth/gmail.readonly",
725
+ "https://www.googleapis.com/auth/gmail.send"
726
+ ],
727
+ "tokenEndpoint": "https://oauth2.googleapis.com/token"
728
+ },
729
+ "type": "oauth2"
730
+ },
731
+ {
732
+ "fields": [
733
+ {
734
+ "name": "service_account_key",
735
+ "required": true,
736
+ "type": "secretString"
737
+ },
738
+ {
739
+ "name": "delegated_user",
740
+ "required": true,
741
+ "type": "string"
742
+ },
743
+ {
744
+ "name": "access_token",
745
+ "required": false,
746
+ "type": "secretString"
747
+ },
748
+ {
749
+ "name": "primary_email",
750
+ "required": false,
751
+ "type": "string"
752
+ }
753
+ ],
754
+ "id": "workspace-domain-delegation",
755
+ "serviceAccount": {
756
+ "jwtBearer": {
757
+ "audience": {
758
+ "fromKey": "token_uri"
759
+ },
760
+ "credentialCopies": [
761
+ {
762
+ "credential": "primary_email",
763
+ "fromCredential": "delegated_user"
764
+ }
765
+ ],
766
+ "credentialMappings": [
767
+ {
768
+ "credential": "access_token",
769
+ "source": "access_token"
770
+ }
771
+ ],
772
+ "issuer": {
773
+ "fromKey": "client_email"
774
+ },
775
+ "keyCredential": "service_account_key",
776
+ "lifetime": "1h",
777
+ "missingExpiry": "reject",
778
+ "privateKey": {
779
+ "fromKey": "private_key"
780
+ },
781
+ "scopes": [
782
+ "https://www.googleapis.com/auth/gmail.readonly",
783
+ "https://www.googleapis.com/auth/gmail.send"
784
+ ],
785
+ "storedMissingExpiry": "refresh",
786
+ "subject": {
787
+ "fromCredential": "delegated_user"
788
+ },
789
+ "terminalErrorCodes": [
790
+ "invalid_grant",
791
+ "invalid_client",
792
+ "unauthorized_client"
793
+ ],
794
+ "tokenEndpoint": {
795
+ "fromKey": "token_uri"
796
+ }
797
+ }
798
+ },
799
+ "type": "serviceAccount"
800
+ }
801
+ ],
802
+ "refreshable": true
803
+ };
804
+ var CredentialFields = {
805
+ "access_token": "accessToken",
806
+ "delegated_user": "delegatedUser",
807
+ "oauth_client_id": "oauthClientId",
808
+ "oauth_client_secret": "oauthClientSecret",
809
+ "primary_email": "primaryEmail",
810
+ "refresh_token": "refreshToken",
811
+ "service_account_key": "serviceAccountKey"
812
+ };
813
+
814
+ // src/refresh.ts
565
815
  var GmailCredentialRefreshDriver = class {
566
- #fetch;
567
- #now;
568
- /** Inject the token request transport and clock for deterministic verification. */
816
+ #manifestDriver;
817
+ /** Inject the token transport and clock without transferring ownership. */
569
818
  constructor(fetchImplementation = fetch, now = () => /* @__PURE__ */ new Date()) {
570
819
  if (!fetchImplementation || !now) throw new TypeError("Gmail token transport and clock are required");
571
- this.#fetch = fetchImplementation;
572
- this.#now = now;
820
+ this.#manifestDriver = new import_oauthtoken.ManifestCredentialRefreshDriver({
821
+ providerName: "Google",
822
+ auth: Authorization,
823
+ credentialFields: CredentialFields,
824
+ fetch: fetchImplementation,
825
+ now
826
+ });
573
827
  }
574
- /** Refresh absent credentials or tokens whose expiry is within five minutes. */
828
+ /** Refresh absent credentials and tokens approaching expiry, including missing expiry. */
575
829
  refreshRequired(state) {
576
830
  return (0, import_oauthtoken.isRefreshRequired)(Boolean(state.credentials.accessToken.reveal()), state.expiresAt, state.now, "refresh");
577
831
  }
578
- /** Make one Google token exchange after the host admits and serializes refresh. */
832
+ /** Apply Gmail's method and delegated mailbox checks before the declared token exchange. */
579
833
  async refresh(state, signal) {
580
834
  const credentials = state.credentials;
581
- if (!credentials.authMethodId || credentials.authMethodId === GoogleOAuthAuthMethodID) {
582
- if (!credentials.oauthClientId || !credentials.oauthClientSecret || !credentials.refreshToken) throw new import_connectors_sdk3.ReauthorizationRequiredError();
583
- const token2 = await this.#tokenEndpoint(GoogleOAuthTokenEndpoint).exchangeRefreshToken({
584
- id: credentials.oauthClientId,
585
- secret: credentials.oauthClientSecret,
586
- authenticationMethod: "client_secret_post"
587
- }, credentials.refreshToken, signal);
588
- this.#verifyScopes(token2.scope);
589
- return {
590
- credentials: { ...credentials, accessToken: token2.accessToken, refreshToken: token2.nextRefreshToken(credentials.refreshToken) },
591
- expiresAt: new Date(this.#now().getTime() + token2.expiresInMs)
592
- };
593
- }
594
- if (credentials.authMethodId !== WorkspaceDomainDelegationAuthMethodID) throw new import_connectors_sdk3.ReauthorizationRequiredError();
835
+ const method = credentials.authMethodId || GoogleOAuthAuthMethodID;
836
+ if (method !== GoogleOAuthAuthMethodID && method !== WorkspaceDomainDelegationAuthMethodID)
837
+ throw new TypeError("Gmail authorization method is not supported");
838
+ if (method !== WorkspaceDomainDelegationAuthMethodID) return this.#manifestDriver.refresh(state, signal);
839
+ this.#validateServiceAccountKey(credentials.serviceAccountKey?.reveal() ?? "");
840
+ const delegatedUser = (credentials.delegatedUser ?? "").trim();
841
+ if (!delegatedUser || !delegatedUser.includes("@")) throw new import_connectors_sdk3.ReauthorizationRequiredError();
842
+ const result = await this.#manifestDriver.refresh({ ...state, credentials: { ...credentials, delegatedUser } }, signal);
843
+ return { ...result, credentials: { ...result.credentials, delegatedUser: credentials.delegatedUser } };
844
+ }
845
+ #validateServiceAccountKey(raw) {
595
846
  let key;
596
847
  try {
597
- key = ServiceAccountKeySchema.parse(JSON.parse(credentials.serviceAccountKey?.reveal() ?? ""));
848
+ const parsed = JSON.parse(raw);
849
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError();
850
+ key = parsed;
598
851
  } catch {
599
852
  throw new import_connectors_sdk3.ReauthorizationRequiredError();
600
853
  }
601
- const delegatedUser = credentials.delegatedUser;
602
- if (new URL(key.token_uri).protocol !== "https:" || !delegatedUser || !parseMailbox(delegatedUser)) throw new import_connectors_sdk3.ReauthorizationRequiredError();
603
- let assertion;
854
+ if (typeof key.client_email !== "string" || !key.client_email || typeof key.private_key !== "string" || !key.private_key || typeof key.token_uri !== "string" || !key.token_uri) throw new import_connectors_sdk3.ReauthorizationRequiredError();
604
855
  try {
605
- assertion = (0, import_oauthtoken.signJWTBearerAssertion)({
606
- issuer: key.client_email,
607
- subject: delegatedUser,
608
- audience: key.token_uri,
609
- scope: RequiredGmailScopes.join(" "),
610
- issuedAt: this.#now(),
611
- lifetimeMs: 36e5
612
- }, (0, import_oauthtoken.parseRSAPrivateKeyPEM)(key.private_key));
856
+ const endpoint = new URL(key.token_uri);
857
+ if (endpoint.protocol !== "https:" || !endpoint.hostname) throw new TypeError();
613
858
  } catch {
614
859
  throw new import_connectors_sdk3.ReauthorizationRequiredError();
615
860
  }
616
- const token = await this.#tokenEndpoint(key.token_uri).exchangeJWTBearerAssertion(assertion, signal);
617
- this.#verifyScopes(token.scope);
618
- return {
619
- credentials: { ...credentials, accessToken: token.accessToken, primaryEmail: credentials.delegatedUser ?? "" },
620
- expiresAt: new Date(this.#now().getTime() + token.expiresInMs)
621
- };
622
- }
623
- #tokenEndpoint(url) {
624
- return new import_oauthtoken.TokenEndpoint({ providerName: "Google", url, terminalErrorCodes: TerminalErrorCodes, fetch: this.#fetch });
625
- }
626
- #verifyScopes(scope) {
627
- if (scope && !(0, import_oauthtoken.hasAllScopes)(scope, RequiredGmailScopes)) throw new import_connectors_sdk3.ReauthorizationRequiredError();
628
861
  }
629
862
  };
630
863
 
@@ -878,7 +1111,7 @@ var GmailSender = class {
878
1111
  return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "TRANSPORT", `Gmail ${operation.requestName} request was not dispatched`));
879
1112
  }
880
1113
  if (error instanceof import_providerhttp2.BodyTooLargeError && error.status) return this.#classifySendStatus(call, fence, budget, credentials, operation, message, error.status, error.headers ?? {}, void 0);
881
- return this.#confirmPossiblySent(call, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
1114
+ return this.#confirmPossiblySent(call, fence, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
882
1115
  }
883
1116
  const receipt = this.#receipt(call, gmailRequestID(response.response.headers));
884
1117
  const isAccepted = response.response.status >= 200 && response.response.status < 300;
@@ -893,11 +1126,10 @@ var GmailSender = class {
893
1126
  }
894
1127
  if (status === 503) {
895
1128
  const lookup = await this.#pollSentMessage(call, budget, credentials);
896
- if (lookup.sent) return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent, receipt);
897
- await recordSafeResend(fence);
1129
+ if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
898
1130
  return retryAfterRefusal(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} is temporarily unavailable`, headers);
899
1131
  }
900
- if (status >= 500) return this.#confirmPossiblySent(call, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
1132
+ if (status >= 500) return this.#confirmPossiblySent(call, fence, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
901
1133
  if (status < 200 || status >= 300) {
902
1134
  if (call.context.attempt > 1) {
903
1135
  try {
@@ -910,16 +1142,21 @@ var GmailSender = class {
910
1142
  }
911
1143
  if (!sentResponse) {
912
1144
  const lookup = await this.#pollSentMessage(call, budget, credentials);
913
- return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent ?? { id: "", threadId: message.requestedThreadId }, receipt);
1145
+ if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
1146
+ return this.#sentMessage(call, budget, credentials, operation, message, { id: "", threadId: message.requestedThreadId }, receipt);
914
1147
  }
915
1148
  return this.#sentMessage(call, budget, credentials, operation, message, sentResponse, receipt);
916
1149
  }
917
- async #confirmPossiblySent(call, budget, credentials, operation, message, kind, reason, receipt) {
1150
+ async #confirmPossiblySent(call, fence, budget, credentials, operation, message, kind, reason, receipt) {
918
1151
  const lookup = await this.#pollSentMessage(call, budget, credentials);
919
- if (lookup.sent) return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent, receipt);
1152
+ if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
920
1153
  const suffix = lookup.hadError ? "the sent-mail search did not answer" : "the sent-mail search found no message";
921
1154
  return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, kind, `${reason}; ${suffix}`));
922
1155
  }
1156
+ async #sentAfterDispatch(call, fence, budget, credentials, operation, message, sent, receipt) {
1157
+ if (sent.id) await recordProviderIdentity(fence, sent.id);
1158
+ return this.#sentMessage(call, budget, credentials, operation, message, sent, receipt);
1159
+ }
923
1160
  async #sentMessage(call, budget, credentials, operation, message, sent, receipt) {
924
1161
  let threadId = sent.threadId;
925
1162
  if (!threadId && sent.id) {
@@ -1120,6 +1357,7 @@ var import_connectors_sdk7 = require("@superdurable/connectors-sdk");
1120
1357
 
1121
1358
  // src/generated/connection.ts
1122
1359
  var import_connectors_sdk6 = require("@superdurable/connectors-sdk");
1360
+ var import_projectconfig = require("@superdurable/connectors-sdk/projectconfig");
1123
1361
  var Connection = class {
1124
1362
  /** Stable provider and connection name. */
1125
1363
  reference;
@@ -1133,6 +1371,9 @@ var Connection = class {
1133
1371
  this.operations = operations;
1134
1372
  }
1135
1373
  };
1374
+ function newProjectCredentialProvider(project, connectionName, decode, encode, decodeShared) {
1375
+ return (0, import_projectconfig.newRefreshingCredentialProvider)(project.connections, { connectorId: ConnectorID2, connectionName }, decode, encode, decodeShared);
1376
+ }
1136
1377
 
1137
1378
  // src/connection.ts
1138
1379
  var GmailConnection = class extends Connection {
@@ -1147,27 +1388,15 @@ var GmailConnection = class extends Connection {
1147
1388
 
1148
1389
  // src/project.ts
1149
1390
  var import_connectors_sdk9 = require("@superdurable/connectors-sdk");
1150
- var import_projectconfig = require("@superdurable/connectors-sdk/projectconfig");
1151
- var import_zod7 = require("zod");
1391
+ var import_zod5 = require("zod");
1152
1392
 
1153
1393
  // src/credential_codec.ts
1154
1394
  var import_connectors_sdk8 = require("@superdurable/connectors-sdk");
1155
- var import_zod6 = require("zod");
1156
- var StoredCredentialsSchema = import_zod6.z.object({
1157
- auth_method: import_zod6.z.string().optional(),
1158
- oauth_client_id: import_zod6.z.string().optional(),
1159
- oauth_client_secret: import_zod6.z.string().optional(),
1160
- access_token: import_zod6.z.string().optional(),
1161
- refresh_token: import_zod6.z.string().optional(),
1162
- primary_email: import_zod6.z.string().optional(),
1163
- service_account_key: import_zod6.z.string().optional(),
1164
- delegated_user: import_zod6.z.string().optional()
1165
- });
1166
1395
  function decodeGmailCredentials(value) {
1167
- return decodeCredentialFields(value, false);
1396
+ return completeCredentials(decodeGmailFields(value, false));
1168
1397
  }
1169
1398
  function decodeGmailSharedCredentials(value) {
1170
- return decodeCredentialFields(value, true);
1399
+ return completeCredentials(decodeGmailFields(value, true));
1171
1400
  }
1172
1401
  function encodeGmailCredentials(credentials) {
1173
1402
  const fields = { auth_method: credentials.authMethodId ?? GoogleOAuthAuthMethodID };
@@ -1182,39 +1411,39 @@ function encodeGmailCredentials(credentials) {
1182
1411
  ]) if (value) fields[name] = value;
1183
1412
  return fields;
1184
1413
  }
1185
- function decodeCredentialFields(value, isShared) {
1186
- const fields = StoredCredentialsSchema.safeParse(value);
1187
- if (!fields.success) throw new TypeError("Gmail credential fields are invalid");
1188
- const stored = fields.data;
1189
- const credentials = {
1190
- authMethodId: stored.auth_method || GoogleOAuthAuthMethodID,
1191
- oauthClientId: stored.oauth_client_id ?? "",
1192
- oauthClientSecret: new import_connectors_sdk8.SecretString(stored.oauth_client_secret ?? ""),
1193
- accessToken: new import_connectors_sdk8.SecretString(stored.access_token ?? ""),
1194
- refreshToken: new import_connectors_sdk8.SecretString(stored.refresh_token ?? ""),
1195
- primaryEmail: stored.primary_email ?? "",
1196
- serviceAccountKey: new import_connectors_sdk8.SecretString(stored.service_account_key ?? ""),
1197
- delegatedUser: stored.delegated_user ?? ""
1414
+ function completeCredentials(decoded) {
1415
+ return {
1416
+ authMethodId: decoded.authMethodId ?? GoogleOAuthAuthMethodID,
1417
+ oauthClientId: decoded.oauthClientId ?? "",
1418
+ oauthClientSecret: decoded.oauthClientSecret ?? new import_connectors_sdk8.SecretString(""),
1419
+ accessToken: decoded.accessToken ?? new import_connectors_sdk8.SecretString(""),
1420
+ refreshToken: decoded.refreshToken ?? new import_connectors_sdk8.SecretString(""),
1421
+ primaryEmail: decoded.primaryEmail ?? "",
1422
+ serviceAccountKey: decoded.serviceAccountKey ?? new import_connectors_sdk8.SecretString(""),
1423
+ delegatedUser: decoded.delegatedUser ?? ""
1198
1424
  };
1199
- if (credentials.authMethodId === GoogleOAuthAuthMethodID) {
1200
- if (!credentials.oauthClientId || !credentials.primaryEmail || !isShared && (!credentials.oauthClientSecret?.reveal() || !credentials.refreshToken?.reveal()) || !credentials.accessToken.reveal()) {
1201
- throw new TypeError("Gmail OAuth connection credentials are incomplete");
1202
- }
1203
- } else if (credentials.authMethodId === WorkspaceDomainDelegationAuthMethodID) {
1204
- if (!credentials.delegatedUser || (isShared ? !credentials.accessToken.reveal() : !credentials.serviceAccountKey?.reveal())) {
1205
- throw new TypeError("Gmail Workspace connection credentials are incomplete");
1425
+ }
1426
+ function decodeGmailFields(value, isShared) {
1427
+ try {
1428
+ return isShared ? decodeSharedCredentials(value) : decodeCredentials(value);
1429
+ } catch (error) {
1430
+ const message = error instanceof Error ? error.message : "";
1431
+ if (message.includes("is required")) {
1432
+ const method = value && typeof value === "object" && "auth_method" in value ? value.auth_method : "";
1433
+ throw new TypeError(method === "workspace-domain-delegation" ? "Gmail Workspace connection credentials are incomplete" : "Gmail OAuth connection credentials are incomplete");
1206
1434
  }
1207
- } else throw new TypeError("Gmail authorization method is invalid");
1208
- return credentials;
1435
+ if (message.includes("auth_method is invalid")) throw new TypeError("Gmail authorization method is invalid");
1436
+ throw new TypeError("Gmail credential fields are invalid");
1437
+ }
1209
1438
  }
1210
1439
 
1211
1440
  // src/project.ts
1212
- var ProjectGmailConfigurationSchema = import_zod7.z.object({
1213
- endpoint: import_zod7.z.string().optional(),
1214
- maxResponseBytes: import_zod7.z.number().int().safe().optional(),
1215
- maxMessageBytes: import_zod7.z.number().int().safe().optional(),
1216
- pollInterval: import_zod7.z.number().int().safe().optional(),
1217
- pollPageSize: import_zod7.z.number().int().safe().optional()
1441
+ var ProjectGmailConfigurationSchema = import_zod5.z.object({
1442
+ endpoint: import_zod5.z.string().optional(),
1443
+ maxResponseBytes: import_zod5.z.number().int().safe().optional(),
1444
+ maxMessageBytes: import_zod5.z.number().int().safe().optional(),
1445
+ pollInterval: import_zod5.z.number().int().safe().optional(),
1446
+ pollPageSize: import_zod5.z.number().int().safe().optional()
1218
1447
  });
1219
1448
  function newProjectConnection(project, connectionName, options = {}) {
1220
1449
  return new GmailConnection(newProjectGmailClient(project, connectionName, options), { provider: ProviderID, name: connectionName });
@@ -1233,7 +1462,7 @@ function newProjectGmailClient(project, connectionName, options = {}) {
1233
1462
  ...fields.pollInterval ? { pollIntervalMs: Math.ceil(fields.pollInterval / 1e6) } : {},
1234
1463
  ...fields.pollPageSize ? { pollPageSize: fields.pollPageSize } : {}
1235
1464
  };
1236
- const provider = (0, import_projectconfig.newRefreshingCredentialProvider)(project.connections, { connectorId: ConnectorID, connectionName }, decodeGmailCredentials, encodeGmailCredentials, decodeGmailSharedCredentials);
1465
+ const provider = newProjectCredentialProvider(project, connectionName, decodeGmailCredentials, encodeGmailCredentials, decodeGmailSharedCredentials);
1237
1466
  return new GmailClient(config, provider, options);
1238
1467
  }
1239
1468
 
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as Message, R as ReplyToMessageInput, S as SendMessageInput, C as Config, a as CredentialSource, b as Credentials, c as SendMessageOutput, G as GetMessageInput, d as GmailOperations, e as GmailConnection } from './connection-NE_da2Az.cjs';
2
- export { f as ConnectorID, g as GetMessageInputSchema, h as GoogleOAuthAuthMethodID, i as MessageSchema, P as ProviderID, j as ReplyToMessageInputSchema, k as SendMessageInputSchema, l as SendMessageOutputSchema, W as WorkspaceDomainDelegationAuthMethodID } from './connection-NE_da2Az.cjs';
1
+ import { M as Message, R as ReplyToMessageInput, S as SendMessageInput, C as Config, a as CredentialSource, b as Credentials, c as SendMessageOutput, G as GetMessageInput, d as GmailOperations, e as GmailConnection } from './connection-D8OV_Hfe.cjs';
2
+ export { f as ConnectorID, g as GetMessageInputSchema, h as GoogleOAuthAuthMethodID, i as MessageSchema, P as ProviderID, j as ReplyToMessageInputSchema, k as SendMessageInputSchema, l as SendMessageOutputSchema, W as WorkspaceDomainDelegationAuthMethodID } from './connection-D8OV_Hfe.cjs';
3
3
  import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
4
4
  import { QueryDefinition, MutationDefinition, CredentialRefreshDriver, Call, FailureKind, CredentialRefreshState, CredentialRefreshResult, Mutation, MutationAttempt, Query, QueryAttempt, Failure, ReceiptDraft, QueryStepConfig, QueryResult, MutationStepConfig, MutationResult, QueryStep, MutationStep } from '@superdurable/connectors-sdk';
5
5
  import { z } from 'zod';
@@ -149,14 +149,14 @@ declare class GmailProvider {
149
149
  /** Parse one accepted Gmail send response. */
150
150
  declare function parseSentResponse(response: ProviderResponse): SentMessageIdentity | undefined;
151
151
 
152
- /** Refresh Gmail OAuth or Workspace delegation credentials without owning persistence. */
152
+ /** Refresh Gmail credentials using generated grant declarations and Google-specific validation. */
153
153
  declare class GmailCredentialRefreshDriver implements CredentialRefreshDriver<Credentials> {
154
154
  #private;
155
- /** Inject the token request transport and clock for deterministic verification. */
155
+ /** Inject the token transport and clock without transferring ownership. */
156
156
  constructor(fetchImplementation?: typeof fetch, now?: () => Date);
157
- /** Refresh absent credentials or tokens whose expiry is within five minutes. */
157
+ /** Refresh absent credentials and tokens approaching expiry, including missing expiry. */
158
158
  refreshRequired(state: CredentialRefreshState<Credentials>): boolean;
159
- /** Make one Google token exchange after the host admits and serializes refresh. */
159
+ /** Apply Gmail's method and delegated mailbox checks before the declared token exchange. */
160
160
  refresh(state: CredentialRefreshState<Credentials>, signal: AbortSignal): Promise<CredentialRefreshResult<Credentials>>;
161
161
  }
162
162
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as Message, R as ReplyToMessageInput, S as SendMessageInput, C as Config, a as CredentialSource, b as Credentials, c as SendMessageOutput, G as GetMessageInput, d as GmailOperations, e as GmailConnection } from './connection-NE_da2Az.js';
2
- export { f as ConnectorID, g as GetMessageInputSchema, h as GoogleOAuthAuthMethodID, i as MessageSchema, P as ProviderID, j as ReplyToMessageInputSchema, k as SendMessageInputSchema, l as SendMessageOutputSchema, W as WorkspaceDomainDelegationAuthMethodID } from './connection-NE_da2Az.js';
1
+ import { M as Message, R as ReplyToMessageInput, S as SendMessageInput, C as Config, a as CredentialSource, b as Credentials, c as SendMessageOutput, G as GetMessageInput, d as GmailOperations, e as GmailConnection } from './connection-D8OV_Hfe.js';
2
+ export { f as ConnectorID, g as GetMessageInputSchema, h as GoogleOAuthAuthMethodID, i as MessageSchema, P as ProviderID, j as ReplyToMessageInputSchema, k as SendMessageInputSchema, l as SendMessageOutputSchema, W as WorkspaceDomainDelegationAuthMethodID } from './connection-D8OV_Hfe.js';
3
3
  import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
4
4
  import { QueryDefinition, MutationDefinition, CredentialRefreshDriver, Call, FailureKind, CredentialRefreshState, CredentialRefreshResult, Mutation, MutationAttempt, Query, QueryAttempt, Failure, ReceiptDraft, QueryStepConfig, QueryResult, MutationStepConfig, MutationResult, QueryStep, MutationStep } from '@superdurable/connectors-sdk';
5
5
  import { z } from 'zod';
@@ -149,14 +149,14 @@ declare class GmailProvider {
149
149
  /** Parse one accepted Gmail send response. */
150
150
  declare function parseSentResponse(response: ProviderResponse): SentMessageIdentity | undefined;
151
151
 
152
- /** Refresh Gmail OAuth or Workspace delegation credentials without owning persistence. */
152
+ /** Refresh Gmail credentials using generated grant declarations and Google-specific validation. */
153
153
  declare class GmailCredentialRefreshDriver implements CredentialRefreshDriver<Credentials> {
154
154
  #private;
155
- /** Inject the token request transport and clock for deterministic verification. */
155
+ /** Inject the token transport and clock without transferring ownership. */
156
156
  constructor(fetchImplementation?: typeof fetch, now?: () => Date);
157
- /** Refresh absent credentials or tokens whose expiry is within five minutes. */
157
+ /** Refresh absent credentials and tokens approaching expiry, including missing expiry. */
158
158
  refreshRequired(state: CredentialRefreshState<Credentials>): boolean;
159
- /** Make one Google token exchange after the host admits and serializes refresh. */
159
+ /** Apply Gmail's method and delegated mailbox checks before the declared token exchange. */
160
160
  refresh(state: CredentialRefreshState<Credentials>, signal: AbortSignal): Promise<CredentialRefreshResult<Credentials>>;
161
161
  }
162
162
 
package/dist/index.js CHANGED
@@ -44,7 +44,7 @@ import {
44
44
  rfcMessageIDAddress,
45
45
  statusFailureKind,
46
46
  validateSendInput
47
- } from "./chunk-IAO6TPJ3.js";
47
+ } from "./chunk-KVNIQW5Y.js";
48
48
  export {
49
49
  ConnectorID,
50
50
  GetMessageBranch,