@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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @mastra/auth-workos
2
2
 
3
+ ## 1.6.4-alpha.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Added organization management and host integration to MastraAuthWorkos so it can be passed directly to a server host without a wrapper adapter. The provider now bootstraps a personal organization for new users (ensureOrganization), checks organization admin roles (isOrganizationAdmin), and resolves its redirect URI from the host public URL during init when not configured explicitly. ([#19765](https://github.com/mastra-ai/mastra/pull/19765))
8
+
9
+ ## 1.6.3
10
+
11
+ ### Patch Changes
12
+
13
+ - Added `mapUserToResourceId` to `MastraAuthWorkosOptions` so it can be set directly in the `MastraAuthWorkos` constructor. This maps an authenticated user to a resource id that multi-tenant tool providers use to bucket connected accounts (for example, Composio's `caller-supplied` scope). Previously the option was consumed at runtime but missing from the typed constructor surface, forcing a post-construction property assignment. ([#19144](https://github.com/mastra-ai/mastra/pull/19144))
14
+
3
15
  ## 1.6.3-alpha.0
4
16
 
5
17
  ### Patch Changes
@@ -319,9 +331,7 @@
319
331
  ```typescript
320
332
  import { MastraRBACWorkos } from '@mastra/auth-workos';
321
333
 
322
- const rbac = new MastraRBACWorkos({
323
- /* config */
324
- });
334
+ const rbac = new MastraRBACWorkos({/* config */});
325
335
 
326
336
  // List all available roles
327
337
  const roles = await rbac.getAvailableRoles();
@@ -347,9 +357,7 @@
347
357
  ```typescript
348
358
  import { MastraRBACWorkos } from '@mastra/auth-workos';
349
359
 
350
- const rbac = new MastraRBACWorkos({
351
- /* config */
352
- });
360
+ const rbac = new MastraRBACWorkos({/* config */});
353
361
 
354
362
  // List all available roles
355
363
  const roles = await rbac.getAvailableRoles();
@@ -3,12 +3,9 @@
3
3
  *
4
4
  * @license Mastra Enterprise License - see ee/LICENSE
5
5
  */
6
- import type { FGACheckContext, IFGAProvider } from './interfaces/fga.js';
6
+ import type { ActorSignal, FGACheckContext, IFGAProvider } from './interfaces/fga.js';
7
7
  import type { MastraFGAPermissionInput } from './interfaces/permissions.generated.js';
8
- export type ActorSignal = true | {
9
- actorKind: 'system';
10
- sourceWorkflow?: string;
11
- };
8
+ export type { ActorSignal };
12
9
  export interface CheckFGAOptions {
13
10
  fgaProvider: IFGAProvider | undefined;
14
11
  user: any;
@@ -8,6 +8,34 @@
8
8
  * @license Mastra Enterprise License - see ee/LICENSE
9
9
  */
10
10
  import type { MastraFGAPermissionInput } from './permissions.generated.js';
11
+ /**
12
+ * Signals that a call is made by a trusted non-user actor rather than an
13
+ * authenticated end user.
14
+ *
15
+ * - `true` is the anonymous system shorthand.
16
+ * - The object form additionally names the acting agent (`agentId`) and carries
17
+ * the permission grants / scope a provider can enforce for least privilege.
18
+ */
19
+ export type ActorSignal = true | {
20
+ actorKind: 'system';
21
+ sourceWorkflow?: string;
22
+ /**
23
+ * Identity of the acting system agent. Unlike the check `resource` (the
24
+ * target), this names the actor itself so a provider can enforce
25
+ * per-agent least privilege.
26
+ */
27
+ agentId?: string;
28
+ /**
29
+ * Permission grants *claimed* for this actor — the actor analog of a
30
+ * user's resolved permissions. This is an untrusted, self-asserted hint:
31
+ * a provider enforcing real least privilege should resolve the actor's
32
+ * authoritative grants from a trusted source (e.g. a manifest or FGA,
33
+ * keyed by `agentId`) rather than trusting these values directly.
34
+ */
35
+ permissions?: MastraFGAPermissionInput[];
36
+ /** Additional provider-specific scope for the actor (e.g. tenant, environment). */
37
+ scope?: Record<string, string>;
38
+ };
11
39
  /**
12
40
  * Optional context for an authorization check.
13
41
  */
@@ -306,6 +334,25 @@ export interface IFGAProvider<TUser = unknown> {
306
334
  filterAccessible<T extends {
307
335
  id: string;
308
336
  }>(user: TUser, resources: T[], resourceType: string, permission: MastraFGAPermissionInput): Promise<T[]>;
337
+ /**
338
+ * Authorize a non-user (system / autonomous agent) actor.
339
+ *
340
+ * System actors bypass the user-centric `require()` path. Implement this
341
+ * method to opt in to provider-driven least privilege for those actors:
342
+ * decide whether the actor (identified by `actor.agentId` and constrained by
343
+ * `actor.permissions` / `actor.scope`) may perform `permission` on
344
+ * `resource`, and throw {@link FGADeniedError} to deny.
345
+ *
346
+ * When this method is not implemented, Mastra preserves the legacy
347
+ * trusted-actor bypass (allow after the tenant-scope check). Adding it is
348
+ * therefore fully backward compatible.
349
+ *
350
+ * @param actor - The system actor signal (`true` shorthand, or an object with
351
+ * `agentId`, `permissions`, `scope`).
352
+ * @param params - The resource and permission being attempted.
353
+ * @throws FGADeniedError if the actor may not perform the action.
354
+ */
355
+ requireActor?(actor: ActorSignal, params: FGACheckParams): Promise<void>;
309
356
  }
310
357
  /**
311
358
  * Extended FGA interface with write operations for managing resources and role assignments.
@@ -270,6 +270,72 @@ export interface ICredentialsProvider<TUser extends User = User> {
270
270
  */
271
271
  isSignUpEnabled?(): boolean;
272
272
  }
273
+ /**
274
+ * Provider interface for organization membership management.
275
+ *
276
+ * Implement this interface to enable multi-tenant hosts (e.g. the Mastra Code
277
+ * web factory) to bootstrap a personal organization for new users and to
278
+ * authorize organization-level administrative mutations.
279
+ */
280
+ export interface IOrganizationsProvider {
281
+ /**
282
+ * Ensure the user belongs to an organization, bootstrapping a personal org
283
+ * on first use when they have none. Must be idempotent under
284
+ * concurrent/retried first logins.
285
+ *
286
+ * @param userId - Stable provider user id
287
+ * @returns The organization id, or `undefined` when the user genuinely
288
+ * stays no-org (bootstrap is best-effort)
289
+ */
290
+ ensureOrganization(userId: string): Promise<string | undefined>;
291
+ /**
292
+ * Whether the user holds an admin-equivalent role in the organization.
293
+ * Provider errors should resolve to `false` rather than throw.
294
+ *
295
+ * @param organizationId - Organization id
296
+ * @param userId - Stable provider user id
297
+ */
298
+ isOrganizationAdmin(organizationId: string, userId: string): Promise<boolean>;
299
+ }
300
+ /**
301
+ * Host-level context handed to {@link IAuthInit.init} once during server
302
+ * preparation. Storage-agnostic: hosts pass whatever database handle their
303
+ * storage backend exposes.
304
+ */
305
+ export interface AuthInitContext {
306
+ /**
307
+ * Database handle for providers that persist their own auth tables
308
+ * (e.g. better-auth). Shape is provider-defined; hosts pass their storage
309
+ * backend's auth database as-is.
310
+ */
311
+ database?: unknown;
312
+ /** Browser-facing origin (no trailing slash), e.g. `https://factory.acme.com`. */
313
+ publicUrl?: string;
314
+ /**
315
+ * Extra browser origins allowed to talk to the API (cross-origin SPA
316
+ * deploys). Providers that enforce their own origin allow-list (e.g.
317
+ * better-auth `trustedOrigins`) must honor these.
318
+ */
319
+ allowedOrigins?: string[];
320
+ }
321
+ /**
322
+ * Optional one-time initialization hook for auth providers. Hosts call
323
+ * `init()` once during preparation with host-level context (database, public
324
+ * origin) so providers can consume it without the deploy entry passing it
325
+ * twice. Providers should fail fast here for requirements only satisfiable at
326
+ * prepare time.
327
+ */
328
+ export interface IAuthInit {
329
+ init(ctx: AuthInitContext): Promise<void>;
330
+ }
331
+ /**
332
+ * Provider interface for handling raw auth HTTP requests. Providers that ship
333
+ * their own HTTP API surface (e.g. better-auth's `/api/auth/*` handler)
334
+ * implement this so hosts can mount it (typically under `/auth/api/*`).
335
+ */
336
+ export interface IAuthHttpHandler {
337
+ handleAuthRequest(request: Request): Promise<Response>;
338
+ }
273
339
  export * from './session/index.js';
274
340
  export * from './provider/index.js';
275
341
  export * from './types/index.js';
@@ -1,5 +1,5 @@
1
1
  import { MastraBase } from '../_types/@internal_core/dist/base/index.d.ts';
2
- import type { CredentialsResult, ISSOProvider, ISessionProvider, IUserProvider, Session, SSOCallbackResult, SSOLoginConfig, User } from '..';
2
+ import type { CredentialsResult, IAuthHttpHandler, IAuthInit, ICredentialsProvider, IOrganizationsProvider, ISSOProvider, ISessionProvider, IUserProvider, Session, SSOCallbackResult, SSOLoginConfig, User } from '..';
3
3
  import type { AuthorizeUserFn, MastraAuthConfig, MastraAuthRequest } from '../types/index.js';
4
4
  export interface MastraAuthProviderOptions<TUser = unknown> {
5
5
  name?: string;
@@ -72,6 +72,13 @@ export declare abstract class MastraAuthProvider<TUser = unknown> extends Mastra
72
72
  abstract authorizeUser(user: TUser, request: MastraAuthRequest): Promise<boolean> | boolean;
73
73
  protected registerOptions(opts?: MastraAuthProviderOptions<TUser>): void;
74
74
  }
75
+ export declare function isSSOProvider(p: unknown): p is ISSOProvider;
76
+ export declare function isSessionProvider(p: unknown): p is ISessionProvider;
77
+ export declare function isUserProvider(p: unknown): p is IUserProvider;
78
+ export declare function isCredentialsProvider(p: unknown): p is ICredentialsProvider;
79
+ export declare function isOrganizationsProvider(p: unknown): p is IOrganizationsProvider;
80
+ export declare function isAuthHttpHandler(p: unknown): p is IAuthHttpHandler;
81
+ export declare function hasAuthInit(p: unknown): p is IAuthInit;
75
82
  export declare class CompositeAuth extends MastraAuthProvider implements ISSOProvider<User>, ISessionProvider<Session>, IUserProvider<User> {
76
83
  private providers;
77
84
  private authenticatedProviderByObject;
@@ -4,7 +4,7 @@
4
4
  * Uses @workos/authkit-session for session management with encrypted
5
5
  * cookie-based sessions that persist across server restarts.
6
6
  */
7
- import type { IUserProvider, ISSOProvider, ISessionProvider, Session, SSOCallbackResult, SSOLoginConfig } from './_types/@internal_auth/dist/index.d.ts';
7
+ import type { AuthInitContext, IAuthInit, IOrganizationsProvider, IUserProvider, ISSOProvider, ISessionProvider, Session, SSOCallbackResult, SSOLoginConfig } from './_types/@internal_auth/dist/index.d.ts';
8
8
  import type { EEUser } from './_types/@internal_auth/dist/ee/index.d.ts';
9
9
  import { MastraAuthProvider } from './_types/@internal_auth/dist/provider/index.d.ts';
10
10
  import { AuthService } from '@workos/authkit-session';
@@ -37,7 +37,7 @@ import type { WorkOSUser, MastraAuthWorkosOptions } from './types.js';
37
37
  * });
