@mastra/auth-workos 1.6.3-alpha.0 → 1.6.4-alpha.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.
package/dist/index.js CHANGED
@@ -155,7 +155,7 @@ var MastraBase = class {
155
155
  }
156
156
  };
157
157
 
158
- // ../../packages/_internals/auth/dist/chunk-7GLKLOU3.js
158
+ // ../../packages/_internals/auth/dist/chunk-NJOKT6V5.js
159
159
  var MastraAuthProvider = class extends MastraBase {
160
160
  protected;
161
161
  public;
@@ -238,6 +238,20 @@ function getWebRequest(request) {
238
238
  var DEV_COOKIE_PASSWORD = crypto.randomUUID() + crypto.randomUUID();
239
239
  var MEMBERSHIP_CACHE_TTL_MS = 60 * 1e3;
240
240
  var MEMBERSHIP_CACHE_MAX_SIZE = 1e3;
241
+ function workosErrorCode(error) {
242
+ if (!error || typeof error !== "object") return void 0;
243
+ const e = error;
244
+ if (typeof e.code === "string") return e.code;
245
+ if (e.rawData && typeof e.rawData.code === "string") return e.rawData.code;
246
+ return void 0;
247
+ }
248
+ function isExternalIdAlreadyUsed(error) {
249
+ return workosErrorCode(error) === "external_id_already_used";
250
+ }
251
+ function isMembershipAlreadyExists(error) {
252
+ const code = workosErrorCode(error);
253
+ return code === "organization_membership_already_exists" || code === "entity_already_exists";
254
+ }
241
255
  var MastraAuthWorkos = class extends MastraAuthProvider {
242
256
  workos;
243
257
  clientId;
@@ -254,18 +268,13 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
254
268
  super({ name: options?.name ?? "workos" });
255
269
  const apiKey = options?.apiKey ?? process.env.WORKOS_API_KEY;
256
270
  const clientId = options?.clientId ?? process.env.WORKOS_CLIENT_ID;
257
- const redirectUri = options?.redirectUri ?? process.env.WORKOS_REDIRECT_URI;
271
+ const redirectUri = options?.redirectUri ?? process.env.WORKOS_REDIRECT_URI ?? "";
258
272
  const cookiePassword = options?.session?.cookiePassword ?? process.env.WORKOS_COOKIE_PASSWORD ?? DEV_COOKIE_PASSWORD;
259
273
  if (!apiKey || !clientId) {
260
274
  throw new Error(
261
275
  "WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables."
262
276
  );
263
277
  }
264
- if (!redirectUri) {
265
- throw new Error(
266
- "WorkOS redirect URI is required. Provide it in the options or set WORKOS_REDIRECT_URI environment variable."
267
- );
268
- }
269
278
  if (cookiePassword.length < 32) {
270
279
  throw new Error(
271
280
  "Cookie password must be at least 32 characters. Set WORKOS_COOKIE_PASSWORD environment variable or provide session.cookiePassword option."
@@ -562,9 +571,15 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
562
571
  * Get the URL to redirect users to for SSO login.
563
572
  */
564
573
  getLoginUrl(redirectUri, state) {
574
+ const resolvedRedirectUri = redirectUri || this.redirectUri;
575
+ if (!resolvedRedirectUri) {
576
+ throw new Error(
577
+ "WorkOS redirect URI is required. Provide it in the options, set the WORKOS_REDIRECT_URI environment variable, or call init() with a publicUrl."
578
+ );
579
+ }
565
580
  const baseOptions = {
566
581
  clientId: this.clientId,
567
- redirectUri: redirectUri || this.redirectUri,
582
+ redirectUri: resolvedRedirectUri,
568
583
  state
569
584
  };
570
585
  if (this.ssoConfig?.connection) {
@@ -757,6 +772,105 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
757
772
  return { "Set-Cookie": cookieParts.join("; ") };
758
773
  }
759
774
  // ============================================================================
775
+ // IAuthInit Implementation
776
+ // ============================================================================
777
+ /**
778
+ * One-time host initialization. Resolves the redirect URI from the host's
779
+ * `publicUrl` (`<publicUrl>/auth/callback`) when it was not provided in the
780
+ * options or via `WORKOS_REDIRECT_URI`.
781
+ *
782
+ * Fails at prepare time rather than handing WorkOS an empty redirect URI on
783
+ * the first login (which breaks hosted login with an opaque provider error).
784
+ */
785
+ async init(ctx) {
786
+ if (!this.redirectUri && ctx.publicUrl) {
787
+ this.redirectUri = `${ctx.publicUrl}/auth/callback`;
788
+ this.config.redirectUri = this.redirectUri;
789
+ const storage = new WebSessionStorage(this.config);
790
+ this.authService = new AuthService(this.config, storage, this.workos, sessionEncryption);
791
+ }
792
+ if (!this.redirectUri) {
793
+ throw new Error(
794
+ "MastraAuthWorkos could not resolve a callback URL: pass `redirectUri` (WORKOS_REDIRECT_URI) or configure the host `publicUrl`."
795
+ );
796
+ }
797
+ }
798
+ // ============================================================================
799
+ // IOrganizationsProvider Implementation
800
+ // ============================================================================
801
+ /**
802
+ * Ensure the user belongs to a WorkOS organization, creating a personal org
803
+ * on first use when they have none.
804
+ *
805
+ * - ≥1 membership → return the first org id (they already belong somewhere;
806
+ * we never auto-create when a membership exists).
807
+ * - 0 memberships → create a personal org + membership and return its id.
808
+ *
809
+ * Idempotency: the create call carries `externalId = userId` and a stable
810
+ * `idempotencyKey`, so concurrent/retried first logins never create duplicate
811
+ * personal orgs. If a prior run created the org but never attached the
812
+ * membership, the create rejects with `external_id_already_used`; we recover
813
+ * the existing org by `externalId` and (re)attach the membership instead of
814
+ * failing.
815
+ *
816
+ * Best-effort: any WorkOS error (e.g. API key lacking org-create permission)
817
+ * is swallowed and returns `undefined`, leaving the user in their no-org
818
+ * state rather than failing the request.
819
+ */
820
+ async ensureOrganization(userId) {
821
+ try {
822
+ const memberships = await this.workos.userManagement.listOrganizationMemberships({ userId }).then((page) => page.autoPagination());
823
+ const firstExisting = memberships.find((m) => m.organizationId)?.organizationId;
824
+ if (firstExisting) return firstExisting;
825
+ const profile = await this.workos.userManagement.getUser(userId).catch(() => null);
826
+ const label = profile?.email ?? userId;
827
+ let organizationId;
828
+ try {
829
+ const organization = await this.workos.organizations.createOrganization(
830
+ {
831
+ name: `${label}'s org`,
832
+ externalId: userId,
833
+ metadata: { mastraPersonalOrg: "true", workosUserId: userId }
834
+ },
835
+ { idempotencyKey: `mastra-personal-org:${userId}` }
836
+ );
837
+ organizationId = organization.id;
838
+ } catch (error) {
839
+ if (!isExternalIdAlreadyUsed(error)) throw error;
840
+ const existing = await this.workos.organizations.getOrganizationByExternalId(userId);
841
+ organizationId = existing.id;
842
+ }
843
+ try {
844
+ await this.workos.userManagement.createOrganizationMembership({ organizationId, userId });
845
+ } catch (error) {
846
+ if (!isMembershipAlreadyExists(error)) throw error;
847
+ }
848
+ this.membershipCache.delete(userId);
849
+ return organizationId;
850
+ } catch (error) {
851
+ console.warn(
852
+ `[WorkOS] Failed to bootstrap personal organization for user ${userId}. The user will see organization_required until this succeeds. Ensure the WorkOS API key can create organizations/memberships.`,
853
+ error
854
+ );
855
+ return void 0;
856
+ }
857
+ }
858
+ /**
859
+ * Whether the user holds an admin-equivalent role (`admin` or `owner`) in
860
+ * the organization. Provider errors resolve to `false`.
861
+ */
862
+ async isOrganizationAdmin(organizationId, userId) {
863
+ try {
864
+ const memberships = await this.workos.userManagement.listOrganizationMemberships({ userId }).then((page) => page.autoPagination());
865
+ const membership = memberships.find((item) => item.organizationId === organizationId);
866
+ if (!membership) return false;
867
+ const slugs = membership.roles?.length ? membership.roles.map((role) => role.slug) : [membership.role.slug];
868
+ return slugs.some((slug) => slug === "admin" || slug === "owner");
869
+ } catch {
870
+ return false;
871
+ }
872
+ }
873
+ // ============================================================================
760
874
  // Helper Methods
761
875
  // ============================================================================
762
876
  /**
@@ -785,7 +899,7 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
785
899
  }
786
900
  };
787
901
 
788
- // ../../packages/_internals/auth/dist/chunk-H3EJ4GVJ.js
902
+ // ../../packages/_internals/auth/dist/chunk-LZCWL5CT.js
789
903
  var FGADeniedError = class extends Error {
790
904
  user;
791
905
  resource;