38
38
  * ```
39
39
  */
40
- export declare class MastraAuthWorkos extends MastraAuthProvider<WorkOSUser> implements IUserProvider<EEUser>, ISSOProvider<EEUser>, ISessionProvider<Session> {
40
+ export declare class MastraAuthWorkos extends MastraAuthProvider<WorkOSUser> implements IUserProvider<EEUser>, ISSOProvider<EEUser>, ISessionProvider<Session>, IOrganizationsProvider, IAuthInit {
41
41
  protected workos: WorkOS;
42
42
  protected clientId: string;
43
43
  protected redirectUri: string;
@@ -143,6 +143,40 @@ export declare class MastraAuthWorkos extends MastraAuthProvider<WorkOSUser> imp
143
143
  * Get response headers to clear the session cookie.
144
144
  */
145
145
  getClearSessionHeaders(): Record<string, string>;
146
+ /**
147
+ * One-time host initialization. Resolves the redirect URI from the host's
148
+ * `publicUrl` (`<publicUrl>/auth/callback`) when it was not provided in the
149
+ * options or via `WORKOS_REDIRECT_URI`.
150
+ *
151
+ * Fails at prepare time rather than handing WorkOS an empty redirect URI on
152
+ * the first login (which breaks hosted login with an opaque provider error).
153
+ */
154
+ init(ctx: AuthInitContext): Promise<void>;
155
+ /**
156
+ * Ensure the user belongs to a WorkOS organization, creating a personal org
157
+ * on first use when they have none.
158
+ *
159
+ * - ≥1 membership → return the first org id (they already belong somewhere;
160
+ * we never auto-create when a membership exists).
161
+ * - 0 memberships → create a personal org + membership and return its id.
162
+ *
163
+ * Idempotency: the create call carries `externalId = userId` and a stable
164
+ * `idempotencyKey`, so concurrent/retried first logins never create duplicate
165
+ * personal orgs. If a prior run created the org but never attached the
166
+ * membership, the create rejects with `external_id_already_used`; we recover
167
+ * the existing org by `externalId` and (re)attach the membership instead of
168
+ * failing.
169
+ *
170
+ * Best-effort: any WorkOS error (e.g. API key lacking org-create permission)
171
+ * is swallowed and returns `undefined`, leaving the user in their no-org
172
+ * state rather than failing the request.
173
+ */
174
+ ensureOrganization(userId: string): Promise<string | undefined>;
175
+ /**
176
+ * Whether the user holds an admin-equivalent role (`admin` or `owner`) in
177
+ * the organization. Provider errors resolve to `false`.
178
+ */
179
+ isOrganizationAdmin(organizationId: string, userId: string): Promise<boolean>;
146
180
  /**
147
181
  * Get the underlying WorkOS client.
148
182
  */
@@ -1 +1 @@
1
- {"version":3,"file":"auth-provider.d.ts","sourceRoot":"","sources":["../src/auth-provider.ts"],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AW,IAAI,MAAM;IAIrB;;OAEG;IACH,cAAc,IAAI,MAAM;CAGzB"}
package/dist/index.cjs CHANGED
@@ -157,7 +157,7 @@ var MastraBase = class {
157
157
  }
158
158
  };
159
159
 
160
- // ../../packages/_internals/auth/dist/chunk-7GLKLOU3.js
160
+ // ../../packages/_internals/auth/dist/chunk-NJOKT6V5.js
161
161
  var MastraAuthProvider = class extends MastraBase {
162
162
  protected;
163
163
  public;
@@ -240,6 +240,20 @@ function getWebRequest(request) {
240
240
  var DEV_COOKIE_PASSWORD = crypto.randomUUID() + crypto.randomUUID();
241
241
  var MEMBERSHIP_CACHE_TTL_MS = 60 * 1e3;
242
242
  var MEMBERSHIP_CACHE_MAX_SIZE = 1e3;
243
+ function workosErrorCode(error) {
244
+ if (!error || typeof error !== "object") return void 0;
245
+ const e = error;
246
+ if (typeof e.code === "string") return e.code;
247
+ if (e.rawData && typeof e.rawData.code === "string") return e.rawData.code;
248
+ return void 0;
249
+ }
250
+ function isExternalIdAlreadyUsed(error) {
251
+ return workosErrorCode(error) === "external_id_already_used";
252
+ }
253
+ function isMembershipAlreadyExists(error) {
254
+ const code = workosErrorCode(error);
255
+ return code === "organization_membership_already_exists" || code === "entity_already_exists";
256
+ }
243
257
  var MastraAuthWorkos = class extends MastraAuthProvider {
244
258
  workos;
245
259
  clientId;
@@ -256,18 +270,13 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
256
270
  super({ name: options?.name ?? "workos" });
257
271
  const apiKey = options?.apiKey ?? process.env.WORKOS_API_KEY;
258
272
  const clientId = options?.clientId ?? process.env.WORKOS_CLIENT_ID;
259
- const redirectUri = options?.redirectUri ?? process.env.WORKOS_REDIRECT_URI;
273
+ const redirectUri = options?.redirectUri ?? process.env.WORKOS_REDIRECT_URI ?? "";
260
274
  const cookiePassword = options?.session?.cookiePassword ?? process.env.WORKOS_COOKIE_PASSWORD ?? DEV_COOKIE_PASSWORD;
261
275
  if (!apiKey || !clientId) {
262
276
  throw new Error(
263
277
  "WorkOS API key and client ID are required. Provide them in the options or set WORKOS_API_KEY and WORKOS_CLIENT_ID environment variables."
264
278
  );
265
279
  }
266
- if (!redirectUri) {
267
- throw new Error(
268
- "WorkOS redirect URI is required. Provide it in the options or set WORKOS_REDIRECT_URI environment variable."
269
- );
270
- }
271
280
  if (cookiePassword.length < 32) {
272
281
  throw new Error(
273
282
  "Cookie password must be at least 32 characters. Set WORKOS_COOKIE_PASSWORD environment variable or provide session.cookiePassword option."
@@ -564,9 +573,15 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
564
573
  * Get the URL to redirect users to for SSO login.
565
574
  */
566
575
  getLoginUrl(redirectUri, state) {
576
+ const resolvedRedirectUri = redirectUri || this.redirectUri;
577
+ if (!resolvedRedirectUri) {
578
+ throw new Error(
579
+ "WorkOS redirect URI is required. Provide it in the options, set the WORKOS_REDIRECT_URI environment variable, or call init() with a publicUrl."
580
+ );
581
+ }
567
582
  const baseOptions = {
568
583
  clientId: this.clientId,
569
- redirectUri: redirectUri || this.redirectUri,
584
+ redirectUri: resolvedRedirectUri,
570
585
  state
571
586
  };
572
587
  if (this.ssoConfig?.connection) {
@@ -759,6 +774,105 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
759
774
  return { "Set-Cookie": cookieParts.join("; ") };
760
775
  }
761
776
  // ============================================================================
777
+ // IAuthInit Implementation
778
+ // ============================================================================
779
+ /**
780
+ * One-time host initialization. Resolves the redirect URI from the host's
781
+ * `publicUrl` (`<publicUrl>/auth/callback`) when it was not provided in the
782
+ * options or via `WORKOS_REDIRECT_URI`.
783
+ *
784
+ * Fails at prepare time rather than handing WorkOS an empty redirect URI on
785
+ * the first login (which breaks hosted login with an opaque provider error).
786
+ */
787
+ async init(ctx) {
788
+ if (!this.redirectUri && ctx.publicUrl) {
789
+ this.redirectUri = `${ctx.publicUrl}/auth/callback`;
790
+ this.config.redirectUri = this.redirectUri;
791
+ const storage = new WebSessionStorage(this.config);
792
+ this.authService = new authkitSession.AuthService(this.config, storage, this.workos, authkitSession.sessionEncryption);
793
+ }
794
+ if (!this.redirectUri) {
795
+ throw new Error(
796
+ "MastraAuthWorkos could not resolve a callback URL: pass `redirectUri` (WORKOS_REDIRECT_URI) or configure the host `publicUrl`."
797
+ );
798
+ }
799
+ }
800
+ // ============================================================================
801
+ // IOrganizationsProvider Implementation
802
+ // ============================================================================
803
+ /**
804
+ * Ensure the user belongs to a WorkOS organization, creating a personal org
805
+ * on first use when they have none.
806
+ *
807
+ * - ≥1 membership → return the first org id (they already belong somewhere;
808
+ * we never auto-create when a membership exists).
809
+ * - 0 memberships → create a personal org + membership and return its id.
810
+ *
811
+ * Idempotency: the create call carries `externalId = userId` and a stable
812
+ * `idempotencyKey`, so concurrent/retried first logins never create duplicate
813
+ * personal orgs. If a prior run created the org but never attached the
814
+ * membership, the create rejects with `external_id_already_used`; we recover
815
+ * the existing org by `externalId` and (re)attach the membership instead of
816
+ * failing.
817
+ *
818
+ * Best-effort: any WorkOS error (e.g. API key lacking org-create permission)
819
+ * is swallowed and returns `undefined`, leaving the user in their no-org
820
+ * state rather than failing the request.
821
+ */
822
+ async ensureOrganization(userId) {
823
+ try {
824
+ const memberships = await this.workos.userManagement.listOrganizationMemberships({ userId }).then((page) => page.autoPagination());
825
+ const firstExisting = memberships.find((m) => m.organizationId)?.organizationId;
826
+ if (firstExisting) return firstExisting;
827
+ const profile = await this.workos.userManagement.getUser(userId).catch(() => null);
828
+ const label = profile?.email ?? userId;
829
+ let organizationId;
830
+ try {
831
+ const organization = await this.workos.organizations.createOrganization(
832
+ {
833
+ name: `${label}'s org`,
834
+ externalId: userId,
835
+ metadata: { mastraPersonalOrg: "true", workosUserId: userId }
836
+ },
837
+ { idempotencyKey: `mastra-personal-org:${userId}` }
838
+ );
839
+ organizationId = organization.id;
840
+ } catch (error) {
841
+ if (!isExternalIdAlreadyUsed(error)) throw error;
842
+ const existing = await this.workos.organizations.getOrganizationByExternalId(userId);
843
+ organizationId = existing.id;
844
+ }
845
+ try {
846
+ await this.workos.userManagement.createOrganizationMembership({ organizationId, userId });
847
+ } catch (error) {
848
+ if (!isMembershipAlreadyExists(error)) throw error;
849
+ }
850
+ this.membershipCache.delete(userId);
851
+ return organizationId;
852
+ } catch (error) {
853
+ console.warn(
854
+ `[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.`,
855
+ error
856
+ );
857
+ return void 0;
858
+ }
859
+ }
860
+ /**
861
+ * Whether the user holds an admin-equivalent role (`admin` or `owner`) in
862
+ * the organization. Provider errors resolve to `false`.
863
+ */
864
+ async isOrganizationAdmin(organizationId, userId) {
865
+ try {
866
+ const memberships = await this.workos.userManagement.listOrganizationMemberships({ userId }).then((page) => page.autoPagination());
867
+ const membership = memberships.find((item) => item.organizationId === organizationId);
868
+ if (!membership) return false;
869
+ const slugs = membership.roles?.length ? membership.roles.map((role) => role.slug) : [membership.role.slug];
870
+ return slugs.some((slug) => slug === "admin" || slug === "owner");
871
+ } catch {
872
+ return false;
873
+ }
874
+ }
875
+ // ============================================================================
762
876
  // Helper Methods
763
877
  // ============================================================================
764
878
  /**
@@ -787,7 +901,7 @@ var MastraAuthWorkos = class extends MastraAuthProvider {
787
901
  }
788
902
  };
789
903
 
790
- // ../../packages/_internals/auth/dist/chunk-H3EJ4GVJ.js
904
+ // ../../packages/_internals/auth/dist/chunk-LZCWL5CT.js
791
905
  var FGADeniedError = class extends Error {
792
906
  user;
793
907
  resource;